@synnaxlabs/pluto 0.46.2 → 0.46.4
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/{Toggle-Djy3iEFS.js → Toggle-BvHOvpZl.js} +1 -1
- package/dist/{Toggle-D7uuc8BY.cjs → Toggle-YrCaaWoP.cjs} +1 -1
- package/dist/{Video-Com7iIjJ.js → Video-B3mUCF7w.js} +1 -1
- package/dist/{Video-BgaQjOlJ.cjs → Video-PX9PWa1_.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-BJh3xDSW.cjs +8 -0
- package/dist/{css-qKD7ZG81.js → css-C24hS2UX.js} +903 -875
- 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/ether.cjs +1 -1
- package/dist/ether.js +6 -6
- package/dist/{external-CfY-kR5_.js → external-1ucYXJx8.js} +2 -2
- package/dist/{external-Bfddv9ir.cjs → external-BwkIuXvQ.cjs} +1 -1
- package/dist/{external-CG-WeHt1.js → external-C-ExavVe.js} +3 -3
- package/dist/{external-C0szVQZ4.js → external-CC9QgzfY.js} +3 -3
- package/dist/{external-BwAIT4Et.js → external-Cg3K8ETl.js} +4 -4
- package/dist/{external-Bp0LGk7L.cjs → external-ChJFeBx4.cjs} +1 -1
- package/dist/{external-BwzXukg6.js → external-ChfziUeG.js} +2 -2
- package/dist/{external-fThC1Pt0.js → external-Ck9vwLNn.js} +3 -3
- package/dist/{external-iLU86byd.cjs → external-Clg5_LVL.cjs} +1 -1
- package/dist/{external-BatQDwpn.cjs → external-CtPQhs2L.cjs} +1 -1
- package/dist/{external-R1DnhHJ8.cjs → external-D-7LQcc1.cjs} +1 -1
- package/dist/{external-ok-onqCX.cjs → external-D7ez6YFA.cjs} +1 -1
- package/dist/{external-CtIn5ns5.js → external-DSC98ftR.js} +3 -3
- package/dist/{external-JI_JLXE9.cjs → external-DcJjrD1A.cjs} +2 -2
- package/dist/{external-qAqWNZPd.cjs → external-DfxokOST.cjs} +1 -1
- package/dist/{external-DPsERPGZ.js → external-Dia3MCeO.js} +3 -3
- package/dist/external-Dxu0KYI_.cjs +1 -0
- package/dist/{external-BH7AW9vg.cjs → external-NOoRXXaT.cjs} +1 -1
- package/dist/{external-B_BNwXoG.js → external-RDyCOmKR.js} +21 -21
- package/dist/{external-BXAiwKcS.js → external-S4v-IR_C.js} +3 -3
- package/dist/{external-CaehDJtX.cjs → external-VIR_Vvod.cjs} +1 -1
- package/dist/{external-BqSq3_g3.js → external-mtaOrZVh.js} +2 -2
- package/dist/{external-DZ9ZLLOd.cjs → external-orHcg1KY.cjs} +1 -1
- package/dist/{external-CM-K5NTq.js → external-ree9J7kb.js} +1 -1
- package/dist/{external-DLIuO7_6.cjs → external-s4B9EjQm.cjs} +1 -1
- package/dist/{external-CwtqVaYf.js → external-wP76ag3P.js} +4 -6
- package/dist/flex.cjs +1 -1
- package/dist/flex.js +1 -1
- package/dist/{fontString-BpD7ezh8.cjs → fontString-BMITZjR-.cjs} +1 -1
- package/dist/{fontString-CpT1noV1.js → fontString-CNdpxtJg.js} +2 -2
- package/dist/header.cjs +1 -1
- package/dist/header.js +1 -1
- package/dist/index.cjs +12 -12
- package/dist/index.js +4689 -4692
- 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/{main-DCwBsS0F.js → main-9Dw_ngUE.js} +3 -3
- package/dist/{main-20msMsI6.cjs → main-rewFivKu.cjs} +30 -30
- package/dist/menu.cjs +1 -1
- package/dist/menu.js +1 -1
- package/dist/pluto.css +1 -1
- package/dist/{provider-B-VPfAGa.js → provider-BMcIM58p.js} +3 -3
- package/dist/{provider-D295Uocj.cjs → provider-CedWF-id.cjs} +3 -3
- package/dist/{provider-qIzR8Puy.js → provider-DXuSQEu0.js} +2816 -2791
- package/dist/provider-DshN-WBB.cjs +83 -0
- package/dist/src/color/GradientPicker.d.ts.map +1 -1
- package/dist/src/ontology/queries.d.ts +3 -10
- package/dist/src/ontology/queries.d.ts.map +1 -1
- package/dist/src/schematic/symbol/queries.d.ts +1 -3
- package/dist/src/schematic/symbol/queries.d.ts.map +1 -1
- package/dist/tabs.cjs +1 -1
- package/dist/tabs.js +1 -1
- package/dist/text.cjs +1 -1
- package/dist/text.js +2 -2
- package/dist/theming.cjs +1 -1
- package/dist/theming.js +2 -2
- package/dist/tree.cjs +1 -1
- package/dist/tree.js +1 -1
- package/dist/triggers.cjs +1 -1
- package/dist/triggers.js +1 -1
- package/dist/{units-WtYBE1br.js → units-BfWwpiDe.js} +1 -1
- package/dist/units-DOj-2MGY.cjs +1 -0
- package/dist/video.cjs +1 -1
- package/dist/video.js +1 -1
- package/package.json +3 -3
- package/dist/css-DA2F4zE4.cjs +0 -8
- package/dist/external-BaO1j7U1.cjs +0 -1
- package/dist/provider-DVqod4rl.cjs +0 -83
- package/dist/units-CLbZ5ejs.cjs +0 -1
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
"use strict";const a=require("zod"),d=require("./css-DA2F4zE4.cjs"),ai=require("react"),Kf=t=>{const e=t.replace(/_[a-z]/g,n=>n[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)},Mc=t=>{const e=(n,r=na)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!Cs(n))return n;r=ep(r);const s={},i=n;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),r):(Object.keys(i).forEach(o=>{let c=i[o];const l=t(o);r.recursive&&(Cs(c)?go(c)||(c=e(c,r)):r.recursiveInArray&&mo(c)&&(c=[...c].map(u=>{let h=u;return Cs(u)?go(h)||(h=e(u,r)):mo(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},Rc=Mc(Kf),Jf=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Xf=Mc(Jf),Qf=[Number,String,Uint8Array],na={recursive:!0,recursiveInArray:!0},ep=(t=na)=>(t.recursive==null?t=na:t.recursiveInArray??=!1,t),mo=t=>t!=null&&Array.isArray(t),Cs=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),go=t=>Qf.some(e=>t instanceof e);let tp=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t))}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const n=JSON.parse(t),r=Rc(n);return e!=null?e.parse(r):r}encodeString(t){const e=Xf(t);return JSON.stringify(e,(n,r)=>ArrayBuffer.isView(r)?Array.from(r):typeof r=="bigint"?r.toString():r)}};const ra=new tp,pe=t=>t!=null&&typeof t=="object"&&"value"in t;let Xt=class{value;constructor(t){this.value=t}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const np=t=>t!=null&&typeof t=="object"&&"toString"in t,rp=(t,e=!1)=>{const n=np(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,i)=>s.localeCompare(i);break;case"stringer":r=(s,i)=>s.toString().localeCompare(i.toString());break;case"number":r=(s,i)=>Number(s)-Number(i);break;case"bigint":r=(s,i)=>BigInt(s)-BigInt(i)>0n?1:-1;break;case"boolean":r=(s,i)=>Number(s)-Number(i);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?sp(r):r},sp=t=>(e,n)=>t(n,e),Wr=a.z.tuple([a.z.number(),a.z.number()]);a.z.tuple([a.z.bigint(),a.z.bigint()]);const Uc=a.z.object({width:a.z.number(),height:a.z.number()}),ap=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()}),ip=["width","height"];a.z.enum(ip);const op=["start","center","end"],cp=["signedWidth","signedHeight"];a.z.enum(cp);const Or=a.z.object({x:a.z.number(),y:a.z.number()}),lp=a.z.object({clientX:a.z.number(),clientY:a.z.number()}),up=["x","y"],Zc=a.z.enum(up),Lc=["top","right","bottom","left"];a.z.enum(Lc);const hp=["left","right"],Dc=a.z.enum(hp),dp=["top","bottom"],Bc=a.z.enum(dp),Fc=["center"],wo=a.z.enum(Fc),fp=[...Lc,...Fc],Yc=a.z.enum(fp);a.z.enum(op);const pp=["first","last"];a.z.enum(pp);const yp=a.z.object({lower:a.z.number(),upper:a.z.number()}),mp=a.z.object({lower:a.z.bigint(),upper:a.z.bigint()});a.z.union([yp,Wr]);a.z.union([mp,Wr]);a.z.enum([...Zc.options,...Yc.options]);a.z.enum(["x","left","right"]);a.z.enum(["y","top","bottom"]);a.z.union([Zc,Yc,a.z.instanceof(String)]);const Hr=t=>(e,n)=>{if(typeof e=="bigint"){if(gp(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Gr=Hr((t,e)=>t-e),Kr=Hr((t,e)=>t+e),gp=t=>typeof t=="bigint"?!0:Number.isInteger(t),Ce=Hr((t,e)=>t*e),Jr=Hr((t,e)=>t/e),ft=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else r.lower=t.lower,r.upper=t.upper;return n?.makeValid?wp(r):r},wp=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,bo=(t,e)=>{const n=ft(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};a.z.object({x:Dc.or(wo),y:Bc.or(wo)});const bp=a.z.object({x:Dc,y:Bc}),vp=Object.freeze({x:"left",y:"top"}),Tp=(t,e)=>t.x===e.x&&t.y===e.y,vo=a.z.union([a.z.number(),Or,Wr,Uc,ap,lp]),Sp=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},To=Object.freeze({x:0,y:0}),sr=a.z.union([a.z.number(),a.z.string()]);a.z.object({top:sr,left:sr,width:sr,height:sr});a.z.object({left:a.z.number(),top:a.z.number(),right:a.z.number(),bottom:a.z.number()});a.z.object({one:Or,two:Or,root:bp});const ii=(t,e,n=0,r=0,s)=>{const i={one:{...To},two:{...To},root:s??vp};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:t,y:e},i.two={x:i.one.x+n,y:i.one.y+r},i}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(i.one={x:t.left,y:t.top},i.two={x:t.right,y:t.bottom},i):(i.one=t,e==null?i.two={x:i.one.x+n,y:i.one.y+r}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+n}:"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))},js=t=>{const e=ii(t);return{lower:e.one.x,upper:e.two.x}},Ps=t=>{const e=ii(t);return{lower:e.one.y,upper:e.two.y}},zp=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Op=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()});a.z.union([Uc,Op,Or,Wr]);const kp=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;a.z.object({offset:vo,scale:vo});a.z.object({offset:a.z.number(),scale:a.z.number()});const Ep=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Np=t=>(e,n,r,s)=>[e,s?r/t:r*t],xp=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:i}=e,{lower:o,upper:c}=t,l=i-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},Ap=t=>(e,n,r)=>[t,r],Ip=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},Cp=t=>(e,n,r)=>{const{lower:s,upper:i}=t;return r=kp(r,s,i),[e,r]};let So=class Ot{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Ot().translate(e)}static magnify(e){return new Ot().magnify(e)}static scale(e,n){return new Ot().scale(e,n)}translate(e){const n=this.new(),r=Ep(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Np(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=ft(e,n),s=this.new(),i=xp(r);return i.type="scale",s.ops.push(i),s}clamp(e,n){const r=ft(e,n),s=this.new(),i=Cp(r);return i.type="clamp",s.ops.push(i),s}reBound(e,n){const r=ft(e,n),s=this.new(),i=Ap(r);return i.type="re-bound",s.ops.push(i),s}invert(){const e=Ip();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Ot;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],i)=>i(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const i=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);i!==-1&&n.push([s,i])}),n.forEach(([r,s])=>{const i=e.ops.slice(r,s);i.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Ot};(class Ne{x;y;currRoot;constructor(e=new So,n=new So,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Ne().translate(e,n)}static translateX(e){return new Ne().translateX(e)}static translateY(e){return new Ne().translateY(e)}static clamp(e){return new Ne().clamp(e)}static magnify(e){return new Ne().magnify(e)}static scale(e){return new Ne().scale(e)}static reBound(e){return new Ne().reBound(e)}translate(e,n){const r=Sp(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(zp(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Tp(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(js(e)),n.y=n.y.scale(Ps(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(js(e)),n.y=this.y.reBound(Ps(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(js(e)),n.y=this.y.clamp(Ps(e)),n}copy(){const e=new Ne;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 ii(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 Ne});let qc=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Vc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",jp=`0123456789${Vc}`,Pp=11,$p=qc(Vc,1),_p=qc(jp,Pp-1),Mp=()=>`${$p()}${_p()}`,Rp=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,sa=2n**63n-1n,Up=2**63-1,Zp=a.z.enum(["static","dynamic"]),zo=365,ar=30,Lp=a.z.union([a.z.tuple([a.z.int()]),a.z.tuple([a.z.int(),a.z.int().min(1).max(12)]),a.z.tuple([a.z.int(),a.z.int().min(1).max(12),a.z.int().min(1).max(31)])]),Wc=(t,e)=>{const n=new R(e);if(![_.DAY,_.HOUR,_.MINUTE,_.SECOND,_.MILLISECOND,_.MICROSECOND,_.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof R?new R(r):new _(r)};let R=class S extends Xt{constructor(e,n="UTC"){if(e==null)super(S.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*S.MILLISECOND.valueOf());else if(typeof e=="string")super(S.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(S.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=S.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===Up?e=sa:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=S.MAX:e=S.MIN)),pe(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new S(BigInt(s.getTime())*S.MILLISECOND.valueOf()).truncate(S.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,i]=e.split(":");let o="00",c="00";i!=null&&([o,c]=i.split("."));let l=S.hours(parseInt(r??"00")).add(S.minutes(parseInt(s??"00"))).add(S.seconds(parseInt(o??"00"))).add(S.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(S.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return S.parseTimeString(e,n);const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new S(BigInt(r.getTime())*S.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(S.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new _(BigInt(new Date().getTimezoneOffset())*S.MINUTE.valueOf())}static since(e){return new S().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new S(e).valueOf()}span(e){return this.range(e).span}range(e){return new mn(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new S(e).valueOf()}afterEq(e){return this.valueOf()>=new S(e).valueOf()}before(e){return this.valueOf()<new S(e).valueOf()}beforeEq(e){return this.valueOf()<=new S(e).valueOf()}add(e){return new S(Kr(this.valueOf(),new _(e).valueOf()))}sub(e){return new S(Gr(this.valueOf(),new _(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(_.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(_.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(_.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(_.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(S.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(S.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new S(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new S(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new S(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new S(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new S(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new S(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new S(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new S(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Wc(this,e)}get isToday(){return this.truncate(_.DAY).equals(S.now().truncate(_.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new S(new Date)}static max(...e){let n=S.MIN;for(const r of e){const s=new S(r);s.after(n)&&(n=s)}return n}static min(...e){let n=S.MAX;for(const r of e){const s=new S(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new S(e,n)}static NANOSECOND=S.nanoseconds(1);static microseconds(e,n="UTC"){return S.nanoseconds(e*1e3,n)}static MICROSECOND=S.microseconds(1);static milliseconds(e,n="UTC"){return S.microseconds(e*1e3,n)}static MILLISECOND=S.milliseconds(1);static seconds(e,n="UTC"){return S.milliseconds(e*1e3,n)}static SECOND=S.seconds(1);static minutes(e,n="UTC"){return S.seconds(e*60,n)}static MINUTE=S.minutes(1);static hours(e,n="UTC"){return S.minutes(e*60,n)}static HOUR=S.hours(1);static days(e,n="UTC"){return S.hours(e*24,n)}static DAY=S.days(1);static MAX=new S(sa);static MIN=new S(0);static ZERO=new S(0);static z=a.z.union([a.z.instanceof(S),a.z.object({value:a.z.bigint()}).transform(e=>new S(e.value)),a.z.string().transform(e=>new S(BigInt(e))),a.z.number().transform(e=>new S(e)),a.z.bigint().transform(e=>new S(e)),a.z.date().transform(e=>new S(e)),a.z.custom(e=>e instanceof _).transform(e=>new S(e)),Lp.transform(e=>new S(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}},_=class k extends Xt{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),pe(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof k?e:e instanceof $s?e.period:e instanceof R?new k(e):(pe(e)&&(e=e.value),["number","bigint"].includes(typeof e)?k.seconds(e):new k(e))}static fromMilliseconds(e){return e instanceof k?e:e instanceof $s?e.period:e instanceof R?new k(e):(pe(e)&&(e=e.value),["number","bigint"].includes(typeof e)?k.milliseconds(e):new k(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new k(e).valueOf()}greaterThan(e){return this.valueOf()>new k(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new k(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new k(e).valueOf()}remainder(e){return Wc(this,e)}truncate(e){return new k(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(k.DAY),r=this.truncate(k.HOUR),s=this.truncate(k.MINUTE),i=this.truncate(k.SECOND),o=this.truncate(k.MILLISECOND),c=this.truncate(k.MICROSECOND),l=this.truncate(k.NANOSECOND),u=n,h=r.sub(n),p=s.sub(r),f=i.sub(s),O=o.sub(i),I=c.sub(o),j=l.sub(c);let w="";return u.isZero||(w+=`${u.days}d `),h.isZero||(w+=`${h.hours}h `),p.isZero||(w+=`${p.minutes}m `),f.isZero||(w+=`${f.seconds}s `),O.isZero||(w+=`${O.milliseconds}ms `),I.isZero||(w+=`${I.microseconds}µs `),j.isZero||(w+=`${j.nanoseconds}ns`),w.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new k(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(k.SECOND))return"< 1s";const s=n.days,i=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/zo),u=Math.floor(s/ar),h=Math.floor(s/7),p=Math.floor(s),f=Math.floor(i),O=Math.floor(o),I=Math.floor(c),j=r?"-":"";if(l>=1){let w=`${l}y`;if(l<2){const T=Math.floor(s%zo/ar);T>0&&(w+=` ${T}mo`)}return j+w}if(h>=1&&s<ar&&s%7===0){let w=`${h}w`;const T=Math.floor(s%7),A=Math.floor(i-h*7*24);return h<2&&(T>0?w+=` ${T}d`:A>0&&A<24&&(w+=` ${A}h`)),j+w}if(u>=1){let w=`${u}mo`;if(u<3){const T=Math.floor(s%ar);T>0&&(w+=` ${T}d`)}return j+w}if(h>=1){let w=`${h}w`;const T=Math.floor(s%7),A=Math.floor(i-h*7*24);return h<2&&(T>0?w+=` ${T}d`:A>0&&A<24&&(w+=` ${A}h`)),j+w}if(p>=1){let w=`${p}d`;const T=Math.floor(i-p*24);return p<2&&T>0&&(w+=` ${T}h`),j+w}if(f>=1){let w=`${f}h`;if(f<3){const T=Math.floor(o-f*60);T>0&&(w+=` ${T}m`)}return j+w}if(O>=1){let w=`${O}m`;if(O<5){const T=Math.floor(c-O*60);T>0&&(w+=` ${T}s`)}return j+w}return`${j}${I}s`}mult(e){return new k(Ce(this.valueOf(),e))}div(e){return new k(Jr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(k.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(k.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(k.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(k.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(k.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(k.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new k(e).valueOf()}add(e){return new k(this.valueOf()+new k(e).valueOf())}sub(e){return new k(this.valueOf()-new k(e).valueOf())}static nanoseconds(e=1){return new k(e)}static NANOSECOND=k.nanoseconds(1);static microseconds(e=1){return k.nanoseconds(Ce(e,1e3))}static MICROSECOND=k.microseconds(1);static milliseconds(e=1){return k.microseconds(Ce(e,1e3))}static MILLISECOND=k.milliseconds(1);static seconds(e=1){return k.milliseconds(Ce(e,1e3))}static SECOND=k.seconds(1);static minutes(e=1){return k.seconds(Ce(e,60))}static MINUTE=k.minutes(1);static hours(e){return k.minutes(Ce(e,60))}static HOUR=k.hours(1);static days(e){return k.hours(Ce(e,24))}static DAY=k.days(1);static MAX=new k(sa);static MIN=new k(0);static ZERO=new k(0);static z=a.z.union([a.z.object({value:a.z.bigint()}).transform(e=>new k(e.value)),a.z.string().transform(e=>new k(BigInt(e))),a.z.number().transform(e=>new k(e)),a.z.bigint().transform(e=>new k(e)),a.z.instanceof(k),a.z.instanceof(R).transform(e=>new k(e)),a.z.custom(e=>e instanceof $s).transform(e=>new k(e))])},$s=class he extends Xt{constructor(e){pe(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new he(e).valueOf()}get period(){return _.seconds(1/this.valueOf())}sampleCount(e){return new _(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new ne(n).valueOf()}span(e){return _.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new ne(n).valueOf())}add(e){return new he(Kr(this.valueOf(),new he(e).valueOf()))}sub(e){return new he(Gr(this.valueOf(),new he(e).valueOf()))}mult(e){return new he(Ce(this.valueOf(),e))}div(e){return new he(Jr(this.valueOf(),e))}static hz(e){return new he(e)}static khz(e){return he.hz(e*1e3)}static z=a.z.union([a.z.number().transform(e=>new he(e)),a.z.instanceof(he)])},ne=class se extends Xt{constructor(e){pe(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new aa(e*this.valueOf())}add(e){return new se(Kr(this.valueOf(),new se(e).valueOf()))}sub(e){return new se(Gr(this.valueOf(),new se(e).valueOf()))}mult(e){return new se(Ce(this.valueOf(),e))}div(e){return new se(Jr(this.valueOf(),e))}static UNKNOWN=new se(0);static BIT128=new se(16);static BIT64=new se(8);static BIT32=new se(4);static BIT16=new se(2);static BIT8=new se(1);static z=a.z.union([a.z.number().transform(e=>new se(e)),a.z.instanceof(se)])},mn=class xe{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new R(e.start),this.end=new R(e.end)):(this.start=new R(e),this.end=new R(n))}get span(){return new _(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.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new xe(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=_.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=_.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=R.max(r.start,e.start),i=R.min(r.end,e.end);return i.before(s)?!1:new _(i.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof xe?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new xe(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new xe(R.min(...e.map(n=>n.start)),R.max(...e.map(n=>n.end)))}static MAX=new xe(R.MIN,R.MAX);static ZERO=new xe(R.ZERO,R.ZERO);static z=a.z.union([a.z.object({start:R.z,end:R.z}).transform(e=>new xe(e.start,e.end)),a.z.instanceof(xe)]);static sort(e,n){return R.sort(e.start,n.start)||R.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>xe.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=R.max(s.end,r.end):n.push(r),n},[])}},q=class m extends Xt{constructor(e){if(pe(e)&&(e=e.value),e instanceof m||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=m.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=m.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(n=>this.equals(n))}toString(e=!1){return e?m.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(m.JSON)||this.equals(m.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(m.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=m.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(m.UINT8)||this.equals(m.UINT16)||this.equals(m.UINT32)||this.equals(m.UINT64)}get isSignedInteger(){return this.equals(m.INT8)||this.equals(m.INT16)||this.equals(m.INT32)||this.equals(m.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(m.INT32)&&e.equals(m.FLOAT64)||this.equals(m.INT8)&&e.equals(m.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 m.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new m("unknown");static FLOAT64=new m("float64");static FLOAT32=new m("float32");static INT64=new m("int64");static INT32=new m("int32");static INT16=new m("int16");static INT8=new m("int8");static UINT64=new m("uint64");static UINT32=new m("uint32");static UINT16=new m("uint16");static UINT8=new m("uint8");static BOOLEAN=new m("boolean");static TIMESTAMP=new m("timestamp");static UUID=new m("uuid");static STRING=new m("string");static JSON=new m("json");static ARRAY_CONSTRUCTORS=new Map([[m.UINT8.toString(),Uint8Array],[m.UINT16.toString(),Uint16Array],[m.UINT32.toString(),Uint32Array],[m.UINT64.toString(),BigUint64Array],[m.FLOAT32.toString(),Float32Array],[m.FLOAT64.toString(),Float64Array],[m.INT8.toString(),Int8Array],[m.INT16.toString(),Int16Array],[m.INT32.toString(),Int32Array],[m.INT64.toString(),BigInt64Array],[m.TIMESTAMP.toString(),BigInt64Array],[m.STRING.toString(),Uint8Array],[m.JSON.toString(),Uint8Array],[m.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,m.UINT8],[Uint16Array.name,m.UINT16],[Uint32Array.name,m.UINT32],[BigUint64Array.name,m.UINT64],[Float32Array.name,m.FLOAT32],[Float64Array.name,m.FLOAT64],[Int8Array.name,m.INT8],[Int16Array.name,m.INT16],[Int32Array.name,m.INT32],[BigInt64Array.name,m.INT64]]);static DENSITIES=new Map([[m.UINT8.toString(),ne.BIT8],[m.UINT16.toString(),ne.BIT16],[m.UINT32.toString(),ne.BIT32],[m.UINT64.toString(),ne.BIT64],[m.FLOAT32.toString(),ne.BIT32],[m.FLOAT64.toString(),ne.BIT64],[m.INT8.toString(),ne.BIT8],[m.INT16.toString(),ne.BIT16],[m.INT32.toString(),ne.BIT32],[m.INT64.toString(),ne.BIT64],[m.TIMESTAMP.toString(),ne.BIT64],[m.STRING.toString(),ne.UNKNOWN],[m.JSON.toString(),ne.UNKNOWN],[m.UUID.toString(),ne.BIT128]]);static ALL=[m.UNKNOWN,m.FLOAT64,m.FLOAT32,m.INT64,m.INT32,m.INT16,m.INT8,m.UINT64,m.UINT32,m.UINT16,m.UINT8,m.TIMESTAMP,m.UUID,m.STRING,m.JSON];static SHORT_STRINGS=new Map([[m.UINT8.toString(),"u8"],[m.UINT16.toString(),"u16"],[m.UINT32.toString(),"u32"],[m.UINT64.toString(),"u64"],[m.INT8.toString(),"i8"],[m.INT16.toString(),"i16"],[m.INT32.toString(),"i32"],[m.INT64.toString(),"i64"],[m.FLOAT32.toString(),"f32"],[m.FLOAT64.toString(),"f64"],[m.BOOLEAN.toString(),"bool"],[m.TIMESTAMP.toString(),"ts"],[m.UUID.toString(),"uuid"],[m.STRING.toString(),"str"],[m.JSON.toString(),"json"]]);static BIG_INT_TYPES=[m.INT64,m.UINT64,m.TIMESTAMP];static z=a.z.union([a.z.string().transform(e=>new m(e)),a.z.instanceof(m)])},aa=class P extends Xt{constructor(e){pe(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return pe(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return pe(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return pe(e)&&(e=e.value),new P(Kr(this.valueOf(),e.valueOf()))}sub(e){return pe(e)&&(e=e.value),new P(Gr(this.valueOf(),e.valueOf()))}mult(e){return new P(Ce(this.valueOf(),e))}div(e){return new P(Jr(this.valueOf(),e))}truncate(e){return new P(Math.trunc(this.valueOf()/new P(e).valueOf())*new P(e).valueOf())}remainder(e){return P.bytes(this.valueOf()%new P(e).valueOf())}get gigabytes(){return this.valueOf()/P.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/P.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/P.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/P.TERABYTE.valueOf()}toString(){const e=this.truncate(P.TERABYTE),n=this.truncate(P.GIGABYTE),r=this.truncate(P.MEGABYTE),s=this.truncate(P.KILOBYTE),i=this.truncate(P.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=i.sub(s);let p="";return o.isZero||(p+=`${o.terabytes}TB `),c.isZero||(p+=`${c.gigabytes}GB `),l.isZero||(p+=`${l.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new P(e)}static BYTE=new P(1);static kilobytes(e=1){return P.bytes(new P(e).valueOf()*1e3)}static KILOBYTE=P.kilobytes(1);static megabytes(e=1){return P.kilobytes(new P(e).valueOf()*1e3)}static MEGABYTE=P.megabytes(1);static gigabytes(e=1){return P.megabytes(new P(e).valueOf()*1e3)}static GIGABYTE=P.gigabytes(1);static terabytes(e){return P.gigabytes(new P(e).valueOf()*1e3)}static TERABYTE=P.terabytes(1);static ZERO=new P(0);static z=a.z.union([a.z.number().transform(e=>new P(e)),a.z.instanceof(P)]);get isZero(){return this.valueOf()===0}};a.z.object({start:a.z.number(),end:a.z.number()});a.z.union([a.z.instanceof(Uint8Array),a.z.instanceof(Uint16Array),a.z.instanceof(Uint32Array),a.z.instanceof(BigUint64Array),a.z.instanceof(Float32Array),a.z.instanceof(Float64Array),a.z.instanceof(Int8Array),a.z.instanceof(Int16Array),a.z.instanceof(Int32Array),a.z.instanceof(BigInt64Array)]);const Hc=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof R||t instanceof _||t instanceof Date},Dp=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):gr(n,-r),gr=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),Bp=/^(?:[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 Fp(t){return typeof t=="string"&&Bp.test(t)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function Yp(t,e=0){return(X[t[e+0]]+X[t[e+1]]+X[t[e+2]]+X[t[e+3]]+"-"+X[t[e+4]]+X[t[e+5]]+"-"+X[t[e+6]]+X[t[e+7]]+"-"+X[t[e+8]]+X[t[e+9]]+"-"+X[t[e+10]]+X[t[e+11]]+X[t[e+12]]+X[t[e+13]]+X[t[e+14]]+X[t[e+15]]).toLowerCase()}function qp(t,e=0){const n=Yp(t,e);if(!Fp(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Gc=(t,e)=>qp(t,e),Le=-1,Vp=a.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Wp=a.z.union([a.z.null(),a.z.undefined()]).transform(()=>new Uint8Array().buffer),ia=10,Hp=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Kc="sy_x_telem_series";let Jc=class Ye{key;discriminator=Kc;dataType;sampleOffset;gl;_data;timeRange=mn.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Le;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=a.z.object({timeRange:mn.z.optional(),dataType:q.z,alignment:a.z.coerce.bigint().optional(),data:a.z.union([Vp,Wp,a.z.instanceof(ArrayBuffer),a.z.instanceof(Uint8Array)]),glBufferUsage:Zp.optional().default("static").optional()});static z=Ye.crudeZ.transform(e=>new Ye(e));constructor(e){Gp(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=Mp(),data:u}=e;if(Kp(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=Hc(u),p=Array.isArray(u);if(n!=null)this.dataType=new q(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(p||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=q.STRING;else if(typeof f=="number")this.dataType=q.FLOAT64;else if(typeof f=="bigint")this.dataType=q.INT64;else if(typeof f=="boolean")this.dataType=q.BOOLEAN;else if(f instanceof R||f instanceof Date||f instanceof R)this.dataType=q.TIMESTAMP;else if(typeof f=="object")this.dataType=q.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new q(u)}if(!p&&!h)this._data=u;else if(p&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const O=f[0];(O instanceof R||O instanceof Date||O instanceof _)&&(f=f.map(I=>new R(I).valueOf())),this.dataType.equals(q.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
|
|
2
|
-
`)}
|
|
3
|
-
`).buffer):this.dataType.equals(q.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(I=>ra.encodeString(I)).join(`
|
|
4
|
-
`)}
|
|
5
|
-
`).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(I=>BigInt(Math.round(I)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??mn.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new q(n).Array(e),i=new Ye({data:s.buffer,dataType:n,...r});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===Le)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===Le)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.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===Le?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(q.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(ra.decodeString(n)))}get byteCapacity(){return new aa(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Le?this.byteCapacity:this.dataType.isVariable?new aa(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Le?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 n=[0];return this.data.forEach((r,s)=>{r===ia&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=Dp(this.dataType,e,this.data[s],n);return new Ye({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(q.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}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(),gr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(q.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}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(),gr(this.cachedMin,this.sampleOffset))}get bounds(){return ft(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(q.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return gr(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Gc(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=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]===ia){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(r,s);return this.dataType.equals(q.STRING)?new TextDecoder().decode(i):Rc(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let n=0,r=this.length-1;const s=rp(e);for(;n<=r;){const i=Math.floor((n+r)/2),o=s(this.at(i,!0),e);if(o===0)return i;o<0?n=i+1:r=i-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(q.FLOAT32)&&!this.dataType.equals(q.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Le){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(s).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,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Le}as(e){return Hp(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:ko(this.alignmentBounds.lower),upper:ko(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return ft(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Jp(this);return this.dataType.equals(q.JSON)?new oi(e):e}return this.dataType.equals(q.UUID)?new Xp(this):new Qp(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Oo(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new Oo(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new Ye({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new Ye({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Ye({data:this.buffer,dataType:this.dataType,timeRange:mn.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(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}};const Gp=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Jc?!0:Hc(t),Kp=Rp(Kc,Jc);class Oo{series;end;index;constructor(e,n,r){this.series=e;const s=ft(0,e.length+1);this.end=bo(s,r),this.index=bo(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let Jp=class{series;index;decoder;constructor(t){if(!t.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=t,this.index=0,this.decoder=new TextDecoder}next(){const t=this.index,e=this.series.data;for(;this.index<e.length&&e[this.index]!==ia;)this.index++;const n=this.index;return t===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(t,n))})}};class oi{wrapped;static schema=a.z.record(a.z.string(),a.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:ra.decodeString(e.value,oi.schema)}}}class Xp{series;index;data;density;constructor(e){if(!e.dataType.equals(q.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=q.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Gc(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Qp=class{series;index;constructor(t){this.series=t,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};const ko=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}};a.z.object({key:a.z.string(),value:a.z.string()});a.z.record(a.z.union([a.z.number(),a.z.string(),a.z.symbol()]),a.z.unknown());const ey=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";ey();const ty=["macOS","Windows","Linux"],ny=["macos","windows","linux"],ry={macos:"macOS",windows:"Windows",linux:"Linux"};a.z.enum(ty).or(a.z.enum(ny).transform(t=>ry[t]));const sy=(...t)=>t.map(Xc).join(""),Xc=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),ay=t=>t.endsWith("/")?t.slice(0,-1):t,iy=(t,e="")=>t===null?"":`?${Object.entries(t).filter(([,n])=>n==null?!1:Array.isArray(n)?n.length>0:!0).map(([n,r])=>`${e}${n}=${r}`).join("&")}`;let oy=class wr{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=Xc(s)}replace(e){return new wr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new wr({...this,pathPrefix:sy(this.path,e)})}toString(){return ay(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new wr({host:"unknown",port:0})};const cy=async t=>await new Promise(e=>setTimeout(e,_.fromMilliseconds(t).milliseconds));class ly{config;retries;interval;constructor(e){this.config={baseInterval:new _(e?.baseInterval??_.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??cy},this.retries=0,this.interval=new _(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const uy=a.z.object({baseInterval:_.z.optional(),maxRetries:a.z.number().optional(),scale:a.z.number().optional()}),hy=Object.freeze(Object.defineProperty({__proto__:null,Breaker:ly,breakerConfigZ:uy},Symbol.toStringTag,{value:"Module"})),dy=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Qc=a.z.string().regex(dy),$t=a.z.number().min(0).max(255),el=a.z.number().min(0).max(1),tl=a.z.tuple([$t,$t,$t,el]),fy=a.z.tuple([$t,$t,$t]),py=a.z.object({rgba255:tl}),yy=a.z.number().min(0).max(360),my=a.z.number().min(0).max(100),gy=a.z.number().min(0).max(100),wy=a.z.tuple([yy,my,gy,el]),ci=a.z.union([Qc,fy,tl,wy,py]),by=ci.transform(t=>li(t)),li=(t,e=1)=>{if(t=ci.parse(t),typeof t=="string")return vy(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},vy=(t,e=1)=>(t=Qc.parse(t),t=Ty(t),[ir(t,0),ir(t,2),ir(t,4),t.length===8?ir(t,6)/255:e]),ir=(t,e)=>parseInt(t.slice(e,e+2),16),Ty=t=>t.startsWith("#")?t.slice(1):t;li("#000000");li("#ffffff");const Sy=a.z.object({key:a.z.string(),color:ci,position:a.z.number(),switched:a.z.boolean().optional()});a.z.array(Sy);const zy=a.z.object({key:a.z.string(),name:a.z.string(),color:by});a.z.object({key:a.z.string(),name:a.z.string(),swatches:a.z.array(zy)});a.z.int().min(0).max(255);a.z.object({name:a.z.string(),key:a.z.string()});const Oy=t=>Object.getOwnPropertySymbols(globalThis).includes(t),ky=(t,e)=>{const n=Symbol.for(t);if(!Oy(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},nl="sy_x_error",Ey=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),Dn=t=>class gn extends Error{static discriminator=nl;discriminator=gn.discriminator;static TYPE=t;type=gn.TYPE;static matches=Ey(t);matches=gn.matches;constructor(n,r){super(n,r),this.name=gn.TYPE}static sub(n){return Dn(`${t}.${n}`)}},rl=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==nl)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},kt="unknown",oa="nil";class Ny{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:oa,data:""};if(rl(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:kt,data:e.message};if(typeof e=="string")return{type:kt,data:e};try{return{type:kt,data:JSON.stringify(e)}}catch{return{type:kt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===oa)return null;if(e.type===kt)return new ca(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new ca(e.data)}}const ui=ky("synnax-error-registry",()=>new Ny),xy=({encode:t,decode:e})=>ui().register({encode:t,decode:e}),Ay=t=>ui().encode(t),Iy=t=>t==null?null:ui().decode(t);let ca=class extends Dn("unknown"){};const Cy=a.z.object({type:a.z.string(),data:a.z.string()});class jy extends Dn("canceled"){}class Py extends Dn("not_implemented"){}const Ke=Object.freeze(Object.defineProperty({__proto__:null,Canceled:jy,NONE:oa,NotImplemented:Py,UNKNOWN:kt,Unknown:ca,createTyped:Dn,decode:Iy,encode:Ay,isTyped:rl,payloadZ:Cy,register:xy},Symbol.toStringTag,{value:"Module"})),$y=a.object({jsonrpc:a.literal("2.0"),method:a.string(),params:a.any().optional(),id:a.union([a.string(),a.number(),a.null()]).optional()}),sl=a.object({jsonrpc:a.literal("2.0"),id:a.union([a.string(),a.number(),a.null()])}),_y=sl.extend({result:a.json()}),My=sl.extend({error:a.object({code:a.number().int(),message:a.string().optional(),data:a.json().optional()})}),Ry=a.union([_y,My]);a.union([$y,Ry]);const Uy=a.uuid();a.object({key:Uy,name:a.string().min(1),color:a.string()});a.z.string().regex(/^\d+\.\d+\.\d+$/);const Zy=["standard","scientific","engineering"];a.z.enum(Zy);a.z.enum(["success","info","warning","error","loading","disabled"]);a.z.object({stack:a.z.string()});let Bn=class extends Ke.createTyped("freighter"){},ze=class extends Bn.sub("eof"){constructor(){super("EOF")}},Rt=class extends Bn.sub("stream_closed"){constructor(){super("StreamClosed")}},Je=class extends Bn.sub("unreachable"){url;constructor(t={}){const{message:e="Unreachable",url:n=oy.UNKNOWN}=t;super(e),this.url=n}};const Ly=t=>{if(!t.type.startsWith(Bn.TYPE))return null;if(ze.matches(t))return{type:ze.TYPE,data:"EOF"};if(Rt.matches(t))return{type:Rt.TYPE,data:"StreamClosed"};if(Je.matches(t))return{type:Je.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Dy=t=>{if(!t.type.startsWith(Bn.TYPE))return null;switch(t.type){case ze.TYPE:return new ze;case Rt.TYPE:return new Rt;case Je.TYPE:return new Je;default:throw new Ke.Unknown(`Unknown error type: ${t.data}`)}};Ke.register({encode:Ly,decode:Dy});let al=class{middleware=[];use(...t){this.middleware.push(...t)}async executeMiddleware(t,e){let n=0;const r=async s=>{if(n===this.middleware.length)return await e(s);const i=this.middleware[n];return n++,await i(s,r)};return await r(t)}};const il="Content-Type",By=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Fy=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&By.has(e))return!0;if(t.name==="TypeError"){const n=String(t.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(n))return!0}return t?.name==="AbortError"||t?.code,!1},Yy=400;let qy=class extends al{endpoint;encoder;constructor(t,e,n=!1){return super(),this.endpoint=t.replace({protocol:n?"https":"http"}),this.encoder=e,new Proxy(this,{get:(r,s,i)=>s==="endpoint"?this.endpoint:Reflect.get(r,s,i)})}get headers(){return{[il]:this.encoder.contentType}}async send(t,e,n,r){e=n?.parse(e);let s=null;const i=this.endpoint.child(t),o={};o.method="POST",o.body=this.encoder.encode(e??{});const[,c]=await this.executeMiddleware({target:i.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async l=>{const u={...l,params:{}};o.headers={...this.headers,...l.params};let h;try{h=await fetch(l.target,o)}catch(f){if(!(f instanceof Error))throw f;return[u,Fy(f)?new Je({url:i}):f]}const p=await h.arrayBuffer();if(h?.ok)return r!=null&&(s=this.encoder.decode(p,r)),[u,null];try{if(h.status!==Yy)return[u,new Error(h.statusText)];const f=this.encoder.decode(p,Ke.payloadZ),O=Ke.decode(f);return[u,O]}catch(f){return[u,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${f.message}`)]}});if(c!=null)return[null,c];if(s==null)throw new Error("Response must be defined");return[s,null]}};const Vy=(t,e)=>{class n{wrapped;constructor(s){this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,i,o,c){const l=new hy.Breaker(e);do{const[u,h]=await this.wrapped.send(s,i,o,c);if(h==null)return[u,null];if(!Je.matches(h))return[null,h];if(console.warn(`[freighter] ${l.retryMessage}`,h),!await l.wait())return[u,h]}while(!0)}}return new n(t)},b=async(t,e,n,r,s)=>{const[i,o]=await t.send(e,n,r,s);if(o!=null)throw o;return i},Wy=a.z.object({type:a.z.enum(["data","close","open"]),payload:a.z.unknown(),error:a.z.optional(Ke.payloadZ)});class Hy{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,n,r,s){this.codec=n,this.reqSchema=r,this.resSchema=s,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 Ke.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ze;if(this.sendClosed)throw new Rt;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=Ke.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,n)=>this.receiveCallbacksQueue.push({resolve:e,reject:n}))}addMessage(e){const n=this.receiveCallbacksQueue.shift();n!=null?n.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,Wy))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Ky?ze.TYPE:Rt.TYPE,data:""}})}}const Gy="freighterctx",Ky=1e3;let Jy=class la extends al{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,n,r=!1){super(),this.secure=r,this.baseUrl=e.replace({protocol:r?"wss":"ws"}),this.encoder=n}withCodec(e){const n=new la(this.baseUrl,e,this.secure);return n.use(...this.middleware),n}async stream(e,n,r){let s;const[,i]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),l={...o,params:{}};c.binaryType=la.MESSAGE_TYPE;const u=await this.wrapSocket(c,n,r);return u instanceof Error?[l,u]:(s=u,[l,null])});if(i!=null)throw i;return s}buildURL(e,n){const r=iy({[il]:this.encoder.contentType,...n.params},Gy);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const i=new Hy(e,this.encoder,n,r);i.receiveOpenAck().then(o=>{o!=null?s(o):s(i)}).catch(o=>s(o))},e.onerror=i=>{const o=i;s(new Error(o.message))}})}};const ol=t=>a.union([a.union([a.null(),a.undefined()]).transform(()=>[]),t.array()]),Xy=t=>Array.isArray(t)?t:t==null?[]:[t],cl=(t,e)=>{if(Array.isArray(e))return e.reduce((s,i)=>cl(s,i),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s==e),r=[...t];return n===-1?r.push(e):r[n]=e,r},Qy=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),ll=(t,e)=>{if(Array.isArray(e))return e.reduce((s,i)=>ll(s,i),t??[]);if(t==null)return[e];const n=t.findIndex(s=>s.key===e.key),r=[...t];return n===-1?r.push(e):r[n]=e,r},em=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n.key)):t.filter(n=>n.key!==e)}),v=Object.freeze(Object.defineProperty({__proto__:null,nullableZ:ol,remove:Qy,removeKeyed:em,toArray:Xy,upsert:cl,upsertKeyed:ll},Symbol.toStringTag,{value:"Module"})),tm=t=>{const e=t.replace(/_[a-z]/g,n=>n[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)},Xr=t=>{const e=(n,r=ua)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!_s(n))return n;r=sm(r);const s={},i=n;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),r):(Object.keys(i).forEach(o=>{let c=i[o];const l=t(o);r.recursive&&(_s(c)?No(c)||(c=e(c,r)):r.recursiveInArray&&Eo(c)&&(c=[...c].map(u=>{let h=u;return _s(u)?No(h)||(h=e(u,r)):Eo(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},hi=Xr(tm),nm=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),ul=Xr(nm),hl=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),rm=[Number,String,Uint8Array],ua={recursive:!0,recursiveInArray:!0},sm=(t=ua)=>(t.recursive==null?t=ua:t.recursiveInArray??=!1,t),Eo=t=>t!=null&&Array.isArray(t),_s=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),No=t=>rm.some(e=>t instanceof e),am=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),im=Xr(am),om=t=>{if(t.length===0)return t;let e=t.replace(/[_-]/g," ");return e=e.replace(/([a-z0-9])([A-Z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/([A-Z]+)([A-Z][a-z])/g,(n,r,s)=>`${r} ${s}`),e=e.replace(/\s+/g," ").trim(),e=e.replace(/\b\w/g,n=>n.toUpperCase()),e},cm=Xr(om),lm=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:ul,capitalize:hl,snakeToCamel:hi,toKebab:im,toProperNoun:cm},Symbol.toStringTag,{value:"Module"})),dl=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);let fl=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t))}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const n=JSON.parse(t),r=hi(n);return e!=null?e.parse(r):r}encodeString(t){const e=ul(t);return JSON.stringify(e,(n,r)=>ArrayBuffer.isView(r)?Array.from(r):typeof r=="bigint"?r.toString():r)}},pl=class{contentType="text/csv";encode(t){const e=this.encodeString(t);return new TextEncoder().encode(e)}decode(t,e){const n=new TextDecoder().decode(t);return this.decodeString(n,e)}encodeString(t){if(!Array.isArray(t)||t.length===0||!dl(t[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(t[0]),n=[e.join(",")];return t.forEach(r=>{const s=e.map(i=>JSON.stringify(r[i]??""));n.push(s.join(","))}),n.join(`
|
|
7
|
-
`)}decodeString(t,e){const[n,...r]=t.trim().split(`
|
|
8
|
-
`).map(o=>o.trim());if(n.length===0)return e!=null?e.parse({}):{};const s=n.split(",").map(o=>o.trim()),i={};return s.forEach(o=>{i[o]=[]}),r.forEach(o=>{const c=o.split(",").map(l=>l.trim());s.forEach((l,u)=>{const h=this.parseValue(c[u]);h!=null&&i[l].push(h)})}),e!=null?e.parse(i):i}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}},yl=class{contentType="text/plain";encode(t){if(typeof t!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(t)}decode(t,e){const n=new TextDecoder().decode(t);return e!=null?e.parse(n):n}};const En=new fl,um=new pl,hm=new yl,dm=[En],wt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:pl,CSV_CODEC:um,ENCODERS:dm,JSONCodec:fl,JSON_CODEC:En,TEXT_CODEC:hm,TextCodec:yl},Symbol.toStringTag,{value:"Module"})),ha=t=>[...new Set(t)],fm=(t,e,n=!0)=>{const r=new Map;return t.forEach(s=>{const i=e(s);if(r.has(i)){if(n)return;r.delete(i)}r.set(i,s)}),Array.from(r.values())},xo=Object.freeze(Object.defineProperty({__proto__:null,by:fm,unique:ha},Symbol.toStringTag,{value:"Module"})),ye=t=>t!=null&&typeof t=="object"&&"value"in t;let Qt=class{value;constructor(t){this.value=t}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const pm=t=>t!=null&&typeof t=="object"&&"toString"in t,Qr=(t,e=!1)=>{const n=pm(t)?"stringer":typeof t;let r;switch(n){case"string":r=(s,i)=>s.localeCompare(i);break;case"stringer":r=(s,i)=>s.toString().localeCompare(i.toString());break;case"number":r=(s,i)=>Number(s)-Number(i);break;case"bigint":r=(s,i)=>BigInt(s)-BigInt(i)>0n?1:-1;break;case"boolean":r=(s,i)=>Number(s)-Number(i);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${n}`),()=>-1}return e?gl(r):r},ym=(t,e,n)=>{const r=Qr(e[t],n);return(s,i)=>r(s[t],i[t])},mm=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,ml=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=Qr(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((i,o)=>i===s[o])?0:-1},gm=(t,e)=>{const n=ha(t),r=ha(e);return ml(n,r)},wm=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,gl=t=>(e,n)=>t(n,e),en=0,br=-1,vr=1,wl=t=>t<en,bl=t=>t>en,bm=t=>t>=en,vl=t=>t===en,vm=(t,e)=>{const n=/([a-zA-Z]+)|(\d+)/g,r=t.replace(/[\s_.-]+/g,"").match(n),s=e.replace(/[\s_.-]+/g,"").match(n);if(!r||!s)return 0;for(let i=0;i<Math.min(r.length,s.length);i++){const o=r[i],c=s[i];if(isNaN(Number(o))&&isNaN(Number(c))){const l=o.localeCompare(c);if(l!==0)return l}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const l=Number(o)-Number(c);if(l!==0)return l}else return isNaN(Number(o))?-1:1}return r.length-s.length},Ao=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:en,GREATER_THAN:vr,LESS_THAN:br,isEqualTo:vl,isGreaterThan:bl,isGreaterThanEqual:bm,isLessThan:wl,newF:Qr,newFieldF:ym,order:wm,primitiveArrays:mm,reverseF:gl,stringsWithNumbers:vm,uniqueUnorderedPrimitiveArrays:gm,unorderedPrimitiveArrays:ml},Symbol.toStringTag,{value:"Module"})),es=a.z.tuple([a.z.number(),a.z.number()]);a.z.tuple([a.z.bigint(),a.z.bigint()]);const Tl=a.z.object({width:a.z.number(),height:a.z.number()}),Tm=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()}),Sm=["width","height"];a.z.enum(Sm);const zm=["start","center","end"],Om=["signedWidth","signedHeight"];a.z.enum(Om);const Nn=a.z.object({x:a.z.number(),y:a.z.number()}),Sl=a.z.object({clientX:a.z.number(),clientY:a.z.number()}),zl=["x","y"],Ol=a.z.enum(zl),di=["top","right","bottom","left"],km=a.z.enum(di),kl=["left","right"],fi=a.z.enum(kl),El=["top","bottom"],pi=a.z.enum(El),yi=["center"],da=a.z.enum(yi),Em=[...di,...yi],mi=a.z.enum(Em);a.z.enum(zm);const Nm=["first","last"];a.z.enum(Nm);const xm=a.z.object({lower:a.z.number(),upper:a.z.number()}),Am=a.z.object({lower:a.z.bigint(),upper:a.z.bigint()});a.z.union([xm,es]);a.z.union([Am,es]);a.z.enum([...Ol.options,...mi.options]);a.z.enum(["x","left","right"]);a.z.enum(["y","top","bottom"]);const Im=a.z.union([Ol,mi,a.z.instanceof(String)]),tn=t=>(e,n)=>{if(typeof e=="bigint"){if(kr(n))return t(e,BigInt(n));const r=t(Number(e),Number(n));return typeof r=="number"?BigInt(Math.round(r)):r}return t(Number(e),Number(n))},Ge=tn((t,e)=>t-e),nn=tn((t,e)=>t+e),Cm=(t,e,n=1e-4)=>Math.abs(t-e)<n,fa=(t,e)=>{const n=typeof t=="bigint",r=typeof e=="bigint";return n&&r?t===e:n&&kr(e)?t===BigInt(e):r&&kr(t)?e===BigInt(t):t===e},jm=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},Nl=tn((t,e)=>t<=e?t:e),kr=t=>typeof t=="bigint"?!0:Number.isInteger(t),Pm=tn((t,e)=>t>=e?t:e),xl=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,ve=tn((t,e)=>t*e),Fn=tn((t,e)=>t/e),K=(t,e,n)=>{const r={};if(typeof e=="object"&&(n=e,e=void 0),n={makeValid:!0,...n},typeof t=="number"||typeof t=="bigint")e!=null?(r.lower=t,r.upper=e):(r.lower=typeof t=="bigint"?0n:0,r.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[r.lower,r.upper]=t}else r.lower=t.lower,r.upper=t.upper;return n?.makeValid?$m(r):r},$m=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Io=(t,e)=>{const n=K(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},or=(t,e)=>{const n=K(t);if(typeof e=="number"||typeof e=="bigint")return e>=n.lower&&e<n.upper;const r=K(e);return r.lower>=n.lower&&r.upper<=n.upper},_m=t=>{const e=K(t);return e.upper-e.lower},Mm=t=>({lower:Math.min(...t.map(e=>K(e).lower)),upper:Math.max(...t.map(e=>K(e).upper))}),Rm=(t,e,n)=>{const r=t.map(c=>K(c)),s=n>0?1:n<0?-1:0;if(s===0)return e;let i=n,o=e;for(;fa(i,0)===!1;){const c=r.findIndex(l=>s>0?o>=l.lower&&o<l.upper:o>l.lower&&o<=l.upper);if(c!==-1){const l=r[c];let u;if(s>0?u=Ge(l.upper,o):u=Ge(o,l.lower),u>0){const h=Nl(xl(i),u);if(o=nn(o,s>0?h:-h),i=Ge(i,s>0?h:-h),fa(i,0))return o;continue}}if(s>0){const l=r.filter(u=>u.lower>o);if(l.length>0)o=l[0].lower;else return o}else{const l=r.filter(u=>u.upper<o);if(l.length>0)o=l[l.length-1].upper;else return o}}return o},Um=(t,e,n)=>{const r=t.map(o=>K(o));if(e===n)return typeof e=="bigint"?0n:0;const s=e<n?K([e,n]):K([n,e]);let i=typeof e=="bigint"?0n:0;for(const o of r){const c=o.lower>s.lower?o.lower:s.lower,l=o.upper<s.upper?o.upper:s.upper;if(c<l){const u=l-c;i=i+u}}return i},Zm=fi,Lm=pi,Dm=da,Bm={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},Fm={top:"left",right:"top",bottom:"right",left:"bottom",center:"center"},Ym=Im,Xe=t=>t instanceof String||!zl.includes(t)?t:t==="x"?"left":"top",qm=t=>Bm[Xe(t)],Vm=t=>Fm[Xe(t)],xn=t=>{const e=Xe(t);return e==="top"||e==="bottom"?"y":"x"},Wm=a.z.object({x:fi.or(da),y:pi.or(da)}),Al=a.z.object({x:fi,y:pi}),gi=Object.freeze({x:"left",y:"top"}),Il=Object.freeze({x:"right",y:"top"}),Cl=Object.freeze({x:"left",y:"bottom"}),jl=Object.freeze({x:"right",y:"bottom"}),wi=Object.freeze({x:"center",y:"center"}),Pl=Object.freeze({x:"center",y:"top"}),$l=Object.freeze({x:"center",y:"bottom"}),_l=Object.freeze({x:"right",y:"center"}),Ml=Object.freeze({x:"left",y:"center"}),Hm=Object.freeze([Ml,_l,Pl,$l,gi,Il,Cl,jl,wi]),Rl=(t,e)=>t.x===e.x&&t.y===e.y,Gm=(t,e)=>{if(typeof e=="object"){let n=!0;return"x"in e&&(t.x===e.x||(n=!1)),"y"in e&&(t.y===e.y||(n=!1)),n}return t.x===e||t.y===e},Km=t=>[t.x,t.y],Tr=t=>xn(Xe(t))==="x",Jm=t=>xn(Xe(t))==="y",Xm=t=>`${t.x}${hl(t.y)}`,Qm=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=Xe(t),r=Xe(e??t)),xn(n)===xn(r)&&n!=="center"&&r!=="center")throw new Error(`[XYLocation] - encountered two locations with the same direction: ${n.toString()} - ${r.toString()}`);const s={...wi};return n==="center"?Tr(r)?[s.x,s.y]=[r,n]:[s.x,s.y]=[n,r]:r==="center"?Tr(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n]:Tr(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n],s},eg=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:$l,BOTTOM_LEFT:Cl,BOTTOM_RIGHT:jl,CENTER:wi,CENTER_LEFT:Ml,CENTER_LOCATIONS:yi,CENTER_RIGHT:_l,OUTER_LOCATIONS:di,TOP_CENTER:Pl,TOP_LEFT:gi,TOP_RIGHT:Il,XY_LOCATIONS:Hm,X_LOCATIONS:kl,Y_LOCATIONS:El,center:Dm,construct:Xe,constructXY:Qm,corner:Al,crude:Ym,direction:xn,isX:Tr,isY:Jm,location:mi,outer:km,rotate90:Vm,swap:qm,x:Zm,xy:Wm,xyCouple:Km,xyEquals:Rl,xyMatches:Gm,xyToString:Xm,y:Lm},Symbol.toStringTag,{value:"Module"})),pa=a.z.union([a.z.number(),Nn,es,Tl,Tm,Sl]),Z=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},yt=Object.freeze({x:0,y:0}),tg=Object.freeze({x:1,y:1}),ng=Object.freeze({x:1/0,y:1/0}),rg=Object.freeze({x:NaN,y:NaN}),Ul=(t,e,n=0)=>{const r=Z(t),s=Z(e);return n===0?r.x===s.x&&r.y===s.y:Math.abs(r.x-s.x)<=n&&Math.abs(r.y-s.y)<=n},sg=t=>Ul(t,yt),bi=(t,e,n)=>{const r=Z(t),s=Z(e,n);return{x:r.x*s.x,y:r.y*s.y}},Zl=(t,e)=>{const n=Z(t);return{x:n.x+e,y:n.y}},Ll=(t,e)=>{const n=Z(t);return{x:n.x,y:n.y+e}},Dl=(t,e,n,...r)=>{if(typeof e=="string"){if(typeof n!="number")throw new Error("The value must be a number.");return e==="x"?Zl(t,n):Ll(t,n)}if(typeof e=="object"&&"x"in e&&typeof e.x=="string"){const s=Z(n),i=Z(t);return e.x==="left"?s.x=-s.x:e.x==="center"&&(s.x=0),e.y==="top"?s.y=-s.y:e.y==="center"&&(s.y=0),{x:i.x+s.x,y:i.y+s.y}}return[t,e,n??yt,...r].reduce((s,i)=>{const o=Z(i);return{x:s.x+o.x,y:s.y+o.y}},yt)},ag=(t,e,n)=>{const r=Z(t);return e==="x"?{x:n,y:r.y}:{x:r.x,y:n}},ig=(t,e)=>{const n=Z(t),r=Z(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},og=(t,e)=>{const n=Z(t),r=Z(e);return{x:r.x-n.x,y:r.y-n.y}},cg=t=>{const e=Z(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},lg=t=>{const e=Z(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},ug=t=>{const e=Z(t);return[e.x,e.y]},hg=t=>{const e=Z(t);return{left:e.x,top:e.y}},dg=(t,e=0)=>{const n=Z(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},wn=(t,e)=>{const n=Z(t),r=Z(e);return{x:n.x-r.x,y:n.y-r.y}},bn=t=>{const e=Z(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:-e.y/n,y:e.x/n}},Bl=t=>{const e=Z(t),n=Math.hypot(e.x,e.y);return n===0?{x:0,y:0}:{x:e.x/n,y:e.y/n}},Fl=(...t)=>{const e=t.reduce((n,r)=>Dl(n,r),yt);return bi(e,1/t.length)},fg=(t,e)=>{const n=[];for(let r=0;r<t.length;r++){const s=t[r];let i,o,c,l;if(r===0){const u=t[r+1],h=wn(u,s);o=bn(h),c=o,l=e}else if(r===t.length-1){const u=t[r-1],h=wn(s,u);i=bn(h),c=i,l=e}else{const u=t[r-1],h=t[r+1],p=wn(s,u),f=wn(h,s);i=bn(p),o=bn(f);const O=Math.acos((p.x*f.x+p.y*f.y)/(Math.hypot(p.x,p.y)*Math.hypot(f.x,f.y))),I=Math.sin(O/2);I===0?l=e:l=e/I,c=Bl(Fl(i,o))}n.push(bi(c,l))}return n},pg=t=>{const e=Z(t);return{x:e.y,y:e.x}},yg=t=>{const e=Z(t);return{x:Math.round(e.x),y:Math.round(e.y)}},mg=t=>{const e=Z(t);return{x:1/e.x,y:1/e.y}},vi=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:ng,NAN:rg,ONE:tg,ZERO:yt,average:Fl,calculateMiters:fg,clientXY:Sl,construct:Z,couple:ug,crudeZ:pa,css:hg,distance:ig,equals:Ul,isFinite:lg,isNan:cg,isZero:sg,normal:bn,normalize:Bl,reciprocal:mg,round:yg,scale:bi,set:ag,sub:wn,swap:pg,translate:Dl,translateX:Zl,translateY:Ll,translation:og,truncate:dg,xy:Nn},Symbol.toStringTag,{value:"Module"})),cr=a.z.union([a.z.number(),a.z.string()]);a.z.object({top:cr,left:cr,width:cr,height:cr});a.z.object({left:a.z.number(),top:a.z.number(),right:a.z.number(),bottom:a.z.number()});a.z.object({one:Nn,two:Nn,root:Al});const Ti=(t,e,n=0,r=0,s)=>{const i={one:{...yt},two:{...yt},root:s??gi};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:t,y:e},i.two={x:i.one.x+n,y:i.one.y+r},i}return"one"in t&&"two"in t&&"root"in t?{...t,root:s??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(i.one={x:t.left,y:t.top},i.two={x:t.right,y:t.bottom},i):(i.one=t,e==null?i.two={x:i.one.x+n,y:i.one.y+r}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+n}:"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))},Ms=t=>{const e=Ti(t);return{lower:e.one.x,upper:e.two.x}},Rs=t=>{const e=Ti(t);return{lower:e.one.y,upper:e.two.y}},gg=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,wg=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()});a.z.union([Tl,wg,Nn,es]);const bg=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;a.z.object({offset:pa,scale:pa});a.z.object({offset:a.z.number(),scale:a.z.number()});const vg=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Tg=t=>(e,n,r,s)=>[e,s?r/t:r*t],Sg=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:i}=e,{lower:o,upper:c}=t,l=i-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},zg=t=>(e,n,r)=>[t,r],Og=()=>(t,e,n)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,n];const{lower:r,upper:s}=t;return[t,s-(n-r)]},kg=t=>(e,n,r)=>{const{lower:s,upper:i}=t;return r=bg(r,s,i),[e,r]};let Co=class Et{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Et().translate(e)}static magnify(e){return new Et().magnify(e)}static scale(e,n){return new Et().scale(e,n)}translate(e){const n=this.new(),r=vg(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Tg(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=K(e,n),s=this.new(),i=Sg(r);return i.type="scale",s.ops.push(i),s}clamp(e,n){const r=K(e,n),s=this.new(),i=kg(r);return i.type="clamp",s.ops.push(i),s}reBound(e,n){const r=K(e,n),s=this.new(),i=zg(r);return i.type="re-bound",s.ops.push(i),s}invert(){const e=Og();e.type="invert";const n=this.new();return n.ops.push(e),n}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Et;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],i)=>i(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const i=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);i!==-1&&n.push([s,i])}),n.forEach(([r,s])=>{const i=e.ops.slice(r,s);i.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Et};(class Ae{x;y;currRoot;constructor(e=new Co,n=new Co,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Ae().translate(e,n)}static translateX(e){return new Ae().translateX(e)}static translateY(e){return new Ae().translateY(e)}static clamp(e){return new Ae().clamp(e)}static magnify(e){return new Ae().magnify(e)}static scale(e){return new Ae().scale(e)}static reBound(e){return new Ae().reBound(e)}translate(e,n){const r=Z(e,n),s=this.copy();return s.x=this.x.translate(r.x),s.y=this.y.translate(r.y),s}translateX(e){const n=this.copy();return n.x=this.x.translate(e),n}translateY(e){const n=this.copy();return n.y=this.y.translate(e),n}magnify(e){const n=this.copy();return n.x=this.x.magnify(e.x),n.y=this.y.magnify(e.y),n}scale(e){const n=this.copy();if(gg(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Rl(r,e.root)&&(r.x!==e.root.x&&(n.x=n.x.invert()),r.y!==e.root.y&&(n.y=n.y.invert())),n.x=n.x.scale(Ms(e)),n.y=n.y.scale(Rs(e)),n}return n.x=n.x.scale(e.width),n.y=n.y.scale(e.height),n}reBound(e){const n=this.copy();return n.x=this.x.reBound(Ms(e)),n.y=this.y.reBound(Rs(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(Ms(e)),n.y=this.y.clamp(Rs(e)),n}copy(){const e=new Ae;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 Ti(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 Ae});let Yl=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const ql="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Eg=`0123456789${ql}`,Vl=11,Ng=Yl(ql,1),xg=Yl(Eg,Vl-1),Si=()=>`${Ng()}${xg()}`,Ag=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:Vl,create:Si},Symbol.toStringTag,{value:"Module"})),Ig=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,Cg=2**8-1,jg=2**16-1,Pg=2**32-1,$g=2n**64n-1n,_g=2**64-1,Mg=-128,Rg=2**7-1,Ug=-32768,Zg=2**15-1,Lg=-2147483648,Dg=2**31-1,Bg=-(2n**63n),Er=2n**63n-1n,Fg=-9223372036854776e3,Wl=2**63-1,Yg=a.z.enum(["static","dynamic"]),jo=365,lr=30,qg=a.z.union([a.z.tuple([a.z.int()]),a.z.tuple([a.z.int(),a.z.int().min(1).max(12)]),a.z.tuple([a.z.int(),a.z.int().min(1).max(12),a.z.int().min(1).max(31)])]),Hl=(t,e)=>{const n=new C(e);if(![x.DAY,x.HOUR,x.MINUTE,x.SECOND,x.MILLISECOND,x.MICROSECOND,x.NANOSECOND].some(s=>s.equals(n)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=t.valueOf()%n.valueOf();return t instanceof C?new C(r):new x(r)};let C=class z extends Qt{constructor(e,n="UTC"){if(e==null)super(z.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*z.MILLISECOND.valueOf());else if(typeof e=="string")super(z.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(z.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=z.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===Wl?e=Er:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=z.MAX:e=z.MIN)),ye(e)&&(e=e.value),super(BigInt(e.valueOf())+r)}}static parseDate([e=1970,n=1,r=1]){const s=new Date(e,n-1,r,0,0,0,0);return new z(BigInt(s.getTime())*z.MILLISECOND.valueOf()).truncate(z.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,i]=e.split(":");let o="00",c="00";i!=null&&([o,c]=i.split("."));let l=z.hours(parseInt(r??"00")).add(z.minutes(parseInt(s??"00"))).add(z.seconds(parseInt(o??"00"))).add(z.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(z.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return z.parseTimeString(e,n);const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new z(BigInt(r.getTime())*z.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(z.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new x(BigInt(new Date().getTimezoneOffset())*z.MINUTE.valueOf())}static since(e){return new z().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new z(e).valueOf()}span(e){return this.range(e).span}range(e){return new F(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new z(e).valueOf()}afterEq(e){return this.valueOf()>=new z(e).valueOf()}before(e){return this.valueOf()<new z(e).valueOf()}beforeEq(e){return this.valueOf()<=new z(e).valueOf()}add(e){return new z(nn(this.valueOf(),new x(e).valueOf()))}sub(e){return new z(Ge(this.valueOf(),new x(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(x.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(x.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(x.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(x.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(z.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new z(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new z(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new z(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new z(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new z(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new z(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new z(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new z(n)}toString(e="ISO",n="UTC"){switch(e){case"ISODate":return this.toISOString(n).slice(0,10);case"ISOTime":return this.toISOString(n).slice(11,23);case"time":return this.timeString(!1,n);case"preciseTime":return this.timeString(!0,n);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,n)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,n)}`;default:return this.toISOString(n)}}remainder(e){return Hl(this,e)}get isToday(){return this.truncate(x.DAY).equals(z.now().truncate(x.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new z(new Date)}static max(...e){let n=z.MIN;for(const r of e){const s=new z(r);s.after(n)&&(n=s)}return n}static min(...e){let n=z.MAX;for(const r of e){const s=new z(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new z(e,n)}static NANOSECOND=z.nanoseconds(1);static microseconds(e,n="UTC"){return z.nanoseconds(e*1e3,n)}static MICROSECOND=z.microseconds(1);static milliseconds(e,n="UTC"){return z.microseconds(e*1e3,n)}static MILLISECOND=z.milliseconds(1);static seconds(e,n="UTC"){return z.milliseconds(e*1e3,n)}static SECOND=z.seconds(1);static minutes(e,n="UTC"){return z.seconds(e*60,n)}static MINUTE=z.minutes(1);static hours(e,n="UTC"){return z.minutes(e*60,n)}static HOUR=z.hours(1);static days(e,n="UTC"){return z.hours(e*24,n)}static DAY=z.days(1);static MAX=new z(Er);static MIN=new z(0);static ZERO=new z(0);static z=a.z.union([a.z.instanceof(z),a.z.object({value:a.z.bigint()}).transform(e=>new z(e.value)),a.z.string().transform(e=>new z(BigInt(e))),a.z.number().transform(e=>new z(e)),a.z.bigint().transform(e=>new z(e)),a.z.date().transform(e=>new z(e)),a.z.custom(e=>e instanceof x).transform(e=>new z(e)),qg.transform(e=>new z(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}},x=class E extends Qt{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),ye(e)&&(e=e.value),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof E?e:e instanceof Us?e.period:e instanceof C?new E(e):(ye(e)&&(e=e.value),["number","bigint"].includes(typeof e)?E.seconds(e):new E(e))}static fromMilliseconds(e){return e instanceof E?e:e instanceof Us?e.period:e instanceof C?new E(e):(ye(e)&&(e=e.value),["number","bigint"].includes(typeof e)?E.milliseconds(e):new E(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new E(e).valueOf()}greaterThan(e){return this.valueOf()>new E(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new E(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new E(e).valueOf()}remainder(e){return Hl(this,e)}truncate(e){return new E(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(E.DAY),r=this.truncate(E.HOUR),s=this.truncate(E.MINUTE),i=this.truncate(E.SECOND),o=this.truncate(E.MILLISECOND),c=this.truncate(E.MICROSECOND),l=this.truncate(E.NANOSECOND),u=n,h=r.sub(n),p=s.sub(r),f=i.sub(s),O=o.sub(i),I=c.sub(o),j=l.sub(c);let w="";return u.isZero||(w+=`${u.days}d `),h.isZero||(w+=`${h.hours}h `),p.isZero||(w+=`${p.minutes}m `),f.isZero||(w+=`${f.seconds}s `),O.isZero||(w+=`${O.milliseconds}ms `),I.isZero||(w+=`${I.microseconds}µs `),j.isZero||(w+=`${j.nanoseconds}ns`),w.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new E(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(E.SECOND))return"< 1s";const s=n.days,i=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/jo),u=Math.floor(s/lr),h=Math.floor(s/7),p=Math.floor(s),f=Math.floor(i),O=Math.floor(o),I=Math.floor(c),j=r?"-":"";if(l>=1){let w=`${l}y`;if(l<2){const T=Math.floor(s%jo/lr);T>0&&(w+=` ${T}mo`)}return j+w}if(h>=1&&s<lr&&s%7===0){let w=`${h}w`;const T=Math.floor(s%7),A=Math.floor(i-h*7*24);return h<2&&(T>0?w+=` ${T}d`:A>0&&A<24&&(w+=` ${A}h`)),j+w}if(u>=1){let w=`${u}mo`;if(u<3){const T=Math.floor(s%lr);T>0&&(w+=` ${T}d`)}return j+w}if(h>=1){let w=`${h}w`;const T=Math.floor(s%7),A=Math.floor(i-h*7*24);return h<2&&(T>0?w+=` ${T}d`:A>0&&A<24&&(w+=` ${A}h`)),j+w}if(p>=1){let w=`${p}d`;const T=Math.floor(i-p*24);return p<2&&T>0&&(w+=` ${T}h`),j+w}if(f>=1){let w=`${f}h`;if(f<3){const T=Math.floor(o-f*60);T>0&&(w+=` ${T}m`)}return j+w}if(O>=1){let w=`${O}m`;if(O<5){const T=Math.floor(c-O*60);T>0&&(w+=` ${T}s`)}return j+w}return`${j}${I}s`}mult(e){return new E(ve(this.valueOf(),e))}div(e){return new E(Fn(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(E.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new E(e).valueOf()}add(e){return new E(this.valueOf()+new E(e).valueOf())}sub(e){return new E(this.valueOf()-new E(e).valueOf())}static nanoseconds(e=1){return new E(e)}static NANOSECOND=E.nanoseconds(1);static microseconds(e=1){return E.nanoseconds(ve(e,1e3))}static MICROSECOND=E.microseconds(1);static milliseconds(e=1){return E.microseconds(ve(e,1e3))}static MILLISECOND=E.milliseconds(1);static seconds(e=1){return E.milliseconds(ve(e,1e3))}static SECOND=E.seconds(1);static minutes(e=1){return E.seconds(ve(e,60))}static MINUTE=E.minutes(1);static hours(e){return E.minutes(ve(e,60))}static HOUR=E.hours(1);static days(e){return E.hours(ve(e,24))}static DAY=E.days(1);static MAX=new E(Er);static MIN=new E(0);static ZERO=new E(0);static z=a.z.union([a.z.object({value:a.z.bigint()}).transform(e=>new E(e.value)),a.z.string().transform(e=>new E(BigInt(e))),a.z.number().transform(e=>new E(e)),a.z.bigint().transform(e=>new E(e)),a.z.instanceof(E),a.z.instanceof(C).transform(e=>new E(e)),a.z.custom(e=>e instanceof Us).transform(e=>new E(e))])},Us=class de extends Qt{constructor(e){ye(e)&&(e=e.value),super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new de(e).valueOf()}get period(){return x.seconds(1/this.valueOf())}sampleCount(e){return new x(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new re(n).valueOf()}span(e){return x.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new re(n).valueOf())}add(e){return new de(nn(this.valueOf(),new de(e).valueOf()))}sub(e){return new de(Ge(this.valueOf(),new de(e).valueOf()))}mult(e){return new de(ve(this.valueOf(),e))}div(e){return new de(Fn(this.valueOf(),e))}static hz(e){return new de(e)}static khz(e){return de.hz(e*1e3)}static z=a.z.union([a.z.number().transform(e=>new de(e)),a.z.instanceof(de)])},re=class ae extends Qt{constructor(e){ye(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Ut(e*this.valueOf())}add(e){return new ae(nn(this.valueOf(),new ae(e).valueOf()))}sub(e){return new ae(Ge(this.valueOf(),new ae(e).valueOf()))}mult(e){return new ae(ve(this.valueOf(),e))}div(e){return new ae(Fn(this.valueOf(),e))}static UNKNOWN=new ae(0);static BIT128=new ae(16);static BIT64=new ae(8);static BIT32=new ae(4);static BIT16=new ae(2);static BIT8=new ae(1);static z=a.z.union([a.z.number().transform(e=>new ae(e)),a.z.instanceof(ae)])},F=class Ie{start;end;constructor(e,n){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(n))}get span(){return new x(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.start.isZero&&this.end.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Ie(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=x.ZERO){if(n.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return r<0&&(r=-r),s<0&&(s=-s),r<=n.valueOf()&&s<=n.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.toString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,n=x.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const s=C.max(r.start,e.start),i=C.min(r.end,e.end);return i.before(s)?!1:new x(i.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof Ie?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new Ie(this.start,this.end);return e.start.after(this.start)&&(n.start=e.start),e.start.after(this.end)&&(n.end=e.start),e.end.before(this.end)&&(n.end=e.end),e.end.before(this.start)&&(n.start=e.end),n}static max(...e){return new Ie(C.min(...e.map(n=>n.start)),C.max(...e.map(n=>n.end)))}static MAX=new Ie(C.MIN,C.MAX);static ZERO=new Ie(C.ZERO,C.ZERO);static z=a.z.union([a.z.object({start:C.z,end:C.z}).transform(e=>new Ie(e.start,e.end)),a.z.instanceof(Ie)]);static sort(e,n){return C.sort(e.start,n.start)||C.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>Ie.sort(n,r)).reduce((n,r)=>{if(r.span.isZero)return n;if(n.length===0)return n.push(r),n;const s=n[n.length-1];return s.overlapsWith(r)||s.end.equals(r.start)?s.end=C.max(s.end,r.end):n.push(r),n},[])}},M=class g extends Qt{constructor(e){if(ye(e)&&(e=e.value),e instanceof g||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=g.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(n==null)throw new Error(`unable to find data type for ${e.toString()}`);super(n.valueOf())}}get Array(){const e=g.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(n=>this.equals(n))}toString(e=!1){return e?g.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(g.JSON)||this.equals(g.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(g.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=g.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(g.UINT8)||this.equals(g.UINT16)||this.equals(g.UINT32)||this.equals(g.UINT64)}get isSignedInteger(){return this.equals(g.INT8)||this.equals(g.INT16)||this.equals(g.INT32)||this.equals(g.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(g.INT32)&&e.equals(g.FLOAT64)||this.equals(g.INT8)&&e.equals(g.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return g.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new g("unknown");static FLOAT64=new g("float64");static FLOAT32=new g("float32");static INT64=new g("int64");static INT32=new g("int32");static INT16=new g("int16");static INT8=new g("int8");static UINT64=new g("uint64");static UINT32=new g("uint32");static UINT16=new g("uint16");static UINT8=new g("uint8");static BOOLEAN=new g("boolean");static TIMESTAMP=new g("timestamp");static UUID=new g("uuid");static STRING=new g("string");static JSON=new g("json");static ARRAY_CONSTRUCTORS=new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]]);static DENSITIES=new Map([[g.UINT8.toString(),re.BIT8],[g.UINT16.toString(),re.BIT16],[g.UINT32.toString(),re.BIT32],[g.UINT64.toString(),re.BIT64],[g.FLOAT32.toString(),re.BIT32],[g.FLOAT64.toString(),re.BIT64],[g.INT8.toString(),re.BIT8],[g.INT16.toString(),re.BIT16],[g.INT32.toString(),re.BIT32],[g.INT64.toString(),re.BIT64],[g.TIMESTAMP.toString(),re.BIT64],[g.STRING.toString(),re.UNKNOWN],[g.JSON.toString(),re.UNKNOWN],[g.UUID.toString(),re.BIT128]]);static ALL=[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON];static SHORT_STRINGS=new Map([[g.UINT8.toString(),"u8"],[g.UINT16.toString(),"u16"],[g.UINT32.toString(),"u32"],[g.UINT64.toString(),"u64"],[g.INT8.toString(),"i8"],[g.INT16.toString(),"i16"],[g.INT32.toString(),"i32"],[g.INT64.toString(),"i64"],[g.FLOAT32.toString(),"f32"],[g.FLOAT64.toString(),"f64"],[g.BOOLEAN.toString(),"bool"],[g.TIMESTAMP.toString(),"ts"],[g.UUID.toString(),"uuid"],[g.STRING.toString(),"str"],[g.JSON.toString(),"json"]]);static BIG_INT_TYPES=[g.INT64,g.UINT64,g.TIMESTAMP];static z=a.z.union([a.z.string().transform(e=>new g(e)),a.z.instanceof(g)])},Ut=class $ extends Qt{constructor(e){ye(e)&&(e=e.value),super(e.valueOf())}largerThan(e){return ye(e)&&(e=e.value),this.valueOf()>e.valueOf()}smallerThan(e){return ye(e)&&(e=e.value),this.valueOf()<e.valueOf()}add(e){return ye(e)&&(e=e.value),new $(nn(this.valueOf(),e.valueOf()))}sub(e){return ye(e)&&(e=e.value),new $(Ge(this.valueOf(),e.valueOf()))}mult(e){return new $(ve(this.valueOf(),e))}div(e){return new $(Fn(this.valueOf(),e))}truncate(e){return new $(Math.trunc(this.valueOf()/new $(e).valueOf())*new $(e).valueOf())}remainder(e){return $.bytes(this.valueOf()%new $(e).valueOf())}get gigabytes(){return this.valueOf()/$.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/$.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/$.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/$.TERABYTE.valueOf()}toString(){const e=this.truncate($.TERABYTE),n=this.truncate($.GIGABYTE),r=this.truncate($.MEGABYTE),s=this.truncate($.KILOBYTE),i=this.truncate($.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=i.sub(s);let p="";return o.isZero||(p+=`${o.terabytes}TB `),c.isZero||(p+=`${c.gigabytes}GB `),l.isZero||(p+=`${l.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new $(e)}static BYTE=new $(1);static kilobytes(e=1){return $.bytes(new $(e).valueOf()*1e3)}static KILOBYTE=$.kilobytes(1);static megabytes(e=1){return $.kilobytes(new $(e).valueOf()*1e3)}static MEGABYTE=$.megabytes(1);static gigabytes(e=1){return $.megabytes(new $(e).valueOf()*1e3)}static GIGABYTE=$.gigabytes(1);static terabytes(e){return $.gigabytes(new $(e).valueOf()*1e3)}static TERABYTE=$.terabytes(1);static ZERO=new $(0);static z=a.z.union([a.z.number().transform(e=>new $(e)),a.z.instanceof($)]);get isZero(){return this.valueOf()===0}};a.z.object({start:a.z.number(),end:a.z.number()});a.z.union([a.z.instanceof(Uint8Array),a.z.instanceof(Uint16Array),a.z.instanceof(Uint32Array),a.z.instanceof(BigUint64Array),a.z.instanceof(Float32Array),a.z.instanceof(Float64Array),a.z.instanceof(Int8Array),a.z.instanceof(Int16Array),a.z.instanceof(Int32Array),a.z.instanceof(BigInt64Array)]);const Gl=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof C||t instanceof x||t instanceof Date},Vg=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Sr(n,-r),Sr=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),Wg=/^(?:[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 Hg(t){return typeof t=="string"&&Wg.test(t)}const Q=[];for(let t=0;t<256;++t)Q.push((t+256).toString(16).slice(1));function Gg(t,e=0){return(Q[t[e+0]]+Q[t[e+1]]+Q[t[e+2]]+Q[t[e+3]]+"-"+Q[t[e+4]]+Q[t[e+5]]+"-"+Q[t[e+6]]+Q[t[e+7]]+"-"+Q[t[e+8]]+Q[t[e+9]]+"-"+Q[t[e+10]]+Q[t[e+11]]+Q[t[e+12]]+Q[t[e+13]]+Q[t[e+14]]+Q[t[e+15]]).toLowerCase()}function Kg(t,e=0){const n=Gg(t,e);if(!Hg(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Kl=(t,e)=>Kg(t,e),De=-1,ya={[Symbol.iterator]:()=>ya,next:()=>({done:!0,value:void 0})},Jg=a.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Xg=a.z.union([a.z.null(),a.z.undefined()]).transform(()=>new Uint8Array().buffer),ma=10,Jl=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Xl="sy_x_telem_series";let We=class qe{key;discriminator=Xl;dataType;sampleOffset;gl;_data;timeRange=F.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=De;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=a.z.object({timeRange:F.z.optional(),dataType:M.z,alignment:a.z.coerce.bigint().optional(),data:a.z.union([Jg,Xg,a.z.instanceof(ArrayBuffer),a.z.instanceof(Uint8Array)]),glBufferUsage:Yg.optional().default("static").optional()});static z=qe.crudeZ.transform(e=>new qe(e));constructor(e){Qg(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=Si(),data:u}=e;if(Ql(u)){const f=u;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=Gl(u),p=Array.isArray(u);if(n!=null)this.dataType=new M(n);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(p||h){let f=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=u[0]}if(typeof f=="string")this.dataType=M.STRING;else if(typeof f=="number")this.dataType=M.FLOAT64;else if(typeof f=="bigint")this.dataType=M.INT64;else if(typeof f=="boolean")this.dataType=M.BOOLEAN;else if(f instanceof C||f instanceof Date||f instanceof C)this.dataType=M.TIMESTAMP;else if(typeof f=="object")this.dataType=M.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new M(u)}if(!p&&!h)this._data=u;else if(p&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[u]:u;const O=f[0];(O instanceof C||O instanceof Date||O instanceof x)&&(f=f.map(I=>new C(I).valueOf())),this.dataType.equals(M.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
|
|
9
|
-
`)}
|
|
10
|
-
`).buffer):this.dataType.equals(M.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(I=>En.encodeString(I)).join(`
|
|
11
|
-
`)}
|
|
12
|
-
`).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(I=>BigInt(Math.round(I)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??F.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:n,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const s=new new M(n).Array(e),i=new qe({data:s.buffer,dataType:n,...r});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===De)return 0;const n=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,n);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===De)return 0;const n=this.capacity-this.writePos,r=e.sub(0,n);return this.writeToUnderlyingData(r),this.cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.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===De?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(M.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(En.decodeString(n)))}get byteCapacity(){return new Ut(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===De?this.byteCapacity:this.dataType.isVariable?new Ut(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===De?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 n=[0];return this.data.forEach((r,s)=>{r===ma&&(e++,n.push(s+1))}),this._cachedIndexes=n,this.cachedLength=e,e}convert(e,n=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let s=0;s<this.length;s++)r[s]=Vg(this.dataType,e,this.data[s],n);return new qe({data:r.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:n,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(M.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}else{const e=this.data;this.cachedMax=e.reduce((n,r)=>n>r?n:r)}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(),Sr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(M.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}else{const e=this.data;this.cachedMin=e.reduce((n,r)=>n<r?n:r)}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(),Sr(this.cachedMin,this.sampleOffset))}get bounds(){return K(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const n=e.cachedMin??e.calcRawMin();n<this.cachedMin&&(this.cachedMin=n)}if(this.cachedMax!=null){const n=e.cachedMax??e.calcRawMax();n>this.cachedMax&&(this.cachedMax=n)}}atAlignment(e,n){const r=Number((e-this.alignment)/this.alignmentMultiple);if(r<0||r>=this.length){if(n===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,n)}at(e,n=!1){if(this.dataType.isVariable)return this.atVariable(e,n??!1);if(this.dataType.equals(M.UUID))return this.atUUID(e,n);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(n===!0)throw new Error(`[series] - no value at index ${e}`);return}return Sr(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Kl(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(r==null){if(n)throw new Error(`[series] - no value at index ${e}`);return}return r}atVariable(e,n){let r=0,s=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],s=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]===ma){if(e===0){s=o;break}r=o+1,e--}if(s===0&&(s=this.data.length),r>=s||e>0){if(n)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(r,s);return this.dataType.equals(M.STRING)?new TextDecoder().decode(i):hi(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let n=0,r=this.length-1;const s=Qr(e);for(;n<=r;){const i=Math.floor((n+r)/2),o=s(this.at(i,!0),e);if(o===0)return i;o<0?n=i+1:r=i-1}return n}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(M.FLOAT32)&&!this.dataType.equals(M.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:n,bufferUsage:r,prevBuffer:s}=this.gl;if(n==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==De){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(s).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,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=De}as(e){return Jl(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:$o(this.alignmentBounds.lower),upper:$o(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return K(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new ew(this);return this.dataType.equals(M.JSON)?new tw(e):e}return this.dataType.equals(M.UUID)?new nw(this):new rw(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Po(this,e,n??this.length)}subAlignmentIterator(e,n){const r=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),s=Math.ceil(Number(n-this.alignment)/Number(this.alignmentMultiple));return new Po(this,r,s)}subBytes(e,n){if(e>=0&&(n==null||n>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,n);return new qe({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,n,r){if(n<=0&&(r==null||r>=this.length))return this;let s;return e?s=this.data.subarray(n,r):s=this.data.slice(n,r),new qe({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new qe({data:this.buffer,dataType:this.dataType,timeRange:F.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(n=>n.toString());else{for(let n=0;n<5;n++)e+=`${this.at(n)?.toString()}`,e+=",";e+="...,";for(let n=-5;n<0;n++)e+=this.at(n)?.toString(),n<-1&&(e+=",")}return e+="])",e}};const Qg=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof We?!0:Gl(t),Ql=Ig(Xl,We);class Po{series;end;index;constructor(e,n,r){this.series=e;const s=K(0,e.length+1);this.end=Io(s,r),this.index=Io(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let ew=class{series;index;decoder;constructor(t){if(!t.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=t,this.index=0,this.decoder=new TextDecoder}next(){const t=this.index,e=this.series.data;for(;this.index<e.length&&e[this.index]!==ma;)this.index++;const n=this.index;return t===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(t,n))})}},tw=class eu{wrapped;static schema=a.z.record(a.z.string(),a.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:En.decodeString(e.value,eu.schema)}}};class nw{series;index;data;density;constructor(e){if(!e.dataType.equals(M.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=M.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Kl(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let rw=class{series;index;constructor(t){this.series=t,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};class sw{series;constructor(e=[]){if(e.length!==0){const n=e[0].dataType;for(let r=1;r<e.length;r++)if(!e[r].dataType.equals(n))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return Jl(e,this.dataType),this}get dataType(){return this.series.length===0?M.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?F.ZERO:new F(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?K(0n,0n):K(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const n=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),r=e.dataType.equals(this.dataType);if(Ql(e)){if(this.series.length!==0&&!r)throw n();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!r)throw n();this.series.push(...e.series)}}get length(){return this.series.reduce((e,n)=>e+n.length,0)}atAlignment(e,n){for(const r of this.series)if(or(r.alignmentBounds,e))return r.atAlignment(e,n);if(n)throw new Error(`[series] - no value at alignment ${e}`)}at(e,n=!1){e<0&&(e=this.length+e);for(const r of this.series){if(e<r.length)return r.at(e,n);e-=r.length}if(n)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,n){return new Zs(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return ya;let r=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)r+=o.length;else if(or(o.alignmentBounds,e)){r+=Math.ceil(Number(e-o.alignment)/Number(o.alignmentMultiple));break}}let s=0;for(let i=0;i<this.series.length;i++){const o=this.series[i];if(n<o.alignment)break;if(n>=o.alignmentBounds.upper)s+=o.length;else if(or(o.alignmentBounds,n)){s+=Math.ceil(Number(n-o.alignment)/Number(o.alignmentMultiple));break}}return new Zs(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return ya;n=Math.min(n,Number(this.distance(e,this.alignmentBounds.upper)));let r=0;for(let s=0;s<this.series.length;s++){const i=this.series[s];if(e<i.alignment)break;if(e>=i.alignmentBounds.upper)r+=i.length;else if(or(i.alignmentBounds,e)){r+=Number(e-i.alignment);break}}return new Zs(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return Mm(this.series.map(e=>e.bounds))}get byteLength(){return new Ut(this.series.reduce((e,n)=>e+n.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let n=0;for(const r of this.series)e.set(r.data,n),n+=r.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,n){const r=this.series.map(s=>s.alignmentBounds);return Rm(r,e,n)}acquire(e){this.series.forEach(n=>n.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,n){const r=this.series.map(s=>s.alignmentBounds);return Um(r,e,n)}parseJSON(e){if(!this.dataType.equals(M.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(n=>n.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new aw(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}class aw{series;seriesIndex;internal;constructor(e){this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}}class Zs{series;index;end;constructor(e,n,r){this.series=e,this.end=r,this.index=n}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 $o=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},iw=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},ow=(t,e,n=".")=>{const r=t.split(n);return r.map((s,i)=>{const o=e(s,i,r);return o==null?null:typeof o=="string"?o:o.join(n)}).filter(s=>s!=null).join(n)},cw=(t,e)=>{if(!Array.isArray(t))return t[e];const n=t[e];if(n!=null||t.length==0)return n;const r=t[0];if(typeof r=="object"&&"key"in r)return t.find(s=>s.key===e)},lw=((t,e,n={optional:!1})=>{const{optional:r,getter:s=cw}=n;if(e==="")return t;const i=e.split(".");if(i.length===1){const c=s(t,i[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${i[0]} is undefined`)}return c}const o=(c,l)=>{if(l>=i.length)return c;for(let u=i.length-l;u>=1;u--){const h=i.slice(l,l+u).join("."),p=s(c,h);if(p!==void 0){if(l+u===i.length)return p;if(p===null){if(r)return null;throw new Error(`Path ${e} does not exist. ${h} is null`)}return o(p,l+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${i[l]} is undefined`)};return o(t,0)});a.z.object({key:a.z.string(),value:a.z.string()});let uw=class{handlers;transform;closer;constructor(t,e){this.transform=t,this.handlers=e??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){let e=t;if(this.transform!=null){const[n,r]=this.transform(t);if(!r)return;e=n}this.handlers.forEach((n,r)=>r(e))}setCloser(t){this.closer=t}async close(){return await this.closer?.()}},hw=class{handlers;constructor(t){this.handlers=t??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){this.handlers.forEach((e,n)=>n(t))}};const dw=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:hw,Observer:uw},Symbol.toStringTag,{value:"Module"})),fw=a.z.record(a.z.union([a.z.number(),a.z.string(),a.z.symbol()]),a.z.unknown()),zi=t=>Object.entries(t),pw=(t,e)=>Object.fromEntries(zi(t).map(([n,r])=>[n,e(r,n)])),yw=t=>Object.fromEntries(zi(t).filter(([e,n])=>n!==void 0)),mw=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},Oe=Object.freeze(Object.defineProperty({__proto__:null,entries:zi,map:pw,omit:mw,purgeUndefined:yw,unknownZ:fw},Symbol.toStringTag,{value:"Module"})),gw=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";gw();const ww=["macOS","Windows","Linux"],bw=["macos","windows","linux"],vw={macos:"macOS",windows:"Windows",linux:"Linux"};a.z.enum(ww).or(a.z.enum(bw).transform(t=>vw[t]));const Tw=(...t)=>t.map(tu).join(""),tu=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Sw=t=>t.endsWith("/")?t.slice(0,-1):t;class Sn{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=tu(s)}replace(e){return new Sn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Sn({...this,pathPrefix:Tw(this.path,e)})}toString(){return Sw(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Sn({host:"unknown",port:0})}const zw=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),Ow=t=>a.array(t).or(t.transform(e=>[e])),nu=t=>ow(t,(e,n,r)=>{const s=n===r.length-1,i=!isNaN(parseInt(e)),o=!isNaN(parseInt(r[n+1]));return i&&(e="element"),s||o?e:[e,"shape"]}),_o=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},kw=((t,e,n)=>e===""?t:lw(_o(t,"shape"),nu(e),{...n,getter:_o})),zn=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:kw,getFieldSchemaPath:nu,nullToUndefined:zw,toArray:Ow},Symbol.toStringTag,{value:"Module"})),Ew=2,Nw=3,xw=2,Aw=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=_m(e);if(n==0)return t;let r;n>=1e3?r=Ew:n>=1?r=Nw:r=Math.ceil(-Math.log10(n))+xw;const s=10**r;return Math.round(t*s)/s},ga=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:Zg,MAX_INT32:Dg,MAX_INT64:Er,MAX_INT64_NUMBER:Wl,MAX_INT8:Rg,MAX_UINT16:jg,MAX_UINT32:Pg,MAX_UINT64:$g,MAX_UINT64_NUMBER:_g,MAX_UINT8:Cg,MIN_INT16:Ug,MIN_INT32:Lg,MIN_INT64:Bg,MIN_INT64_NUMBER:Fg,MIN_INT8:Mg,abs:xl,add:nn,closeTo:Cm,div:Fn,equal:fa,isInteger:kr,max:Pm,min:Nl,mult:ve,roundBySpan:Aw,roundToNearestMagnitude:jm,sub:Ge},Symbol.toStringTag,{value:"Module"})),Iw=async t=>await new Promise(e=>setTimeout(e,x.fromMilliseconds(t).milliseconds));class Cw{config;retries;interval;constructor(e){this.config={baseInterval:new x(e?.baseInterval??x.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Iw},this.retries=0,this.interval=new x(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:n,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(n),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const jw=a.z.object({baseInterval:x.z.optional(),maxRetries:a.z.number().optional(),scale:a.z.number().optional()}),ru=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Cw,breakerConfigZ:jw},Symbol.toStringTag,{value:"Module"})),Pw=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,su=a.z.string().regex(Pw),_t=a.z.number().min(0).max(255),au=a.z.number().min(0).max(1),iu=a.z.tuple([_t,_t,_t,au]),$w=a.z.tuple([_t,_t,_t]),_w=a.z.object({rgba255:iu}),Mw=a.z.number().min(0).max(360),Rw=a.z.number().min(0).max(100),Uw=a.z.number().min(0).max(100),Zw=a.z.tuple([Mw,Rw,Uw,au]),Oi=a.z.union([su,$w,iu,Zw,_w]),Lw=Oi.transform(t=>ki(t)),ki=(t,e=1)=>{if(t=Oi.parse(t),typeof t=="string")return Dw(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},Dw=(t,e=1)=>(t=su.parse(t),t=Bw(t),[ur(t,0),ur(t,2),ur(t,4),t.length===8?ur(t,6)/255:e]),ur=(t,e)=>parseInt(t.slice(e,e+2),16),Bw=t=>t.startsWith("#")?t.slice(1):t;ki("#000000");ki("#ffffff");const Fw=a.z.object({key:a.z.string(),color:Oi,position:a.z.number(),switched:a.z.boolean().optional()});a.z.array(Fw);const Yw=a.z.object({key:a.z.string(),name:a.z.string(),color:Lw});a.z.object({key:a.z.string(),name:a.z.string(),swatches:a.z.array(Yw)});const ou=a.z.int().min(0).max(255),cu=255,lu=0,qw={lower:lu,upper:cu+1},uu=a.z.object({name:a.z.string(),key:a.z.string()}),An=t=>a.z.object({subject:uu,resource:t,authority:ou}),Vw=(...t)=>e=>e.filter(n=>{let r=!1;return n.to!=null&&(r=t.includes(n.to.resource)),n.from!=null&&!r&&(r=t.includes(n.from.resource)),r}),hu=t=>a.z.object({from:An(t),to:a.z.null()}),du=t=>a.z.object({from:a.z.null(),to:An(t)}),Ww=t=>a.z.union([hu(t),du(t),a.z.object({from:An(t),to:An(t)})]),me=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:cu,AUTHORITY_BOUNDS:qw,ZERO_AUTHORITY:lu,acquireZ:du,authorityZ:ou,filterTransfersByChannelKey:Vw,releaseZ:hu,stateZ:An,subjectZ:uu,transferZ:Ww},Symbol.toStringTag,{value:"Module"})),Hw=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Gw=(t,e)=>{const n=Symbol.for(t);if(!Hw(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},fu="sy_x_error",Kw=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),Yn=t=>class vn extends Error{static discriminator=fu;discriminator=vn.discriminator;static TYPE=t;type=vn.TYPE;static matches=Kw(t);matches=vn.matches;constructor(n,r){super(n,r),this.name=vn.TYPE}static sub(n){return Yn(`${t}.${n}`)}},pu=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==fu)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Nt="unknown",wa="nil";class Jw{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:wa,data:""};if(pu(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:Nt,data:e.message};if(typeof e=="string")return{type:Nt,data:e};try{return{type:Nt,data:JSON.stringify(e)}}catch{return{type:Nt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===wa)return null;if(e.type===Nt)return new ba(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new ba(e.data)}}const Ei=Gw("synnax-error-registry",()=>new Jw),Xw=({encode:t,decode:e})=>Ei().register({encode:t,decode:e}),Qw=t=>Ei().encode(t),eb=t=>t==null?null:Ei().decode(t);class ba extends Yn("unknown"){}const tb=a.z.object({type:a.z.string(),data:a.z.string()});class nb extends Yn("canceled"){}class rb extends Yn("not_implemented"){}const Re=Object.freeze(Object.defineProperty({__proto__:null,Canceled:nb,NONE:wa,NotImplemented:rb,UNKNOWN:Nt,Unknown:ba,createTyped:Yn,decode:eb,encode:Qw,isTyped:pu,payloadZ:tb,register:Xw},Symbol.toStringTag,{value:"Module"})),sb=a.object({jsonrpc:a.literal("2.0"),method:a.string(),params:a.any().optional(),id:a.union([a.string(),a.number(),a.null()]).optional()}),yu=a.object({jsonrpc:a.literal("2.0"),id:a.union([a.string(),a.number(),a.null()])}),ab=yu.extend({result:a.json()}),ib=yu.extend({error:a.object({code:a.number().int(),message:a.string().optional(),data:a.json().optional()})}),ob=a.union([ab,ib]);a.union([sb,ob]);const mu=a.uuid(),gu=a.object({key:mu,name:a.string().min(1),color:a.string()}),wu=Object.freeze(Object.defineProperty({__proto__:null,keyZ:mu,labelZ:gu},Symbol.toStringTag,{value:"Module"})),va=a.z.string().regex(/^\d+\.\d+\.\d+$/),qn=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=va.parse(t),s=va.parse(e),[i,o,c]=r.split(".").map(Number),[l,u,h]=s.split(".").map(Number);if(n.checkMajor){if(i<l)return br;if(i>l)return vr}if(n.checkMinor){if(o<u)return br;if(o>u)return vr}if(n.checkPatch){if(c<h)return br;if(c>h)return vr}return en}),cb=(t,e,n={})=>vl(qn(t,e,n)),bu=(t,e,n={})=>bl(qn(t,e,n)),lb=(t,e,n={})=>wl(qn(t,e,n)),ub=({name:t,migrate:e})=>n=>{try{const r=e(n);return console.log(`${t} migrated: ${n.version} -> ${r.version}`),r}catch(r){throw console.log(`${t} failed to migrate from ${n.version}`),console.error(r),r}},hb=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const i=Object.keys(e).sort(qn).pop();if(i==null)return u=>{if(u.version??=r,u.version!==s.version)return console.log(`${t} version ${u.version} is newer than latest version of ${s.version}.
|
|
14
|
-
Returning default instead.
|
|
15
|
-
`),s;try{return n!=null?n.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const l=u=>{try{if(o===0||bu(u.version,i))return console.log(c?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${s.version}`),u;const h=u.version,p=e[h],f=p(u);return c=!0,l(f)}catch(h){return console.log(`${t} failed to migrate from ${u.version} to ${i}`),console.error(h),s}};return u=>{try{if(u.version==null)if(r!=null)console.log(`${t} version is null. Setting version to default of ${r}`),u.version=r;else return console.log(`${t} version is null and no default version set. Exiting with default`),s;return l(u)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),s}}},Mo=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:qn,createMigration:ub,migrator:hb,semVerNewer:bu,semVerOlder:lb,semVerZ:va,versionsEqual:cb},Symbol.toStringTag,{value:"Module"})),db=["standard","scientific","engineering"];a.z.enum(db);const vu=a.z.enum(["success","info","warning","error","loading","disabled"]),fb=t=>a.z.object({key:a.z.string(),name:a.z.string().default(""),variant:vu,message:a.z.string(),description:a.z.string().optional(),time:C.z,labels:ol(gu).optional(),details:t??a.z.unknown().optional()}),pb=a.z.object({stack:a.z.string()}),yb=(t,e)=>{if(!(t instanceof Error))throw t;return Tu({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??""}})},Tu=t=>({key:Si(),time:C.now(),name:"",...t}),mb=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},gb=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},rn=Object.freeze(Object.defineProperty({__proto__:null,create:Tu,exceptionDetailsSchema:pb,fromException:yb,keepVariants:mb,removeVariants:gb,statusZ:fb,variantZ:vu},Symbol.toStringTag,{value:"Module"})),wb=(t,e="")=>{if(typeof t=="string")return t;const n=t.length;return n===0?e:n===1?t[0]:n===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[n-1]}`},bb=t=>{const e=t.split(" "),n=new Set,r=e.map(o=>o.charAt(0).toLowerCase()).join("");n.add(r.replace(/-/g,"_")),n.add(r.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;t.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const l=e.map((u,h)=>h!==c?u.charAt(0).toLowerCase():u).join("");n.add(l.replace(/-/g,"_")),n.add(l.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const i=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return n.add(i.join("").replace(/-/g,"_")),n.add(i.join("_").replace(/-/g,"_")),Array.from(n).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},vb=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Tb=t=>t.length===0?t:t[t.length-1]==="y"?`${t.slice(0,-1)}ies`:t[t.length-1]==="s"||t[t.length-1]==="x"||t[t.length-1]==="z"||t.endsWith("ch")||t.endsWith("sh")?`${t}es`:`${t}s`,Ta=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:bb,naturalLanguageJoin:wb,pluralName:Tb,trimPrefix:vb},Symbol.toStringTag,{value:"Module"})),Sb="all",zb="create",Ob="delete",kb="retrieve",Eb="update",Sa=a.z.enum([Sb,zb,Ob,kb,Eb]);class je extends Re.createTyped("sy"){}let D=class extends je.sub("validation"){};class In extends D.sub("path"){path;error;static encodedSchema=a.z.object({path:a.z.string().array(),error:Re.payloadZ});constructor(e,n){const r=v.toArray(e);super(`${r.join(".")}: ${n.message}`),this.path=r.flatMap(s=>s.split(".")),this.error=n}static decode(e){const n=In.encodedSchema.parse(JSON.parse(e.data));return new In(n.path,Re.decode(n.error))}}class Nr extends je.sub("auth"){}class za extends Nr.sub("invalid_token"){}class Oa extends Nr.sub("expired_token"){}class ee extends je.sub("unexpected"){constructor(e){super(`
|
|
16
|
-
Unexpected error encountered:
|
|
17
|
-
|
|
18
|
-
${e}
|
|
19
|
-
|
|
20
|
-
Please report this to the Synnax team.
|
|
21
|
-
`)}}class Qe extends je.sub("query"){}class Ue extends Qe.sub("not_found"){}class xr extends Qe.sub("multiple_results"){}class Ro extends je.sub("route"){path;constructor(e,n){super(e),this.path=n}}class ka extends je.sub("control"){}class Uo extends ka.sub("unauthorized"){}class Nb extends je.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class R1 extends je.sub("contiguity"){}const xb=t=>t.type.startsWith(je.TYPE)?t.type.startsWith(D.TYPE)?t.type===In.TYPE?In.decode(t):new D(t.data):t.type.startsWith(Nr.TYPE)?t.type.startsWith(za.TYPE)?new za(t.data):t.type.startsWith(Oa.TYPE)?new Oa(t.data):new Nr(t.data):t.type.startsWith(ee.TYPE)?new ee(t.data):t.type.startsWith(Qe.TYPE)?t.type.startsWith(Ue.TYPE)?new Ue(t.data):t.type.startsWith(xr.TYPE)?new xr(t.data):new Qe(t.data):t.type.startsWith(ka.TYPE)?t.type.startsWith(Uo.TYPE)?new Uo(t.data):new ka(t.data):t.type.startsWith(Ro.TYPE)?new Ro(t.data,t.data):new ee(t.data):null,Ab=()=>{throw new Re.NotImplemented};Re.register({encode:Ab,decode:xb});const Ib=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof Je?[n,new Je({message:`Cannot reach cluster at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},Vn=a.z.uuid(),Su=a.z.string(),ts=a.z.object({key:Vn,name:Su}),Cb=t=>({type:"group",key:t}),ns=a.z.enum(["label","log","allow_all","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","table","arc","schematic_symbol","status"]),zu=a.z.string().transform(t=>{const[e,n]=t.split(":");return{type:ns.parse(e),key:n??""}}),U=a.z.object({type:ns,key:a.z.string()}).or(zu),jb={type:"builtin",key:"root"},Zt=(t=>(typeof t=="string"&&(t=zu.parse(t)),Array.isArray(t)?t.map(e=>Zt(e)):`${t.type}:${t.key}`)),Pb=(t,e)=>t.type===e.type&&t.key===e.key,Ou=t=>{const e=v.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:n})=>n):e.map(n=>U.parse(n))},ku=a.z.object({id:U,name:a.z.string(),data:Oe.unknownZ.optional().nullable()}).transform(t=>({key:Zt(t.id),...t})),$b=t=>t==="to"?"from":"to",_b=a.z.object({from:U,type:a.z.string(),to:U}).or(a.z.string().transform(t=>{const[e,n,r]=t.split("->");return{from:U.parse(e),type:n,to:U.parse(r)}})),Mb=t=>`${Zt(t.from)}->${t.type}->${Zt(t.to)}`,Rb="parent",Ub=(t,e)=>!(e.type!=null&&e.type!==t.type||e.from?.type!=null&&e.from.type!==t.from.type||e.to?.type!=null&&e.to.type!==t.to.type||e.from?.key!=null&&e.from.key!==t.from.key||e.to?.key!=null&&e.to.key!==t.to.key),Zb="sy_group_set",Lb="sy_group_delete",Db=a.object({group:ts}),Bb=a.object({parent:U,key:Vn.optional(),name:a.string()}),Fb=a.object({key:Vn,name:a.string()}),Yb=a.object({keys:a.array(Vn)}),qb="/ontology/create-group",Vb="/ontology/rename-group",Wb="/ontology/delete-group";let Eu=class{client;constructor(t){this.client=t}async create(t){return(await b(this.client,qb,t,Bb,Db)).group}async rename(t,e){await b(this.client,Vb,{key:t,name:e},Fb,a.object({}))}async delete(t){await b(this.client,Wb,{keys:v.toArray(t)},Yb,a.object({}))}};const Hb=Object.freeze(Object.defineProperty({__proto__:null,Client:Eu,DELETE_CHANNEL_NAME:Lb,SET_CHANNEL_NAME:Zb,groupZ:ts,keyZ:Vn,nameZ:Su,ontologyID:Cb},Symbol.toStringTag,{value:"Module"})),Gb="/ontology/add-children",Kb="/ontology/remove-children",Jb="/ontology/move-children",Zo=a.z.object({id:U,children:U.array()}),Xb=a.z.object({from:U,to:U,children:U.array()}),Ls=a.z.object({});let Qb=class{client;constructor(t){this.client=t}async addChildren(t,...e){await b(this.client,Gb,{id:t,children:e},Zo,Ls)}async removeChildren(t,...e){await b(this.client,Kb,{id:t,children:e},Zo,Ls)}async moveChildren(t,e,...n){await b(this.client,Jb,{from:t,to:e,children:n},Xb,Ls)}};const ev="/ontology/retrieve",tv=a.z.object({ids:U.array().optional(),children:a.z.boolean().optional(),parents:a.z.boolean().optional(),excludeFieldData:a.z.boolean().optional(),searchTerm:a.z.string().optional(),limit:a.z.number().optional(),offset:a.z.number().optional(),types:ns.array().optional()}),nv=a.z.object({resources:ku.array()});let Nu=class{type="ontology";groups;client;writer;framer;constructor(t,e){this.client=t,this.writer=new Qb(t),this.groups=new Eu(t),this.framer=e}async retrieve(t,e){if(!Array.isArray(t)&&typeof t=="object"&&!("key"in t))return this.execRetrieve(t);const n=Ou(t),r=await this.execRetrieve({ids:n,...e});if(Array.isArray(t))return r;if(r.length===0)throw new Qe(`No resource found with ID ${Ta.naturalLanguageJoin(n.map(s=>Zt(s)))}`);return r[0]}async retrieveChildren(t,e){return await this.execRetrieve({ids:v.toArray(t),children:!0,...e})}async retrieveParents(t,e){return await this.execRetrieve({ids:v.toArray(t),parents:!0,...e})}async addChildren(t,...e){return await this.writer.addChildren(t,...e)}async removeChildren(t,...e){return await this.writer.removeChildren(t,...e)}async moveChildren(t,e,...n){return await this.writer.moveChildren(t,e,...n)}async execRetrieve(t){const{resources:e}=await b(this.client,ev,t,tv,nv);return e}};const rv="sy_ontology_resource_set",sv="sy_ontology_resource_delete",av="sy_ontology_relationship_set",iv="sy_ontology_relationship_delete",ov=Object.freeze(Object.defineProperty({__proto__:null,Client:Nu,PARENT_OF_RELATIONSHIP_TYPE:Rb,RELATIONSHIP_DELETE_CHANNEL_NAME:iv,RELATIONSHIP_SET_CHANNEL_NAME:av,RESOURCE_DELETE_CHANNEL_NAME:sv,RESOURCE_SET_CHANNEL_NAME:rv,ROOT_ID:jb,idToString:Zt,idZ:U,idsEqual:Pb,matchRelationship:Ub,oppositeRelationshipDirection:$b,parseIDs:Ou,relationshipToString:Mb,relationshipZ:_b,resourceTypeZ:ns,resourceZ:ku},Symbol.toStringTag,{value:"Module"})),Wn=a.z.uuid(),Ni=a.z.object({key:Wn,subjects:v.nullableZ(U),objects:v.nullableZ(U),actions:v.nullableZ(Sa)}),cv=a.z.object({key:Wn.optional(),subjects:U.array().or(U),objects:U.array().or(U),actions:Sa.array().or(Sa)}),lv=a.z.object({keys:Wn.array().optional(),subjects:U.array().optional()}),uv=a.z.object({key:Wn}).transform(({key:t})=>({keys:[t]})),hv=a.z.union([a.z.object({for:U}).transform(({for:t})=>({subjects:[t]})),a.z.object({for:U.array()}).transform(({for:t})=>({subjects:t})),lv]),dv=a.z.union([uv,hv]),fv=a.z.object({policies:v.nullableZ(Ni)}),pv=a.z.object({policies:Ni.partial({key:!0}).array()}),yv=a.z.object({policies:Ni.array()}),mv=a.z.object({keys:Wn.array()}),gv=a.z.object({}),wv="/access/policy/retrieve",bv="/access/policy/create",vv="/access/policy/delete";let Tv=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=cv.array().parse(v.toArray(t)).map(s=>({objects:v.toArray(s.objects),actions:v.toArray(s.actions),subjects:v.toArray(s.subjects)})),r=await b(this.client,bv,{policies:n},pv,yv);return e?r.policies:r.policies[0]}async retrieve(t){const e="key"in t,n=await b(this.client,wv,t,dv,fv);return e?n.policies[0]:n.policies}async delete(t){await b(this.client,vv,{keys:v.toArray(t)},mv,gv)}},Sv=class{policy;constructor(t){this.policy=new Tv(t)}};function y(t,e,n){function r(c,l){var u;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(u=c._zod).traits??(u.traits=new Set),c._zod.traits.add(t),e(c,l);for(const h in o.prototype)h in c||Object.defineProperty(c,h,{value:o.prototype[h].bind(c)});c._zod.constr=o,c._zod.def=l}const s=n?.Parent??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function o(c){var l;const u=n?.Parent?new i:this;r(u,c),(l=u._zod).deferred??(l.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Mt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class xu extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Au={};function mt(t){return Au}function zv(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,r])=>e.indexOf(+n)===-1).map(([n,r])=>r)}function Ea(t,e){return typeof e=="bigint"?e.toString():e}function xi(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ai(t){return t==null}function Ii(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Ov(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let s=(r.split(".")[1]||"").length;if(s===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(s=Number.parseInt(l[1]))}const i=n>s?n:s,o=Number.parseInt(t.toFixed(i).replace(".","")),c=Number.parseInt(e.toFixed(i).replace(".",""));return o%c/10**i}const Lo=Symbol("evaluating");function B(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Lo)return r===void 0&&(r=Lo,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function kv(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function et(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function sn(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Do(t){return JSON.stringify(t)}const Iu="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Ar(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Ev=xi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Cn(t){if(Ar(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(Ar(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Cu(t){return Cn(t)?{...t}:Array.isArray(t)?[...t]:t}const Nv=new Set(["string","number","symbol"]);function rs(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tt(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function N(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function xv(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Av={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Iv(t,e){const n=t._zod.def,r=sn(t._zod.def,{get shape(){const s={};for(const i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(s[i]=n.shape[i])}return et(this,"shape",s),s},checks:[]});return tt(t,r)}function Cv(t,e){const n=t._zod.def,r=sn(t._zod.def,{get shape(){const s={...t._zod.def.shape};for(const i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete s[i]}return et(this,"shape",s),s},checks:[]});return tt(t,r)}function jv(t,e){if(!Cn(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=sn(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return et(this,"shape",s),s},checks:[]});return tt(t,r)}function Pv(t,e){if(!Cn(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return et(this,"shape",r),r},checks:t._zod.def.checks};return tt(t,n)}function $v(t,e){const n=sn(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return et(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return tt(t,n)}function _v(t,e,n){const r=sn(e._zod.def,{get shape(){const s=e._zod.def.shape,i={...s};if(n)for(const o in n){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(i[o]=t?new t({type:"optional",innerType:s[o]}):s[o])}else for(const o in s)i[o]=t?new t({type:"optional",innerType:s[o]}):s[o];return et(this,"shape",i),i},checks:[]});return tt(e,r)}function Mv(t,e,n){const r=sn(e._zod.def,{get shape(){const s=e._zod.def.shape,i={...s};if(n)for(const o in n){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(i[o]=new t({type:"nonoptional",innerType:s[o]}))}else for(const o in s)i[o]=new t({type:"nonoptional",innerType:s[o]});return et(this,"shape",i),i},checks:[]});return tt(e,r)}function jt(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ju(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function hr(t){return typeof t=="string"?t:t?.message}function gt(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=hr(t.inst?._zod.def?.error?.(t))??hr(e?.error?.(t))??hr(n.customError?.(t))??hr(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Ci(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function jn(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Pu=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Ea,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},$u=y("$ZodError",Pu),_u=y("$ZodError",Pu,{Parent:Error});function Rv(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function Uv(t,e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(c=>s({issues:c}));else if(o.code==="invalid_key")s({issues:o.issues});else if(o.code==="invalid_element")s({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let c=r,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(o))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return s(t),r}const ji=t=>(e,n,r,s)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Mt;if(o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>gt(l,i,mt())));throw Iu(c,s?.callee),c}return o.value},Pi=t=>async(e,n,r,s)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>gt(l,i,mt())));throw Iu(c,s?.callee),c}return o.value},ss=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Mt;return i.issues.length?{success:!1,error:new(t??$u)(i.issues.map(o=>gt(o,s,mt())))}:{success:!0,data:i.value}},Zv=ss(_u),as=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:n,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(o=>gt(o,s,mt())))}:{success:!0,data:i.value}},Lv=as(_u),Dv=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ji(t)(e,n,s)},Bv=t=>(e,n,r)=>ji(t)(e,n,r),Fv=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Pi(t)(e,n,s)},Yv=t=>async(e,n,r)=>Pi(t)(e,n,r),qv=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ss(t)(e,n,s)},Vv=t=>(e,n,r)=>ss(t)(e,n,r),Wv=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return as(t)(e,n,s)},Hv=t=>async(e,n,r)=>as(t)(e,n,r),Gv=/^[cC][^\s-]{8,}$/,Kv=/^[0-9a-z]+$/,Jv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xv=/^[0-9a-vA-V]{20}$/,Qv=/^[A-Za-z0-9]{27}$/,eT=/^[a-zA-Z0-9_-]{21}$/,tT=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,nT=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Bo=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,rT=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function aT(){return new RegExp(sT,"u")}const iT=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oT=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cT=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lT=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uT=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mu=/^[A-Za-z0-9_-]*$/,hT=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,dT=/^\+(?:[0-9]){6,14}[0-9]$/,Ru="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",fT=new RegExp(`^${Ru}$`);function Uu(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function pT(t){return new RegExp(`^${Uu(t)}$`)}function yT(t){const e=Uu({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Ru}T(?:${r})$`)}const mT=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},gT=/^-?\d+$/,wT=/^-?\d+(?:\.\d+)?/,bT=/^(?:true|false)$/i,vT=/^[^A-Z]*$/,TT=/^[^a-z]*$/,oe=y("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Zu={number:"number",bigint:"bigint",object:"date"},Lu=y("$ZodCheckLessThan",(t,e)=>{oe.init(t,e);const n=Zu[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,i=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Du=y("$ZodCheckGreaterThan",(t,e)=>{oe.init(t,e);const n=Zu[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,i=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ST=y("$ZodCheckMultipleOf",(t,e)=>{oe.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Ov(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),zT=y("$ZodCheckNumberFormat",(t,e)=>{oe.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,i]=Av[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=i,n&&(c.pattern=gT)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>i&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:t})}}),OT=y("$ZodCheckMaxLength",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ai(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const i=Ci(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),kT=y("$ZodCheckMinLength",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ai(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const i=Ci(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),ET=y("$ZodCheckLengthEquals",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ai(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,i=s.length;if(i===e.length)return;const o=Ci(s),c=i>e.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),is=y("$ZodCheckStringFormat",(t,e)=>{var n,r;oe.init(t,e),t._zod.onattach.push(s=>{const i=s._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),NT=y("$ZodCheckRegex",(t,e)=>{is.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),xT=y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=vT),is.init(t,e)}),AT=y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=TT),is.init(t,e)}),IT=y("$ZodCheckIncludes",(t,e)=>{oe.init(t,e);const n=rs(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),CT=y("$ZodCheckStartsWith",(t,e)=>{oe.init(t,e);const n=new RegExp(`^${rs(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),jT=y("$ZodCheckEndsWith",(t,e)=>{oe.init(t,e);const n=new RegExp(`.*${rs(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),PT=y("$ZodCheckOverwrite",(t,e)=>{oe.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class $T{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(`
|
|
22
|
-
`).filter(i=>i),r=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const e=Function,n=this?.args,r=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,r.join(`
|
|
23
|
-
`))}}const _T={major:4,minor:1,patch:8},H=y("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=_T;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const i of s._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,c,l)=>{let u=jt(o),h;for(const p of c){if(p._zod.def.when){if(!p._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,O=p._zod.check(o);if(O instanceof Promise&&l?.async===!1)throw new Mt;if(h||O instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await O,o.issues.length!==f&&(u||(u=jt(o,f)))});else{if(o.issues.length===f)continue;u||(u=jt(o,f))}}return h?h.then(()=>o):o},i=(o,c,l)=>{if(jt(o))return o.aborted=!0,o;const u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Mt;return u.then(h=>t._zod.parse(h,l))}return t._zod.parse(u,l)};t._zod.run=(o,c)=>{if(c.skipChecks)return t._zod.parse(o,c);if(c.direction==="backward"){const u=t._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>i(h,o,c)):i(u,o,c)}const l=t._zod.parse(o,c);if(l instanceof Promise){if(c.async===!1)throw new Mt;return l.then(u=>s(u,r,c))}return s(l,r,c)}}t["~standard"]={validate:s=>{try{const i=Zv(t,s);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Lv(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),$i=y("$ZodString",(t,e)=>{H.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??mT(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Y=y("$ZodStringFormat",(t,e)=>{is.init(t,e),$i.init(t,e)}),MT=y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=nT),Y.init(t,e)}),RT=y("$ZodUUID",(t,e)=>{if(e.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Bo(n))}else e.pattern??(e.pattern=Bo());Y.init(t,e)}),UT=y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=rT),Y.init(t,e)}),ZT=y("$ZodURL",(t,e)=>{Y.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:hT.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=s.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),LT=y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=aT()),Y.init(t,e)}),DT=y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=eT),Y.init(t,e)}),BT=y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Gv),Y.init(t,e)}),FT=y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Kv),Y.init(t,e)}),YT=y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Jv),Y.init(t,e)}),qT=y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Xv),Y.init(t,e)}),VT=y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Qv),Y.init(t,e)}),WT=y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=yT(e)),Y.init(t,e)}),HT=y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=fT),Y.init(t,e)}),GT=y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=pT(e)),Y.init(t,e)}),KT=y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=tT),Y.init(t,e)}),JT=y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=iT),Y.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),XT=y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=oT),Y.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),QT=y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=cT),Y.init(t,e)}),eS=y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=lT),Y.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[s,i]=r;if(!i)throw new Error;const o=Number(i);if(`${o}`!==i)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Bu(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const tS=y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=uT),Y.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Bu(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function nS(t){if(!Mu.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Bu(n)}const rS=y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Mu),Y.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{nS(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),sS=y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=dT),Y.init(t,e)});function aS(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const iS=y("$ZodJWT",(t,e)=>{Y.init(t,e),t._zod.check=n=>{aS(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Fu=y("$ZodNumber",(t,e)=>{H.init(t,e),t._zod.pattern=t._zod.bag.pattern??wT,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const i=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...i?{received:i}:{}}),n}}),oS=y("$ZodNumber",(t,e)=>{zT.init(t,e),Fu.init(t,e)}),cS=y("$ZodBoolean",(t,e)=>{H.init(t,e),t._zod.pattern=bT,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),lS=y("$ZodUnknown",(t,e)=>{H.init(t,e),t._zod.parse=n=>n}),uS=y("$ZodNever",(t,e)=>{H.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Fo(t,e,n){t.issues.length&&e.issues.push(...ju(n,t.issues)),e.value[n]=t.value}const hS=y("$ZodArray",(t,e)=>{H.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const i=[];for(let o=0;o<s.length;o++){const c=s[o],l=e.element._zod.run({value:c,issues:[]},r);l instanceof Promise?i.push(l.then(u=>Fo(u,n,o))):Fo(l,n,o)}return i.length?Promise.all(i).then(()=>n):n}});function Ir(t,e,n,r){t.issues.length&&e.issues.push(...ju(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Yu(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=xv(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function qu(t,e,n,r,s,i){const o=[],c=s.keySet,l=s.catchall._zod,u=l.def.type;for(const h of Object.keys(e)){if(c.has(h))continue;if(u==="never"){o.push(h);continue}const p=l.run({value:e[h],issues:[]},r);p instanceof Promise?t.push(p.then(f=>Ir(f,n,h,e))):Ir(p,n,h,e)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:i}),t.length?Promise.all(t).then(()=>n):n}const dS=y("$ZodObject",(t,e)=>{H.init(t,e);const n=xi(()=>Yu(e));B(t._zod,"propValues",()=>{const o=e.shape,c={};for(const l in o){const u=o[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(const h of u.values)c[l].add(h)}}return c});const r=Ar,s=e.catchall;let i;t._zod.parse=(o,c)=>{i??(i=n.value);const l=o.value;if(!r(l))return o.issues.push({expected:"object",code:"invalid_type",input:l,inst:t}),o;o.value={};const u=[],h=i.shape;for(const p of i.keys){const f=h[p]._zod.run({value:l[p],issues:[]},c);f instanceof Promise?u.push(f.then(O=>Ir(O,o,p,l))):Ir(f,o,p,l)}return s?qu(u,l,o,c,n.value,t):u.length?Promise.all(u).then(()=>o):o}}),fS=y("$ZodObjectJIT",(t,e)=>{dS.init(t,e);const n=t._zod.parse,r=xi(()=>Yu(e)),s=p=>{const f=new $T(["shape","payload","ctx"]),O=r.value,I=A=>{const W=Do(A);return`shape[${W}]._zod.run({ value: input[${W}], issues: [] }, ctx)`};f.write("const input = payload.value;");const j=Object.create(null);let w=0;for(const A of O.keys)j[A]=`key_${w++}`;f.write("const newResult = {};");for(const A of O.keys){const W=j[A],J=Do(A);f.write(`const ${W} = ${I(A)};`),f.write(`
|
|
24
|
-
if (${W}.issues.length) {
|
|
25
|
-
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
|
|
26
|
-
...iss,
|
|
27
|
-
path: iss.path ? [${J}, ...iss.path] : [${J}]
|
|
28
|
-
})));
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
if (${W}.value === undefined) {
|
|
33
|
-
if (${J} in input) {
|
|
34
|
-
newResult[${J}] = undefined;
|
|
35
|
-
}
|
|
36
|
-
} else {
|
|
37
|
-
newResult[${J}] = ${W}.value;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
`)}f.write("payload.value = newResult;"),f.write("return payload;");const T=f.compile();return(A,W)=>T(p,A,W)};let i;const o=Ar,c=!Au.jitless,l=c&&Ev.value,u=e.catchall;let h;t._zod.parse=(p,f)=>{h??(h=r.value);const O=p.value;return o(O)?c&&l&&f?.async===!1&&f.jitless!==!0?(i||(i=s(e.shape)),p=i(p,f),u?qu([],O,p,f,h,t):p):n(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),p)}});function Yo(t,e,n,r){for(const i of t)if(i.issues.length===0)return e.value=i.value,e;const s=t.filter(i=>!jt(i));return s.length===1?(e.value=s[0].value,s[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(i=>i.issues.map(o=>gt(o,r,mt())))}),e)}const pS=y("$ZodUnion",(t,e)=>{H.init(t,e),B(t._zod,"optin",()=>e.options.some(s=>s._zod.optin==="optional")?"optional":void 0),B(t._zod,"optout",()=>e.options.some(s=>s._zod.optout==="optional")?"optional":void 0),B(t._zod,"values",()=>{if(e.options.every(s=>s._zod.values))return new Set(e.options.flatMap(s=>Array.from(s._zod.values)))}),B(t._zod,"pattern",()=>{if(e.options.every(s=>s._zod.pattern)){const s=e.options.map(i=>i._zod.pattern);return new RegExp(`^(${s.map(i=>Ii(i.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(s,i)=>{if(n)return r(s,i);let o=!1;const c=[];for(const l of e.options){const u=l._zod.run({value:s.value,issues:[]},i);if(u instanceof Promise)c.push(u),o=!0;else{if(u.issues.length===0)return u;c.push(u)}}return o?Promise.all(c).then(l=>Yo(l,s,t,i)):Yo(c,s,t,i)}}),yS=y("$ZodIntersection",(t,e)=>{H.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,i=e.left._zod.run({value:s,issues:[]},r),o=e.right._zod.run({value:s,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([c,l])=>qo(n,c,l)):qo(n,i,o)}});function Na(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Cn(t)&&Cn(e)){const n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),s={...t,...e};for(const i of r){const o=Na(t[i],e[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};s[i]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const s=t[r],i=e[r],o=Na(s,i);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function qo(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),jt(t))return t;const r=Na(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const mS=y("$ZodEnum",(t,e)=>{H.init(t,e);const n=zv(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>Nv.has(typeof s)).map(s=>typeof s=="string"?rs(s):s.toString()).join("|")})$`),t._zod.parse=(s,i)=>{const o=s.value;return r.has(o)||s.issues.push({code:"invalid_value",values:n,input:o,inst:t}),s}}),gS=y("$ZodTransform",(t,e)=>{H.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xu(t.constructor.name);const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(n.value=i,n));if(s instanceof Promise)throw new Mt;return n.value=s,n}});function Vo(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const wS=y("$ZodOptional",(t,e)=>{H.init(t,e),t._zod.optin="optional",t._zod.optout="optional",B(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),B(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ii(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>Vo(i,n.value)):Vo(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),bS=y("$ZodNullable",(t,e)=>{H.init(t,e),B(t._zod,"optin",()=>e.innerType._zod.optin),B(t._zod,"optout",()=>e.innerType._zod.optout),B(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ii(n.source)}|null)$`):void 0}),B(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),vS=y("$ZodDefault",(t,e)=>{H.init(t,e),t._zod.optin="optional",B(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>Wo(i,e)):Wo(s,e)}});function Wo(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const TS=y("$ZodPrefault",(t,e)=>{H.init(t,e),t._zod.optin="optional",B(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),SS=y("$ZodNonOptional",(t,e)=>{H.init(t,e),B(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>Ho(i,t)):Ho(s,t)}});function Ho(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const zS=y("$ZodCatch",(t,e)=>{H.init(t,e),B(t._zod,"optin",()=>e.innerType._zod.optin),B(t._zod,"optout",()=>e.innerType._zod.optout),B(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(o=>gt(o,r,mt()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>gt(i,r,mt()))},input:n.value}),n.issues=[]),n)}}),OS=y("$ZodPipe",(t,e)=>{H.init(t,e),B(t._zod,"values",()=>e.in._zod.values),B(t._zod,"optin",()=>e.in._zod.optin),B(t._zod,"optout",()=>e.out._zod.optout),B(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const i=e.out._zod.run(n,r);return i instanceof Promise?i.then(o=>dr(o,e.in,r)):dr(i,e.in,r)}const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(i=>dr(i,e.out,r)):dr(s,e.out,r)}});function dr(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const kS=y("$ZodReadonly",(t,e)=>{H.init(t,e),B(t._zod,"propValues",()=>e.innerType._zod.propValues),B(t._zod,"values",()=>e.innerType._zod.values),B(t._zod,"optin",()=>e.innerType._zod.optin),B(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(Go):Go(s)}});function Go(t){return t.value=Object.freeze(t.value),t}const ES=y("$ZodCustom",(t,e)=>{oe.init(t,e),H.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(i=>Ko(i,n,r,t));Ko(s,n,r,t)}});function Ko(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(jn(s))}}class NS{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const s={...r,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function xS(){return new NS}const fr=xS();function AS(t,e){return new t({type:"string",...N(e)})}function IS(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function Jo(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function Vu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function CS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function jS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function PS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function $S(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function _S(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function MS(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function RS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function US(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function ZS(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function LS(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function DS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function BS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function FS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function YS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function qS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function VS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function WS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function HS(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function GS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}function KS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function JS(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function XS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function QS(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function ez(t,e){return new t({type:"number",checks:[],...N(e)})}function tz(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function nz(t,e){return new t({type:"boolean",...N(e)})}function rz(t){return new t({type:"unknown"})}function sz(t,e){return new t({type:"never",...N(e)})}function Xo(t,e){return new Lu({check:"less_than",...N(e),value:t,inclusive:!1})}function Ds(t,e){return new Lu({check:"less_than",...N(e),value:t,inclusive:!0})}function Qo(t,e){return new Du({check:"greater_than",...N(e),value:t,inclusive:!1})}function Bs(t,e){return new Du({check:"greater_than",...N(e),value:t,inclusive:!0})}function ec(t,e){return new ST({check:"multiple_of",...N(e),value:t})}function Wu(t,e){return new OT({check:"max_length",...N(e),maximum:t})}function Cr(t,e){return new kT({check:"min_length",...N(e),minimum:t})}function Hu(t,e){return new ET({check:"length_equals",...N(e),length:t})}function az(t,e){return new NT({check:"string_format",format:"regex",...N(e),pattern:t})}function iz(t){return new xT({check:"string_format",format:"lowercase",...N(t)})}function oz(t){return new AT({check:"string_format",format:"uppercase",...N(t)})}function cz(t,e){return new IT({check:"string_format",format:"includes",...N(e),includes:t})}function lz(t,e){return new CT({check:"string_format",format:"starts_with",...N(e),prefix:t})}function uz(t,e){return new jT({check:"string_format",format:"ends_with",...N(e),suffix:t})}function Hn(t){return new PT({check:"overwrite",tx:t})}function hz(t){return Hn(e=>e.normalize(t))}function dz(){return Hn(t=>t.trim())}function fz(){return Hn(t=>t.toLowerCase())}function pz(){return Hn(t=>t.toUpperCase())}function yz(t,e,n){return new t({type:"array",element:e,...N(n)})}function mz(t,e,n){return new t({type:"custom",check:"custom",fn:e,...N(n)})}function gz(t){const e=wz(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(jn(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(jn(s))}},t(n.value,n)));return e}function wz(t,e){const n=new oe({check:"custom",...N(e)});return n._zod.check=t,n}const bz=y("ZodISODateTime",(t,e)=>{WT.init(t,e),V.init(t,e)});function vz(t){return KS(bz,t)}const Tz=y("ZodISODate",(t,e)=>{HT.init(t,e),V.init(t,e)});function Sz(t){return JS(Tz,t)}const zz=y("ZodISOTime",(t,e)=>{GT.init(t,e),V.init(t,e)});function Oz(t){return XS(zz,t)}const kz=y("ZodISODuration",(t,e)=>{KT.init(t,e),V.init(t,e)});function Ez(t){return QS(kz,t)}const Nz=(t,e)=>{$u.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Uv(t,n)},flatten:{value:n=>Rv(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Ea,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Ea,2)}},isEmpty:{get(){return t.issues.length===0}}})},we=y("ZodError",Nz,{Parent:Error}),xz=ji(we),Az=Pi(we),Iz=ss(we),Cz=as(we),jz=Dv(we),Pz=Bv(we),$z=Fv(we),_z=Yv(we),Mz=qv(we),Rz=Vv(we),Uz=Wv(we),Zz=Hv(we),G=y("ZodType",(t,e)=>(H.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>tt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>xz(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Iz(t,n,r),t.parseAsync=async(n,r)=>Az(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Cz(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>jz(t,n,r),t.decode=(n,r)=>Pz(t,n,r),t.encodeAsync=async(n,r)=>$z(t,n,r),t.decodeAsync=async(n,r)=>_z(t,n,r),t.safeEncode=(n,r)=>Mz(t,n,r),t.safeDecode=(n,r)=>Rz(t,n,r),t.safeEncodeAsync=async(n,r)=>Uz(t,n,r),t.safeDecodeAsync=async(n,r)=>Zz(t,n,r),t.refine=(n,r)=>t.check(CO(n,r)),t.superRefine=n=>t.check(jO(n)),t.overwrite=n=>t.check(Hn(n)),t.optional=()=>ac(t),t.nullable=()=>ic(t),t.nullish=()=>ac(ic(t)),t.nonoptional=n=>OO(t,n),t.array=()=>hO(t),t.or=n=>_i([t,n]),t.and=n=>yO(t,n),t.transform=n=>oc(t,wO(n)),t.default=n=>TO(t,n),t.prefault=n=>zO(t,n),t.catch=n=>EO(t,n),t.pipe=n=>oc(t,n),t.readonly=()=>AO(t),t.describe=n=>{const r=t.clone();return fr.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return fr.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return fr.get(t);const r=t.clone();return fr.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Gu=y("_ZodString",(t,e)=>{$i.init(t,e),G.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(az(...r)),t.includes=(...r)=>t.check(cz(...r)),t.startsWith=(...r)=>t.check(lz(...r)),t.endsWith=(...r)=>t.check(uz(...r)),t.min=(...r)=>t.check(Cr(...r)),t.max=(...r)=>t.check(Wu(...r)),t.length=(...r)=>t.check(Hu(...r)),t.nonempty=(...r)=>t.check(Cr(1,...r)),t.lowercase=r=>t.check(iz(r)),t.uppercase=r=>t.check(oz(r)),t.trim=()=>t.check(dz()),t.normalize=(...r)=>t.check(hz(...r)),t.toLowerCase=()=>t.check(fz()),t.toUpperCase=()=>t.check(pz())}),Lz=y("ZodString",(t,e)=>{$i.init(t,e),Gu.init(t,e),t.email=n=>t.check(IS(Dz,n)),t.url=n=>t.check($S(Fz,n)),t.jwt=n=>t.check(GS(sO,n)),t.emoji=n=>t.check(_S(Yz,n)),t.guid=n=>t.check(Jo(tc,n)),t.uuid=n=>t.check(Vu(Tn,n)),t.uuidv4=n=>t.check(CS(Tn,n)),t.uuidv6=n=>t.check(jS(Tn,n)),t.uuidv7=n=>t.check(PS(Tn,n)),t.nanoid=n=>t.check(MS(qz,n)),t.guid=n=>t.check(Jo(tc,n)),t.cuid=n=>t.check(RS(Vz,n)),t.cuid2=n=>t.check(US(Wz,n)),t.ulid=n=>t.check(ZS(Hz,n)),t.base64=n=>t.check(VS(tO,n)),t.base64url=n=>t.check(WS(nO,n)),t.xid=n=>t.check(LS(Gz,n)),t.ksuid=n=>t.check(DS(Kz,n)),t.ipv4=n=>t.check(BS(Jz,n)),t.ipv6=n=>t.check(FS(Xz,n)),t.cidrv4=n=>t.check(YS(Qz,n)),t.cidrv6=n=>t.check(qS(eO,n)),t.e164=n=>t.check(HS(rO,n)),t.datetime=n=>t.check(vz(n)),t.date=n=>t.check(Sz(n)),t.time=n=>t.check(Oz(n)),t.duration=n=>t.check(Ez(n))});function ge(t){return AS(Lz,t)}const V=y("ZodStringFormat",(t,e)=>{Y.init(t,e),Gu.init(t,e)}),Dz=y("ZodEmail",(t,e)=>{UT.init(t,e),V.init(t,e)}),tc=y("ZodGUID",(t,e)=>{MT.init(t,e),V.init(t,e)}),Tn=y("ZodUUID",(t,e)=>{RT.init(t,e),V.init(t,e)});function Bz(t){return Vu(Tn,t)}const Fz=y("ZodURL",(t,e)=>{ZT.init(t,e),V.init(t,e)}),Yz=y("ZodEmoji",(t,e)=>{LT.init(t,e),V.init(t,e)}),qz=y("ZodNanoID",(t,e)=>{DT.init(t,e),V.init(t,e)}),Vz=y("ZodCUID",(t,e)=>{BT.init(t,e),V.init(t,e)}),Wz=y("ZodCUID2",(t,e)=>{FT.init(t,e),V.init(t,e)}),Hz=y("ZodULID",(t,e)=>{YT.init(t,e),V.init(t,e)}),Gz=y("ZodXID",(t,e)=>{qT.init(t,e),V.init(t,e)}),Kz=y("ZodKSUID",(t,e)=>{VT.init(t,e),V.init(t,e)}),Jz=y("ZodIPv4",(t,e)=>{JT.init(t,e),V.init(t,e)}),Xz=y("ZodIPv6",(t,e)=>{XT.init(t,e),V.init(t,e)}),Qz=y("ZodCIDRv4",(t,e)=>{QT.init(t,e),V.init(t,e)}),eO=y("ZodCIDRv6",(t,e)=>{eS.init(t,e),V.init(t,e)}),tO=y("ZodBase64",(t,e)=>{tS.init(t,e),V.init(t,e)}),nO=y("ZodBase64URL",(t,e)=>{rS.init(t,e),V.init(t,e)}),rO=y("ZodE164",(t,e)=>{sS.init(t,e),V.init(t,e)}),sO=y("ZodJWT",(t,e)=>{iS.init(t,e),V.init(t,e)}),Ku=y("ZodNumber",(t,e)=>{Fu.init(t,e),G.init(t,e),t.gt=(r,s)=>t.check(Qo(r,s)),t.gte=(r,s)=>t.check(Bs(r,s)),t.min=(r,s)=>t.check(Bs(r,s)),t.lt=(r,s)=>t.check(Xo(r,s)),t.lte=(r,s)=>t.check(Ds(r,s)),t.max=(r,s)=>t.check(Ds(r,s)),t.int=r=>t.check(rc(r)),t.safe=r=>t.check(rc(r)),t.positive=r=>t.check(Qo(0,r)),t.nonnegative=r=>t.check(Bs(0,r)),t.negative=r=>t.check(Xo(0,r)),t.nonpositive=r=>t.check(Ds(0,r)),t.multipleOf=(r,s)=>t.check(ec(r,s)),t.step=(r,s)=>t.check(ec(r,s)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function nc(t){return ez(Ku,t)}const aO=y("ZodNumberFormat",(t,e)=>{oS.init(t,e),Ku.init(t,e)});function rc(t){return tz(aO,t)}const iO=y("ZodBoolean",(t,e)=>{cS.init(t,e),G.init(t,e)});function os(t){return nz(iO,t)}const oO=y("ZodUnknown",(t,e)=>{lS.init(t,e),G.init(t,e)});function sc(){return rz(oO)}const cO=y("ZodNever",(t,e)=>{uS.init(t,e),G.init(t,e)});function lO(t){return sz(cO,t)}const uO=y("ZodArray",(t,e)=>{hS.init(t,e),G.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Cr(n,r)),t.nonempty=n=>t.check(Cr(1,n)),t.max=(n,r)=>t.check(Wu(n,r)),t.length=(n,r)=>t.check(Hu(n,r)),t.unwrap=()=>t.element});function hO(t,e){return yz(uO,t,e)}const dO=y("ZodObject",(t,e)=>{fS.init(t,e),G.init(t,e),B(t,"shape",()=>e.shape),t.keyof=()=>mO(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:sc()}),t.loose=()=>t.clone({...t._zod.def,catchall:sc()}),t.strict=()=>t.clone({...t._zod.def,catchall:lO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>jv(t,n),t.safeExtend=n=>Pv(t,n),t.merge=n=>$v(t,n),t.pick=n=>Iv(t,n),t.omit=n=>Cv(t,n),t.partial=(...n)=>_v(Ju,t,n[0]),t.required=(...n)=>Mv(Xu,t,n[0])});function ie(t,e){const n={type:"object",get shape(){return et(this,"shape",t?kv(t):{}),this.shape},...N(e)};return new dO(n)}const fO=y("ZodUnion",(t,e)=>{pS.init(t,e),G.init(t,e),t.options=e.options});function _i(t,e){return new fO({type:"union",options:t,...N(e)})}const pO=y("ZodIntersection",(t,e)=>{yS.init(t,e),G.init(t,e)});function yO(t,e){return new pO({type:"intersection",left:t,right:e})}const xa=y("ZodEnum",(t,e)=>{mS.init(t,e),G.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const i={};for(const o of r)if(n.has(o))i[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new xa({...e,checks:[],...N(s),entries:i})},t.exclude=(r,s)=>{const i={...e.entries};for(const o of r)if(n.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new xa({...e,checks:[],...N(s),entries:i})}});function mO(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new xa({type:"enum",entries:n,...N(e)})}const gO=y("ZodTransform",(t,e)=>{gS.init(t,e),G.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xu(t.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(jn(i,n.value,e));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),n.issues.push(jn(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(i=>(n.value=i,n)):(n.value=s,n)}});function wO(t){return new gO({type:"transform",transform:t})}const Ju=y("ZodOptional",(t,e)=>{wS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ac(t){return new Ju({type:"optional",innerType:t})}const bO=y("ZodNullable",(t,e)=>{bS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ic(t){return new bO({type:"nullable",innerType:t})}const vO=y("ZodDefault",(t,e)=>{vS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function TO(t,e){return new vO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Cu(e)}})}const SO=y("ZodPrefault",(t,e)=>{TS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function zO(t,e){return new SO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Cu(e)}})}const Xu=y("ZodNonOptional",(t,e)=>{SS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function OO(t,e){return new Xu({type:"nonoptional",innerType:t,...N(e)})}const kO=y("ZodCatch",(t,e)=>{zS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function EO(t,e){return new kO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const NO=y("ZodPipe",(t,e)=>{OS.init(t,e),G.init(t,e),t.in=e.in,t.out=e.out});function oc(t,e){return new NO({type:"pipe",in:t,out:e})}const xO=y("ZodReadonly",(t,e)=>{kS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function AO(t){return new xO({type:"readonly",innerType:t})}const IO=y("ZodCustom",(t,e)=>{ES.init(t,e),G.init(t,e)});function CO(t,e={}){return mz(IO,t,e)}function jO(t){return gz(t)}const Pe=t=>t?JSON.parse(t):{},Mi=ie({key:ge(),type:ge(),config:Oe.unknownZ.or(ge().transform(Pe)),source:ge().optional()}),Qu=Mi.extend({position:vi.xy}),Aa=ie({param:ge(),node:ge()}),Ri=ie({source:Aa,target:Aa}),PO=ie({nodes:Mi.array(),edges:Ri.array()}),eh=ie({nodes:Qu.array(),edges:Ri.array()}),th=ie({raw:ge()}),Gn=Bz(),cs=ie({key:Gn,name:ge(),graph:eh,text:th,deploy:os(),version:ge()}),nh=cs.partial({key:!0}),rh="arc",$O=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=v.toArray(t);const i=s[0],o=typeof i;let c;return o==="string"&&n&&!isNaN(parseInt(i))&&"number"in e?(c=e.number,s=s.map(l=>parseInt(l))):c=e[o],{single:r,variant:c,normalized:s,actual:t}},ue=(t,e,n,r)=>{if(r){if(n.length===0)throw new Ue(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new xr(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},_O="/arc/retrieve",MO="/arc/create",RO="/arc/delete",UO=ie({keys:Gn.array().optional(),names:ge().array().optional(),searchTerm:ge().optional(),limit:nc().optional(),offset:nc().optional(),includeStatus:os().optional()}),ZO=ie({arcs:nh.array()}),LO=ie({keys:Gn.array()}),DO=ie({arcs:v.nullableZ(cs)}),BO=ie({arcs:cs.array()}),FO=ie({}),YO=ie({key:Gn,includeStatus:os().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),qO=ie({name:ge(),includeStatus:os().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),sh=_i([YO,qO]),VO=_i([sh,UO]);let ah=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=await b(this.client,MO,{arcs:v.toArray(t)},ZO,BO);return e?n.arcs:n.arcs[0]}async retrieve(t){const e="key"in t||"name"in t,n=await b(this.client,_O,t,VO,DO);return ue("Arc",t,n.arcs,e),e?n.arcs[0]:n.arcs}async delete(t){await b(this.client,RO,{keys:v.toArray(t)},LO,FO)}};const WO=t=>({type:rh,key:t}),HO=Object.freeze(Object.defineProperty({__proto__:null,Client:ah,ONTOLOGY_TYPE:rh,arcZ:cs,edgeZ:Ri,graphNodeZ:Qu,graphZ:eh,handleZ:Aa,irNodeZ:Mi,irZ:PO,keyZ:Gn,newZ:nh,ontologyID:WO,singleRetrieveArgsZ:sh,textZ:th},Symbol.toStringTag,{value:"Module"})),cc="Channel key must be a valid uint32.",L=a.z.uint32().or(a.z.string().refine(t=>!isNaN(Number(t)),{message:cc}).transform(Number).refine(t=>t<ga.MAX_UINT32,{message:cc})),Me=a.z.string(),ih=rn.statusZ(),an=a.z.object({name:Me,key:L,dataType:M.z,leaseholder:a.z.number(),index:L,isIndex:a.z.boolean(),internal:a.z.boolean(),virtual:a.z.boolean(),alias:a.z.string().optional(),expression:a.z.string().default(""),requires:v.nullableZ(L),status:ih.optional()}),oh=an.extend({key:L.optional(),leaseholder:a.z.number().optional(),index:L.optional(),isIndex:a.z.boolean().optional(),internal:a.z.boolean().optional().default(!1),virtual:a.z.boolean().optional().default(!1),expression:a.z.string().optional().default(""),requires:v.nullableZ(L).optional().default([])}),bt=a.z.union([zn.toArray(L),zn.toArray(Me),zn.toArray(an).transform(t=>t.map(e=>e.key))]),GO=new Error("request for lock canceled");var KO=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function c(h){try{u(r.next(h))}catch(p){o(p)}}function l(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class JO{constructor(e,n=GO){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,s)=>{const i={resolve:r,reject:s,weight:e,priority:n},o=ch(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return KO(this,arguments,void 0,function*(n,r=1,s=0){const[i,o]=yield this.acquire(r,s);try{return yield n(i)}finally{o()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),XO(this._weightedWaiters[e-1],{resolve:r,priority:n})})}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 n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let n=this._value;n>0;n--){const r=this._weightedWaiters[n-1];if(!r)continue;const s=r.findIndex(i=>i.priority<=e);(s===-1?r:r.splice(0,s)).forEach((i=>i.resolve()))}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}}function XO(t,e){const n=ch(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function ch(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var QO=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function c(h){try{u(r.next(h))}catch(p){o(p)}}function l(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class ek{constructor(e){this._semaphore=new JO(1,e)}acquire(){return QO(this,arguments,void 0,function*(e=0){const[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}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 tk=a.z.object({leaseholder:a.z.number().optional(),keys:L.array().optional(),names:a.z.string().array().optional(),searchTerm:a.z.string().optional(),rangeKey:a.z.string().optional(),limit:a.z.number().optional(),offset:a.z.number().optional(),dataTypes:M.z.array().optional(),notDataTypes:M.z.array().optional(),virtual:a.z.boolean().optional(),isIndex:a.z.boolean().optional(),internal:a.z.boolean().optional(),calculated:a.z.boolean().optional()}),nk=a.z.object({channels:v.nullableZ(an)}),Se=t=>(Array.isArray(t)&&t.length>0&&typeof t[0]=="object"?t=t.map(e=>e.key):typeof t=="object"&&"key"in t&&(t=[t.key]),$O(t,{number:"keys",string:"names"}));class Kn{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const r=Se(e),{variant:s}=r;let{normalized:i}=r;return s==="keys"&&i.indexOf(0)!==-1&&(i=i.filter(o=>o!==0)),i.length===0?[]:await this.execute({[s]:i,...n})}async execute(e){const[n,r]=await this.client.send(Kn.ENDPOINT,e,tk,nk);if(r!=null)throw r;return n.channels}}class Ui{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,n){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:r}=Se(e),s=[],i=[];if(r.forEach(c=>{const l=this.get(c);l!=null?s.push(...l):i.push(c)}),i.length===0)return s;const o=await this.wrapped.retrieve(i,n);return this.set(o),s.concat(o)}delete(e){const{variant:n,normalized:r}=Se(e);n==="names"?r.forEach(s=>{const i=this.namesToKeys.get(s);i!=null&&(i.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):r.forEach(s=>{const i=this.cache.get(s);i!=null&&(this.cache.delete(s),this.namesToKeys.delete(i.name))})}rename(e,n){e.forEach((r,s)=>{const i=n[s],o=this.cache.get(r);if(o==null)return;this.cache.delete(r);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(r),c.size===0&&this.namesToKeys.delete(o.name)),o.name=i,this.cache.set(r,o);const l=this.namesToKeys.get(i);l==null?this.namesToKeys.set(i,new Set([r])):l.add(r)})}set(e){e.forEach(n=>{this.cache.set(n.key,n);const r=this.namesToKeys.get(n.name);r==null?this.namesToKeys.set(n.name,new Set([n.key])):r.add(n.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const n=this.namesToKeys.get(e);if(n==null)return;const r=[];if(n.forEach(s=>{const i=this.cache.get(s);i!=null&&r.push(i)}),r.length!==0)return r}}class lh{mu=new ek;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=iw(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=Se(e);return r==="names"?await this.wrapped.retrieve(n):await new Promise((s,i)=>{this.mu.runExclusive(()=>{this.requests.set(n,{resolve:s,reject:i}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((n,r)=>r.forEach(s=>e.add(s)));try{const n=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((r,s)=>r.resolve(n.filter(i=>s.includes(i.key))))}catch(n){this.requests.forEach(r=>r.reject(n))}finally{this.requests.clear()}})}}const uh=async(t,e)=>{const{normalized:n}=Se(e),r=await t.retrieve(n),s=[];if(n.forEach(i=>{r.find(o=>o.name===i||o.key===i)==null&&s.push(i)}),s.length>0)throw new Qe(`Could not find channels: ${JSON.stringify(s)}`);return r},rk="sy_channel_set",sk="sy_channel_delete";class Ia{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;requires;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:i=!1,index:o=0,internal:c=!1,virtual:l=!1,frameClient:u,alias:h,status:p,expression:f="",requires:O=[]}){this.key=L.parse(s),this.name=n,this.dataType=new M(e),this.leaseholder=r,this.index=L.parse(o),this.isIndex=i,this.internal=c,this.alias=h,this.virtual=l,this.expression=f,this.requires=L.array().parse(O??[]),p!=null&&(this.status=rn.create(p)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new D("cannot read from a channel that has not been created");return this._frameClient}get payload(){return an.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 jr(this.payload)}get ontologyID(){return fh(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,n){return await this.framer.write(e,this.key,n)}}const ak="sy_calculation_status",ik="/channel/retrieve-group",ok=a.z.object({}),ck=a.z.object({group:ts});let hh=class{frameClient;client;retriever;writer;constructor(t,e,n,r){this.frameClient=t,this.retriever=e,this.client=n,this.writer=r}async create(t,e={}){const{retrieveIfNameExists:n=!1}=e,r=!Array.isArray(t);let s=v.toArray(t),i=[];if(n){const o=await this.retriever.retrieve(s.map(l=>l.name)),c=new Set(o.map(l=>l.name));s=s.filter(l=>!c.has(l.name)),i=this.sugar(o)}return i=i.concat(this.sugar(await this.writer.create(s))),r?i[0]:i}async retrieve(t,e){if(typeof t=="object"&&!Array.isArray(t))return this.sugar(await this.retriever.retrieve(t));const n=!Array.isArray(t),r=this.sugar(await this.retriever.retrieve(t,e));return ue("channel",t,r,n),n?r[0]:r}async delete(t){const{normalized:e,variant:n}=Se(t);return n==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(t,e){return await this.writer.rename(v.toArray(t),v.toArray(e))}createDebouncedBatchRetriever(t=10){return new Ui(new lh(new Kn(this.client),t))}sugar(t){const{frameClient:e}=this;return Array.isArray(t)?t.map(n=>new Ia({...n,frameClient:e})):new Ia({...t,frameClient:e})}async retrieveGroup(){return(await b(this.client,ik,{},ok,ck)).group}};const jr=({virtual:t,expression:e})=>t&&e!=="",dh=async(t,e)=>{if(!jr(e))return e.index;for(const n of e.requires){const r=await t(n);if(r==null)return null;if(!r.virtual)return r.index}for(const n of e.requires){const r=await t(n);if(r==null)return null;if(jr(r)){const s=await dh(t,r);if(s!=null)return s}}return null},fh=t=>({type:"channel",key:t.toString()}),lk=a.z.object({channels:oh.array()}),uk=a.z.object({channels:an.array()}),hk=a.z.object({keys:L.array().optional(),names:Me.array().optional()}),dk=a.z.object({}),fk=a.z.object({keys:L.array(),names:Me.array()}),pk=a.z.object({}),yk="/channel/create",mk="/channel/delete",gk="/channel/rename";let ph=class{client;cache;constructor(t,e){this.client=t,this.cache=e}async create(t){const{channels:e}=await b(this.client,yk,{channels:t.map(n=>({...n,dataType:n.dataType}))},lk,uk);return this.cache.set(e),e}async delete(t){const e=L.array().parse(t.keys??[]);await b(this.client,mk,t,hk,dk),e.length>0&&this.cache.delete(e),t.names!=null&&this.cache.delete(t.names)}async rename(t,e){await b(this.client,gk,{keys:t,names:e},fk,pk),this.cache.rename(t,e)}};const Ca=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:ak,CacheRetriever:Ui,Channel:Ia,Client:hh,ClusterRetriever:Kn,DELETE_CHANNEL_NAME:sk,DebouncedBatchRetriever:lh,SET_CHANNEL_NAME:rk,Writer:ph,analyzeParams:Se,isCalculated:jr,keyZ:L,nameZ:Me,newZ:oh,ontologyID:fh,paramsZ:bt,payloadZ:an,resolveCalculatedIndex:dh,retrieveRequired:uh,statusZ:ih},Symbol.toStringTag,{value:"Module"})),nt=a.z.uuid(),Jn=a.z.object({key:nt,username:a.z.string().min(1,"Username is required"),firstName:a.z.string().default(""),lastName:a.z.string().default(""),rootUser:a.z.boolean().default(!0)}),yh=Jn.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:a.z.string().min(1)}),wk=a.z.object({keys:nt.array().optional(),usernames:a.z.string().array().optional()}),bk=a.z.object({key:nt}).transform(({key:t})=>({keys:[t]})),vk=a.z.object({username:a.z.string()}).transform(({username:t})=>({usernames:[t]})),Tk=a.z.object({usernames:a.z.string().array()}).transform(({usernames:t})=>({usernames:t})),Sk=a.z.union([bk,vk,Tk,wk]),zk=a.z.object({users:v.nullableZ(Jn)}),Ok=a.z.object({users:yh.array()}),kk=a.z.object({users:Jn.array()}),Ek=a.z.object({key:nt,username:a.z.string().min(1)}),Nk=a.z.object({}),xk=a.z.object({key:nt,firstName:a.z.string().optional(),lastName:a.z.string().optional()}),Ak=a.z.object({}),Ik=a.z.object({keys:nt.array()}),Ck=a.z.object({}),jk="/user/retrieve",Pk="/user/create",$k="/user/change-username",_k="/user/rename",Mk="/user/delete";let mh=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=await b(this.client,Pk,{users:v.toArray(t)},Ok,kk);return e?n.users:n.users[0]}async changeUsername(t,e){await b(this.client,$k,{key:t,username:e},Ek,Nk)}async retrieve(t){const e="key"in t||"username"in t,n=await b(this.client,jk,t,Sk,zk);if(!e)return n.users;if(n.users.length===0){const r="key"in t?`key ${t.key}`:`username ${t.username}`;throw new Ue(`No user with ${r} found`)}if(n.users.length>1){const r="key"in t?`key ${t.key}`:`username ${t.username}`;throw new xr(`Multiple users found with ${r}`)}return n.users[0]}async rename(t,e,n){await b(this.client,_k,{key:t,firstName:e,lastName:n},xk,Ak)}async delete(t){await b(this.client,Mk,{keys:v.toArray(t)},Ik,Ck)}};const Rk=t=>({type:"user",key:t}),Uk=Object.freeze(Object.defineProperty({__proto__:null,Client:mh,keyZ:nt,newZ:yh,ontologyID:Rk,userZ:Jn},Symbol.toStringTag,{value:"Module"})),Zk=a.z.object({username:a.z.string(),password:a.z.string()}),Lk=a.z.object({token:a.z.string(),user:Jn}),lc="/auth/login",Dk=3,Bk="/auth/change-password",Fk=a.z.object({username:a.z.string(),password:a.z.string(),newPassword:a.z.string().min(1)}),Yk=a.z.object({}),qk=[za,Oa];let Vk=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(t,e){this.client=t,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(t){if(!this.authenticated)throw new Error("Not authenticated");await b(this.client,Bk,{username:this.credentials.username,password:this.credentials.password,newPassword:t},Fk,Yk),this.credentials.password=t}middleware(){const t=async(e,n)=>{if(!this.authenticated&&!e.target.endsWith(lc)){this.authenticating??=new Promise((o,c)=>{this.client.send(lc,this.credentials,Zk,Lk).then(([l,u])=>{if(u!=null)return o(u);this.token=l?.token,this.user=l?.user,this.authenticated=!0,o(null)}).catch(c)});const i=await this.authenticating;if(i!=null)return[e,i]}e.params.Authorization=`Bearer ${this.token}`;const[r,s]=await n(e);return qk.some(i=>i.matches(s))&&this.retryCount<Dk?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,t(e,n)):(this.retryCount=0,[r,s])};return t}};const Wk=a.z.enum(["disconnected","connecting","connected","failed"]),Hk=a.z.object({status:Wk,error:a.z.instanceof(Error).optional(),message:a.z.string().optional(),clusterKey:a.z.string(),clientVersion:a.z.string(),clientServerCompatible:a.z.boolean(),nodeVersion:a.z.string().optional()}),Gk=a.z.object({clusterKey:a.z.string(),nodeVersion:a.z.string().optional()}),uc={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.46.0"},hc=(t,e,n)=>{const r=n?"cluster":"client";return`Synnax cluster node version ${t!=null?`${t} `:""}is too ${n?"old":"new"} for client version ${e}.
|
|
41
|
-
This may cause compatibility issues. We recommend updating the ${r}. For more information, see
|
|
42
|
-
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${r}-version`};class Pr{static ENDPOINT="/connectivity/check";static DEFAULT=uc;_state;pollFrequency=x.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=Hk;versionWarned=!1;constructor(e,n=x.seconds(30),r,s){this._state={...uc},this.client=e,this.pollFrequency=n,this.clientVersion=r,this.name=s,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const[n,r]=await this.client.send(Pr.ENDPOINT,{},a.z.object({}),Gk);if(r!=null)throw r;const s=n.nodeVersion,i=this.clientVersion,o=this.versionWarned;s==null?(this._state.clientServerCompatible=!1,o||(console.warn(hc(null,i,!0)),this.versionWarned=!0)):Mo.versionsEqual(i,s,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,o||(console.warn(hc(s,i,Mo.semVerNewer(i,s))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const Kk=a.z.object({keys:L.array().optional(),bounds:F.z,names:Me.array().optional()}),Jk=a.z.object({}),Xk="/frame/delete";class Qk{client;constructor(e){this.client=e}async delete(e){await b(this.client,Xk,e,Kk,Jk)}}const dc=t=>{const e=v.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},fc=(t,e)=>{const n=v.toArray(t);if(n.length===e.length)return;const r=dc(t);throw dc===null?new D("[Frame] - channel keys or names must be provided when constructing a frame."):new D(`[Frame] - ${r}s and series must be the same length.
|
|
43
|
-
Got ${n.length} ${r}s and ${e.length} series.`)};let le=class xt{columns=[];series=[];constructor(e=[],n=[]){if(e instanceof xt){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((r,s)=>this.push(s,...v.toArray(r)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const r=e;r.series??=[],r.keys??=[];const s=r.series.map(i=>gh(i));fc(r.keys,s),r.keys.forEach((i,o)=>this.push(i,s[o]))}else Object.entries(e).forEach(([r,s])=>{const i=parseInt(r);if(!isNaN(i))return this.push(i,...v.toArray(s));this.push(r,...v.toArray(s))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const r=v.toArray(n),s=v.toArray(e);fc(s,r),r.forEach((i,o)=>this.push(s[o],i));return}throw new D(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
44
|
-
payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
|
|
45
|
-
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 ee("colType is not key");return this.columns??[]}get uniqueKeys(){return xo.unique(this.keys)}get names(){if(this.colType==="key")throw new ee("colType is not name");return this.columns??[]}get uniqueNames(){return xo.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>wh(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(n=>n.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return F.ZERO;const r=C.min(...this.series.map(i=>i.timeRange.start)),s=C.max(...this.series.map(i=>i.timeRange.end));return new F(r,s)}const n=this.get(e);return n==null?F.ZERO:n.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(n=>e.includes(n)):new sw(this.series.filter((n,r)=>this.columns[r]===e))}push(e,...n){if(e instanceof xt){if(this.colType!==null&&e.colType!==this.colType)throw new D("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...n),typeof e=="string"&&this.colType==="key")throw new D("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new D("keyVariant must match");this.columns.push(...Array.from({length:n.length},()=>e))}}concat(e){return new xt([...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 n=new xt;return this.forEach((r,s,i)=>n.push(...e(r,s,i))),n}forEach(e){this.columns.forEach((n,r)=>{const s=this.series[r];e(n,s,r)})}at(e,n=!1){const r={};return this.uniqueColumns.forEach(s=>{r[s]=this.get(s).at(e,n)}),r}filter(e){const n=new xt;return this.columns.forEach((r,s)=>{const i=this.series[s];e(r,i,s)&&n.push(r,i)}),n}get byteLength(){return new Ut(this.series.reduce((e,n)=>e.add(n.byteLength),Ut.ZERO))}get digest(){const e={};return this.keys.forEach((n,r)=>{const s=this.series[r].digest;n in e?e[n].push(s):e[n]=[s]}),e}get length(){return this.series.reduce((e,n)=>e+n.length,0)}toString(){let e=`Frame{
|
|
46
|
-
`;return this.uniqueColumns.forEach(n=>{e+=` ${n}: ${this.get(n).series.map(r=>r.toString()).join(",")}
|
|
47
|
-
`}),e+="}",e}};const ls=a.z.object({keys:a.z.union([a.z.null().transform(()=>[]),a.z.number().array().optional().default([])]),series:a.z.union([a.z.null().transform(()=>[]),We.crudeZ.array().optional().default([])])}),gh=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new We({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},wh=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var Lt=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(Lt||{}),Pn=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Pn||{});const eE=new x(-1);class ja extends je.sub("writer_closed"){constructor(){super("WriterClosed")}}const tE=a.z.enum(Pn).or(a.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),bh=a.z.object({start:C.z.optional(),controlSubject:me.subjectZ.optional(),authorities:a.z.union([me.authorityZ.transform(t=>[t]),me.authorityZ.array()]).default([me.ABSOLUTE_AUTHORITY]),mode:tE.default(1),errOnUnauthorized:a.z.boolean().default(!1),enableAutoCommit:a.z.boolean().default(!1),autoIndexPersistInterval:x.z.default(x.SECOND),useHighPerformanceCodec:a.z.boolean().default(!0)}),nE=bh.extend({keys:L.array().optional()}),pc=bh.extend({channels:bt}),vh=pc.or(bt.transform(t=>pc.parse({channels:t,start:C.now()}))),rE=a.z.object({command:a.z.enum(Lt),config:nE.optional(),frame:ls.optional(),buffer:a.z.instanceof(Uint8Array).optional()}),sE=a.z.object({command:a.z.enum(Lt),end:C.z,err:Re.payloadZ.optional()}),aE=a.z.tuple([a.z.union([a.z.record(L.or(Me),me.authorityZ),L.or(Me),me.authorityZ]),me.authorityZ.optional()]).transform(([t,e])=>{if(me.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(L.or(Me).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const n=t;return{keys:Object.keys(n),authorities:Object.values(n)}});let Th=class Pa{static ENDPOINT="/frame/write";stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=vh.parse(r),i=await Li.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new hE(i.codec)));const o=await n.stream(Pa.ENDPOINT,rE,sE),c=new Pa(o,i);return await c.execute({command:0,config:{...s,keys:i.keys}}),c}async write(e,n){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const r=await this.adapter.adapt(e,n);this.stream.send({command:1,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=aE.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:3,config:s})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),C.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(ja.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=ze.matches(r)?new ja:r:this.closeErr=Re.decode(n?.err)}}async execute(e){const n=this.stream.send(e);for(n!=null&&await this.closeInternal(n);;){const[r,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const i=Re.decode(r?.err);if(i!=null&&await this.closeInternal(i),r?.command==e.command)return r}}};const yc=t=>t.data.byteLength/t.dataType.density.valueOf(),iE=t=>{const{keys:e,series:n}=t;e.forEach((r,s)=>{n[s].key=r}),n.sort((r,s)=>r.key-s.key),e.sort((r,s)=>r-s),n.forEach(r=>delete r.key)},mc=5,gc=4,wc=3,bc=2,vc=1,Tc=0,Ee=M.TIMESTAMP.density.valueOf(),Be=8,Fe=4,Fs=4,Ys=4,oE=1;class Sh{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],n=[]){(e.length>0||n.length>0)&&this.update(e,n)}update(e,n){this.seqNum++;const r={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,i)=>{const o=n[i];r.keyDataTypes.set(s,o),o.isVariable&&(r.hasVariableDataTypes=!0)}),r.keys.sort(),this.states.set(this.seqNum,r),this.currState=r}throwIfNotUpdated(e){if(this.seqNum<1)throw new D(`
|
|
48
|
-
The codec has not been updated with a list of channels and data types.
|
|
49
|
-
Please call the update method before calling ${e}.
|
|
50
|
-
`)}encode(e,n=0){this.throwIfNotUpdated("encode");let r=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(r=e.toPayload()),iE(r);let s=-1,i,o,c,l=n+oE+Ys,u=!this.currState?.hasVariableDataTypes,h=!0,p=!0,f=!0,O=!0,I=!0;r.keys.length!==this.currState?.keys.length&&(f=!1,l+=r.keys.length*Fs),r.series.forEach((A,W)=>{const J=yc(A),un=r.keys[W],ct=this.currState?.keyDataTypes.get(un);if(ct==null)throw new D(`Channel ${un} was not provided in the list of channels when opening the writer`);if(!ct.equals(A.dataType))throw new D(`Series data type of ${A.dataType.toString()} does not match the data type of ${ct.toString()} for channel ${un}`);if(l+=A.data.byteLength,s===-1){s=J,i=A.timeRange?.start,o=A.timeRange?.end,c=BigInt(A.alignment??0n);return}s!==J&&(u=!1),(i?.valueOf()!==A.timeRange?.start.valueOf()||o?.valueOf()!==A.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(A.alignment??0)&&(O=!1)}),p=h&&i==null&&o==null,I=O&&(c===void 0||c===0n),u?l+=Fe:l+=r.keys.length*Fe,p||(h?l+=Ee*2:l+=r.keys.length*Ee*2),I||(O?l+=Be:l+=r.keys.length*Be);const j=new Uint8Array(l),w=new DataView(j.buffer);let T=n;return j[T]=Number(I)<<mc|Number(O)<<gc|Number(u)<<wc|Number(h)<<bc|Number(p)<<vc|Number(f)<<Tc,T++,w.setUint32(T,this.seqNum,!0),T+=Ys,u&&(w.setUint32(T,s,!0),T+=Fe),h&&!p&&(w.setBigUint64(T,i?.valueOf()??0n,!0),w.setBigUint64(T,o?.valueOf()??0n,!0),T+=Ee*2),O&&!I&&(w.setBigUint64(T,c??0n,!0),T+=Be),r.series.forEach((A,W)=>{if(f||(w.setUint32(T,r.keys[W],!0),T+=Fs),!u){let J=A.data.byteLength;A.dataType.isVariable||(J=yc(A)),w.setUint32(T,J,!0),T+=Fe}j.set(new Uint8Array(A.data),T),T+=A.data.byteLength,!h&&!p&&(w.setBigUint64(T,A.timeRange?.start.valueOf()??0n,!0),w.setBigUint64(T,A.timeRange?.end.valueOf()??0n,!0),T+=Ee*2),!O&&!I&&(w.setBigUint64(T,A.alignment??0n,!0),T+=Be)}),j}decode(e,n=0){this.throwIfNotUpdated("decode");const r=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let i=n,o=0,c=0,l,u,h;const p=new DataView(r.buffer,r.byteOffset,r.byteLength),f=!!(r[i]>>mc&1),O=!!(r[i]>>gc&1),I=!!(r[i]>>wc&1),j=!!(r[i]>>bc&1),w=!!(r[i]>>vc&1),T=!!(r[i]>>Tc&1);i++;const A=p.getUint32(i,!0);i+=Ys;const W=this.states.get(A);if(W==null)return s;if(I){if(i+Fe>p.byteLength)return s;o=p.getUint32(i,!0),i+=Fe}if(j&&!w){if(i+Ee>p.byteLength)return s;l=new C(p.getBigUint64(i,!0)),i+=Ee,u=new C(p.getBigUint64(i,!0)),i+=Ee}if(O&&!f){if(i+Be>p.byteLength)return s;h=p.getBigUint64(i,!0),i+=Be}return T&&(s.keys=[...W.keys]),W.keys.forEach((J,un)=>{if(!T){if(i>=p.byteLength||p.getUint32(i,!0)!==J)return;i+=Fs,s.keys.push(J)}const ct=W.keyDataTypes.get(J);if(c=0,I)c=o;else{if(i+Fe>p.byteLength)return;c=p.getUint32(i,!0),i+=Fe}let rr=c;if(ct.isVariable||(rr*=ct.density.valueOf()),i+rr>p.byteLength){s.keys.splice(un,1);return}const lt={dataType:ct,data:r.slice(i,i+rr).buffer};if(i+=rr,!j&&!w){if(i+Ee*2>p.byteLength)return;const Hf=p.getBigUint64(i,!0);i+=Ee;const Gf=p.getBigUint64(i,!0);i+=Ee,lt.timeRange=new F({start:Hf,end:Gf})}else w?lt.timeRange=new F({start:0n,end:0n}):lt.timeRange=new F({start:l?.valueOf()??0n,end:u?.valueOf()??0n});if(!O&&!f){if(i+Be>p.byteLength)return;h=p.getBigUint64(i,!0),i+=Be,lt.alignment=h}else f?lt.alignment=0n:lt.alignment=h;s.series.push(lt)}),s}}const Zi=254,cE=new Uint8Array([Zi]),lE=255,uE=new Uint8Array([lE]),zh="application/sy-framer";class hE{contentType=zh;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=wt.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=Lt.Write){const s=this.lowPerfCodec.encode(n),i=new Uint8Array({length:s.byteLength+1});return i.set(cE,0),i.set(new Uint8Array(s),1),i}const r=this.base.encode(n.payload?.frame,1);return r.set(uE,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Zi)return this.lowPerfCodec.decode(e.slice(1),n);const r={type:"data"},s=this.base.decode(e,1);return r.payload={command:Lt.Write,frame:s},r}}class dE{contentType=zh;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=wt.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Zi?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class us{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Sh}static async open(e,n){const r=new us(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=Se(e),s=await this.retriever.retrieve(r),i=s.map(c=>c.key);if(Ao.uniqueUnorderedPrimitiveArrays(this.keys,i)===Ao.EQUAL)return!1;if(this.codec.update(i,s.map(c=>c.dataType)),n==="keys")return this.adapter=null,this.keys=r,!0;const o=new Map;return this.adapter=o,r.forEach(c=>{const l=s.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} not found`);o.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys()),!0}adapt(e){if(this.adapter==null)return e;const n=this.adapter;return e.map((r,s)=>{if(typeof r=="number"){const i=n.get(r);if(i==null)throw new Error(`Channel ${r} not found`);return[i,s]}return[r,s]})}}class Li{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Sh}static async open(e,n){const r=new Li(e);return await r.update(n),r}async adaptParams(e){const n=bt.parse(e);return await Promise.all(n.map(async r=>await this.adaptToKey(r)))}async update(e){const n=await uh(this.retriever,e),r=n.map(l=>l.key),s=new Set(this.keys),i=new Set(r),o=!i.isSubsetOf(s),c=!s.isSubsetOf(i);return o||c?(this.adapter=new Map(n.map(l=>[l.name,l.key])),this.keys=r,this.codec.update(this.keys,n.map(l=>l.dataType)),!0):!1}async fetchChannel(e){const n=await this.retriever.retrieve(e);if(n.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return n[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,n){if(typeof e=="string"||typeof e=="number"){if(n==null)throw new D(`
|
|
51
|
-
Received a single channel name or key but no series.
|
|
52
|
-
`);if(Array.isArray(n)){if(n.some(l=>l instanceof We||Array.isArray(l)))throw new D(`
|
|
53
|
-
Received a single channel name or key but multiple series.
|
|
54
|
-
`);n=n}const o=await this.fetchChannel(e),c=new We({data:n,dataType:o.dataType});return new le(o.key,c)}if(Array.isArray(e)){if(n==null)throw new D(`
|
|
55
|
-
Received an array of channel names or keys but no series.
|
|
56
|
-
`);if(!Array.isArray(n))throw new D(`
|
|
57
|
-
Received an array of channel names or keys but no array of series.
|
|
58
|
-
`);const o=[],c=[];for(let l=0;l<e.length;l++){const u=await this.fetchChannel(e[l]);if(l>=n.length)throw new D(`
|
|
59
|
-
Received an array of channel names or keys but not enough series.
|
|
60
|
-
`);const h=new We({data:n[l],dataType:u.dataType});o.push(u.key),c.push(h)}return new le(o,c)}if(e instanceof le||e instanceof Map){const o=new le(e);if(this.adapter==null)return o;const c=o.columns.map(l=>{const u=typeof l=="string"?this.adapter?.get(l):l;if(u==null)throw new D(`
|
|
61
|
-
Channel ${l} was not provided in the list of channels when opening the writer
|
|
62
|
-
`);return u});return new le(c,o.series)}const r=[],s=[],i=Object.entries(e);for(let o=0;o<i.length;o++){const[c,l]=i[o],u=await this.fetchChannel(c),h=new We({data:l,dataType:u.dataType});r.push(u.key),s.push(h)}return new le(r,s)}}class Oh{name;stream;constructor(e,n){this.stream=n,this.name=e}async receive(){const[e,n]=await this.stream.receive();if(n!=null)throw n;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,n]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
|
|
63
|
-
Please report this error to the Synnax team.`),n!=null){if(ze.matches(n))return;throw n}}}closeSend(){this.stream.closeSend()}send(e){const n=this.stream.send(e);if(n!=null)throw n}}const $r=new x(-1);var Di=(t=>(t[t.Open=0]="Open",t[t.Next=1]="Next",t[t.Prev=2]="Prev",t[t.SeekFirst=3]="SeekFirst",t[t.SeekLast=4]="SeekLast",t[t.SeekLE=5]="SeekLE",t[t.SeekGE=6]="SeekGE",t[t.Valid=7]="Valid",t[t.Error=8]="Error",t))(Di||{}),kh=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(kh||{});const fE=a.z.object({command:a.z.enum(Di),span:x.z.optional(),bounds:F.z.optional(),stamp:C.z.optional(),keys:L.array().optional(),chunkSize:a.z.number().optional()}),pE=a.z.object({variant:a.z.enum(kh),ack:a.z.boolean(),command:a.z.enum(Di),error:Re.payloadZ.optional().nullable(),frame:ls.optional()});class $n{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,n){this.stream=new Oh("Iterator",e),this.value=new le,this.adapter=n}static async _open(e,n,r,s,i={}){const o=await us.open(r,n),c=await s.stream($n.ENDPOINT,fE,pE),l=new $n(c,o);return await l.execute({command:0,keys:o.keys,bounds:new F(e),chunkSize:i.chunkSize??1e5}),l}async next(e=$r){return await this.execute({command:1,span:new x(e)})}async prev(e=$r){return await this.execute({command:2,span:new x(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 C(e)})}async seekGE(e){return await this.execute({command:6,stamp:new C(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new yE(this)}async execute(e){for(this.stream.send(e),this.value=new le;;){const n=await this.stream.receive();if(n.variant===1)return n.ack;this.value.push(this.adapter.adapt(new le(n.frame)))}}}class yE{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 mE=a.z.object({keys:a.z.number().array(),downsampleFactor:a.z.number()}),gE=a.z.object({frame:ls}),wE="/frame/stream",Sc=a.z.object({channels:bt,downsampleFactor:a.z.number().optional().default(1),useHighPerformanceCodec:a.z.boolean().optional().default(!0)}),Bi=Sc.or(bt.transform(t=>Sc.parse({channels:t}))),Eh=(t,e)=>async n=>{const r=Bi.parse(n),s=await us.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new dE(s.codec)));const i=await e.stream(wE,mE,gE),o=new bE(i,s);i.send({keys:s.keys,downsampleFactor:r.downsampleFactor??1});const[,c]=await i.receive();if(c!=null)throw c;return o},Nh=async(t,e,n)=>await Eh(t,e)(n);class bE{stream;adapter;downsampleFactor;constructor(e,n){this.stream=new Oh("Streamer",e),this.adapter=n,this.downsampleFactor=1}get keys(){return this.adapter.keys}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ze.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new le((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 hs{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=Bi.parse(n);const{maxRetries:s=5e3,baseInterval:i=x.seconds(1),scale:o=1}=r??{};this.breaker=new ru.Breaker({maxRetries:s,baseInterval:i,scale:o})}static async open(e,n,r){const s=new hs(e,n,r);return await s.runStreamer(),s}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=bt.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(ze.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(ze.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 xh extends dw.Observer{streamer;closePromise;constructor(e,n){super(n),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 vE=t=>({type:"framer",key:t.toString()});let Ah=class{streamClient;retriever;deleter;constructor(t,e,n){this.streamClient=t,this.retriever=n,this.deleter=new Qk(e)}async openIterator(t,e,n){return await $n._open(t,e,this.retriever,this.streamClient,n)}async openWriter(t){return await Th._open(this.retriever,this.streamClient,t)}async openStreamer(t){return await Nh(this.retriever,this.streamClient,t)}async write(t,e,n){if(n==null){const s=e,i=await this.openWriter({start:t,channels:Object.keys(s),mode:Pn.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:x.MAX});return await i.write(s),await i.close()}const r=await this.openWriter({start:t,channels:e,mode:Pn.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:x.MAX});await r.write(e,n),await r.close()}async read(t,e){const{single:n}=Se(e),r=await this.readFrame(t,e);return n?r.get(e):r}async readFrame(t,e){const n=await this.openIterator(t,e),r=new le;try{for await(const s of n)r.push(s)}finally{await n.close()}return r}async readLatest(t,e=1){const{single:n}=Se(t),r=await this.readLatestNFrame(t,e);return n?r.get(t):r}async readLatestNFrame(t,e){const n=await this.openIterator(F.MAX,t,{chunkSize:e}),r=new le;if(e>0)try{await n.seekLast(),await n.prev($r),r.push(n.value)}finally{await n.close()}return r}async delete(t,e){const{normalized:n,variant:r}=Se(t),s=new F(e);return r==="keys"?await this.deleter.delete({keys:n,bounds:s}):await this.deleter.delete({names:n,bounds:s})}};const Ih=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:eE,AUTO_SPAN:$r,Client:Ah,Frame:le,HardenedStreamer:hs,Iterator:$n,ObservableStreamer:xh,Writer:Th,WriterClosedError:ja,WriterCommand:Lt,WriterMode:Pn,createStreamOpener:Eh,frameZ:ls,ontologyID:vE,openStreamer:Nh,seriesFromPayload:gh,seriesToPayload:wh,streamerConfigZ:Bi,writerConfigZ:vh},Symbol.toStringTag,{value:"Module"})),TE=me.ABSOLUTE_AUTHORITY,SE=me.ZERO_AUTHORITY,zE=me.stateZ(a.z.number()),OE=t=>t.to==null?`${t.from?.resource} - ${t.from?.subject.name} -> released`:t.from==null?`${t.to.resource} - released -> ${t.to.subject.name} (${t.to.authority.toString()})`:`${t.to.resource} - ${t.from.subject.name} -> ${t.to.subject.name} (${t.to.authority.toString()})`,kE=a.z.object({transfers:a.z.array(me.transferZ(L))});class Ch extends xh{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,kE);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new wt.JSONCodec}subjects(){const e=new Map;return this.states.forEach(n=>e.set(n.subject.key,n.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const jh="sy_node_1_control";let Ph=class{framer;constructor(t){this.framer=t}async openStateTracker(){const t=await hs.open(async e=>await this.framer.openStreamer(e),jh);return new Ch(t)}};const EE=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:TE,CONTROL_STATE_CHANNEL_NAME:jh,Client:Ph,StateTracker:Ch,ZERO_AUTHORITY:SE,stateZ:zE,transferString:OE},Symbol.toStringTag,{value:"Module"}));let NE=class{tasks;racks;devices;constructor(t,e,n){this.tasks=t,this.racks=e,this.devices=n}};const ke=a.z.uint32(),$h=a.z.object({rack:ke}),_h=rn.statusZ($h),ds=a.z.object({key:ke,name:a.z.string(),status:zn.nullToUndefined(_h)}),Mh=ds.partial({key:!0}),Rh=t=>t?wt.JSON_CODEC.decodeString(t,Oe.unknownZ):{},on=a.z.string(),Uh=a.z.object({rack:ke,device:on}),Zh=rn.statusZ(Uh),fs=a.z.object({key:on,rack:ke.min(1,"Must select a location to connect from"),name:a.z.string().min(1,"Name is required"),make:a.z.string().min(1,"Make is required"),model:a.z.string().min(1,"Model is required"),location:a.z.string().min(1,"Location is required"),configured:a.z.boolean().optional(),properties:Oe.unknownZ.or(a.z.string().transform(Rh)),status:zn.nullToUndefined(Zh)}),Lh=fs.extend({properties:a.z.unknown().transform(t=>wt.JSON_CODEC.encodeString(t))}),xE="sy_device_set",AE="sy_device_delete",IE="sy_device_status",CE="/hardware/device/retrieve",jE="/hardware/device/create",PE="/hardware/device/delete",$E=a.z.object({devices:Lh.array()}),_E=a.z.object({devices:fs.array()}),ME=a.z.object({keys:on.array()}),RE=a.z.object({}),UE=a.z.object({keys:on.array().optional(),names:a.z.string().array().optional(),makes:a.z.string().array().optional(),models:a.z.string().array().optional(),locations:a.z.string().array().optional(),racks:ke.array().optional(),searchTerm:a.z.string().optional(),limit:a.z.number().optional(),offset:a.z.number().optional(),includeStatus:a.z.boolean().optional()}),ZE=a.z.object({devices:v.nullableZ(fs)}),LE=a.z.object({key:on,includeStatus:a.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),DE=a.z.union([LE,UE]);let Dh=class{client;constructor(t){this.client=t}async retrieve(t){const e=typeof t=="object"&&"key"in t,n=await b(this.client,CE,t,DE,ZE);ue("Device",t,n.devices,e);const r=n.devices;return e?r[0]:r}async create(t){const e=!Array.isArray(t),n=(await b(this.client,jE,{devices:v.toArray(t)},$E,_E)).devices;return e?n[0]:n}async delete(t){await b(this.client,PE,{keys:v.toArray(t)},ME,RE)}};const BE=t=>({type:"device",key:t}),FE=Object.freeze(Object.defineProperty({__proto__:null,Client:Dh,DELETE_CHANNEL_NAME:AE,SET_CHANNEL_NAME:xE,STATUS_CHANNEL_NAME:IE,deviceZ:fs,keyZ:on,newZ:Lh,ontologyID:BE,statusDetailsSchema:Uh,statusZ:Zh},Symbol.toStringTag,{value:"Module"})),YE="/hardware/rack/retrieve",qE="/hardware/rack/create",VE="/hardware/rack/delete",WE="sy_rack_status",HE="sy_rack_set",GE="sy_rack_delete",KE=a.z.object({keys:ke.array().optional(),names:a.z.string().array().optional(),searchTerm:a.z.string().optional(),embedded:a.z.boolean().optional(),hostIsNode:a.z.boolean().optional(),limit:a.z.number().optional(),offset:a.z.number().optional(),includeStatus:a.z.boolean().optional()}),JE=a.z.object({racks:v.nullableZ(ds)}),XE=a.z.union([a.z.object({key:ke,includeStatus:a.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),a.z.object({name:a.z.string(),includeStatus:a.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),QE=KE,e0=a.z.union([XE,QE]),t0=a.z.object({racks:Mh.array()}),n0=a.z.object({racks:ds.array()}),r0=a.z.object({keys:ke.array()}),s0=a.z.object({});let Bh=class{client;tasks;constructor(t,e){this.client=t,this.tasks=e}async delete(t){await b(this.client,VE,{keys:v.toArray(t)},r0,s0)}async create(t){const e=!Array.isArray(t),n=await b(this.client,qE,{racks:v.toArray(t)},t0,n0),r=this.sugar(n.racks);return e?r[0]:r}async retrieve(t){const e="key"in t||"name"in t,n=await b(this.client,YE,t,e0,JE),r=this.sugar(n.racks);return ue("Rack",t,r,e),e?r[0]:r}sugar(t){const e=!Array.isArray(t),n=v.toArray(t).map(({key:r,name:s,status:i})=>new Fh(r,s,this.tasks,i));return e?n[0]:n}};class Fh{key;name;status;tasks;constructor(e,n,r,s){this.key=e,this.name=n,this.tasks=r,this.status=s}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,n){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,n)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const a0=t=>({type:"rack",key:t.toString()}),i0=Object.freeze(Object.defineProperty({__proto__:null,Client:Bh,DELETE_CHANNEL_NAME:GE,Rack:Fh,SET_CHANNEL_NAME:HE,STATUS_CHANNEL_NAME:WE,keyZ:ke,newZ:Mh,ontologyID:a0,rackZ:ds,statusDetailsSchema:$h,statusZ:_h},Symbol.toStringTag,{value:"Module"})),Ze=a.z.union([a.z.string(),a.z.bigint().transform(t=>t.toString()),a.z.number().transform(t=>t.toString())]),Yh=t=>a.z.object({task:Ze,running:a.z.boolean(),data:t}),Fi=t=>rn.statusZ(Yh(t)),Xn=(t={typeSchema:a.z.string(),configSchema:a.z.unknown(),statusDataSchema:a.z.unknown()})=>a.z.object({key:Ze,name:a.z.string(),type:t.typeSchema,internal:a.z.boolean().optional(),config:a.z.string().transform(Rh).or(t.configSchema),status:Fi(t.statusDataSchema).optional().nullable(),snapshot:a.z.boolean().optional()}),qh=t=>Xn(t).omit({key:!0}).extend({key:Ze.transform(e=>e.toString()).optional(),config:a.z.unknown().transform(e=>wt.JSON_CODEC.encodeString(e))}),o0=a.z.object({task:Ze,type:a.z.string(),key:a.z.string(),args:Oe.unknownZ.or(a.z.string().transform(Pe)).or(a.z.array(a.z.unknown())).or(a.z.null()).optional()}),c0=t=>Number(BigInt(t)>>32n),$a="sy_task_status",_a="sy_task_cmd",l0="sy_task_set",u0="sy_task_delete",ht=new Error("Task not created"),Vh=async(t,e)=>{const n=await e.retrieveParents(Yi(t));return n.length===0?null:n[0]};class Wh{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw ht;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw ht;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw ht;return this.rangeClient_}constructor({key:e,type:n,name:r,config:s,internal:i=!1,snapshot:o=!1,status:c},l,u,h,p){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=l??{typeSchema:a.z.string(),configSchema:a.z.unknown(),statusDataSchema:a.z.unknown()},this.internal=i,this.snapshot=o,this.status=c,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=p}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return Yi(this.key)}async executeCommand(e){return await Kh({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await Jh({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas?.statusDataSchema})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw ht;return this.snapshot?await Vh(this.key,this.ontologyClient):null}}const h0=a.z.object({rack:ke.optional(),keys:Ze.array().optional(),names:a.z.string().array().optional(),types:a.z.string().array().optional(),includeStatus:a.z.boolean().optional(),searchTerm:a.z.string().optional(),offset:a.z.number().optional(),limit:a.z.number().optional()}),Hh=a.z.union([a.z.object({key:Ze,includeStatus:a.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),a.z.object({name:a.z.string(),includeStatus:a.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),a.z.object({type:a.z.string(),rack:ke.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),d0=h0,f0=a.z.union([Hh,d0]),p0=t=>a.z.object({tasks:v.nullableZ(Xn(t))}),y0="/hardware/task/retrieve",m0="/hardware/task/create",g0="/hardware/task/delete",w0="/hardware/task/copy",b0=t=>a.z.object({tasks:qh(t).array()}),v0=t=>a.z.object({tasks:Xn(t).array()}),T0=a.z.object({keys:Ze.array()}),S0=a.z.object({}),z0=a.z.object({key:Ze,name:a.z.string(),snapshot:a.z.boolean()}),O0=t=>a.z.object({task:Xn(t)});let Gh=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(t,e,n,r){this.client=t,this.frameClient=e,this.ontologyClient=n,this.rangeClient=r}async create(t,e){const n=!Array.isArray(t),r=b0(e),s=v0(e),i=await b(this.client,m0,{tasks:v.toArray(t)},r,s),o=this.sugar(i.tasks,e);return n?o[0]:o}async delete(t){await b(this.client,g0,{keys:v.toArray(t)},T0,S0)}async retrieve({schemas:t,...e}){const n=Hh.safeParse(e).success,r=(await b(this.client,y0,e,f0,p0(t))).tasks,s=this.sugar(r,t);return ue("Task",e,s,n),n?s[0]:s}async copy(t,e,n){const r=O0(),s=await b(this.client,w0,{key:t,name:e,snapshot:n},z0,r);return this.sugar(s.task)}async retrieveSnapshottedTo(t){if(this.ontologyClient==null)throw ht;return await Vh(t,this.ontologyClient)}sugar(t,e){const n=!Array.isArray(t),r=v.toArray(t).map(({key:s,name:i,type:o,config:c,status:l,internal:u,snapshot:h})=>new Wh({key:s,name:i,type:o,config:c,internal:u,snapshot:h,status:l},e,this.frameClient,this.ontologyClient,this.rangeClient));return n?r[0]:r}async executeCommand(t){return"commands"in t?await qi({...t,frameClient:this.frameClient}):await Kh({...t,frameClient:this.frameClient})}async executeCommandSync(t){if("commands"in t){const n=async()=>{const{commands:r}=t;return(await this.retrieve({keys:r.map(s=>s.task)})).map(s=>s.name)};return await Xh({...t,frameClient:this.frameClient,name:n})}const e=async()=>{const{task:n}=t;return(await this.retrieve({key:n})).name};return await Jh({frameClient:this.frameClient,name:e,...t})}};const Yi=t=>({type:"task",key:t}),Kh=async({frameClient:t,task:e,type:n,args:r})=>(await qi({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],qi=async({frameClient:t,commands:e})=>{if(t==null)throw ht;const n=await t.openWriter(_a),r=e.map(s=>({...s,key:Ag.create()}));return await n.write(_a,r),await n.close(),r.map(s=>s.key)},Jh=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:i,args:o})=>(await Xh({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:i,name:s}))[0],Xh=async({frameClient:t,commands:e,timeout:n=x.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw ht;const i=await t.openStreamer($a),o=await qi({frameClient:t,commands:e}),c=new x(n);let l=[],u;const h=new Promise((p,f)=>{u=setTimeout(()=>{(async()=>{const O=e.map(I=>I.task);f(await k0("command",s,c,O))})()},c.milliseconds)});try{for(;;){const p=await Promise.race([i.read(),h]),f=Fi(r).parse(p.at(-1)[$a]);if(o.includes(f.key)&&(l=[...l.filter(O=>O.key!==f.key),f],l.length===o.length))return l}}finally{clearTimeout(u),i.close()}},k0=async(t,e,n,r)=>{const s=lm.capitalize(t),i=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=v.toArray(await e());const c=Ta.naturalLanguageJoin(o);return new Error(`${s} command to ${c} timed out after ${i}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${s} command to task with key ${Ta.naturalLanguageJoin(r)} timed out after ${i}`)}},E0=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:_a,Client:Gh,DELETE_CHANNEL_NAME:u0,SET_CHANNEL_NAME:l0,STATUS_CHANNEL_NAME:$a,Task:Wh,commandZ:o0,keyZ:Ze,newZ:qh,ontologyID:Yi,rackKey:c0,statusDetailsZ:Yh,statusZ:Fi,taskZ:Xn},Symbol.toStringTag,{value:"Module"})),rt=wu.keyZ,Qn=wu.labelZ,N0="labeled_by",x0="sy_label_set",A0="sy_label_delete",Qh=Qn.extend({key:rt.optional()}),I0=a.object({labels:Qh.array()}),C0=a.object({labels:Qn.array()}),j0=a.object({keys:rt.array()}),ed=a.object({id:U,labels:rt.array(),replace:a.boolean().optional()}),P0=ed.omit({replace:!0}),qs=a.object({}),$0="/label/create",_0="/label/delete",M0="/label/set",R0="/label/remove",U0="/label/retrieve",Z0=a.object({keys:rt.array().optional(),for:U.optional(),searchTerm:a.string().optional(),offset:a.number().optional(),limit:a.number().optional()}),L0=a.object({key:rt}).transform(({key:t})=>({keys:[t]})),D0=a.union([L0,Z0]),B0=a.object({labels:v.nullableZ(Qn)});let td=class{type="label";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,n=await b(this.client,U0,t,D0,B0);return ue("Label",t,n.labels,e),e?n.labels[0]:n.labels}async label(t,e,n={}){await b(this.client,M0,{id:t,labels:e,replace:n.replace},ed,qs)}async remove(t,e){await b(this.client,R0,{id:t,labels:e},P0,qs)}async create(t){const e=Array.isArray(t),n=await b(this.client,$0,{labels:v.toArray(t)},I0,C0);return e?n.labels:n.labels[0]}async delete(t){await b(this.client,_0,{keys:v.toArray(t)},j0,qs)}};const F0=t=>({type:"label",key:t}),Y0=Object.freeze(Object.defineProperty({__proto__:null,Client:td,DELETE_CHANNEL_NAME:A0,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:N0,SET_CHANNEL_NAME:x0,keyZ:rt,labelZ:Qn,newZ:Qh,ontologyID:F0},Symbol.toStringTag,{value:"Module"})),te=a.z.uuid(),Vi=a.z.string().min(1),er=a.z.object({key:te,name:Vi,timeRange:F.z.refine(({isValid:t})=>t,{error:"Time range start time must be before or equal to time range end time"}).refine(({end:t})=>t.valueOf()<=ga.MAX_INT64,{error:"Time range end time must be less than or equal to the maximum value of an int64"}).refine(({start:t})=>t.valueOf()>=ga.MIN_INT64,{error:"Time range start time must be greater than or equal to the minimum value of an int64"}),color:a.z.string().optional(),labels:Qn.array().or(a.z.null().transform(()=>{})).optional(),get parent(){return er.optional().nullable().transform(t=>t===void 0?null:t)}}),nd=er.omit({parent:!0,labels:!0}).partial({key:!0}),q0="sy_range_alias_set",V0="sy_range_alias_delete",W0=a.z.object({range:te,aliases:a.z.string().array()}),H0=a.z.object({aliases:a.z.record(a.z.string(),L)}),G0=a.z.object({range:te,aliases:a.z.record(L,a.z.string())}),K0=a.z.unknown(),J0=a.z.object({range:te,channels:L.array()}),X0=a.z.unknown(),Q0=a.z.object({range:te}),eN=a.z.object({aliases:a.z.record(a.z.string(),a.z.string())}),tN=a.z.object({range:te,channels:L.array()}),nN=a.z.object({aliases:a.z.record(a.z.string(),a.z.string())});let ut=class At{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,n,r){this.rangeKey=e,this.cache=new Map,this.client=r,this.frameClient=n}async resolve(e){const n=[],r=typeof e=="string",s={};if(r){const o=this.cache.get(e);if(o!=null)return o;n.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:n.push(o)});if(n.length===0)return s;const i=await b(this.client,At.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:n},W0,H0);return Object.entries(i.aliases).forEach(([o,c])=>this.cache.set(o,c)),r?i.aliases[n[0]]:{...s,...i.aliases}}async set(e){await b(this.client,At.SET_ENDPOINT,{range:this.rangeKey,aliases:e},G0,K0)}async list(){return(await b(this.client,At.LIST_ENDPOINT,{range:this.rangeKey},Q0,eN)).aliases}async retrieve(e){const n=typeof e=="number",r=await b(this.client,At.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:v.toArray(e)},tN,nN);return n?r.aliases[e]:r.aliases}async delete(e){await b(this.client,At.DELETE_ENDPOINT,{range:this.rangeKey,channels:v.toArray(e)},J0,X0)}};const rN=a.z.object({alias:a.z.string().optional(),channel:L,range:te}),rd="---",sN=t=>`${t.range}${rd}${t.channel}`,aN=t=>{const[e,n]=t.split(rd);return{range:e,channel:Number(n)}},iN="sy_range_kv_set",oN="sy_range_kv_delete",Wi=a.z.object({range:te,key:a.z.string(),value:a.z.string()}),cN=({range:t,key:e})=>`${t}<--->${e}`,lN=a.z.object({range:te,keys:a.z.string().array()}),uN=a.z.object({pairs:v.nullableZ(Wi)}),hN=a.z.object({range:te,pairs:Wi.array()}),dN=a.z.object({range:te,keys:a.z.string().array()});class pt{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,n){this.rangeKey=e,this.client=n}async get(e){const n=await b(this.client,pt.GET_ENDPOINT,{range:this.rangeKey,keys:v.toArray(e)},lN,uN);return typeof e=="string"?n.pairs[0].value:Object.fromEntries(n.pairs.map(r=>[r.key,r.value]))}async list(){return this.get([])}async set(e,n=""){let r;dl(e)?r=Object.entries(e).map(([s,i])=>({range:this.rangeKey,key:s,value:i})):r=[{range:this.rangeKey,key:e,value:n}],await b(this.client,pt.SET_ENDPOINT,{range:this.rangeKey,pairs:r},hN,a.z.unknown())}async delete(e){await b(this.client,pt.DELETE_ENDPOINT,{range:this.rangeKey,keys:v.toArray(e)},dN,a.z.unknown())}}const fN="sy_range_set",pN="sy_range_delete";class sd{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:n=F.ZERO,key:r,color:s,parent:i,labels:o},{frameClient:c,kv:l,aliaser:u,channels:h,labelClient:p,ontologyClient:f,rangeClient:O}){this.key=r,this.name=e,this.timeRange=n,this.parent=i,this.labels=o,this.frameClient=c,this.color=s,this.kv=l,this.aliaser=u,this.channels=h,this.labelClient=p,this.ontologyClient=f,this.rangeClient=O}get ontologyID(){return Pt(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,n){const r=await this.channels.retrieve(e);if(r.length===0)throw new Qe(`Channel ${e} does not exist`);await this.aliaser.set({[r[0].key]:n})}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(n=>n.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:Pt(this.key)})}async addLabel(...e){await this.labelClient.label(Pt(this.key),e)}async removeLabel(...e){await this.labelClient.remove(Pt(this.key),e)}static sort(e,n){return F.sort(e.timeRange,n.timeRange)}}const yN=a.z.object({keys:te.array().optional(),names:a.z.array(a.z.string()).optional(),searchTerm:a.z.string().optional(),overlapsWith:F.z.optional(),limit:a.z.number().int().optional(),offset:a.z.number().int().optional(),hasLabels:rt.array().optional(),includeLabels:a.z.boolean().optional(),includeParent:a.z.boolean().optional()}),mN=yN.or(te.array().transform(t=>({keys:t}))).or(te.transform(t=>({keys:[t]}))).or(a.z.string().transform(t=>({names:[t]}))).or(a.z.string().array().transform(t=>({names:t}))).or(F.z.transform(t=>({overlapsWith:t}))),gN="/range/retrieve",wN=a.z.object({ranges:v.nullableZ(er)});let ad=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(t,e,n,r,s,i){this.frameClient=t,this.writer=e,this.unaryClient=n,this.channels=r,this.labelClient=s,this.ontologyClient=i}async create(t,e){const n=!Array.isArray(t),r=this.sugarMany(await this.writer.create(v.toArray(t),e));return n?r[0]:r}async rename(t,e){await this.writer.rename(t,e)}async delete(t){await this.writer.delete(v.toArray(t))}async retrieve(t){const e=typeof t=="string",{ranges:n}=await b(this.unaryClient,gN,t,mN,wN);return ue("Range",t,n,e),e?this.sugarMany(n)[0]:this.sugarMany(n)}getKV(t){return new pt(t,this.unaryClient)}async retrieveParent(t){const e=await this.ontologyClient.retrieveParents(Pt(t));if(e.length===0)return null;const n=e[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOntologyResource(t){return this.sugarOne(id(t))}async retrieveAlias(t,e){return await new ut(t,this.frameClient,this.unaryClient).retrieve(e)}async retrieveAliases(t,e){return await new ut(t,this.frameClient,this.unaryClient).retrieve(e)}async listAliases(t){return await new ut(t,this.frameClient,this.unaryClient).list()}async setAlias(t,e,n){await new ut(t,this.frameClient,this.unaryClient).set({[e]:n})}async deleteAlias(t,e){await new ut(t,this.frameClient,this.unaryClient).delete(e)}sugarOne(t){return new sd(t,{frameClient:this.frameClient,kv:new pt(t.key,this.unaryClient),aliaser:new ut(t.key,this.frameClient,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(t){return t.map(e=>this.sugarOne(e))}resourceToRange(t){return this.sugarOne({key:t.id.key,name:t.data?.name,timeRange:new F(t.data?.timeRange),color:t.data?.color,labels:[],parent:null})}};const Pt=t=>({type:"range",key:t}),bN=t=>({type:"range-alias",key:t}),id=({data:t,id:{key:e},name:n})=>{const r=F.z.parse(t?.timeRange);return{key:e,name:n,timeRange:r,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},vN=a.z.object({ranges:er.array()}),TN=a.z.object({parent:U.optional(),ranges:nd.array()}),SN=a.z.object({keys:te.array()}),zN=a.z.object({}),ON=a.z.object({key:te,name:Vi}),kN=a.z.object({}),EN="/range/create",NN="/range/delete",xN="/range/rename";class od{client;constructor(e){this.client=e}async rename(e,n){await b(this.client,xN,{key:e,name:n},ON,kN)}async create(e,n){return(await b(this.client,EN,{ranges:e,...n},TN,vN)).ranges}async delete(e){await b(this.client,NN,{keys:e},SN,zN)}}const AN=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:ut,Client:ad,DELETE_ALIAS_CHANNEL_NAME:V0,DELETE_CHANNEL_NAME:pN,KV:pt,KV_DELETE_CHANNEL:oN,KV_SET_CHANNEL:iN,Range:sd,SET_ALIAS_CHANNEL_NAME:q0,SET_CHANNEL_NAME:fN,Writer:od,aliasKey:sN,aliasOntologyID:bN,aliasZ:rN,convertOntologyResourceToPayload:id,decodeDeleteAliasChange:aN,keyZ:te,kvPairKey:cN,kvPairZ:Wi,nameZ:Vi,newZ:nd,ontologyID:Pt,payloadZ:er},Symbol.toStringTag,{value:"Module"})),ps=a.z.string(),ys=rn.statusZ,cd=t=>ys(t).omit({labels:!0}).partial({key:!0}),IN="sy_status_set",CN="sy_status_delete",jN=t=>({type:"status",key:t}),PN=t=>a.object({parent:U.optional(),statuses:cd(t).array()}),$N=t=>a.object({statuses:ys(t).array()}),_N=a.object({keys:ps.array()}),MN=a.object({}),RN="/status/set",UN="/status/delete",ZN="/status/retrieve",LN=a.object({keys:ps.array().optional(),searchTerm:a.string().optional(),offset:a.number().optional(),limit:a.number().optional(),includeLabels:a.boolean().optional(),hasLabels:rt.array().optional()}),DN=a.object({key:ps,includeLabels:a.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),BN=a.union([DN,LN]),FN=t=>a.object({statuses:v.nullableZ(ys(t))});let ld=class{type="status";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,n=await b(this.client,ZN,t,BN,FN(t.detailsSchema));ue("Status",t,n.statuses,e);const r=n.statuses;return e?r[0]:r}async set(t,e={}){const n=Array.isArray(t),r=(await b(this.client,RN,{statuses:v.toArray(t),parent:e.parent},PN(e.detailsSchema),$N(e.detailsSchema))).statuses;return n?r:r[0]}async delete(t){await b(this.client,UN,{keys:v.toArray(t)},_N,MN)}};const YN=Object.freeze(Object.defineProperty({__proto__:null,Client:ld,DELETE_CHANNEL_NAME:CN,SET_CHANNEL_NAME:IN,keyZ:ps,newZ:cd,ontologyID:jN,statusZ:ys},Symbol.toStringTag,{value:"Module"})),qN="/api/v1/";class VN{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child(qN);const s=new wt.JSONCodec;this.unary=Vy(new qy(this.url,s,this.secure),n),this.stream=new Jy(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const vt=a.z.uuid(),ms=a.z.object({key:vt,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe))}),ud=ms.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),$e=a.z.uuid(),gs=a.z.object({key:$e,name:a.z.string().min(1,"Name is required"),layout:Oe.unknownZ.or(a.z.string().transform(Pe))}),hd=gs.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),dd=gs.omit({layout:!0}).extend({layout:a.z.string().transform(Pe)}),WN="/workspace/lineplot/retrieve",HN="/workspace/lineplot/create",GN="/workspace/lineplot/rename",KN="/workspace/lineplot/set-data",JN="/workspace/lineplot/delete",XN=a.z.object({key:vt,name:a.z.string()}),QN=a.z.object({key:vt,data:a.z.string()}),ex=a.z.object({keys:vt.array()}),tx=a.z.object({keys:vt.array()}),fd=a.z.object({key:vt}).transform(({key:t})=>({keys:[t]})),pd=a.z.union([fd,tx]),nx=a.z.object({linePlots:v.nullableZ(ms)}),rx=a.z.object({workspace:$e,linePlots:ud.array()}),sx=a.z.object({linePlots:ms.array()}),Vs=a.z.object({});let yd=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await b(this.client,HN,{workspace:t,linePlots:v.toArray(e)},rx,sx);return n?r.linePlots:r.linePlots[0]}async rename(t,e){await b(this.client,GN,{key:t,name:e},XN,Vs)}async setData(t,e){await b(this.client,KN,{key:t,data:JSON.stringify(e)},QN,Vs)}async retrieve(t){const e=fd.safeParse(t).success,n=await b(this.client,WN,t,pd,nx);return ue("LinePlot",t,n.linePlots,e),e?n.linePlots[0]:n.linePlots}async delete(t){await b(this.client,JN,{keys:v.toArray(t)},ex,Vs)}};const ax=t=>({type:"lineplot",key:t}),ix=Object.freeze(Object.defineProperty({__proto__:null,Client:yd,keyZ:vt,linePlotZ:ms,newZ:ud,ontologyID:ax,retrieveArgsZ:pd},Symbol.toStringTag,{value:"Module"})),Tt=a.z.uuid(),ws=a.z.object({key:Tt,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe))}),md=ws.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ox="/workspace/log/retrieve",cx="/workspace/log/create",lx="/workspace/log/rename",ux="/workspace/log/set-data",hx="/workspace/log/delete",dx=a.z.object({key:Tt,name:a.z.string()}),fx=a.z.object({key:Tt,data:a.z.string()}),px=a.z.object({keys:Tt.array()}),yx=a.z.object({keys:Tt.array()}),gd=a.z.object({key:Tt}).transform(({key:t})=>({keys:[t]})),wd=a.z.union([gd,yx]),mx=a.z.object({logs:v.nullableZ(ws)}),gx=a.z.object({workspace:$e,logs:md.array()}),wx=a.z.object({logs:ws.array()}),Ws=a.z.object({});let bd=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await b(this.client,cx,{workspace:t,logs:v.toArray(e)},gx,wx);return n?r.logs:r.logs[0]}async rename(t,e){await b(this.client,lx,{key:t,name:e},dx,Ws)}async setData(t,e){await b(this.client,ux,{key:t,data:JSON.stringify(e)},fx,Ws)}async retrieve(t){const e=gd.safeParse(t).success,n=await b(this.client,ox,t,wd,mx);return ue("Log",t,n.logs,e),e?n.logs[0]:n.logs}async delete(t){await b(this.client,hx,{keys:v.toArray(t)},px,Ws)}};const bx=t=>({type:"log",key:t}),vx=Object.freeze(Object.defineProperty({__proto__:null,Client:bd,keyZ:Tt,logZ:ws,newZ:md,ontologyID:bx,retrieveArgsZ:wd},Symbol.toStringTag,{value:"Module"})),st=a.z.uuid(),bs=a.z.object({key:st,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe)),snapshot:a.z.boolean()}),vd=bs.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Hi=bs.extend({data:a.z.string().transform(Pe)}),cn=a.z.uuid(),Td=a.z.object({key:a.z.string(),name:a.z.string(),selectors:a.z.string().array().default([]),strokeColor:a.z.string().optional(),fillColor:a.z.string().optional()}),Sd=a.z.object({key:a.z.string(),name:a.z.string(),regions:Td.array()}),zd=a.z.object({key:a.z.string(),position:vi.xy,orientation:eg.outer}),Tx=a.z.object({zoom:a.z.number().positive().default(1),position:vi.xy}),Od=a.z.object({svg:a.z.string().min(1,"SVG is required"),states:Sd.array(),variant:a.z.string().min(1,"Variant is required"),handles:zd.array(),scale:a.z.number().positive().default(1),scaleStroke:a.z.boolean().default(!1),previewViewport:Tx.default({zoom:1,position:{x:0,y:0}})}),vs=a.z.object({key:cn,version:a.z.literal(1).optional().default(1),name:a.z.string().min(1,"Name is required"),data:Od}),kd=vs.partial({key:!0}),Sx="/workspace/schematic/symbol/retrieve",zx="/workspace/schematic/symbol/create",Ox="/workspace/schematic/symbol/rename",kx="/workspace/schematic/symbol/delete",Ex="/workspace/schematic/symbol/retrieve_group",Nx=a.z.object({symbols:kd.array(),parent:U}),xx=a.z.object({key:cn,name:a.z.string()}),Ax=a.z.object({keys:cn.array()}),Ix=a.z.object({keys:cn.array().optional(),searchTerm:a.z.string().optional(),offset:a.z.number().optional(),limit:a.z.number().optional()}),Cx=a.z.object({key:cn}).transform(({key:t})=>({keys:[t]})),jx=a.z.union([Cx,Ix]),Px=a.z.object({symbols:v.nullableZ(vs)}),$x=a.z.object({symbols:vs.array()}),zc=a.z.object({}),_x=a.z.object({}),Mx=a.z.object({group:ts}),Rx="sy_schematic_symbol_set",Ux="sy_schematic_symbol_delete";let Ed=class{client;constructor(t){this.client=t}async create(t){const e="symbols"in t,n=e?t.symbols:[t],r=await b(this.client,zx,{symbols:n,parent:t.parent},Nx,$x);return e?r.symbols:r.symbols[0]}async rename(t,e){await b(this.client,Ox,{key:t,name:e},xx,zc)}async retrieve(t){const e="key"in t,n=await b(this.client,Sx,t,jx,Px);return ue("Schematic Symbol",t,n.symbols,e),e?n.symbols[0]:n.symbols}async delete(t){await b(this.client,kx,{keys:v.toArray(t)},Ax,zc)}async retrieveGroup(){return(await b(this.client,Ex,{},_x,Mx)).group}};const Zx=t=>({type:"schematic_symbol",key:t}),Lx=Object.freeze(Object.defineProperty({__proto__:null,Client:Ed,DELETE_CHANNEL_NAME:Ux,SET_CHANNEL_NAME:Rx,handleZ:zd,keyZ:cn,newZ:kd,ontologyID:Zx,regionZ:Td,specZ:Od,stateZ:Sd,symbolZ:vs},Symbol.toStringTag,{value:"Module"})),Dx="/workspace/schematic/retrieve",Bx="/workspace/schematic/create",Fx="/workspace/schematic/rename",Yx="/workspace/schematic/set-data",qx="/workspace/schematic/delete",Vx="/workspace/schematic/copy",Wx=a.z.object({key:st,name:a.z.string()}),Hx=a.z.object({key:st,data:a.z.string()}),Gx=a.z.object({keys:st.array()}),Kx=a.z.object({key:st,name:a.z.string(),snapshot:a.z.boolean()}),Jx=a.z.object({keys:st.array()}),Nd=a.z.object({key:st}).transform(({key:t})=>({keys:[t]})),xd=a.z.union([Nd,Jx]),Xx=a.z.object({schematics:v.nullableZ(Hi)}),Qx=a.z.object({workspace:$e,schematics:vd.array()}),eA=a.z.object({schematics:Hi.array()}),tA=a.z.object({schematic:bs}),Hs=a.z.object({});let Ad=class{symbols;client;constructor(t){this.client=t,this.symbols=new Ed(t)}async create(t,e){const n=Array.isArray(e),r=await b(this.client,Bx,{workspace:t,schematics:v.toArray(e)},Qx,eA);return n?r.schematics:r.schematics[0]}async rename(t,e){await b(this.client,Fx,{key:t,name:e},Wx,Hs)}async setData(t,e){await b(this.client,Yx,{key:t,data:JSON.stringify(e)},Hx,Hs)}async retrieve(t){const e=Nd.safeParse(t).success,n=await b(this.client,Dx,t,xd,Xx);return ue("Schematic",t,n.schematics,e),e?n.schematics[0]:n.schematics}async delete(t){await b(this.client,qx,{keys:v.toArray(t)},Gx,Hs)}async copy(t){return(await b(this.client,Vx,t,Kx,tA)).schematic}};const nA=t=>({type:"schematic",key:t}),rA=Object.freeze(Object.defineProperty({__proto__:null,Client:Ad,keyZ:st,newZ:vd,ontologyID:nA,remoteZ:Hi,retrieveArgsZ:xd,schematicZ:bs,symbol:Lx},Symbol.toStringTag,{value:"Module"})),St=a.z.uuid(),Gi=a.z.object({key:St,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe))}),Id=Gi.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Ki=Gi.extend({data:a.z.string().transform(Pe)}),sA="/workspace/table/retrieve",aA="/workspace/table/create",iA="/workspace/table/rename",oA="/workspace/table/set-data",cA="/workspace/table/delete",lA=a.z.object({key:St,name:a.z.string()}),uA=a.z.object({key:St,data:a.z.string()}),hA=a.z.object({keys:St.array()}),dA=a.z.object({keys:St.array()}),Cd=a.z.object({key:St}).transform(({key:t})=>({keys:[t]})),jd=a.z.union([Cd,dA]),fA=a.z.object({tables:v.nullableZ(Ki)}),pA=a.z.object({workspace:$e,tables:Id.array()}),yA=a.z.object({tables:Ki.array()}),Gs=a.z.object({});let Pd=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await b(this.client,aA,{workspace:t,tables:v.toArray(e)},pA,yA);return n?r.tables:r.tables[0]}async rename(t,e){await b(this.client,iA,{key:t,name:e},lA,Gs)}async setData(t,e){await b(this.client,oA,{key:t,data:JSON.stringify(e)},uA,Gs)}async retrieve(t){const e=Cd.safeParse(t).success,n=await b(this.client,sA,t,jd,fA);return ue("Table",t,n.tables,e),e?n.tables[0]:n.tables}async delete(t){await b(this.client,cA,{keys:v.toArray(t)},hA,Gs)}};const mA=t=>({type:"table",key:t}),gA=Object.freeze(Object.defineProperty({__proto__:null,Client:Pd,keyZ:St,newZ:Id,ontologyID:mA,remoteZ:Ki,retrieveArgsZ:jd,tableZ:Gi},Symbol.toStringTag,{value:"Module"})),Oc="/workspace/retrieve",wA="/workspace/create",bA="/workspace/rename",vA="/workspace/set-layout",TA="/workspace/delete",kc=a.z.object({keys:$e.array().optional(),searchTerm:a.z.string().optional(),author:nt.optional(),offset:a.z.number().optional(),limit:a.z.number().optional()}),SA=a.z.object({workspaces:hd.array()}),zA=a.z.object({key:$e,name:a.z.string()}),OA=a.z.object({key:$e,layout:Oe.unknownZ.transform(t=>JSON.stringify(t))}),kA=a.z.object({keys:$e.array()}),Ec=a.z.object({workspaces:v.nullableZ(gs)}),EA=a.z.object({workspaces:dd.array()}),Ks=a.z.object({}),NA="sy_workspace_set",xA="sy_workspace_delete";class $d{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new Ad(e),this.lineplots=new yd(e),this.logs=new bd(e),this.tables=new Pd(e)}async create(e){const n=Array.isArray(e),r=await b(this.client,wA,{workspaces:v.toArray(e)},SA,EA);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await b(this.client,bA,{key:e,name:n},zA,Ks)}async setLayout(e,n){await b(this.client,vA,{key:e,layout:n},OA,Ks)}async retrieve(e){let n;const r=typeof e!="string";typeof e=="string"||Array.isArray(e)?n={keys:v.toArray(e)}:n=e;const s=await b(this.client,Oc,n,kc,Ec);return r?s.workspaces:s.workspaces[0]}async retrieveByAuthor(e){return(await b(this.client,Oc,{author:e},kc,Ec)).workspaces}async delete(e){await b(this.client,TA,{keys:v.toArray(e)},kA,Ks)}}const AA=t=>({type:"workspace",key:t}),IA=Object.freeze(Object.defineProperty({__proto__:null,Client:$d,DELETE_CHANNEL_NAME:xA,SET_CHANNEL_NAME:NA,keyZ:$e,newZ:hd,ontologyID:AA,remoteZ:dd,workspaceZ:gs},Symbol.toStringTag,{value:"Module"})),_d=a.z.object({host:a.z.string({error:"Host is required"}).min(1,"Host is required"),port:a.z.number({error:"Port is required"}).or(a.z.string({error:"Port is required"})),username:a.z.string().min(1,"Username is required"),password:a.z.string().min(1,"Password is required"),connectivityPollFrequency:x.z.default(x.seconds(30)),secure:a.z.boolean().optional().default(!1),name:a.z.string().optional(),retry:ru.breakerConfigZ.optional()});class Ji extends Ah{createdAt;props;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;hardware;control;arcs;static connectivity=Pr;transport;clientVersion="0.46.0";constructor(e){const n=_d.parse(e),{host:r,port:s,username:i,password:o,connectivityPollFrequency:c,secure:l,retry:u}=n,h=new VN(new Sn({host:r,port:Number(s)}),u,l);h.use(Ib);let p;i!=null&&o!=null&&(p=new Vk(h.unary,{username:i,password:o}),h.use(p.middleware()));const f=new Ui(new Kn(h.unary)),O=new ph(h.unary,f);super(h.stream,h.unary,f),this.createdAt=C.now(),this.props=n,this.auth=p,this.transport=h,this.channels=new hh(this,f,h.unary,O),this.connectivity=new Pr(h.unary,c,this.clientVersion,n.name),this.control=new Ph(this),this.ontology=new Nu(h.unary,this);const I=new od(this.transport.unary);this.labels=new td(this.transport.unary),this.statuses=new ld(this.transport.unary),this.ranges=new ad(this,I,this.transport.unary,f,this.labels,this.ontology),this.access=new Sv(this.transport.unary),this.users=new mh(this.transport.unary),this.workspaces=new $d(this.transport.unary);const j=new Dh(this.transport.unary),w=new Gh(this.transport.unary,this,this.ontology,this.ranges),T=new Bh(this.transport.unary,w);this.hardware=new NE(w,T,j),this.arcs=new ah(this.transport.unary)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}x.seconds(1);const Js=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Xi=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},CA=(t,e)=>{let n=null;return e===0?t:(...r)=>{n===null&&(n=setTimeout(()=>{t(...r),n=null},e))}},On=".",Md=(t,e,n=".")=>{const r=t.split(n);return r.map((s,i)=>{const o=e(s,i,r);return o==null?null:typeof o=="string"?o:o.join(n)}).filter(s=>s!=null).join(n)},ln=(t,e)=>{if(!Array.isArray(t))return t[e];const n=t[e];if(n!=null||t.length==0)return n;const r=t[0];if(typeof r=="object"&&"key"in r)return t.find(s=>s.key===e)},jA=(t,e)=>{const n=t.split(".");return n.forEach((r,s)=>{e=ln(e,r),e!=null&&typeof e=="object"&&"key"in e&&(n[s]=e.key)}),n.join(".")},PA=(t,e)=>{const n=t.split(".");return e<0?n[n.length+e]:n[e]},$A=(t,e)=>{if(e.length===0)return!0;const n=t.split("."),r=e.split(".");if(r.length>n.length)return!1;for(let s=0;s<r.length;s++){const i=n[s],o=r[s];if(o!=="*"&&i!==o)return!1}return!0},It=t=>{const e=parseInt(t);return isNaN(e)||e<0||e.toString()!==t?null:e},Ma=(t,e)=>{for(let n=1;n<=e.length;n++){const r=e.slice(0,n).join(".");if(ln(t,r)!=null)return[r,n]}return null},Qi=((t,e,n={optional:!1})=>{const{optional:r,getter:s=ln}=n;if(e==="")return t;const i=e.split(".");if(i.length===1){const c=s(t,i[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${i[0]} is undefined`)}return c}const o=(c,l)=>{if(l>=i.length)return c;for(let u=i.length-l;u>=1;u--){const h=i.slice(l,l+u).join("."),p=s(c,h);if(p!==void 0){if(l+u===i.length)return p;if(p===null){if(r)return null;throw new Error(`Path ${e} does not exist. ${h} is null`)}return o(p,l+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${i[l]} is undefined`)};return o(t,0)}),_A=(t,e)=>Qi(t,e,{optional:!0})!==null,MA=t=>{try{return structuredClone(t)}catch{return console.warn("Failed to deep copy object, falling back to JSON.parse(JSON.stringify)",t),console.trace(),JSON.parse(JSON.stringify(t))}},RA=(t,e,n="")=>{const r={},s=(i,o,c)=>{if(typeof i!=typeof o||i===null||o===null){r[c]=[i,o];return}if(typeof i=="object"&&typeof o=="object")if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length){r[c]=[i,o];return}for(let l=0;l<i.length;l++)s(i[l],o[l],`${c}[${l}]`)}else new Set([...Object.keys(i),...Object.keys(o)]).forEach(l=>{s(i[l],o[l],c!==""?`${c}.${l}`:l)});else i!==o&&(r[c]=[i,o])};return s(t,e,n),r},Ra=(t,e)=>{const n=Array.isArray(t),r=Array.isArray(e);if(n!==r)return!1;if(n&&r){const o=t,c=e;if(o.length!==c.length)return!1;for(let l=0;l<o.length;l++)if(!Ra(o[l],c[l]))return!1;return!0}if(t==null||e==null||typeof t!="object"||typeof e!="object")return t===e;if("equals"in t)return t.equals(e);const s=Object.keys(t),i=Object.keys(e);if(s.length!==i.length)return!1;for(const o of s){const c=t[o],l=e[o];if(typeof c=="object"&&typeof l=="object"){if(!Ra(c,l))return!1}else if(c!==l)return!1}return!0},Rd=(t,e)=>{if(typeof t!="object"||t==null)return t===e;const n=Object.keys(t),r=Object.keys(e);if(r.length>n.length)return!1;for(const s of r){const i=t[s],o=e[s];if(typeof i=="object"&&typeof o=="object"){if(!Rd(i,o))return!1}else if(i!==o)return!1}return!0},Ua=(t,...e)=>{if(e.length===0)return t;const n=e.shift();if(Js(t)&&Js(n))for(const r in n)try{Js(n[r])?(r in t||Object.assign(t,{[r]:{}}),Ua(t[r],n[r])):Object.assign(t,{[r]:n[r]})}catch(s){throw s instanceof TypeError?new TypeError(`.${r}: ${s.message}`):s}return Ua(t,...e)},UA=(t,e,n)=>{const r=(s,i,o)=>{if(o.def?.type==="union")return o.def.options.reduce((c,l)=>r(c,i,l),s);if(o.def?.type==="intersection"){const c=r(s,i,o.def.left);return r(c,i,o.def.right)}for(const c in i){const l=i[c];let u=o?.shape;if(u!=null)for(;u!=null;){if(u[c]!=null){const h=u[c].safeParse(l);if(h.success){s[c]=h.data;break}}u=u.def?.shape}typeof l=="object"&&!Array.isArray(l)&&l!==null&&o&&o.shape&&o.shape[c]&&(s[c]||={},r(s[c],l,o.shape[c]))}return s};return r({...t},e,n)},ZA=(t,e)=>{const n=e.split(On);let r=t,s=0;for(;s<n.length;){if(s===n.length-1){const o=n[s];if(Array.isArray(r)){const c=parseInt(o);if(!isNaN(c)&&c<r.length){r.splice(c,1);return}const l=r[0];if(typeof l=="object"&&"key"in l){const u=r.findIndex(h=>h.key===o);if(u!==-1){r.splice(u,1);return}}return}delete r[o];return}let i=!1;if(Array.isArray(r)&&r.length>0){const o=r[0];if(typeof o=="object"&&"key"in o)for(let c=n.length-s;c>=1;c--){const l=n.slice(s,s+c).join(On),u=r.find(h=>h.key===l);if(u!=null){if(s+c===n.length){const h=r.findIndex(p=>p.key===l);h!==-1&&r.splice(h,1);return}r=u,s+=c,i=!0;break}}}if(!i)for(let o=n.length-s;o>=1;o--){const c=n.slice(s,s+o).join(On);if(!Array.isArray(r)&&typeof r=="object"&&r!==null&&c in r){if(s+o===n.length){delete r[c];return}r=r[c],s+=o,i=!0;break}}if(!i){const o=ln(r,n[s]);if(o==null)return;r=o,s++}}},LA=(t,e,n)=>{const r=e.split(On);let s=t,i=0;for(;i<r.length-1;){const o=Ma(s,r.slice(i,r.length-1));let c;o!=null?[c,i]=[o[0],i+o[1]]:(c=r[i],i++);let l=ln(s,c);if(l==null){const u=r[i];let h=It(u);h==null&&u.startsWith("-")&&It(u.substring(1))!=null&&(h=0),l=h!=null?[]:{},s[c]=l}s=l}try{const o=r[r.length-1];if(Array.isArray(s)){let l=It(o);if(l==null){if(o.startsWith("-")){const u=It(o.substring(1));u!=null&&(l=s.length-u)}if(l==null){if(s.length===0){const h=It(o);if(h!=null){s[h]=n;return}}const u=s[0];if(typeof u=="object"&&"key"in u){const h=s.findIndex(p=>p.key===o);if(h!==-1){s[h]=n;return}}return}}s[l]=n;return}const c=Ma(s,[o]);if(c!=null){s[c[0]]=n;return}s[o]=n}catch(o){throw console.error("failed to set value",n,"at path",e,"on object",t),o}},Ts=Object.freeze(Object.defineProperty({__proto__:null,SEPARATOR:On,copy:MA,defaultGetter:ln,difference:RA,element:PA,equal:Ra,findBestKey:Ma,get:Qi,getIndex:It,has:_A,override:Ua,overrideValidItems:UA,partialEqual:Rd,pathsMatch:$A,remove:ZA,resolvePath:jA,set:LA,transformPath:Md},Symbol.toStringTag,{value:"Module"}));let DA=class{handlers;transform;closer;constructor(e,n){this.transform=e,this.handlers=n??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let n=e;if(this.transform!=null){const[r,s]=this.transform(e);if(!s)return;n=r}this.handlers.forEach((r,s)=>s(n))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}};class BA{handlers;constructor(e){this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((n,r)=>r(e))}}const eo=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:BA,Observer:DA},Symbol.toStringTag,{value:"Module"}));let FA=class{sender;handlers;constructor(e){this.sender=e,this.handlers=new Map}handle({data:e}){const n=this.handlers.get(e.type)?.handler;n==null?console.warn(`No handler for ${e.type}`):n(e.payload)}route(e){const n=YA(e,this.sender),r=new qA(n);return this.handlers.set(e,r),r}};const YA=(t,e)=>(n,r)=>e({type:t,payload:n},r);class qA{_send;handler;constructor(e){this._send=e,this.handler=null}send(e,n=[]){this._send(e,n)}handle(e){this.handler=e}}const Za=(t,e,n="")=>{try{return t.parse(e)}catch(r){if(r instanceof a.z.ZodError){const s=r.issues.map(i=>i.path.length===0?i.message:`${i.path.join(".")}: ${i.message}`);throw new Error(`${n} - ${s.join(`
|
|
64
|
-
`)}`)}else throw r}},Ud=t=>typeof t=="function",to=(t,e)=>Ud(t)?t(e):t,Zd=t=>e=>e==null?void 0:t(e),Ss=t=>Ld(t)?t():t,Ld=t=>typeof t=="function",Dd=({initial:t,value:e,onChange:n})=>{const[r,s]=ai.useState(e??t);return e!=null&&n!=null?[e,n]:[r,s]},Bd=({initial:t,value:e,onChange:n})=>{const[r,s]=ai.useState(Ss(e??t));return e!=null&&n!=null?[e,n]:[r,s]},VA=(t,e)=>{const[n,r]=ai.useState(()=>{const s=localStorage.getItem(e);return s==null?Ss(t):JSON.parse(s)});return[n,s=>{r(s),localStorage.setItem(e,JSON.stringify(s))}]},WA=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:Ss,executeSetter:to,isInitialSetter:Ld,isSetter:Ud,skipNull:Zd,usePassthrough:Dd,usePersisted:VA,usePurePassthrough:Bd},Symbol.toStringTag,{value:"Module"}));let Nc=null;const HA=()=>(Nc??=document.createElement("canvas"),Nc),GA=(t,e,n)=>{if(d.S.RUNTIME==="node")return{width:0,height:0};n??=HA().getContext("2d"),n.font=e;const r=n.measureText(t);return zs(r)},zs=t=>({width:Math.trunc(Math.abs(t.actualBoundingBoxLeft)+Math.abs(t.actualBoundingBoxRight)),height:Math.trunc(Math.abs(t.actualBoundingBoxAscent)+Math.abs(t.actualBoundingBoxDescent))}),kn=["h1","h2","h3","h4","h5","p","small"],KA=a.z.enum(kn),JA=t=>{const e=kn.indexOf(t);return e===-1||e===kn.length-1?t:kn[e+1]},XA=a.z.union([a.z.number(),a.z.enum(["normal","bold","bolder","lighter"])]),Ve=a.z.object({size:a.z.number(),weight:a.z.union([a.z.number(),a.z.string()]),lineHeight:a.z.number(),textTransform:a.z.string().optional()}),QA={tiny:"small",small:"small",medium:"p",large:"h5",huge:"h2"},eI={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"},tI=a.z.object({l0:d.kr.colorZ,l1:d.kr.colorZ,l2:d.kr.colorZ,l3:d.kr.colorZ,l4:d.kr.colorZ,l5:d.kr.colorZ,l6:d.kr.colorZ,l7:d.kr.colorZ,l8:d.kr.colorZ,l9:d.kr.colorZ,l10:d.kr.colorZ,l11:d.kr.colorZ}),fe=(t,e)=>[t[0],t[1],e,t[3]],nI=a.z.object({m2:d.kr.colorZ,m1:d.kr.colorZ,z:d.kr.colorZ,p1:d.kr.colorZ,p2:d.kr.colorZ}),pr=nI.or(d.kr.colorZ.transform(t=>{const e=d.kr.hsla(t);return{m2:d.kr.fromHSLA(fe(e,40)),m1:d.kr.fromHSLA(fe(e,45)),z:t,p1:d.kr.fromHSLA(fe(e,55)),p2:d.kr.fromHSLA(fe(e,65))}})),Fd=a.z.object({name:a.z.string(),key:a.z.string(),colors:a.z.object({border:d.kr.colorZ,primary:pr,gray:tI,error:pr,secondary:pr,warning:pr,palettes:a.z.record(a.z.string(),d.kr.paletteZ),visualization:a.z.object({palettes:a.z.record(a.z.string(),a.z.array(d.kr.colorZ))}).optional().default({palettes:{}}),white:d.kr.colorZ,black:d.kr.colorZ,text:d.kr.colorZ,textInverted:d.kr.colorZ,textOnPrimary:d.kr.colorZ.optional().default(d.kr.ZERO),logo:a.z.string()}),sizes:a.z.object({base:a.z.number(),border:a.z.object({radius:a.z.number(),width:a.z.number(),thickWidth:a.z.number()}),schematic:a.z.object({elementStrokeWidth:a.z.number()})}),typography:a.z.object({family:a.z.string(),codeFamily:a.z.string(),h1:Ve,h2:Ve,h3:Ve,h4:Ve,h5:Ve,p:Ve,small:Ve})}).transform(t=>((t.colors.textOnPrimary==null||d.kr.isZero(t.colors.textOnPrimary))&&(t.colors.textOnPrimary=d.kr.pickByContrast(t.colors.primary.z,t.colors.text,t.colors.textInverted)),t)),rI='"Inter Variable", sans-serif',sI='"Geist Mono", monospace',aI=6,hn=[357,91,55,1],dn=[48,90,55,1],iI=["#FEFEFE","#FAFAFA","#F2F2F2","#ECECEC","#E4E4E4","#D1D1D1","#BCBCBC","#ACACAC","#8F8F8F","#4F4F4F","#292929","#050505"],fn=Object.fromEntries(iI.map((t,e)=>[`l${e}`,t])),oI=()=>typeof window>"u"?!1:window.devicePixelRatio>1,cI=oI(),La={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:fn,border:fn.l4,error:{m2:d.kr.fromHSLA(fe(hn,30)),m1:d.kr.fromHSLA(fe(hn,40)),z:d.kr.fromHSLA(hn),p1:d.kr.fromHSLA(fe(hn,65)),p2:d.kr.fromHSLA(fe(hn,77))},warning:{m2:d.kr.fromHSLA(fe(dn,30)),m1:d.kr.fromHSLA(fe(dn,40)),z:d.kr.fromHSLA(dn),p1:d.kr.fromHSLA(fe(dn,65)),p2:d.kr.fromHSLA(fe(dn,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:fn.l11,textInverted:fn.l0,textOnPrimary:fn.l0},sizes:{base:aI,border:{radius:3,width:cI?.5:1,thickWidth:1},schematic:{elementStrokeWidth:2}},typography:{family:rI,codeFamily:sI,h1:{size:5.5,weight:"500",lineHeight:5.5*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}}},Yd=Object.freeze({...La,key:"synnaxLight",name:"Synnax Light"}),lI=["#020202","#080808","#151515","#202020","#272727","#3B3B3B","#4A4A4A","#5C5C5C","#767676","#959595","#dadada","#FAFAFA"],pn=Object.fromEntries(lI.map((t,e)=>[`l${e}`,t])),qd=Object.freeze({...La,key:"synnaxDark",name:"Synnax Dark",colors:{...La.colors,gray:pn,logo:"var(--pluto-text-color)",border:pn.l4,text:pn.l11,textInverted:pn.l0,textOnPrimary:pn.l11}}),uI={synnaxDark:qd,synnaxLight:Yd},Vd=["tiny","small","medium","large","huge"],Wd=a.z.enum(Vd),hI=t=>Wd.safeParse(t).success;class Dt{_noop=!1;key;path;serviceName;constructor(e,n,r="",s=!1){this.key=e,this.path=n,this.serviceName=r,this._noop=s}child(e){return new Dt(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}static NOOP=new Dt("","","")}const Da=["debug","info","warn","error"],Hd=t=>{const e=Da.indexOf(t);return({level:n})=>Da.indexOf(n)>=e},dI=t=>{const{include:e,exclude:n}=t;return({path:r})=>!(e!=null&&!e.some(s=>r.startsWith(s))||n!=null&&n.some(s=>r.startsWith(s)))};class Bt{meta=Dt.NOOP;filters;constructor(e={}){const{filters:n=[]}=e;this.filters=n}filter(e){return!this.meta.noop&&this.filters.every(n=>n({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const n=new Bt({filters:this.filters});return n.meta=e,n}debug(e,n,r=!1){!this.filter("debug")&&!r||(n==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,yr(n)))}info(e,n,r=!1){!this.filter("info")&&!r||(n==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,yr(n)))}warn(e,n,r=!1){!this.filter("warn")&&!r||(n==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,yr(n)))}error(e,n,r=!1){!this.filter("error")&&!r||(n==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,yr(n)))}static NOOP=new Bt}const yr=t=>typeof t=="function"?t():t;var fI=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},dt="1.9.0",xc=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function pI(t){var e=new Set([t]),n=new Set,r=t.match(xc);if(!r)return function(){return!1};var s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(s.prerelease!=null)return function(c){return c===t};function i(c){return n.add(c),!1}function o(c){return e.add(c),!0}return function(c){if(e.has(c))return!0;if(n.has(c))return!1;var l=c.match(xc);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||s.major!==u.major?i(c):s.major===0?s.minor===u.minor&&s.patch<=u.patch?o(c):i(c):s.minor<=u.minor?o(c):i(c)}}var yI=pI(dt),mI=dt.split(".")[0],_n=Symbol.for("opentelemetry.js.api."+mI),Mn=fI;function no(t,e,n,r){var s;r===void 0&&(r=!1);var i=Mn[_n]=(s=Mn[_n])!==null&&s!==void 0?s:{version:dt};if(!r&&i[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return n.error(o.stack||o.message),!1}if(i.version!==dt){var o=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+dt);return n.error(o.stack||o.message),!1}return i[t]=e,n.debug("@opentelemetry/api: Registered a global for "+t+" v"+dt+"."),!0}function Rn(t){var e,n,r=(e=Mn[_n])===null||e===void 0?void 0:e.version;if(!(!r||!yI(r)))return(n=Mn[_n])===null||n===void 0?void 0:n[t]}function ro(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+dt+".");var n=Mn[_n];n&&delete n[t]}var gI=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},wI=function(t,e,n){if(arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))},bI=(function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return yn("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return yn("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return yn("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return yn("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return yn("verbose",this._namespace,e)},t})();function yn(t,e,n){var r=Rn("diag");if(r)return n.unshift(e),r[t].apply(r,wI([],gI(n),!1))}var ce;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(ce||(ce={}));function vI(t,e){t<ce.NONE?t=ce.NONE:t>ce.ALL&&(t=ce.ALL),e=e||{};function n(r,s){var i=e[r];return typeof i=="function"&&t>=s?i.bind(e):function(){}}return{error:n("error",ce.ERROR),warn:n("warn",ce.WARN),info:n("info",ce.INFO),debug:n("debug",ce.DEBUG),verbose:n("verbose",ce.VERBOSE)}}var TI=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},SI=function(t,e,n){if(arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))},zI="diag",Un=(function(){function t(){function e(s){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var c=Rn("diag");if(c)return c[s].apply(c,SI([],TI(i),!1))}}var n=this,r=function(s,i){var o,c,l;if(i===void 0&&(i={logLevel:ce.INFO}),s===n){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof i=="number"&&(i={logLevel:i});var h=Rn("diag"),p=vI((c=i.logLevel)!==null&&c!==void 0?c:ce.INFO,s);if(h&&!i.suppressOverrideMessage){var f=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";h.warn("Current logger will be overwritten from "+f),p.warn("Current logger will overwrite one already registered from "+f)}return no("diag",p,n,!0)};n.setLogger=r,n.disable=function(){ro(zI,n)},n.createComponentLogger=function(s){return new bI(s)},n.verbose=e("verbose"),n.debug=e("debug"),n.info=e("info"),n.warn=e("warn"),n.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t})(),OI=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},kI=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},EI=(function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var n=this._entries.get(e);if(n)return Object.assign({},n)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var n=OI(e,2),r=n[0],s=n[1];return[r,s]})},t.prototype.setEntry=function(e,n){var r=new t(this._entries);return r._entries.set(e,n),r},t.prototype.removeEntry=function(e){var n=new t(this._entries);return n._entries.delete(e),n},t.prototype.removeEntries=function(){for(var e,n,r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var i=new t(this._entries);try{for(var o=kI(r),c=o.next();!c.done;c=o.next()){var l=c.value;i._entries.delete(l)}}catch(u){e={error:u}}finally{try{c&&!c.done&&(n=o.return)&&n.call(o)}finally{if(e)throw e.error}}return i},t.prototype.clear=function(){return new t},t})();Un.instance();function NI(t){return t===void 0&&(t={}),new EI(new Map(Object.entries(t)))}function xI(t){return Symbol.for(t)}var AI=(function(){function t(e){var n=this;n._currentContext=e?new Map(e):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,s){var i=new t(n._currentContext);return i._currentContext.set(r,s),i},n.deleteValue=function(r){var s=new t(n._currentContext);return s._currentContext.delete(r),s}}return t})(),II=new AI,CI={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},jI={set:function(t,e,n){t!=null&&(t[e]=n)}},PI=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},$I=function(t,e,n){if(arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))},_I=(function(){function t(){}return t.prototype.active=function(){return II},t.prototype.with=function(e,n,r){for(var s=[],i=3;i<arguments.length;i++)s[i-3]=arguments[i];return n.call.apply(n,$I([r],PI(s),!1))},t.prototype.bind=function(e,n){return n},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),MI=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},RI=function(t,e,n){if(arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))},Xs="context",UI=new _I,Gd=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return no(Xs,e,Un.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,n,r){for(var s,i=[],o=3;o<arguments.length;o++)i[o-3]=arguments[o];return(s=this._getContextManager()).with.apply(s,RI([e,n,r],MI(i),!1))},t.prototype.bind=function(e,n){return this._getContextManager().bind(e,n)},t.prototype._getContextManager=function(){return Rn(Xs)||UI},t.prototype.disable=function(){this._getContextManager().disable(),ro(Xs,Un.instance())},t})(),Ba;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Ba||(Ba={}));var ZI=Gd.getInstance(),LI=(function(){function t(){}return t.prototype.inject=function(e,n){},t.prototype.extract=function(e,n){return e},t.prototype.fields=function(){return[]},t})(),so=xI("OpenTelemetry Baggage Key");function Kd(t){return t.getValue(so)||void 0}function DI(){return Kd(Gd.getInstance().active())}function BI(t,e){return t.setValue(so,e)}function FI(t){return t.deleteValue(so)}var Qs="propagation",YI=new LI,qI=(function(){function t(){this.createBaggage=NI,this.getBaggage=Kd,this.getActiveBaggage=DI,this.setBaggage=BI,this.deleteBaggage=FI}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return no(Qs,e,Un.instance())},t.prototype.inject=function(e,n,r){return r===void 0&&(r=jI),this._getGlobalPropagator().inject(e,n,r)},t.prototype.extract=function(e,n,r){return r===void 0&&(r=CI),this._getGlobalPropagator().extract(e,n,r)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){ro(Qs,Un.instance())},t.prototype._getGlobalPropagator=function(){return Rn(Qs)||YI},t})(),VI=qI.getInstance();const Ac=["bench","debug","prod"],WI=t=>e=>Ac.indexOf(e)>=Ac.indexOf(t);class Zn{meta=Dt.NOOP;otelTracer;filter;constructor(e,n=WI("debug")){this.otelTracer=e,this.filter=n}child(e){const n=new Zn(this.otelTracer,this.filter);return n.meta=e,n}debug(e,n){return this.trace(e,"debug",n)}bench(e,n){return this.trace(e,"bench",n)}prod(e,n){return this.trace(e,"prod",n)}trace(e,n,r){const s=this.meta.noop||!this.filter(n)||this.otelTracer==null;if(r==null){if(s)return()=>{};const i=new Fa(e,this.otelTracer.startSpan(e));return i.start(),()=>i.end()}return s?r(new Jd(e)):this.otelTracer.startActiveSpan(e,i=>{const o=new Fa(e,i);return r(o)})}propagate(e){if(this.meta.noop)return;const n=ZI.active();VI.inject(n,e,{set:(r,s,i)=>{r[s]=i}})}static NOOP=new Zn}class Fa{key;otel;constructor(e,n){this.key=e,this.otel=n}set(e,n){this.otel.setAttribute(e,n)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:Ba.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 Jd{key;constructor(e){this.key=e}set(){}recordError(e){}}class Ft{meta;T;L;constructor({key:e="",serviceName:n="",logger:r=Bt.NOOP,tracer:s=Zn.NOOP,noop:i=!1,__meta:o}){this.meta=o??new Dt(e,e,n,i),this.T=s.child(this.meta),this.L=r.child(this.meta)}child(e){const n=this.meta.child(e);return new Ft({__meta:n,tracer:this.T,logger:this.L})}static NOOP=new Ft({noop:!0})}const HI=Ft.NOOP,Te=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:Ft,LOG_LEVELS:Da,Logger:Bt,NOOP:HI,NoopSpan:Jd,Tracer:Zn,_Span:Fa,logLevelKeyFiler:dI,logThresholdFilter:Hd},Symbol.toStringTag,{value:"Module"})),ea=(t,e)=>t instanceof Error?(t.message=`[${e}] - ${t.message}`,t):new Error(e??"unknown error",{cause:t});class Os{type;key;sender;_internalState;_state;_prevState;_deleted=!1;parentCtxValues;childCtxValues;childCtxChangedKeys;instrumentation;schema=void 0;constructor({key:e,type:n,sender:r,instrumentation:s,parentCtxValues:i}){this.type=n,this.key=e,this.sender=r,this._internalState={},this.instrumentation=s.child(this.toString()),this.parentCtxValues=new Map,i?.forEach((o,c)=>this.parentCtxValues.set(c,o)),this.childCtxValues=new Map,this.childCtxChangedKeys=new Set}get _schema(){if(this.schema==null)throw new D(`[AetherLeaf] - expected subclass to define component schema, but none was found.
|
|
65
|
-
Make sure to define a property 'schema' on the class.`);return this.schema}setState(e){const n=to(e,this.state);this._prevState=d.Br(this._state),this._state=Za(this._schema,n,`${this.toString()}`),this.sender.send({variant:"update",key:this.key,state:this._state})}get state(){if(this._state==null)throw new ee(`[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 n=this.parentCtxValues.get(e);if(n===void 0)throw new Ue(`Context value for ${e} not found on ${this.toString()}`);return n},getOptional:e=>this.parentCtxValues.get(e),has:e=>this.parentCtxValues.has(e),wasSetPreviously:e=>this.childCtxValues.has(e),set:(e,n,r=!0)=>{this.childCtxValues.set(e,n),r&&this.childCtxChangedKeys.add(e)}}}toString(){return`${this.type}(${this.key})`}_updateState({path:e,state:n}){if(!this.deleted)try{const r=this.instrumentation.T.debug(`${this.toString()}:updateState`);this.validatePath(e);const s=Za(this._schema,n,`${this.toString()}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:Ts.difference(this.state,s)})):this.instrumentation.L.debug("setting initial state",{state:n,path:e}),this._prevState=this._state??s,this._state=s,this.afterUpdate(this.ctx),r()}catch(r){throw ea(r,`${this.toString()}.updateState`)}}_updateContext(e){try{const n=this.instrumentation.T.debug(`${this.toString()}:updateContext`);e.forEach((r,s)=>this.parentCtxValues.set(s,r)),this.afterUpdate(this.ctx),n()}catch(n){throw ea(n,`${this.type}.${this.key}.updateContext`)}}_delete(e){try{const n=this.instrumentation.T.debug(`${this.toString()}:delete`);this.validatePath(e),this._deleted=!0,this.afterDelete(this.ctx),n()}catch(n){throw ea(n,`[${this.toString()}:delete]`)}}afterUpdate(e){}afterDelete(e){}validatePath(e){if(e.length===0)throw new ee(`[Leaf.setState] - ${this.toString()} received an empty path`);const n=e[e.length-1];if(e.length>1)throw new ee(`[Leaf.setState] - ${this.toString()} received a subPath ${e.join(".")} but is a leaf`);if(n!==this.key)throw new ee(`[Leaf.setState] - ${this.toString()} received a key ${n} but expected ${this.key}`)}}class at extends Os{_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(n=>e.includes(n.type))}_updateState(e){const{path:n,type:r,create:s}=e;if(this.deleted)return;const i=this.parsePath(n);if(i.length===0){if(this.childCtxChangedKeys.clear(),super._updateState(e),this.childCtxChangedKeys.size==0)return;this.updateChildContexts();return}const c=i[0],l=this.getChild(c);if(l!=null)return l._updateState({...e,path:i});if(i.length>1){const h=n.slice(0,n.indexOf(c)+1).join("."),p=n.join(".");throw new ee(`Child of ${this.toString()} at path ${h} does not exist,
|
|
66
|
-
but an extended path ${p} was provided. This means that the aether
|
|
67
|
-
tree is attempting to create a new child of type ${r} (or nested children)
|
|
68
|
-
on a child that does not exist.
|
|
69
|
-
|
|
70
|
-
Children present: ${this.children.map(f=>`${f.type}:${f.key}`).join(".")}
|
|
71
|
-
|
|
72
|
-
`)}const u=s(this.childCtx());u._updateState({...e,path:i}),this._children.set(c,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((n,r)=>e(n,r,this.childCtxValues)),this.parentCtxValues.forEach((n,r)=>{this.childCtxValues.has(r)||e(n,r,this.parentCtxValues)})}}}updateChildContexts(){const e=this.childCtx();this.children.forEach(n=>n._updateContext(e))}_delete(e){const n=this.parsePath(e);if(n.length===0){for(const s of this.children)s._delete([s.key]);this._children.clear(),super._delete([this.key])}const r=this.getChild(n[0]);if(r!=null){if(n.length>1)return r._delete(n);this._children.delete(r.key),r._delete(n)}}parsePath(e,n){const[r,...s]=e;if(r==null)throw new Error(`Composite ${this.toString()} received an empty path${n!=null?` for ${n}`:""}`);if(r!==this.key)throw new ee(`[Composite.getRequiredKey] - ${this.toString()} received a key ${r} but expected ${this.key}`);return s}}const GI=a.z.object({}),KI=()=>{throw new Error("should not call create")};class He extends at{static TYPE="root";static KEY="root";comms;registry;schema=GI;constructor({comms:e,instrumentation:n=Te.Instrumentation.NOOP,registry:r}){super({key:He.KEY,type:He.TYPE,sender:e,instrumentation:n,parentCtxValues:null}),this.comms=e,this.registry=r}static render(e){const n=new He(e);return n._updateState({path:[He.KEY],type:"",state:{},create:KI}),n.comms.handle(r=>{try{n.handle(r)}catch(s){const i={name:"unknown",message:JSON.stringify(s),stack:"unknown"};s instanceof Error&&(i.name=s.name,i.message=s.message,i.stack=s.stack),n.comms.send({variant:"error",error:i})}}),n}handle(e){const{path:n,variant:r,type:s}=e;if(r==="delete"){this._delete(n);return}const{state:i}=e;this._updateState({path:n,type:s,state:i,create:o=>{const c=n[n.length-1];return this.create({key:c,type:s,parentCtxValues:o})}})}create({key:e,type:n,parentCtxValues:r}){const s=this.registry[n];if(s==null)throw new ee(`[Root.create] - ${n} not found in registry`);return new s({key:e,type:n,sender:this.comms,instrumentation:this.instrumentation,parentCtxValues:r})}}const Xd=He.render.bind(He),JI=Object.freeze(Object.defineProperty({__proto__:null,Composite:at,Leaf:Os,Root:He,render:Xd},Symbol.toStringTag,{value:"Module"})),XI=(t,e)=>Array.isArray(e)?e.some(n=>n.matches(t)):e?.matches(t)??!1,Qd=(t,e,n)=>{const r=d.Vr.fromException(t,e);return console.error(r),XI(t,n)?null:r},ef=(t,e,n,r)=>{if(typeof t=="function")return!0;const s=Qd(t,n,r);return s!=null&&e(s),!1},tf=async(t,e,n,r)=>{try{const s=t();s!=null&&await s}catch(s){const i=Qd(s,n,r);if(i!=null)return e(i)}},nf=t=>(e,n,r)=>{ef(e,t,n,r)&&tf(e,t,n,r)},rf=t=>async(e,n,r)=>{ef(e,t,n,r)&&await tf(e,t,n,r)},sf=a.z.object({statuses:d.Vr.statusZ().array()}),_r="status.aggregator";class Ya extends at{static TYPE="status.Aggregator";schema=sf;afterUpdate(e){e.wasSetPreviously(_r)||e.set(_r,{add:this.add.bind(this),create:d.Vr.create})}add(e){this.setState(n=>({...n,statuses:[...n.statuses,d.Vr.create(e)]}))}}const ks=t=>t.get(_r).add,QI=t=>{const e=t.getOptional(_r);return e!=null?e.add:()=>{}},Es=t=>nf(ks(t)),eC=t=>rf(ks(t)),tC={[Ya.TYPE]:Ya},qa="pluto-theming-context",af=a.z.object({name:a.z.string(),url:a.z.string()}),nC=a.z.object({theme:Fd,fontURLs:a.z.array(af)});let Va=class of extends at{static TYPE="theming.Provider";static z=nC;schema=of.z;afterUpdate(e){if(e.getOptional(qa)!=null&&this.state.theme.key===this.prevState.theme.key)return;e.set(qa,this.state.theme),Es(e)(async()=>{await this.loadFonts()},"failed to load theme fonts")}async loadFonts(){await Promise.all(this.state.fontURLs.map(async({name:e,url:n})=>{const r=new FontFace(e,`url(${n})`);try{await r.load(),self.fonts.add(r)}catch(s){console.error(s)}}))}};const rC=t=>t.get(qa),sC={[Va.TYPE]:Va},cf=a.z.object({include:a.z.string().array().optional(),exclude:a.z.string().array().optional(),level:a.z.enum(Te.LOG_LEVELS).optional().default("info")}),Wa="alamos-provider";let Ha=class extends at{static TYPE="alamos.Provider";schema=cf;afterUpdate(e){if(e.getOptional(Wa)!=null)return;const r=[],{include:s,exclude:i,level:o}=this.state;(s!=null||i!=null)&&r.push(Te.logLevelKeyFiler({include:s,exclude:i})),o!=null&&r.push(Te.logThresholdFilter(o)),r.length===0&&r.push(()=>!1),this.internal.ins=new Te.Instrumentation({key:"aether",logger:new Te.Logger({filters:r})}),e.set(Wa,this.internal.ins)}};const ao=(t,e)=>{const n=t.get(Wa);if(n==null)throw new Error("No instrumentation provider");return e==null?n:n.child(e)},aC={[Ha.TYPE]:Ha},zr=(t,e)=>d.jt.construct(d.jt.left(t)-e.x,d.jt.top(t)-e.y,d.jt.width(t)+e.x*2,d.jt.height(t)+e.y*2);class Mr{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,n,r,s=d.C.XY.IDENTITY){this.wrapped=e,this.scale_=s,this.atlasRegistry=n,this.dpr=r}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 Mr(this,this.atlasRegistry,this.dpr,e)}get canvas(){return this.wrapped.canvas}get miterLimit(){return this.cachedMiterLimit??this.wrapped.miterLimit}set miterLimit(e){const n=this.scale_.x.dim(e);n!==this.cachedMiterLimit&&(this.cachedMiterLimit=n,this.wrapped.miterLimit=n)}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,n,r,s,i,o,c,l,u){this.wrapped.drawImage(e,n,r,s,i,o!=null?this.scale_.x.pos(o):o,c!=null?this.scale_.y.pos(c):c,l!=null?this.scale_.x.dim(l):l,u!=null?this.scale_.y.dim(u):u)}beginPath(){this.wrapped.beginPath()}clip(e,n){this.wrapped.clip(e,n)}fill(e,n){if(e==null)return this.wrapped.fill();this.wrapped.fill(e,n)}isPointInPath(e,n,r,s){return this.wrapped.isPointInPath(e,n,r,s)}isPointInStroke(e,n,r){return this.wrapped.isPointInStroke(e,n,r)}stroke(e){if(e==null)return this.wrapped.stroke();this.wrapped.stroke(e)}createConicGradient(e,n,r){return this.wrapped.createConicGradient(e,n,r)}createLinearGradient(e,n,r,s){return this.wrapped.createLinearGradient(e,n,r,s)}createPattern(e,n){return this.wrapped.createPattern(e,n)}createRadialGradient(e,n,r,s,i,o){return this.wrapped.createRadialGradient(e,n,r,s,i,o)}get filter(){return this.wrapped.filter}set filter(e){this.wrapped.filter=e}createImageData(e,n,r){return this.wrapped.createImageData(e,n,r)}getImageData(e,n,r,s,i){return this.wrapped.getImageData(e,n,r,s,i)}putImageData(e,n,r,s,i,o,c){this.wrapped.putImageData(e,n,r,s,i,o,c)}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,n,r,s,i,o){this.wrapped.arc(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),s,i,o)}arcTo(e,n,r,s,i){this.wrapped.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.pos(r),this.scale_.y.pos(s),this.scale_.x.dim(i))}bezierCurveTo(e,n,r,s,i,o){this.wrapped.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.pos(r),this.scale_.y.pos(s),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.wrapped.closePath()}ellipse(e,n,r,s,i,o,c,l){this.wrapped.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s),i,o,c,l)}lineTo(e,n){this.wrapped.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(n))}moveTo(e,n){this.wrapped.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(n))}quadraticCurveTo(e,n,r,s){this.wrapped.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.pos(r),this.scale_.y.pos(s))}rect(e,n,r,s){this.wrapped.rect(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s))}roundRect(e,n,r,s,i){this.wrapped.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s),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 n=this.scale_.x.dim(e);n!==this.cachedLineWidth&&(this.cachedLineWidth=n,this.wrapped.lineWidth=n)}getLineDash(){return this.wrapped.getLineDash()}setLineDash(e){const n=Array.from(e).map(r=>this.scale_.x.dim(r));this.wrapped.setLineDash(n)}clearRect(e,n,r,s){this.wrapped.clearRect(e,n,r,s)}fillRect(e,n,r,s){this.wrapped.fillRect(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s))}strokeRect(e,n,r,s){this.wrapped.strokeRect(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s))}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,n,r,s,i={}){const[o,c]=this.checkAtlasFillStyle(i.useAtlas);if(o){this.atlasRegistry.get({font:this.font,textColor:c}).fillText(this,e,n,r);return}this.wrapped.fillText(e,this.scale_.x.pos(n),this.scale_.y.pos(r),s!=null?this.scale_.x.dim(s):void 0)}measureText(e){return this.wrapped.measureText(e)}textDimensions(e,n={}){const[r,s]=this.checkAtlasFillStyle(n.useAtlas);return r?this.atlasRegistry.get({font:this.font,textColor:s}).measureText(e):zs(this.measureText(e))}strokeText(e,n,r,s){this.wrapped.strokeText(e,this.scale_.x.pos(n),this.scale_.y.pos(r),s!=null?this.scale_.x.dim(s):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,n){this.wrapped.scale(e,n),this.dpr=e}scissor(e,n=d.Q.ZERO){const r=new iC(this.scale_);return e=zr(e,n),r.rect(...d.Q.couple(d.jt.topLeft(e)),...d._.couple(d.jt.dims(e))),this.save(),this.clip(r.getPath()),()=>this.restore()}setTransform(e,n,r,s,i,o){this.wrapped.setTransform(e,n,r,s,i,o)}transform(e,n,r,s,i,o){this.wrapped.transform(e,n,r,s,i,o)}translate(e,n){this.wrapped.translate(e,n)}}class iC{scale_;path;constructor(e=d.C.XY.IDENTITY,n){this.scale_=e,n instanceof Path2D||typeof n=="string"?this.path=new Path2D(n):this.path=new Path2D}addPath(e,n){this.path.addPath(e,n)}arc(e,n,r,s,i,o){this.path.arc(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),s,i,o)}arcTo(e,n,r,s,i){this.path.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.pos(r),this.scale_.y.pos(s),this.scale_.x.dim(i))}bezierCurveTo(e,n,r,s,i,o){this.path.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.pos(r),this.scale_.y.pos(s),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.path.closePath()}ellipse(e,n,r,s,i,o,c,l){this.path.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s),i,o,c,l)}lineTo(e,n){this.path.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(n))}moveTo(e,n){this.path.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(n))}quadraticCurveTo(e,n,r,s){this.path.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.pos(r),this.scale_.y.pos(s))}rect(e,n,r,s){this.path.rect(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s))}roundRect(e,n,r,s,i){const o=this.scaleRadii(i);this.path.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(n),this.scale_.x.dim(r),this.scale_.y.dim(s),o)}scaleRadii(e){return e==null?e:typeof e=="number"?this.scale_.x.dim(e):Array.isArray(e)?e.map(n=>this.scaleRadius(n)):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 oC=`precision mediump float;
|
|
73
|
-
|
|
74
|
-
void main(void) {
|
|
75
|
-
gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
|
|
76
|
-
}
|
|
77
|
-
`,cC=`attribute vec4 a_position;
|
|
78
|
-
|
|
79
|
-
void main(void) {
|
|
80
|
-
gl_Position = a_position;
|
|
81
|
-
}
|
|
82
|
-
`,Ic=t=>new Error(`failed to compile webgl program: ${t}`),lC=new Error("null shader encountered");let lf=class{renderCtx;prog;vertShader;fragShader;uniformLocCache=new Map;constructor(e,n,r){this.renderCtx=e;const s=e.gl.createProgram();if(s==null)throw Ic("failed to create program");this.prog=s,this.vertShader=n,this.fragShader=r,this.compile()}setAsActive(){return this.renderCtx.gl.useProgram(this.prog),()=>this.renderCtx.gl.useProgram(null)}uniformXY(e,n){this.renderCtx.gl.uniform2fv(this.getUniformLoc(e),d.Q.couple(n))}uniformColor(e,n){this.renderCtx.gl.uniform4fv(this.getUniformLoc(e),d.kr.rgba1(n))}getUniformLoc(e){const n=this.uniformLocCache.get(e);if(n!=null)return n;const r=this.renderCtx.gl.getUniformLocation(this.prog,e);if(r==null)throw new Error(`unexpected missing uniform ${e}`);return this.uniformLocCache.set(e,r),r}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,n){const r=this.renderCtx.gl,s=r.createShader(n);if(s==null)throw lC;if(r.shaderSource(s,e),r.compileShader(s),!r.getShaderParameter(s,r.COMPILE_STATUS)){const o=r.getShaderInfoLog(s);throw r.deleteShader(s),Ic(o??"unknown")}r.attachShader(this.prog,s)}};const uC=new Float32Array([0,0,0,0,0,0]);class hC extends lf{positionBuffer;constructor(e){super(e,cC,oC);const n=e.gl.createBuffer();if(n==null)throw new ee("webgl: failed to create buffer");this.positionBuffer=n,e.gl.bindBuffer(e.gl.ARRAY_BUFFER,this.positionBuffer),e.gl.bufferData(e.gl.ARRAY_BUFFER,uC,e.gl.STATIC_DRAW)}exec(){const{gl:e}=this.renderCtx,n=e.getAttribLocation(this.prog,"a_position");e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer);const r=e.createVertexArray();e.bindVertexArray(r),e.enableVertexAttribArray(n),e.vertexAttribPointer(n,2,e.FLOAT,!1,0,0),this.setAsActive(),e.drawArrays(e.TRIANGLES,0,3)}}const Cc={high:1,low:0};class uf{requests=new Map;cleanup=new Map;afterRender;instrumentation;handleError;constructor({afterRender:e,instrumentation:n=Te.Instrumentation.NOOP,handleError:r}){this.afterRender=e,this.instrumentation=n,this.handleError=r,this.start()}set(e){const n=this.requests.get(e.key);if(n==null)this.requests.set(e.key,e);else{const r=Cc[e.priority]>=Cc[n.priority],s=e.canvases.length>=n.canvases.length;r&&s&&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:n}=this;e.forEach((r,s)=>{const i=n.get(s);i!=null&&(r(i),e.delete(s))})}renderSync(){const{requests:e}=this;e.forEach(n=>{try{const r=n.render();r!=null&&this.cleanup.set(n.key,r)}catch(r){this.handleError(r,"render loop failed")}})}start(){const e=()=>{try{this.render()}catch(n){this.handleError(n,"render loop failed")}requestAnimationFrame(e)};requestAnimationFrame(e)}}const mr=2,_e=2;class io{atlas;charDims;charMap;static DEFAULT_CHARS="0123456789.:-µmsNa∞ᴇABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz%";constructor(e){const{font:n,characters:r=io.DEFAULT_CHARS,textColor:s}=e;this.charMap=new Map;const i=d.c.unique(Array.from(r)),c=new OffscreenCanvas(1,1).getContext("2d");c.font=n;const l=c.measureText("0");this.charDims=zs(l),this.charDims.width+=mr,this.charDims.height+=mr;const u=i.length,h=this.charDims.width,p=this.charDims.height,f=Math.ceil(Math.sqrt(u)),O=Math.ceil(u/f);this.atlas=new OffscreenCanvas(h*f*_e,p*(O+1)*_e);const I=this.atlas.getContext("2d");I.scale(_e,_e),I.font=n,I.textBaseline="alphabetic",I.textAlign="left",I.fillStyle=d.kr.hex(s),I.clearRect(0,0,this.atlas.width,this.atlas.height),i.forEach((j,w)=>{const T=w%f,A=Math.floor(w/f),W=T*h,J=(A+1)*p;I.fillText(j,W,J),this.charMap.set(j,w)})}fillText(e,n,r,s){const{width:i,height:o}=this.charDims,c=Math.ceil(Math.sqrt(this.charMap.size));e.textAlign==="center"&&(r-=i*n.length/2),e.textBaseline==="middle"&&(s+=o/2);for(let l=0;l<n.length;l++){const u=n[l],h=this.charMap.get(u);if(h===void 0)continue;const p=h%c,f=Math.floor(h/c);e.drawImage(this.atlas,p*i*_e,f*o*_e+mr,i*_e,o*_e,r+l*i,s-o-mr/_e,i,o)}}measureText(e){return{width:e.length*this.charDims.width,height:this.charDims.height}}}class dC{atlases;constructor(){this.atlases=new Map}get(e){const n=`${e.font}-${d.kr.hex(e.textColor)}-${e.characters}`;if(this.atlases.has(n))return this.atlases.get(n);const r=new io(e);return this.atlases.set(n,r),r}}const jc=t=>(t.textRendering="optimizeSpeed",t.imageSmoothingEnabled=!1,t);let hf=class Ct{glCanvas;upper2dCanvas;lower2dCanvas;gl;lower2d;upper2d;region;dpr;loop;clearProgram;os;static CONTEXT_KEY=d.CSS.B("render-context");instrumentation;static create(e,n,r,s,i){const o=ao(e,"render_context"),c=new Ct(n,r,s,i,o,ks(e),Es(e));return e.set(Ct.CONTEXT_KEY,c),c}constructor(e,n,r,s,i,o,c){this.upper2dCanvas=r,this.lower2dCanvas=n,this.glCanvas=e,this.os=s,this.instrumentation=i,this.dpr=1;const l=this.lower2dCanvas.getContext("2d");if(l==null)throw new Error("Could not get 2D context");const u=new dC;this.lower2d=jc(new Mr(l,u,this.dpr));const h=this.upper2dCanvas.getContext("2d");if(h==null)throw new Error("Could not get 2D context");this.upper2d=jc(new Mr(h,u,this.dpr));const p={preserveDrawingBuffer:!0,powerPreference:"high-performance",stencil:!1,depth:!1},f=this.glCanvas.getContext("webgl2",p);if(f==null)throw new Error("Could not get WebGL context");f.disable(f.DEPTH_TEST),f.disable(f.STENCIL_TEST),f.disable(f.CULL_FACE),f.disable(f.DITHER),this.gl=f,this.glCanvas.oncontextlost=()=>o({variant:"error",message:"WebGL context lost"});const O=()=>{this.gl.flush(),this.gl.finish()};this.loop=new uf({afterRender:O,instrumentation:this.instrumentation,handleError:c}),this.region=d.jt.ZERO,this.os==="Windows"&&(this.clearProgram=new hC(this))}static useOptional(e){return e.getOptional(Ct.CONTEXT_KEY)}static use(e){return e.get(Ct.CONTEXT_KEY)}update(e){e.set(Ct.CONTEXT_KEY,this)}resize(e,n){d.jt.equals(this.region,e)&&this.dpr===n||(this.region=e,this.dpr=n,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,d.jt.width(e)*n,d.jt.height(e)*n))}resizeCanvas(e){e.width=d.jt.width(this.region)*this.dpr,e.height=d.jt.height(this.region)*this.dpr}get aspect(){return d.jt.aspect(this.region)}scaleRegion(e){return new d.C.XY(d.C.Scale.scale(0,1).scale(d.jt.width(e)).translate(d.jt.left(e)).reBound(d.jt.width(this.region)).scale(-1,1),d.C.Scale.scale(0,1).scale(d.jt.height(e)).invert().translate(d.jt.top(e)).reBound(d.jt.height(this.region)).scale(-1,1).invert())}scissor(e,n=d.Q.ZERO,r){const s=[];return r.includes("upper2d")&&s.push(this.upper2d.scissor(e,n)),r.includes("lower2d")&&s.push(this.lower2d.scissor(e,n)),r.includes("gl")&&s.push(this.scissorGL(e,n)),()=>s.forEach(i=>i())}scissorGL(e,n=d.Q.ZERO){return this.gl.enable(this.gl.SCISSOR_TEST),e=zr(e,n),this.gl.scissor(d.jt.left(e)*this.dpr,(d.jt.height(this.region)-d.jt.bottom(e))*this.dpr,d.jt.width(e)*this.dpr,d.jt.height(e)*this.dpr),()=>this.gl.disable(this.gl.SCISSOR_TEST)}erase(e,n=d.Q.ZERO,...r){n=d.Q.construct(n),r.length===0&&(r=["upper2d","lower2d","gl"]),r.includes("upper2d")&&this.eraseCanvas(this.upper2d,e,n),r.includes("lower2d")&&this.eraseCanvas(this.lower2d,e,n),r.includes("gl")&&this.eraseGL(e,n)}eraseGL(e,n=d.Q.ZERO){const{gl:r}=this,s=this.scissorGL(zr(e,n));r.clearColor(...d.kr.rgba1(d.kr.ZERO)),r.clear(r.COLOR_BUFFER_BIT),this.os==="Windows"&&this.clearProgram?.exec(),s()}eraseCanvas(e,n,r=d.Q.ZERO){const s=zr(n,r);e.clearRect(...d.Q.couple(d.jt.topLeft(s)),...d._.couple(d.jt.dims(s)))}};const df=a.z.object({region:d.jt.box,enabled:a.z.boolean().optional().default(!1)}),Pc=["gl","lower2d","upper2d"];class Ga extends Os{static TYPE="eraser";schema=df;afterUpdate(e){this.deleted||(this.internal.renderCtx=hf.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:Pc})}render(){this.deleted||!this.state.enabled||this.internal.renderCtx.erase(this.state.region,d.Q.construct(0),...Pc)}}const fC={[Ga.TYPE]:Ga};class it extends eo.Observer{cleanup(){}}class Ka extends it{static TYPE="noop-boolean-sink";set(){}}const pC={type:Ka.TYPE,props:{},variant:"sink",valueType:"boolean"};class Ja extends it{static TYPE="noop-numeric-sink";set(){}}const yC={type:Ja.TYPE,props:{},variant:"sink",valueType:"number"};class Xa extends it{static TYPE="noop-boolean-source";value(){return!1}}const mC={type:Xa.TYPE,props:{},variant:"source",valueType:"boolean"};class Qa extends it{static TYPE="noop-numeric-source";value(){return 0}}const gC={type:Qa.TYPE,props:{},variant:"source",valueType:"number"};class ei extends it{static TYPE="noop-string-source";value(){return""}}const wC={type:ei.TYPE,props:{},variant:"source",valueType:"string"};class ti extends it{static TYPE="noop-status-source";value(){return{key:"noop",name:"noop",variant:"disabled",message:"unknown",time:d.r.now()}}}const bC={type:ti.TYPE,props:{},variant:"source",valueType:"status"};class ni extends it{static TYPE="noop-color-source";value(){return d.kr.ZERO}}const vC={type:ni.TYPE,props:{},variant:"source",valueType:"color"};class ri extends it{static TYPE="noop-series";value(){return[d.H.ZERO,new d.Oe([])]}}const TC={type:ri.TYPE,props:{},variant:"source",valueType:"series"},SC={[Ka.TYPE]:Ka,[Ja.TYPE]:Ja,[Xa.TYPE]:Xa,[Qa.TYPE]:Qa,[ti.TYPE]:ti,[ni.TYPE]:ni,[ei.TYPE]:ei,[ri.TYPE]:ri};class ff{type="noop";create(e){const n=SC[e.type];return n==null?null:new n}}const zC=a.z.instanceof(ArrayBuffer),tr=a.z.object({type:a.z.string(),variant:a.z.enum(["source","sink","source-transformer","sink-transformer"]),valueType:a.z.string(),props:a.z.any(),transfer:a.z.array(zC).optional()}),ot=tr.extend({variant:a.z.literal("source")}),Ns=tr.extend({variant:a.z.literal("sink")}),pf=tr.extend({variant:a.z.literal("source-transformer")}),yf=tr.extend({variant:a.z.literal("sink-transformer")}),OC=ot.extend({valueType:a.z.literal("series")}),kC=ot.extend({valueType:a.z.literal("boolean")}),EC=Ns.extend({valueType:a.z.literal("boolean")}),NC=yf.extend({valueType:a.z.literal("boolean")}),xC=pf.extend({valueType:a.z.literal("boolean")}),AC=ot.extend({valueType:a.z.literal("number")}),IC=Ns.extend({valueType:a.z.literal("number")}),CC=ot.extend({valueType:a.z.literal("color")}),jC=ot.extend({valueType:a.z.literal("status")}),PC=ot.extend({valueType:a.z.literal("string")});class xs extends eo.BaseObserver{props_=void 0;uProps_=void 0;constructor(e){super(),this.uProps_=e}get props(){if(this.props_==null){const e=this.schema.safeParse(this.uProps_);if(e.success)this.props_=e.data;else throw new D(`[BaseTelem] - expected props to be valid, but found the following errors:
|
|
83
|
-
${e.error.message}`)}return this.props_}cleanup(){}}class be extends xs{}class mf extends xs{}class zt extends be{source_=void 0;get source(){if(this.source_==null)throw new D("[UnarySourceTransformer] - expected source to exist, but none was found.");return this.source_}value(){return this.transform(this.source.value())}onChange(e){return this.source.onChange(()=>{this.shouldNotify(this.source.value())&&e()})}setSources(e){this.source_=Object.values(e)[0]}shouldNotify(e){return!0}}class gf extends be{sources={};value(){const e=Object.fromEntries(Object.entries(this.sources).map(([n,r])=>[n,r.value()]));return this.transform(e)}setSources(e){this.sources={...this.sources,...e}}}class wf extends xs{sinks={};get sink(){const[e]=Object.values(this.sinks);if(e==null)throw new D("[UnarySinkTransformer] - expected sink to exist, but none was found.");return e}set(...e){return this.sink.set(...this.transform(...e))}setSinks(e){this.sinks={...this.sinks,...e}}}const oo=a.z.object({from:a.z.string(),to:a.z.string()}),bf=a.z.object({connections:a.z.array(oo),outlet:a.z.string(),segments:a.z.record(a.z.string(),ot)});class co{type="pipeline";factory;constructor(e){this.factory=e}create(e){switch(e.type){case Rr.TYPE:return new Rr(e.props,this.factory);case Ur.TYPE:return new Ur(e.props,this.factory);default:return null}}}class Rr extends be{static TYPE="source-pipeline";schema=bf;sources={};get outlet(){const{outlet:e}=this.props,n=this.sources[e];if(n==null)throw new D(`[SourcePipeline] - expected source to exist at outlet '${e}', but none was found.`);return n}constructor(e,n){super(e);const{connections:r,segments:s}=this.props;Object.entries(s).forEach(([i,o])=>{const c=n.create(o);c!=null&&(this.sources[i]=c)}),r.forEach(({from:i,to:o})=>{const c=this.sources[i],l=this.sources[o];c==null||l==null||"setSources"in l&&l.setSources({[i]:c})})}value(){return this.outlet.value()}onChange(e){return this.outlet.onChange(e)}cleanup(){Object.values(this.sources).forEach(e=>e.cleanup?.())}}const $C=(t,e)=>({variant:"source",props:e,type:Rr.TYPE,valueType:t}),vf=a.z.object({connections:a.z.array(oo),inlet:a.z.string(),segments:a.z.record(a.z.string(),Ns)});class Ur extends mf{static TYPE="sink-pipeline";schema=vf;sinks={};get inlet(){const{inlet:e}=this.props,n=this.sinks[e];if(n==null)throw new D(`[SinkPipeline] - expected source to exist at inlet '${e}', but none was found.`);return n}constructor(e,n){super(e);const{connections:r,segments:s}=this.props;Object.entries(s).forEach(([i,o])=>{const c=n.create(o);c!=null&&(this.sinks[i]=c)}),r.forEach(({from:i,to:o})=>{const c=this.sinks[i],l=this.sinks[o];c==null||l==null||"setSinks"in c&&c.setSinks({[o]:l})})}set(...e){return this.inlet.set(...e)}cleanup(){Object.values(this.sinks).forEach(e=>e.cleanup?.())}}const _C=(t,e)=>({variant:"sink",props:e,type:Ur.TYPE,valueType:t}),Tf=a.z.object({channel:a.z.number().or(a.z.string())});class Zr extends be{static TYPE="stream-channel-value";schema=Tf;client;removeStreamHandler=null;leadingBuffer=null;valid=!1;onStatusChange;constructor(e,n,r){super(n),this.client=e,this.onStatusChange=r?.onStatusChange}get testingOnlyLeadingBuffer(){return this.leadingBuffer}get testingOnlyValid(){return this.valid}cleanup(){this.removeStreamHandler?.(),this.valid=!1,this.leadingBuffer?.release(),this.leadingBuffer=null,this.removeStreamHandler=null}value(){return d.O.isZero(this.props.channel)?NaN:(this.valid||this.read(),this.leadingBuffer==null||this.leadingBuffer.length===0?NaN:this.leadingBuffer.at(-1,!0))}async read(){try{this.valid=!0,this.removeStreamHandler?.();const e=await this.client.retrieveChannel(this.props.channel),n=r=>{const s=r.get(e.key);if(s==null)return;const i=s.series.at(-1);i!=null&&(i.acquire(),this.leadingBuffer?.release(),this.leadingBuffer=i),this.notify()};this.removeStreamHandler=await this.client.stream(n,[e.key]),this.notify()}catch(e){this.valid=!1,this.onStatusChange?.(d.Vr.fromException(e,"failed to stream channel value"))}}}const Sf=async(t,e,n)=>{const r=await t.retrieveChannel(e),s=Ca.isCalculated(r);if(!n||r.isIndex)return{key:r.key,dataType:r.dataType,virtual:r.virtual,isCalculated:s};if(s){const i=await Ca.resolveCalculatedIndex(t.retrieveChannel.bind(t),r);if(i==null)throw new Ue("Failed to resolve calculated index");return{key:(await t.retrieveChannel(i)).key,dataType:d.n.TIMESTAMP,virtual:!1,isCalculated:s}}if(r.virtual)throw new Ue("cannot use virtual channels as a data source");return{key:r.index,dataType:d.n.TIMESTAMP,virtual:!1,isCalculated:s}},MC=a.z.object({timeRange:d.m.z,channel:a.z.number().or(a.z.string()),useIndexOfChannel:a.z.boolean().optional().default(!1)});class Lr extends be{static TYPE="series-source";client;schema=MC;data=new d.Oe;valid=!1;channel=null;onStatusChange;constructor(e,n,r){super(n),this.client=e,this.onStatusChange=r?.onStatusChange}cleanup(){this.data.release(),this.valid=!1,this.channel=null}value(){const{channel:e,timeRange:n}=this.props;if(n.span.isZero||e===0)return[d.H.ZERO,this.data];this.valid||this.read();const{channel:r,data:s}=this;if(r==null)return[d.H.ZERO,this.data];let i=s.bounds;return r.dataType.equals(d.n.TIMESTAMP)&&(i=d.H.min([i,n.numericBounds])),[i,s]}async read(){try{this.valid=!0;const{timeRange:e,channel:n,useIndexOfChannel:r}=this.props;this.channel=await Sf(this.client,n,r);const s=await this.client.read(e,this.channel.key);s.acquire(),this.data=s,this.notify()}catch(e){this.valid=!1,this.onStatusChange?.(d.Vr.fromException(e,"failed to read channel data"))}}}const RC=a.z.object({channel:a.z.number().or(a.z.string()),useIndexOfChannel:a.z.boolean().optional().default(!1),timeSpan:d.a$1.z,keepFor:d.a$1.z.optional()});class Dr extends be{static TYPE="dynamic-series-source";client;data=new d.Oe([]);now;onStatusChange;channel=null;stopStreaming;valid=!1;schema=RC;constructor(e,n,r,s=()=>d.r.now()){super(n),this.client=e,this.now=s,this.onStatusChange=r?.onStatusChange}value(){const{channel:e,timeSpan:n}=this.props;if(e===0)return[d.H.ZERO,this.data];this.valid||this.read();const{data:r,channel:s}=this,i=this.now();if(s!=null&&s.dataType.isVariable)return[d.H.ZERO,this.data];const o=r.series.filter(l=>l.timeRange.end.after(i.sub(n))).map(l=>l.bounds),c=d.H.max(o);return s!=null&&s.dataType.equals(d.n.TIMESTAMP)&&(c.lower=Math.max(c.lower,c.upper-Number(n.valueOf()))),[c,this.data]}async read(){try{this.valid=!0;const{channel:e,useIndexOfChannel:n,timeSpan:r}=this.props;this.channel=await Sf(this.client,e,n);const s=this.now().spanRange(-r);if(!this.channel.virtual||this.channel.isCalculated){const o=await this.client.read(s,this.channel.key);o.acquire(),this.data.push(o)}this.stopStreaming?.();const i=o=>{if(this.channel==null)return;const c=o.get(this.channel.key);c!=null&&(c.acquire(),this.data.push(c),this.notify(),this.gcOutOfRangeData())};this.stopStreaming=await this.client.stream(i,[this.channel.key]),this.notify()}catch(e){this.valid=!1,this.onStatusChange?.(d.Vr.fromException(e,"failed to stream channel data"))}}gcOutOfRangeData(){const e=this.now().sub(this.props.keepFor??this.props.timeSpan),n=this.data.series.findIndex(r=>r.timeRange.end.before(e));n!==-1&&(this.data.series.splice(n,1).forEach(r=>r.release()),this.gcOutOfRangeData())}cleanup(){this.stopStreaming?.(),this.stopStreaming=void 0,this.data.release(),this.valid=!1}}const UC={[Lr.TYPE]:Lr,[Dr.TYPE]:Dr,[Zr.TYPE]:Zr};class zf{type="remote";client;constructor(e){this.client=e}create(e,n){const r=UC[e.type];return r==null?null:new r(this.client,e.props,n)}}const ZC=t=>({type:Lr.TYPE,props:t,variant:"source",valueType:"series"}),LC=t=>({type:Dr.TYPE,props:t,variant:"source",valueType:"series"}),DC=t=>({type:Zr.TYPE,props:t,variant:"source",valueType:"number"});class Of{type="static";create(e){switch(e.type){case si.TYPE:return new si(e.props);case Br.TYPE:return new Br(e.props);case Fr.TYPE:return new Fr(e.props);case Yr.TYPE:return new Yr(e.props);case qr.TYPE:return new qr(e.props);default:return null}}}const lo=a.z.object({data:a.z.array(d.de),offsets:a.z.array(a.z.number()).optional().default([])});class si extends be{data;schema=lo;static TYPE="static-series";constructor(e){super(e),this.data=this.props.data.map((n,r)=>new d.x({data:n,dataType:d.n.FLOAT32,timeRange:d.m.ZERO,sampleOffset:this.props.offsets[r]??0}))}value(){return[d.H.max(this.data.map(n=>n.bounds)),this.data]}}const kf=lo.extend({rate:d.v.z,yOffset:a.z.number().optional().default(0),scroll:a.z.number().optional().default(0),startPosition:a.z.number().optional().default(0),scrollBounds:a.z.boolean().optional().default(!1)});class Br extends be{static TYPE="iterative-series";schema=kf;position;interval;data;constructor(e){super(e),this.position=this.props.startPosition,this.start(this.props.rate),this.data=this.props.data.map((n,r)=>new d.x({data:n,dataType:d.n.FLOAT32,timeRange:d.m.ZERO,sampleOffset:this.props.offsets[r]??0}))}value(){const e=this.data.map(r=>r.slice(0,this.position));if(this.props.scrollBounds){const r=e[0].data[this.position-this.props.scroll<0?0:this.position-this.props.scroll],s=e[0].data[this.position-1];return[{lower:Number(r),upper:Number(s)},new d.Oe(e)]}return[d.H.max(e.map(r=>r.bounds)),new d.Oe(e)]}start(e){this.interval!=null&&clearInterval(this.interval),this.interval=setInterval(()=>{this.notify?.(),this.position++},e.period.milliseconds)}cleanup(){clearInterval(this.interval),this.interval=void 0}}const Ef=a.z.number();class Fr extends be{static TYPE="static-numeric";schema=Ef;value(){return this.props}}const Nf=a.z.string();class Yr extends be{static TYPE="static-string";schema=Nf;value(){return this.props}}const xf=d.kr.crudeZ;class qr extends be{static TYPE="static-color";schema=xf;value(){return d.kr.construct(this.props)}}const BC=t=>({type:si.TYPE,props:t,variant:"source",valueType:"series"}),FC=t=>({type:Br.TYPE,props:t,variant:"source",valueType:"series"}),YC=t=>({type:Fr.TYPE,props:t,variant:"source",valueType:"number"}),qC=t=>({type:Yr.TYPE,props:t,variant:"source",valueType:"string"}),VC=t=>({type:qr.TYPE,props:t,variant:"source",valueType:"color"});class Af{type="transformer";create(e){switch(e.type){case Yt.TYPE:return new Yt(e.props);case qt.TYPE:return new qt(e.props);case Vt.TYPE:return new Vt(e.props);case Wt.TYPE:return new Wt(e.props);case Ht.TYPE:return new Ht(e.props);case Vr.TYPE:return new Vr(e.props);case Gt.TYPE:return new Gt(e.props);case Kt.TYPE:return new Kt(e.props)}return null}}const WC=a.z.object({truthy:a.z.number().optional().default(1),falsy:a.z.number().optional().default(0)}),HC=t=>({props:t,type:Yt.TYPE,variant:"sink",valueType:"boolean"});class Yt extends wf{static TYPE="boolean-numeric-converter-sink";static propsZ=WC;schema=Yt.propsZ;transform(...e){return e.map(n=>n?this.props.truthy:this.props.falsy)}}const If=a.z.object({trueBound:d.H.bounds}),GC=t=>({props:t,type:qt.TYPE,variant:"source",valueType:"boolean"});class qt extends zt{static TYPE="boolean-source";static propsZ=If;schema=qt.propsZ;curr=null;shouldNotify(e){const n=d.H.contains(this.props.trueBound,e)!==this.curr;return this.curr=d.H.contains(this.props.trueBound,e),n}transform(e){return this.curr=d.H.contains(this.props.trueBound,e),this.curr}}const Cf=a.z.object({});class Vt extends gf{static TYPE="mean";static propsZ=Cf;schema=Vt.propsZ;transform(e){return Object.values(e).reduce((n,r)=>n+r,0)/Object.keys(e).length}}const KC=t=>({props:t,type:Vt.TYPE,variant:"source",valueType:"boolean"}),jf=a.z.object({trueVariant:d.Vr.variantZ.optional().default("success")});class Wt extends zt{static TYPE="boolean-status";static propsZ=jf;schema=Wt.propsZ;transform(e){return e.variant===this.props.trueVariant}}const JC=t=>({props:t,type:Wt.TYPE,variant:"source",valueType:"boolean"}),Pf=a.z.object({precision:a.z.number().optional().default(2),prefix:a.z.string().optional().default(""),suffix:a.z.string().optional().default(""),notation:d.zr.notationZ.optional().default("standard")});class Ht extends zt{static TYPE="stringify-number";static propsZ=Pf;schema=Ht.propsZ;transform(e){if(isNaN(e))return"";const{precision:n,prefix:r,suffix:s,notation:i}=this.props;return`${r}${d.zr.stringifyNumber(e,n,i)}${s}`}}const XC=t=>({props:t,type:Ht.TYPE,variant:"source",valueType:"string"}),$f=a.z.object({windowSize:a.z.number().optional().default(5)});class Vr extends zt{static TYPE="rolling-average";static propsZ=Cf;schema=$f;values=[];transform(e){return this.props.windowSize<2||isNaN(e)?e:this.values.reduce((n,r)=>n+r,0)/this.values.length}shouldNotify(e){return this.props.windowSize<2?!0:(this.values.length>this.props.windowSize&&(this.values=[]),this.values.push(e),this.values.length===this.props.windowSize)}}const QC=t=>({props:t,type:Vr.TYPE,variant:"source",valueType:"number"}),_f=a.z.object({gradient:d.kr.gradientZ});class Gt extends zt{static TYPE="color-gradient";static propsZ=_f;schema=Gt.propsZ;transform(e){return d.kr.fromGradient(this.props.gradient,e)}}const e1=t=>({props:t,type:Gt.TYPE,variant:"source",valueType:"color"}),Mf=a.z.object({scale:d.C.transform});class Kt extends zt{static TYPE="scale-number";static propsZ=Mf;schema=Kt.propsZ;transform(e){if(isNaN(e))return e;const{offset:n,scale:r}=this.props.scale;return e*r+n}}const t1=t=>({props:t,type:Kt.TYPE,variant:"source",valueType:"number"}),Rf=a.z.enum(["average","decimate"]),n1=a.z.object({mode:Rf,windowSize:a.z.number().optional().default(5)}),r1=t=>({props:t,type:uo.TYPE,variant:"source",valueType:"number"}),Uf=(t,e,n)=>{const r=e.length*n;for(let s=r;s<t.length;s+=n){const i=t.sub(s,s+1);i!==void 0&&e.write(i)}},s1=(t,e,n)=>{const r=e.length*n;for(let s=r;s<t.length&&!(s+n>t.length);s+=n){const i=Math.min(s+n,t.length);let o=0,c=0;for(let l=s;l<i;l++){const u=t.at(l);u!==void 0&&typeof u=="number"&&(o+=u,c++)}c>0&&e.write(new d.x({data:[o/c],dataType:t.dataType}))}},a1={decimate:Uf,average:s1};class uo{static TYPE="series-downsampler";_downsample=null;cache=new d.Oe;props;constructor(e){this.props=e}downsample(e){return this._downsample==null&&(e.series[0].sampleOffset!==0?this._downsample=Uf:this._downsample=a1[this.props.mode]),this._downsample}transform(e){if(this.props.mode==="decimate"||this.props.windowSize<=1)return e;if(e.series.length===0)return this.cache;for(;this.cache.series.length>0&&!this.cache.series[0].key.startsWith(e.series[0].key);)this.cache.series.shift();return e.series.forEach((n,r)=>{let s=this.cache.series.at(r);if(s==null){const i=Math.ceil(n.capacity/this.props.windowSize);s=d.x.alloc({key:n.key+d.Dt.create(),dataType:n.dataType,capacity:i,alignment:n.alignment,alignmentMultiple:BigInt(this.props.windowSize),sampleOffset:n.sampleOffset,timeRange:n.timeRange}),this.cache.push(s)}else if(!s.key.startsWith(n.key))throw new ee(`[SeriesDownsampler] - expected series with key ${n.key} to be in cache, but found ${s.key}`);this.downsample(e)(n,s,this.props.windowSize)}),this.cache}}const i1=t=>({props:t,type:uo.TYPE,variant:"source",valueType:"series"});class ho{factories;type="compound";constructor(e){this.factories=e}add(e){this.factories=[...this.factories.filter(n=>n.type!==e.type),e]}create(e,n){for(const r of this.factories){const s=r.create(e,n);if(s!=null)return s}return null}}const Zf=t=>{const e=[new Af,new Of,new ff],n=new ho(e);return t!=null&&n.add(new zf(t)),n.add(new co(n)),n};class As{factory;key;parent;constructor(e,n){this.factory=e,this.key=d.Dt.create(),this.parent=n}child(e,n){const r=new ho([...this.factory.factories,...d.a.toArray(e)]);return r.add(new co(r)),new As(r,n)}create(e,n){const r=this.factory.create(e,n);if(r==null)throw new ee(`Telemetry service could not find a source for type ${e.type}`);return r}}const nr="pluto-telem-context",Is=t=>t.get(nr),Lf=(t,e)=>t.set(nr,e),o1=(t,e,n)=>{const r=Is(t);if(r!=null&&n!=null&&r.key===n?.parent?.key)return n;const s=r.child(e,r);return t.set(nr,s),s};class Df{spec;wrapped;prevProv;constructor(e,n,r){this.wrapped=e,this.spec=r,this.prevProv=n}shouldUpdate(e,n){return this.prevProv.key!==e.key||!Ts.equal(this.spec,n)}}class $c extends Df{value(){return this.wrapped.value()}cleanup(){this.wrapped.cleanup?.()}onChange(e){return this.wrapped.onChange(e)}}class _c extends Df{set(...e){this.wrapped.set(...e)}cleanup(){this.wrapped.cleanup?.()}}const c1=(t,e,n,r)=>{const s=Is(t);if(n instanceof $c){if(!n.shouldUpdate(s,e))return n;n.cleanup?.()}return new $c(s.create(e,r),s,e)},l1=(t,e,n,r)=>{const s=Is(t);if(n instanceof _c){if(!n.shouldUpdate(s,e))return n;n.cleanup?.()}return new _c(s.create(e,r),s,e)},u1=a.z.object({props:_d.nullable(),state:Ji.connectivity.connectionStateZ.nullable()}),fo={client:null};class Jt extends at{static TYPE="synnax.Provider";static stateZ=u1;schema=Jt.stateZ;afterUpdate(e){if(e.wasSetPreviously(po)||ta(e,fo),this.state.props==null){this.internal.client!=null&&(this.internal.client?.close(),this.internal.client=null),ta(e,this.internal);return}this.prevState.props!=null&&Ts.equal(this.state.props,this.prevState.props)&&this.internal.client!=null||(this.internal.client=new Ji(this.state.props),ta(e,this.internal))}}const po="pluto-client-context",ta=(t,e)=>t.set(po,e),yo=t=>t.get(po)?.client??null,Bf={[Jt.TYPE]:Jt},h1=Object.freeze(Object.defineProperty({__proto__:null,Provider:Jt,REGISTRY:Bf,ZERO_CONTEXT_VALUE:fo,use:yo},Symbol.toStringTag,{value:"Module"})),Ff=(t,e)=>t.dataType.isVariable||t.dataType.equals(d.n.UINT8)?t:(e==null&&t.dataType.equals(d.n.TIMESTAMP)&&(e=BigInt(t.data[0])),t.convert(d.n.FLOAT32,e)),d1=t=>t.isVariable||t.equals(d.n.UINT8)?t:d.n.FLOAT32,Yf=()=>({purgedSeries:0,purgedBytes:d.c$1.bytes(0)}),qf={instrumentation:Te.NOOP,staleEntryThreshold:d.a$1.seconds(20)};class f1{data=[];props;constructor(e){this.props={...qf,...e}}write(e){e.length!==0&&(e.series.forEach(n=>this.writeOne(Ff(n))),this.checkIntegrity(e))}dirtyRead(e){const n=this.data.filter(({data:o})=>o.timeRange.overlapsWith(e)).map(({data:o})=>o);if(n.length===0)return{series:new d.Oe([]),gaps:[e]};const r=n.map((o,c)=>c===0?d.m.ZERO:new d.m(n[c-1].timeRange.end,o.timeRange.start)).filter(o=>!o.span.isZero&&o.isValid),s=new d.m(e.start,n[0].timeRange.start),i=new d.m(n[n.length-1].timeRange.end,e.end);return s.isValid&&!s.span.isZero&&r.unshift(s),i.isValid&&!i.span.isZero&&r.push(i),{series:new d.Oe(n),gaps:r}}gc(){const{staleEntryThreshold:e}=this.props,n=Yf(),r=this.data.filter(s=>{const i=s.data.refCount>0||d.r.since(s.addedAt).lessThan(e);return i||(n.purgedBytes=n.purgedBytes.add(s.data.byteCapacity)),i});return n.purgedSeries=this.data.length-r.length,this.data=r,n}close(){this.data=[]}writeOne(e){const{instrumentation:{L:n}}=this.props;if(e.length===0)return;const r=d.H.buildInsertionPlan(this.data.map(l=>l.data.alignmentBounds),e.alignmentBounds);if(r===null)return n.debug("Found no viable insertion plan",{inserting:e.digest,cacheContents:this.data.map(l=>l.data.digest)});const{removeBefore:s,removeAfter:i,insertInto:o,deleteInBetween:c}=r;e=e.slice(s,e.data.length-i),e.length!==0&&this.data.splice(o,c,{data:e,addedAt:d.r.now()})}checkIntegrity(e){const{instrumentation:{L:n}}=this.props,r=this.data.map(i=>i.data.alignmentBounds);if(r.some((i,o)=>r.some((c,l)=>o===l?!1:d.H.overlapsWith(i,c))))throw n.debug("Cache is in an invalid state - bounds overlap!",()=>({write:e.series.map(i=>i.digest),cacheContents:this.data.map(i=>i.data.digest)})),new Error("Invalid state")}}const p1=100,y1=1e6,m1=1e4,g1=100,w1=40;class b1{props;counter=0;curr;avgRate=0;timeOfLastWrite;totalWrites=0;now=()=>d.r.now();constructor(e){this.props=e,this.curr=null,e.now!=null&&(this.now=e.now),this.timeOfLastWrite=this.now()}get length(){return this.curr?.length??0}get leadingBuffer(){return this.curr}write(e){const n=e.series.flatMap(r=>this._write(r));return{flushed:new d.Oe(n.flatMap(r=>r.flushed.series)),allocated:new d.Oe(n.flatMap(r=>r.allocated.series))}}allocate(e,n,r){this.counter++;const s=this.props.dataType.isVariable,i=this.props.dataType.equals(d.n.TIMESTAMP);return d.x.alloc({capacity:s?e*w1:e,dataType:d1(this.props.dataType),timeRange:r.range(d.r.MAX),sampleOffset:i?r.valueOf():0,glBufferUsage:"dynamic",alignment:n,key:`dynamic-${this.counter}`})}_write(e){const n=this.nextBufferSize(),r={flushed:new d.Oe([]),allocated:new d.Oe([])};if(this.curr==null)this.curr=this.allocate(n,e.alignment,this.now()),r.allocated.push(this.curr);else if(Math.abs(Number(this.curr.alignment+BigInt(this.curr.length)-e.alignment))>1){const l=this.now();this.curr.timeRange.end=l,r.flushed.push(this.curr),this.curr=this.allocate(n,e.alignment,l),r.allocated.push(this.curr)}const s=Ff(e,this.curr.sampleOffset),i=this.curr.write(s);if(i===e.length)return this.updateAvgRate(e),r;const o=this.now();this.curr.timeRange.end=o,r.flushed.push(this.curr),this.curr=this.allocate(n,e.alignment+BigInt(i),o),r.allocated.push(this.curr);const c=this._write(e.slice(i));return r.flushed.push(c.flushed),r.allocated.push(c.allocated),r}updateAvgRate(e){if(typeof this.props.dynamicBufferSize=="number")return;const n=e.length/this.now().span(this.timeOfLastWrite).seconds;this.totalWrites>0&&isFinite(n)&&n>0&&(this.avgRate=(this.avgRate*(this.totalWrites-1)+n)/this.totalWrites),this.totalWrites++,this.timeOfLastWrite=this.now()}nextBufferSize(){const{dynamicBufferSize:e}=this.props;if(typeof e=="number")return e;if(this.totalWrites<g1)return m1;const n=d.Nr.roundToNearestMagnitude(this.avgRate*e.seconds);return Math.round(Math.max(Math.min(n,y1),p1))}close(){this.curr=null}}class v1{channel;closed=!1;ins;static;dynamic;constructor(e){this.channel=e.channel,this.ins=e.instrumentation??Te.NOOP,this.static=new f1(e),this.dynamic=new b1({dynamicBufferSize:e.dynamicBufferSize,dataType:this.channel.dataType})}writeDynamic(e){if(this.closed)return this.ins.L.warn(`Ignoring attempted dynamic write to a closed cache for channel ${this.channel.name}`),new d.Oe([]);const{flushed:n,allocated:r}=this.dynamic.write(e);return n.length>0&&this.static.write(n),r}get leadingBuffer(){return this.dynamic.leadingBuffer}writeStatic(e){if(this.closed)return this.ins.L.warn(`Ignoring attempted static write to a closed cache for channel ${this.channel.name}`);this.static.write(e)}read(e){return this.closed?(this.ins.L.warn(`Ignoring attempted dirty read from a closed cache for channel ${this.channel.name}`),{series:new d.Oe([]),gaps:[e]}):this.static.dirtyRead(e)}gc(){return this.closed?(this.ins.L.warn(`Ignoring attempted garbage collection on a closed cache for channel ${this.channel.name}`),{purgedSeries:0,purgedBytes:d.c$1.bytes(0)}):this.static.gc()}close(){this.closed=!0,this.dynamic.close(),this.static.close()}}const T1=x.seconds(60);class S1{props;cache=new Map;gcInterval;constructor(e){this.props={dynamicBufferSize:T1,gcInterval:x.seconds(30),...qf,...e},this.gcInterval=setInterval(()=>this.gc(),this.props.gcInterval.milliseconds)}async populateMissing(e){const{instrumentation:n,channelRetriever:r,dynamicBufferSize:s}=this.props,i=[];for(const c of e)this.cache.has(c)||i.push(c);if(i.length===0)return;(await r.retrieve(i)).forEach(c=>{if(this.cache.has(c.key))return;const l=new v1({channel:c,dynamicBufferSize:s,instrumentation:n.child(`cache-${c.name}-${c.key}`)});this.cache.set(c.key,l)})}get(e){const n=this.cache.get(e);if(n!=null)return n;throw new ee(`cache entry for ${e} not found`)}gc(){const{instrumentation:{L:e}}=this.props;e.info("starting garbage collection");const n=Yf();this.cache.forEach(r=>{const s=r.gc();n.purgedSeries+=s.purgedSeries,n.purgedBytes=n.purgedBytes.add(s.purgedBytes)}),e.info("garbage collection complete",{purgedSeries:n.purgedSeries,purgedBytes:n.purgedBytes.toString()},!0)}close(){clearInterval(this.gcInterval),this.cache.forEach(e=>e.close()),this.cache.clear()}}class z1{args;debouncedRead;mu=d.Xr.newMutex({requests:new Set,closed:!1});constructor(e){this.args={...e,instrumentation:e.instrumentation??Te.NOOP,batchDebounce:e.batchDebounce??d.a$1.milliseconds(50),overlapThreshold:e.overlapThreshold??d.a$1.milliseconds(5)};const n=this.args.batchDebounce.milliseconds;this.debouncedRead=Xi(()=>void this.batchRead(),n)}async read(e,n){const{cache:r}=this.args;await r.populateMissing([n]);const s=r.get(n),{series:i,gaps:o}=s.read(e);if(o.length===0)return i;const{mu:c}=this;return await new Promise((l,u)=>{c.runExclusive(async()=>{c.closed||c.requests.add({channel:n,gaps:o,resolve:l,reject:u})}),this.debouncedRead()}),s.read(e).series}async batchRead(){const{readRemote:e,cache:n,overlapThreshold:r}=this.args,{mu:s}=this;await s.runExclusive(async()=>{const i=o=>s.requests.forEach(({resolve:c,reject:l})=>o==null?c():l(o));try{if(s.closed)return i();const o=[];s.requests.forEach(({channel:c,gaps:l})=>l.forEach(u=>{const h=o.find(p=>p.gap.equals(u,r));h==null?o.push({gap:u,channels:new Set([c])}):(h.channels.add(c),h.gap=d.m.max(h.gap,u))})),await Promise.all(o.map(async({gap:c,channels:l})=>{const u=await e(c,Array.from(l));l.forEach(h=>n.get(h).writeStatic(u.get(h)))})),i()}catch(o){i(o)}finally{s.requests.clear()}})}async close(){await this.mu.runExclusive(async()=>{this.mu.closed=!0})}}const O1=new Error("request for lock canceled");var k1=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function c(h){try{u(r.next(h))}catch(p){o(p)}}function l(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class E1{constructor(e,n=O1){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,s)=>{const i={resolve:r,reject:s,weight:e,priority:n},o=Vf(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return k1(this,arguments,void 0,function*(n,r=1,s=0){const[i,o]=yield this.acquire(r,s);try{return yield n(i)}finally{o()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),N1(this._weightedWaiters[e-1],{resolve:r,priority:n})})}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 n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let n=this._value;n>0;n--){const r=this._weightedWaiters[n-1];if(!r)continue;const s=r.findIndex(i=>i.priority<=e);(s===-1?r:r.splice(0,s)).forEach((i=>i.resolve()))}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}}function N1(t,e){const n=Vf(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function Vf(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var x1=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function c(h){try{u(r.next(h))}catch(p){o(p)}}function l(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class A1{constructor(e){this._semaphore=new E1(1,e)}acquire(){return x1(this,arguments,void 0,function*(e=0){const[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}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 I1=d.a$1.milliseconds(100).milliseconds;class C1{props;mu=new A1;listeners=new Map;debouncedUpdateStreamer;streamerRunLoop=null;streamer=null;closed=!1;constructor(e){this.props={instrumentation:Te.NOOP,...e,streamUpdateDelay:new d.a$1(e.streamUpdateDelay??d.a$1.seconds(5))},this.debouncedUpdateStreamer=Xi(()=>void this.updateStreamer(),I1)}async stream(e,n){const{cache:r,instrumentation:s}=this.props;return this.closed?()=>{}:(await r.populateMissing(n),await this.mu.runExclusive(async()=>{s.L.debug("adding stream handler",{keys:n}),this.listeners.set(e,{valid:!0,keys:new Set(n)});const i=new Map(n.map(o=>{const c=r.get(o);return[o,new d.Oe(d.a.toArray(c.leadingBuffer))]}));return e(i),this.debouncedUpdateStreamer(),()=>this.removeStreamHandler(e)}))}removeStreamHandler(e){const{instrumentation:n}=this.props;this.mu.runExclusive(()=>{const r=this.listeners.get(e);r!=null&&(r.valid=!1)}),setTimeout(()=>{this.mu.runExclusive(async()=>{if(n.L.debug("removing stream handler"),this.listeners.delete(e))return this.debouncedUpdateStreamer();n.L.warn("attempted to remove non-existent stream handler")})},this.props.streamUpdateDelay.milliseconds)}async updateStreamer(){if(this.closed)return;const{instrumentation:e}=this.props;try{const n=new Set;if(this.listeners.forEach(i=>i.keys.forEach(o=>n.add(o))),n.size===0){e.L.info("no keys to stream, closing streamer"),this.streamer?.close(),this.streamerRunLoop!=null&&await this.streamerRunLoop,this.streamer=null,e.L.info("streamer closed successfully");return}const r=Array.from(n);if(d.k.primitiveArrays(r,this.streamer?.keys??[])===d.k.EQUAL){e.L.debug("streamer keys unchanged",{keys:r});return}this.streamer==null&&(e.L.info("creating new streamer",{keys:r}),this.streamer=await this.props.openStreamer({channels:r}),this.streamerRunLoop=this.runStreamer(this.streamer)),e.L.debug("updating streamer",{prev:this.streamer.keys,next:r}),await this.streamer.update(r)}catch(n){throw e.L.error("failed to update streamer",{error:n}),n}}async runStreamer(e){const{cache:n,instrumentation:r}=this.props;try{for await(const s of e){const i=new Map;for(const o of s.keys){const c=s.get(o),u=n.get(o).writeDynamic(c);i.set(o,u)}i.size!==0&&this.listeners.forEach(({valid:o},c)=>o&&c(i))}}catch(s){throw r.L.error("streamer run loop failed",{error:s},!0),s}}async close(){const{instrumentation:e}=this.props;try{this.streamer?.close(),this.streamerRunLoop!=null&&await this.streamerRunLoop}catch(n){e.L.error("failed to close streamer",{error:n})}this.closed=!0}}class j1{async retrieveChannel(){throw new Ue("NoopClient does not support retrieving channels")}async read(){return new d.Oe([])}async stream(){return async()=>{}}async close(){}}class P1{ins;cache;reader;streamer;channelRetriever;constructor({instrumentation:e,core:n}){this.ins=e,this.channelRetriever=n.channels.createDebouncedBatchRetriever(10),this.cache=new S1({channelRetriever:this.channelRetriever,instrumentation:this.ins.child("cache")}),this.reader=new z1({cache:this.cache,readRemote:n.read.bind(n),instrumentation:this.ins.child("reader")}),this.streamer=new C1({cache:this.cache,openStreamer:async r=>Ih.HardenedStreamer.open(n.openStreamer.bind(n),r),instrumentation:this.ins.child("streamer")})}async retrieveChannel(e){const n=await this.channelRetriever.retrieve([e]);if(n.length===0)throw new Qe(`channel ${e} not found`);return n[0]}async read(e,n){return await this.reader.read(e,n)}async stream(e,n){return await this.streamer.stream(e,n)}async close(){this.ins.L.info("closing client"),await this.streamer.close(),await this.reader.close(),this.cache.close()}}const Wf=a.z.object({});class Ln extends at{static TYPE="telem.Provider";static stateZ=Wf;schema=Ln.stateZ;prevCore=null;client=null;afterUpdate(e){const{internal:n}=this,r=yo(e),s=Es(e);if(n.instrumentation=ao(e,"telem").child("provider"),!(r!==this.prevCore||!e.wasSetPreviously(nr)))return;this.prevCore=r,this.client!=null&&s(async()=>{if(this.client==null)throw new Error("no client to close");await this.client.close()},"failed to close client"),this.client=r==null?new j1:new P1({core:r,instrumentation:n.instrumentation});const o=Zf(this.client),c=new As(o);Lf(e,c)}}const $1={[Ln.TYPE]:Ln};exports.A=x;exports.AbstractSink=mf;exports.AbstractSource=be;exports.Aggregator=Ya;exports.BI=YN;exports.Base=xs;exports.BaseProvider=Ln;exports.BooleanStatus=Wt;exports.Bt=ee;exports.CI=FE;exports.COMPONENT_SIZE_LEVELS=QA;exports.CONTEXT_KEY=nr;exports.ChannelData=Lr;exports.ColorGradient=Gt;exports.Composite=at;exports.CompoundTelemFactory=ho;exports.Context=hf;exports.Context$1=As;exports.EI=Uk;exports.Eraser=Ga;exports.FI=ix;exports.FixedColorSource=qr;exports.FixedNumber=Fr;exports.FixedString=Yr;exports.GI=rA;exports.GLProgram=lf;exports.H=D;exports.IterativeSeries=Br;exports.KI=gA;exports.LEVELS=kn;exports.LEVEL_COMPONENT_SIZES=eI;exports.Leaf=Os;exports.Loop=uf;exports.MI=E0;exports.Mean=Vt;exports.MultiSourceTransformer=gf;exports.NoopFactory=ff;exports.O=Ft;exports.PI=Y0;exports.PS=Ji;exports.PipelineFactory=co;exports.Provider=Va;exports.Provider$1=Jt;exports.Provider$2=Ha;exports.REGISTRY=sC;exports.REGISTRY$1=$1;exports.REGISTRY$2=Bf;exports.REGISTRY$3=tC;exports.REGISTRY$4=fC;exports.REGISTRY$5=aC;exports.RemoteFactory=zf;exports.RollingAverage=Vr;exports.SI=Ih;exports.SIZES=Vd;exports.SYNNAX_DARK=qd;exports.SYNNAX_LIGHT=Yd;exports.SYNNAX_THEMES=uI;exports.ScaleNumber=Kt;exports.SeriesDownsampler=uo;exports.SetPoint=Yt;exports.SinkPipeline=Ur;exports.SourcePipeline=Rr;exports.StaticFactory=Of;exports.StreamChannelData=Dr;exports.StreamChannelValue=Zr;exports.StringifyNumber=Ht;exports.T=Ts;exports.TransformerFactory=Af;exports.UnarySinkTransformer=wf;exports.UnarySourceTransformer=zt;exports.WithinBounds=qt;exports.XI=IA;exports.YI=vx;exports.ZERO_CONTEXT_VALUE=fo;exports._=Bt;exports._I=i0;exports._r=Ue;exports.a=eo;exports.aether=JI;exports.aggregatorStateZ=sf;exports.be=Hd;exports.booleanSinkSpecZ=EC;exports.booleanSinkTransformerSpecZ=NC;exports.booleanSourceSpecZ=kC;exports.booleanSourceTransformerSpecZ=xC;exports.booleanStatus=JC;exports.booleanStatusProps=jf;exports.cI=Hb;exports.channelData=ZC;exports.colorGradient=e1;exports.colorGradientProps=_f;exports.colorSourceSpecZ=CC;exports.connectionZ=oo;exports.createAsyncErrorHandler=rf;exports.createErrorHandler=nf;exports.createFactory=Zf;exports.d=FA;exports.dimensions=GA;exports.dimensionsFromMetrics=zs;exports.downLevel=JA;exports.downsampleMode=r1;exports.downsampleModeProps=n1;exports.downsampleModeZ=Rf;exports.eraserStateZ=df;exports.executeInitialSetter=Ss;exports.executeSetter=to;exports.fixedArray=BC;exports.fixedColor=VC;exports.fixedColorSourcePropsZ=xf;exports.fixedNumber=YC;exports.fixedNumberPropsZ=Ef;exports.fixedSeriesPropsZ=lo;exports.fixedString=qC;exports.fixedStringPropsZ=Nf;exports.fontSpecZ=af;exports.g=Md;exports.gI=HO;exports.h=Qi;exports.hI=ov;exports.iI=Nb;exports.isSize=hI;exports.iterativeArray=FC;exports.iterativeSeriesPropsZ=kf;exports.j=M;exports.kI=EE;exports.levelZ=KA;exports.mean=KC;exports.noopBooleanSinkSpec=pC;exports.noopBooleanSourceSpec=mC;exports.noopColorSourceSpec=vC;exports.noopNumericSinkSpec=yC;exports.noopNumericSourceSpec=gC;exports.noopSeriesSourceSpec=TC;exports.noopStatusSourceSpec=bC;exports.noopStringSourceSpec=wC;exports.numberSinkSpecZ=IC;exports.numberSourceSpecZ=AC;exports.o=Xi;exports.prettyParse=Za;exports.provider=h1;exports.providerStateZ=Wf;exports.providerStateZ$1=cf;exports.r=CA;exports.render=Xd;exports.rollingAverage=QC;exports.rollingAverageProps=$f;exports.scaleNumber=t1;exports.scaleNumberProps=Mf;exports.seriesDownsampler=i1;exports.seriesSourceSpecZ=OC;exports.setContext=Lf;exports.setpoint=HC;exports.sinkPipeline=_C;exports.sinkPipelinePropsZ=vf;exports.sinkSpecZ=Ns;exports.sinkTransformerSpecZ=yf;exports.size=Wd;exports.skipNull=Zd;exports.sourcePipeline=$C;exports.sourcePipelinePropsZ=bf;exports.sourceSpecZ=ot;exports.sourceTransformerSpecZ=pf;exports.specZ=Ve;exports.specZ$1=tr;exports.state=WA;exports.statusSourceSpecZ=jC;exports.streamChannelData=LC;exports.streamChannelValue=DC;exports.streamChannelValuePropsZ=Tf;exports.stringSourceSpecZ=PC;exports.stringifyNumber=XC;exports.stringifyNumberProps=Pf;exports.themeZ=Fd;exports.use=rC;exports.use$1=yo;exports.useAdder=ks;exports.useAsyncErrorHandler=eC;exports.useChildContext=o1;exports.useContext=Is;exports.useErrorHandler=Es;exports.useInstrumentation=ao;exports.useOptionalAdder=QI;exports.usePassthrough=Dd;exports.usePurePassthrough=Bd;exports.useSink=l1;exports.useSource=c1;exports.vI=Ca;exports.weightZ=XA;exports.withinBounds=GC;exports.withinBoundsProps=If;exports.y=C;exports.zI=AN;
|