@synnaxlabs/pluto 0.46.2 → 0.46.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/{Toggle-Djy3iEFS.js → Toggle-BvHOvpZl.js} +1 -1
  2. package/dist/{Toggle-D7uuc8BY.cjs → Toggle-YrCaaWoP.cjs} +1 -1
  3. package/dist/{Video-Com7iIjJ.js → Video-B3mUCF7w.js} +1 -1
  4. package/dist/{Video-BgaQjOlJ.cjs → Video-PX9PWa1_.cjs} +1 -1
  5. package/dist/button.cjs +1 -1
  6. package/dist/button.js +1 -1
  7. package/dist/color.cjs +1 -1
  8. package/dist/color.js +1 -1
  9. package/dist/css-BJh3xDSW.cjs +8 -0
  10. package/dist/{css-qKD7ZG81.js → css-C24hS2UX.js} +903 -875
  11. package/dist/css.cjs +1 -1
  12. package/dist/css.js +2 -2
  13. package/dist/dialog.cjs +1 -1
  14. package/dist/dialog.js +1 -1
  15. package/dist/ether.cjs +1 -1
  16. package/dist/ether.js +6 -6
  17. package/dist/{external-CfY-kR5_.js → external-1ucYXJx8.js} +2 -2
  18. package/dist/{external-CwtqVaYf.js → external-BN2wbDrK.js} +3 -3
  19. package/dist/{external-Bfddv9ir.cjs → external-BwkIuXvQ.cjs} +1 -1
  20. package/dist/{external-CG-WeHt1.js → external-C-ExavVe.js} +3 -3
  21. package/dist/{external-C0szVQZ4.js → external-CC9QgzfY.js} +3 -3
  22. package/dist/{external-BwAIT4Et.js → external-Cg3K8ETl.js} +4 -4
  23. package/dist/{external-Bp0LGk7L.cjs → external-ChJFeBx4.cjs} +1 -1
  24. package/dist/{external-BwzXukg6.js → external-ChfziUeG.js} +2 -2
  25. package/dist/{external-fThC1Pt0.js → external-Ck9vwLNn.js} +3 -3
  26. package/dist/{external-iLU86byd.cjs → external-Clg5_LVL.cjs} +1 -1
  27. package/dist/{external-BatQDwpn.cjs → external-CtPQhs2L.cjs} +1 -1
  28. package/dist/{external-R1DnhHJ8.cjs → external-D-7LQcc1.cjs} +1 -1
  29. package/dist/{external-ok-onqCX.cjs → external-D7ez6YFA.cjs} +1 -1
  30. package/dist/{external-CtIn5ns5.js → external-DSC98ftR.js} +3 -3
  31. package/dist/{external-JI_JLXE9.cjs → external-DcJjrD1A.cjs} +2 -2
  32. package/dist/{external-qAqWNZPd.cjs → external-DfxokOST.cjs} +1 -1
  33. package/dist/{external-DPsERPGZ.js → external-Dia3MCeO.js} +3 -3
  34. package/dist/external-Dxu0KYI_.cjs +1 -0
  35. package/dist/{external-BH7AW9vg.cjs → external-NOoRXXaT.cjs} +1 -1
  36. package/dist/{external-B_BNwXoG.js → external-RDyCOmKR.js} +21 -21
  37. package/dist/{external-BXAiwKcS.js → external-S4v-IR_C.js} +3 -3
  38. package/dist/{external-CaehDJtX.cjs → external-VIR_Vvod.cjs} +1 -1
  39. package/dist/{external-BqSq3_g3.js → external-mtaOrZVh.js} +2 -2
  40. package/dist/{external-DZ9ZLLOd.cjs → external-orHcg1KY.cjs} +1 -1
  41. package/dist/{external-CM-K5NTq.js → external-ree9J7kb.js} +1 -1
  42. package/dist/{external-DLIuO7_6.cjs → external-s4B9EjQm.cjs} +1 -1
  43. package/dist/flex.cjs +1 -1
  44. package/dist/flex.js +1 -1
  45. package/dist/{fontString-BpD7ezh8.cjs → fontString-BMITZjR-.cjs} +1 -1
  46. package/dist/{fontString-CpT1noV1.js → fontString-CNdpxtJg.js} +2 -2
  47. package/dist/header.cjs +1 -1
  48. package/dist/header.js +1 -1
  49. package/dist/index.cjs +12 -12
  50. package/dist/index.js +4689 -4692
  51. package/dist/input.cjs +1 -1
  52. package/dist/input.js +1 -1
  53. package/dist/list.cjs +1 -1
  54. package/dist/list.js +1 -1
  55. package/dist/{main-DCwBsS0F.js → main-9Dw_ngUE.js} +3 -3
  56. package/dist/{main-20msMsI6.cjs → main-rewFivKu.cjs} +30 -30
  57. package/dist/menu.cjs +1 -1
  58. package/dist/menu.js +1 -1
  59. package/dist/{provider-B-VPfAGa.js → provider-BMcIM58p.js} +3 -3
  60. package/dist/{provider-D295Uocj.cjs → provider-CedWF-id.cjs} +3 -3
  61. package/dist/{provider-qIzR8Puy.js → provider-DXuSQEu0.js} +2816 -2791
  62. package/dist/provider-DshN-WBB.cjs +83 -0
  63. package/dist/src/ontology/queries.d.ts +3 -10
  64. package/dist/src/ontology/queries.d.ts.map +1 -1
  65. package/dist/src/schematic/symbol/queries.d.ts +1 -3
  66. package/dist/src/schematic/symbol/queries.d.ts.map +1 -1
  67. package/dist/tabs.cjs +1 -1
  68. package/dist/tabs.js +1 -1
  69. package/dist/text.cjs +1 -1
  70. package/dist/text.js +2 -2
  71. package/dist/theming.cjs +1 -1
  72. package/dist/theming.js +2 -2
  73. package/dist/tree.cjs +1 -1
  74. package/dist/tree.js +1 -1
  75. package/dist/triggers.cjs +1 -1
  76. package/dist/triggers.js +1 -1
  77. package/dist/{units-WtYBE1br.js → units-BfWwpiDe.js} +1 -1
  78. package/dist/units-DOj-2MGY.cjs +1 -0
  79. package/dist/video.cjs +1 -1
  80. package/dist/video.js +1 -1
  81. package/package.json +5 -5
  82. package/dist/css-DA2F4zE4.cjs +0 -8
  83. package/dist/external-BaO1j7U1.cjs +0 -1
  84. package/dist/provider-DVqod4rl.cjs +0 -83
  85. package/dist/units-CLbZ5ejs.cjs +0 -1
@@ -0,0 +1,83 @@
1
+ "use strict";const a=require("zod"),d=require("./css-BJh3xDSW.cjs"),oi=require("react"),ep=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)},Ml=t=>{const e=(n,r=ra)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!js(n))return n;r=sp(r);const s={},i=n;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),r):(Object.keys(i).forEach(o=>{let l=i[o];const c=t(o);r.recursive&&(js(l)?wo(l)||(l=e(l,r)):r.recursiveInArray&&go(l)&&(l=[...l].map(u=>{let h=u;return js(u)?wo(h)||(h=e(u,r)):go(u)&&(h=e({key:u},r).key),h}))),s[c]=l}),s)};return e},Ul=Ml(ep),tp=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),np=Ml(tp),rp=[Number,String,Uint8Array],ra={recursive:!0,recursiveInArray:!0},sp=(t=ra)=>(t.recursive==null?t=ra:t.recursiveInArray??=!1,t),go=t=>t!=null&&Array.isArray(t),js=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),wo=t=>rp.some(e=>t instanceof e);let ap=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=Ul(n);return e!=null?e.parse(r):r}encodeString(t){const e=np(t);return JSON.stringify(e,(n,r)=>ArrayBuffer.isView(r)?Array.from(r):typeof r=="bigint"?r.toString():r)}};const sa=new ap,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 ip=t=>t!=null&&typeof t=="object"&&"toString"in t,op=(t,e=!1)=>{const n=ip(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?lp(r):r},lp=t=>(e,n)=>t(n,e),Hr=a.z.tuple([a.z.number(),a.z.number()]);a.z.tuple([a.z.bigint(),a.z.bigint()]);const Zl=a.z.object({width:a.z.number(),height:a.z.number()}),cp=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()}),up=["width","height"];a.z.enum(up);const hp=["start","center","end"],dp=["signedWidth","signedHeight"];a.z.enum(dp);const Or=a.z.object({x:a.z.number(),y:a.z.number()}),fp=a.z.object({clientX:a.z.number(),clientY:a.z.number()}),pp=["x","y"],Ll=a.z.enum(pp),Dl=["top","right","bottom","left"];a.z.enum(Dl);const yp=["left","right"],Bl=a.z.enum(yp),mp=["top","bottom"],Fl=a.z.enum(mp),Yl=["center"],bo=a.z.enum(Yl),gp=[...Dl,...Yl],ql=a.z.enum(gp);a.z.enum(hp);const wp=["first","last"];a.z.enum(wp);const bp=a.z.object({lower:a.z.number(),upper:a.z.number()}),vp=a.z.object({lower:a.z.bigint(),upper:a.z.bigint()});a.z.union([bp,Hr]);a.z.union([vp,Hr]);a.z.enum([...Ll.options,...ql.options]);a.z.enum(["x","left","right"]);a.z.enum(["y","top","bottom"]);a.z.union([Ll,ql,a.z.instanceof(String)]);const Gr=t=>(e,n)=>{if(typeof e=="bigint"){if(Tp(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))},Kr=Gr((t,e)=>t-e),Jr=Gr((t,e)=>t+e),Tp=t=>typeof t=="bigint"?!0:Number.isInteger(t),Ce=Gr((t,e)=>t*e),Xr=Gr((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?Sp(r):r},Sp=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,vo=(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:Bl.or(bo),y:Fl.or(bo)});const zp=a.z.object({x:Bl,y:Fl}),Op=Object.freeze({x:"left",y:"top"}),Ep=(t,e)=>t.x===e.x&&t.y===e.y,To=a.z.union([a.z.number(),Or,Hr,Zl,cp,fp]),kp=(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}},So=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:zp});const li=(t,e,n=0,r=0,s)=>{const i={one:{...So},two:{...So},root:s??Op};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))},Ps=t=>{const e=li(t);return{lower:e.one.x,upper:e.two.x}},$s=t=>{const e=li(t);return{lower:e.one.y,upper:e.two.y}},Np=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,xp=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()});a.z.union([Zl,xp,Or,Hr]);const Ap=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;a.z.object({offset:To,scale:To});a.z.object({offset:a.z.number(),scale:a.z.number()});const Ip=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Cp=t=>(e,n,r,s)=>[e,s?r/t:r*t],jp=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:i}=e,{lower:o,upper:l}=t,c=i-s,u=l-o;if(n==="dimension")return[t,r*(u/c)];const h=(r-s)*(u/c)+o;return[t,h]},Pp=t=>(e,n,r)=>[t,r],$p=()=>(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)]},Rp=t=>(e,n,r)=>{const{lower:s,upper:i}=t;return r=Ap(r,s,i),[e,r]};let zo=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=Ip(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Cp(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=ft(e,n),s=this.new(),i=jp(r);return i.type="scale",s.ops.push(i),s}clamp(e,n){const r=ft(e,n),s=this.new(),i=Rp(r);return i.type="clamp",s.ops.push(i),s}reBound(e,n){const r=ft(e,n),s=this.new(),i=Pp(r);return i.type="re-bound",s.ops.push(i),s}invert(){const e=$p();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,l])=>s>=o&&s<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>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 zo,n=new zo,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=kp(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(Np(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Ep(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(Ps(e)),n.y=n.y.scale($s(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(Ps(e)),n.y=this.y.reBound($s(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(Ps(e)),n.y=this.y.clamp($s(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 li(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 Vl=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Wl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",_p=`0123456789${Wl}`,Mp=11,Up=Vl(Wl,1),Zp=Vl(_p,Mp-1),Lp=()=>`${Up()}${Zp()}`,Dp=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,aa=2n**63n-1n,Bp=2**63-1,Fp=a.z.enum(["static","dynamic"]),Oo=365,ar=30,Yp=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 M(e);if(![R.DAY,R.HOUR,R.MINUTE,R.SECOND,R.MILLISECOND,R.MICROSECOND,R.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 M?new M(r):new R(r)};let M=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===Bp?e=aa: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",l="00";i!=null&&([o,l]=i.split("."));let c=S.hours(parseInt(r??"00")).add(S.minutes(parseInt(s??"00"))).add(S.seconds(parseInt(o??"00"))).add(S.milliseconds(parseInt(l??"00")));return n==="local"&&(c=c.add(S.utcOffset)),c.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 R(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(Jr(this.valueOf(),new R(e).valueOf()))}sub(e){return new S(Kr(this.valueOf(),new R(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(R.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(R.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(R.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(R.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 Hl(this,e)}get isToday(){return this.truncate(R.DAY).equals(S.now().truncate(R.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(aa);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 R).transform(e=>new S(e)),Yp.transform(e=>new S(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}},R=class E 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 E?e:e instanceof Rs?e.period:e instanceof M?new E(e):(pe(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 Rs?e.period:e instanceof M?new E(e):(pe(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),l=this.truncate(E.MICROSECOND),c=this.truncate(E.NANOSECOND),u=n,h=r.sub(n),p=s.sub(r),f=i.sub(s),O=o.sub(i),I=l.sub(o),j=c.sub(l);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,l=n.seconds,c=Math.floor(s/Oo),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(l),j=r?"-":"";if(c>=1){let w=`${c}y`;if(c<2){const T=Math.floor(s%Oo/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(l-O*60);T>0&&(w+=` ${T}s`)}return j+w}return`${j}${I}s`}mult(e){return new E(Ce(this.valueOf(),e))}div(e){return new E(Xr(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(Ce(e,1e3))}static MICROSECOND=E.microseconds(1);static milliseconds(e=1){return E.microseconds(Ce(e,1e3))}static MILLISECOND=E.milliseconds(1);static seconds(e=1){return E.milliseconds(Ce(e,1e3))}static SECOND=E.seconds(1);static minutes(e=1){return E.seconds(Ce(e,60))}static MINUTE=E.minutes(1);static hours(e){return E.minutes(Ce(e,60))}static HOUR=E.hours(1);static days(e){return E.hours(Ce(e,24))}static DAY=E.days(1);static MAX=new E(aa);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(M).transform(e=>new E(e)),a.z.custom(e=>e instanceof Rs).transform(e=>new E(e))])},Rs=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 R.seconds(1/this.valueOf())}sampleCount(e){return new R(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new ne(n).valueOf()}span(e){return R.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new ne(n).valueOf())}add(e){return new he(Jr(this.valueOf(),new he(e).valueOf()))}sub(e){return new he(Kr(this.valueOf(),new he(e).valueOf()))}mult(e){return new he(Ce(this.valueOf(),e))}div(e){return new he(Xr(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 ia(e*this.valueOf())}add(e){return new se(Jr(this.valueOf(),new se(e).valueOf()))}sub(e){return new se(Kr(this.valueOf(),new se(e).valueOf()))}mult(e){return new se(Ce(this.valueOf(),e))}div(e){return new se(Xr(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 M(e.start),this.end=new M(e.end)):(this.start=new M(e),this.end=new M(n))}get span(){return new R(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=R.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=R.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=M.max(r.start,e.start),i=M.min(r.end,e.end);return i.before(s)?!1:new R(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(M.min(...e.map(n=>n.start)),M.max(...e.map(n=>n.end)))}static MAX=new xe(M.MIN,M.MAX);static ZERO=new xe(M.ZERO,M.ZERO);static z=a.z.union([a.z.object({start:M.z,end:M.z}).transform(e=>new xe(e.start,e.end)),a.z.instanceof(xe)]);static sort(e,n){return M.sort(e.start,n.start)||M.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=M.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)])},ia=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(Jr(this.valueOf(),e.valueOf()))}sub(e){return pe(e)&&(e=e.value),new P(Kr(this.valueOf(),e.valueOf()))}mult(e){return new P(Ce(this.valueOf(),e))}div(e){return new P(Xr(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,l=n.sub(e),c=r.sub(n),u=s.sub(r),h=i.sub(s);let p="";return o.isZero||(p+=`${o.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),c.isZero||(p+=`${c.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new 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 Gl=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof M||t instanceof R||t instanceof Date},qp=(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),Vp=/^(?:[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 Wp(t){return typeof t=="string"&&Vp.test(t)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function Hp(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 Gp(t,e=0){const n=Hp(t,e);if(!Wp(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Kl=(t,e)=>Gp(t,e),Le=-1,Kp=a.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Jp=a.z.union([a.z.null(),a.z.undefined()]).transform(()=>new Uint8Array().buffer),oa=10,Xp=(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`)},Jl="sy_x_telem_series";let Xl=class Ye{key;discriminator=Jl;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([Kp,Jp,a.z.instanceof(ArrayBuffer),a.z.instanceof(Uint8Array)]),glBufferUsage:Fp.optional().default("static").optional()});static z=Ye.crudeZ.transform(e=>new Ye(e));constructor(e){Qp(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:l=1n,key:c=Lp(),data:u}=e;if(ey(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 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 M||f instanceof Date||f instanceof M)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 M||O instanceof Date||O instanceof R)&&(f=f.map(I=>new M(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=>sa.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=c,this.alignment=o,this.alignmentMultiple=l,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(sa.decodeString(n)))}get byteCapacity(){return new ia(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 ia(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===oa&&(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]=qp(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=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]===oa){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):Ul(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let n=0,r=this.length-1;const s=op(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 Xp(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 ty(this);return this.dataType.equals(q.JSON)?new ny(e):e}return this.dataType.equals(q.UUID)?new ry(this):new sy(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new Eo(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 Eo(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 Qp=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Xl?!0:Gl(t),ey=Dp(Jl,Xl);class Eo{series;end;index;constructor(e,n,r){this.series=e;const s=ft(0,e.length+1);this.end=vo(s,r),this.index=vo(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class ty{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,n=this.series.data;for(;this.index<n.length&&n[this.index]!==oa;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}}let ny=class Ql{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:sa.decodeString(e.value,Ql.schema)}}};class ry{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=Kl(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let sy=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 ay=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";ay();const iy=["macOS","Windows","Linux"],oy=["macos","windows","linux"],ly={macos:"macOS",windows:"Windows",linux:"Linux"};a.z.enum(iy).or(a.z.enum(oy).transform(t=>ly[t]));const cy=(...t)=>t.map(ec).join(""),ec=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),uy=t=>t.endsWith("/")?t.slice(0,-1):t,hy=(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 dy=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=ec(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:cy(this.path,e)})}toString(){return uy(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new wr({host:"unknown",port:0})};const fy=async t=>await new Promise(e=>setTimeout(e,R.fromMilliseconds(t).milliseconds));class py{config;retries;interval;constructor(e){this.config={baseInterval:new R(e?.baseInterval??R.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??fy},this.retries=0,this.interval=new R(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 yy=a.z.object({baseInterval:R.z.optional(),maxRetries:a.z.number().optional(),scale:a.z.number().optional()}),my=Object.freeze(Object.defineProperty({__proto__:null,Breaker:py,breakerConfigZ:yy},Symbol.toStringTag,{value:"Module"})),gy=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,tc=a.z.string().regex(gy),$t=a.z.number().min(0).max(255),nc=a.z.number().min(0).max(1),rc=a.z.tuple([$t,$t,$t,nc]),wy=a.z.tuple([$t,$t,$t]),by=a.z.object({rgba255:rc}),vy=a.z.number().min(0).max(360),Ty=a.z.number().min(0).max(100),Sy=a.z.number().min(0).max(100),zy=a.z.tuple([vy,Ty,Sy,nc]),ci=a.z.union([tc,wy,rc,zy,by]),Oy=ci.transform(t=>ui(t)),ui=(t,e=1)=>{if(t=ci.parse(t),typeof t=="string")return Ey(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},Ey=(t,e=1)=>(t=tc.parse(t),t=ky(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),ky=t=>t.startsWith("#")?t.slice(1):t;ui("#000000");ui("#ffffff");const Ny=a.z.object({key:a.z.string(),color:ci,position:a.z.number(),switched:a.z.boolean().optional()});a.z.array(Ny);const xy=a.z.object({key:a.z.string(),name:a.z.string(),color:Oy});a.z.object({key:a.z.string(),name:a.z.string(),swatches:a.z.array(xy)});a.z.int().min(0).max(255);a.z.object({name:a.z.string(),key:a.z.string()});const Ay=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Iy=(t,e)=>{const n=Symbol.for(t);if(!Ay(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},sc="sy_x_error",Cy=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=sc;discriminator=gn.discriminator;static TYPE=t;type=gn.TYPE;static matches=Cy(t);matches=gn.matches;constructor(n,r){super(n,r),this.name=gn.TYPE}static sub(n){return Dn(`${t}.${n}`)}},ac=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==sc)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Et="unknown",la="nil";class jy{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:la,data:""};if(ac(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:Et,data:e.message};if(typeof e=="string")return{type:Et,data:e};try{return{type:Et,data:JSON.stringify(e)}}catch{return{type:Et,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===la)return null;if(e.type===Et)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 hi=Iy("synnax-error-registry",()=>new jy),Py=({encode:t,decode:e})=>hi().register({encode:t,decode:e}),$y=t=>hi().encode(t),Ry=t=>t==null?null:hi().decode(t);let ca=class extends Dn("unknown"){};const _y=a.z.object({type:a.z.string(),data:a.z.string()});class My extends Dn("canceled"){}class Uy extends Dn("not_implemented"){}const Ke=Object.freeze(Object.defineProperty({__proto__:null,Canceled:My,NONE:la,NotImplemented:Uy,UNKNOWN:Et,Unknown:ca,createTyped:Dn,decode:Ry,encode:$y,isTyped:ac,payloadZ:_y,register:Py},Symbol.toStringTag,{value:"Module"})),Zy=a.object({jsonrpc:a.literal("2.0"),method:a.string(),params:a.any().optional(),id:a.union([a.string(),a.number(),a.null()]).optional()}),ic=a.object({jsonrpc:a.literal("2.0"),id:a.union([a.string(),a.number(),a.null()])}),Ly=ic.extend({result:a.json()}),Dy=ic.extend({error:a.object({code:a.number().int(),message:a.string().optional(),data:a.json().optional()})}),By=a.union([Ly,Dy]);a.union([Zy,By]);const Fy=a.uuid();a.object({key:Fy,name:a.string().min(1),color:a.string()});a.z.string().regex(/^\d+\.\d+\.\d+$/);const Yy=["standard","scientific","engineering"];a.z.enum(Yy);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")}},Mt=class extends Bn.sub("stream_closed"){constructor(){super("StreamClosed")}},Je=class extends Bn.sub("unreachable"){url;constructor(t={}){const{message:e="Unreachable",url:n=dy.UNKNOWN}=t;super(e),this.url=n}};const qy=t=>{if(!t.type.startsWith(Bn.TYPE))return null;if(ze.matches(t))return{type:ze.TYPE,data:"EOF"};if(Mt.matches(t))return{type:Mt.TYPE,data:"StreamClosed"};if(Je.matches(t))return{type:Je.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Vy=t=>{if(!t.type.startsWith(Bn.TYPE))return null;switch(t.type){case ze.TYPE:return new ze;case Mt.TYPE:return new Mt;case Je.TYPE:return new Je;default:throw new Ke.Unknown(`Unknown error type: ${t.data}`)}};Ke.register({encode:qy,decode:Vy});let oc=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 lc="Content-Type",Wy=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Hy=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&Wy.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},Gy=400;let Ky=class extends oc{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{[lc]: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[,l]=await this.executeMiddleware({target:i.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async c=>{const u={...c,params:{}};o.headers={...this.headers,...c.params};let h;try{h=await fetch(c.target,o)}catch(f){if(!(f instanceof Error))throw f;return[u,Hy(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!==Gy)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(l!=null)return[null,l];if(s==null)throw new Error("Response must be defined");return[s,null]}};const Jy=(t,e)=>{class n{wrapped;constructor(s){this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,i,o,l){const c=new my.Breaker(e);do{const[u,h]=await this.wrapped.send(s,i,o,l);if(h==null)return[u,null];if(!Je.matches(h))return[null,h];if(console.warn(`[freighter] ${c.retryMessage}`,h),!await c.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},Xy=a.z.object({type:a.z.enum(["data","close","open"]),payload:a.z.unknown(),error:a.z.optional(Ke.payloadZ)});class Qy{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 Mt;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,Xy))}onClose(e){this.addMessage({type:"close",error:{type:e.code===tm?ze.TYPE:Mt.TYPE,data:""}})}}const em="freighterctx",tm=1e3;class Er extends oc{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 Er(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 l=new WebSocket(this.buildURL(e,o)),c={...o,params:{}};l.binaryType=Er.MESSAGE_TYPE;const u=await this.wrapSocket(l,n,r);return u instanceof Error?[c,u]:(s=u,[c,null])});if(i!=null)throw i;return s}buildURL(e,n){const r=hy({[lc]:this.encoder.contentType,...n.params},em);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const i=new Qy(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 cc=t=>a.union([a.union([a.null(),a.undefined()]).transform(()=>[]),t.array()]),nm=t=>Array.isArray(t)?t:t==null?[]:[t],uc=(t,e)=>{if(Array.isArray(e))return e.reduce((s,i)=>uc(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},rm=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),hc=(t,e)=>{if(Array.isArray(e))return e.reduce((s,i)=>hc(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},sm=((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:cc,remove:rm,removeKeyed:sm,toArray:nm,upsert:uc,upsertKeyed:hc},Symbol.toStringTag,{value:"Module"})),am=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)},Qr=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=lm(r);const s={},i=n;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),r):(Object.keys(i).forEach(o=>{let l=i[o];const c=t(o);r.recursive&&(_s(l)?xo(l)||(l=e(l,r)):r.recursiveInArray&&No(l)&&(l=[...l].map(u=>{let h=u;return _s(u)?xo(h)||(h=e(u,r)):No(u)&&(h=e({key:u},r).key),h}))),s[c]=l}),s)};return e},di=Qr(am),im=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),dc=Qr(im),fc=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),om=[Number,String,Uint8Array],ua={recursive:!0,recursiveInArray:!0},lm=(t=ua)=>(t.recursive==null?t=ua:t.recursiveInArray??=!1,t),No=t=>t!=null&&Array.isArray(t),_s=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),xo=t=>om.some(e=>t instanceof e),cm=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),um=Qr(cm),hm=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},dm=Qr(hm),fm=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:dc,capitalize:fc,snakeToCamel:di,toKebab:um,toProperNoun:dm},Symbol.toStringTag,{value:"Module"})),pc=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);let yc=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=di(n);return e!=null?e.parse(r):r}encodeString(t){const e=dc(t);return JSON.stringify(e,(n,r)=>ArrayBuffer.isView(r)?Array.from(r):typeof r=="bigint"?r.toString():r)}},mc=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||!pc(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 l=o.split(",").map(c=>c.trim());s.forEach((c,u)=>{const h=this.parseValue(l[u]);h!=null&&i[c].push(h)})}),e!=null?e.parse(i):i}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}},gc=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 kn=new yc,pm=new mc,ym=new gc,mm=[kn],wt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:mc,CSV_CODEC:pm,ENCODERS:mm,JSONCodec:yc,JSON_CODEC:kn,TEXT_CODEC:ym,TextCodec:gc},Symbol.toStringTag,{value:"Module"})),ha=t=>[...new Set(t)],gm=(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())},Ao=Object.freeze(Object.defineProperty({__proto__:null,by:gm,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 wm=t=>t!=null&&typeof t=="object"&&"toString"in t,es=(t,e=!1)=>{const n=wm(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?bc(r):r},bm=(t,e,n)=>{const r=es(e[t],n);return(s,i)=>r(s[t],i[t])},vm=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,wc=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=es(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((i,o)=>i===s[o])?0:-1},Tm=(t,e)=>{const n=ha(t),r=ha(e);return wc(n,r)},Sm=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,bc=t=>(e,n)=>t(n,e),en=0,br=-1,vr=1,vc=t=>t<en,Tc=t=>t>en,zm=t=>t>=en,Sc=t=>t===en,Om=(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],l=s[i];if(isNaN(Number(o))&&isNaN(Number(l))){const c=o.localeCompare(l);if(c!==0)return c}else if(!isNaN(Number(o))&&!isNaN(Number(l))){const c=Number(o)-Number(l);if(c!==0)return c}else return isNaN(Number(o))?-1:1}return r.length-s.length},Io=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:en,GREATER_THAN:vr,LESS_THAN:br,isEqualTo:Sc,isGreaterThan:Tc,isGreaterThanEqual:zm,isLessThan:vc,newF:es,newFieldF:bm,order:Sm,primitiveArrays:vm,reverseF:bc,stringsWithNumbers:Om,uniqueUnorderedPrimitiveArrays:Tm,unorderedPrimitiveArrays:wc},Symbol.toStringTag,{value:"Module"})),ts=a.z.tuple([a.z.number(),a.z.number()]);a.z.tuple([a.z.bigint(),a.z.bigint()]);const zc=a.z.object({width:a.z.number(),height:a.z.number()}),Em=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()}),km=["width","height"];a.z.enum(km);const Nm=["start","center","end"],xm=["signedWidth","signedHeight"];a.z.enum(xm);const Nn=a.z.object({x:a.z.number(),y:a.z.number()}),Oc=a.z.object({clientX:a.z.number(),clientY:a.z.number()}),Ec=["x","y"],kc=a.z.enum(Ec),fi=["top","right","bottom","left"],Am=a.z.enum(fi),Nc=["left","right"],pi=a.z.enum(Nc),xc=["top","bottom"],yi=a.z.enum(xc),mi=["center"],da=a.z.enum(mi),Im=[...fi,...mi],gi=a.z.enum(Im);a.z.enum(Nm);const Cm=["first","last"];a.z.enum(Cm);const jm=a.z.object({lower:a.z.number(),upper:a.z.number()}),Pm=a.z.object({lower:a.z.bigint(),upper:a.z.bigint()});a.z.union([jm,ts]);a.z.union([Pm,ts]);a.z.enum([...kc.options,...gi.options]);a.z.enum(["x","left","right"]);a.z.enum(["y","top","bottom"]);const $m=a.z.union([kc,gi,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),Rm=(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},_m=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},Ac=tn((t,e)=>t<=e?t:e),kr=t=>typeof t=="bigint"?!0:Number.isInteger(t),Mm=tn((t,e)=>t>=e?t:e),Ic=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?Um(r):r},Um=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Co=(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},Cc=t=>{const e=K(t);return e.upper-e.lower},Zm=t=>({lower:Math.min(...t.map(e=>K(e).lower)),upper:Math.max(...t.map(e=>K(e).upper))}),Lm=(t,e,n)=>{const r=t.map(l=>K(l)),s=n>0?1:n<0?-1:0;if(s===0)return e;let i=n,o=e;for(;fa(i,0)===!1;){const l=r.findIndex(c=>s>0?o>=c.lower&&o<c.upper:o>c.lower&&o<=c.upper);if(l!==-1){const c=r[l];let u;if(s>0?u=Ge(c.upper,o):u=Ge(o,c.lower),u>0){const h=Ac(Ic(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 c=r.filter(u=>u.lower>o);if(c.length>0)o=c[0].lower;else return o}else{const c=r.filter(u=>u.upper<o);if(c.length>0)o=c[c.length-1].upper;else return o}}return o},Dm=(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 l=o.lower>s.lower?o.lower:s.lower,c=o.upper<s.upper?o.upper:s.upper;if(l<c){const u=c-l;i=i+u}}return i},Bm=pi,Fm=yi,Ym=da,qm={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},Vm={top:"left",right:"top",bottom:"right",left:"bottom",center:"center"},Wm=$m,Xe=t=>t instanceof String||!Ec.includes(t)?t:t==="x"?"left":"top",Hm=t=>qm[Xe(t)],Gm=t=>Vm[Xe(t)],xn=t=>{const e=Xe(t);return e==="top"||e==="bottom"?"y":"x"},Km=a.z.object({x:pi.or(da),y:yi.or(da)}),jc=a.z.object({x:pi,y:yi}),wi=Object.freeze({x:"left",y:"top"}),Pc=Object.freeze({x:"right",y:"top"}),$c=Object.freeze({x:"left",y:"bottom"}),Rc=Object.freeze({x:"right",y:"bottom"}),bi=Object.freeze({x:"center",y:"center"}),_c=Object.freeze({x:"center",y:"top"}),Mc=Object.freeze({x:"center",y:"bottom"}),Uc=Object.freeze({x:"right",y:"center"}),Zc=Object.freeze({x:"left",y:"center"}),Jm=Object.freeze([Zc,Uc,_c,Mc,wi,Pc,$c,Rc,bi]),Lc=(t,e)=>t.x===e.x&&t.y===e.y,Xm=(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},Qm=t=>[t.x,t.y],Tr=t=>xn(Xe(t))==="x",eg=t=>xn(Xe(t))==="y",tg=t=>`${t.x}${fc(t.y)}`,ng=(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={...bi};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},rg=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:Mc,BOTTOM_LEFT:$c,BOTTOM_RIGHT:Rc,CENTER:bi,CENTER_LEFT:Zc,CENTER_LOCATIONS:mi,CENTER_RIGHT:Uc,OUTER_LOCATIONS:fi,TOP_CENTER:_c,TOP_LEFT:wi,TOP_RIGHT:Pc,XY_LOCATIONS:Jm,X_LOCATIONS:Nc,Y_LOCATIONS:xc,center:Ym,construct:Xe,constructXY:ng,corner:jc,crude:Wm,direction:xn,isX:Tr,isY:eg,location:gi,outer:Am,rotate90:Gm,swap:Hm,x:Bm,xy:Km,xyCouple:Qm,xyEquals:Lc,xyMatches:Xm,xyToString:tg,y:Fm},Symbol.toStringTag,{value:"Module"})),pa=a.z.union([a.z.number(),Nn,ts,zc,Em,Oc]),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}),sg=Object.freeze({x:1,y:1}),ag=Object.freeze({x:1/0,y:1/0}),ig=Object.freeze({x:NaN,y:NaN}),Dc=(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},og=t=>Dc(t,yt),vi=(t,e,n)=>{const r=Z(t),s=Z(e,n);return{x:r.x*s.x,y:r.y*s.y}},Bc=(t,e)=>{const n=Z(t);return{x:n.x+e,y:n.y}},Fc=(t,e)=>{const n=Z(t);return{x:n.x,y:n.y+e}},Yc=(t,e,n,...r)=>{if(typeof e=="string"){if(typeof n!="number")throw new Error("The value must be a number.");return e==="x"?Bc(t,n):Fc(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)},lg=(t,e,n)=>{const r=Z(t);return e==="x"?{x:n,y:r.y}:{x:r.x,y:n}},cg=(t,e)=>{const n=Z(t),r=Z(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},ug=(t,e)=>{const n=Z(t),r=Z(e);return{x:r.x-n.x,y:r.y-n.y}},hg=t=>{const e=Z(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},dg=t=>{const e=Z(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},fg=t=>{const e=Z(t);return[e.x,e.y]},pg=t=>{const e=Z(t);return{left:e.x,top:e.y}},yg=(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}},qc=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}},Vc=(...t)=>{const e=t.reduce((n,r)=>Yc(n,r),yt);return vi(e,1/t.length)},mg=(t,e)=>{const n=[];for(let r=0;r<t.length;r++){const s=t[r];let i,o,l,c;if(r===0){const u=t[r+1],h=wn(u,s);o=bn(h),l=o,c=e}else if(r===t.length-1){const u=t[r-1],h=wn(s,u);i=bn(h),l=i,c=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?c=e:c=e/I,l=qc(Vc(i,o))}n.push(vi(l,c))}return n},gg=t=>{const e=Z(t);return{x:e.y,y:e.x}},wg=t=>{const e=Z(t);return{x:Math.round(e.x),y:Math.round(e.y)}},bg=t=>{const e=Z(t);return{x:1/e.x,y:1/e.y}},Ti=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:ag,NAN:ig,ONE:sg,ZERO:yt,average:Vc,calculateMiters:mg,clientXY:Oc,construct:Z,couple:fg,crudeZ:pa,css:pg,distance:cg,equals:Dc,isFinite:dg,isNan:hg,isZero:og,normal:bn,normalize:qc,reciprocal:bg,round:wg,scale:vi,set:lg,sub:wn,swap:gg,translate:Yc,translateX:Bc,translateY:Fc,translation:ug,truncate:yg,xy:Nn},Symbol.toStringTag,{value:"Module"})),lr=a.z.union([a.z.number(),a.z.string()]);a.z.object({top:lr,left:lr,width:lr,height:lr});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:jc});const Si=(t,e,n=0,r=0,s)=>{const i={one:{...yt},two:{...yt},root:s??wi};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=Si(t);return{lower:e.one.x,upper:e.two.x}},Us=t=>{const e=Si(t);return{lower:e.one.y,upper:e.two.y}},vg=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,Tg=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()});a.z.union([zc,Tg,Nn,ts]);const Sg=(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 zg=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],Og=t=>(e,n,r,s)=>[e,s?r/t:r*t],Eg=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:i}=e,{lower:o,upper:l}=t,c=i-s,u=l-o;if(n==="dimension")return[t,r*(u/c)];const h=(r-s)*(u/c)+o;return[t,h]},kg=t=>(e,n,r)=>[t,r],Ng=()=>(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)]},xg=t=>(e,n,r)=>{const{lower:s,upper:i}=t;return r=Sg(r,s,i),[e,r]};let jo=class kt{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new kt().translate(e)}static magnify(e){return new kt().magnify(e)}static scale(e,n){return new kt().scale(e,n)}translate(e){const n=this.new(),r=zg(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=Og(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=K(e,n),s=this.new(),i=Eg(r);return i.type="scale",s.ops.push(i),s}clamp(e,n){const r=K(e,n),s=this.new(),i=xg(r);return i.type="clamp",s.ops.push(i),s}reBound(e,n){const r=K(e,n),s=this.new(),i=kg(r);return i.type="re-bound",s.ops.push(i),s}invert(){const e=Ng();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 kt;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,l])=>s>=o&&s<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>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 kt};(class Ae{x;y;currRoot;constructor(e=new jo,n=new jo,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(vg(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!Lc(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(Us(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(Us(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(Ms(e)),n.y=this.y.clamp(Us(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 Si(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 Wc=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const Hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ag=`0123456789${Hc}`,Gc=11,Ig=Wc(Hc,1),Cg=Wc(Ag,Gc-1),zi=()=>`${Ig()}${Cg()}`,jg=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:Gc,create:zi},Symbol.toStringTag,{value:"Module"})),Pg=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,$g=2**8-1,Rg=2**16-1,_g=2**32-1,Mg=2n**64n-1n,Ug=2**64-1,Zg=-128,Lg=2**7-1,Dg=-32768,Bg=2**15-1,Fg=-2147483648,Yg=2**31-1,qg=-(2n**63n),Nr=2n**63n-1n,Vg=-9223372036854776e3,Kc=2**63-1,Wg=a.z.enum(["static","dynamic"]),Po=365,cr=30,Hg=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)])]),Jc=(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===Kc?e=Nr: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",l="00";i!=null&&([o,l]=i.split("."));let c=z.hours(parseInt(r??"00")).add(z.minutes(parseInt(s??"00"))).add(z.seconds(parseInt(o??"00"))).add(z.milliseconds(parseInt(l??"00")));return n==="local"&&(c=c.add(z.utcOffset)),c.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 Jc(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(Nr);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)),Hg.transform(e=>new z(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}},x=class k 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 k?e:e instanceof Zs?e.period:e instanceof C?new k(e):(ye(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 Zs?e.period:e instanceof C?new k(e):(ye(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 Jc(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),l=this.truncate(k.MICROSECOND),c=this.truncate(k.NANOSECOND),u=n,h=r.sub(n),p=s.sub(r),f=i.sub(s),O=o.sub(i),I=l.sub(o),j=c.sub(l);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,l=n.seconds,c=Math.floor(s/Po),u=Math.floor(s/cr),h=Math.floor(s/7),p=Math.floor(s),f=Math.floor(i),O=Math.floor(o),I=Math.floor(l),j=r?"-":"";if(c>=1){let w=`${c}y`;if(c<2){const T=Math.floor(s%Po/cr);T>0&&(w+=` ${T}mo`)}return j+w}if(h>=1&&s<cr&&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%cr);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(l-O*60);T>0&&(w+=` ${T}s`)}return j+w}return`${j}${I}s`}mult(e){return new k(ve(this.valueOf(),e))}div(e){return new k(Fn(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(ve(e,1e3))}static MICROSECOND=k.microseconds(1);static milliseconds(e=1){return k.microseconds(ve(e,1e3))}static MILLISECOND=k.milliseconds(1);static seconds(e=1){return k.milliseconds(ve(e,1e3))}static SECOND=k.seconds(1);static minutes(e=1){return k.seconds(ve(e,60))}static MINUTE=k.minutes(1);static hours(e){return k.minutes(ve(e,60))}static HOUR=k.hours(1);static days(e){return k.hours(ve(e,24))}static DAY=k.days(1);static MAX=new k(Nr);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(C).transform(e=>new k(e)),a.z.custom(e=>e instanceof Zs).transform(e=>new k(e))])},Zs=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},[])}},_=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,l=n.sub(e),c=r.sub(n),u=s.sub(r),h=i.sub(s);let p="";return o.isZero||(p+=`${o.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),c.isZero||(p+=`${c.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new $(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 Xc=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof C||t instanceof x||t instanceof Date},Gg=(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),Kg=/^(?:[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 Jg(t){return typeof t=="string"&&Kg.test(t)}const Q=[];for(let t=0;t<256;++t)Q.push((t+256).toString(16).slice(1));function Xg(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 Qg(t,e=0){const n=Xg(t,e);if(!Jg(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Qc=(t,e)=>Qg(t,e),De=-1,ya={[Symbol.iterator]:()=>ya,next:()=>({done:!0,value:void 0})},ew=a.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),tw=a.z.union([a.z.null(),a.z.undefined()]).transform(()=>new Uint8Array().buffer),ma=10,eu=(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`)},tu="sy_x_telem_series";let We=class qe{key;discriminator=tu;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:_.z,alignment:a.z.coerce.bigint().optional(),data:a.z.union([ew,tw,a.z.instanceof(ArrayBuffer),a.z.instanceof(Uint8Array)]),glBufferUsage:Wg.optional().default("static").optional()});static z=qe.crudeZ.transform(e=>new qe(e));constructor(e){nw(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:l=1n,key:c=zi(),data:u}=e;if(nu(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=Xc(u),p=Array.isArray(u);if(n!=null)this.dataType=new _(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=_.STRING;else if(typeof f=="number")this.dataType=_.FLOAT64;else if(typeof f=="bigint")this.dataType=_.INT64;else if(typeof f=="boolean")this.dataType=_.BOOLEAN;else if(f instanceof C||f instanceof Date||f instanceof C)this.dataType=_.TIMESTAMP;else if(typeof f=="object")this.dataType=_.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new _(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(_.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
9
+ `)}
10
+ `).buffer):this.dataType.equals(_.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(I=>kn.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=c,this.alignment=o,this.alignmentMultiple=l,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 _(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(_.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(kn.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]=Gg(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(_.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(_.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(_.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=Qc(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(_.STRING)?new TextDecoder().decode(i):di(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let n=0,r=this.length-1;const s=es(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(_.FLOAT32)&&!this.dataType.equals(_.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 eu(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ro(this.alignmentBounds.lower),upper:Ro(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 rw(this);return this.dataType.equals(_.JSON)?new sw(e):e}return this.dataType.equals(_.UUID)?new aw(this):new iw(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new $o(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 $o(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 nw=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof We?!0:Xc(t),nu=Pg(tu,We);let $o=class{series;end;index;constructor(t,e,n){this.series=t;const r=K(0,t.length+1);this.end=Co(r,n),this.index=Co(r,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},rw=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))})}},sw=class ru{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:kn.decodeString(e.value,ru.schema)}}};class aw{series;index;data;density;constructor(e){if(!e.dataType.equals(_.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=_.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Qc(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let iw=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 ow{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 eu(e,this.dataType),this}get dataType(){return this.series.length===0?_.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(nu(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 Ls(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 Ls(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 Ls(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return Zm(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 Lm(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 Dm(r,e,n)}parseJSON(e){if(!this.dataType.equals(_.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 lw(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}let lw=class{series;seriesIndex;internal;constructor(t){this.series=t,this.seriesIndex=0,this.internal=t[0][Symbol.iterator]()}next(){const t=this.internal.next();return t.done===!1?t:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}},Ls=class{series;index;end;constructor(t,e,n){this.series=t,this.end=n,this.index=e}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 Ro=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},cw=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},uw=(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)},hw=(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)},dw=((t,e,n={optional:!1})=>{const{optional:r,getter:s=hw}=n;if(e==="")return t;const i=e.split(".");if(i.length===1){const l=s(t,i[0]);if(l===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${i[0]} is undefined`)}return l}const o=(l,c)=>{if(c>=i.length)return l;for(let u=i.length-c;u>=1;u--){const h=i.slice(c,c+u).join("."),p=s(l,h);if(p!==void 0){if(c+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,c+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${i[c]} is undefined`)};return o(t,0)});a.z.object({key:a.z.string(),value:a.z.string()});let fw=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?.()}},pw=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 yw=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:pw,Observer:fw},Symbol.toStringTag,{value:"Module"})),mw=a.z.record(a.z.union([a.z.number(),a.z.string(),a.z.symbol()]),a.z.unknown()),Oi=t=>Object.entries(t),gw=(t,e)=>Object.fromEntries(Oi(t).map(([n,r])=>[n,e(r,n)])),ww=t=>Object.fromEntries(Oi(t).filter(([e,n])=>n!==void 0)),bw=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},Oe=Object.freeze(Object.defineProperty({__proto__:null,entries:Oi,map:gw,omit:bw,purgeUndefined:ww,unknownZ:mw},Symbol.toStringTag,{value:"Module"})),vw=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";vw();const Tw=["macOS","Windows","Linux"],Sw=["macos","windows","linux"],zw={macos:"macOS",windows:"Windows",linux:"Linux"};a.z.enum(Tw).or(a.z.enum(Sw).transform(t=>zw[t]));const Ow=(...t)=>t.map(su).join(""),su=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Ew=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=su(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:Ow(this.path,e)})}toString(){return Ew(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Sn({host:"unknown",port:0})}const kw=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),Nw=t=>a.array(t).or(t.transform(e=>[e])),au=t=>uw(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},xw=((t,e,n)=>e===""?t:dw(_o(t,"shape"),au(e),{...n,getter:_o})),zn=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:xw,getFieldSchemaPath:au,nullToUndefined:kw,toArray:Nw},Symbol.toStringTag,{value:"Module"})),ga=2,wa=3,iu=2,Aw=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=Cc(e);if(n==0)return t;let r;n>=1e3?r=ga:n>=1?r=wa:r=Math.ceil(-Math.log10(n))+iu;const s=10**r;return Math.round(t*s)/s},Iw=5,Cw=1e-10,jw=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=Math.abs(t);if(n===0)return 0;let r=!1,s=0;if(e!=null){s=Cc(e);const l=s/n;r=s>0&&l>Cw}if(r){let l;s>=1e3?l=ga:s>=1?l=wa:l=Math.ceil(-Math.log10(s))+iu;const c=10**l;return Math.round(t*c)/c}if(n>=1e3){const l=10**ga;return Math.round(t*l)/l}if(n>=1){const l=10**wa;return Math.round(t*l)/l}const i=Math.floor(Math.log10(n)),o=10**(Iw-i-1);return Math.round(t*o)/o},ba=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:Bg,MAX_INT32:Yg,MAX_INT64:Nr,MAX_INT64_NUMBER:Kc,MAX_INT8:Lg,MAX_UINT16:Rg,MAX_UINT32:_g,MAX_UINT64:Mg,MAX_UINT64_NUMBER:Ug,MAX_UINT8:$g,MIN_INT16:Dg,MIN_INT32:Fg,MIN_INT64:qg,MIN_INT64_NUMBER:Vg,MIN_INT8:Zg,abs:Ic,add:nn,closeTo:Rm,div:Fn,equal:fa,isInteger:kr,max:Mm,min:Ac,mult:ve,roundBySpan:Aw,roundToNearestMagnitude:_m,smartRound:jw,sub:Ge},Symbol.toStringTag,{value:"Module"})),Pw=async t=>await new Promise(e=>setTimeout(e,x.fromMilliseconds(t).milliseconds));class $w{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??Pw},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 Rw=a.z.object({baseInterval:x.z.optional(),maxRetries:a.z.number().optional(),scale:a.z.number().optional()}),ou=Object.freeze(Object.defineProperty({__proto__:null,Breaker:$w,breakerConfigZ:Rw},Symbol.toStringTag,{value:"Module"})),_w=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,lu=a.z.string().regex(_w),Rt=a.z.number().min(0).max(255),cu=a.z.number().min(0).max(1),uu=a.z.tuple([Rt,Rt,Rt,cu]),Mw=a.z.tuple([Rt,Rt,Rt]),Uw=a.z.object({rgba255:uu}),Zw=a.z.number().min(0).max(360),Lw=a.z.number().min(0).max(100),Dw=a.z.number().min(0).max(100),Bw=a.z.tuple([Zw,Lw,Dw,cu]),Ei=a.z.union([lu,Mw,uu,Bw,Uw]),Fw=Ei.transform(t=>ki(t)),ki=(t,e=1)=>{if(t=Ei.parse(t),typeof t=="string")return Yw(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},Yw=(t,e=1)=>(t=lu.parse(t),t=qw(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),qw=t=>t.startsWith("#")?t.slice(1):t;ki("#000000");ki("#ffffff");const Vw=a.z.object({key:a.z.string(),color:Ei,position:a.z.number(),switched:a.z.boolean().optional()});a.z.array(Vw);const Ww=a.z.object({key:a.z.string(),name:a.z.string(),color:Fw});a.z.object({key:a.z.string(),name:a.z.string(),swatches:a.z.array(Ww)});const hu=a.z.int().min(0).max(255),du=255,fu=0,Hw={lower:fu,upper:du+1},pu=a.z.object({name:a.z.string(),key:a.z.string()}),An=t=>a.z.object({subject:pu,resource:t,authority:hu}),Gw=(...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}),yu=t=>a.z.object({from:An(t),to:a.z.null()}),mu=t=>a.z.object({from:a.z.null(),to:An(t)}),Kw=t=>a.z.union([yu(t),mu(t),a.z.object({from:An(t),to:An(t)})]),me=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:du,AUTHORITY_BOUNDS:Hw,ZERO_AUTHORITY:fu,acquireZ:mu,authorityZ:hu,filterTransfersByChannelKey:Gw,releaseZ:yu,stateZ:An,subjectZ:pu,transferZ:Kw},Symbol.toStringTag,{value:"Module"})),Jw=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Xw=(t,e)=>{const n=Symbol.for(t);if(!Jw(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},gu="sy_x_error",Qw=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=gu;discriminator=vn.discriminator;static TYPE=t;type=vn.TYPE;static matches=Qw(t);matches=vn.matches;constructor(n,r){super(n,r),this.name=vn.TYPE}static sub(n){return Yn(`${t}.${n}`)}},wu=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==gu)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Nt="unknown",va="nil";class eb{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:va,data:""};if(wu(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===va)return null;if(e.type===Nt)return new Ta(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Ta(e.data)}}const Ni=Xw("synnax-error-registry",()=>new eb),tb=({encode:t,decode:e})=>Ni().register({encode:t,decode:e}),nb=t=>Ni().encode(t),rb=t=>t==null?null:Ni().decode(t);class Ta extends Yn("unknown"){}const sb=a.z.object({type:a.z.string(),data:a.z.string()});class ab extends Yn("canceled"){}class ib extends Yn("not_implemented"){}const Me=Object.freeze(Object.defineProperty({__proto__:null,Canceled:ab,NONE:va,NotImplemented:ib,UNKNOWN:Nt,Unknown:Ta,createTyped:Yn,decode:rb,encode:nb,isTyped:wu,payloadZ:sb,register:tb},Symbol.toStringTag,{value:"Module"})),ob=a.object({jsonrpc:a.literal("2.0"),method:a.string(),params:a.any().optional(),id:a.union([a.string(),a.number(),a.null()]).optional()}),bu=a.object({jsonrpc:a.literal("2.0"),id:a.union([a.string(),a.number(),a.null()])}),lb=bu.extend({result:a.json()}),cb=bu.extend({error:a.object({code:a.number().int(),message:a.string().optional(),data:a.json().optional()})}),ub=a.union([lb,cb]);a.union([ob,ub]);const vu=a.uuid(),Tu=a.object({key:vu,name:a.string().min(1),color:a.string()}),Su=Object.freeze(Object.defineProperty({__proto__:null,keyZ:vu,labelZ:Tu},Symbol.toStringTag,{value:"Module"})),Sa=a.z.string().regex(/^\d+\.\d+\.\d+$/),qn=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=Sa.parse(t),s=Sa.parse(e),[i,o,l]=r.split(".").map(Number),[c,u,h]=s.split(".").map(Number);if(n.checkMajor){if(i<c)return br;if(i>c)return vr}if(n.checkMinor){if(o<u)return br;if(o>u)return vr}if(n.checkPatch){if(l<h)return br;if(l>h)return vr}return en}),hb=(t,e,n={})=>Sc(qn(t,e,n)),zu=(t,e,n={})=>Tc(qn(t,e,n)),db=(t,e,n={})=>vc(qn(t,e,n)),fb=({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}},pb=({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 l=!1;const c=u=>{try{if(o===0||zu(u.version,i))return console.log(l?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${s.version}`),u;const h=u.version,p=e[h],f=p(u);return l=!0,c(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 c(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:fb,migrator:pb,semVerNewer:zu,semVerOlder:db,semVerZ:Sa,versionsEqual:hb},Symbol.toStringTag,{value:"Module"})),yb=["standard","scientific","engineering"];a.z.enum(yb);const Ou=a.z.enum(["success","info","warning","error","loading","disabled"]),mb=t=>a.z.object({key:a.z.string(),name:a.z.string().default(""),variant:Ou,message:a.z.string(),description:a.z.string().optional(),time:C.z,labels:cc(Tu).optional(),details:t??a.z.unknown().optional()}),gb=a.z.object({stack:a.z.string()}),wb=(t,e)=>{if(!(t instanceof Error))throw t;return Eu({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??""}})},Eu=t=>({key:zi(),time:C.now(),name:"",...t}),bb=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},vb=(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:Eu,exceptionDetailsSchema:gb,fromException:wb,keepVariants:bb,removeVariants:vb,statusZ:mb,variantZ:Ou},Symbol.toStringTag,{value:"Module"})),Tb=(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]}`},Sb=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,l)=>{if(s.test(o)){const c=e.map((u,h)=>h!==l?u.charAt(0).toLowerCase():u).join("");n.add(c.replace(/-/g,"_")),n.add(c.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))},zb=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Ob=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`,za=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:Sb,naturalLanguageJoin:Tb,pluralName:Ob,trimPrefix:zb},Symbol.toStringTag,{value:"Module"})),Eb="all",kb="create",Nb="delete",xb="retrieve",Ab="update",Oa=a.z.enum([Eb,kb,Nb,xb,Ab]);class je extends Me.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:Me.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,Me.decode(n.error))}}class xr extends je.sub("auth"){}class Ea extends xr.sub("invalid_token"){}class ka extends xr.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 Ar extends Qe.sub("multiple_results"){}class Uo extends je.sub("route"){path;constructor(e,n){super(e),this.path=n}}class Na extends je.sub("control"){}class Zo extends Na.sub("unauthorized"){}class Ib extends je.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class L1 extends je.sub("contiguity"){}const Cb=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(xr.TYPE)?t.type.startsWith(Ea.TYPE)?new Ea(t.data):t.type.startsWith(ka.TYPE)?new ka(t.data):new xr(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(Ar.TYPE)?new Ar(t.data):new Qe(t.data):t.type.startsWith(Na.TYPE)?t.type.startsWith(Zo.TYPE)?new Zo(t.data):new Na(t.data):t.type.startsWith(Uo.TYPE)?new Uo(t.data,t.data):new ee(t.data):null,jb=()=>{throw new Me.NotImplemented};Me.register({encode:jb,decode:Cb});const Pb=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(),ku=a.z.string(),ns=a.z.object({key:Vn,name:ku}),$b=t=>({type:"group",key:t}),rs=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"]),Nu=a.z.string().transform(t=>{const[e,n]=t.split(":");return{type:rs.parse(e),key:n??""}}),U=a.z.object({type:rs,key:a.z.string()}).or(Nu),Rb={type:"builtin",key:"root"},Zt=(t=>(typeof t=="string"&&(t=Nu.parse(t)),Array.isArray(t)?t.map(e=>Zt(e)):`${t.type}:${t.key}`)),_b=(t,e)=>t.type===e.type&&t.key===e.key,xu=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))},Au=a.z.object({id:U,name:a.z.string(),data:Oe.unknownZ.optional().nullable()}).transform(t=>({key:Zt(t.id),...t})),Mb=t=>t==="to"?"from":"to",Ub=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)}})),Zb=t=>`${Zt(t.from)}->${t.type}->${Zt(t.to)}`,Lb="parent",Db=(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),Bb="sy_group_set",Fb="sy_group_delete",Yb=a.object({group:ns}),qb=a.object({parent:U,key:Vn.optional(),name:a.string()}),Vb=a.object({key:Vn,name:a.string()}),Wb=a.object({keys:a.array(Vn)}),Hb="/ontology/create-group",Gb="/ontology/rename-group",Kb="/ontology/delete-group";let Iu=class{client;constructor(t){this.client=t}async create(t){return(await b(this.client,Hb,t,qb,Yb)).group}async rename(t,e){await b(this.client,Gb,{key:t,name:e},Vb,a.object({}))}async delete(t){await b(this.client,Kb,{keys:v.toArray(t)},Wb,a.object({}))}};const Jb=Object.freeze(Object.defineProperty({__proto__:null,Client:Iu,DELETE_CHANNEL_NAME:Fb,SET_CHANNEL_NAME:Bb,groupZ:ns,keyZ:Vn,nameZ:ku,ontologyID:$b},Symbol.toStringTag,{value:"Module"})),Xb="/ontology/add-children",Qb="/ontology/remove-children",ev="/ontology/move-children",Lo=a.z.object({id:U,children:U.array()}),tv=a.z.object({from:U,to:U,children:U.array()}),Ds=a.z.object({});let nv=class{client;constructor(t){this.client=t}async addChildren(t,...e){await b(this.client,Xb,{id:t,children:e},Lo,Ds)}async removeChildren(t,...e){await b(this.client,Qb,{id:t,children:e},Lo,Ds)}async moveChildren(t,e,...n){await b(this.client,ev,{from:t,to:e,children:n},tv,Ds)}};const rv="/ontology/retrieve",sv=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:rs.array().optional()}),av=a.z.object({resources:Au.array()});let Cu=class{type="ontology";groups;client;writer;framer;constructor(t,e){this.client=t,this.writer=new nv(t),this.groups=new Iu(t),this.framer=e}async retrieve(t,e){if(!Array.isArray(t)&&typeof t=="object"&&!("key"in t))return this.execRetrieve(t);const n=xu(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 ${za.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,rv,t,sv,av);return e}};const iv="sy_ontology_resource_set",ov="sy_ontology_resource_delete",lv="sy_ontology_relationship_set",cv="sy_ontology_relationship_delete",uv=Object.freeze(Object.defineProperty({__proto__:null,Client:Cu,PARENT_OF_RELATIONSHIP_TYPE:Lb,RELATIONSHIP_DELETE_CHANNEL_NAME:cv,RELATIONSHIP_SET_CHANNEL_NAME:lv,RESOURCE_DELETE_CHANNEL_NAME:ov,RESOURCE_SET_CHANNEL_NAME:iv,ROOT_ID:Rb,idToString:Zt,idZ:U,idsEqual:_b,matchRelationship:Db,oppositeRelationshipDirection:Mb,parseIDs:xu,relationshipToString:Zb,relationshipZ:Ub,resourceTypeZ:rs,resourceZ:Au},Symbol.toStringTag,{value:"Module"})),Wn=a.z.uuid(),xi=a.z.object({key:Wn,subjects:v.nullableZ(U),objects:v.nullableZ(U),actions:v.nullableZ(Oa)}),hv=a.z.object({key:Wn.optional(),subjects:U.array().or(U),objects:U.array().or(U),actions:Oa.array().or(Oa)}),dv=a.z.object({keys:Wn.array().optional(),subjects:U.array().optional()}),fv=a.z.object({key:Wn}).transform(({key:t})=>({keys:[t]})),pv=a.z.union([a.z.object({for:U}).transform(({for:t})=>({subjects:[t]})),a.z.object({for:U.array()}).transform(({for:t})=>({subjects:t})),dv]),yv=a.z.union([fv,pv]),mv=a.z.object({policies:v.nullableZ(xi)}),gv=a.z.object({policies:xi.partial({key:!0}).array()}),wv=a.z.object({policies:xi.array()}),bv=a.z.object({keys:Wn.array()}),vv=a.z.object({}),Tv="/access/policy/retrieve",Sv="/access/policy/create",zv="/access/policy/delete";let Ov=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=hv.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,Sv,{policies:n},gv,wv);return e?r.policies:r.policies[0]}async retrieve(t){const e="key"in t,n=await b(this.client,Tv,t,yv,mv);return e?n.policies[0]:n.policies}async delete(t){await b(this.client,zv,{keys:v.toArray(t)},bv,vv)}},Ev=class{policy;constructor(t){this.policy=new Ov(t)}};function y(t,e,n){function r(l,c){var u;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(u=l._zod).traits??(u.traits=new Set),l._zod.traits.add(t),e(l,c);for(const h in o.prototype)h in l||Object.defineProperty(l,h,{value:o.prototype[h].bind(l)});l._zod.constr=o,l._zod.def=c}const s=n?.Parent??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function o(l){var c;const u=n?.Parent?new i:this;r(u,l),(c=u._zod).deferred??(c.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class _t extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ju extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Pu={};function mt(t){return Pu}function kv(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 xa(t,e){return typeof e=="bigint"?e.toString():e}function Ai(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ii(t){return t==null}function Ci(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Nv(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 c=r.match(/\d?e-(\d?)/);c?.[1]&&(s=Number.parseInt(c[1]))}const i=n>s?n:s,o=Number.parseInt(t.toFixed(i).replace(".","")),l=Number.parseInt(e.toFixed(i).replace(".",""));return o%l/10**i}const Do=Symbol("evaluating");function B(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Do)return r===void 0&&(r=Do,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function xv(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 Bo(t){return JSON.stringify(t)}const $u="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Ir(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Av=Ai(()=>{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(Ir(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(Ir(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ru(t){return Cn(t)?{...t}:Array.isArray(t)?[...t]:t}const Iv=new Set(["string","number","symbol"]);function ss(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 Cv(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const jv={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 Pv(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 $v(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 Rv(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 _v(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 Mv(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 Uv(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 Zv(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 _u(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 ji(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 Mu=(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,xa,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Uu=y("$ZodError",Mu),Zu=y("$ZodError",Mu,{Parent:Error});function Lv(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 Dv(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(l=>s({issues:l}));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 l=r,c=0;for(;c<o.path.length;){const u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(t),r}const Pi=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 _t;if(o.issues.length){const l=new(s?.Err??t)(o.issues.map(c=>gt(c,i,mt())));throw $u(l,s?.callee),l}return o.value},$i=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 l=new(s?.Err??t)(o.issues.map(c=>gt(c,i,mt())));throw $u(l,s?.callee),l}return o.value},as=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 _t;return i.issues.length?{success:!1,error:new(t??Uu)(i.issues.map(o=>gt(o,s,mt())))}:{success:!0,data:i.value}},Bv=as(Zu),is=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}},Fv=is(Zu),Yv=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Pi(t)(e,n,s)},qv=t=>(e,n,r)=>Pi(t)(e,n,r),Vv=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return $i(t)(e,n,s)},Wv=t=>async(e,n,r)=>$i(t)(e,n,r),Hv=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return as(t)(e,n,s)},Gv=t=>(e,n,r)=>as(t)(e,n,r),Kv=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return is(t)(e,n,s)},Jv=t=>async(e,n,r)=>is(t)(e,n,r),Xv=/^[cC][^\s-]{8,}$/,Qv=/^[0-9a-z]+$/,eT=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tT=/^[0-9a-vA-V]{20}$/,nT=/^[A-Za-z0-9]{27}$/,rT=/^[a-zA-Z0-9_-]{21}$/,sT=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,aT=/^([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})$/,Fo=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)$/,iT=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,oT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function lT(){return new RegExp(oT,"u")}const 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])$/,uT=/^(([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}|:))$/,hT=/^((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])$/,dT=/^(([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])$/,fT=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Lu=/^[A-Za-z0-9_-]*$/,pT=/^(?=.{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])?)*\.?$/,yT=/^\+(?:[0-9]){6,14}[0-9]$/,Du="(?:(?:\\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])))",mT=new RegExp(`^${Du}$`);function Bu(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 gT(t){return new RegExp(`^${Bu(t)}$`)}function wT(t){const e=Bu({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(`^${Du}T(?:${r})$`)}const bT=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},vT=/^-?\d+$/,TT=/^-?\d+(?:\.\d+)?/,ST=/^(?:true|false)$/i,zT=/^[^A-Z]*$/,OT=/^[^a-z]*$/,oe=y("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Fu={number:"number",bigint:"bigint",object:"date"},Yu=y("$ZodCheckLessThan",(t,e)=>{oe.init(t,e);const n=Fu[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})}}),qu=y("$ZodCheckGreaterThan",(t,e)=>{oe.init(t,e);const n=Fu[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})}}),ET=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):Nv(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})}}),kT=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]=jv[e.format];t._zod.onattach.push(o=>{const l=o._zod.bag;l.format=e.format,l.minimum=s,l.maximum=i,n&&(l.pattern=vT)}),t._zod.check=o=>{const l=o.value;if(n){if(!Number.isInteger(l)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?o.issues.push({input:l,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:l,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}}l<s&&o.issues.push({origin:"number",input:l,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),l>i&&o.issues.push({origin:"number",input:l,code:"too_big",maximum:i,inst:t})}}),NT=y("$ZodCheckMaxLength",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ii(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=ji(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),xT=y("$ZodCheckMinLength",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ii(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=ji(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),AT=y("$ZodCheckLengthEquals",(t,e)=>{var n;oe.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ii(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=ji(s),l=i>e.length;r.issues.push({origin:o,...l?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),os=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=()=>{})}),IT=y("$ZodCheckRegex",(t,e)=>{os.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})}}),CT=y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=zT),os.init(t,e)}),jT=y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=OT),os.init(t,e)}),PT=y("$ZodCheckIncludes",(t,e)=>{oe.init(t,e);const n=ss(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})}}),$T=y("$ZodCheckStartsWith",(t,e)=>{oe.init(t,e);const n=new RegExp(`^${ss(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})}}),RT=y("$ZodCheckEndsWith",(t,e)=>{oe.init(t,e);const n=new RegExp(`.*${ss(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})}}),_T=y("$ZodCheckOverwrite",(t,e)=>{oe.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class MT{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 UT={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=UT;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,l,c)=>{let u=jt(o),h;for(const p of l){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&&c?.async===!1)throw new _t;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,l,c)=>{if(jt(o))return o.aborted=!0,o;const u=s(l,r,c);if(u instanceof Promise){if(c.async===!1)throw new _t;return u.then(h=>t._zod.parse(h,c))}return t._zod.parse(u,c)};t._zod.run=(o,l)=>{if(l.skipChecks)return t._zod.parse(o,l);if(l.direction==="backward"){const u=t._zod.parse({value:o.value,issues:[]},{...l,skipChecks:!0});return u instanceof Promise?u.then(h=>i(h,o,l)):i(u,o,l)}const c=t._zod.parse(o,l);if(c instanceof Promise){if(l.async===!1)throw new _t;return c.then(u=>s(u,r,l))}return s(c,r,l)}}t["~standard"]={validate:s=>{try{const i=Bv(t,s);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Fv(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ri=y("$ZodString",(t,e)=>{H.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??bT(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)=>{os.init(t,e),Ri.init(t,e)}),ZT=y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=aT),Y.init(t,e)}),LT=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=Fo(n))}else e.pattern??(e.pattern=Fo());Y.init(t,e)}),DT=y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=iT),Y.init(t,e)}),BT=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:pT.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})}}}),FT=y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=lT()),Y.init(t,e)}),YT=y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=rT),Y.init(t,e)}),qT=y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Xv),Y.init(t,e)}),VT=y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Qv),Y.init(t,e)}),WT=y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=eT),Y.init(t,e)}),HT=y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=tT),Y.init(t,e)}),GT=y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=nT),Y.init(t,e)}),KT=y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=wT(e)),Y.init(t,e)}),JT=y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=mT),Y.init(t,e)}),XT=y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=gT(e)),Y.init(t,e)}),QT=y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=sT),Y.init(t,e)}),eS=y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=cT),Y.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),tS=y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=uT),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})}}}),nS=y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=hT),Y.init(t,e)}),rS=y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=dT),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 Vu(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const sS=y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=fT),Y.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Vu(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function aS(t){if(!Lu.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Vu(n)}const iS=y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Lu),Y.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{aS(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),oS=y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=yT),Y.init(t,e)});function lS(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 cS=y("$ZodJWT",(t,e)=>{Y.init(t,e),t._zod.check=n=>{lS(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Wu=y("$ZodNumber",(t,e)=>{H.init(t,e),t._zod.pattern=t._zod.bag.pattern??TT,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}}),uS=y("$ZodNumber",(t,e)=>{kT.init(t,e),Wu.init(t,e)}),hS=y("$ZodBoolean",(t,e)=>{H.init(t,e),t._zod.pattern=ST,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}}),dS=y("$ZodUnknown",(t,e)=>{H.init(t,e),t._zod.parse=n=>n}),fS=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 Yo(t,e,n){t.issues.length&&e.issues.push(..._u(n,t.issues)),e.value[n]=t.value}const pS=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 l=s[o],c=e.element._zod.run({value:l,issues:[]},r);c instanceof Promise?i.push(c.then(u=>Yo(u,n,o))):Yo(c,n,o)}return i.length?Promise.all(i).then(()=>n):n}});function Cr(t,e,n,r){t.issues.length&&e.issues.push(..._u(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Hu(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=Cv(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Gu(t,e,n,r,s,i){const o=[],l=s.keySet,c=s.catchall._zod,u=c.def.type;for(const h of Object.keys(e)){if(l.has(h))continue;if(u==="never"){o.push(h);continue}const p=c.run({value:e[h],issues:[]},r);p instanceof Promise?t.push(p.then(f=>Cr(f,n,h,e))):Cr(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 yS=y("$ZodObject",(t,e)=>{H.init(t,e);const n=Ai(()=>Hu(e));B(t._zod,"propValues",()=>{const o=e.shape,l={};for(const c in o){const u=o[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(const h of u.values)l[c].add(h)}}return l});const r=Ir,s=e.catchall;let i;t._zod.parse=(o,l)=>{i??(i=n.value);const c=o.value;if(!r(c))return o.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),o;o.value={};const u=[],h=i.shape;for(const p of i.keys){const f=h[p]._zod.run({value:c[p],issues:[]},l);f instanceof Promise?u.push(f.then(O=>Cr(O,o,p,c))):Cr(f,o,p,c)}return s?Gu(u,c,o,l,n.value,t):u.length?Promise.all(u).then(()=>o):o}}),mS=y("$ZodObjectJIT",(t,e)=>{yS.init(t,e);const n=t._zod.parse,r=Ai(()=>Hu(e)),s=p=>{const f=new MT(["shape","payload","ctx"]),O=r.value,I=A=>{const W=Bo(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=Bo(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=Ir,l=!Pu.jitless,c=l&&Av.value,u=e.catchall;let h;t._zod.parse=(p,f)=>{h??(h=r.value);const O=p.value;return o(O)?l&&c&&f?.async===!1&&f.jitless!==!0?(i||(i=s(e.shape)),p=i(p,f),u?Gu([],O,p,f,h,t):p):n(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),p)}});function qo(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 gS=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=>Ci(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 l=[];for(const c of e.options){const u=c._zod.run({value:s.value,issues:[]},i);if(u instanceof Promise)l.push(u),o=!0;else{if(u.issues.length===0)return u;l.push(u)}}return o?Promise.all(l).then(c=>qo(c,s,t,i)):qo(l,s,t,i)}}),wS=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(([l,c])=>Vo(n,l,c)):Vo(n,i,o)}});function Aa(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=Aa(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=Aa(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 Vo(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=Aa(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 bS=y("$ZodEnum",(t,e)=>{H.init(t,e);const n=kv(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>Iv.has(typeof s)).map(s=>typeof s=="string"?ss(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}}),vS=y("$ZodTransform",(t,e)=>{H.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new ju(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 _t;return n.value=s,n}});function Wo(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const TS=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(`^(${Ci(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=>Wo(i,n.value)):Wo(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),SS=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(`^(${Ci(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)}),zS=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=>Ho(i,e)):Ho(s,e)}});function Ho(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const OS=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))}),ES=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=>Go(i,t)):Go(s,t)}});function Go(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 kS=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)}}),NS=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 xS=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(Ko):Ko(s)}});function Ko(t){return t.value=Object.freeze(t.value),t}const AS=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=>Jo(i,n,r,t));Jo(s,n,r,t)}});function Jo(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 IS{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 CS(){return new IS}const fr=CS();function jS(t,e){return new t({type:"string",...N(e)})}function PS(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function Xo(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function Ku(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function $S(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function RS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function _S(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function MS(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function US(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function ZS(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function LS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function DS(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function BS(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function FS(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function YS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function qS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function VS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function WS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function HS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function GS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function KS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function JS(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function XS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}function QS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function ez(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function tz(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function nz(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function rz(t,e){return new t({type:"number",checks:[],...N(e)})}function sz(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function az(t,e){return new t({type:"boolean",...N(e)})}function iz(t){return new t({type:"unknown"})}function oz(t,e){return new t({type:"never",...N(e)})}function Qo(t,e){return new Yu({check:"less_than",...N(e),value:t,inclusive:!1})}function Bs(t,e){return new Yu({check:"less_than",...N(e),value:t,inclusive:!0})}function el(t,e){return new qu({check:"greater_than",...N(e),value:t,inclusive:!1})}function Fs(t,e){return new qu({check:"greater_than",...N(e),value:t,inclusive:!0})}function tl(t,e){return new ET({check:"multiple_of",...N(e),value:t})}function Ju(t,e){return new NT({check:"max_length",...N(e),maximum:t})}function jr(t,e){return new xT({check:"min_length",...N(e),minimum:t})}function Xu(t,e){return new AT({check:"length_equals",...N(e),length:t})}function lz(t,e){return new IT({check:"string_format",format:"regex",...N(e),pattern:t})}function cz(t){return new CT({check:"string_format",format:"lowercase",...N(t)})}function uz(t){return new jT({check:"string_format",format:"uppercase",...N(t)})}function hz(t,e){return new PT({check:"string_format",format:"includes",...N(e),includes:t})}function dz(t,e){return new $T({check:"string_format",format:"starts_with",...N(e),prefix:t})}function fz(t,e){return new RT({check:"string_format",format:"ends_with",...N(e),suffix:t})}function Hn(t){return new _T({check:"overwrite",tx:t})}function pz(t){return Hn(e=>e.normalize(t))}function yz(){return Hn(t=>t.trim())}function mz(){return Hn(t=>t.toLowerCase())}function gz(){return Hn(t=>t.toUpperCase())}function wz(t,e,n){return new t({type:"array",element:e,...N(n)})}function bz(t,e,n){return new t({type:"custom",check:"custom",fn:e,...N(n)})}function vz(t){const e=Tz(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 Tz(t,e){const n=new oe({check:"custom",...N(e)});return n._zod.check=t,n}const Sz=y("ZodISODateTime",(t,e)=>{KT.init(t,e),V.init(t,e)});function zz(t){return QS(Sz,t)}const Oz=y("ZodISODate",(t,e)=>{JT.init(t,e),V.init(t,e)});function Ez(t){return ez(Oz,t)}const kz=y("ZodISOTime",(t,e)=>{XT.init(t,e),V.init(t,e)});function Nz(t){return tz(kz,t)}const xz=y("ZodISODuration",(t,e)=>{QT.init(t,e),V.init(t,e)});function Az(t){return nz(xz,t)}const Iz=(t,e)=>{Uu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Dv(t,n)},flatten:{value:n=>Lv(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,xa,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,xa,2)}},isEmpty:{get(){return t.issues.length===0}}})},we=y("ZodError",Iz,{Parent:Error}),Cz=Pi(we),jz=$i(we),Pz=as(we),$z=is(we),Rz=Yv(we),_z=qv(we),Mz=Vv(we),Uz=Wv(we),Zz=Hv(we),Lz=Gv(we),Dz=Kv(we),Bz=Jv(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)=>Cz(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Pz(t,n,r),t.parseAsync=async(n,r)=>jz(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>$z(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Rz(t,n,r),t.decode=(n,r)=>_z(t,n,r),t.encodeAsync=async(n,r)=>Mz(t,n,r),t.decodeAsync=async(n,r)=>Uz(t,n,r),t.safeEncode=(n,r)=>Zz(t,n,r),t.safeDecode=(n,r)=>Lz(t,n,r),t.safeEncodeAsync=async(n,r)=>Dz(t,n,r),t.safeDecodeAsync=async(n,r)=>Bz(t,n,r),t.refine=(n,r)=>t.check($O(n,r)),t.superRefine=n=>t.check(RO(n)),t.overwrite=n=>t.check(Hn(n)),t.optional=()=>il(t),t.nullable=()=>ol(t),t.nullish=()=>il(ol(t)),t.nonoptional=n=>NO(t,n),t.array=()=>pO(t),t.or=n=>_i([t,n]),t.and=n=>wO(t,n),t.transform=n=>ll(t,TO(n)),t.default=n=>OO(t,n),t.prefault=n=>kO(t,n),t.catch=n=>AO(t,n),t.pipe=n=>ll(t,n),t.readonly=()=>jO(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)),Qu=y("_ZodString",(t,e)=>{Ri.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(lz(...r)),t.includes=(...r)=>t.check(hz(...r)),t.startsWith=(...r)=>t.check(dz(...r)),t.endsWith=(...r)=>t.check(fz(...r)),t.min=(...r)=>t.check(jr(...r)),t.max=(...r)=>t.check(Ju(...r)),t.length=(...r)=>t.check(Xu(...r)),t.nonempty=(...r)=>t.check(jr(1,...r)),t.lowercase=r=>t.check(cz(r)),t.uppercase=r=>t.check(uz(r)),t.trim=()=>t.check(yz()),t.normalize=(...r)=>t.check(pz(...r)),t.toLowerCase=()=>t.check(mz()),t.toUpperCase=()=>t.check(gz())}),Fz=y("ZodString",(t,e)=>{Ri.init(t,e),Qu.init(t,e),t.email=n=>t.check(PS(Yz,n)),t.url=n=>t.check(MS(Vz,n)),t.jwt=n=>t.check(XS(oO,n)),t.emoji=n=>t.check(US(Wz,n)),t.guid=n=>t.check(Xo(nl,n)),t.uuid=n=>t.check(Ku(Tn,n)),t.uuidv4=n=>t.check($S(Tn,n)),t.uuidv6=n=>t.check(RS(Tn,n)),t.uuidv7=n=>t.check(_S(Tn,n)),t.nanoid=n=>t.check(ZS(Hz,n)),t.guid=n=>t.check(Xo(nl,n)),t.cuid=n=>t.check(LS(Gz,n)),t.cuid2=n=>t.check(DS(Kz,n)),t.ulid=n=>t.check(BS(Jz,n)),t.base64=n=>t.check(GS(sO,n)),t.base64url=n=>t.check(KS(aO,n)),t.xid=n=>t.check(FS(Xz,n)),t.ksuid=n=>t.check(YS(Qz,n)),t.ipv4=n=>t.check(qS(eO,n)),t.ipv6=n=>t.check(VS(tO,n)),t.cidrv4=n=>t.check(WS(nO,n)),t.cidrv6=n=>t.check(HS(rO,n)),t.e164=n=>t.check(JS(iO,n)),t.datetime=n=>t.check(zz(n)),t.date=n=>t.check(Ez(n)),t.time=n=>t.check(Nz(n)),t.duration=n=>t.check(Az(n))});function ge(t){return jS(Fz,t)}const V=y("ZodStringFormat",(t,e)=>{Y.init(t,e),Qu.init(t,e)}),Yz=y("ZodEmail",(t,e)=>{DT.init(t,e),V.init(t,e)}),nl=y("ZodGUID",(t,e)=>{ZT.init(t,e),V.init(t,e)}),Tn=y("ZodUUID",(t,e)=>{LT.init(t,e),V.init(t,e)});function qz(t){return Ku(Tn,t)}const Vz=y("ZodURL",(t,e)=>{BT.init(t,e),V.init(t,e)}),Wz=y("ZodEmoji",(t,e)=>{FT.init(t,e),V.init(t,e)}),Hz=y("ZodNanoID",(t,e)=>{YT.init(t,e),V.init(t,e)}),Gz=y("ZodCUID",(t,e)=>{qT.init(t,e),V.init(t,e)}),Kz=y("ZodCUID2",(t,e)=>{VT.init(t,e),V.init(t,e)}),Jz=y("ZodULID",(t,e)=>{WT.init(t,e),V.init(t,e)}),Xz=y("ZodXID",(t,e)=>{HT.init(t,e),V.init(t,e)}),Qz=y("ZodKSUID",(t,e)=>{GT.init(t,e),V.init(t,e)}),eO=y("ZodIPv4",(t,e)=>{eS.init(t,e),V.init(t,e)}),tO=y("ZodIPv6",(t,e)=>{tS.init(t,e),V.init(t,e)}),nO=y("ZodCIDRv4",(t,e)=>{nS.init(t,e),V.init(t,e)}),rO=y("ZodCIDRv6",(t,e)=>{rS.init(t,e),V.init(t,e)}),sO=y("ZodBase64",(t,e)=>{sS.init(t,e),V.init(t,e)}),aO=y("ZodBase64URL",(t,e)=>{iS.init(t,e),V.init(t,e)}),iO=y("ZodE164",(t,e)=>{oS.init(t,e),V.init(t,e)}),oO=y("ZodJWT",(t,e)=>{cS.init(t,e),V.init(t,e)}),eh=y("ZodNumber",(t,e)=>{Wu.init(t,e),G.init(t,e),t.gt=(r,s)=>t.check(el(r,s)),t.gte=(r,s)=>t.check(Fs(r,s)),t.min=(r,s)=>t.check(Fs(r,s)),t.lt=(r,s)=>t.check(Qo(r,s)),t.lte=(r,s)=>t.check(Bs(r,s)),t.max=(r,s)=>t.check(Bs(r,s)),t.int=r=>t.check(sl(r)),t.safe=r=>t.check(sl(r)),t.positive=r=>t.check(el(0,r)),t.nonnegative=r=>t.check(Fs(0,r)),t.negative=r=>t.check(Qo(0,r)),t.nonpositive=r=>t.check(Bs(0,r)),t.multipleOf=(r,s)=>t.check(tl(r,s)),t.step=(r,s)=>t.check(tl(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 rl(t){return rz(eh,t)}const lO=y("ZodNumberFormat",(t,e)=>{uS.init(t,e),eh.init(t,e)});function sl(t){return sz(lO,t)}const cO=y("ZodBoolean",(t,e)=>{hS.init(t,e),G.init(t,e)});function ls(t){return az(cO,t)}const uO=y("ZodUnknown",(t,e)=>{dS.init(t,e),G.init(t,e)});function al(){return iz(uO)}const hO=y("ZodNever",(t,e)=>{fS.init(t,e),G.init(t,e)});function dO(t){return oz(hO,t)}const fO=y("ZodArray",(t,e)=>{pS.init(t,e),G.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(jr(n,r)),t.nonempty=n=>t.check(jr(1,n)),t.max=(n,r)=>t.check(Ju(n,r)),t.length=(n,r)=>t.check(Xu(n,r)),t.unwrap=()=>t.element});function pO(t,e){return wz(fO,t,e)}const yO=y("ZodObject",(t,e)=>{mS.init(t,e),G.init(t,e),B(t,"shape",()=>e.shape),t.keyof=()=>bO(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:al()}),t.loose=()=>t.clone({...t._zod.def,catchall:al()}),t.strict=()=>t.clone({...t._zod.def,catchall:dO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Rv(t,n),t.safeExtend=n=>_v(t,n),t.merge=n=>Mv(t,n),t.pick=n=>Pv(t,n),t.omit=n=>$v(t,n),t.partial=(...n)=>Uv(th,t,n[0]),t.required=(...n)=>Zv(nh,t,n[0])});function ie(t,e){const n={type:"object",get shape(){return et(this,"shape",t?xv(t):{}),this.shape},...N(e)};return new yO(n)}const mO=y("ZodUnion",(t,e)=>{gS.init(t,e),G.init(t,e),t.options=e.options});function _i(t,e){return new mO({type:"union",options:t,...N(e)})}const gO=y("ZodIntersection",(t,e)=>{wS.init(t,e),G.init(t,e)});function wO(t,e){return new gO({type:"intersection",left:t,right:e})}const Ia=y("ZodEnum",(t,e)=>{bS.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 Ia({...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 Ia({...e,checks:[],...N(s),entries:i})}});function bO(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Ia({type:"enum",entries:n,...N(e)})}const vO=y("ZodTransform",(t,e)=>{vS.init(t,e),G.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new ju(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 TO(t){return new vO({type:"transform",transform:t})}const th=y("ZodOptional",(t,e)=>{TS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function il(t){return new th({type:"optional",innerType:t})}const SO=y("ZodNullable",(t,e)=>{SS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ol(t){return new SO({type:"nullable",innerType:t})}const zO=y("ZodDefault",(t,e)=>{zS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function OO(t,e){return new zO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Ru(e)}})}const EO=y("ZodPrefault",(t,e)=>{OS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function kO(t,e){return new EO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Ru(e)}})}const nh=y("ZodNonOptional",(t,e)=>{ES.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function NO(t,e){return new nh({type:"nonoptional",innerType:t,...N(e)})}const xO=y("ZodCatch",(t,e)=>{kS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function AO(t,e){return new xO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const IO=y("ZodPipe",(t,e)=>{NS.init(t,e),G.init(t,e),t.in=e.in,t.out=e.out});function ll(t,e){return new IO({type:"pipe",in:t,out:e})}const CO=y("ZodReadonly",(t,e)=>{xS.init(t,e),G.init(t,e),t.unwrap=()=>t._zod.def.innerType});function jO(t){return new CO({type:"readonly",innerType:t})}const PO=y("ZodCustom",(t,e)=>{AS.init(t,e),G.init(t,e)});function $O(t,e={}){return bz(PO,t,e)}function RO(t){return vz(t)}const Pe=t=>t?JSON.parse(t):{},Mi=ie({key:ge(),type:ge(),config:Oe.unknownZ.or(ge().transform(Pe)),source:ge().optional()}),rh=Mi.extend({position:Ti.xy}),Ca=ie({param:ge(),node:ge()}),Ui=ie({source:Ca,target:Ca}),_O=ie({nodes:Mi.array(),edges:Ui.array()}),sh=ie({nodes:rh.array(),edges:Ui.array()}),ah=ie({raw:ge()}),Gn=qz(),cs=ie({key:Gn,name:ge(),graph:sh,text:ah,deploy:ls(),version:ge()}),ih=cs.partial({key:!0}),oh="arc",MO=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=v.toArray(t);const i=s[0],o=typeof i;let l;return o==="string"&&n&&!isNaN(parseInt(i))&&"number"in e?(l=e.number,s=s.map(c=>parseInt(c))):l=e[o],{single:r,variant:l,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 Ar(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},UO="/arc/retrieve",ZO="/arc/create",LO="/arc/delete",DO=ie({keys:Gn.array().optional(),names:ge().array().optional(),searchTerm:ge().optional(),limit:rl().optional(),offset:rl().optional(),includeStatus:ls().optional()}),BO=ie({arcs:ih.array()}),FO=ie({keys:Gn.array()}),YO=ie({arcs:v.nullableZ(cs)}),qO=ie({arcs:cs.array()}),VO=ie({}),WO=ie({key:Gn,includeStatus:ls().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),HO=ie({name:ge(),includeStatus:ls().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),lh=_i([WO,HO]),GO=_i([lh,DO]);let ch=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=await b(this.client,ZO,{arcs:v.toArray(t)},BO,qO);return e?n.arcs:n.arcs[0]}async retrieve(t){const e="key"in t||"name"in t,n=await b(this.client,UO,t,GO,YO);return ue("Arc",t,n.arcs,e),e?n.arcs[0]:n.arcs}async delete(t){await b(this.client,LO,{keys:v.toArray(t)},FO,VO)}};const KO=t=>({type:oh,key:t}),JO=Object.freeze(Object.defineProperty({__proto__:null,Client:ch,ONTOLOGY_TYPE:oh,arcZ:cs,edgeZ:Ui,graphNodeZ:rh,graphZ:sh,handleZ:Ca,irNodeZ:Mi,irZ:_O,keyZ:Gn,newZ:ih,ontologyID:KO,singleRetrieveArgsZ:lh,textZ:ah},Symbol.toStringTag,{value:"Module"})),cl="Channel key must be a valid uint32.",L=a.z.uint32().or(a.z.string().refine(t=>!isNaN(Number(t)),{message:cl}).transform(Number).refine(t=>t<ba.MAX_UINT32,{message:cl})),_e=a.z.string(),uh=rn.statusZ(),an=a.z.object({name:_e,key:L,dataType:_.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:uh.optional()}),hh=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(_e),zn.toArray(an).transform(t=>t.map(e=>e.key))]),XO=new Error("request for lock canceled");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 l(h){try{u(r.next(h))}catch(p){o(p)}}function c(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(l,c)}u((r=r.apply(t,e||[])).next())})};class eE{constructor(e,n=XO){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=dh(this._queue,l=>n<=l.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return QO(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]=[]),tE(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 tE(t,e){const n=dh(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function dh(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var nE=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 l(h){try{u(r.next(h))}catch(p){o(p)}}function c(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(l,c)}u((r=r.apply(t,e||[])).next())})};class rE{constructor(e){this._semaphore=new eE(1,e)}acquire(){return nE(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 sE=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:_.z.array().optional(),notDataTypes:_.z.array().optional(),virtual:a.z.boolean().optional(),isIndex:a.z.boolean().optional(),internal:a.z.boolean().optional(),calculated:a.z.boolean().optional()}),aE=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]),MO(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,sE,aE);if(r!=null)throw r;return n.channels}}class Zi{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(l=>{const c=this.get(l);c!=null?s.push(...c):i.push(l)}),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 l=this.namesToKeys.get(o.name);l!=null&&(l.delete(r),l.size===0&&this.namesToKeys.delete(o.name)),o.name=i,this.cache.set(r,o);const c=this.namesToKeys.get(i);c==null?this.namesToKeys.set(i,new Set([r])):c.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 fh{mu=new rE;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=cw(()=>{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 ph=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},iE="sy_channel_set",oE="sy_channel_delete";class ja{_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:l=!1,virtual:c=!1,frameClient:u,alias:h,status:p,expression:f="",requires:O=[]}){this.key=L.parse(s),this.name=n,this.dataType=new _(e),this.leaseholder=r,this.index=L.parse(o),this.isIndex=i,this.internal=l,this.alias=h,this.virtual=c,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 Pr(this.payload)}get ontologyID(){return gh(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 lE="sy_calculation_status",cE="/channel/retrieve-group",uE=a.z.object({}),hE=a.z.object({group:ns});let yh=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(c=>c.name)),l=new Set(o.map(c=>c.name));s=s.filter(c=>!l.has(c.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 Zi(new fh(new Kn(this.client),t))}sugar(t){const{frameClient:e}=this;return Array.isArray(t)?t.map(n=>new ja({...n,frameClient:e})):new ja({...t,frameClient:e})}async retrieveGroup(){return(await b(this.client,cE,{},uE,hE)).group}};const Pr=({virtual:t,expression:e})=>t&&e!=="",mh=async(t,e)=>{if(!Pr(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(Pr(r)){const s=await mh(t,r);if(s!=null)return s}}return null},gh=t=>({type:"channel",key:t.toString()}),dE=a.z.object({channels:hh.array()}),fE=a.z.object({channels:an.array()}),pE=a.z.object({keys:L.array().optional(),names:_e.array().optional()}),yE=a.z.object({}),mE=a.z.object({keys:L.array(),names:_e.array()}),gE=a.z.object({}),wE="/channel/create",bE="/channel/delete",vE="/channel/rename";let wh=class{client;cache;constructor(t,e){this.client=t,this.cache=e}async create(t){const{channels:e}=await b(this.client,wE,{channels:t.map(n=>({...n,dataType:n.dataType}))},dE,fE);return this.cache.set(e),e}async delete(t){const e=L.array().parse(t.keys??[]);await b(this.client,bE,t,pE,yE),e.length>0&&this.cache.delete(e),t.names!=null&&this.cache.delete(t.names)}async rename(t,e){await b(this.client,vE,{keys:t,names:e},mE,gE),this.cache.rename(t,e)}};const Pa=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:lE,CacheRetriever:Zi,Channel:ja,Client:yh,ClusterRetriever:Kn,DELETE_CHANNEL_NAME:oE,DebouncedBatchRetriever:fh,SET_CHANNEL_NAME:iE,Writer:wh,analyzeParams:Se,isCalculated:Pr,keyZ:L,nameZ:_e,newZ:hh,ontologyID:gh,paramsZ:bt,payloadZ:an,resolveCalculatedIndex:mh,retrieveRequired:ph,statusZ:uh},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)}),bh=Jn.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:a.z.string().min(1)}),TE=a.z.object({keys:nt.array().optional(),usernames:a.z.string().array().optional()}),SE=a.z.object({key:nt}).transform(({key:t})=>({keys:[t]})),zE=a.z.object({username:a.z.string()}).transform(({username:t})=>({usernames:[t]})),OE=a.z.object({usernames:a.z.string().array()}).transform(({usernames:t})=>({usernames:t})),EE=a.z.union([SE,zE,OE,TE]),kE=a.z.object({users:v.nullableZ(Jn)}),NE=a.z.object({users:bh.array()}),xE=a.z.object({users:Jn.array()}),AE=a.z.object({key:nt,username:a.z.string().min(1)}),IE=a.z.object({}),CE=a.z.object({key:nt,firstName:a.z.string().optional(),lastName:a.z.string().optional()}),jE=a.z.object({}),PE=a.z.object({keys:nt.array()}),$E=a.z.object({}),RE="/user/retrieve",_E="/user/create",ME="/user/change-username",UE="/user/rename",ZE="/user/delete";let vh=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=await b(this.client,_E,{users:v.toArray(t)},NE,xE);return e?n.users:n.users[0]}async changeUsername(t,e){await b(this.client,ME,{key:t,username:e},AE,IE)}async retrieve(t){const e="key"in t||"username"in t,n=await b(this.client,RE,t,EE,kE);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 Ar(`Multiple users found with ${r}`)}return n.users[0]}async rename(t,e,n){await b(this.client,UE,{key:t,firstName:e,lastName:n},CE,jE)}async delete(t){await b(this.client,ZE,{keys:v.toArray(t)},PE,$E)}};const LE=t=>({type:"user",key:t}),DE=Object.freeze(Object.defineProperty({__proto__:null,Client:vh,keyZ:nt,newZ:bh,ontologyID:LE,userZ:Jn},Symbol.toStringTag,{value:"Module"})),BE=a.z.object({username:a.z.string(),password:a.z.string()}),FE=a.z.object({token:a.z.string(),user:Jn}),ul="/auth/login",YE=3,qE="/auth/change-password",VE=a.z.object({username:a.z.string(),password:a.z.string(),newPassword:a.z.string().min(1)}),WE=a.z.object({}),HE=[Ea,ka];let GE=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,qE,{username:this.credentials.username,password:this.credentials.password,newPassword:t},VE,WE),this.credentials.password=t}middleware(){const t=async(e,n)=>{if(!this.authenticated&&!e.target.endsWith(ul)){this.authenticating??=new Promise((o,l)=>{this.client.send(ul,this.credentials,BE,FE).then(([c,u])=>{if(u!=null)return o(u);this.token=c?.token,this.user=c?.user,this.authenticated=!0,o(null)}).catch(l)});const i=await this.authenticating;if(i!=null)return[e,i]}e.params.Authorization=`Bearer ${this.token}`;const[r,s]=await n(e);return HE.some(i=>i.matches(s))&&this.retryCount<YE?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,t(e,n)):(this.retryCount=0,[r,s])};return t}};const KE=a.z.enum(["disconnected","connecting","connected","failed"]),JE=a.z.object({status:KE,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()}),XE=a.z.object({clusterKey:a.z.string(),nodeVersion:a.z.string().optional()}),hl={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.46.0"},dl=(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 $r{static ENDPOINT="/connectivity/check";static DEFAULT=hl;_state;pollFrequency=x.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=JE;versionWarned=!1;constructor(e,n=x.seconds(30),r,s){this._state={...hl},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($r.ENDPOINT,{},a.z.object({}),XE);if(r!=null)throw r;const s=n.nodeVersion,i=this.clientVersion,o=this.versionWarned;s==null?(this._state.clientServerCompatible=!1,o||(console.warn(dl(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(dl(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 QE=a.z.object({keys:L.array().optional(),bounds:F.z,names:_e.array().optional()}),ek=a.z.object({}),tk="/frame/delete";class nk{client;constructor(e){this.client=e}async delete(e){await b(this.client,tk,e,QE,ek)}}const fl=t=>{const e=v.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},pl=(t,e)=>{const n=v.toArray(t);if(n.length===e.length)return;const r=fl(t);throw fl===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 ce=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=>Th(i));pl(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);pl(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 Ao.unique(this.keys)}get names(){if(this.colType==="key")throw new ee("colType is not name");return this.columns??[]}get uniqueNames(){return Ao.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Sh(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 ow(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 us=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([])])}),Th=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new We({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},Sh=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 rk=new x(-1);class $a extends je.sub("writer_closed"){constructor(){super("WriterClosed")}}const sk=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}})),zh=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:sk.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)}),ak=zh.extend({keys:L.array().optional()}),yl=zh.extend({channels:bt}),Oh=yl.or(bt.transform(t=>yl.parse({channels:t,start:C.now()}))),ik=a.z.object({command:a.z.enum(Lt),config:ak.optional(),frame:us.optional(),buffer:a.z.instanceof(Uint8Array).optional()}),ok=a.z.object({command:a.z.enum(Lt),end:C.z,err:Me.payloadZ.optional()}),lk=a.z.tuple([a.z.union([a.z.record(L.or(_e),me.authorityZ),L.or(_e),me.authorityZ]),me.authorityZ.optional()]).transform(([t,e])=>{if(me.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(L.or(_e).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 Eh=class Ra{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=Oh.parse(r),i=await Di.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new pk(i.codec)));const o=await n.stream(Ra.ENDPOINT,ik,ok),l=new Ra(o,i);return await l.execute({command:0,config:{...s,keys:i.keys}}),l}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=lk.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($a.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=ze.matches(r)?new $a:r:this.closeErr=Me.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=Me.decode(r?.err);if(i!=null&&await this.closeInternal(i),r?.command==e.command)return r}}};const ml=t=>t.data.byteLength/t.dataType.density.valueOf(),ck=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)},gl=5,wl=4,bl=3,vl=2,Tl=1,Sl=0,ke=_.TIMESTAMP.density.valueOf(),Be=8,Fe=4,Ys=4,qs=4,uk=1;class kh{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()),ck(r);let s=-1,i,o,l,c=n+uk+qs,u=!this.currState?.hasVariableDataTypes,h=!0,p=!0,f=!0,O=!0,I=!0;r.keys.length!==this.currState?.keys.length&&(f=!1,c+=r.keys.length*Ys),r.series.forEach((A,W)=>{const J=ml(A),un=r.keys[W],lt=this.currState?.keyDataTypes.get(un);if(lt==null)throw new D(`Channel ${un} was not provided in the list of channels when opening the writer`);if(!lt.equals(A.dataType))throw new D(`Series data type of ${A.dataType.toString()} does not match the data type of ${lt.toString()} for channel ${un}`);if(c+=A.data.byteLength,s===-1){s=J,i=A.timeRange?.start,o=A.timeRange?.end,l=BigInt(A.alignment??0n);return}s!==J&&(u=!1),(i?.valueOf()!==A.timeRange?.start.valueOf()||o?.valueOf()!==A.timeRange?.end.valueOf())&&(h=!1),l!==BigInt(A.alignment??0)&&(O=!1)}),p=h&&i==null&&o==null,I=O&&(l===void 0||l===0n),u?c+=Fe:c+=r.keys.length*Fe,p||(h?c+=ke*2:c+=r.keys.length*ke*2),I||(O?c+=Be:c+=r.keys.length*Be);const j=new Uint8Array(c),w=new DataView(j.buffer);let T=n;return j[T]=Number(I)<<gl|Number(O)<<wl|Number(u)<<bl|Number(h)<<vl|Number(p)<<Tl|Number(f)<<Sl,T++,w.setUint32(T,this.seqNum,!0),T+=qs,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+=ke*2),O&&!I&&(w.setBigUint64(T,l??0n,!0),T+=Be),r.series.forEach((A,W)=>{if(f||(w.setUint32(T,r.keys[W],!0),T+=Ys),!u){let J=A.data.byteLength;A.dataType.isVariable||(J=ml(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+=ke*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,l=0,c,u,h;const p=new DataView(r.buffer,r.byteOffset,r.byteLength),f=!!(r[i]>>gl&1),O=!!(r[i]>>wl&1),I=!!(r[i]>>bl&1),j=!!(r[i]>>vl&1),w=!!(r[i]>>Tl&1),T=!!(r[i]>>Sl&1);i++;const A=p.getUint32(i,!0);i+=qs;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+ke>p.byteLength)return s;c=new C(p.getBigUint64(i,!0)),i+=ke,u=new C(p.getBigUint64(i,!0)),i+=ke}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+=Ys,s.keys.push(J)}const lt=W.keyDataTypes.get(J);if(l=0,I)l=o;else{if(i+Fe>p.byteLength)return;l=p.getUint32(i,!0),i+=Fe}let rr=l;if(lt.isVariable||(rr*=lt.density.valueOf()),i+rr>p.byteLength){s.keys.splice(un,1);return}const ct={dataType:lt,data:r.slice(i,i+rr).buffer};if(i+=rr,!j&&!w){if(i+ke*2>p.byteLength)return;const Xf=p.getBigUint64(i,!0);i+=ke;const Qf=p.getBigUint64(i,!0);i+=ke,ct.timeRange=new F({start:Xf,end:Qf})}else w?ct.timeRange=new F({start:0n,end:0n}):ct.timeRange=new F({start:c?.valueOf()??0n,end:u?.valueOf()??0n});if(!O&&!f){if(i+Be>p.byteLength)return;h=p.getBigUint64(i,!0),i+=Be,ct.alignment=h}else f?ct.alignment=0n:ct.alignment=h;s.series.push(ct)}),s}}const Li=254,hk=new Uint8Array([Li]),dk=255,fk=new Uint8Array([dk]),Nh="application/sy-framer";class pk{contentType=Nh;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(hk,0),i.set(new Uint8Array(s),1),i}const r=this.base.encode(n.payload?.frame,1);return r.set(fk,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Li)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 yk{contentType=Nh;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)===Li?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class hs{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new kh}static async open(e,n){const r=new hs(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(l=>l.key);if(Io.uniqueUnorderedPrimitiveArrays(this.keys,i)===Io.EQUAL)return!1;if(this.codec.update(i,s.map(l=>l.dataType)),n==="keys")return this.adapter=null,this.keys=r,!0;const o=new Map;return this.adapter=o,r.forEach(l=>{const c=s.find(u=>u.name===l);if(c==null)throw new Error(`Channel ${l} not found`);o.set(c.key,c.name)}),this.keys=Array.from(this.adapter.keys()),!0}adapt(e){if(this.adapter==null)return e;const 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 Di{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new kh}static async open(e,n){const r=new Di(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 ph(this.retriever,e),r=n.map(c=>c.key),s=new Set(this.keys),i=new Set(r),o=!i.isSubsetOf(s),l=!s.isSubsetOf(i);return o||l?(this.adapter=new Map(n.map(c=>[c.name,c.key])),this.keys=r,this.codec.update(this.keys,n.map(c=>c.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(c=>c instanceof We||Array.isArray(c)))throw new D(`
53
+ Received a single channel name or key but multiple series.
54
+ `);n=n}const o=await this.fetchChannel(e),l=new We({data:n,dataType:o.dataType});return new ce(o.key,l)}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=[],l=[];for(let c=0;c<e.length;c++){const u=await this.fetchChannel(e[c]);if(c>=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[c],dataType:u.dataType});o.push(u.key),l.push(h)}return new ce(o,l)}if(e instanceof ce||e instanceof Map){const o=new ce(e);if(this.adapter==null)return o;const l=o.columns.map(c=>{const u=typeof c=="string"?this.adapter?.get(c):c;if(u==null)throw new D(`
61
+ Channel ${c} was not provided in the list of channels when opening the writer
62
+ `);return u});return new ce(l,o.series)}const r=[],s=[],i=Object.entries(e);for(let o=0;o<i.length;o++){const[l,c]=i[o],u=await this.fetchChannel(l),h=new We({data:c,dataType:u.dataType});r.push(u.key),s.push(h)}return new ce(r,s)}}class xh{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 Rr=new x(-1);var Bi=(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))(Bi||{}),Ah=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(Ah||{});const mk=a.z.object({command:a.z.enum(Bi),span:x.z.optional(),bounds:F.z.optional(),stamp:C.z.optional(),keys:L.array().optional(),chunkSize:a.z.number().optional()}),gk=a.z.object({variant:a.z.enum(Ah),ack:a.z.boolean(),command:a.z.enum(Bi),error:Me.payloadZ.optional().nullable(),frame:us.optional()});class $n{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,n){this.stream=new xh("Iterator",e),this.value=new ce,this.adapter=n}static async _open(e,n,r,s,i={}){const o=await hs.open(r,n),l=await s.stream($n.ENDPOINT,mk,gk),c=new $n(l,o);return await c.execute({command:0,keys:o.keys,bounds:new F(e),chunkSize:i.chunkSize??1e5}),c}async next(e=Rr){return await this.execute({command:1,span:new x(e)})}async prev(e=Rr){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 wk(this)}async execute(e){for(this.stream.send(e),this.value=new ce;;){const n=await this.stream.receive();if(n.variant===1)return n.ack;this.value.push(this.adapter.adapt(new ce(n.frame)))}}}class wk{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 bk=a.z.object({keys:a.z.number().array(),downsampleFactor:a.z.number()}),vk=a.z.object({frame:us}),Tk="/frame/stream",zl=a.z.object({channels:bt,downsampleFactor:a.z.number().optional().default(1),useHighPerformanceCodec:a.z.boolean().optional().default(!0)}),Fi=zl.or(bt.transform(t=>zl.parse({channels:t}))),Ih=(t,e)=>async n=>{const r=Fi.parse(n),s=await hs.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new yk(s.codec)));const i=await e.stream(Tk,bk,vk),o=new Sk(i,s);i.send({keys:s.keys,downsampleFactor:r.downsampleFactor??1});const[,l]=await i.receive();if(l!=null)throw l;return o},Ch=async(t,e,n)=>await Ih(t,e)(n);class Sk{stream;adapter;downsampleFactor;constructor(e,n){this.stream=new xh("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 ce((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 ds{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=Fi.parse(n);const{maxRetries:s=5e3,baseInterval:i=x.seconds(1),scale:o=1}=r??{};this.breaker=new ou.Breaker({maxRetries:s,baseInterval:i,scale:o})}static async open(e,n,r){const s=new ds(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 jh extends yw.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 zk=t=>({type:"framer",key:t.toString()});let Ph=class{streamClient;retriever;deleter;constructor(t,e,n){this.streamClient=t,this.retriever=n,this.deleter=new nk(e)}async openIterator(t,e,n){return await $n._open(t,e,this.retriever,this.streamClient,n)}async openWriter(t){return await Eh._open(this.retriever,this.streamClient,t)}async openStreamer(t){return await Ch(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 ce;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 ce;if(e>0)try{await n.seekLast(),await n.prev(Rr),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 $h=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:rk,AUTO_SPAN:Rr,Client:Ph,Frame:ce,HardenedStreamer:ds,Iterator:$n,ObservableStreamer:jh,Writer:Eh,WriterClosedError:$a,WriterCommand:Lt,WriterMode:Pn,createStreamOpener:Ih,frameZ:us,ontologyID:zk,openStreamer:Ch,seriesFromPayload:Th,seriesToPayload:Sh,streamerConfigZ:Fi,writerConfigZ:Oh},Symbol.toStringTag,{value:"Module"})),Ok=me.ABSOLUTE_AUTHORITY,Ek=me.ZERO_AUTHORITY,kk=me.stateZ(a.z.number()),Nk=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()})`,xk=a.z.object({transfers:a.z.array(me.transferZ(L))});class Rh extends jh{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,xk);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 _h="sy_node_1_control";let Mh=class{framer;constructor(t){this.framer=t}async openStateTracker(){const t=await ds.open(async e=>await this.framer.openStreamer(e),_h);return new Rh(t)}};const Ak=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Ok,CONTROL_STATE_CHANNEL_NAME:_h,Client:Mh,StateTracker:Rh,ZERO_AUTHORITY:Ek,stateZ:kk,transferString:Nk},Symbol.toStringTag,{value:"Module"}));let Ik=class{tasks;racks;devices;constructor(t,e,n){this.tasks=t,this.racks=e,this.devices=n}};const Ee=a.z.uint32(),Uh=a.z.object({rack:Ee}),Zh=rn.statusZ(Uh),fs=a.z.object({key:Ee,name:a.z.string(),status:zn.nullToUndefined(Zh)}),Lh=fs.partial({key:!0}),Dh=t=>t?wt.JSON_CODEC.decodeString(t,Oe.unknownZ):{},on=a.z.string(),Bh=a.z.object({rack:Ee,device:on}),Fh=rn.statusZ(Bh),ps=a.z.object({key:on,rack:Ee.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(Dh)),status:zn.nullToUndefined(Fh)}),Yh=ps.extend({properties:a.z.unknown().transform(t=>wt.JSON_CODEC.encodeString(t))}),Ck="sy_device_set",jk="sy_device_delete",Pk="sy_device_status",$k="/hardware/device/retrieve",Rk="/hardware/device/create",_k="/hardware/device/delete",Mk=a.z.object({devices:Yh.array()}),Uk=a.z.object({devices:ps.array()}),Zk=a.z.object({keys:on.array()}),Lk=a.z.object({}),Dk=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:Ee.array().optional(),searchTerm:a.z.string().optional(),limit:a.z.number().optional(),offset:a.z.number().optional(),includeStatus:a.z.boolean().optional()}),Bk=a.z.object({devices:v.nullableZ(ps)}),Fk=a.z.object({key:on,includeStatus:a.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),Yk=a.z.union([Fk,Dk]);let qh=class{client;constructor(t){this.client=t}async retrieve(t){const e=typeof t=="object"&&"key"in t,n=await b(this.client,$k,t,Yk,Bk);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,Rk,{devices:v.toArray(t)},Mk,Uk)).devices;return e?n[0]:n}async delete(t){await b(this.client,_k,{keys:v.toArray(t)},Zk,Lk)}};const qk=t=>({type:"device",key:t}),Vk=Object.freeze(Object.defineProperty({__proto__:null,Client:qh,DELETE_CHANNEL_NAME:jk,SET_CHANNEL_NAME:Ck,STATUS_CHANNEL_NAME:Pk,deviceZ:ps,keyZ:on,newZ:Yh,ontologyID:qk,statusDetailsSchema:Bh,statusZ:Fh},Symbol.toStringTag,{value:"Module"})),Wk="/hardware/rack/retrieve",Hk="/hardware/rack/create",Gk="/hardware/rack/delete",Kk="sy_rack_status",Jk="sy_rack_set",Xk="sy_rack_delete",Qk=a.z.object({keys:Ee.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()}),e0=a.z.object({racks:v.nullableZ(fs)}),t0=a.z.union([a.z.object({key:Ee,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}))]),n0=Qk,r0=a.z.union([t0,n0]),s0=a.z.object({racks:Lh.array()}),a0=a.z.object({racks:fs.array()}),i0=a.z.object({keys:Ee.array()}),o0=a.z.object({});let Vh=class{client;tasks;constructor(t,e){this.client=t,this.tasks=e}async delete(t){await b(this.client,Gk,{keys:v.toArray(t)},i0,o0)}async create(t){const e=!Array.isArray(t),n=await b(this.client,Hk,{racks:v.toArray(t)},s0,a0),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,Wk,t,r0,e0),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 Wh(r,s,this.tasks,i));return e?n[0]:n}};class Wh{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 l0=t=>({type:"rack",key:t.toString()}),c0=Object.freeze(Object.defineProperty({__proto__:null,Client:Vh,DELETE_CHANNEL_NAME:Xk,Rack:Wh,SET_CHANNEL_NAME:Jk,STATUS_CHANNEL_NAME:Kk,keyZ:Ee,newZ:Lh,ontologyID:l0,rackZ:fs,statusDetailsSchema:Uh,statusZ:Zh},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())]),Hh=t=>a.z.object({task:Ze,running:a.z.boolean(),data:t}),Yi=t=>rn.statusZ(Hh(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(Dh).or(t.configSchema),status:Yi(t.statusDataSchema).optional().nullable(),snapshot:a.z.boolean().optional()}),Gh=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))}),u0=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()}),h0=t=>Number(BigInt(t)>>32n),_a="sy_task_status",Ma="sy_task_cmd",d0="sy_task_set",f0="sy_task_delete",ht=new Error("Task not created"),Kh=async(t,e)=>{const n=await e.retrieveParents(qi(t));return n.length===0?null:n[0]};class Jh{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:l},c,u,h,p){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=c??{typeSchema:a.z.string(),configSchema:a.z.unknown(),statusDataSchema:a.z.unknown()},this.internal=i,this.snapshot=o,this.status=l,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=p}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return qi(this.key)}async executeCommand(e){return await ed({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await td({...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 Kh(this.key,this.ontologyClient):null}}const p0=a.z.object({rack:Ee.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()}),Xh=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:Ee.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),y0=p0,m0=a.z.union([Xh,y0]),g0=t=>a.z.object({tasks:v.nullableZ(Xn(t))}),w0="/hardware/task/retrieve",b0="/hardware/task/create",v0="/hardware/task/delete",T0="/hardware/task/copy",S0=t=>a.z.object({tasks:Gh(t).array()}),z0=t=>a.z.object({tasks:Xn(t).array()}),O0=a.z.object({keys:Ze.array()}),E0=a.z.object({}),k0=a.z.object({key:Ze,name:a.z.string(),snapshot:a.z.boolean()}),N0=t=>a.z.object({task:Xn(t)});let Qh=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=S0(e),s=z0(e),i=await b(this.client,b0,{tasks:v.toArray(t)},r,s),o=this.sugar(i.tasks,e);return n?o[0]:o}async delete(t){await b(this.client,v0,{keys:v.toArray(t)},O0,E0)}async retrieve({schemas:t,...e}){const n=Xh.safeParse(e).success,r=(await b(this.client,w0,e,m0,g0(t))).tasks,s=this.sugar(r,t);return ue("Task",e,s,n),n?s[0]:s}async copy(t,e,n){const r=N0(),s=await b(this.client,T0,{key:t,name:e,snapshot:n},k0,r);return this.sugar(s.task)}async retrieveSnapshottedTo(t){if(this.ontologyClient==null)throw ht;return await Kh(t,this.ontologyClient)}sugar(t,e){const n=!Array.isArray(t),r=v.toArray(t).map(({key:s,name:i,type:o,config:l,status:c,internal:u,snapshot:h})=>new Jh({key:s,name:i,type:o,config:l,internal:u,snapshot:h,status:c},e,this.frameClient,this.ontologyClient,this.rangeClient));return n?r[0]:r}async executeCommand(t){return"commands"in t?await Vi({...t,frameClient:this.frameClient}):await ed({...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 nd({...t,frameClient:this.frameClient,name:n})}const e=async()=>{const{task:n}=t;return(await this.retrieve({key:n})).name};return await td({frameClient:this.frameClient,name:e,...t})}};const qi=t=>({type:"task",key:t}),ed=async({frameClient:t,task:e,type:n,args:r})=>(await Vi({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],Vi=async({frameClient:t,commands:e})=>{if(t==null)throw ht;const n=await t.openWriter(Ma),r=e.map(s=>({...s,key:jg.create()}));return await n.write(Ma,r),await n.close(),r.map(s=>s.key)},td=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:i,args:o})=>(await nd({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:i,name:s}))[0],nd=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 Vi({frameClient:t,commands:e}),l=new x(n);let c=[],u;const h=new Promise((p,f)=>{u=setTimeout(()=>{(async()=>{const O=e.map(I=>I.task);f(await x0("command",s,l,O))})()},l.milliseconds)});try{for(;;){const p=await Promise.race([i.read(),h]),f=Yi(r).parse(p.at(-1)[_a]);if(o.includes(f.key)&&(c=[...c.filter(O=>O.key!==f.key),f],c.length===o.length))return c}}finally{clearTimeout(u),i.close()}},x0=async(t,e,n,r)=>{const s=fm.capitalize(t),i=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=v.toArray(await e());const l=za.naturalLanguageJoin(o);return new Error(`${s} command to ${l} 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 ${za.naturalLanguageJoin(r)} timed out after ${i}`)}},A0=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:Ma,Client:Qh,DELETE_CHANNEL_NAME:f0,SET_CHANNEL_NAME:d0,STATUS_CHANNEL_NAME:_a,Task:Jh,commandZ:u0,keyZ:Ze,newZ:Gh,ontologyID:qi,rackKey:h0,statusDetailsZ:Hh,statusZ:Yi,taskZ:Xn},Symbol.toStringTag,{value:"Module"})),rt=Su.keyZ,Qn=Su.labelZ,I0="labeled_by",C0="sy_label_set",j0="sy_label_delete",rd=Qn.extend({key:rt.optional()}),P0=a.object({labels:rd.array()}),$0=a.object({labels:Qn.array()}),R0=a.object({keys:rt.array()}),sd=a.object({id:U,labels:rt.array(),replace:a.boolean().optional()}),_0=sd.omit({replace:!0}),Vs=a.object({}),M0="/label/create",U0="/label/delete",Z0="/label/set",L0="/label/remove",D0="/label/retrieve",B0=a.object({keys:rt.array().optional(),for:U.optional(),searchTerm:a.string().optional(),offset:a.number().optional(),limit:a.number().optional()}),F0=a.object({key:rt}).transform(({key:t})=>({keys:[t]})),Y0=a.union([F0,B0]),q0=a.object({labels:v.nullableZ(Qn)});let ad=class{type="label";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,n=await b(this.client,D0,t,Y0,q0);return ue("Label",t,n.labels,e),e?n.labels[0]:n.labels}async label(t,e,n={}){await b(this.client,Z0,{id:t,labels:e,replace:n.replace},sd,Vs)}async remove(t,e){await b(this.client,L0,{id:t,labels:e},_0,Vs)}async create(t){const e=Array.isArray(t),n=await b(this.client,M0,{labels:v.toArray(t)},P0,$0);return e?n.labels:n.labels[0]}async delete(t){await b(this.client,U0,{keys:v.toArray(t)},R0,Vs)}};const V0=t=>({type:"label",key:t}),W0=Object.freeze(Object.defineProperty({__proto__:null,Client:ad,DELETE_CHANNEL_NAME:j0,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:I0,SET_CHANNEL_NAME:C0,keyZ:rt,labelZ:Qn,newZ:rd,ontologyID:V0},Symbol.toStringTag,{value:"Module"})),te=a.z.uuid(),Wi=a.z.string().min(1),er=a.z.object({key:te,name:Wi,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()<=ba.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()>=ba.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)}}),id=er.omit({parent:!0,labels:!0}).partial({key:!0}),H0="sy_range_alias_set",G0="sy_range_alias_delete",K0=a.z.object({range:te,aliases:a.z.string().array()}),J0=a.z.object({aliases:a.z.record(a.z.string(),L)}),X0=a.z.object({range:te,aliases:a.z.record(L,a.z.string())}),Q0=a.z.unknown(),eN=a.z.object({range:te,channels:L.array()}),tN=a.z.unknown(),nN=a.z.object({range:te}),rN=a.z.object({aliases:a.z.record(a.z.string(),a.z.string())}),sN=a.z.object({range:te,channels:L.array()}),aN=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 l=this.cache.get(o);l!=null?s[o]=l:n.push(o)});if(n.length===0)return s;const i=await b(this.client,At.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:n},K0,J0);return Object.entries(i.aliases).forEach(([o,l])=>this.cache.set(o,l)),r?i.aliases[n[0]]:{...s,...i.aliases}}async set(e){await b(this.client,At.SET_ENDPOINT,{range:this.rangeKey,aliases:e},X0,Q0)}async list(){return(await b(this.client,At.LIST_ENDPOINT,{range:this.rangeKey},nN,rN)).aliases}async retrieve(e){const n=typeof e=="number",r=await b(this.client,At.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:v.toArray(e)},sN,aN);return n?r.aliases[e]:r.aliases}async delete(e){await b(this.client,At.DELETE_ENDPOINT,{range:this.rangeKey,channels:v.toArray(e)},eN,tN)}};const iN=a.z.object({alias:a.z.string().optional(),channel:L,range:te}),od="---",oN=t=>`${t.range}${od}${t.channel}`,lN=t=>{const[e,n]=t.split(od);return{range:e,channel:Number(n)}},cN="sy_range_kv_set",uN="sy_range_kv_delete",Hi=a.z.object({range:te,key:a.z.string(),value:a.z.string()}),hN=({range:t,key:e})=>`${t}<--->${e}`,dN=a.z.object({range:te,keys:a.z.string().array()}),fN=a.z.object({pairs:v.nullableZ(Hi)}),pN=a.z.object({range:te,pairs:Hi.array()}),yN=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)},dN,fN);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;pc(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},pN,a.z.unknown())}async delete(e){await b(this.client,pt.DELETE_ENDPOINT,{range:this.rangeKey,keys:v.toArray(e)},yN,a.z.unknown())}}const mN="sy_range_set",gN="sy_range_delete";class ld{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:l,kv:c,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=l,this.color=s,this.kv=c,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 wN=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()}),bN=wN.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}))),vN="/range/retrieve",TN=a.z.object({ranges:v.nullableZ(er)});let cd=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,vN,t,bN,TN);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(ud(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 ld(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}),SN=t=>({type:"range-alias",key:t}),ud=({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}},zN=a.z.object({ranges:er.array()}),ON=a.z.object({parent:U.optional(),ranges:id.array()}),EN=a.z.object({keys:te.array()}),kN=a.z.object({}),NN=a.z.object({key:te,name:Wi}),xN=a.z.object({}),AN="/range/create",IN="/range/delete",CN="/range/rename";class hd{client;constructor(e){this.client=e}async rename(e,n){await b(this.client,CN,{key:e,name:n},NN,xN)}async create(e,n){return(await b(this.client,AN,{ranges:e,...n},ON,zN)).ranges}async delete(e){await b(this.client,IN,{keys:e},EN,kN)}}const jN=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:ut,Client:cd,DELETE_ALIAS_CHANNEL_NAME:G0,DELETE_CHANNEL_NAME:gN,KV:pt,KV_DELETE_CHANNEL:uN,KV_SET_CHANNEL:cN,Range:ld,SET_ALIAS_CHANNEL_NAME:H0,SET_CHANNEL_NAME:mN,Writer:hd,aliasKey:oN,aliasOntologyID:SN,aliasZ:iN,convertOntologyResourceToPayload:ud,decodeDeleteAliasChange:lN,keyZ:te,kvPairKey:hN,kvPairZ:Hi,nameZ:Wi,newZ:id,ontologyID:Pt,payloadZ:er},Symbol.toStringTag,{value:"Module"})),ys=a.z.string(),ms=rn.statusZ,dd=t=>ms(t).omit({labels:!0}).partial({key:!0}),PN="sy_status_set",$N="sy_status_delete",RN=t=>({type:"status",key:t}),_N=t=>a.object({parent:U.optional(),statuses:dd(t).array()}),MN=t=>a.object({statuses:ms(t).array()}),UN=a.object({keys:ys.array()}),ZN=a.object({}),LN="/status/set",DN="/status/delete",BN="/status/retrieve",FN=a.object({keys:ys.array().optional(),searchTerm:a.string().optional(),offset:a.number().optional(),limit:a.number().optional(),includeLabels:a.boolean().optional(),hasLabels:rt.array().optional()}),YN=a.object({key:ys,includeLabels:a.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),qN=a.union([YN,FN]),VN=t=>a.object({statuses:v.nullableZ(ms(t))});let fd=class{type="status";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,n=await b(this.client,BN,t,qN,VN(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,LN,{statuses:v.toArray(t),parent:e.parent},_N(e.detailsSchema),MN(e.detailsSchema))).statuses;return n?r:r[0]}async delete(t){await b(this.client,DN,{keys:v.toArray(t)},UN,ZN)}};const WN=Object.freeze(Object.defineProperty({__proto__:null,Client:fd,DELETE_CHANNEL_NAME:$N,SET_CHANNEL_NAME:PN,keyZ:ys,newZ:dd,ontologyID:RN,statusZ:ms},Symbol.toStringTag,{value:"Module"})),HN="/api/v1/";class GN{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child(HN);const s=new wt.JSONCodec;this.unary=Jy(new Ky(this.url,s,this.secure),n),this.stream=new Er(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const vt=a.z.uuid(),gs=a.z.object({key:vt,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe))}),pd=gs.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),$e=a.z.uuid(),ws=a.z.object({key:$e,name:a.z.string().min(1,"Name is required"),layout:Oe.unknownZ.or(a.z.string().transform(Pe))}),yd=ws.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),md=ws.omit({layout:!0}).extend({layout:a.z.string().transform(Pe)}),KN="/workspace/lineplot/retrieve",JN="/workspace/lineplot/create",XN="/workspace/lineplot/rename",QN="/workspace/lineplot/set-data",ex="/workspace/lineplot/delete",tx=a.z.object({key:vt,name:a.z.string()}),nx=a.z.object({key:vt,data:a.z.string()}),rx=a.z.object({keys:vt.array()}),sx=a.z.object({keys:vt.array()}),gd=a.z.object({key:vt}).transform(({key:t})=>({keys:[t]})),wd=a.z.union([gd,sx]),ax=a.z.object({linePlots:v.nullableZ(gs)}),ix=a.z.object({workspace:$e,linePlots:pd.array()}),ox=a.z.object({linePlots:gs.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,JN,{workspace:t,linePlots:v.toArray(e)},ix,ox);return n?r.linePlots:r.linePlots[0]}async rename(t,e){await b(this.client,XN,{key:t,name:e},tx,Ws)}async setData(t,e){await b(this.client,QN,{key:t,data:JSON.stringify(e)},nx,Ws)}async retrieve(t){const e=gd.safeParse(t).success,n=await b(this.client,KN,t,wd,ax);return ue("LinePlot",t,n.linePlots,e),e?n.linePlots[0]:n.linePlots}async delete(t){await b(this.client,ex,{keys:v.toArray(t)},rx,Ws)}};const lx=t=>({type:"lineplot",key:t}),cx=Object.freeze(Object.defineProperty({__proto__:null,Client:bd,keyZ:vt,linePlotZ:gs,newZ:pd,ontologyID:lx,retrieveArgsZ:wd},Symbol.toStringTag,{value:"Module"})),Tt=a.z.uuid(),bs=a.z.object({key:Tt,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe))}),vd=bs.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ux="/workspace/log/retrieve",hx="/workspace/log/create",dx="/workspace/log/rename",fx="/workspace/log/set-data",px="/workspace/log/delete",yx=a.z.object({key:Tt,name:a.z.string()}),mx=a.z.object({key:Tt,data:a.z.string()}),gx=a.z.object({keys:Tt.array()}),wx=a.z.object({keys:Tt.array()}),Td=a.z.object({key:Tt}).transform(({key:t})=>({keys:[t]})),Sd=a.z.union([Td,wx]),bx=a.z.object({logs:v.nullableZ(bs)}),vx=a.z.object({workspace:$e,logs:vd.array()}),Tx=a.z.object({logs:bs.array()}),Hs=a.z.object({});let zd=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await b(this.client,hx,{workspace:t,logs:v.toArray(e)},vx,Tx);return n?r.logs:r.logs[0]}async rename(t,e){await b(this.client,dx,{key:t,name:e},yx,Hs)}async setData(t,e){await b(this.client,fx,{key:t,data:JSON.stringify(e)},mx,Hs)}async retrieve(t){const e=Td.safeParse(t).success,n=await b(this.client,ux,t,Sd,bx);return ue("Log",t,n.logs,e),e?n.logs[0]:n.logs}async delete(t){await b(this.client,px,{keys:v.toArray(t)},gx,Hs)}};const Sx=t=>({type:"log",key:t}),zx=Object.freeze(Object.defineProperty({__proto__:null,Client:zd,keyZ:Tt,logZ:bs,newZ:vd,ontologyID:Sx,retrieveArgsZ:Sd},Symbol.toStringTag,{value:"Module"})),st=a.z.uuid(),vs=a.z.object({key:st,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe)),snapshot:a.z.boolean()}),Od=vs.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Gi=vs.extend({data:a.z.string().transform(Pe)}),ln=a.z.uuid(),Ed=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()}),kd=a.z.object({key:a.z.string(),name:a.z.string(),regions:Ed.array()}),Nd=a.z.object({key:a.z.string(),position:Ti.xy,orientation:rg.outer}),Ox=a.z.object({zoom:a.z.number().positive().default(1),position:Ti.xy}),xd=a.z.object({svg:a.z.string().min(1,"SVG is required"),states:kd.array(),variant:a.z.string().min(1,"Variant is required"),handles:Nd.array(),scale:a.z.number().positive().default(1),scaleStroke:a.z.boolean().default(!1),previewViewport:Ox.default({zoom:1,position:{x:0,y:0}})}),Ts=a.z.object({key:ln,version:a.z.literal(1).optional().default(1),name:a.z.string().min(1,"Name is required"),data:xd}),Ad=Ts.partial({key:!0}),Ex="/workspace/schematic/symbol/retrieve",kx="/workspace/schematic/symbol/create",Nx="/workspace/schematic/symbol/rename",xx="/workspace/schematic/symbol/delete",Ax="/workspace/schematic/symbol/retrieve_group",Ix=a.z.object({symbols:Ad.array(),parent:U}),Cx=a.z.object({key:ln,name:a.z.string()}),jx=a.z.object({keys:ln.array()}),Px=a.z.object({keys:ln.array().optional(),searchTerm:a.z.string().optional(),offset:a.z.number().optional(),limit:a.z.number().optional()}),$x=a.z.object({key:ln}).transform(({key:t})=>({keys:[t]})),Rx=a.z.union([$x,Px]),_x=a.z.object({symbols:v.nullableZ(Ts)}),Mx=a.z.object({symbols:Ts.array()}),Ol=a.z.object({}),Ux=a.z.object({}),Zx=a.z.object({group:ns}),Lx="sy_schematic_symbol_set",Dx="sy_schematic_symbol_delete";let Id=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,kx,{symbols:n,parent:t.parent},Ix,Mx);return e?r.symbols:r.symbols[0]}async rename(t,e){await b(this.client,Nx,{key:t,name:e},Cx,Ol)}async retrieve(t){const e="key"in t,n=await b(this.client,Ex,t,Rx,_x);return ue("Schematic Symbol",t,n.symbols,e),e?n.symbols[0]:n.symbols}async delete(t){await b(this.client,xx,{keys:v.toArray(t)},jx,Ol)}async retrieveGroup(){return(await b(this.client,Ax,{},Ux,Zx)).group}};const Bx=t=>({type:"schematic_symbol",key:t}),Fx=Object.freeze(Object.defineProperty({__proto__:null,Client:Id,DELETE_CHANNEL_NAME:Dx,SET_CHANNEL_NAME:Lx,handleZ:Nd,keyZ:ln,newZ:Ad,ontologyID:Bx,regionZ:Ed,specZ:xd,stateZ:kd,symbolZ:Ts},Symbol.toStringTag,{value:"Module"})),Yx="/workspace/schematic/retrieve",qx="/workspace/schematic/create",Vx="/workspace/schematic/rename",Wx="/workspace/schematic/set-data",Hx="/workspace/schematic/delete",Gx="/workspace/schematic/copy",Kx=a.z.object({key:st,name:a.z.string()}),Jx=a.z.object({key:st,data:a.z.string()}),Xx=a.z.object({keys:st.array()}),Qx=a.z.object({key:st,name:a.z.string(),snapshot:a.z.boolean()}),eA=a.z.object({keys:st.array()}),Cd=a.z.object({key:st}).transform(({key:t})=>({keys:[t]})),jd=a.z.union([Cd,eA]),tA=a.z.object({schematics:v.nullableZ(Gi)}),nA=a.z.object({workspace:$e,schematics:Od.array()}),rA=a.z.object({schematics:Gi.array()}),sA=a.z.object({schematic:vs}),Gs=a.z.object({});let Pd=class{symbols;client;constructor(t){this.client=t,this.symbols=new Id(t)}async create(t,e){const n=Array.isArray(e),r=await b(this.client,qx,{workspace:t,schematics:v.toArray(e)},nA,rA);return n?r.schematics:r.schematics[0]}async rename(t,e){await b(this.client,Vx,{key:t,name:e},Kx,Gs)}async setData(t,e){await b(this.client,Wx,{key:t,data:JSON.stringify(e)},Jx,Gs)}async retrieve(t){const e=Cd.safeParse(t).success,n=await b(this.client,Yx,t,jd,tA);return ue("Schematic",t,n.schematics,e),e?n.schematics[0]:n.schematics}async delete(t){await b(this.client,Hx,{keys:v.toArray(t)},Xx,Gs)}async copy(t){return(await b(this.client,Gx,t,Qx,sA)).schematic}};const aA=t=>({type:"schematic",key:t}),iA=Object.freeze(Object.defineProperty({__proto__:null,Client:Pd,keyZ:st,newZ:Od,ontologyID:aA,remoteZ:Gi,retrieveArgsZ:jd,schematicZ:vs,symbol:Fx},Symbol.toStringTag,{value:"Module"})),St=a.z.uuid(),Ki=a.z.object({key:St,name:a.z.string(),data:Oe.unknownZ.or(a.z.string().transform(Pe))}),$d=Ki.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Ji=Ki.extend({data:a.z.string().transform(Pe)}),oA="/workspace/table/retrieve",lA="/workspace/table/create",cA="/workspace/table/rename",uA="/workspace/table/set-data",hA="/workspace/table/delete",dA=a.z.object({key:St,name:a.z.string()}),fA=a.z.object({key:St,data:a.z.string()}),pA=a.z.object({keys:St.array()}),yA=a.z.object({keys:St.array()}),Rd=a.z.object({key:St}).transform(({key:t})=>({keys:[t]})),_d=a.z.union([Rd,yA]),mA=a.z.object({tables:v.nullableZ(Ji)}),gA=a.z.object({workspace:$e,tables:$d.array()}),wA=a.z.object({tables:Ji.array()}),Ks=a.z.object({});let Md=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await b(this.client,lA,{workspace:t,tables:v.toArray(e)},gA,wA);return n?r.tables:r.tables[0]}async rename(t,e){await b(this.client,cA,{key:t,name:e},dA,Ks)}async setData(t,e){await b(this.client,uA,{key:t,data:JSON.stringify(e)},fA,Ks)}async retrieve(t){const e=Rd.safeParse(t).success,n=await b(this.client,oA,t,_d,mA);return ue("Table",t,n.tables,e),e?n.tables[0]:n.tables}async delete(t){await b(this.client,hA,{keys:v.toArray(t)},pA,Ks)}};const bA=t=>({type:"table",key:t}),vA=Object.freeze(Object.defineProperty({__proto__:null,Client:Md,keyZ:St,newZ:$d,ontologyID:bA,remoteZ:Ji,retrieveArgsZ:_d,tableZ:Ki},Symbol.toStringTag,{value:"Module"})),El="/workspace/retrieve",TA="/workspace/create",SA="/workspace/rename",zA="/workspace/set-layout",OA="/workspace/delete",kl=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()}),EA=a.z.object({workspaces:yd.array()}),kA=a.z.object({key:$e,name:a.z.string()}),NA=a.z.object({key:$e,layout:Oe.unknownZ.transform(t=>JSON.stringify(t))}),xA=a.z.object({keys:$e.array()}),Nl=a.z.object({workspaces:v.nullableZ(ws)}),AA=a.z.object({workspaces:md.array()}),Js=a.z.object({}),IA="sy_workspace_set",CA="sy_workspace_delete";class Ud{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new Pd(e),this.lineplots=new bd(e),this.logs=new zd(e),this.tables=new Md(e)}async create(e){const n=Array.isArray(e),r=await b(this.client,TA,{workspaces:v.toArray(e)},EA,AA);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await b(this.client,SA,{key:e,name:n},kA,Js)}async setLayout(e,n){await b(this.client,zA,{key:e,layout:n},NA,Js)}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,El,n,kl,Nl);return r?s.workspaces:s.workspaces[0]}async retrieveByAuthor(e){return(await b(this.client,El,{author:e},kl,Nl)).workspaces}async delete(e){await b(this.client,OA,{keys:v.toArray(e)},xA,Js)}}const jA=t=>({type:"workspace",key:t}),PA=Object.freeze(Object.defineProperty({__proto__:null,Client:Ud,DELETE_CHANNEL_NAME:CA,SET_CHANNEL_NAME:IA,keyZ:$e,newZ:yd,ontologyID:jA,remoteZ:md,workspaceZ:ws},Symbol.toStringTag,{value:"Module"})),Zd=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:ou.breakerConfigZ.optional()});class Xi extends Ph{createdAt;props;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;hardware;control;arcs;static connectivity=$r;transport;clientVersion="0.46.0";constructor(e){const n=Zd.parse(e),{host:r,port:s,username:i,password:o,connectivityPollFrequency:l,secure:c,retry:u}=n,h=new GN(new Sn({host:r,port:Number(s)}),u,c);h.use(Pb);let p;i!=null&&o!=null&&(p=new GE(h.unary,{username:i,password:o}),h.use(p.middleware()));const f=new Zi(new Kn(h.unary)),O=new wh(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 yh(this,f,h.unary,O),this.connectivity=new $r(h.unary,l,this.clientVersion,n.name),this.control=new Mh(this),this.ontology=new Cu(h.unary,this);const I=new hd(this.transport.unary);this.labels=new ad(this.transport.unary),this.statuses=new fd(this.transport.unary),this.ranges=new cd(this,I,this.transport.unary,f,this.labels,this.ontology),this.access=new Ev(this.transport.unary),this.users=new vh(this.transport.unary),this.workspaces=new Ud(this.transport.unary);const j=new qh(this.transport.unary),w=new Qh(this.transport.unary,this,this.ontology,this.ranges),T=new Vh(this.transport.unary,w);this.hardware=new Ik(w,T,j),this.arcs=new ch(this.transport.unary)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}x.seconds(1);const Xs=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Qi=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},$A=(t,e)=>{let n=null;return e===0?t:(...r)=>{n===null&&(n=setTimeout(()=>{t(...r),n=null},e))}},On=".",Ld=(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)},cn=(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)},RA=(t,e)=>{const n=t.split(".");return n.forEach((r,s)=>{e=cn(e,r),e!=null&&typeof e=="object"&&"key"in e&&(n[s]=e.key)}),n.join(".")},_A=(t,e)=>{const n=t.split(".");return e<0?n[n.length+e]:n[e]},MA=(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},Ua=(t,e)=>{for(let n=1;n<=e.length;n++){const r=e.slice(0,n).join(".");if(cn(t,r)!=null)return[r,n]}return null},eo=((t,e,n={optional:!1})=>{const{optional:r,getter:s=cn}=n;if(e==="")return t;const i=e.split(".");if(i.length===1){const l=s(t,i[0]);if(l===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${i[0]} is undefined`)}return l}const o=(l,c)=>{if(c>=i.length)return l;for(let u=i.length-c;u>=1;u--){const h=i.slice(c,c+u).join("."),p=s(l,h);if(p!==void 0){if(c+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,c+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${i[c]} is undefined`)};return o(t,0)}),UA=(t,e)=>eo(t,e,{optional:!0})!==null,ZA=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))}},LA=(t,e,n="")=>{const r={},s=(i,o,l)=>{if(typeof i!=typeof o||i===null||o===null){r[l]=[i,o];return}if(typeof i=="object"&&typeof o=="object")if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length){r[l]=[i,o];return}for(let c=0;c<i.length;c++)s(i[c],o[c],`${l}[${c}]`)}else new Set([...Object.keys(i),...Object.keys(o)]).forEach(c=>{s(i[c],o[c],l!==""?`${l}.${c}`:c)});else i!==o&&(r[l]=[i,o])};return s(t,e,n),r},Za=(t,e)=>{const n=Array.isArray(t),r=Array.isArray(e);if(n!==r)return!1;if(n&&r){const o=t,l=e;if(o.length!==l.length)return!1;for(let c=0;c<o.length;c++)if(!Za(o[c],l[c]))return!1;return!0}if(t==null||e==null||typeof t!="object"||typeof e!="object")return t===e;if("equals"in t)return t.equals(e);const s=Object.keys(t),i=Object.keys(e);if(s.length!==i.length)return!1;for(const o of s){const l=t[o],c=e[o];if(typeof l=="object"&&typeof c=="object"){if(!Za(l,c))return!1}else if(l!==c)return!1}return!0},Dd=(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(!Dd(i,o))return!1}else if(i!==o)return!1}return!0},La=(t,...e)=>{if(e.length===0)return t;const n=e.shift();if(Xs(t)&&Xs(n))for(const r in n)try{Xs(n[r])?(r in t||Object.assign(t,{[r]:{}}),La(t[r],n[r])):Object.assign(t,{[r]:n[r]})}catch(s){throw s instanceof TypeError?new TypeError(`.${r}: ${s.message}`):s}return La(t,...e)},DA=(t,e,n)=>{const r=(s,i,o)=>{if(o.def?.type==="union")return o.def.options.reduce((l,c)=>r(l,i,c),s);if(o.def?.type==="intersection"){const l=r(s,i,o.def.left);return r(l,i,o.def.right)}for(const l in i){const c=i[l];let u=o?.shape;if(u!=null)for(;u!=null;){if(u[l]!=null){const h=u[l].safeParse(c);if(h.success){s[l]=h.data;break}}u=u.def?.shape}typeof c=="object"&&!Array.isArray(c)&&c!==null&&o&&o.shape&&o.shape[l]&&(s[l]||={},r(s[l],c,o.shape[l]))}return s};return r({...t},e,n)},BA=(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 l=parseInt(o);if(!isNaN(l)&&l<r.length){r.splice(l,1);return}const c=r[0];if(typeof c=="object"&&"key"in c){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 l=n.length-s;l>=1;l--){const c=n.slice(s,s+l).join(On),u=r.find(h=>h.key===c);if(u!=null){if(s+l===n.length){const h=r.findIndex(p=>p.key===c);h!==-1&&r.splice(h,1);return}r=u,s+=l,i=!0;break}}}if(!i)for(let o=n.length-s;o>=1;o--){const l=n.slice(s,s+o).join(On);if(!Array.isArray(r)&&typeof r=="object"&&r!==null&&l in r){if(s+o===n.length){delete r[l];return}r=r[l],s+=o,i=!0;break}}if(!i){const o=cn(r,n[s]);if(o==null)return;r=o,s++}}},FA=(t,e,n)=>{const r=e.split(On);let s=t,i=0;for(;i<r.length-1;){const o=Ua(s,r.slice(i,r.length-1));let l;o!=null?[l,i]=[o[0],i+o[1]]:(l=r[i],i++);let c=cn(s,l);if(c==null){const u=r[i];let h=It(u);h==null&&u.startsWith("-")&&It(u.substring(1))!=null&&(h=0),c=h!=null?[]:{},s[l]=c}s=c}try{const o=r[r.length-1];if(Array.isArray(s)){let c=It(o);if(c==null){if(o.startsWith("-")){const u=It(o.substring(1));u!=null&&(c=s.length-u)}if(c==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[c]=n;return}const l=Ua(s,[o]);if(l!=null){s[l[0]]=n;return}s[o]=n}catch(o){throw console.error("failed to set value",n,"at path",e,"on object",t),o}},Ss=Object.freeze(Object.defineProperty({__proto__:null,SEPARATOR:On,copy:ZA,defaultGetter:cn,difference:LA,element:_A,equal:Za,findBestKey:Ua,get:eo,getIndex:It,has:UA,override:La,overrideValidItems:DA,partialEqual:Dd,pathsMatch:MA,remove:BA,resolvePath:RA,set:FA,transformPath:Ld},Symbol.toStringTag,{value:"Module"}));let YA=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 qA{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 to=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:qA,Observer:YA},Symbol.toStringTag,{value:"Module"}));let VA=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=WA(e,this.sender),r=new HA(n);return this.handlers.set(e,r),r}};const WA=(t,e)=>(n,r)=>e({type:t,payload:n},r);class HA{_send;handler;constructor(e){this._send=e,this.handler=null}send(e,n=[]){this._send(e,n)}handle(e){this.handler=e}}const Da=(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}},Bd=t=>typeof t=="function",no=(t,e)=>Bd(t)?t(e):t,Fd=t=>e=>e==null?void 0:t(e),zs=t=>Yd(t)?t():t,Yd=t=>typeof t=="function",qd=({initial:t,value:e,onChange:n})=>{const[r,s]=oi.useState(e??t);return e!=null&&n!=null?[e,n]:[r,s]},Vd=({initial:t,value:e,onChange:n})=>{const[r,s]=oi.useState(zs(e??t));return e!=null&&n!=null?[e,n]:[r,s]},GA=(t,e)=>{const[n,r]=oi.useState(()=>{const s=localStorage.getItem(e);return s==null?zs(t):JSON.parse(s)});return[n,s=>{r(s),localStorage.setItem(e,JSON.stringify(s))}]},KA=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:zs,executeSetter:no,isInitialSetter:Yd,isSetter:Bd,skipNull:Fd,usePassthrough:qd,usePersisted:GA,usePurePassthrough:Vd},Symbol.toStringTag,{value:"Module"}));let xl=null;const JA=()=>(xl??=document.createElement("canvas"),xl),XA=(t,e,n)=>{if(d.S.RUNTIME==="node")return{width:0,height:0};n??=JA().getContext("2d"),n.font=e;const r=n.measureText(t);return Os(r)},Os=t=>({width:Math.trunc(Math.abs(t.actualBoundingBoxLeft)+Math.abs(t.actualBoundingBoxRight)),height:Math.trunc(Math.abs(t.actualBoundingBoxAscent)+Math.abs(t.actualBoundingBoxDescent))}),En=["h1","h2","h3","h4","h5","p","small"],QA=a.z.enum(En),eI=t=>{const e=En.indexOf(t);return e===-1||e===En.length-1?t:En[e+1]},tI=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()}),nI={tiny:"small",small:"small",medium:"p",large:"h5",huge:"h2"},rI={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"},sI=a.z.object({l0:d.Rr.colorZ,l1:d.Rr.colorZ,l2:d.Rr.colorZ,l3:d.Rr.colorZ,l4:d.Rr.colorZ,l5:d.Rr.colorZ,l6:d.Rr.colorZ,l7:d.Rr.colorZ,l8:d.Rr.colorZ,l9:d.Rr.colorZ,l10:d.Rr.colorZ,l11:d.Rr.colorZ}),fe=(t,e)=>[t[0],t[1],e,t[3]],aI=a.z.object({m2:d.Rr.colorZ,m1:d.Rr.colorZ,z:d.Rr.colorZ,p1:d.Rr.colorZ,p2:d.Rr.colorZ}),pr=aI.or(d.Rr.colorZ.transform(t=>{const e=d.Rr.hsla(t);return{m2:d.Rr.fromHSLA(fe(e,40)),m1:d.Rr.fromHSLA(fe(e,45)),z:t,p1:d.Rr.fromHSLA(fe(e,55)),p2:d.Rr.fromHSLA(fe(e,65))}})),Wd=a.z.object({name:a.z.string(),key:a.z.string(),colors:a.z.object({border:d.Rr.colorZ,primary:pr,gray:sI,error:pr,secondary:pr,warning:pr,palettes:a.z.record(a.z.string(),d.Rr.paletteZ),visualization:a.z.object({palettes:a.z.record(a.z.string(),a.z.array(d.Rr.colorZ))}).optional().default({palettes:{}}),white:d.Rr.colorZ,black:d.Rr.colorZ,text:d.Rr.colorZ,textInverted:d.Rr.colorZ,textOnPrimary:d.Rr.colorZ.optional().default(d.Rr.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.Rr.isZero(t.colors.textOnPrimary))&&(t.colors.textOnPrimary=d.Rr.pickByContrast(t.colors.primary.z,t.colors.text,t.colors.textInverted)),t)),iI='"Inter Variable", sans-serif',oI='"Geist Mono", monospace',lI=6,hn=[357,91,55,1],dn=[48,90,55,1],cI=["#FEFEFE","#FAFAFA","#F2F2F2","#ECECEC","#E4E4E4","#D1D1D1","#BCBCBC","#ACACAC","#8F8F8F","#4F4F4F","#292929","#050505"],fn=Object.fromEntries(cI.map((t,e)=>[`l${e}`,t])),uI=()=>typeof window>"u"?!1:window.devicePixelRatio>1,hI=uI(),Ba={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.Rr.fromHSLA(fe(hn,30)),m1:d.Rr.fromHSLA(fe(hn,40)),z:d.Rr.fromHSLA(hn),p1:d.Rr.fromHSLA(fe(hn,65)),p2:d.Rr.fromHSLA(fe(hn,77))},warning:{m2:d.Rr.fromHSLA(fe(dn,30)),m1:d.Rr.fromHSLA(fe(dn,40)),z:d.Rr.fromHSLA(dn),p1:d.Rr.fromHSLA(fe(dn,65)),p2:d.Rr.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:lI,border:{radius:3,width:hI?.5:1,thickWidth:1},schematic:{elementStrokeWidth:2}},typography:{family:iI,codeFamily:oI,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}}},Hd=Object.freeze({...Ba,key:"synnaxLight",name:"Synnax Light"}),dI=["#020202","#080808","#151515","#202020","#272727","#3B3B3B","#4A4A4A","#5C5C5C","#767676","#959595","#dadada","#FAFAFA"],pn=Object.fromEntries(dI.map((t,e)=>[`l${e}`,t])),Gd=Object.freeze({...Ba,key:"synnaxDark",name:"Synnax Dark",colors:{...Ba.colors,gray:pn,logo:"var(--pluto-text-color)",border:pn.l4,text:pn.l11,textInverted:pn.l0,textOnPrimary:pn.l11}}),fI={synnaxDark:Gd,synnaxLight:Hd},Kd=["tiny","small","medium","large","huge"],Jd=a.z.enum(Kd),pI=t=>Jd.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 Fa=["debug","info","warn","error"],Xd=t=>{const e=Fa.indexOf(t);return({level:n})=>Fa.indexOf(n)>=e},yI=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 mI=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},dt="1.9.0",Al=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function gI(t){var e=new Set([t]),n=new Set,r=t.match(Al);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(l){return l===t};function i(l){return n.add(l),!1}function o(l){return e.add(l),!0}return function(l){if(e.has(l))return!0;if(n.has(l))return!1;var c=l.match(Al);if(!c)return i(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||s.major!==u.major?i(l):s.major===0?s.minor===u.minor&&s.patch<=u.patch?o(l):i(l):s.minor<=u.minor?o(l):i(l)}}var wI=gI(dt),bI=dt.split(".")[0],Rn=Symbol.for("opentelemetry.js.api."+bI),_n=mI;function ro(t,e,n,r){var s;r===void 0&&(r=!1);var i=_n[Rn]=(s=_n[Rn])!==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 Mn(t){var e,n,r=(e=_n[Rn])===null||e===void 0?void 0:e.version;if(!(!r||!wI(r)))return(n=_n[Rn])===null||n===void 0?void 0:n[t]}function so(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+dt+".");var n=_n[Rn];n&&delete n[t]}var vI=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(l){o={error:l}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},TI=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))},SI=(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=Mn("diag");if(r)return n.unshift(e),r[t].apply(r,TI([],vI(n),!1))}var le;(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"})(le||(le={}));function zI(t,e){t<le.NONE?t=le.NONE:t>le.ALL&&(t=le.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",le.ERROR),warn:n("warn",le.WARN),info:n("info",le.INFO),debug:n("debug",le.DEBUG),verbose:n("verbose",le.VERBOSE)}}var 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(l){o={error:l}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},EI=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))},kI="diag",Un=(function(){function t(){function e(s){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var l=Mn("diag");if(l)return l[s].apply(l,EI([],OI(i),!1))}}var n=this,r=function(s,i){var o,l,c;if(i===void 0&&(i={logLevel:le.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=Mn("diag"),p=zI((l=i.logLevel)!==null&&l!==void 0?l:le.INFO,s);if(h&&!i.suppressOverrideMessage){var f=(c=new Error().stack)!==null&&c!==void 0?c:"<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 ro("diag",p,n,!0)};n.setLogger=r,n.disable=function(){so(kI,n)},n.createComponentLogger=function(s){return new SI(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})(),NI=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(l){o={error:l}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},xI=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.")},AI=(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=NI(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=xI(r),l=o.next();!l.done;l=o.next()){var c=l.value;i._entries.delete(c)}}catch(u){e={error:u}}finally{try{l&&!l.done&&(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 II(t){return t===void 0&&(t={}),new AI(new Map(Object.entries(t)))}function CI(t){return Symbol.for(t)}var jI=(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})(),PI=new jI,$I={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},RI={set:function(t,e,n){t!=null&&(t[e]=n)}},_I=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(l){o={error:l}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},MI=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))},UI=(function(){function t(){}return t.prototype.active=function(){return PI},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,MI([r],_I(s),!1))},t.prototype.bind=function(e,n){return n},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),ZI=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(l){o={error:l}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},LI=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))},Qs="context",DI=new UI,Qd=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return ro(Qs,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,LI([e,n,r],ZI(i),!1))},t.prototype.bind=function(e,n){return this._getContextManager().bind(e,n)},t.prototype._getContextManager=function(){return Mn(Qs)||DI},t.prototype.disable=function(){this._getContextManager().disable(),so(Qs,Un.instance())},t})(),Ya;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Ya||(Ya={}));var BI=Qd.getInstance(),FI=(function(){function t(){}return t.prototype.inject=function(e,n){},t.prototype.extract=function(e,n){return e},t.prototype.fields=function(){return[]},t})(),ao=CI("OpenTelemetry Baggage Key");function ef(t){return t.getValue(ao)||void 0}function YI(){return ef(Qd.getInstance().active())}function qI(t,e){return t.setValue(ao,e)}function VI(t){return t.deleteValue(ao)}var ea="propagation",WI=new FI,HI=(function(){function t(){this.createBaggage=II,this.getBaggage=ef,this.getActiveBaggage=YI,this.setBaggage=qI,this.deleteBaggage=VI}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return ro(ea,e,Un.instance())},t.prototype.inject=function(e,n,r){return r===void 0&&(r=RI),this._getGlobalPropagator().inject(e,n,r)},t.prototype.extract=function(e,n,r){return r===void 0&&(r=$I),this._getGlobalPropagator().extract(e,n,r)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){so(ea,Un.instance())},t.prototype._getGlobalPropagator=function(){return Mn(ea)||WI},t})(),GI=HI.getInstance();const Il=["bench","debug","prod"],KI=t=>e=>Il.indexOf(e)>=Il.indexOf(t);class Zn{meta=Dt.NOOP;otelTracer;filter;constructor(e,n=KI("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 qa(e,this.otelTracer.startSpan(e));return i.start(),()=>i.end()}return s?r(new tf(e)):this.otelTracer.startActiveSpan(e,i=>{const o=new qa(e,i);return r(o)})}propagate(e){if(this.meta.noop)return;const n=BI.active();GI.inject(n,e,{set:(r,s,i)=>{r[s]=i}})}static NOOP=new Zn}class qa{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:Ya.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 tf{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 JI=Ft.NOOP,Te=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:Ft,LOG_LEVELS:Fa,Logger:Bt,NOOP:JI,NoopSpan:tf,Tracer:Zn,_Span:qa,logLevelKeyFiler:yI,logThresholdFilter:Xd},Symbol.toStringTag,{value:"Module"})),ta=(t,e)=>t instanceof Error?(t.message=`[${e}] - ${t.message}`,t):new Error(e??"unknown error",{cause:t});class Es{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,l)=>this.parentCtxValues.set(l,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=no(e,this.state);this._prevState=d.Hr(this._state),this._state=Da(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=Da(this._schema,n,`${this.toString()}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:Ss.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 ta(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 ta(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 ta(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 Es{_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 l=i[0],c=this.getChild(l);if(c!=null)return c._updateState({...e,path:i});if(i.length>1){const h=n.slice(0,n.indexOf(l)+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(l,u)}_updateContext(e){super._updateContext(e),this.updateChildContexts()}childCtx(){return{get:e=>this.childCtxValues.get(e)??this.parentCtxValues.get(e),forEach:e=>{this.childCtxValues.forEach((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 XI=a.z.object({}),QI=()=>{throw new Error("should not call create")};class He extends at{static TYPE="root";static KEY="root";comms;registry;schema=XI;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:QI}),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 l=n[n.length-1];return this.create({key:l,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 nf=He.render.bind(He),eC=Object.freeze(Object.defineProperty({__proto__:null,Composite:at,Leaf:Es,Root:He,render:nf},Symbol.toStringTag,{value:"Module"})),tC=(t,e)=>Array.isArray(e)?e.some(n=>n.matches(t)):e?.matches(t)??!1,rf=(t,e,n)=>{const r=d.Xr.fromException(t,e);return console.error(r),tC(t,n)?null:r},sf=(t,e,n,r)=>{if(typeof t=="function")return!0;const s=rf(t,n,r);return s!=null&&e(s),!1},af=async(t,e,n,r)=>{try{const s=t();s!=null&&await s}catch(s){const i=rf(s,n,r);if(i!=null)return e(i)}},of=t=>(e,n,r)=>{sf(e,t,n,r)&&af(e,t,n,r)},lf=t=>async(e,n,r)=>{sf(e,t,n,r)&&await af(e,t,n,r)},cf=a.z.object({statuses:d.Xr.statusZ().array()}),_r="status.aggregator";class Va extends at{static TYPE="status.Aggregator";schema=cf;afterUpdate(e){e.wasSetPreviously(_r)||e.set(_r,{add:this.add.bind(this),create:d.Xr.create})}add(e){this.setState(n=>({...n,statuses:[...n.statuses,d.Xr.create(e)]}))}}const ks=t=>t.get(_r).add,nC=t=>{const e=t.getOptional(_r);return e!=null?e.add:()=>{}},Ns=t=>of(ks(t)),rC=t=>lf(ks(t)),sC={[Va.TYPE]:Va},Wa="pluto-theming-context",uf=a.z.object({name:a.z.string(),url:a.z.string()}),aC=a.z.object({theme:Wd,fontURLs:a.z.array(uf)});let Ha=class hf extends at{static TYPE="theming.Provider";static z=aC;schema=hf.z;afterUpdate(e){if(e.getOptional(Wa)!=null&&this.state.theme.key===this.prevState.theme.key)return;e.set(Wa,this.state.theme),Ns(e)(async()=>{await this.loadFonts()},"failed to load theme fonts")}async loadFonts(){await Promise.all(this.state.fontURLs.map(async({name:e,url:n})=>{const r=new FontFace(e,`url(${n})`);try{await r.load(),self.fonts.add(r)}catch(s){console.error(s)}}))}};const iC=t=>t.get(Wa),oC={[Ha.TYPE]:Ha},df=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")}),Ga="alamos-provider";let Ka=class extends at{static TYPE="alamos.Provider";schema=df;afterUpdate(e){if(e.getOptional(Ga)!=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(Ga,this.internal.ins)}};const io=(t,e)=>{const n=t.get(Ga);if(n==null)throw new Error("No instrumentation provider");return e==null?n:n.child(e)},lC={[Ka.TYPE]:Ka},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,l,c,u){this.wrapped.drawImage(e,n,r,s,i,o!=null?this.scale_.x.pos(o):o,l!=null?this.scale_.y.pos(l):l,c!=null?this.scale_.x.dim(c):c,u!=null?this.scale_.y.dim(u):u)}beginPath(){this.wrapped.beginPath()}clip(e,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,l){this.wrapped.putImageData(e,n,r,s,i,o,l)}get imageSmoothingEnabled(){return this.wrapped.imageSmoothingEnabled}set imageSmoothingEnabled(e){this.wrapped.imageSmoothingEnabled=e}get imageSmoothingQuality(){return this.wrapped.imageSmoothingQuality}set imageSmoothingQuality(e){this.wrapped.imageSmoothingQuality=e}arc(e,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,l,c){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,l,c)}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,l]=this.checkAtlasFillStyle(i.useAtlas);if(o){this.atlasRegistry.get({font:this.font,textColor:l}).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):Os(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 cC(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 cC{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,l,c){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,l,c)}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 uC=`precision mediump float;
73
+
74
+ void main(void) {
75
+ gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
76
+ }
77
+ `,hC=`attribute vec4 a_position;
78
+
79
+ void main(void) {
80
+ gl_Position = a_position;
81
+ }
82
+ `,Cl=t=>new Error(`failed to compile webgl program: ${t}`),dC=new Error("null shader encountered");let ff=class{renderCtx;prog;vertShader;fragShader;uniformLocCache=new Map;constructor(e,n,r){this.renderCtx=e;const s=e.gl.createProgram();if(s==null)throw Cl("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.Rr.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 dC;if(r.shaderSource(s,e),r.compileShader(s),!r.getShaderParameter(s,r.COMPILE_STATUS)){const o=r.getShaderInfoLog(s);throw r.deleteShader(s),Cl(o??"unknown")}r.attachShader(this.prog,s)}};const fC=new Float32Array([0,0,0,0,0,0]);class pC extends ff{positionBuffer;constructor(e){super(e,hC,uC);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,fC,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 jl={high:1,low:0};class pf{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=jl[e.priority]>=jl[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,Re=2;class oo{atlas;charDims;charMap;static DEFAULT_CHARS="0123456789.:-µmsNa∞ᴇABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz%";constructor(e){const{font:n,characters:r=oo.DEFAULT_CHARS,textColor:s}=e;this.charMap=new Map;const i=d.c.unique(Array.from(r)),l=new OffscreenCanvas(1,1).getContext("2d");l.font=n;const c=l.measureText("0");this.charDims=Os(c),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*Re,p*(O+1)*Re);const I=this.atlas.getContext("2d");I.scale(Re,Re),I.font=n,I.textBaseline="alphabetic",I.textAlign="left",I.fillStyle=d.Rr.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,l=Math.ceil(Math.sqrt(this.charMap.size));e.textAlign==="center"&&(r-=i*n.length/2),e.textBaseline==="middle"&&(s+=o/2);for(let c=0;c<n.length;c++){const u=n[c],h=this.charMap.get(u);if(h===void 0)continue;const p=h%l,f=Math.floor(h/l);e.drawImage(this.atlas,p*i*Re,f*o*Re+mr,i*Re,o*Re,r+c*i,s-o-mr/Re,i,o)}}measureText(e){return{width:e.length*this.charDims.width,height:this.charDims.height}}}class yC{atlases;constructor(){this.atlases=new Map}get(e){const n=`${e.font}-${d.Rr.hex(e.textColor)}-${e.characters}`;if(this.atlases.has(n))return this.atlases.get(n);const r=new oo(e);return this.atlases.set(n,r),r}}const Pl=t=>(t.textRendering="optimizeSpeed",t.imageSmoothingEnabled=!1,t);let yf=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=io(e,"render_context"),l=new Ct(n,r,s,i,o,ks(e),Ns(e));return e.set(Ct.CONTEXT_KEY,l),l}constructor(e,n,r,s,i,o,l){this.upper2dCanvas=r,this.lower2dCanvas=n,this.glCanvas=e,this.os=s,this.instrumentation=i,this.dpr=1;const c=this.lower2dCanvas.getContext("2d");if(c==null)throw new Error("Could not get 2D context");const u=new yC;this.lower2d=Pl(new Mr(c,u,this.dpr));const h=this.upper2dCanvas.getContext("2d");if(h==null)throw new Error("Could not get 2D context");this.upper2d=Pl(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 pf({afterRender:O,instrumentation:this.instrumentation,handleError:l}),this.region=d.jt.ZERO,this.os==="Windows"&&(this.clearProgram=new pC(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.Rr.rgba1(d.Rr.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 mf=a.z.object({region:d.jt.box,enabled:a.z.boolean().optional().default(!1)}),$l=["gl","lower2d","upper2d"];class Ja extends Es{static TYPE="eraser";schema=mf;afterUpdate(e){this.deleted||(this.internal.renderCtx=yf.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:$l})}render(){this.deleted||!this.state.enabled||this.internal.renderCtx.erase(this.state.region,d.Q.construct(0),...$l)}}const mC={[Ja.TYPE]:Ja};class it extends to.Observer{cleanup(){}}class Xa extends it{static TYPE="noop-boolean-sink";set(){}}const gC={type:Xa.TYPE,props:{},variant:"sink",valueType:"boolean"};class Qa extends it{static TYPE="noop-numeric-sink";set(){}}const wC={type:Qa.TYPE,props:{},variant:"sink",valueType:"number"};class ei extends it{static TYPE="noop-boolean-source";value(){return!1}}const bC={type:ei.TYPE,props:{},variant:"source",valueType:"boolean"};class ti extends it{static TYPE="noop-numeric-source";value(){return 0}}const vC={type:ti.TYPE,props:{},variant:"source",valueType:"number"};class ni extends it{static TYPE="noop-string-source";value(){return""}}const TC={type:ni.TYPE,props:{},variant:"source",valueType:"string"};class ri extends it{static TYPE="noop-status-source";value(){return{key:"noop",name:"noop",variant:"disabled",message:"unknown",time:d.r.now()}}}const SC={type:ri.TYPE,props:{},variant:"source",valueType:"status"};class si extends it{static TYPE="noop-color-source";value(){return d.Rr.ZERO}}const zC={type:si.TYPE,props:{},variant:"source",valueType:"color"};class ai extends it{static TYPE="noop-series";value(){return[d.H.ZERO,new d.Oe([])]}}const OC={type:ai.TYPE,props:{},variant:"source",valueType:"series"},EC={[Xa.TYPE]:Xa,[Qa.TYPE]:Qa,[ei.TYPE]:ei,[ti.TYPE]:ti,[ri.TYPE]:ri,[si.TYPE]:si,[ni.TYPE]:ni,[ai.TYPE]:ai};class gf{type="noop";create(e){const n=EC[e.type];return n==null?null:new n}}const kC=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(kC).optional()}),ot=tr.extend({variant:a.z.literal("source")}),xs=tr.extend({variant:a.z.literal("sink")}),wf=tr.extend({variant:a.z.literal("source-transformer")}),bf=tr.extend({variant:a.z.literal("sink-transformer")}),NC=ot.extend({valueType:a.z.literal("series")}),xC=ot.extend({valueType:a.z.literal("boolean")}),AC=xs.extend({valueType:a.z.literal("boolean")}),IC=bf.extend({valueType:a.z.literal("boolean")}),CC=wf.extend({valueType:a.z.literal("boolean")}),jC=ot.extend({valueType:a.z.literal("number")}),PC=xs.extend({valueType:a.z.literal("number")}),$C=ot.extend({valueType:a.z.literal("color")}),RC=ot.extend({valueType:a.z.literal("status")}),_C=ot.extend({valueType:a.z.literal("string")});class As extends to.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 As{}class vf extends As{}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 Tf 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 Sf extends As{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 lo=a.z.object({from:a.z.string(),to:a.z.string()}),zf=a.z.object({connections:a.z.array(lo),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 Ur.TYPE:return new Ur(e.props,this.factory);case Zr.TYPE:return new Zr(e.props,this.factory);default:return null}}}class Ur extends be{static TYPE="source-pipeline";schema=zf;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 l=n.create(o);l!=null&&(this.sources[i]=l)}),r.forEach(({from:i,to:o})=>{const l=this.sources[i],c=this.sources[o];l==null||c==null||"setSources"in c&&c.setSources({[i]:l})})}value(){return this.outlet.value()}onChange(e){return this.outlet.onChange(e)}cleanup(){Object.values(this.sources).forEach(e=>e.cleanup?.())}}const MC=(t,e)=>({variant:"source",props:e,type:Ur.TYPE,valueType:t}),Of=a.z.object({connections:a.z.array(lo),inlet:a.z.string(),segments:a.z.record(a.z.string(),xs)});class Zr extends vf{static TYPE="sink-pipeline";schema=Of;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 l=n.create(o);l!=null&&(this.sinks[i]=l)}),r.forEach(({from:i,to:o})=>{const l=this.sinks[i],c=this.sinks[o];l==null||c==null||"setSinks"in l&&l.setSinks({[o]:c})})}set(...e){return this.inlet.set(...e)}cleanup(){Object.values(this.sinks).forEach(e=>e.cleanup?.())}}const UC=(t,e)=>({variant:"sink",props:e,type:Zr.TYPE,valueType:t}),Ef=a.z.object({channel:a.z.number().or(a.z.string())});class Lr extends be{static TYPE="stream-channel-value";schema=Ef;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.Xr.fromException(e,"failed to stream channel value"))}}}const kf=async(t,e,n)=>{const r=await t.retrieveChannel(e),s=Pa.isCalculated(r);if(!n||r.isIndex)return{key:r.key,dataType:r.dataType,virtual:r.virtual,isCalculated:s};if(s){const i=await Pa.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}},ZC=a.z.object({timeRange:d.m.z,channel:a.z.number().or(a.z.string()),useIndexOfChannel:a.z.boolean().optional().default(!1)});class Dr extends be{static TYPE="series-source";client;schema=ZC;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 kf(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.Xr.fromException(e,"failed to read channel data"))}}}const LC=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 Br extends be{static TYPE="dynamic-series-source";client;data=new d.Oe([]);now;onStatusChange;channel=null;stopStreaming;valid=!1;schema=LC;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(c=>c.timeRange.end.after(i.sub(n))).map(c=>c.bounds),l=d.H.max(o);return s!=null&&s.dataType.equals(d.n.TIMESTAMP)&&(l.lower=Math.max(l.lower,l.upper-Number(n.valueOf()))),[l,this.data]}async read(){try{this.valid=!0;const{channel:e,useIndexOfChannel:n,timeSpan:r}=this.props;this.channel=await kf(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 l=o.get(this.channel.key);l!=null&&(l.acquire(),this.data.push(l),this.notify(),this.gcOutOfRangeData())};this.stopStreaming=await this.client.stream(i,[this.channel.key]),this.notify()}catch(e){this.valid=!1,this.onStatusChange?.(d.Xr.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 DC={[Dr.TYPE]:Dr,[Br.TYPE]:Br,[Lr.TYPE]:Lr};class Nf{type="remote";client;constructor(e){this.client=e}create(e,n){const r=DC[e.type];return r==null?null:new r(this.client,e.props,n)}}const BC=t=>({type:Dr.TYPE,props:t,variant:"source",valueType:"series"}),FC=t=>({type:Br.TYPE,props:t,variant:"source",valueType:"series"}),YC=t=>({type:Lr.TYPE,props:t,variant:"source",valueType:"number"});class xf{type="static";create(e){switch(e.type){case ii.TYPE:return new ii(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);case Vr.TYPE:return new Vr(e.props);default:return null}}}const uo=a.z.object({data:a.z.array(d.de),offsets:a.z.array(a.z.number()).optional().default([])});class ii extends be{data;schema=uo;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 Af=uo.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 Fr extends be{static TYPE="iterative-series";schema=Af;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 If=a.z.number();class Yr extends be{static TYPE="static-numeric";schema=If;value(){return this.props}}const Cf=a.z.string();class qr extends be{static TYPE="static-string";schema=Cf;value(){return this.props}}const jf=d.Rr.crudeZ;class Vr extends be{static TYPE="static-color";schema=jf;value(){return d.Rr.construct(this.props)}}const qC=t=>({type:ii.TYPE,props:t,variant:"source",valueType:"series"}),VC=t=>({type:Fr.TYPE,props:t,variant:"source",valueType:"series"}),WC=t=>({type:Yr.TYPE,props:t,variant:"source",valueType:"number"}),HC=t=>({type:qr.TYPE,props:t,variant:"source",valueType:"string"}),GC=t=>({type:Vr.TYPE,props:t,variant:"source",valueType:"color"});class Pf{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 Wr.TYPE:return new Wr(e.props);case Gt.TYPE:return new Gt(e.props);case Kt.TYPE:return new Kt(e.props)}return null}}const KC=a.z.object({truthy:a.z.number().optional().default(1),falsy:a.z.number().optional().default(0)}),JC=t=>({props:t,type:Yt.TYPE,variant:"sink",valueType:"boolean"});class Yt extends Sf{static TYPE="boolean-numeric-converter-sink";static propsZ=KC;schema=Yt.propsZ;transform(...e){return e.map(n=>n?this.props.truthy:this.props.falsy)}}const $f=a.z.object({trueBound:d.H.bounds}),XC=t=>({props:t,type:qt.TYPE,variant:"source",valueType:"boolean"});class qt extends zt{static TYPE="boolean-source";static propsZ=$f;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 Rf=a.z.object({});class Vt extends Tf{static TYPE="mean";static propsZ=Rf;schema=Vt.propsZ;transform(e){return Object.values(e).reduce((n,r)=>n+r,0)/Object.keys(e).length}}const QC=t=>({props:t,type:Vt.TYPE,variant:"source",valueType:"boolean"}),_f=a.z.object({trueVariant:d.Xr.variantZ.optional().default("success")});class Wt extends zt{static TYPE="boolean-status";static propsZ=_f;schema=Wt.propsZ;transform(e){return e.variant===this.props.trueVariant}}const e1=t=>({props:t,type:Wt.TYPE,variant:"source",valueType:"boolean"}),Mf=a.z.object({precision:a.z.number().optional().default(2),prefix:a.z.string().optional().default(""),suffix:a.z.string().optional().default(""),notation:d.Fr.notationZ.optional().default("standard")});class Ht extends zt{static TYPE="stringify-number";static propsZ=Mf;schema=Ht.propsZ;transform(e){if(isNaN(e))return"";const{precision:n,prefix:r,suffix:s,notation:i}=this.props;return`${r}${d.Fr.stringifyNumber(e,n,i)}${s}`}}const t1=t=>({props:t,type:Ht.TYPE,variant:"source",valueType:"string"}),Uf=a.z.object({windowSize:a.z.number().optional().default(5)});class Wr extends zt{static TYPE="rolling-average";static propsZ=Rf;schema=Uf;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 n1=t=>({props:t,type:Wr.TYPE,variant:"source",valueType:"number"}),Zf=a.z.object({gradient:d.Rr.gradientZ});class Gt extends zt{static TYPE="color-gradient";static propsZ=Zf;schema=Gt.propsZ;transform(e){return d.Rr.fromGradient(this.props.gradient,e)}}const r1=t=>({props:t,type:Gt.TYPE,variant:"source",valueType:"color"}),Lf=a.z.object({scale:d.C.transform});class Kt extends zt{static TYPE="scale-number";static propsZ=Lf;schema=Kt.propsZ;transform(e){if(isNaN(e))return e;const{offset:n,scale:r}=this.props.scale;return e*r+n}}const s1=t=>({props:t,type:Kt.TYPE,variant:"source",valueType:"number"}),Df=a.z.enum(["average","decimate"]),a1=a.z.object({mode:Df,windowSize:a.z.number().optional().default(5)}),i1=t=>({props:t,type:ho.TYPE,variant:"source",valueType:"number"}),Bf=(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)}},o1=(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,l=0;for(let c=s;c<i;c++){const u=t.at(c);u!==void 0&&typeof u=="number"&&(o+=u,l++)}l>0&&e.write(new d.x({data:[o/l],dataType:t.dataType}))}},l1={decimate:Bf,average:o1};class ho{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=Bf:this._downsample=l1[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 c1=t=>({props:t,type:ho.TYPE,variant:"source",valueType:"series"});class fo{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 Ff=t=>{const e=[new Pf,new xf,new gf],n=new fo(e);return t!=null&&n.add(new Nf(t)),n.add(new co(n)),n};class Is{factory;key;parent;constructor(e,n){this.factory=e,this.key=d.Dt.create(),this.parent=n}child(e,n){const r=new fo([...this.factory.factories,...d.a.toArray(e)]);return r.add(new co(r)),new Is(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",Cs=t=>t.get(nr),Yf=(t,e)=>t.set(nr,e),u1=(t,e,n)=>{const r=Cs(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 qf{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||!Ss.equal(this.spec,n)}}class Rl extends qf{value(){return this.wrapped.value()}cleanup(){this.wrapped.cleanup?.()}onChange(e){return this.wrapped.onChange(e)}}class _l extends qf{set(...e){this.wrapped.set(...e)}cleanup(){this.wrapped.cleanup?.()}}const h1=(t,e,n,r)=>{const s=Cs(t);if(n instanceof Rl){if(!n.shouldUpdate(s,e))return n;n.cleanup?.()}return new Rl(s.create(e,r),s,e)},d1=(t,e,n,r)=>{const s=Cs(t);if(n instanceof _l){if(!n.shouldUpdate(s,e))return n;n.cleanup?.()}return new _l(s.create(e,r),s,e)},f1=a.z.object({props:Zd.nullable(),state:Xi.connectivity.connectionStateZ.nullable()}),po={client:null};class Jt extends at{static TYPE="synnax.Provider";static stateZ=f1;schema=Jt.stateZ;afterUpdate(e){if(e.wasSetPreviously(yo)||na(e,po),this.state.props==null){this.internal.client!=null&&(this.internal.client?.close(),this.internal.client=null),na(e,this.internal);return}this.prevState.props!=null&&Ss.equal(this.state.props,this.prevState.props)&&this.internal.client!=null||(this.internal.client=new Xi(this.state.props),na(e,this.internal))}}const yo="pluto-client-context",na=(t,e)=>t.set(yo,e),mo=t=>t.get(yo)?.client??null,Vf={[Jt.TYPE]:Jt},p1=Object.freeze(Object.defineProperty({__proto__:null,Provider:Jt,REGISTRY:Vf,ZERO_CONTEXT_VALUE:po,use:mo},Symbol.toStringTag,{value:"Module"})),Wf=(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)),y1=t=>t.isVariable||t.equals(d.n.UINT8)?t:d.n.FLOAT32,Hf=()=>({purgedSeries:0,purgedBytes:d.c$1.bytes(0)}),Gf={instrumentation:Te.NOOP,staleEntryThreshold:d.a$1.seconds(20)};class m1{data=[];props;constructor(e){this.props={...Gf,...e}}write(e){e.length!==0&&(e.series.forEach(n=>this.writeOne(Wf(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,l)=>l===0?d.m.ZERO:new d.m(n[l-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=Hf(),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(c=>c.data.alignmentBounds),e.alignmentBounds);if(r===null)return n.debug("Found no viable insertion plan",{inserting:e.digest,cacheContents:this.data.map(c=>c.data.digest)});const{removeBefore:s,removeAfter:i,insertInto:o,deleteInBetween:l}=r;e=e.slice(s,e.data.length-i),e.length!==0&&this.data.splice(o,l,{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((l,c)=>o===c?!1:d.H.overlapsWith(i,l))))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 g1=100,w1=1e6,b1=1e4,v1=100,T1=40;class S1{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*T1:e,dataType:y1(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 c=this.now();this.curr.timeRange.end=c,r.flushed.push(this.curr),this.curr=this.allocate(n,e.alignment,c),r.allocated.push(this.curr)}const s=Wf(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 l=this._write(e.slice(i));return r.flushed.push(l.flushed),r.allocated.push(l.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<v1)return b1;const n=d.Ar.roundToNearestMagnitude(this.avgRate*e.seconds);return Math.round(Math.max(Math.min(n,w1),g1))}close(){this.curr=null}}class z1{channel;closed=!1;ins;static;dynamic;constructor(e){this.channel=e.channel,this.ins=e.instrumentation??Te.NOOP,this.static=new m1(e),this.dynamic=new S1({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 O1=x.seconds(60);class E1{props;cache=new Map;gcInterval;constructor(e){this.props={dynamicBufferSize:O1,gcInterval:x.seconds(30),...Gf,...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 l of e)this.cache.has(l)||i.push(l);if(i.length===0)return;(await r.retrieve(i)).forEach(l=>{if(this.cache.has(l.key))return;const c=new z1({channel:l,dynamicBufferSize:s,instrumentation:n.child(`cache-${l.name}-${l.key}`)});this.cache.set(l.key,c)})}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=Hf();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 k1{args;debouncedRead;mu=d.Jr.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=Qi(()=>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:l}=this;return await new Promise((c,u)=>{l.runExclusive(async()=>{l.closed||l.requests.add({channel:n,gaps:o,resolve:c,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:l,reject:c})=>o==null?l():c(o));try{if(s.closed)return i();const o=[];s.requests.forEach(({channel:l,gaps:c})=>c.forEach(u=>{const h=o.find(p=>p.gap.equals(u,r));h==null?o.push({gap:u,channels:new Set([l])}):(h.channels.add(l),h.gap=d.m.max(h.gap,u))})),await Promise.all(o.map(async({gap:l,channels:c})=>{const u=await e(l,Array.from(c));c.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 N1=new Error("request for lock canceled");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 l(h){try{u(r.next(h))}catch(p){o(p)}}function c(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(l,c)}u((r=r.apply(t,e||[])).next())})};class A1{constructor(e,n=N1){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=Kf(this._queue,l=>n<=l.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return x1(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]=[]),I1(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 I1(t,e){const n=Kf(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function Kf(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var C1=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 l(h){try{u(r.next(h))}catch(p){o(p)}}function c(h){try{u(r.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):s(h.value).then(l,c)}u((r=r.apply(t,e||[])).next())})};class j1{constructor(e){this._semaphore=new A1(1,e)}acquire(){return C1(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 P1=d.a$1.milliseconds(100).milliseconds;class $1{props;mu=new j1;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=Qi(()=>void this.updateStreamer(),P1)}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 l=r.get(o);return[o,new d.Oe(d.a.toArray(l.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 l=s.get(o),u=n.get(o).writeDynamic(l);i.set(o,u)}i.size!==0&&this.listeners.forEach(({valid:o},l)=>o&&l(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 R1{async retrieveChannel(){throw new Ue("NoopClient does not support retrieving channels")}async read(){return new d.Oe([])}async stream(){return async()=>{}}async close(){}}class _1{ins;cache;reader;streamer;channelRetriever;constructor({instrumentation:e,core:n}){this.ins=e,this.channelRetriever=n.channels.createDebouncedBatchRetriever(10),this.cache=new E1({channelRetriever:this.channelRetriever,instrumentation:this.ins.child("cache")}),this.reader=new k1({cache:this.cache,readRemote:n.read.bind(n),instrumentation:this.ins.child("reader")}),this.streamer=new $1({cache:this.cache,openStreamer:async r=>$h.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 Jf=a.z.object({});class Ln extends at{static TYPE="telem.Provider";static stateZ=Jf;schema=Ln.stateZ;prevCore=null;client=null;afterUpdate(e){const{internal:n}=this,r=mo(e),s=Ns(e);if(n.instrumentation=io(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 R1:new _1({core:r,instrumentation:n.instrumentation});const o=Ff(this.client),l=new Is(o);Yf(e,l)}}const M1={[Ln.TYPE]:Ln};exports.A=x;exports.AbstractSink=vf;exports.AbstractSource=be;exports.Aggregator=Va;exports.BI=A0;exports.Base=As;exports.BaseProvider=Ln;exports.BooleanStatus=Wt;exports.Bt=ee;exports.CI=$h;exports.COMPONENT_SIZE_LEVELS=nI;exports.CONTEXT_KEY=nr;exports.ChannelData=Dr;exports.ColorGradient=Gt;exports.Composite=at;exports.CompoundTelemFactory=fo;exports.Context=yf;exports.Context$1=Is;exports.Eraser=Ja;exports.FI=W0;exports.FixedColorSource=Vr;exports.FixedNumber=Yr;exports.FixedString=qr;exports.GLProgram=ff;exports.H=D;exports.HI=WN;exports.IterativeSeries=Fr;exports.JI=cx;exports.LEVELS=En;exports.LEVEL_COMPONENT_SIZES=rI;exports.LS=Xi;exports.Leaf=Es;exports.Loop=pf;exports.Mean=Vt;exports.MultiSourceTransformer=Tf;exports.NI=JO;exports.NoopFactory=gf;exports.O=Ft;exports.PI=Vk;exports.PipelineFactory=co;exports.Provider=Ha;exports.Provider$1=Jt;exports.Provider$2=Ka;exports.REGISTRY=oC;exports.REGISTRY$1=M1;exports.REGISTRY$2=Vf;exports.REGISTRY$3=sC;exports.REGISTRY$4=mC;exports.REGISTRY$5=lC;exports.RemoteFactory=Nf;exports.RollingAverage=Wr;exports.SI=Pa;exports.SIZES=Kd;exports.SYNNAX_DARK=Gd;exports.SYNNAX_LIGHT=Hd;exports.SYNNAX_THEMES=fI;exports.ScaleNumber=Kt;exports.SeriesDownsampler=ho;exports.SetPoint=Yt;exports.SinkPipeline=Zr;exports.SourcePipeline=Ur;exports.StaticFactory=xf;exports.StreamChannelData=Br;exports.StreamChannelValue=Lr;exports.StringifyNumber=Ht;exports.T=Ss;exports.TransformerFactory=Pf;exports.UnarySinkTransformer=Sf;exports.UnarySourceTransformer=zt;exports.WithinBounds=qt;exports.XI=zx;exports.YI=jN;exports.ZERO_CONTEXT_VALUE=po;exports._=Bt;exports._I=Ak;exports.a=to;exports.aether=eC;exports.aggregatorStateZ=cf;exports.be=Xd;exports.booleanSinkSpecZ=AC;exports.booleanSinkTransformerSpecZ=IC;exports.booleanSourceSpecZ=xC;exports.booleanSourceTransformerSpecZ=CC;exports.booleanStatus=e1;exports.booleanStatusProps=_f;exports.channelData=BC;exports.colorGradient=r1;exports.colorGradientProps=Zf;exports.colorSourceSpecZ=$C;exports.connectionZ=lo;exports.createAsyncErrorHandler=lf;exports.createErrorHandler=of;exports.createFactory=Ff;exports.d=VA;exports.dimensions=XA;exports.dimensionsFromMetrics=Os;exports.downLevel=eI;exports.downsampleMode=i1;exports.downsampleModeProps=a1;exports.downsampleModeZ=Df;exports.eraserStateZ=mf;exports.executeInitialSetter=zs;exports.executeSetter=no;exports.fixedArray=qC;exports.fixedColor=GC;exports.fixedColorSourcePropsZ=jf;exports.fixedNumber=WC;exports.fixedNumberPropsZ=If;exports.fixedSeriesPropsZ=uo;exports.fixedString=HC;exports.fixedStringPropsZ=Cf;exports.fontSpecZ=uf;exports.g=Ld;exports.gI=uv;exports.h=eo;exports.hI=Ib;exports.isSize=pI;exports.iterativeArray=VC;exports.iterativeSeriesPropsZ=Af;exports.j=_;exports.jr=Ue;exports.kI=DE;exports.levelZ=QA;exports.mean=QC;exports.nk=vA;exports.noopBooleanSinkSpec=gC;exports.noopBooleanSourceSpec=bC;exports.noopColorSourceSpec=zC;exports.noopNumericSinkSpec=wC;exports.noopNumericSourceSpec=vC;exports.noopSeriesSourceSpec=OC;exports.noopStatusSourceSpec=SC;exports.noopStringSourceSpec=TC;exports.numberSinkSpecZ=PC;exports.numberSourceSpecZ=jC;exports.o=Qi;exports.pI=Jb;exports.prettyParse=Da;exports.provider=p1;exports.providerStateZ=Jf;exports.providerStateZ$1=df;exports.r=$A;exports.render=nf;exports.rollingAverage=n1;exports.rollingAverageProps=Uf;exports.scaleNumber=s1;exports.scaleNumberProps=Lf;exports.seriesDownsampler=c1;exports.seriesSourceSpecZ=NC;exports.setContext=Yf;exports.setpoint=JC;exports.sinkPipeline=UC;exports.sinkPipelinePropsZ=Of;exports.sinkSpecZ=xs;exports.sinkTransformerSpecZ=bf;exports.size=Jd;exports.sk=PA;exports.skipNull=Fd;exports.sourcePipeline=MC;exports.sourcePipelinePropsZ=zf;exports.sourceSpecZ=ot;exports.sourceTransformerSpecZ=wf;exports.specZ=Ve;exports.specZ$1=tr;exports.state=KA;exports.statusSourceSpecZ=RC;exports.streamChannelData=FC;exports.streamChannelValue=YC;exports.streamChannelValuePropsZ=Ef;exports.stringSourceSpecZ=_C;exports.stringifyNumber=t1;exports.stringifyNumberProps=Mf;exports.themeZ=Wd;exports.tk=iA;exports.use=iC;exports.use$1=mo;exports.useAdder=ks;exports.useAsyncErrorHandler=rC;exports.useChildContext=u1;exports.useContext=Cs;exports.useErrorHandler=Ns;exports.useInstrumentation=io;exports.useOptionalAdder=nC;exports.usePassthrough=qd;exports.usePurePassthrough=Vd;exports.useSink=d1;exports.useSource=h1;exports.weightZ=tI;exports.withinBounds=XC;exports.withinBoundsProps=$f;exports.y=C;exports.zI=c0;