@synnaxlabs/pluto 0.47.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/dist/{Animated-NfnNvlbz.cjs → Animated--SNIwznU.cjs} +1 -1
  2. package/dist/{Animated-CUFx-eAB.js → Animated-CC7iS0zH.js} +21 -21
  3. package/dist/{Animated-CEx4LoLs.js → Animated-DfDp0-ep.js} +4 -4
  4. package/dist/{Animated-Bq6z2XkH.cjs → Animated-TMpTdCqK.cjs} +1 -1
  5. package/dist/{Box-D5Qv__kr.js → Box-CoQUaJk2.js} +2 -2
  6. package/dist/{Box-BvqALodh.cjs → Box-Ds_D3xR_.cjs} +1 -1
  7. package/dist/Button-BaMa3eGI.cjs +1 -0
  8. package/dist/Button-NgDHbsf8.js +306 -0
  9. package/dist/{Dialog-BnPvG5WQ.cjs → Dialog-BL8T9CVw.cjs} +1 -1
  10. package/dist/{Dialog-Bi1Sf3oc.js → Dialog-CBDFqieV.js} +4 -4
  11. package/dist/{Editable-CxgdRDPb.js → Editable-C7KPD0hC.js} +3 -3
  12. package/dist/{Editable-BXFY3-UW.cjs → Editable-CWt3zqDm.cjs} +1 -1
  13. package/dist/{Haul-BuI0PZpo.js → Haul-Be1j5BU3.js} +2 -2
  14. package/dist/{Haul-2Xa_nMgc.cjs → Haul-D1WaI_xE.cjs} +1 -1
  15. package/dist/{Items-CHAbP2ZL.cjs → Items-BYlg9bb-.cjs} +1 -1
  16. package/dist/{Items-Cmc6otoS.js → Items-mikdEpyC.js} +8 -8
  17. package/dist/{Menu-CQ_GMgB9.js → Menu-CcWs0t21.js} +9 -9
  18. package/dist/{Menu-BImhHf24.cjs → Menu-DJoh8bH7.cjs} +1 -1
  19. package/dist/{Provider-D0P_lzCo.js → Provider-DScd3hYf.js} +26 -26
  20. package/dist/{Provider-BV7nN39a.cjs → Provider-fx1wTnXk.cjs} +2 -2
  21. package/dist/Tags-DvPUmH2r.js +908 -0
  22. package/dist/Tags-KHafaGjR.cjs +1 -0
  23. package/dist/{Text-BnUGzpJq.js → Text-BbbqH88W.js} +491 -486
  24. package/dist/Text-CZrjPRjJ.cjs +1 -0
  25. package/dist/{Video-VlT7jSYk.cjs → Video-DRSEX8t7.cjs} +1 -1
  26. package/dist/{Video-CITi2j07.js → Video-_DrutSeT.js} +2 -2
  27. package/dist/button.cjs +1 -1
  28. package/dist/button.js +1 -1
  29. package/dist/color.cjs +1 -1
  30. package/dist/color.js +1 -1
  31. package/dist/css-C_YE-5Xa.cjs +8 -0
  32. package/dist/{css-D6ZBcSwh.js → css-Cn63X_Yv.js} +1161 -1111
  33. package/dist/css.cjs +1 -1
  34. package/dist/css.js +2 -2
  35. package/dist/{deep-DtdcJG4q.cjs → deep-7SxmCL0x.cjs} +1 -1
  36. package/dist/{deep-DRVLw7iw.js → deep-szN5DCOH.js} +1 -1
  37. package/dist/dialog.cjs +1 -1
  38. package/dist/dialog.js +1 -1
  39. package/dist/{dimensions-CGLhBwVq.cjs → dimensions-DFDTcQRG.cjs} +1 -1
  40. package/dist/{dimensions-BFCMI7yN.js → dimensions-Dclfavlh.js} +1 -1
  41. package/dist/{eraser-DvzR9kLf.js → eraser-Bpl4bpBx.js} +13 -13
  42. package/dist/{eraser-Dm5Du4PL.cjs → eraser-Bqibt23a.cjs} +2 -2
  43. package/dist/ether.cjs +1 -1
  44. package/dist/ether.js +7 -7
  45. package/dist/{_commonjsHelpers-BH3jXuIh.cjs → event-BxvV3arE.cjs} +1 -1
  46. package/dist/{_commonjsHelpers-ByX85dGu.js → event-nNH_pXSr.js} +17 -14
  47. package/dist/{external-CMBnwYR4.cjs → external-19BIaQc6.cjs} +1 -1
  48. package/dist/{external-Daiy-vZ3.js → external-1uZLLxz-.js} +771 -792
  49. package/dist/{external-DGNBXSAj.js → external-6rS2YiWR.js} +16066 -15782
  50. package/dist/{external-CAcL3DJP.js → external-8H4eB7TN.js} +8 -8
  51. package/dist/{external-Eaj0hgzm.cjs → external-AInsIJp-.cjs} +1 -1
  52. package/dist/{external-CTsR6bs9.cjs → external-B3jTkhc4.cjs} +4 -22
  53. package/dist/external-B8hxM_jw.cjs +79 -0
  54. package/dist/{external-BTlfU938.js → external-BOWnCKIe.js} +3 -3
  55. package/dist/{external-D7EEjQaR.js → external-Bi-OQCBH.js} +19 -18
  56. package/dist/{external-6vmyay3h.js → external-Bq4gfE5e.js} +6 -6
  57. package/dist/{external-6RyUkYAB.js → external-C0_sN1J0.js} +2 -2
  58. package/dist/{external-CSntN1is.cjs → external-CFZ33YbY.cjs} +1 -1
  59. package/dist/{external-CTrkvlmd.cjs → external-CFdDgpzj.cjs} +1 -1
  60. package/dist/{external-BcZE443U.cjs → external-CJFfVl_u.cjs} +1 -1
  61. package/dist/{external-BrQU-ZN8.cjs → external-CN15E8ls.cjs} +1 -1
  62. package/dist/{external-Bo9Dyf8v.js → external-Caetm5fI.js} +5 -5
  63. package/dist/external-CfEVFfhL.cjs +1 -0
  64. package/dist/{external-CtiE4JLk.js → external-D6TsHpoG.js} +10 -10
  65. package/dist/{external-Clec0nDH.cjs → external-D7WE6Leo.cjs} +1 -1
  66. package/dist/{external-OLyg-4Ab.cjs → external-DUGcSVbJ.cjs} +1 -1
  67. package/dist/{external-BSjAne2q.js → external-DwhfVdFp.js} +5 -5
  68. package/dist/{external-BhOvtmPt.js → external-X_eFMRtE.js} +2 -2
  69. package/dist/{external-Dl0l3iHN.cjs → external-pRQzznIG.cjs} +1 -1
  70. package/dist/{external-OzDazbiJ.js → external-y1Apm7j1.js} +14 -14
  71. package/dist/flex.cjs +1 -1
  72. package/dist/flex.js +1 -1
  73. package/dist/{fontString-yPlq8smc.cjs → fontString-BcSXNOgW.cjs} +1 -1
  74. package/dist/{fontString-CGd4NYXa.js → fontString-D7EMGjIw.js} +2 -2
  75. package/dist/header.cjs +1 -1
  76. package/dist/header.js +1 -1
  77. package/dist/{hooks-Bvv-S6WC.js → hooks-BmUn8s1r.js} +4 -4
  78. package/dist/{hooks-CoF3Fkrn.cjs → hooks-CutQY1o9.cjs} +1 -1
  79. package/dist/index.cjs +8 -40
  80. package/dist/index.js +9333 -9141
  81. package/dist/input.cjs +1 -1
  82. package/dist/input.js +1 -1
  83. package/dist/{jsx-runtime-OVHDjVDe.js → jsx-runtime-BbD0H88J.js} +108 -128
  84. package/dist/jsx-runtime-nZSsnGb7.cjs +6 -0
  85. package/dist/list.cjs +1 -1
  86. package/dist/list.js +1 -1
  87. package/dist/menu.cjs +1 -1
  88. package/dist/menu.js +1 -1
  89. package/dist/pluto.css +1 -1
  90. package/dist/{provider-C8In649C.js → provider-B6SgG_sT.js} +4910 -4821
  91. package/dist/provider-C9Beoajx.cjs +72 -0
  92. package/dist/src/button/Button.d.ts +2 -1
  93. package/dist/src/button/Button.d.ts.map +1 -1
  94. package/dist/src/channel/LinePlot.d.ts +4 -1
  95. package/dist/src/channel/LinePlot.d.ts.map +1 -1
  96. package/dist/src/channel/Select.d.ts +2 -2
  97. package/dist/src/channel/Select.d.ts.map +1 -1
  98. package/dist/src/cluster/index.d.ts +2 -0
  99. package/dist/src/cluster/index.d.ts.map +1 -0
  100. package/dist/src/cluster/queries.d.ts +6 -0
  101. package/dist/src/cluster/queries.d.ts.map +1 -0
  102. package/dist/src/cluster/queries.spec.d.ts +2 -0
  103. package/dist/src/cluster/queries.spec.d.ts.map +1 -0
  104. package/dist/src/color/GradientPicker.d.ts.map +1 -1
  105. package/dist/src/flux/retrieve.d.ts +9 -8
  106. package/dist/src/flux/retrieve.d.ts.map +1 -1
  107. package/dist/src/hardware/device/Select.d.ts +1 -1
  108. package/dist/src/hardware/device/Select.d.ts.map +1 -1
  109. package/dist/src/hardware/rack/Select.d.ts +1 -1
  110. package/dist/src/hardware/rack/Select.d.ts.map +1 -1
  111. package/dist/src/icon/registry.d.ts +1 -0
  112. package/dist/src/icon/registry.d.ts.map +1 -1
  113. package/dist/src/index.d.ts +1 -0
  114. package/dist/src/index.d.ts.map +1 -1
  115. package/dist/src/input/DateTime.d.ts.map +1 -1
  116. package/dist/src/input/DateTime.spec.d.ts +2 -0
  117. package/dist/src/input/DateTime.spec.d.ts.map +1 -0
  118. package/dist/src/label/Select.d.ts +3 -3
  119. package/dist/src/label/Select.d.ts.map +1 -1
  120. package/dist/src/menu/Item.d.ts.map +1 -1
  121. package/dist/src/schematic/symbol/Primitives.d.ts.map +1 -1
  122. package/dist/src/select/Dialog.d.ts +2 -3
  123. package/dist/src/select/Dialog.d.ts.map +1 -1
  124. package/dist/src/select/Multiple.d.ts.map +1 -1
  125. package/dist/src/select/MultipleTrigger.d.ts.map +1 -1
  126. package/dist/src/status/Select.d.ts +1 -1
  127. package/dist/src/status/Select.d.ts.map +1 -1
  128. package/dist/src/status/queries.d.ts +13 -0
  129. package/dist/src/status/queries.d.ts.map +1 -1
  130. package/dist/src/synnax/Provider.d.ts +2 -2
  131. package/dist/src/synnax/Provider.d.ts.map +1 -1
  132. package/dist/src/synnax/aether/provider.d.ts.map +1 -1
  133. package/dist/src/table/Table.d.ts.map +1 -1
  134. package/dist/src/tag/Tag.d.ts.map +1 -1
  135. package/dist/src/user/Avatar.d.ts +7 -0
  136. package/dist/src/user/Avatar.d.ts.map +1 -0
  137. package/dist/src/user/external.d.ts +3 -0
  138. package/dist/src/user/external.d.ts.map +1 -0
  139. package/dist/src/user/index.d.ts +1 -1
  140. package/dist/src/user/index.d.ts.map +1 -1
  141. package/dist/src/user/queries.d.ts +1 -0
  142. package/dist/src/user/queries.d.ts.map +1 -1
  143. package/dist/src/vis/draw2d/index.d.ts +2 -1
  144. package/dist/src/vis/draw2d/index.d.ts.map +1 -1
  145. package/dist/src/vis/measure/Measure.d.ts +4 -1
  146. package/dist/src/vis/measure/Measure.d.ts.map +1 -1
  147. package/dist/src/vis/measure/aether/measure.d.ts +27 -1
  148. package/dist/src/vis/measure/aether/measure.d.ts.map +1 -1
  149. package/dist/tabs.cjs +1 -1
  150. package/dist/tabs.js +1 -1
  151. package/dist/text.cjs +1 -1
  152. package/dist/text.js +2 -2
  153. package/dist/theming.cjs +1 -1
  154. package/dist/theming.js +2 -2
  155. package/dist/tree.cjs +1 -1
  156. package/dist/tree.js +1 -1
  157. package/dist/triggers.cjs +1 -1
  158. package/dist/triggers.js +1 -1
  159. package/dist/{units-BqIfn6VX.js → units-cBd5OJg4.js} +1 -1
  160. package/dist/units-zxke9Ng2.cjs +1 -0
  161. package/dist/value-Ce4T858D.cjs +53 -0
  162. package/dist/{value-ChGMEPP3.js → value-UJNdARAu.js} +2715 -2512
  163. package/dist/video.cjs +1 -1
  164. package/dist/video.js +1 -1
  165. package/package.json +23 -21
  166. package/dist/Button-BMeq9Z2I.cjs +0 -1
  167. package/dist/Button-CMRdj9Ti.js +0 -305
  168. package/dist/Tags-6IUFBvU-.js +0 -604
  169. package/dist/Tags-DtnStTuF.cjs +0 -1
  170. package/dist/Text-DY08sSZe.cjs +0 -1
  171. package/dist/css-HnNQMUzV.cjs +0 -8
  172. package/dist/external-DDzR-j7b.cjs +0 -1
  173. package/dist/external-Ddn3rc_Q.cjs +0 -85
  174. package/dist/jsx-runtime-Dszzpdy0.cjs +0 -22
  175. package/dist/provider-lNhTlIWj.cjs +0 -72
  176. package/dist/units-DCifOxd9.cjs +0 -1
  177. package/dist/value-B3LTg1lE.cjs +0 -53
@@ -1,72 +0,0 @@
1
- "use strict";const a=require("zod"),A=require("./css-HnNQMUzV.cjs"),De=require("./types-D-yz1qsT.cjs"),_h=require("./deep-DtdcJG4q.cjs"),Rh=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)},oo=t=>{const e=(n,r=hs)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!Br(n))return n;r=Bh(r);const s={},i=n;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),r):(Object.keys(i).forEach(o=>{let c=i[o];const l=t(o);r.recursive&&(Br(c)?Ga(c)||(c=e(c,r)):r.recursiveInArray&&Ha(c)&&(c=[...c].map(u=>{let h=u;return Br(u)?Ga(h)||(h=e(u,r)):Ha(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},co=oo(Rh),Zh=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),Lh=oo(Zh),Dh=[Number,String,Uint8Array],hs={recursive:!0,recursiveInArray:!0},Bh=(t=hs)=>(t.recursive==null?t=hs:t.recursiveInArray??=!1,t),Ha=t=>t!=null&&Array.isArray(t),Br=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Ga=t=>Dh.some(e=>t instanceof e);let Fh=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=co(n);return e!=null?e.parse(r):r}encodeString(t){const e=Lh(t);return JSON.stringify(e,(n,r)=>ArrayBuffer.isView(r)?Array.from(r):typeof r=="bigint"?r.toString():r)}};const ds=new Fh,pe=t=>t!=null&&typeof t=="object"&&"value"in t;let Ut=class{value;constructor(t){this.value=t}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const qh=t=>t!=null&&typeof t=="object"&&"toString"in t,Yh=(t,e=!1)=>{const n=qh(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?Vh(r):r},Vh=t=>(e,n)=>t(n,e),mr=a.z.tuple([a.z.number(),a.z.number()]);a.z.tuple([a.z.bigint(),a.z.bigint()]);const lo=a.z.object({width:a.z.number(),height:a.z.number()}),Wh=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()}),Hh=["width","height"];a.z.enum(Hh);const Gh=["start","center","end"],Kh=["signedWidth","signedHeight"];a.z.enum(Kh);const sr=a.z.object({x:a.z.number(),y:a.z.number()}),Jh=a.z.object({clientX:a.z.number(),clientY:a.z.number()}),Xh=["x","y"],uo=a.z.enum(Xh),ho=["top","right","bottom","left"];a.z.enum(ho);const Qh=["left","right"],fo=a.z.enum(Qh),ed=["top","bottom"],po=a.z.enum(ed),yo=["center"],Ka=a.z.enum(yo),td=[...ho,...yo],mo=a.z.enum(td);a.z.enum(Gh);const nd=["first","last"];a.z.enum(nd);const rd=a.z.object({lower:a.z.number(),upper:a.z.number()}),sd=a.z.object({lower:a.z.bigint(),upper:a.z.bigint()});a.z.union([rd,mr]);a.z.union([sd,mr]);a.z.enum([...uo.options,...mo.options]);a.z.enum(["x","left","right"]);a.z.enum(["y","top","bottom"]);a.z.union([uo,mo,a.z.instanceof(String)]);const gr=t=>(e,n)=>{if(typeof e=="bigint"){if(ad(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))},wr=gr((t,e)=>t-e),br=gr((t,e)=>t+e),ad=t=>typeof t=="bigint"?!0:Number.isInteger(t),Ie=gr((t,e)=>t*e),vr=gr((t,e)=>t/e),ot=(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?id(r):r},id=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Ja=(t,e)=>{const n=ot(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e};a.z.object({x:fo.or(Ka),y:po.or(Ka)});const od=a.z.object({x:fo,y:po}),cd=Object.freeze({x:"left",y:"top"}),ld=(t,e)=>t.x===e.x&&t.y===e.y,Xa=a.z.union([a.z.number(),sr,mr,lo,Wh,Jh]),ud=(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}},Qa=Object.freeze({x:0,y:0}),Ln=a.z.union([a.z.number(),a.z.string()]);a.z.object({top:Ln,left:Ln,width:Ln,height:Ln});a.z.object({left:a.z.number(),top:a.z.number(),right:a.z.number(),bottom:a.z.number()});a.z.object({one:sr,two:sr,root:od});const Xs=(t,e,n=0,r=0,s)=>{const i={one:{...Qa},two:{...Qa},root:s??cd};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))},Fr=t=>{const e=Xs(t);return{lower:e.one.x,upper:e.two.x}},qr=t=>{const e=Xs(t);return{lower:e.one.y,upper:e.two.y}},hd=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,dd=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()});a.z.union([lo,dd,sr,mr]);const fd=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;a.z.object({offset:Xa,scale:Xa});a.z.object({offset:a.z.number(),scale:a.z.number()});const pd=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],yd=t=>(e,n,r,s)=>[e,s?r/t:r*t],md=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:i}=e,{lower:o,upper:c}=t,l=i-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},gd=t=>(e,n,r)=>[t,r],wd=()=>(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)]},bd=t=>(e,n,r)=>{const{lower:s,upper:i}=t;return r=fd(r,s,i),[e,r]};let ei=class gt{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new gt().translate(e)}static magnify(e){return new gt().magnify(e)}static scale(e,n){return new gt().scale(e,n)}translate(e){const n=this.new(),r=pd(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=yd(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=ot(e,n),s=this.new(),i=md(r);return i.type="scale",s.ops.push(i),s}clamp(e,n){const r=ot(e,n),s=this.new(),i=bd(r);return i.type="clamp",s.ops.push(i),s}reBound(e,n){const r=ot(e,n),s=this.new(),i=gd(r);return i.type="re-bound",s.ops.push(i),s}invert(){const e=wd();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 gt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],i)=>i(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const i=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);i!==-1&&n.push([s,i])}),n.forEach(([r,s])=>{const i=e.ops.slice(r,s);i.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new gt};(class ke{x;y;currRoot;constructor(e=new ei,n=new ei,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new ke().translate(e,n)}static translateX(e){return new ke().translateX(e)}static translateY(e){return new ke().translateY(e)}static clamp(e){return new ke().clamp(e)}static magnify(e){return new ke().magnify(e)}static scale(e){return new ke().scale(e)}static reBound(e){return new ke().reBound(e)}translate(e,n){const r=ud(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(hd(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!ld(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(Fr(e)),n.y=n.y.scale(qr(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(Fr(e)),n.y=this.y.reBound(qr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(Fr(e)),n.y=this.y.clamp(qr(e)),n}copy(){const e=new ke;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 Xs(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 ke});let go=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const wo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",vd=`0123456789${wo}`,zd=11,Td=go(wo,1),Od=go(vd,zd-1),Sd=()=>`${Td()}${Od()}`,kd=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,Nd=a.z.enum(["static","dynamic"]),fs=2n**63n-1n,Ed=2**63-1,ti=365,Dn=30,Ad=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)])]),bo=(t,e)=>{const n=new _(e);if(![U.DAY,U.HOUR,U.MINUTE,U.SECOND,U.MILLISECOND,U.MICROSECOND,U.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 _?new _(r):new U(r)};let _=class z extends Ut{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===Ed?e=fs:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=z.MAX:e=z.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 z(BigInt(s.getTime())*z.MILLISECOND.valueOf()).truncate(z.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,i]=e.split(":");let o="00",c="00";i!=null&&([o,c]=i.split("."));let l=z.hours(parseInt(r??"00")).add(z.minutes(parseInt(s??"00"))).add(z.seconds(parseInt(o??"00"))).add(z.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(z.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return z.parseTimeString(e,n);const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new z(BigInt(r.getTime())*z.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(z.utcOffset).date().toISOString()}timeString(e=!1,n="UTC"){const r=this.toISOString(n);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),n=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${n} ${r}`}static get utcOffset(){return new U(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 Jt(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(br(this.valueOf(),new U(e).valueOf()))}sub(e){return new z(wr(this.valueOf(),new U(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(U.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(U.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(U.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(U.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 bo(this,e)}get isToday(){return this.truncate(U.DAY).equals(z.now().truncate(U.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(fs);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 U).transform(e=>new z(e)),Ad.transform(e=>new z(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}},U=class S extends Ut{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 S?e:e instanceof Yr?e.period:e instanceof _?new S(e):(pe(e)&&(e=e.value),["number","bigint"].includes(typeof e)?S.seconds(e):new S(e))}static fromMilliseconds(e){return e instanceof S?e:e instanceof Yr?e.period:e instanceof _?new S(e):(pe(e)&&(e=e.value),["number","bigint"].includes(typeof e)?S.milliseconds(e):new S(e))}valueOf(){return this.value}lessThan(e){return this.valueOf()<new S(e).valueOf()}greaterThan(e){return this.valueOf()>new S(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new S(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new S(e).valueOf()}remainder(e){return bo(this,e)}truncate(e){return new S(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(S.DAY),r=this.truncate(S.HOUR),s=this.truncate(S.MINUTE),i=this.truncate(S.SECOND),o=this.truncate(S.MILLISECOND),c=this.truncate(S.MICROSECOND),l=this.truncate(S.NANOSECOND),u=n,h=r.sub(n),f=s.sub(r),d=i.sub(s),O=o.sub(i),C=c.sub(o),j=l.sub(c);let w="";return u.isZero||(w+=`${u.days}d `),h.isZero||(w+=`${h.hours}h `),f.isZero||(w+=`${f.minutes}m `),d.isZero||(w+=`${d.seconds}s `),O.isZero||(w+=`${O.milliseconds}ms `),C.isZero||(w+=`${C.microseconds}µs `),j.isZero||(w+=`${j.nanoseconds}ns`),w.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new S(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(S.SECOND))return"< 1s";const s=n.days,i=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/ti),u=Math.floor(s/Dn),h=Math.floor(s/7),f=Math.floor(s),d=Math.floor(i),O=Math.floor(o),C=Math.floor(c),j=r?"-":"";if(l>=1){let w=`${l}y`;if(l<2){const v=Math.floor(s%ti/Dn);v>0&&(w+=` ${v}mo`)}return j+w}if(h>=1&&s<Dn&&s%7===0){let w=`${h}w`;const v=Math.floor(s%7),I=Math.floor(i-h*7*24);return h<2&&(v>0?w+=` ${v}d`:I>0&&I<24&&(w+=` ${I}h`)),j+w}if(u>=1){let w=`${u}mo`;if(u<3){const v=Math.floor(s%Dn);v>0&&(w+=` ${v}d`)}return j+w}if(h>=1){let w=`${h}w`;const v=Math.floor(s%7),I=Math.floor(i-h*7*24);return h<2&&(v>0?w+=` ${v}d`:I>0&&I<24&&(w+=` ${I}h`)),j+w}if(f>=1){let w=`${f}d`;const v=Math.floor(i-f*24);return f<2&&v>0&&(w+=` ${v}h`),j+w}if(d>=1){let w=`${d}h`;if(d<3){const v=Math.floor(o-d*60);v>0&&(w+=` ${v}m`)}return j+w}if(O>=1){let w=`${O}m`;if(O<5){const v=Math.floor(c-O*60);v>0&&(w+=` ${v}s`)}return j+w}return`${j}${C}s`}mult(e){return new S(Ie(this.valueOf(),e))}div(e){return new S(vr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(S.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(S.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(S.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(S.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 isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new S(e).valueOf()}add(e){return new S(this.valueOf()+new S(e).valueOf())}sub(e){return new S(this.valueOf()-new S(e).valueOf())}static nanoseconds(e=1){return new S(e)}static NANOSECOND=S.nanoseconds(1);static microseconds(e=1){return S.nanoseconds(Ie(e,1e3))}static MICROSECOND=S.microseconds(1);static milliseconds(e=1){return S.microseconds(Ie(e,1e3))}static MILLISECOND=S.milliseconds(1);static seconds(e=1){return S.milliseconds(Ie(e,1e3))}static SECOND=S.seconds(1);static minutes(e=1){return S.seconds(Ie(e,60))}static MINUTE=S.minutes(1);static hours(e){return S.minutes(Ie(e,60))}static HOUR=S.hours(1);static days(e){return S.hours(Ie(e,24))}static DAY=S.days(1);static MAX=new S(fs);static MIN=new S(0);static ZERO=new S(0);static z=a.z.union([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.instanceof(S),a.z.instanceof(_).transform(e=>new S(e)),a.z.custom(e=>e instanceof Yr).transform(e=>new S(e))])},Yr=class he extends Ut{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 U.seconds(1/this.valueOf())}sampleCount(e){return new U(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new te(n).valueOf()}span(e){return U.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new te(n).valueOf())}add(e){return new he(br(this.valueOf(),new he(e).valueOf()))}sub(e){return new he(wr(this.valueOf(),new he(e).valueOf()))}mult(e){return new he(Ie(this.valueOf(),e))}div(e){return new he(vr(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)])},te=class se extends Ut{constructor(e){pe(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new ps(e*this.valueOf())}add(e){return new se(br(this.valueOf(),new se(e).valueOf()))}sub(e){return new se(wr(this.valueOf(),new se(e).valueOf()))}mult(e){return new se(Ie(this.valueOf(),e))}div(e){return new se(vr(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)])},Jt=class Ne{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new _(e.start),this.end=new _(e.end)):(this.start=new _(e),this.end=new _(n))}get span(){return new U(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 Ne(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=U.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=U.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=_.max(r.start,e.start),i=_.min(r.end,e.end);return i.before(s)?!1:new U(i.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof Ne?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new Ne(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 Ne(_.min(...e.map(n=>n.start)),_.max(...e.map(n=>n.end)))}static MAX=new Ne(_.MIN,_.MAX);static ZERO=new Ne(_.ZERO,_.ZERO);static z=a.z.union([a.z.object({start:_.z,end:_.z}).transform(e=>new Ne(e.start,e.end)),a.z.instanceof(Ne)]);static sort(e,n){return _.sort(e.start,n.start)||_.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>Ne.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=_.max(s.end,r.end):n.push(r),n},[])}},q=class y extends Ut{constructor(e){if(pe(e)&&(e=e.value),e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const n=y.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=y.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(n=>this.equals(n))}toString(e=!1){return e?y.SHORT_STRINGS.get(this.valueOf())??this.valueOf():this.valueOf()}get isVariable(){return this.equals(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=new y("boolean");static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),te.BIT8],[y.UINT16.toString(),te.BIT16],[y.UINT32.toString(),te.BIT32],[y.UINT64.toString(),te.BIT64],[y.FLOAT32.toString(),te.BIT32],[y.FLOAT64.toString(),te.BIT64],[y.INT8.toString(),te.BIT8],[y.INT16.toString(),te.BIT16],[y.INT32.toString(),te.BIT32],[y.INT64.toString(),te.BIT64],[y.TIMESTAMP.toString(),te.BIT64],[y.STRING.toString(),te.UNKNOWN],[y.JSON.toString(),te.UNKNOWN],[y.UUID.toString(),te.BIT128]]);static ALL=[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON];static SHORT_STRINGS=new Map([[y.UINT8.toString(),"u8"],[y.UINT16.toString(),"u16"],[y.UINT32.toString(),"u32"],[y.UINT64.toString(),"u64"],[y.INT8.toString(),"i8"],[y.INT16.toString(),"i16"],[y.INT32.toString(),"i32"],[y.INT64.toString(),"i64"],[y.FLOAT32.toString(),"f32"],[y.FLOAT64.toString(),"f64"],[y.BOOLEAN.toString(),"bool"],[y.TIMESTAMP.toString(),"ts"],[y.UUID.toString(),"uuid"],[y.STRING.toString(),"str"],[y.JSON.toString(),"json"]]);static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=a.z.union([a.z.string().transform(e=>new y(e)),a.z.instanceof(y)])},ps=class $ extends Ut{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 $(br(this.valueOf(),e.valueOf()))}sub(e){return pe(e)&&(e=e.value),new $(wr(this.valueOf(),e.valueOf()))}mult(e){return new $(Ie(this.valueOf(),e))}div(e){return new $(vr(this.valueOf(),e))}truncate(e){return new $(Math.trunc(this.valueOf()/new $(e).valueOf())*new $(e).valueOf())}remainder(e){return $.bytes(this.valueOf()%new $(e).valueOf())}get gigabytes(){return this.valueOf()/$.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/$.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/$.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/$.TERABYTE.valueOf()}toString(){const e=this.truncate($.TERABYTE),n=this.truncate($.GIGABYTE),r=this.truncate($.MEGABYTE),s=this.truncate($.KILOBYTE),i=this.truncate($.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=i.sub(s);let f="";return o.isZero||(f+=`${o.terabytes}TB `),c.isZero||(f+=`${c.gigabytes}GB `),l.isZero||(f+=`${l.megabytes}MB `),u.isZero||(f+=`${u.kilobytes}KB `),(!h.isZero||f==="")&&(f+=`${h.valueOf()}B`),f.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 vo=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof _||t instanceof U||t instanceof Date},Id=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):Xn(n,-r),Xn=(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),xd=/^(?:[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 Cd(t){return typeof t=="string"&&xd.test(t)}const J=[];for(let t=0;t<256;++t)J.push((t+256).toString(16).slice(1));function jd(t,e=0){return(J[t[e+0]]+J[t[e+1]]+J[t[e+2]]+J[t[e+3]]+"-"+J[t[e+4]]+J[t[e+5]]+"-"+J[t[e+6]]+J[t[e+7]]+"-"+J[t[e+8]]+J[t[e+9]]+"-"+J[t[e+10]]+J[t[e+11]]+J[t[e+12]]+J[t[e+13]]+J[t[e+14]]+J[t[e+15]]).toLowerCase()}function $d(t,e=0){const n=jd(t,e);if(!Cd(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const zo=(t,e)=>$d(t,e),_e=-1,Md=a.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Ud=a.z.union([a.z.null(),a.z.undefined()]).transform(()=>new Uint8Array().buffer),ys=10,Pd=(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`)},To="sy_x_telem_series";let Oo=class Be{key;discriminator=To;dataType;sampleOffset;gl;_data;timeRange=Jt.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=_e;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=a.z.object({timeRange:Jt.z.optional(),dataType:q.z,alignment:a.z.coerce.bigint().optional(),data:a.z.union([Md,Ud,a.z.instanceof(ArrayBuffer),a.z.instanceof(Uint8Array)]),glBufferUsage:Nd.optional().default("static").optional()});static z=Be.crudeZ.transform(e=>new Be(e));constructor(e){_d(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=Sd(),data:u}=e;if(Rd(u)){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this.timeRange=d.timeRange,this.alignment=d.alignment,this.alignmentMultiple=d.alignmentMultiple,this.cachedMin=d.cachedMin,this.cachedMax=d.cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this.cachedLength=d.cachedLength;return}const h=vo(u),f=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(f||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=q.STRING;else if(typeof d=="number")this.dataType=q.FLOAT64;else if(typeof d=="bigint")this.dataType=q.INT64;else if(typeof d=="boolean")this.dataType=q.BOOLEAN;else if(d instanceof _||d instanceof Date||d instanceof _)this.dataType=q.TIMESTAMP;else if(typeof d=="object")this.dataType=q.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new q(u)}if(!f&&!h)this._data=u;else if(f&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[u]:u;const O=d[0];(O instanceof _||O instanceof Date||O instanceof U)&&(d=d.map(C=>new _(C).valueOf())),this.dataType.equals(q.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
2
- `)}
3
- `).buffer):this.dataType.equals(q.JSON)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(C=>ds.encodeString(C)).join(`
4
- `)}
5
- `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(d.map(C=>BigInt(Math.round(C)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(d.map(Number)).buffer:this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??Jt.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 Be({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===_e)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===_e)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===_e?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(ds.decodeString(n)))}get byteCapacity(){return new ps(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===_e?this.byteCapacity:this.dataType.isVariable?new ps(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===_e?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===ys&&(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]=Id(this.dataType,e,this.data[s],n);return new Be({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(),Xn(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(),Xn(this.cachedMin,this.sampleOffset))}get bounds(){return ot(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 Xn(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=zo(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]===ys){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):co(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let n=0,r=this.length-1;const s=Yh(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!==_e){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=_e}as(e){return Pd(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:ri(this.alignmentBounds.lower),upper:ri(this.alignmentBounds.upper),multiple:this.alignmentMultiple},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return ot(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 Zd(this);return this.dataType.equals(q.JSON)?new Ld(e):e}return this.dataType.equals(q.UUID)?new Dd(this):new Bd(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new ni(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 ni(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 Be({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 Be({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Be({data:this.buffer,dataType:this.dataType,timeRange:Jt.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 _d=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Oo?!0:vo(t),Rd=kd(To,Oo);class ni{series;end;index;constructor(e,n,r){this.series=e;const s=ot(0,e.length+1);this.end=Ja(s,r),this.index=Ja(s,n)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class Zd{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]!==ys;)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 Ld=class So{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:ds.decodeString(e.value,So.schema)}}};class Dd{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=zo(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Bd=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 ri=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 Fd=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Fd();const qd=["macOS","Windows","Linux"],Yd=["macos","windows","linux"],Vd={macos:"macOS",windows:"Windows",linux:"Linux"};a.z.enum(qd).or(a.z.enum(Yd).transform(t=>Vd[t]));const Wd=(...t)=>t.map(ko).join(""),ko=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Hd=t=>t.endsWith("/")?t.slice(0,-1):t,Gd=(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 Kd=class Qn{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=ko(s)}replace(e){return new Qn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Qn({...this,pathPrefix:Wd(this.path,e)})}toString(){return Hd(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Qn({host:"unknown",port:0})};const Jd=async t=>await new Promise(e=>setTimeout(e,U.fromMilliseconds(t).milliseconds));class Xd{config;retries;interval;constructor(e){this.config={baseInterval:new U(e?.baseInterval??U.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Jd},this.retries=0,this.interval=new U(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 Qd=a.z.object({baseInterval:U.z.optional(),maxRetries:a.z.number().optional(),scale:a.z.number().optional()}),ef=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Xd,breakerConfigZ:Qd},Symbol.toStringTag,{value:"Module"})),tf=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,No=a.z.string().regex(tf),kt=a.z.number().min(0).max(255),Eo=a.z.number().min(0).max(1),Ao=a.z.tuple([kt,kt,kt,Eo]),nf=a.z.tuple([kt,kt,kt]),rf=a.z.object({rgba255:Ao}),sf=a.z.number().min(0).max(360),af=a.z.number().min(0).max(100),of=a.z.number().min(0).max(100),cf=a.z.tuple([sf,af,of,Eo]),Qs=a.z.union([No,nf,Ao,cf,rf]),lf=Qs.transform(t=>ea(t)),ea=(t,e=1)=>{if(t=Qs.parse(t),typeof t=="string")return uf(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},uf=(t,e=1)=>(t=No.parse(t),t=hf(t),[Bn(t,0),Bn(t,2),Bn(t,4),t.length===8?Bn(t,6)/255:e]),Bn=(t,e)=>parseInt(t.slice(e,e+2),16),hf=t=>t.startsWith("#")?t.slice(1):t;ea("#000000");ea("#ffffff");const df=a.z.object({key:a.z.string(),color:Qs,position:a.z.number(),switched:a.z.boolean().optional()});a.z.array(df);const ff=a.z.object({key:a.z.string(),name:a.z.string(),color:lf});a.z.object({key:a.z.string(),name:a.z.string(),swatches:a.z.array(ff)});a.z.int().min(0).max(255);a.z.object({name:a.z.string(),key:a.z.string()});const pf=t=>Object.getOwnPropertySymbols(globalThis).includes(t),yf=(t,e)=>{const n=Symbol.for(t);if(!pf(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Io="sy_x_error",mf=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),zn=t=>class Xt extends Error{static discriminator=Io;discriminator=Xt.discriminator;static TYPE=t;type=Xt.TYPE;static matches=mf(t);matches=Xt.matches;constructor(n,r){super(n,r),this.name=Xt.TYPE}static sub(n){return zn(`${t}.${n}`)}},xo=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Io)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},wt="unknown",ms="nil";class gf{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:ms,data:""};if(xo(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:wt,data:e.message};if(typeof e=="string")return{type:wt,data:e};try{return{type:wt,data:JSON.stringify(e)}}catch{return{type:wt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===ms)return null;if(e.type===wt)return new gs(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new gs(e.data)}}const ta=yf("synnax-error-registry",()=>new gf),wf=({encode:t,decode:e})=>ta().register({encode:t,decode:e}),bf=t=>ta().encode(t),vf=t=>t==null?null:ta().decode(t);let gs=class extends zn("unknown"){};const zf=a.z.object({type:a.z.string(),data:a.z.string()});class Tf extends zn("canceled"){}class Of extends zn("not_implemented"){}const We=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Tf,NONE:ms,NotImplemented:Of,UNKNOWN:wt,Unknown:gs,createTyped:zn,decode:vf,encode:bf,isTyped:xo,payloadZ:zf,register:wf},Symbol.toStringTag,{value:"Module"})),Sf=a.object({jsonrpc:a.literal("2.0"),method:a.string(),params:a.any().optional(),id:a.union([a.string(),a.number(),a.null()]).optional()}),Co=a.object({jsonrpc:a.literal("2.0"),id:a.union([a.string(),a.number(),a.null()])}),kf=Co.extend({result:a.json()}),Nf=Co.extend({error:a.object({code:a.number().int(),message:a.string().optional(),data:a.json().optional()})}),Ef=a.union([kf,Nf]);a.union([Sf,Ef]);const Af=a.uuid();a.object({key:Af,name:a.string().min(1),color:a.string()});a.z.string().regex(/^\d+\.\d+\.\d+$/);const If=["standard","scientific","engineering"];a.z.enum(If);a.z.enum(["success","info","warning","error","loading","disabled"]);a.z.object({stack:a.z.string(),error:a.z.instanceof(Error)});let Tn=class extends We.createTyped("freighter"){},ze=class extends Tn.sub("eof"){constructor(){super("EOF")}},At=class extends Tn.sub("stream_closed"){constructor(){super("StreamClosed")}},He=class extends Tn.sub("unreachable"){url;constructor(t={}){const{message:e="Unreachable",url:n=Kd.UNKNOWN}=t;super(e),this.url=n}};const xf=t=>{if(!t.type.startsWith(Tn.TYPE))return null;if(ze.matches(t))return{type:ze.TYPE,data:"EOF"};if(At.matches(t))return{type:At.TYPE,data:"StreamClosed"};if(He.matches(t))return{type:He.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},Cf=t=>{if(!t.type.startsWith(Tn.TYPE))return null;switch(t.type){case ze.TYPE:return new ze;case At.TYPE:return new At;case He.TYPE:return new He;default:throw new We.Unknown(`Unknown error type: ${t.data}`)}};We.register({encode:xf,decode:Cf});let jo=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 $o="Content-Type",jf=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),$f=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&jf.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},Mf=400;let Uf=class extends jo{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{[$o]:this.encoder.contentType}}async send(t,e,n,r){e=n?.parse(e);let s=null;const i=this.endpoint.child(t),o={};o.method="POST",o.body=this.encoder.encode(e??{});const[,c]=await this.executeMiddleware({target:i.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async l=>{const u={...l,params:{}};o.headers={...this.headers,...l.params};let h;try{h=await fetch(l.target,o)}catch(d){if(!(d instanceof Error))throw d;return[u,$f(d)?new He({url:i}):d]}const f=await h.arrayBuffer();if(h?.ok)return r!=null&&(s=this.encoder.decode(f,r)),[u,null];try{if(h.status!==Mf)return[u,new Error(h.statusText)];const d=this.encoder.decode(f,We.payloadZ),O=We.decode(d);return[u,O]}catch(d){return[u,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${d.message}`)]}});if(c!=null)return[null,c];if(s==null)throw new Error("Response must be defined");return[s,null]}};const Pf=(t,e)=>{class n{wrapped;constructor(s){this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,i,o,c){const l=new ef.Breaker(e);do{const[u,h]=await this.wrapped.send(s,i,o,c);if(h==null)return[u,null];if(!He.matches(h))return[null,h];if(console.warn(`[freighter] ${l.retryMessage}`,h),!await l.wait())return[u,h]}while(!0)}}return new n(t)},g=async(t,e,n,r,s)=>{const[i,o]=await t.send(e,n,r,s);if(o!=null)throw o;return i},_f=a.z.object({type:a.z.enum(["data","close","open"]),payload:a.z.unknown(),error:a.z.optional(We.payloadZ)});class Rf{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 We.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ze;if(this.sendClosed)throw new At;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=We.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,_f))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Lf?ze.TYPE:At.TYPE,data:""}})}}const Zf="freighterctx",Lf=1e3;class ar extends jo{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 ar(this.baseUrl,e,this.secure);return n.use(...this.middleware),n}async stream(e,n,r){let s;const[,i]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),l={...o,params:{}};c.binaryType=ar.MESSAGE_TYPE;const u=await this.wrapSocket(c,n,r);return u instanceof Error?[l,u]:(s=u,[l,null])});if(i!=null)throw i;return s}buildURL(e,n){const r=Gd({[$o]:this.encoder.contentType,...n.params},Zf);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,n,r){return await new Promise(s=>{e.onopen=()=>{const i=new Rf(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 Mo=t=>a.union([a.union([a.null(),a.undefined()]).transform(()=>[]),t.array()]),Df=t=>Array.isArray(t)?t:t==null?[]:[t],Uo=(t,e)=>{if(Array.isArray(e))return e.reduce((s,i)=>Uo(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},Bf=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n)):t.filter(n=>n!=e)}),Po=(t,e)=>{if(Array.isArray(e))return e.reduce((s,i)=>Po(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},Ff=((t,e)=>{if(t!=null)return Array.isArray(e)?t.filter(n=>!e.includes(n.key)):t.filter(n=>n.key!==e)}),b=Object.freeze(Object.defineProperty({__proto__:null,nullableZ:Mo,remove:Bf,removeKeyed:Ff,toArray:Df,upsert:Uo,upsertKeyed:Po},Symbol.toStringTag,{value:"Module"})),qf=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)},zr=t=>{const e=(n,r=ws)=>{if(typeof n=="string")return t(n);if(Array.isArray(n))return n.map(o=>e(o,r));if(!Vr(n))return n;r=Wf(r);const s={},i=n;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),r):(Object.keys(i).forEach(o=>{let c=i[o];const l=t(o);r.recursive&&(Vr(c)?ai(c)||(c=e(c,r)):r.recursiveInArray&&si(c)&&(c=[...c].map(u=>{let h=u;return Vr(u)?ai(h)||(h=e(u,r)):si(u)&&(h=e({key:u},r).key),h}))),s[l]=c}),s)};return e},na=zr(qf),Yf=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}_${r.toLowerCase()}`),_o=zr(Yf),Ro=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),Vf=[Number,String,Uint8Array],ws={recursive:!0,recursiveInArray:!0},Wf=(t=ws)=>(t.recursive==null?t=ws:t.recursiveInArray??=!1,t),si=t=>t!=null&&Array.isArray(t),Vr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),ai=t=>Vf.some(e=>t instanceof e),Hf=t=>t.replace(/[\s_]+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,n,r)=>`${n}-${r.toLowerCase()}`).toLowerCase(),Gf=zr(Hf),Kf=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},Jf=zr(Kf),Xf=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:_o,capitalize:Ro,snakeToCamel:na,toKebab:Gf,toProperNoun:Jf},Symbol.toStringTag,{value:"Module"})),Zo=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);let Lo=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=na(n);return e!=null?e.parse(r):r}encodeString(t){const e=_o(t);return JSON.stringify(e,(n,r)=>ArrayBuffer.isView(r)?Array.from(r):typeof r=="bigint"?r.toString():r)}},Do=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||!Zo(t[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(t[0]),n=[e.join(",")];return t.forEach(r=>{const s=e.map(i=>JSON.stringify(r[i]??""));n.push(s.join(","))}),n.join(`
7
- `)}decodeString(t,e){const[n,...r]=t.trim().split(`
8
- `).map(o=>o.trim());if(n.length===0)return e!=null?e.parse({}):{};const s=n.split(",").map(o=>o.trim()),i={};return s.forEach(o=>{i[o]=[]}),r.forEach(o=>{const c=o.split(",").map(l=>l.trim());s.forEach((l,u)=>{const h=this.parseValue(c[u]);h!=null&&i[l].push(h)})}),e!=null?e.parse(i):i}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}},Bo=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 an=new Lo,Qf=new Do,ep=new Bo,tp=[an],dt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Do,CSV_CODEC:Qf,ENCODERS:tp,JSONCodec:Lo,JSON_CODEC:an,TEXT_CODEC:ep,TextCodec:Bo},Symbol.toStringTag,{value:"Module"})),bs=t=>[...new Set(t)],np=(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())},ii=Object.freeze(Object.defineProperty({__proto__:null,by:np,unique:bs},Symbol.toStringTag,{value:"Module"})),ye=t=>t!=null&&typeof t=="object"&&"value"in t;let Pt=class{value;constructor(t){this.value=t}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const rp=t=>t!=null&&typeof t=="object"&&"toString"in t,On=(t,e=!1)=>{const n=rp(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?qo(r):r},sp=(t,e,n)=>{const r=On(e[t],n);return(s,i)=>r(s[t],i[t])},ap=(t,e)=>t.length!==e.length?t.length-e.length:t.every((n,r)=>n===e[r])?0:-1,Fo=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const n=On(t[0]),r=[...t].sort(n),s=[...e].sort(n);return r.every((i,o)=>i===s[o])?0:-1},ip=(t,e)=>{const n=bs(t),r=bs(e);return Fo(n,r)},op=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,qo=t=>(e,n)=>t(n,e),_t=0,er=-1,tr=1,Yo=t=>t<_t,Vo=t=>t>_t,cp=t=>t>=_t,Wo=t=>t===_t,lp=(t,e)=>{const n=/([a-zA-Z]+)|(\d+)/g,r=t.replace(/[\s_.-]+/g,"").match(n),s=e.replace(/[\s_.-]+/g,"").match(n);if(!r||!s)return 0;for(let i=0;i<Math.min(r.length,s.length);i++){const o=r[i],c=s[i];if(isNaN(Number(o))&&isNaN(Number(c))){const l=o.localeCompare(c);if(l!==0)return l}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const l=Number(o)-Number(c);if(l!==0)return l}else return isNaN(Number(o))?-1:1}return r.length-s.length},Tr=a.z.tuple([a.z.number(),a.z.number()]);a.z.tuple([a.z.bigint(),a.z.bigint()]);const Ho=a.z.object({width:a.z.number(),height:a.z.number()}),up=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()}),hp=["width","height"];a.z.enum(hp);const dp=["start","center","end"],fp=["signedWidth","signedHeight"];a.z.enum(fp);const on=a.z.object({x:a.z.number(),y:a.z.number()}),Go=a.z.object({clientX:a.z.number(),clientY:a.z.number()}),Ko=["x","y"],Jo=a.z.enum(Ko),ra=["top","right","bottom","left"],pp=a.z.enum(ra),Xo=["left","right"],sa=a.z.enum(Xo),Qo=["top","bottom"],aa=a.z.enum(Qo),ia=["center"],vs=a.z.enum(ia),yp=[...ra,...ia],oa=a.z.enum(yp);a.z.enum(dp);const mp=["first","last"];a.z.enum(mp);const gp=a.z.object({lower:a.z.number(),upper:a.z.number()}),wp=a.z.object({lower:a.z.bigint(),upper:a.z.bigint()});a.z.union([gp,Tr]);a.z.union([wp,Tr]);a.z.enum([...Jo.options,...oa.options]);a.z.enum(["x","left","right"]);a.z.enum(["y","top","bottom"]);const bp=a.z.union([Jo,oa,a.z.instanceof(String)]),Rt=t=>(e,n)=>{if(typeof e=="bigint"){if(ir(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))},Ve=Rt((t,e)=>t-e),Zt=Rt((t,e)=>t+e),vp=(t,e,n=1e-4)=>Math.abs(t-e)<n,zs=(t,e)=>{const n=typeof t=="bigint",r=typeof e=="bigint";return n&&r?t===e:n&&ir(e)?t===BigInt(e):r&&ir(t)?e===BigInt(t):t===e},zp=t=>{const e=10**Math.floor(Math.log10(t));return Math.round(t/e)*e},ec=Rt((t,e)=>t<=e?t:e),ir=t=>typeof t=="bigint"?!0:Number.isInteger(t),Tp=Rt((t,e)=>t>=e?t:e),tc=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,be=Rt((t,e)=>t*e),Sn=Rt((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?Op(r):r},Op=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,oi=(t,e)=>{const n=K(t);return e<n.lower?n.lower:e>=n.upper?n.upper-(typeof n.upper=="number"?1:1n):e},Fn=(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},nc=t=>{const e=K(t);return e.upper-e.lower},Sp=t=>({lower:Math.min(...t.map(e=>K(e).lower)),upper:Math.max(...t.map(e=>K(e).upper))}),kp=(t,e,n)=>{const r=t.map(c=>K(c)),s=n>0?1:n<0?-1:0;if(s===0)return e;let i=n,o=e;for(;zs(i,0)===!1;){const c=r.findIndex(l=>s>0?o>=l.lower&&o<l.upper:o>l.lower&&o<=l.upper);if(c!==-1){const l=r[c];let u;if(s>0?u=Ve(l.upper,o):u=Ve(o,l.lower),u>0){const h=ec(tc(i),u);if(o=Zt(o,s>0?h:-h),i=Ve(i,s>0?h:-h),zs(i,0))return o;continue}}if(s>0){const l=r.filter(u=>u.lower>o);if(l.length>0)o=l[0].lower;else return o}else{const l=r.filter(u=>u.upper<o);if(l.length>0)o=l[l.length-1].upper;else return o}}return o},Np=(t,e,n)=>{const r=t.map(o=>K(o));if(e===n)return typeof e=="bigint"?0n:0;const s=e<n?K([e,n]):K([n,e]);let i=typeof e=="bigint"?0n:0;for(const o of r){const c=o.lower>s.lower?o.lower:s.lower,l=o.upper<s.upper?o.upper:s.upper;if(c<l){const u=l-c;i=i+u}}return i},Ep=sa,Ap=aa,Ip=vs,xp={top:"bottom",right:"left",bottom:"top",left:"right",center:"center"},Cp={top:"left",right:"top",bottom:"right",left:"bottom",center:"center"},jp=bp,Ge=t=>t instanceof String||!Ko.includes(t)?t:t==="x"?"left":"top",$p=t=>xp[Ge(t)],Mp=t=>Cp[Ge(t)],cn=t=>{const e=Ge(t);return e==="top"||e==="bottom"?"y":"x"},Up=a.z.object({x:sa.or(vs),y:aa.or(vs)}),rc=a.z.object({x:sa,y:aa}),ca=Object.freeze({x:"left",y:"top"}),sc=Object.freeze({x:"right",y:"top"}),ac=Object.freeze({x:"left",y:"bottom"}),ic=Object.freeze({x:"right",y:"bottom"}),la=Object.freeze({x:"center",y:"center"}),oc=Object.freeze({x:"center",y:"top"}),cc=Object.freeze({x:"center",y:"bottom"}),lc=Object.freeze({x:"right",y:"center"}),uc=Object.freeze({x:"left",y:"center"}),Pp=Object.freeze([uc,lc,oc,cc,ca,sc,ac,ic,la]),hc=(t,e)=>t.x===e.x&&t.y===e.y,_p=(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},Rp=t=>[t.x,t.y],nr=t=>cn(Ge(t))==="x",Zp=t=>cn(Ge(t))==="y",Lp=t=>`${t.x}${Ro(t.y)}`,Dp=(t,e)=>{let n,r;if(typeof t=="object"&&"x"in t?(n=t.x,r=t.y):(n=Ge(t),r=Ge(e??t)),cn(n)===cn(r)&&n!=="center"&&r!=="center")throw new Error(`[XYLocation] - encountered two locations with the same direction: ${n.toString()} - ${r.toString()}`);const s={...la};return n==="center"?nr(r)?[s.x,s.y]=[r,n]:[s.x,s.y]=[n,r]:r==="center"?nr(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n]:nr(n)?[s.x,s.y]=[n,r]:[s.x,s.y]=[r,n],s},Bp=Object.freeze(Object.defineProperty({__proto__:null,BOTTOM_CENTER:cc,BOTTOM_LEFT:ac,BOTTOM_RIGHT:ic,CENTER:la,CENTER_LEFT:uc,CENTER_LOCATIONS:ia,CENTER_RIGHT:lc,OUTER_LOCATIONS:ra,TOP_CENTER:oc,TOP_LEFT:ca,TOP_RIGHT:sc,XY_LOCATIONS:Pp,X_LOCATIONS:Xo,Y_LOCATIONS:Qo,center:Ip,construct:Ge,constructXY:Dp,corner:rc,crude:jp,direction:cn,isX:nr,isY:Zp,location:oa,outer:pp,rotate90:Mp,swap:$p,x:Ep,xy:Up,xyCouple:Rp,xyEquals:hc,xyMatches:_p,xyToString:Lp,y:Ap},Symbol.toStringTag,{value:"Module"})),Ts=a.z.union([a.z.number(),on,Tr,Ho,up,Go]),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}},lt=Object.freeze({x:0,y:0}),Fp=Object.freeze({x:1,y:1}),qp=Object.freeze({x:1/0,y:1/0}),Yp=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},Vp=t=>dc(t,lt),ua=(t,e,n)=>{const r=Z(t),s=Z(e,n);return{x:r.x*s.x,y:r.y*s.y}},fc=(t,e)=>{const n=Z(t);return{x:n.x+e,y:n.y}},pc=(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"?fc(t,n):pc(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??lt,...r].reduce((s,i)=>{const o=Z(i);return{x:s.x+o.x,y:s.y+o.y}},lt)},Wp=(t,e,n)=>{const r=Z(t);return e==="x"?{x:n,y:r.y}:{x:r.x,y:n}},Hp=(t,e)=>{const n=Z(t),r=Z(e);return Math.sqrt((n.x-r.x)**2+(n.y-r.y)**2)},Gp=(t,e)=>{const n=Z(t),r=Z(e);return{x:r.x-n.x,y:r.y-n.y}},Kp=t=>{const e=Z(t);return Number.isNaN(e.x)||Number.isNaN(e.y)},Jp=t=>{const e=Z(t);return Number.isFinite(e.x)&&Number.isFinite(e.y)},Xp=t=>{const e=Z(t);return[e.x,e.y]},Qp=t=>{const e=Z(t);return{left:e.x,top:e.y}},ey=(t,e=0)=>{const n=Z(t);return{x:Number(n.x.toFixed(e)),y:Number(n.y.toFixed(e))}},Qt=(t,e)=>{const n=Z(t),r=Z(e);return{x:n.x-r.x,y:n.y-r.y}},en=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}},mc=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}},gc=(...t)=>{const e=t.reduce((n,r)=>yc(n,r),lt);return ua(e,1/t.length)},ty=(t,e)=>{const n=[];for(let r=0;r<t.length;r++){const s=t[r];let i,o,c,l;if(r===0){const u=t[r+1],h=Qt(u,s);o=en(h),c=o,l=e}else if(r===t.length-1){const u=t[r-1],h=Qt(s,u);i=en(h),c=i,l=e}else{const u=t[r-1],h=t[r+1],f=Qt(s,u),d=Qt(h,s);i=en(f),o=en(d);const O=Math.acos((f.x*d.x+f.y*d.y)/(Math.hypot(f.x,f.y)*Math.hypot(d.x,d.y))),C=Math.sin(O/2);C===0?l=e:l=e/C,c=mc(gc(i,o))}n.push(ua(c,l))}return n},ny=t=>{const e=Z(t);return{x:e.y,y:e.x}},ry=t=>{const e=Z(t);return{x:Math.round(e.x),y:Math.round(e.y)}},sy=t=>{const e=Z(t);return{x:1/e.x,y:1/e.y}},ha=Object.freeze(Object.defineProperty({__proto__:null,INFINITY:qp,NAN:Yp,ONE:Fp,ZERO:lt,average:gc,calculateMiters:ty,clientXY:Go,construct:Z,couple:Xp,crudeZ:Ts,css:Qp,distance:Hp,equals:dc,isFinite:Jp,isNan:Kp,isZero:Vp,normal:en,normalize:mc,reciprocal:sy,round:ry,scale:ua,set:Wp,sub:Qt,swap:ny,translate:yc,translateX:fc,translateY:pc,translation:Gp,truncate:ey,xy:on},Symbol.toStringTag,{value:"Module"})),qn=a.z.union([a.z.number(),a.z.string()]);a.z.object({top:qn,left:qn,width:qn,height:qn});a.z.object({left:a.z.number(),top:a.z.number(),right:a.z.number(),bottom:a.z.number()});a.z.object({one:on,two:on,root:rc});const da=(t,e,n=0,r=0,s)=>{const i={one:{...lt},two:{...lt},root:s??ca};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))},Wr=t=>{const e=da(t);return{lower:e.one.x,upper:e.two.x}},Hr=t=>{const e=da(t);return{lower:e.one.y,upper:e.two.y}},ay=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,iy=a.z.object({signedWidth:a.z.number(),signedHeight:a.z.number()});a.z.union([Ho,iy,on,Tr]);const oy=(t,e,n)=>e!==void 0&&t<e?e:n!==void 0&&t>n?n:t;a.z.object({offset:Ts,scale:Ts});a.z.object({offset:a.z.number(),scale:a.z.number()});const cy=t=>(e,n,r,s)=>n==="dimension"?[e,r]:[e,s?r-t:r+t],ly=t=>(e,n,r,s)=>[e,s?r/t:r*t],uy=t=>(e,n,r)=>{if(e===null)return[t,r];const{lower:s,upper:i}=e,{lower:o,upper:c}=t,l=i-s,u=c-o;if(n==="dimension")return[t,r*(u/l)];const h=(r-s)*(u/l)+o;return[t,h]},hy=t=>(e,n,r)=>[t,r],dy=()=>(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)]},fy=t=>(e,n,r)=>{const{lower:s,upper:i}=t;return r=oy(r,s,i),[e,r]};let ci=class bt{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new bt().translate(e)}static magnify(e){return new bt().magnify(e)}static scale(e,n){return new bt().scale(e,n)}translate(e){const n=this.new(),r=cy(e);return r.type="translate",n.ops.push(r),n}magnify(e){const n=this.new(),r=ly(e);return r.type="magnify",n.ops.push(r),n}scale(e,n){const r=K(e,n),s=this.new(),i=uy(r);return i.type="scale",s.ops.push(i),s}clamp(e,n){const r=K(e,n),s=this.new(),i=fy(r);return i.type="clamp",s.ops.push(i),s}reBound(e,n){const r=K(e,n),s=this.new(),i=hy(r);return i.type="re-bound",s.ops.push(i),s}invert(){const e=dy();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 bt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,n){return this.currBounds=null,this.ops.reduce(([r,s],i)=>i(r,e,s,this.reversed),[null,n])[1]}reverse(){const e=this.new();e.ops.reverse();const n=[];return e.ops.forEach((r,s)=>{if(r.type==="scale"||n.some(([o,c])=>s>=o&&s<=c))return;const i=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);i!==-1&&n.push([s,i])}),n.forEach(([r,s])=>{const i=e.ops.slice(r,s);i.unshift(e.ops[s]),e.ops.splice(r,s-r+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new bt};(class Ee{x;y;currRoot;constructor(e=new ci,n=new ci,r=null){this.x=e,this.y=n,this.currRoot=r}static translate(e,n){return new Ee().translate(e,n)}static translateX(e){return new Ee().translateX(e)}static translateY(e){return new Ee().translateY(e)}static clamp(e){return new Ee().clamp(e)}static magnify(e){return new Ee().magnify(e)}static scale(e){return new Ee().scale(e)}static reBound(e){return new Ee().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(ay(e)){const r=this.currRoot;return n.currRoot=e.root,r!=null&&!hc(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(Wr(e)),n.y=n.y.scale(Hr(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(Wr(e)),n.y=this.y.reBound(Hr(e)),n}clamp(e){const n=this.copy();return n.x=this.x.clamp(Wr(e)),n.y=this.y.clamp(Hr(e)),n}copy(){const e=new Ee;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 da(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 Ee});let wc=(t,e=21)=>(n=e)=>{let r="",s=n|0;for(;s--;)r+=t[Math.random()*t.length|0];return r};const bc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",py=`0123456789${bc}`,vc=11,yy=wc(bc,1),my=wc(py,vc-1),fa=()=>`${yy()}${my()}`,gy=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:vc,create:fa},Symbol.toStringTag,{value:"Module"})),wy=(t,e)=>n=>n instanceof e||typeof n=="object"&&n!==null&&"discriminator"in n&&n.discriminator===t,by=a.z.enum(["static","dynamic"]),vy=2**8-1,zy=2**16-1,Ty=2**32-1,Oy=2n**64n-1n,Sy=2**64-1,ky=-128,Ny=2**7-1,Ey=-32768,Ay=2**15-1,Iy=-2147483648,xy=2**31-1,Cy=-(2n**63n),or=2n**63n-1n,jy=-9223372036854776e3,zc=2**63-1,li=365,Yn=30,$y=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)])]),Tc=(t,e)=>{const n=new x(e);if(![E.DAY,E.HOUR,E.MINUTE,E.SECOND,E.MILLISECOND,E.MICROSECOND,E.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 x?new x(r):new E(r)};let x=class T extends Pt{constructor(e,n="UTC"){if(e==null)super(T.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*T.MILLISECOND.valueOf());else if(typeof e=="string")super(T.parseDateTimeString(e,n).valueOf());else if(Array.isArray(e))super(T.parseDate(e));else{let r=0n;e instanceof Number&&(e=e.valueOf()),n==="local"&&(r=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e===zc?e=or:e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.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 T(BigInt(s.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,n="UTC"){const[r,s,i]=e.split(":");let o="00",c="00";i!=null&&([o,c]=i.split("."));let l=T.hours(parseInt(r??"00")).add(T.minutes(parseInt(s??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(c??"00")));return n==="local"&&(l=l.add(T.utcOffset)),l.valueOf()}static parseDateTimeString(e,n="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,n);const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new T(BigInt(r.getTime())*T.MILLISECOND.valueOf(),n).valueOf()}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.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 E(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new B(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(Zt(this.valueOf(),new E(e).valueOf()))}sub(e){return new T(Ve(this.valueOf(),new E(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(T.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const n=this.date();return n.setUTCFullYear(e),new T(n)}get month(){return this.date().getUTCMonth()}setMonth(e){const n=this.date();return n.setUTCMonth(e),new T(n)}get day(){return this.date().getUTCDate()}setDay(e){const n=this.date();return n.setUTCDate(e),new T(n)}get hour(){return this.date().getUTCHours()}get localHour(){return this.date().getHours()}setLocalHour(e){const n=this.date();return n.setHours(e),new T(n)}setHour(e){const n=this.date();return n.setUTCHours(e),new T(n)}get minute(){return this.date().getUTCMinutes()}setMinute(e){const n=this.date();return n.setUTCMinutes(e),new T(n)}get second(){return this.date().getUTCSeconds()}setSecond(e){const n=this.date();return n.setUTCSeconds(e),new T(n)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const n=this.date();return n.setUTCMilliseconds(e),new T(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 Tc(this,e)}get isToday(){return this.truncate(E.DAY).equals(T.now().truncate(E.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let n=T.MIN;for(const r of e){const s=new T(r);s.after(n)&&(n=s)}return n}static min(...e){let n=T.MAX;for(const r of e){const s=new T(r);s.before(n)&&(n=s)}return n}static nanoseconds(e,n="UTC"){return new T(e,n)}static NANOSECOND=T.nanoseconds(1);static microseconds(e,n="UTC"){return T.nanoseconds(e*1e3,n)}static MICROSECOND=T.microseconds(1);static milliseconds(e,n="UTC"){return T.microseconds(e*1e3,n)}static MILLISECOND=T.milliseconds(1);static seconds(e,n="UTC"){return T.milliseconds(e*1e3,n)}static SECOND=T.seconds(1);static minutes(e,n="UTC"){return T.seconds(e*60,n)}static MINUTE=T.minutes(1);static hours(e,n="UTC"){return T.minutes(e*60,n)}static HOUR=T.hours(1);static days(e,n="UTC"){return T.hours(e*24,n)}static DAY=T.days(1);static MAX=new T(or);static MIN=new T(0);static ZERO=new T(0);static z=a.z.union([a.z.instanceof(T),a.z.object({value:a.z.bigint()}).transform(e=>new T(e.value)),a.z.string().transform(e=>new T(BigInt(e))),a.z.number().transform(e=>new T(e)),a.z.bigint().transform(e=>new T(e)),a.z.date().transform(e=>new T(e)),a.z.custom(e=>e instanceof E).transform(e=>new T(e)),$y.transform(e=>new T(e))]);static sort(e,n){return Number(e.valueOf()-n.valueOf())}},E=class k extends Pt{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 Gr?e.period:e instanceof x?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 Gr?e.period:e instanceof x?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 Tc(this,e)}truncate(e){return new k(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(e="full"){if(e==="semantic")return this.toSemanticString();const n=this.truncate(k.DAY),r=this.truncate(k.HOUR),s=this.truncate(k.MINUTE),i=this.truncate(k.SECOND),o=this.truncate(k.MILLISECOND),c=this.truncate(k.MICROSECOND),l=this.truncate(k.NANOSECOND),u=n,h=r.sub(n),f=s.sub(r),d=i.sub(s),O=o.sub(i),C=c.sub(o),j=l.sub(c);let w="";return u.isZero||(w+=`${u.days}d `),h.isZero||(w+=`${h.hours}h `),f.isZero||(w+=`${f.minutes}m `),d.isZero||(w+=`${d.seconds}s `),O.isZero||(w+=`${O.milliseconds}ms `),C.isZero||(w+=`${C.microseconds}µs `),j.isZero||(w+=`${j.nanoseconds}ns`),w.trim()}toSemanticString(){const e=this.valueOf()<0n?-this.valueOf():this.valueOf(),n=new k(e),r=this.valueOf()<0n;if(n.valueOf()===0n)return"0s";if(n.lessThan(k.SECOND))return"< 1s";const s=n.days,i=n.hours,o=n.minutes,c=n.seconds,l=Math.floor(s/li),u=Math.floor(s/Yn),h=Math.floor(s/7),f=Math.floor(s),d=Math.floor(i),O=Math.floor(o),C=Math.floor(c),j=r?"-":"";if(l>=1){let w=`${l}y`;if(l<2){const v=Math.floor(s%li/Yn);v>0&&(w+=` ${v}mo`)}return j+w}if(h>=1&&s<Yn&&s%7===0){let w=`${h}w`;const v=Math.floor(s%7),I=Math.floor(i-h*7*24);return h<2&&(v>0?w+=` ${v}d`:I>0&&I<24&&(w+=` ${I}h`)),j+w}if(u>=1){let w=`${u}mo`;if(u<3){const v=Math.floor(s%Yn);v>0&&(w+=` ${v}d`)}return j+w}if(h>=1){let w=`${h}w`;const v=Math.floor(s%7),I=Math.floor(i-h*7*24);return h<2&&(v>0?w+=` ${v}d`:I>0&&I<24&&(w+=` ${I}h`)),j+w}if(f>=1){let w=`${f}d`;const v=Math.floor(i-f*24);return f<2&&v>0&&(w+=` ${v}h`),j+w}if(d>=1){let w=`${d}h`;if(d<3){const v=Math.floor(o-d*60);v>0&&(w+=` ${v}m`)}return j+w}if(O>=1){let w=`${O}m`;if(O<5){const v=Math.floor(c-O*60);v>0&&(w+=` ${v}s`)}return j+w}return`${j}${C}s`}mult(e){return new k(be(this.valueOf(),e))}div(e){return new k(Sn(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(be(e,1e3))}static MICROSECOND=k.microseconds(1);static milliseconds(e=1){return k.microseconds(be(e,1e3))}static MILLISECOND=k.milliseconds(1);static seconds(e=1){return k.milliseconds(be(e,1e3))}static SECOND=k.seconds(1);static minutes(e=1){return k.seconds(be(e,60))}static MINUTE=k.minutes(1);static hours(e){return k.minutes(be(e,60))}static HOUR=k.hours(1);static days(e){return k.hours(be(e,24))}static DAY=k.days(1);static MAX=new k(or);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(x).transform(e=>new k(e)),a.z.custom(e=>e instanceof Gr).transform(e=>new k(e))])},Gr=class de extends Pt{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 E.seconds(1/this.valueOf())}sampleCount(e){return new E(e).seconds*this.valueOf()}byteCount(e,n){return this.sampleCount(e)*new ne(n).valueOf()}span(e){return E.seconds(e/this.valueOf())}byteSpan(e,n){return this.span(e.valueOf()/new ne(n).valueOf())}add(e){return new de(Zt(this.valueOf(),new de(e).valueOf()))}sub(e){return new de(Ve(this.valueOf(),new de(e).valueOf()))}mult(e){return new de(be(this.valueOf(),e))}div(e){return new de(Sn(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)])},ne=class ae extends Pt{constructor(e){ye(e)&&(e=e.value),super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new It(e*this.valueOf())}add(e){return new ae(Zt(this.valueOf(),new ae(e).valueOf()))}sub(e){return new ae(Ve(this.valueOf(),new ae(e).valueOf()))}mult(e){return new ae(be(this.valueOf(),e))}div(e){return new ae(Sn(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)])},B=class Ae{start;end;constructor(e,n){typeof e=="object"&&"start"in e?(this.start=new x(e.start),this.end=new x(e.end)):(this.start=new x(e),this.end=new x(n))}get span(){return new E(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 Ae(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,n=E.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=E.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=x.max(r.start,e.start),i=x.min(r.end,e.end);return i.before(s)?!1:new E(i.sub(s)).greaterThanOrEqual(n)}contains(e){return e instanceof Ae?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const n=new Ae(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 Ae(x.min(...e.map(n=>n.start)),x.max(...e.map(n=>n.end)))}static MAX=new Ae(x.MIN,x.MAX);static ZERO=new Ae(x.ZERO,x.ZERO);static z=a.z.union([a.z.object({start:x.z,end:x.z}).transform(e=>new Ae(e.start,e.end)),a.z.instanceof(Ae)]);static sort(e,n){return x.sort(e.start,n.start)||x.sort(e.end,n.end)}static simplify(e){return e.map(n=>n.makeValid()).sort((n,r)=>Ae.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=x.max(s.end,r.end):n.push(r),n},[])}},P=class m extends Pt{constructor(e){if(ye(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)])},It=class M extends Pt{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 M(Zt(this.valueOf(),e.valueOf()))}sub(e){return ye(e)&&(e=e.value),new M(Ve(this.valueOf(),e.valueOf()))}mult(e){return new M(be(this.valueOf(),e))}div(e){return new M(Sn(this.valueOf(),e))}truncate(e){return new M(Math.trunc(this.valueOf()/new M(e).valueOf())*new M(e).valueOf())}remainder(e){return M.bytes(this.valueOf()%new M(e).valueOf())}get gigabytes(){return this.valueOf()/M.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/M.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/M.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/M.TERABYTE.valueOf()}toString(){const e=this.truncate(M.TERABYTE),n=this.truncate(M.GIGABYTE),r=this.truncate(M.MEGABYTE),s=this.truncate(M.KILOBYTE),i=this.truncate(M.BYTE),o=e,c=n.sub(e),l=r.sub(n),u=s.sub(r),h=i.sub(s);let f="";return o.isZero||(f+=`${o.terabytes}TB `),c.isZero||(f+=`${c.gigabytes}GB `),l.isZero||(f+=`${l.megabytes}MB `),u.isZero||(f+=`${u.kilobytes}KB `),(!h.isZero||f==="")&&(f+=`${h.valueOf()}B`),f.trim()}static bytes(e=1){return new M(e)}static BYTE=new M(1);static kilobytes(e=1){return M.bytes(new M(e).valueOf()*1e3)}static KILOBYTE=M.kilobytes(1);static megabytes(e=1){return M.kilobytes(new M(e).valueOf()*1e3)}static MEGABYTE=M.megabytes(1);static gigabytes(e=1){return M.megabytes(new M(e).valueOf()*1e3)}static GIGABYTE=M.gigabytes(1);static terabytes(e){return M.gigabytes(new M(e).valueOf()*1e3)}static TERABYTE=M.terabytes(1);static ZERO=new M(0);static z=a.z.union([a.z.number().transform(e=>new M(e)),a.z.instanceof(M)]);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 Oc=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof x||t instanceof E||t instanceof Date},My=(t,e,n,r=0)=>t.usesBigInt&&!e.usesBigInt?Number(n)-Number(r):!t.usesBigInt&&e.usesBigInt?BigInt(n.valueOf())-BigInt(r.valueOf()):rr(n,-r),rr=(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),Uy=/^(?:[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 Py(t){return typeof t=="string"&&Uy.test(t)}const X=[];for(let t=0;t<256;++t)X.push((t+256).toString(16).slice(1));function _y(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 Ry(t,e=0){const n=_y(t,e);if(!Py(n))throw TypeError("Stringified UUID is invalid");return n}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Sc=(t,e)=>Ry(t,e),Re=-1,Os={[Symbol.iterator]:()=>Os,next:()=>({done:!0,value:void 0})},Zy=a.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Ly=a.z.union([a.z.null(),a.z.undefined()]).transform(()=>new Uint8Array().buffer),Ss=10,kc=(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`)},Nc="sy_x_telem_series";let qe=class Fe{key;discriminator=Nc;dataType;sampleOffset;gl;_data;timeRange=B.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Re;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=a.z.object({timeRange:B.z.optional(),dataType:P.z,alignment:a.z.coerce.bigint().optional(),data:a.z.union([Zy,Ly,a.z.instanceof(ArrayBuffer),a.z.instanceof(Uint8Array)]),glBufferUsage:by.optional().default("static").optional()});static z=Fe.crudeZ.transform(e=>new Fe(e));constructor(e){Dy(e)&&(e={data:e}),e.data??=[];const{dataType:n,timeRange:r,sampleOffset:s=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:c=1n,key:l=fa(),data:u}=e;if(Ec(u)){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this.timeRange=d.timeRange,this.alignment=d.alignment,this.alignmentMultiple=d.alignmentMultiple,this.cachedMin=d.cachedMin,this.cachedMax=d.cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this.cachedLength=d.cachedLength;return}const h=Oc(u),f=Array.isArray(u);if(n!=null)this.dataType=new P(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(f||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=P.STRING;else if(typeof d=="number")this.dataType=P.FLOAT64;else if(typeof d=="bigint")this.dataType=P.INT64;else if(typeof d=="boolean")this.dataType=P.BOOLEAN;else if(d instanceof x||d instanceof Date||d instanceof x)this.dataType=P.TIMESTAMP;else if(typeof d=="object")this.dataType=P.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new P(u)}if(!f&&!h)this._data=u;else if(f&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[u]:u;const O=d[0];(O instanceof x||O instanceof Date||O instanceof E)&&(d=d.map(C=>new x(C).valueOf())),this.dataType.equals(P.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
9
- `)}
10
- `).buffer):this.dataType.equals(P.JSON)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(C=>an.encodeString(C)).join(`
11
- `)}
12
- `).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(d.map(C=>BigInt(Math.round(C)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(d.map(Number)).buffer:this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=s??0,this.timeRange=r??B.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 P(n).Array(e),i=new Fe({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===Re)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===Re)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===Re?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(P.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(n=>e.parse(an.decodeString(n)))}get byteCapacity(){return new It(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Re?this.byteCapacity:this.dataType.isVariable?new It(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Re?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===Ss&&(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]=My(this.dataType,e,this.data[s],n);return new Fe({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(P.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(),rr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(P.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((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(),rr(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(P.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 rr(r,this.sampleOffset)}atUUID(e,n){e<0&&(e=this.length+e);const r=Sc(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]===Ss){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(P.STRING)?new TextDecoder().decode(i):na(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let n=0,r=this.length-1;const s=On(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(P.FLOAT32)&&!this.dataType.equals(P.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!==Re){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=Re}as(e){return kc(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:hi(this.alignmentBounds.lower),upper:hi(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 By(this);return this.dataType.equals(P.JSON)?new Fy(e):e}return this.dataType.equals(P.UUID)?new qy(this):new Yy(this)}slice(e,n){return this.sliceSub(!1,e,n)}sub(e,n){return this.sliceSub(!0,e,n)}subIterator(e,n){return new ui(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 ui(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 Fe({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 Fe({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(n)})}reAlign(e){return new Fe({data:this.buffer,dataType:this.dataType,timeRange:B.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 Dy=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof qe?!0:Oc(t),Ec=wy(Nc,qe);let ui=class{series;end;index;constructor(t,e,n){this.series=t;const r=K(0,t.length+1);this.end=oi(r,n),this.index=oi(r,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},By=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]!==Ss;)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))})}},Fy=class Ac{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:an.decodeString(e.value,Ac.schema)}}};class qy{series;index;data;density;constructor(e){if(!e.dataType.equals(P.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=P.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Sc(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Yy=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 Vy{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 kc(e,this.dataType),this}get dataType(){return this.series.length===0?P.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?B.ZERO:new B(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(Ec(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(Fn(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 Kr(this,e,n??this.length)}subAlignmentIterator(e,n){if(e>=this.alignmentBounds.upper||n<=this.alignmentBounds.lower)return Os;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(Fn(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(Fn(o.alignmentBounds,n)){s+=Math.ceil(Number(n-o.alignment)/Number(o.alignmentMultiple));break}}return new Kr(this,r,s)}subAlignmentSpanIterator(e,n){if(e>=this.alignmentBounds.upper)return Os;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(Fn(i.alignmentBounds,e)){r+=Number(e-i.alignment);break}}return new Kr(this,r,r+n)}updateGLBuffer(e){this.series.forEach(n=>n.updateGLBuffer(e))}get bounds(){return Sp(this.series.map(e=>e.bounds))}get byteLength(){return new It(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 kp(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 Np(r,e,n)}parseJSON(e){if(!this.dataType.equals(P.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 Wy(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}let Wy=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}},Kr=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 hi=t=>{const e=t>>32n,n=t&0xffffffffn;return{domain:e,sample:n}},Ic=(t,e,n)=>{let r=0,s=t.length;const i=n??On(e);for(;r<s;){const o=Math.floor((r+s)/2),c=i(t[o],e);if(c===0)return o;c<0?r=o+1:s=o}return r},Hy=(t,e,n)=>{const r=Ic(t,e,n);t.splice(r,0,e)},di=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:_t,GREATER_THAN:tr,LESS_THAN:er,insert:Hy,isEqualTo:Wo,isGreaterThan:Vo,isGreaterThanEqual:cp,isLessThan:Yo,newF:On,newFieldF:sp,order:op,primitiveArrays:ap,reverseF:qo,search:Ic,stringsWithNumbers:lp,uniqueUnorderedPrimitiveArrays:ip,unorderedPrimitiveArrays:Fo},Symbol.toStringTag,{value:"Module"})),Gy=(t,e)=>{let n=null;return e===0?t:(...r)=>{n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>t(...r),e)}},Ky=(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)},Jy=(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)},Xy=((t,e,n={optional:!1})=>{const{optional:r,getter:s=Jy}=n;if(e==="")return t;const i=e.split(".");if(i.length===1){const c=s(t,i[0]);if(c===void 0){if(r)return null;throw new Error(`Path ${e} does not exist. ${i[0]} is undefined`)}return c}const o=(c,l)=>{if(l>=i.length)return c;for(let u=i.length-l;u>=1;u--){const h=i.slice(l,l+u).join("."),f=s(c,h);if(f!==void 0){if(l+u===i.length)return f;if(f===null){if(r)return null;throw new Error(`Path ${e} does not exist. ${h} is null`)}return o(f,l+u)}}if(r)return null;throw new Error(`Path ${e} does not exist. ${i[l]} is undefined`)};return o(t,0)});a.z.object({key:a.z.string(),value:a.z.string()});let Qy=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?.()}},em=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 tm=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:em,Observer:Qy},Symbol.toStringTag,{value:"Module"})),nm=a.z.record(a.z.union([a.z.number(),a.z.string(),a.z.symbol()]),a.z.unknown()),pa=t=>Object.entries(t),rm=(t,e)=>Object.fromEntries(pa(t).map(([n,r])=>[n,e(r,n)])),sm=t=>Object.fromEntries(pa(t).filter(([e,n])=>n!==void 0)),am=(t,...e)=>{const n={...t};for(const r of e)delete n[r];return n},Te=Object.freeze(Object.defineProperty({__proto__:null,entries:pa,map:rm,omit:am,purgeUndefined:sm,unknownZ:nm},Symbol.toStringTag,{value:"Module"})),im=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";im();const om=["macOS","Windows","Linux"],cm=["macos","windows","linux"],lm={macos:"macOS",windows:"Windows",linux:"Linux"};a.z.enum(om).or(a.z.enum(cm).transform(t=>lm[t]));const um=(...t)=>t.map(xc).join(""),xc=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),hm=t=>t.endsWith("/")?t.slice(0,-1):t;class rn{protocol;host;port;path;constructor({host:e,port:n,protocol:r="",pathPrefix:s=""}){this.protocol=r,this.host=e,this.port=n,this.path=xc(s)}replace(e){return new rn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new rn({...this,pathPrefix:um(this.path,e)})}toString(){return hm(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new rn({host:"unknown",port:0})}const dm=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),fm=t=>a.array(t).or(t.transform(e=>[e])),Cc=t=>Ky(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"]}),fi=(t,e)=>{if(t==null)return null;const n=t[e];return n==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:n},pm=((t,e,n)=>e===""?t:Xy(fi(t,"shape"),Cc(e),{...n,getter:fi})),sn=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:pm,getFieldSchemaPath:Cc,nullToUndefined:dm,toArray:fm},Symbol.toStringTag,{value:"Module"})),ks=2,Ns=3,jc=2,ym=(t,e)=>{if(Number.isNaN(t)||!Number.isFinite(t))return t;const n=nc(e);if(n==0)return t;let r;n>=1e3?r=ks:n>=1?r=Ns:r=Math.ceil(-Math.log10(n))+jc;const s=10**r;return Math.round(t*s)/s},mm=5,gm=1e-10,wm=(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=nc(e);const c=s/n;r=s>0&&c>gm}if(r){let c;s>=1e3?c=ks:s>=1?c=Ns:c=Math.ceil(-Math.log10(s))+jc;const l=10**c;return Math.round(t*l)/l}if(n>=1e3){const c=10**ks;return Math.round(t*c)/c}if(n>=1){const c=10**Ns;return Math.round(t*c)/c}const i=Math.floor(Math.log10(n)),o=10**(mm-i-1);return Math.round(t*o)/o},Es=Object.freeze(Object.defineProperty({__proto__:null,MAX_INT16:Ay,MAX_INT32:xy,MAX_INT64:or,MAX_INT64_NUMBER:zc,MAX_INT8:Ny,MAX_UINT16:zy,MAX_UINT32:Ty,MAX_UINT64:Oy,MAX_UINT64_NUMBER:Sy,MAX_UINT8:vy,MIN_INT16:Ey,MIN_INT32:Iy,MIN_INT64:Cy,MIN_INT64_NUMBER:jy,MIN_INT8:ky,abs:tc,add:Zt,closeTo:vp,div:Sn,equal:zs,isInteger:ir,max:Tp,min:ec,mult:be,roundBySpan:ym,roundToNearestMagnitude:zp,smartRound:wm,sub:Ve},Symbol.toStringTag,{value:"Module"})),bm=async t=>await new Promise(e=>setTimeout(e,E.fromMilliseconds(t).milliseconds));class vm{config;retries;interval;constructor(e){this.config={baseInterval:new E(e?.baseInterval??E.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??bm},this.retries=0,this.interval=new E(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 zm=a.z.object({baseInterval:E.z.optional(),maxRetries:a.z.number().optional(),scale:a.z.number().optional()}),$c=Object.freeze(Object.defineProperty({__proto__:null,Breaker:vm,breakerConfigZ:zm},Symbol.toStringTag,{value:"Module"})),Tm=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Mc=a.z.string().regex(Tm),Nt=a.z.number().min(0).max(255),Uc=a.z.number().min(0).max(1),Pc=a.z.tuple([Nt,Nt,Nt,Uc]),Om=a.z.tuple([Nt,Nt,Nt]),Sm=a.z.object({rgba255:Pc}),km=a.z.number().min(0).max(360),Nm=a.z.number().min(0).max(100),Em=a.z.number().min(0).max(100),Am=a.z.tuple([km,Nm,Em,Uc]),ya=a.z.union([Mc,Om,Pc,Am,Sm]),Im=ya.transform(t=>ma(t)),ma=(t,e=1)=>{if(t=ya.parse(t),typeof t=="string")return xm(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},xm=(t,e=1)=>(t=Mc.parse(t),t=Cm(t),[Vn(t,0),Vn(t,2),Vn(t,4),t.length===8?Vn(t,6)/255:e]),Vn=(t,e)=>parseInt(t.slice(e,e+2),16),Cm=t=>t.startsWith("#")?t.slice(1):t;ma("#000000");ma("#ffffff");const jm=a.z.object({key:a.z.string(),color:ya,position:a.z.number(),switched:a.z.boolean().optional()});a.z.array(jm);const $m=a.z.object({key:a.z.string(),name:a.z.string(),color:Im});a.z.object({key:a.z.string(),name:a.z.string(),swatches:a.z.array($m)});const _c=a.z.int().min(0).max(255),Rc=255,Zc=0,Mm={lower:Zc,upper:Rc+1},Lc=a.z.object({name:a.z.string(),key:a.z.string()}),ln=t=>a.z.object({subject:Lc,resource:t,authority:_c}),Um=(...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}),Dc=t=>a.z.object({from:ln(t),to:a.z.null()}),Bc=t=>a.z.object({from:a.z.null(),to:ln(t)}),Pm=t=>a.z.union([Dc(t),Bc(t),a.z.object({from:ln(t),to:ln(t)})]),me=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Rc,AUTHORITY_BOUNDS:Mm,ZERO_AUTHORITY:Zc,acquireZ:Bc,authorityZ:_c,filterTransfersByChannelKey:Um,releaseZ:Dc,stateZ:ln,subjectZ:Lc,transferZ:Pm},Symbol.toStringTag,{value:"Module"})),_m=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Rm=(t,e)=>{const n=Symbol.for(t);if(!_m(n)){const r=e();Object.defineProperty(globalThis,n,{value:r})}return()=>globalThis[n]},Fc="sy_x_error",Zm=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),kn=t=>class tn extends Error{static discriminator=Fc;discriminator=tn.discriminator;static TYPE=t;type=tn.TYPE;static matches=Zm(t);matches=tn.matches;constructor(n,r){super(n,r),this.name=tn.TYPE}static sub(n){return kn(`${t}.${n}`)}},qc=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Fc)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},vt="unknown",As="nil";class Lm{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:As,data:""};if(qc(e))for(const n of this.providers){const r=n.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:vt,data:e.message};if(typeof e=="string")return{type:vt,data:e};try{return{type:vt,data:JSON.stringify(e)}}catch{return{type:vt,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===As)return null;if(e.type===vt)return new Is(e.data);for(const n of this.providers){const r=n.decode(e);if(r!=null)return r}return new Is(e.data)}}const ga=Rm("synnax-error-registry",()=>new Lm),Dm=({encode:t,decode:e})=>ga().register({encode:t,decode:e}),Bm=t=>ga().encode(t),Fm=t=>t==null?null:ga().decode(t);class Is extends kn("unknown"){}const qm=a.z.object({type:a.z.string(),data:a.z.string()});class Ym extends kn("canceled"){}class Vm extends kn("not_implemented"){}const Ue=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Ym,NONE:As,NotImplemented:Vm,UNKNOWN:vt,Unknown:Is,createTyped:kn,decode:Fm,encode:Bm,isTyped:qc,payloadZ:qm,register:Dm},Symbol.toStringTag,{value:"Module"})),Wm=a.object({jsonrpc:a.literal("2.0"),method:a.string(),params:a.any().optional(),id:a.union([a.string(),a.number(),a.null()]).optional()}),Yc=a.object({jsonrpc:a.literal("2.0"),id:a.union([a.string(),a.number(),a.null()])}),Hm=Yc.extend({result:a.json()}),Gm=Yc.extend({error:a.object({code:a.number().int(),message:a.string().optional(),data:a.json().optional()})}),Km=a.union([Hm,Gm]);a.union([Wm,Km]);const Vc=a.uuid(),Wc=a.object({key:Vc,name:a.string().min(1),color:a.string()}),Hc=Object.freeze(Object.defineProperty({__proto__:null,keyZ:Vc,labelZ:Wc},Symbol.toStringTag,{value:"Module"})),xs=a.z.string().regex(/^\d+\.\d+\.\d+$/),Nn=((t,e,n={})=>{n.checkMajor??=!0,n.checkMinor??=!0,n.checkPatch??=!0;const r=xs.parse(t),s=xs.parse(e),[i,o,c]=r.split(".").map(Number),[l,u,h]=s.split(".").map(Number);if(n.checkMajor){if(i<l)return er;if(i>l)return tr}if(n.checkMinor){if(o<u)return er;if(o>u)return tr}if(n.checkPatch){if(c<h)return er;if(c>h)return tr}return _t}),Jm=(t,e,n={})=>Wo(Nn(t,e,n)),Gc=(t,e,n={})=>Vo(Nn(t,e,n)),Xm=(t,e,n={})=>Yo(Nn(t,e,n)),Qm=({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}},eg=({name:t,migrations:e,targetSchema:n,defaultVersion:r,def:s})=>{const i=Object.keys(e).sort(Nn).pop();if(i==null)return u=>{if(u.version??=r,u.version!==s.version)return console.log(`${t} version ${u.version} is newer than latest version of ${s.version}.
14
- Returning default instead.
15
- `),s;try{return n!=null?n.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),s}};const o=Object.keys(e).length;let c=!1;const l=u=>{try{if(o===0||Gc(u.version,i))return console.log(c?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${s.version}`),u;const h=u.version,f=e[h],d=f(u);return c=!0,l(d)}catch(h){return console.log(`${t} failed to migrate from ${u.version} to ${i}`),console.error(h),s}};return u=>{try{if(u.version==null)if(r!=null)console.log(`${t} version is null. Setting version to default of ${r}`),u.version=r;else return console.log(`${t} version is null and no default version set. Exiting with default`),s;return l(u)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),s}}},pi=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Nn,createMigration:Qm,migrator:eg,semVerNewer:Gc,semVerOlder:Xm,semVerZ:xs,versionsEqual:Jm},Symbol.toStringTag,{value:"Module"})),tg=["standard","scientific","engineering"];a.z.enum(tg);const Kc=a.z.enum(["success","info","warning","error","loading","disabled"]),ng=t=>a.z.object({key:a.z.string(),name:a.z.string().default(""),variant:Kc,message:a.z.string(),description:a.z.string().optional(),time:x.z,labels:Mo(Wc).optional(),details:t??a.z.unknown().optional()}),rg=a.z.object({stack:a.z.string(),error:a.z.instanceof(Error)}),sg=(t,e)=>{if(!(t instanceof Error))throw t;return Jc({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??"",error:t}})},Jc=t=>({key:fa(),time:x.now(),name:"",...t}),ag=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0},ig=(t,e=[])=>{if(t!=null)return Array.isArray(e)?e.includes(t)?void 0:t:e===t?void 0:t},Lt=Object.freeze(Object.defineProperty({__proto__:null,create:Jc,exceptionDetailsSchema:rg,fromException:sg,keepVariants:ag,removeVariants:ig,statusZ:ng,variantZ:Kc},Symbol.toStringTag,{value:"Module"})),og=(t,e)=>{if(!e.has(t))return t;let n=t,r=1,s=t;for(;e.has(s);){const i=s.match(cg);i?(n=s.slice(0,i.index).trim(),r=parseInt(i[1])+1):(n=s,r=1),s=`${n} (${r})`}return s},cg=/\((\d+)\)$/,lg=(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]}`},ug=t=>{const e=t.split(" "),n=new Set,r=e.map(o=>o.charAt(0).toLowerCase()).join("");n.add(r.replace(/-/g,"_")),n.add(r.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;t.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const l=e.map((u,h)=>h!==c?u.charAt(0).toLowerCase():u).join("");n.add(l.replace(/-/g,"_")),n.add(l.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const i=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return n.add(i.join("").replace(/-/g,"_")),n.add(i.join("_").replace(/-/g,"_")),Array.from(n).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},hg=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Cs=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:ug,deduplicateFileName:og,naturalLanguageJoin:lg,trimPrefix:hg},Symbol.toStringTag,{value:"Module"})),dg="all",fg="create",pg="delete",yg="retrieve",mg="update",js=a.z.enum([dg,fg,pg,yg,mg]);class Ce extends Ue.createTyped("sy"){}let V=class extends Ce.sub("validation"){};class un extends V.sub("path"){path;error;static encodedSchema=a.z.object({path:a.z.string().array(),error:Ue.payloadZ});constructor(e,n){const r=b.toArray(e);super(`${r.join(".")}: ${n.message}`),this.path=r.flatMap(s=>s.split(".")),this.error=n}static decode(e){const n=un.encodedSchema.parse(JSON.parse(e.data));return new un(n.path,Ue.decode(n.error))}}class cr extends Ce.sub("auth"){}class $s extends cr.sub("invalid_token"){}class Ms extends cr.sub("expired_token"){}class le extends Ce.sub("unexpected"){constructor(e){super(`
16
- Unexpected error encountered:
17
-
18
- ${e}
19
-
20
- Please report this to the Synnax team.
21
- `)}}class Ke extends Ce.sub("query"){}class xt extends Ke.sub("not_found"){}class lr extends Ke.sub("multiple_results"){}class yi extends Ce.sub("route"){path;constructor(e,n){super(e),this.path=n}}class Us extends Ce.sub("control"){}class mi extends Us.sub("unauthorized"){}class gg extends Ce.sub("disconnected"){constructor(e="Operation failed because no Core is connected."){super(e)}}class UA extends Ce.sub("contiguity"){}const wg=t=>t.type.startsWith(Ce.TYPE)?t.type.startsWith(V.TYPE)?t.type===un.TYPE?un.decode(t):new V(t.data):t.type.startsWith(cr.TYPE)?t.type.startsWith($s.TYPE)?new $s(t.data):t.type.startsWith(Ms.TYPE)?new Ms(t.data):new cr(t.data):t.type.startsWith(le.TYPE)?new le(t.data):t.type.startsWith(Ke.TYPE)?t.type.startsWith(xt.TYPE)?new xt(t.data):t.type.startsWith(lr.TYPE)?new lr(t.data):new Ke(t.data):t.type.startsWith(Us.TYPE)?t.type.startsWith(mi.TYPE)?new mi(t.data):new Us(t.data):t.type.startsWith(yi.TYPE)?new yi(t.data,t.data):new le(t.data):null,bg=()=>{throw new Ue.NotImplemented};Ue.register({encode:bg,decode:wg});const vg=async(t,e)=>{const[n,r]=await e(t);return r==null?[n,r]:r instanceof He?[n,new He({message:`Cannot reach Core at ${r.url.host}:${r.url.port}`,url:r.url})]:[n,r]},En=a.z.uuid(),Xc=a.z.string(),Or=a.z.object({key:En,name:Xc}),zg=t=>({type:"group",key:t}),Sr=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"]),Qc=a.z.string().transform(t=>{const[e,n]=t.split(":");return{type:Sr.parse(e),key:n??""}}),R=a.z.object({type:Sr,key:a.z.string()}).or(Qc),Tg={type:"builtin",key:"root"},Ct=(t=>(typeof t=="string"&&(t=Qc.parse(t)),Array.isArray(t)?t.map(e=>Ct(e)):`${t.type}:${t.key}`)),Og=(t,e)=>t.type===e.type&&t.key===e.key,el=t=>{const e=b.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:n})=>n):e.map(n=>R.parse(n))},tl=a.z.object({id:R,name:a.z.string(),data:Te.unknownZ.optional().nullable()}).transform(t=>({key:Ct(t.id),...t})),Sg=t=>t==="to"?"from":"to",kg=a.z.object({from:R,type:a.z.string(),to:R}).or(a.z.string().transform(t=>{const[e,n,r]=t.split("->");return{from:R.parse(e),type:n,to:R.parse(r)}})),Ng=t=>`${Ct(t.from)}->${t.type}->${Ct(t.to)}`,Eg="parent",Ag=(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),Ig="sy_group_set",xg="sy_group_delete",Cg=a.object({group:Or}),jg=a.object({parent:R,key:En.optional(),name:a.string()}),$g=a.object({key:En,name:a.string()}),Mg=a.object({keys:a.array(En)}),Ug="/ontology/create-group",Pg="/ontology/rename-group",_g="/ontology/delete-group";let nl=class{client;constructor(t){this.client=t}async create(t){return(await g(this.client,Ug,t,jg,Cg)).group}async rename(t,e){await g(this.client,Pg,{key:t,name:e},$g,a.object({}))}async delete(t){await g(this.client,_g,{keys:b.toArray(t)},Mg,a.object({}))}};const Rg=Object.freeze(Object.defineProperty({__proto__:null,Client:nl,DELETE_CHANNEL_NAME:xg,SET_CHANNEL_NAME:Ig,groupZ:Or,keyZ:En,nameZ:Xc,ontologyID:zg},Symbol.toStringTag,{value:"Module"})),Zg="/ontology/add-children",Lg="/ontology/remove-children",Dg="/ontology/move-children",gi=a.z.object({id:R,children:R.array()}),Bg=a.z.object({from:R,to:R,children:R.array()}),Jr=a.z.object({});let Fg=class{client;constructor(t){this.client=t}async addChildren(t,...e){await g(this.client,Zg,{id:t,children:e},gi,Jr)}async removeChildren(t,...e){await g(this.client,Lg,{id:t,children:e},gi,Jr)}async moveChildren(t,e,...n){await g(this.client,Dg,{from:t,to:e,children:n},Bg,Jr)}};const qg="/ontology/retrieve",Yg=a.z.object({ids:R.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:Sr.array().optional()}),Vg=a.z.object({resources:tl.array()});let rl=class{type="ontology";groups;client;writer;framer;constructor(t,e){this.client=t,this.writer=new Fg(t),this.groups=new nl(t),this.framer=e}async retrieve(t,e){if(!Array.isArray(t)&&typeof t=="object"&&!("key"in t))return this.execRetrieve(t);const n=el(t),r=await this.execRetrieve({ids:n,...e});if(Array.isArray(t))return r;if(r.length===0)throw new Ke(`No resource found with ID ${Cs.naturalLanguageJoin(n.map(s=>Ct(s)))}`);return r[0]}async retrieveChildren(t,e){return await this.execRetrieve({ids:b.toArray(t),children:!0,...e})}async retrieveParents(t,e){return await this.execRetrieve({ids:b.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 g(this.client,qg,t,Yg,Vg);return e}};const Wg="sy_ontology_resource_set",Hg="sy_ontology_resource_delete",Gg="sy_ontology_relationship_set",Kg="sy_ontology_relationship_delete",Jg=Object.freeze(Object.defineProperty({__proto__:null,Client:rl,PARENT_OF_RELATIONSHIP_TYPE:Eg,RELATIONSHIP_DELETE_CHANNEL_NAME:Kg,RELATIONSHIP_SET_CHANNEL_NAME:Gg,RESOURCE_DELETE_CHANNEL_NAME:Hg,RESOURCE_SET_CHANNEL_NAME:Wg,ROOT_ID:Tg,idToString:Ct,idZ:R,idsEqual:Og,matchRelationship:Ag,oppositeRelationshipDirection:Sg,parseIDs:el,relationshipToString:Ng,relationshipZ:kg,resourceTypeZ:Sr,resourceZ:tl},Symbol.toStringTag,{value:"Module"})),An=a.z.uuid(),wa=a.z.object({key:An,subjects:b.nullableZ(R),objects:b.nullableZ(R),actions:b.nullableZ(js)}),Xg=a.z.object({key:An.optional(),subjects:R.array().or(R),objects:R.array().or(R),actions:js.array().or(js)}),Qg=a.z.object({keys:An.array().optional(),subjects:R.array().optional()}),ew=a.z.object({key:An}).transform(({key:t})=>({keys:[t]})),tw=a.z.union([a.z.object({for:R}).transform(({for:t})=>({subjects:[t]})),a.z.object({for:R.array()}).transform(({for:t})=>({subjects:t})),Qg]),nw=a.z.union([ew,tw]),rw=a.z.object({policies:b.nullableZ(wa)}),sw=a.z.object({policies:wa.partial({key:!0}).array()}),aw=a.z.object({policies:wa.array()}),iw=a.z.object({keys:An.array()}),ow=a.z.object({}),cw="/access/policy/retrieve",lw="/access/policy/create",uw="/access/policy/delete";let hw=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=Xg.array().parse(b.toArray(t)).map(s=>({objects:b.toArray(s.objects),actions:b.toArray(s.actions),subjects:b.toArray(s.subjects)})),r=await g(this.client,lw,{policies:n},sw,aw);return e?r.policies:r.policies[0]}async retrieve(t){const e="key"in t,n=await g(this.client,cw,t,nw,rw);return e?n.policies[0]:n.policies}async delete(t){await g(this.client,uw,{keys:b.toArray(t)},iw,ow)}},dw=class{policy;constructor(t){this.policy=new hw(t)}};function p(t,e,n){function r(c,l){var u;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(u=c._zod).traits??(u.traits=new Set),c._zod.traits.add(t),e(c,l);for(const h in o.prototype)h in c||Object.defineProperty(c,h,{value:o.prototype[h].bind(c)});c._zod.constr=o,c._zod.def=l}const s=n?.Parent??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function o(c){var l;const u=n?.Parent?new i:this;r(u,c),(l=u._zod).deferred??(l.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Et extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class sl extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const al={};function ut(t){return al}function fw(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 Ps(t,e){return typeof e=="bigint"?e.toString():e}function ba(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function va(t){return t==null}function za(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function pw(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let s=(r.split(".")[1]||"").length;if(s===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(s=Number.parseInt(l[1]))}const i=n>s?n:s,o=Number.parseInt(t.toFixed(i).replace(".","")),c=Number.parseInt(e.toFixed(i).replace(".",""));return o%c/10**i}const wi=Symbol("evaluating");function L(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==wi)return r===void 0&&(r=wi,r=n()),r},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function yw(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Je(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Dt(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function bi(t){return JSON.stringify(t)}const il="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ur(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const mw=ba(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function hn(t){if(ur(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(ur(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ol(t){return hn(t)?{...t}:Array.isArray(t)?[...t]:t}const gw=new Set(["string","number","symbol"]);function kr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xe(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 ww(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const bw={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 vw(t,e){const n=t._zod.def,r=Dt(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 Je(this,"shape",s),s},checks:[]});return Xe(t,r)}function zw(t,e){const n=t._zod.def,r=Dt(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 Je(this,"shape",s),s},checks:[]});return Xe(t,r)}function Tw(t,e){if(!hn(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=Dt(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return Je(this,"shape",s),s},checks:[]});return Xe(t,r)}function Ow(t,e){if(!hn(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 Je(this,"shape",r),r},checks:t._zod.def.checks};return Xe(t,n)}function Sw(t,e){const n=Dt(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Je(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return Xe(t,n)}function kw(t,e,n){const r=Dt(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 Je(this,"shape",i),i},checks:[]});return Xe(e,r)}function Nw(t,e,n){const r=Dt(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 Je(this,"shape",i),i},checks:[]});return Xe(e,r)}function Ot(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 cl(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Wn(t){return typeof t=="string"?t:t?.message}function ht(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=Wn(t.inst?._zod.def?.error?.(t))??Wn(e?.error?.(t))??Wn(n.customError?.(t))??Wn(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Ta(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function dn(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const ll=(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,Ps,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ul=p("$ZodError",ll),hl=p("$ZodError",ll,{Parent:Error});function Ew(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 Aw(t,e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(c=>s({issues:c}));else if(o.code==="invalid_key")s({issues:o.issues});else if(o.code==="invalid_element")s({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let c=r,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(o))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return s(t),r}const Oa=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 Et;if(o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>ht(l,i,ut())));throw il(c,s?.callee),c}return o.value},Sa=t=>async(e,n,r,s)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(s?.Err??t)(o.issues.map(l=>ht(l,i,ut())));throw il(c,s?.callee),c}return o.value},Nr=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 Et;return i.issues.length?{success:!1,error:new(t??ul)(i.issues.map(o=>ht(o,s,ut())))}:{success:!0,data:i.value}},Iw=Nr(hl),Er=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=>ht(o,s,ut())))}:{success:!0,data:i.value}},xw=Er(hl),Cw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Oa(t)(e,n,s)},jw=t=>(e,n,r)=>Oa(t)(e,n,r),$w=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Sa(t)(e,n,s)},Mw=t=>async(e,n,r)=>Sa(t)(e,n,r),Uw=t=>(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Nr(t)(e,n,s)},Pw=t=>(e,n,r)=>Nr(t)(e,n,r),_w=t=>async(e,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Er(t)(e,n,s)},Rw=t=>async(e,n,r)=>Er(t)(e,n,r),Zw=/^[cC][^\s-]{8,}$/,Lw=/^[0-9a-z]+$/,Dw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Bw=/^[0-9a-vA-V]{20}$/,Fw=/^[A-Za-z0-9]{27}$/,qw=/^[a-zA-Z0-9_-]{21}$/,Yw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vw=/^([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})$/,vi=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)$/,Ww=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Hw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Gw(){return new RegExp(Hw,"u")}const Kw=/^(?:(?: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])$/,Jw=/^(([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}|:))$/,Xw=/^((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])$/,Qw=/^(([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])$/,eb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,dl=/^[A-Za-z0-9_-]*$/,tb=/^(?=.{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])?)*\.?$/,nb=/^\+(?:[0-9]){6,14}[0-9]$/,fl="(?:(?:\\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])))",rb=new RegExp(`^${fl}$`);function pl(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 sb(t){return new RegExp(`^${pl(t)}$`)}function ab(t){const e=pl({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(`^${fl}T(?:${r})$`)}const ib=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},ob=/^-?\d+$/,cb=/^-?\d+(?:\.\d+)?/,lb=/^(?:true|false)$/i,ub=/^[^A-Z]*$/,hb=/^[^a-z]*$/,ie=p("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),yl={number:"number",bigint:"bigint",object:"date"},ml=p("$ZodCheckLessThan",(t,e)=>{ie.init(t,e);const n=yl[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})}}),gl=p("$ZodCheckGreaterThan",(t,e)=>{ie.init(t,e);const n=yl[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})}}),db=p("$ZodCheckMultipleOf",(t,e)=>{ie.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):pw(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})}}),fb=p("$ZodCheckNumberFormat",(t,e)=>{ie.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,i]=bw[e.format];t._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=i,n&&(c.pattern=ob)}),t._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),c>i&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:t})}}),pb=p("$ZodCheckMaxLength",(t,e)=>{var n;ie.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!va(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=Ta(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),yb=p("$ZodCheckMinLength",(t,e)=>{var n;ie.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!va(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=Ta(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),mb=p("$ZodCheckLengthEquals",(t,e)=>{var n;ie.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!va(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=Ta(s),c=i>e.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Ar=p("$ZodCheckStringFormat",(t,e)=>{var n,r;ie.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=()=>{})}),gb=p("$ZodCheckRegex",(t,e)=>{Ar.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})}}),wb=p("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ub),Ar.init(t,e)}),bb=p("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=hb),Ar.init(t,e)}),vb=p("$ZodCheckIncludes",(t,e)=>{ie.init(t,e);const n=kr(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})}}),zb=p("$ZodCheckStartsWith",(t,e)=>{ie.init(t,e);const n=new RegExp(`^${kr(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})}}),Tb=p("$ZodCheckEndsWith",(t,e)=>{ie.init(t,e);const n=new RegExp(`.*${kr(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})}}),Ob=p("$ZodCheckOverwrite",(t,e)=>{ie.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class Sb{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 kb={major:4,minor:1,patch:8},W=p("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=kb;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const i of s._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,c,l)=>{let u=Ot(o),h;for(const f of c){if(f._zod.def.when){if(!f._zod.def.when(o))continue}else if(u)continue;const d=o.issues.length,O=f._zod.check(o);if(O instanceof Promise&&l?.async===!1)throw new Et;if(h||O instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await O,o.issues.length!==d&&(u||(u=Ot(o,d)))});else{if(o.issues.length===d)continue;u||(u=Ot(o,d))}}return h?h.then(()=>o):o},i=(o,c,l)=>{if(Ot(o))return o.aborted=!0,o;const u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Et;return u.then(h=>t._zod.parse(h,l))}return t._zod.parse(u,l)};t._zod.run=(o,c)=>{if(c.skipChecks)return t._zod.parse(o,c);if(c.direction==="backward"){const u=t._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>i(h,o,c)):i(u,o,c)}const l=t._zod.parse(o,c);if(l instanceof Promise){if(c.async===!1)throw new Et;return l.then(u=>s(u,r,c))}return s(l,r,c)}}t["~standard"]={validate:s=>{try{const i=Iw(t,s);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return xw(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ka=p("$ZodString",(t,e)=>{W.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??ib(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}}),F=p("$ZodStringFormat",(t,e)=>{Ar.init(t,e),ka.init(t,e)}),Nb=p("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Vw),F.init(t,e)}),Eb=p("$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=vi(n))}else e.pattern??(e.pattern=vi());F.init(t,e)}),Ab=p("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ww),F.init(t,e)}),Ib=p("$ZodURL",(t,e)=>{F.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:tb.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})}}}),xb=p("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Gw()),F.init(t,e)}),Cb=p("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=qw),F.init(t,e)}),jb=p("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Zw),F.init(t,e)}),$b=p("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Lw),F.init(t,e)}),Mb=p("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Dw),F.init(t,e)}),Ub=p("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Bw),F.init(t,e)}),Pb=p("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Fw),F.init(t,e)}),_b=p("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=ab(e)),F.init(t,e)}),Rb=p("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=rb),F.init(t,e)}),Zb=p("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=sb(e)),F.init(t,e)}),Lb=p("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Yw),F.init(t,e)}),Db=p("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Kw),F.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Bb=p("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Jw),F.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})}}}),Fb=p("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Xw),F.init(t,e)}),qb=p("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Qw),F.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 wl(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Yb=p("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=eb),F.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{wl(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Vb(t){if(!dl.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return wl(n)}const Wb=p("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=dl),F.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Vb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Hb=p("$ZodE164",(t,e)=>{e.pattern??(e.pattern=nb),F.init(t,e)});function Gb(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 Kb=p("$ZodJWT",(t,e)=>{F.init(t,e),t._zod.check=n=>{Gb(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),bl=p("$ZodNumber",(t,e)=>{W.init(t,e),t._zod.pattern=t._zod.bag.pattern??cb,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}}),Jb=p("$ZodNumber",(t,e)=>{fb.init(t,e),bl.init(t,e)}),Xb=p("$ZodBoolean",(t,e)=>{W.init(t,e),t._zod.pattern=lb,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}}),Qb=p("$ZodUnknown",(t,e)=>{W.init(t,e),t._zod.parse=n=>n}),ev=p("$ZodNever",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function zi(t,e,n){t.issues.length&&e.issues.push(...cl(n,t.issues)),e.value[n]=t.value}const tv=p("$ZodArray",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const i=[];for(let o=0;o<s.length;o++){const c=s[o],l=e.element._zod.run({value:c,issues:[]},r);l instanceof Promise?i.push(l.then(u=>zi(u,n,o))):zi(l,n,o)}return i.length?Promise.all(i).then(()=>n):n}});function hr(t,e,n,r){t.issues.length&&e.issues.push(...cl(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function vl(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=ww(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function zl(t,e,n,r,s,i){const o=[],c=s.keySet,l=s.catchall._zod,u=l.def.type;for(const h of Object.keys(e)){if(c.has(h))continue;if(u==="never"){o.push(h);continue}const f=l.run({value:e[h],issues:[]},r);f instanceof Promise?t.push(f.then(d=>hr(d,n,h,e))):hr(f,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 nv=p("$ZodObject",(t,e)=>{W.init(t,e);const n=ba(()=>vl(e));L(t._zod,"propValues",()=>{const o=e.shape,c={};for(const l in o){const u=o[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(const h of u.values)c[l].add(h)}}return c});const r=ur,s=e.catchall;let i;t._zod.parse=(o,c)=>{i??(i=n.value);const l=o.value;if(!r(l))return o.issues.push({expected:"object",code:"invalid_type",input:l,inst:t}),o;o.value={};const u=[],h=i.shape;for(const f of i.keys){const d=h[f]._zod.run({value:l[f],issues:[]},c);d instanceof Promise?u.push(d.then(O=>hr(O,o,f,l))):hr(d,o,f,l)}return s?zl(u,l,o,c,n.value,t):u.length?Promise.all(u).then(()=>o):o}}),rv=p("$ZodObjectJIT",(t,e)=>{nv.init(t,e);const n=t._zod.parse,r=ba(()=>vl(e)),s=f=>{const d=new Sb(["shape","payload","ctx"]),O=r.value,C=I=>{const G=bi(I);return`shape[${G}]._zod.run({ value: input[${G}], issues: [] }, ctx)`};d.write("const input = payload.value;");const j=Object.create(null);let w=0;for(const I of O.keys)j[I]=`key_${w++}`;d.write("const newResult = {};");for(const I of O.keys){const G=j[I],re=bi(I);d.write(`const ${G} = ${C(I)};`),d.write(`
24
- if (${G}.issues.length) {
25
- payload.issues = payload.issues.concat(${G}.issues.map(iss => ({
26
- ...iss,
27
- path: iss.path ? [${re}, ...iss.path] : [${re}]
28
- })));
29
- }
30
-
31
-
32
- if (${G}.value === undefined) {
33
- if (${re} in input) {
34
- newResult[${re}] = undefined;
35
- }
36
- } else {
37
- newResult[${re}] = ${G}.value;
38
- }
39
-
40
- `)}d.write("payload.value = newResult;"),d.write("return payload;");const v=d.compile();return(I,G)=>v(f,I,G)};let i;const o=ur,c=!al.jitless,l=c&&mw.value,u=e.catchall;let h;t._zod.parse=(f,d)=>{h??(h=r.value);const O=f.value;return o(O)?c&&l&&d?.async===!1&&d.jitless!==!0?(i||(i=s(e.shape)),f=i(f,d),u?zl([],O,f,d,h,t):f):n(f,d):(f.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),f)}});function Ti(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=>!Ot(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=>ht(o,r,ut())))}),e)}const sv=p("$ZodUnion",(t,e)=>{W.init(t,e),L(t._zod,"optin",()=>e.options.some(s=>s._zod.optin==="optional")?"optional":void 0),L(t._zod,"optout",()=>e.options.some(s=>s._zod.optout==="optional")?"optional":void 0),L(t._zod,"values",()=>{if(e.options.every(s=>s._zod.values))return new Set(e.options.flatMap(s=>Array.from(s._zod.values)))}),L(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=>za(i.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(s,i)=>{if(n)return r(s,i);let o=!1;const c=[];for(const l of e.options){const u=l._zod.run({value:s.value,issues:[]},i);if(u instanceof Promise)c.push(u),o=!0;else{if(u.issues.length===0)return u;c.push(u)}}return o?Promise.all(c).then(l=>Ti(l,s,t,i)):Ti(c,s,t,i)}}),av=p("$ZodIntersection",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,i=e.left._zod.run({value:s,issues:[]},r),o=e.right._zod.run({value:s,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([c,l])=>Oi(n,c,l)):Oi(n,i,o)}});function _s(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(hn(t)&&hn(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=_s(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=_s(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 Oi(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Ot(t))return t;const r=_s(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 iv=p("$ZodEnum",(t,e)=>{W.init(t,e);const n=fw(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(s=>gw.has(typeof s)).map(s=>typeof s=="string"?kr(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}}),ov=p("$ZodTransform",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new sl(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 Et;return n.value=s,n}});function Si(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const cv=p("$ZodOptional",(t,e)=>{W.init(t,e),t._zod.optin="optional",t._zod.optout="optional",L(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),L(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${za(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=>Si(i,n.value)):Si(s,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),lv=p("$ZodNullable",(t,e)=>{W.init(t,e),L(t._zod,"optin",()=>e.innerType._zod.optin),L(t._zod,"optout",()=>e.innerType._zod.optout),L(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${za(n.source)}|null)$`):void 0}),L(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)}),uv=p("$ZodDefault",(t,e)=>{W.init(t,e),t._zod.optin="optional",L(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=>ki(i,e)):ki(s,e)}});function ki(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const hv=p("$ZodPrefault",(t,e)=>{W.init(t,e),t._zod.optin="optional",L(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))}),dv=p("$ZodNonOptional",(t,e)=>{W.init(t,e),L(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=>Ni(i,t)):Ni(s,t)}});function Ni(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 fv=p("$ZodCatch",(t,e)=>{W.init(t,e),L(t._zod,"optin",()=>e.innerType._zod.optin),L(t._zod,"optout",()=>e.innerType._zod.optout),L(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=>ht(o,r,ut()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>ht(i,r,ut()))},input:n.value}),n.issues=[]),n)}}),pv=p("$ZodPipe",(t,e)=>{W.init(t,e),L(t._zod,"values",()=>e.in._zod.values),L(t._zod,"optin",()=>e.in._zod.optin),L(t._zod,"optout",()=>e.out._zod.optout),L(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=>Hn(o,e.in,r)):Hn(i,e.in,r)}const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(i=>Hn(i,e.out,r)):Hn(s,e.out,r)}});function Hn(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const yv=p("$ZodReadonly",(t,e)=>{W.init(t,e),L(t._zod,"propValues",()=>e.innerType._zod.propValues),L(t._zod,"values",()=>e.innerType._zod.values),L(t._zod,"optin",()=>e.innerType._zod.optin),L(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(Ei):Ei(s)}});function Ei(t){return t.value=Object.freeze(t.value),t}const mv=p("$ZodCustom",(t,e)=>{ie.init(t,e),W.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=>Ai(i,n,r,t));Ai(s,n,r,t)}});function Ai(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(dn(s))}}class gv{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 wv(){return new gv}const Gn=wv();function bv(t,e){return new t({type:"string",...N(e)})}function vv(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function Ii(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function Tl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function zv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function Tv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function Ov(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function Sv(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function kv(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function Nv(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function Ev(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function Av(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function Iv(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function xv(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function Cv(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function jv(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function $v(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function Mv(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function Uv(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function Pv(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function _v(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function Rv(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function Zv(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}function Lv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function Dv(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function Bv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function Fv(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function qv(t,e){return new t({type:"number",checks:[],...N(e)})}function Yv(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function Vv(t,e){return new t({type:"boolean",...N(e)})}function Wv(t){return new t({type:"unknown"})}function Hv(t,e){return new t({type:"never",...N(e)})}function xi(t,e){return new ml({check:"less_than",...N(e),value:t,inclusive:!1})}function Xr(t,e){return new ml({check:"less_than",...N(e),value:t,inclusive:!0})}function Ci(t,e){return new gl({check:"greater_than",...N(e),value:t,inclusive:!1})}function Qr(t,e){return new gl({check:"greater_than",...N(e),value:t,inclusive:!0})}function ji(t,e){return new db({check:"multiple_of",...N(e),value:t})}function Ol(t,e){return new pb({check:"max_length",...N(e),maximum:t})}function dr(t,e){return new yb({check:"min_length",...N(e),minimum:t})}function Sl(t,e){return new mb({check:"length_equals",...N(e),length:t})}function Gv(t,e){return new gb({check:"string_format",format:"regex",...N(e),pattern:t})}function Kv(t){return new wb({check:"string_format",format:"lowercase",...N(t)})}function Jv(t){return new bb({check:"string_format",format:"uppercase",...N(t)})}function Xv(t,e){return new vb({check:"string_format",format:"includes",...N(e),includes:t})}function Qv(t,e){return new zb({check:"string_format",format:"starts_with",...N(e),prefix:t})}function ez(t,e){return new Tb({check:"string_format",format:"ends_with",...N(e),suffix:t})}function In(t){return new Ob({check:"overwrite",tx:t})}function tz(t){return In(e=>e.normalize(t))}function nz(){return In(t=>t.trim())}function rz(){return In(t=>t.toLowerCase())}function sz(){return In(t=>t.toUpperCase())}function az(t,e,n){return new t({type:"array",element:e,...N(n)})}function iz(t,e,n){return new t({type:"custom",check:"custom",fn:e,...N(n)})}function oz(t){const e=cz(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(dn(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(dn(s))}},t(n.value,n)));return e}function cz(t,e){const n=new ie({check:"custom",...N(e)});return n._zod.check=t,n}const lz=p("ZodISODateTime",(t,e)=>{_b.init(t,e),Y.init(t,e)});function uz(t){return Lv(lz,t)}const hz=p("ZodISODate",(t,e)=>{Rb.init(t,e),Y.init(t,e)});function dz(t){return Dv(hz,t)}const fz=p("ZodISOTime",(t,e)=>{Zb.init(t,e),Y.init(t,e)});function pz(t){return Bv(fz,t)}const yz=p("ZodISODuration",(t,e)=>{Lb.init(t,e),Y.init(t,e)});function mz(t){return Fv(yz,t)}const gz=(t,e)=>{ul.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Aw(t,n)},flatten:{value:n=>Ew(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Ps,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Ps,2)}},isEmpty:{get(){return t.issues.length===0}}})},we=p("ZodError",gz,{Parent:Error}),wz=Oa(we),bz=Sa(we),vz=Nr(we),zz=Er(we),Tz=Cw(we),Oz=jw(we),Sz=$w(we),kz=Mw(we),Nz=Uw(we),Ez=Pw(we),Az=_w(we),Iz=Rw(we),H=p("ZodType",(t,e)=>(W.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)=>Xe(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>wz(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>vz(t,n,r),t.parseAsync=async(n,r)=>bz(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>zz(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Tz(t,n,r),t.decode=(n,r)=>Oz(t,n,r),t.encodeAsync=async(n,r)=>Sz(t,n,r),t.decodeAsync=async(n,r)=>kz(t,n,r),t.safeEncode=(n,r)=>Nz(t,n,r),t.safeDecode=(n,r)=>Ez(t,n,r),t.safeEncodeAsync=async(n,r)=>Az(t,n,r),t.safeDecodeAsync=async(n,r)=>Iz(t,n,r),t.refine=(n,r)=>t.check(zT(n,r)),t.superRefine=n=>t.check(TT(n)),t.overwrite=n=>t.check(In(n)),t.optional=()=>_i(t),t.nullable=()=>Ri(t),t.nullish=()=>_i(Ri(t)),t.nonoptional=n=>pT(t,n),t.array=()=>tT(t),t.or=n=>Na([t,n]),t.and=n=>aT(t,n),t.transform=n=>Zi(t,cT(n)),t.default=n=>hT(t,n),t.prefault=n=>fT(t,n),t.catch=n=>mT(t,n),t.pipe=n=>Zi(t,n),t.readonly=()=>bT(t),t.describe=n=>{const r=t.clone();return Gn.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Gn.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Gn.get(t);const r=t.clone();return Gn.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),kl=p("_ZodString",(t,e)=>{ka.init(t,e),H.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(Gv(...r)),t.includes=(...r)=>t.check(Xv(...r)),t.startsWith=(...r)=>t.check(Qv(...r)),t.endsWith=(...r)=>t.check(ez(...r)),t.min=(...r)=>t.check(dr(...r)),t.max=(...r)=>t.check(Ol(...r)),t.length=(...r)=>t.check(Sl(...r)),t.nonempty=(...r)=>t.check(dr(1,...r)),t.lowercase=r=>t.check(Kv(r)),t.uppercase=r=>t.check(Jv(r)),t.trim=()=>t.check(nz()),t.normalize=(...r)=>t.check(tz(...r)),t.toLowerCase=()=>t.check(rz()),t.toUpperCase=()=>t.check(sz())}),xz=p("ZodString",(t,e)=>{ka.init(t,e),kl.init(t,e),t.email=n=>t.check(vv(Cz,n)),t.url=n=>t.check(Sv($z,n)),t.jwt=n=>t.check(Zv(Hz,n)),t.emoji=n=>t.check(kv(Mz,n)),t.guid=n=>t.check(Ii($i,n)),t.uuid=n=>t.check(Tl(nn,n)),t.uuidv4=n=>t.check(zv(nn,n)),t.uuidv6=n=>t.check(Tv(nn,n)),t.uuidv7=n=>t.check(Ov(nn,n)),t.nanoid=n=>t.check(Nv(Uz,n)),t.guid=n=>t.check(Ii($i,n)),t.cuid=n=>t.check(Ev(Pz,n)),t.cuid2=n=>t.check(Av(_z,n)),t.ulid=n=>t.check(Iv(Rz,n)),t.base64=n=>t.check(Pv(Yz,n)),t.base64url=n=>t.check(_v(Vz,n)),t.xid=n=>t.check(xv(Zz,n)),t.ksuid=n=>t.check(Cv(Lz,n)),t.ipv4=n=>t.check(jv(Dz,n)),t.ipv6=n=>t.check($v(Bz,n)),t.cidrv4=n=>t.check(Mv(Fz,n)),t.cidrv6=n=>t.check(Uv(qz,n)),t.e164=n=>t.check(Rv(Wz,n)),t.datetime=n=>t.check(uz(n)),t.date=n=>t.check(dz(n)),t.time=n=>t.check(pz(n)),t.duration=n=>t.check(mz(n))});function ge(t){return bv(xz,t)}const Y=p("ZodStringFormat",(t,e)=>{F.init(t,e),kl.init(t,e)}),Cz=p("ZodEmail",(t,e)=>{Ab.init(t,e),Y.init(t,e)}),$i=p("ZodGUID",(t,e)=>{Nb.init(t,e),Y.init(t,e)}),nn=p("ZodUUID",(t,e)=>{Eb.init(t,e),Y.init(t,e)});function jz(t){return Tl(nn,t)}const $z=p("ZodURL",(t,e)=>{Ib.init(t,e),Y.init(t,e)}),Mz=p("ZodEmoji",(t,e)=>{xb.init(t,e),Y.init(t,e)}),Uz=p("ZodNanoID",(t,e)=>{Cb.init(t,e),Y.init(t,e)}),Pz=p("ZodCUID",(t,e)=>{jb.init(t,e),Y.init(t,e)}),_z=p("ZodCUID2",(t,e)=>{$b.init(t,e),Y.init(t,e)}),Rz=p("ZodULID",(t,e)=>{Mb.init(t,e),Y.init(t,e)}),Zz=p("ZodXID",(t,e)=>{Ub.init(t,e),Y.init(t,e)}),Lz=p("ZodKSUID",(t,e)=>{Pb.init(t,e),Y.init(t,e)}),Dz=p("ZodIPv4",(t,e)=>{Db.init(t,e),Y.init(t,e)}),Bz=p("ZodIPv6",(t,e)=>{Bb.init(t,e),Y.init(t,e)}),Fz=p("ZodCIDRv4",(t,e)=>{Fb.init(t,e),Y.init(t,e)}),qz=p("ZodCIDRv6",(t,e)=>{qb.init(t,e),Y.init(t,e)}),Yz=p("ZodBase64",(t,e)=>{Yb.init(t,e),Y.init(t,e)}),Vz=p("ZodBase64URL",(t,e)=>{Wb.init(t,e),Y.init(t,e)}),Wz=p("ZodE164",(t,e)=>{Hb.init(t,e),Y.init(t,e)}),Hz=p("ZodJWT",(t,e)=>{Kb.init(t,e),Y.init(t,e)}),Nl=p("ZodNumber",(t,e)=>{bl.init(t,e),H.init(t,e),t.gt=(r,s)=>t.check(Ci(r,s)),t.gte=(r,s)=>t.check(Qr(r,s)),t.min=(r,s)=>t.check(Qr(r,s)),t.lt=(r,s)=>t.check(xi(r,s)),t.lte=(r,s)=>t.check(Xr(r,s)),t.max=(r,s)=>t.check(Xr(r,s)),t.int=r=>t.check(Ui(r)),t.safe=r=>t.check(Ui(r)),t.positive=r=>t.check(Ci(0,r)),t.nonnegative=r=>t.check(Qr(0,r)),t.negative=r=>t.check(xi(0,r)),t.nonpositive=r=>t.check(Xr(0,r)),t.multipleOf=(r,s)=>t.check(ji(r,s)),t.step=(r,s)=>t.check(ji(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 Mi(t){return qv(Nl,t)}const Gz=p("ZodNumberFormat",(t,e)=>{Jb.init(t,e),Nl.init(t,e)});function Ui(t){return Yv(Gz,t)}const Kz=p("ZodBoolean",(t,e)=>{Xb.init(t,e),H.init(t,e)});function xn(t){return Vv(Kz,t)}const Jz=p("ZodUnknown",(t,e)=>{Qb.init(t,e),H.init(t,e)});function Pi(){return Wv(Jz)}const Xz=p("ZodNever",(t,e)=>{ev.init(t,e),H.init(t,e)});function Qz(t){return Hv(Xz,t)}const eT=p("ZodArray",(t,e)=>{tv.init(t,e),H.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(dr(n,r)),t.nonempty=n=>t.check(dr(1,n)),t.max=(n,r)=>t.check(Ol(n,r)),t.length=(n,r)=>t.check(Sl(n,r)),t.unwrap=()=>t.element});function tT(t,e){return az(eT,t,e)}const nT=p("ZodObject",(t,e)=>{rv.init(t,e),H.init(t,e),L(t,"shape",()=>e.shape),t.keyof=()=>iT(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Pi()}),t.loose=()=>t.clone({...t._zod.def,catchall:Pi()}),t.strict=()=>t.clone({...t._zod.def,catchall:Qz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Tw(t,n),t.safeExtend=n=>Ow(t,n),t.merge=n=>Sw(t,n),t.pick=n=>vw(t,n),t.omit=n=>zw(t,n),t.partial=(...n)=>kw(El,t,n[0]),t.required=(...n)=>Nw(Al,t,n[0])});function ee(t,e){const n={type:"object",get shape(){return Je(this,"shape",t?yw(t):{}),this.shape},...N(e)};return new nT(n)}const rT=p("ZodUnion",(t,e)=>{sv.init(t,e),H.init(t,e),t.options=e.options});function Na(t,e){return new rT({type:"union",options:t,...N(e)})}const sT=p("ZodIntersection",(t,e)=>{av.init(t,e),H.init(t,e)});function aT(t,e){return new sT({type:"intersection",left:t,right:e})}const Rs=p("ZodEnum",(t,e)=>{iv.init(t,e),H.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 Rs({...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 Rs({...e,checks:[],...N(s),entries:i})}});function iT(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Rs({type:"enum",entries:n,...N(e)})}const oT=p("ZodTransform",(t,e)=>{ov.init(t,e),H.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new sl(t.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(dn(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(dn(o))}};const s=e.transform(n.value,n);return s instanceof Promise?s.then(i=>(n.value=i,n)):(n.value=s,n)}});function cT(t){return new oT({type:"transform",transform:t})}const El=p("ZodOptional",(t,e)=>{cv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function _i(t){return new El({type:"optional",innerType:t})}const lT=p("ZodNullable",(t,e)=>{lv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ri(t){return new lT({type:"nullable",innerType:t})}const uT=p("ZodDefault",(t,e)=>{uv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function hT(t,e){return new uT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():ol(e)}})}const dT=p("ZodPrefault",(t,e)=>{hv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function fT(t,e){return new dT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():ol(e)}})}const Al=p("ZodNonOptional",(t,e)=>{dv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function pT(t,e){return new Al({type:"nonoptional",innerType:t,...N(e)})}const yT=p("ZodCatch",(t,e)=>{fv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function mT(t,e){return new yT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const gT=p("ZodPipe",(t,e)=>{pv.init(t,e),H.init(t,e),t.in=e.in,t.out=e.out});function Zi(t,e){return new gT({type:"pipe",in:t,out:e})}const wT=p("ZodReadonly",(t,e)=>{yv.init(t,e),H.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bT(t){return new wT({type:"readonly",innerType:t})}const vT=p("ZodCustom",(t,e)=>{mv.init(t,e),H.init(t,e)});function zT(t,e={}){return iz(vT,t,e)}function TT(t){return oz(t)}const Ir=a.z.string(),Cn=t=>Lt.statusZ(t),Il=t=>Cn(t).omit({labels:!0}).partial({key:!0}),OT="sy_status_set",ST="sy_status_delete",kT=t=>({type:"status",key:t}),je=t=>t?JSON.parse(t):{},Ea=ee({key:ge(),type:ge(),config:Te.unknownZ.or(ge().transform(je))}),xl=Ea.extend({position:ha.xy}),Zs=ee({param:ge(),node:ge()}),Aa=ee({source:Zs,target:Zs}),NT=ee({nodes:Ea.array(),edges:Aa.array()}),Cl=ee({nodes:xl.array(),edges:Aa.array()}),jl=ee({raw:ge()}),jn=jz(),$l=ee({running:xn()}),Ml=Cn($l),xr=ee({key:jn,name:ge(),graph:Cl,text:jl,deploy:xn(),version:ge(),status:Ml.optional().nullable()}),Ul=xr.partial({key:!0}).omit({status:!0}),Pl="arc",ET=(t,e,{convertNumericStrings:n=!0}={})=>{const r=!Array.isArray(t);let s=b.toArray(t);const i=s[0],o=typeof i;let c;return o==="string"&&n&&!isNaN(parseInt(i))&&"number"in e?(c=e.number,s=s.map(l=>parseInt(l))):c=e[o],{single:r,variant:c,normalized:s,actual:t}},ue=(t,e,n,r)=>{if(r){if(n.length===0)throw new xt(`${t} not found matching ${JSON.stringify(e)}`);if(n.length>1)throw new lr(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${n.length}`)}},AT="sy_arc_set",IT="sy_arc_delete",xT="/arc/retrieve",CT="/arc/create",jT="/arc/delete",$T="/arc/lsp",MT=ee({keys:jn.array().optional(),names:ge().array().optional(),searchTerm:ge().optional(),limit:Mi().optional(),offset:Mi().optional(),includeStatus:xn().optional()}),UT=ee({arcs:Ul.array()}),PT=ee({keys:jn.array()}),_T=ee({arcs:b.nullableZ(xr)}),RT=ee({arcs:xr.array()}),ZT=ee({}),Ls=ee({content:ge()}),LT=ee({key:jn,includeStatus:xn().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),DT=ee({name:ge(),includeStatus:xn().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e})),_l=Na([LT,DT]),BT=Na([_l,MT]);let Rl=class{client;streamClient;constructor(t,e){this.client=t,this.streamClient=e}async create(t){const e=Array.isArray(t),n=await g(this.client,CT,{arcs:b.toArray(t)},UT,RT);return e?n.arcs:n.arcs[0]}async retrieve(t){const e="key"in t||"name"in t,n=await g(this.client,xT,t,BT,_T);return ue("Arc",t,n.arcs,e),e?n.arcs[0]:n.arcs}async delete(t){await g(this.client,jT,{keys:b.toArray(t)},PT,ZT)}async openLSP(){return await this.streamClient.stream($T,Ls,Ls)}};const FT=t=>({type:Pl,key:t}),qT=Object.freeze(Object.defineProperty({__proto__:null,Client:Rl,DELETE_CHANNEL_NAME:IT,ONTOLOGY_TYPE:Pl,SET_CHANNEL_NAME:AT,arcZ:xr,edgeZ:Aa,graphNodeZ:xl,graphZ:Cl,handleZ:Zs,irNodeZ:Ea,irZ:NT,keyZ:jn,lspMessageZ:Ls,newZ:Ul,ontologyID:FT,singleRetrieveArgsZ:_l,statusDetailsZ:$l,statusZ:Ml,textZ:jl},Symbol.toStringTag,{value:"Module"})),Li="Channel key must be a valid uint32.",D=a.z.uint32().or(a.z.string().refine(t=>!isNaN(Number(t)),{message:Li}).transform(Number).refine(t=>t<Es.MAX_UINT32,{message:Li})),Me=a.z.string(),Zl=["min","max","avg","none"],Ll=a.z.enum(Zl),Ia=a.z.object({type:Ll,resetChannel:D.optional(),duration:E.z.optional()}),Dl=Lt.statusZ(),Bt=a.z.object({name:Me,key:D,dataType:P.z,leaseholder:a.z.number(),index:D,isIndex:a.z.boolean(),internal:a.z.boolean(),virtual:a.z.boolean(),alias:a.z.string().optional(),expression:a.z.string().default(""),status:Dl.optional(),operations:b.nullableZ(Ia),requires:b.nullableZ(D)}),Bl=Bt.omit({requires:!0}).extend({key:D.optional(),leaseholder:a.z.number().optional(),index:D.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(""),operations:b.nullableZ(Ia).optional()}),ft=a.z.union([sn.toArray(D),sn.toArray(Me),sn.toArray(Bt).transform(t=>t.map(e=>e.key))]),YT=new Error("request for lock canceled");var VT=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function c(h){try{u(r.next(h))}catch(f){o(f)}}function l(h){try{u(r.throw(h))}catch(f){o(f)}}function u(h){h.done?i(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class WT{constructor(e,n=YT){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=Fl(this._queue,c=>n<=c.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return VT(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]=[]),HT(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 HT(t,e){const n=Fl(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function Fl(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var GT=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function c(h){try{u(r.next(h))}catch(f){o(f)}}function l(h){try{u(r.throw(h))}catch(f){o(f)}}function u(h){h.done?i(h.value):s(h.value).then(c,l)}u((r=r.apply(t,e||[])).next())})};class KT{constructor(e){this._semaphore=new WT(1,e)}acquire(){return GT(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 JT=a.z.object({leaseholder:a.z.number().optional(),keys:D.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:P.z.array().optional(),notDataTypes:P.z.array().optional(),virtual:a.z.boolean().optional(),isIndex:a.z.boolean().optional(),internal:a.z.boolean().optional(),calculated:a.z.boolean().optional(),legacyCalculated:a.z.boolean().optional()}),XT=a.z.object({channels:b.nullableZ(Bt)}),ve=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]),ET(t,{number:"keys",string:"names"}));class $n{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=ve(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($n.ENDPOINT,e,JT,XT);if(r!=null)throw r;return n.channels}}class xa{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}=ve(e),s=[],i=[];if(r.forEach(c=>{const l=this.get(c);l!=null?s.push(...l):i.push(c)}),i.length===0)return s;const o=await this.wrapped.retrieve(i,n);return this.set(o),s.concat(o)}delete(e){const{variant:n,normalized:r}=ve(e);n==="names"?r.forEach(s=>{const i=this.namesToKeys.get(s);i!=null&&(i.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):r.forEach(s=>{const i=this.cache.get(s);i!=null&&(this.cache.delete(s),this.namesToKeys.delete(i.name))})}rename(e,n){e.forEach((r,s)=>{const i=n[s],o=this.cache.get(r);if(o==null)return;this.cache.delete(r);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(r),c.size===0&&this.namesToKeys.delete(o.name)),o.name=i,this.cache.set(r,o);const l=this.namesToKeys.get(i);l==null?this.namesToKeys.set(i,new Set([r])):l.add(r)})}set(e){e.forEach(n=>{this.cache.set(n.key,n);const r=this.namesToKeys.get(n.name);r==null?this.namesToKeys.set(n.name,new Set([n.key])):r.add(n.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const n=this.namesToKeys.get(e);if(n==null)return;const r=[];if(n.forEach(s=>{const i=this.cache.get(s);i!=null&&r.push(i)}),r.length!==0)return r}}class ql{mu=new KT;requests=new Map;wrapped;debouncedRun;constructor(e,n){this.wrapped=e,this.debouncedRun=Gy(()=>{this.run()},n)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n,variant:r}=ve(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 Yl=async(t,e)=>{const{normalized:n}=ve(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 Ke(`Could not find channels: ${JSON.stringify(s)}`);return r},QT="sy_channel_set",eO="sy_channel_delete";class Ds{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;operations;requires;status;constructor({dataType:e,name:n,leaseholder:r=0,key:s=0,isIndex:i=!1,index:o=0,internal:c=!1,virtual:l=!1,frameClient:u,alias:h,status:f,expression:d="",operations:O=[],requires:C=[]}){this.key=D.parse(s),this.name=n,this.dataType=new P(e),this.leaseholder=r,this.index=D.parse(o),this.isIndex=i,this.internal=c,this.alias=h,this.virtual=l,this.expression=d,this.operations=O,this.requires=C,f!=null&&(this.status=Lt.create(f)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new V("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Bt.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,requires:this.requires,expression:this.expression,status:this.status,operations:this.operations})}get isCalculated(){return fn(this.payload)}get ontologyID(){return Wl(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 tO="sy_calculation_status",nO="/channel/retrieve-group",rO=a.z.object({}),sO=a.z.object({group:Or});let Vl=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=b.toArray(t),i=[];if(n){const o=await this.retriever.retrieve(s.map(l=>l.name)),c=new Set(o.map(l=>l.name));s=s.filter(l=>!c.has(l.name)),i=this.sugar(o)}return i=i.concat(this.sugar(await this.writer.create(s))),r?i[0]:i}async retrieve(t,e){if(typeof t=="object"&&!Array.isArray(t))return this.sugar(await this.retriever.retrieve(t));const n=!Array.isArray(t),r=this.sugar(await this.retriever.retrieve(t,e));return ue("channel",t,r,n),n?r[0]:r}async delete(t){const{normalized:e,variant:n}=ve(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(b.toArray(t),b.toArray(e))}createDebouncedBatchRetriever(t=10){return new xa(new ql(new $n(this.client),t))}sugar(t){const{frameClient:e}=this;return Array.isArray(t)?t.map(n=>new Ds({...n,frameClient:e})):new Ds({...t,frameClient:e})}async retrieveGroup(){return(await g(this.client,nO,{},rO,sO)).group}};const fn=({virtual:t,expression:e})=>t&&e!=="",aO=t=>fn(t)&&t.requires.length>0,Wl=t=>({type:"channel",key:t.toString()}),Hl=async(t,e)=>{if(!fn(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(fn(r)){const s=await Hl(t,r);if(s!=null)return s}}return null},iO=a.z.object({channels:Bl.array()}),oO=a.z.object({channels:Bt.array()}),cO=a.z.object({keys:D.array().optional(),names:Me.array().optional()}),lO=a.z.object({}),uO=a.z.object({keys:D.array(),names:Me.array()}),hO=a.z.object({}),dO="/channel/create",fO="/channel/delete",pO="/channel/rename";let Gl=class{client;cache;constructor(t,e){this.client=t,this.cache=e}async create(t){const{channels:e}=await g(this.client,dO,{channels:t.map(n=>({...n,dataType:n.dataType}))},iO,oO);return this.cache.set(e),e}async delete(t){const e=D.array().parse(t.keys??[]);await g(this.client,fO,t,cO,lO),e.length>0&&this.cache.delete(e),t.names!=null&&this.cache.delete(t.names)}async rename(t,e){await g(this.client,pO,{keys:t,names:e},uO,hO),this.cache.rename(t,e)}};const yO=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:tO,CacheRetriever:xa,Channel:Ds,Client:Vl,ClusterRetriever:$n,DELETE_CHANNEL_NAME:eO,DebouncedBatchRetriever:ql,OPERATION_TYPES:Zl,SET_CHANNEL_NAME:QT,Writer:Gl,analyzeParams:ve,isCalculated:fn,isLegacyCalculated:aO,keyZ:D,nameZ:Me,newZ:Bl,ontologyID:Wl,operationType:Ll,operationZ:Ia,paramsZ:ft,payloadZ:Bt,resolveLegacyCalculatedIndex:Hl,retrieveRequired:Yl,statusZ:Dl},Symbol.toStringTag,{value:"Module"})),Qe=a.z.uuid(),Mn=a.z.object({key:Qe,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)}),Kl=Mn.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:a.z.string().min(1)}),mO=a.z.object({keys:Qe.array().optional(),usernames:a.z.string().array().optional()}),gO=a.z.object({key:Qe}).transform(({key:t})=>({keys:[t]})),wO=a.z.object({username:a.z.string()}).transform(({username:t})=>({usernames:[t]})),bO=a.z.object({usernames:a.z.string().array()}).transform(({usernames:t})=>({usernames:t})),vO=a.z.union([gO,wO,bO,mO]),zO=a.z.object({users:b.nullableZ(Mn)}),TO=a.z.object({users:Kl.array()}),OO=a.z.object({users:Mn.array()}),SO=a.z.object({key:Qe,username:a.z.string().min(1)}),kO=a.z.object({}),NO=a.z.object({key:Qe,firstName:a.z.string().optional(),lastName:a.z.string().optional()}),EO=a.z.object({}),AO=a.z.object({keys:Qe.array()}),IO=a.z.object({}),xO="/user/retrieve",CO="/user/create",jO="/user/change-username",$O="/user/rename",MO="/user/delete";let Jl=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),n=await g(this.client,CO,{users:b.toArray(t)},TO,OO);return e?n.users:n.users[0]}async changeUsername(t,e){await g(this.client,jO,{key:t,username:e},SO,kO)}async retrieve(t){const e="key"in t||"username"in t,n=await g(this.client,xO,t,vO,zO);if(!e)return n.users;if(n.users.length===0){const r="key"in t?`key ${t.key}`:`username ${t.username}`;throw new xt(`No user with ${r} found`)}if(n.users.length>1){const r="key"in t?`key ${t.key}`:`username ${t.username}`;throw new lr(`Multiple users found with ${r}`)}return n.users[0]}async rename(t,e,n){await g(this.client,$O,{key:t,firstName:e,lastName:n},NO,EO)}async delete(t){await g(this.client,MO,{keys:b.toArray(t)},AO,IO)}};const UO=t=>({type:"user",key:t}),PO=Object.freeze(Object.defineProperty({__proto__:null,Client:Jl,keyZ:Qe,newZ:Kl,ontologyID:UO,userZ:Mn},Symbol.toStringTag,{value:"Module"})),_O=a.z.object({username:a.z.string(),password:a.z.string()}),RO=a.z.object({token:a.z.string(),user:Mn}),Di="/auth/login",ZO=3,LO="/auth/change-password",DO=a.z.object({username:a.z.string(),password:a.z.string(),newPassword:a.z.string().min(1)}),BO=a.z.object({}),FO=[$s,Ms];let qO=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 g(this.client,LO,{username:this.credentials.username,password:this.credentials.password,newPassword:t},DO,BO),this.credentials.password=t}middleware(){const t=async(e,n)=>{if(!this.authenticated&&!e.target.endsWith(Di)){this.authenticating??=new Promise((o,c)=>{this.client.send(Di,this.credentials,_O,RO).then(([l,u])=>{if(u!=null)return o(u);this.token=l?.token,this.user=l?.user,this.authenticated=!0,o(null)}).catch(c)});const i=await this.authenticating;if(i!=null)return[e,i]}e.params.Authorization=`Bearer ${this.token}`;const[r,s]=await n(e);return FO.some(i=>i.matches(s))&&this.retryCount<ZO?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,t(e,n)):(this.retryCount=0,[r,s])};return t}};const YO=a.z.enum(["disconnected","connecting","connected","failed"]),VO=a.z.object({status:YO,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()}),WO=a.z.object({clusterKey:a.z.string(),nodeVersion:a.z.string().optional()}),Bi={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.47.0"},Fi=(t,e,n)=>{const r=n?"Core":"client";return`Synnax Core 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 fr{static ENDPOINT="/connectivity/check";static DEFAULT=Bi;_state;pollFrequency=E.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=VO;versionWarned=!1;constructor(e,n=E.seconds(30),r,s){this._state={...Bi},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(fr.ENDPOINT,{},a.z.object({}),WO);if(r!=null)throw r;const s=n.nodeVersion,i=this.clientVersion,o=this.versionWarned;s==null?(this._state.clientServerCompatible=!1,o||(console.warn(Fi(null,i,!0)),this.versionWarned=!0)):pi.versionsEqual(i,s,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,o||(console.warn(Fi(s,i,pi.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 HO=a.z.object({keys:D.array().optional(),bounds:B.z,names:Me.array().optional()}),GO=a.z.object({});class KO{client;constructor(e){this.client=e}async delete(e){await g(this.client,"/frame/delete",e,HO,GO)}}const qi=t=>{const e=b.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Yi=(t,e)=>{const n=b.toArray(t);if(n.length===e.length)return;const r=qi(t);throw qi===null?new V("[Frame] - channel keys or names must be provided when constructing a frame."):new V(`[Frame] - ${r}s and series must be the same length.
43
- Got ${n.length} ${r}s and ${e.length} series.`)};let ce=class zt{columns=[];series=[];constructor(e=[],n=[]){if(e instanceof zt){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((r,s)=>this.push(s,...b.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=>Xl(i));Yi(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,...b.toArray(s));this.push(r,...b.toArray(s))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const r=b.toArray(n),s=b.toArray(e);Yi(s,r),r.forEach((i,o)=>this.push(s[o],i));return}throw new V(`[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 le("colType is not key");return this.columns??[]}get uniqueKeys(){return ii.unique(this.keys)}get names(){if(this.colType==="key")throw new le("colType is not name");return this.columns??[]}get uniqueNames(){return ii.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Ql(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 B.ZERO;const r=x.min(...this.series.map(i=>i.timeRange.start)),s=x.max(...this.series.map(i=>i.timeRange.end));return new B(r,s)}const n=this.get(e);return n==null?B.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 Vy(this.series.filter((n,r)=>this.columns[r]===e))}push(e,...n){if(e instanceof zt){if(this.colType!==null&&e.colType!==this.colType)throw new V("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 V("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new V("keyVariant must match");this.columns.push(...Array.from({length:n.length},()=>e))}}concat(e){return new zt([...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 zt;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 zt;return this.columns.forEach((r,s)=>{const i=this.series[s];e(r,i,s)&&n.push(r,i)}),n}get byteLength(){return new It(this.series.reduce((e,n)=>e.add(n.byteLength),It.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 Cr=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(()=>[]),qe.crudeZ.array().optional().default([])])}),Xl=t=>{const{dataType:e,data:n,timeRange:r,alignment:s}=t;return new qe({data:n,dataType:e,timeRange:r,glBufferUsage:"static",alignment:s})},Ql=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var xe=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(xe||{});const Vi=t=>t.data.byteLength/t.dataType.density.valueOf(),JO=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)},Wi=5,Hi=4,Gi=3,Ki=2,Ji=1,Xi=0,Se=P.TIMESTAMP.density.valueOf(),Ze=8,Le=4,es=4,ts=4,XO=1;class eu{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 V(`
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()),JO(r);let s=-1,i,o,c,l=n+XO+ts,u=!this.currState?.hasVariableDataTypes,h=!0,f=!0,d=!0,O=!0,C=!0;r.keys.length!==this.currState?.keys.length&&(d=!1,l+=r.keys.length*es),r.series.forEach((I,G)=>{const re=Vi(I),Yt=r.keys[G],nt=this.currState?.keyDataTypes.get(Yt);if(nt==null)throw new V(`Channel ${Yt} was not provided in the list of channels when opening the writer`);if(!nt.equals(I.dataType))throw new V(`Series data type of ${I.dataType.toString()} does not match the data type of ${nt.toString()} for channel ${Yt}`);if(l+=I.data.byteLength,s===-1){s=re,i=I.timeRange?.start,o=I.timeRange?.end,c=BigInt(I.alignment??0n);return}s!==re&&(u=!1),(i?.valueOf()!==I.timeRange?.start.valueOf()||o?.valueOf()!==I.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(I.alignment??0)&&(O=!1)}),f=h&&i==null&&o==null,C=O&&(c===void 0||c===0n),u?l+=Le:l+=r.keys.length*Le,f||(h?l+=Se*2:l+=r.keys.length*Se*2),C||(O?l+=Ze:l+=r.keys.length*Ze);const j=new Uint8Array(l),w=new DataView(j.buffer);let v=n;return j[v]=Number(C)<<Wi|Number(O)<<Hi|Number(u)<<Gi|Number(h)<<Ki|Number(f)<<Ji|Number(d)<<Xi,v++,w.setUint32(v,this.seqNum,!0),v+=ts,u&&(w.setUint32(v,s,!0),v+=Le),h&&!f&&(w.setBigUint64(v,i?.valueOf()??0n,!0),w.setBigUint64(v,o?.valueOf()??0n,!0),v+=Se*2),O&&!C&&(w.setBigUint64(v,c??0n,!0),v+=Ze),r.series.forEach((I,G)=>{if(d||(w.setUint32(v,r.keys[G],!0),v+=es),!u){let re=I.data.byteLength;I.dataType.isVariable||(re=Vi(I)),w.setUint32(v,re,!0),v+=Le}j.set(new Uint8Array(I.data),v),v+=I.data.byteLength,!h&&!f&&(w.setBigUint64(v,I.timeRange?.start.valueOf()??0n,!0),w.setBigUint64(v,I.timeRange?.end.valueOf()??0n,!0),v+=Se*2),!O&&!C&&(w.setBigUint64(v,I.alignment??0n,!0),v+=Ze)}),j}decode(e,n=0){this.throwIfNotUpdated("decode");const r=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let i=n,o=0,c=0,l,u,h;const f=new DataView(r.buffer,r.byteOffset,r.byteLength),d=!!(r[i]>>Wi&1),O=!!(r[i]>>Hi&1),C=!!(r[i]>>Gi&1),j=!!(r[i]>>Ki&1),w=!!(r[i]>>Ji&1),v=!!(r[i]>>Xi&1);i++;const I=f.getUint32(i,!0);i+=ts;const G=this.states.get(I);if(G==null)return s;if(C){if(i+Le>f.byteLength)return s;o=f.getUint32(i,!0),i+=Le}if(j&&!w){if(i+Se>f.byteLength)return s;l=new x(f.getBigUint64(i,!0)),i+=Se,u=new x(f.getBigUint64(i,!0)),i+=Se}if(O&&!d){if(i+Ze>f.byteLength)return s;h=f.getBigUint64(i,!0),i+=Ze}return v&&(s.keys=[...G.keys]),G.keys.forEach((re,Yt)=>{if(!v){if(i>=f.byteLength||f.getUint32(i,!0)!==re)return;i+=es,s.keys.push(re)}const nt=G.keyDataTypes.get(re);if(c=0,C)c=o;else{if(i+Le>f.byteLength)return;c=f.getUint32(i,!0),i+=Le}let Zn=c;if(nt.isVariable||(Zn*=nt.density.valueOf()),i+Zn>f.byteLength){s.keys.splice(Yt,1);return}const rt={dataType:nt,data:r.slice(i,i+Zn).buffer};if(i+=Zn,!j&&!w){if(i+Se*2>f.byteLength)return;const Uh=f.getBigUint64(i,!0);i+=Se;const Ph=f.getBigUint64(i,!0);i+=Se,rt.timeRange=new B({start:Uh,end:Ph})}else w?rt.timeRange=new B({start:0n,end:0n}):rt.timeRange=new B({start:l?.valueOf()??0n,end:u?.valueOf()??0n});if(!O&&!d){if(i+Ze>f.byteLength)return;h=f.getBigUint64(i,!0),i+=Ze,rt.alignment=h}else d?rt.alignment=0n:rt.alignment=h;s.series.push(rt)}),s}}const Ca=254,QO=new Uint8Array([Ca]),eS=255,tS=new Uint8Array([eS]),tu="application/sy-framer";class nS{contentType=tu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=dt.JSON_CODEC}encode(e){const n=e;if(n.type=="close"||n.payload?.command!=xe.Write){const s=this.lowPerfCodec.encode(n),i=new Uint8Array({length:s.byteLength+1});return i.set(QO,0),i.set(new Uint8Array(s),1),i}const r=this.base.encode(n.payload?.frame,1);return r.set(tS,0),r}decode(e,n){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Ca)return this.lowPerfCodec.decode(e.slice(1),n);const r={type:"data"},s=this.base.decode(e,1);return r.payload={command:xe.Write,frame:s},r}}class rS{contentType=tu;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=dt.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,n){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===Ca?this.lowPerfCodec.decode(e.slice(1),n):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class jr{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new eu}static async open(e,n){const r=new jr(e);return await r.update(n),r}async update(e){const{variant:n,normalized:r}=ve(e),s=await this.retriever.retrieve(r),i=s.map(c=>c.key);if(di.uniqueUnorderedPrimitiveArrays(this.keys,i)===di.EQUAL)return!1;if(this.codec.update(i,s.map(c=>c.dataType)),n==="keys")return this.adapter=null,this.keys=r,!0;const o=new Map;return this.adapter=o,r.forEach(c=>{const l=s.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} not found`);o.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys()),!0}adapt(e){if(this.adapter==null)return e;const n=this.adapter;return e.map((r,s)=>{if(typeof r=="number"){const i=n.get(r);if(i==null)throw new Error(`Channel ${r} not found`);return[i,s]}return[r,s]})}}class ja{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new eu}static async open(e,n){const r=new ja(e);return await r.update(n),r}async adaptParams(e){const n=ft.parse(e);return await Promise.all(n.map(async r=>await this.adaptToKey(r)))}async update(e){const n=await Yl(this.retriever,e),r=n.map(l=>l.key),s=new Set(this.keys),i=new Set(r),o=!i.isSubsetOf(s),c=!s.isSubsetOf(i);return o||c?(this.adapter=new Map(n.map(l=>[l.name,l.key])),this.keys=r,this.codec.update(this.keys,n.map(l=>l.dataType)),!0):!1}async fetchChannel(e){const n=await this.retriever.retrieve(e);if(n.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return n[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,n){if(typeof e=="string"||typeof e=="number"){if(n==null)throw new V(`
51
- Received a single channel name or key but no series.
52
- `);if(Array.isArray(n)){if(n.some(l=>l instanceof qe||Array.isArray(l)))throw new V(`
53
- Received a single channel name or key but multiple series.
54
- `);n=n}const o=await this.fetchChannel(e),c=new qe({data:n,dataType:o.dataType});return new ce(o.key,c)}if(Array.isArray(e)){if(n==null)throw new V(`
55
- Received an array of channel names or keys but no series.
56
- `);if(!Array.isArray(n))throw new V(`
57
- Received an array of channel names or keys but no array of series.
58
- `);const o=[],c=[];for(let l=0;l<e.length;l++){const u=await this.fetchChannel(e[l]);if(l>=n.length)throw new V(`
59
- Received an array of channel names or keys but not enough series.
60
- `);const h=new qe({data:n[l],dataType:u.dataType});o.push(u.key),c.push(h)}return new ce(o,c)}if(e instanceof ce||e instanceof Map){const o=new ce(e);if(this.adapter==null)return o;const c=o.columns.map(l=>{const u=typeof l=="string"?this.adapter?.get(l):l;if(u==null)throw new V(`
61
- Channel ${l} was not provided in the list of channels when opening the writer
62
- `);return u});return new ce(c,o.series)}const r=[],s=[],i=Object.entries(e);for(let o=0;o<i.length;o++){const[c,l]=i[o],u=await this.fetchChannel(c),h=new qe({data:l,dataType:u.dataType});r.push(u.key),s.push(h)}return new ce(r,s)}}class nu{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 pr=new E(-1);var $a=(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))($a||{}),ru=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(ru||{});const sS=a.z.object({command:a.z.enum($a),span:E.z.optional(),bounds:B.z.optional(),stamp:x.z.optional(),keys:D.array().optional(),chunkSize:a.z.number().optional()}),aS=a.z.object({variant:a.z.enum(ru),ack:a.z.boolean(),command:a.z.enum($a),error:Ue.payloadZ.optional().nullable(),frame:Cr.optional()});class $r{stream;adapter;value;constructor(e,n){this.stream=new nu("Iterator",e),this.value=new ce,this.adapter=n}static async _open(e,n,r,s,i={}){const o=await jr.open(r,n),c=await s.stream("/frame/iterate",sS,aS),l=new $r(c,o);return await l.execute({command:0,keys:o.keys,bounds:new B(e),chunkSize:i.chunkSize??1e5}),l}async next(e=pr){return await this.execute({command:1,span:new E(e)})}async prev(e=pr){return await this.execute({command:2,span:new E(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 x(e)})}async seekGE(e){return await this.execute({command:6,stamp:new x(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new iS(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 iS{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 oS=a.z.object({keys:a.z.number().array(),downsampleFactor:a.z.number()}),cS=a.z.object({frame:Cr}),Qi=a.z.object({channels:ft,downsampleFactor:a.z.number().optional().default(1),useHighPerformanceCodec:a.z.boolean().optional().default(!0)}),Ma=Qi.or(ft.transform(t=>Qi.parse({channels:t}))),su=(t,e)=>async n=>{const r=Ma.parse(n),s=await jr.open(t,r.channels);r.useHighPerformanceCodec&&(e=e.withCodec(new rS(s.codec)));const i=await e.stream("/frame/stream",oS,cS),o=new lS(i,s);i.send({keys:s.keys,downsampleFactor:r.downsampleFactor??1});const[,c]=await i.receive();if(c!=null)throw c;return o},au=async(t,e,n)=>await su(t,e)(n);class lS{stream;adapter;downsampleFactor;constructor(e,n){this.stream=new nu("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 Mr{wrapped_=null;breaker;opener;config;constructor(e,n,r={}){this.opener=e,this.config=Ma.parse(n);const{maxRetries:s=5e3,baseInterval:i=E.seconds(1),scale:o=1}=r??{};this.breaker=new $c.Breaker({maxRetries:s,baseInterval:i,scale:o})}static async open(e,n,r){const s=new Mr(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=ft.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 iu extends tm.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)}}var pn=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(pn||{});const uS=new E(-1);class Bs extends Ce.sub("writer_closed"){constructor(){super("WriterClosed")}}const hS=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}})),ou=a.z.object({start:x.z.optional(),controlSubject:me.subjectZ.optional(),authorities:a.z.union([me.authorityZ.transform(t=>[t]),me.authorityZ.array()]).default([me.ABSOLUTE_AUTHORITY]),mode:hS.default(1),errOnUnauthorized:a.z.boolean().default(!1),enableAutoCommit:a.z.boolean().default(!0),autoIndexPersistInterval:E.z.default(E.SECOND),useHighPerformanceCodec:a.z.boolean().default(!0)}),dS=ou.extend({keys:D.array().optional()}),eo=ou.extend({channels:ft}),cu=eo.or(ft.transform(t=>eo.parse({channels:t,start:x.now()}))),fS=a.z.object({command:a.z.enum(xe),config:dS.optional(),frame:Cr.optional(),buffer:a.z.instanceof(Uint8Array).optional()}),pS=a.z.object({command:a.z.enum(xe),end:x.z,err:Ue.payloadZ.optional()}),yS=a.z.tuple([a.z.union([a.z.record(D.or(Me),me.authorityZ),D.or(Me),me.authorityZ]),me.authorityZ.optional()]).transform(([t,e])=>{if(me.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(D.or(Me).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const n=t;return{keys:Object.keys(n),authorities:Object.values(n)}});let lu=class uu{stream;adapter;closeErr=null;constructor(e,n){this.stream=e,this.adapter=n}static async _open(e,n,r){const s=cu.parse(r),i=await ja.open(e,s.channels);s.useHighPerformanceCodec&&(n=n.withCodec(new nS(i.codec)));const o=await n.stream("/frame/write",fS,pS),c=new uu(o,i);return await c.execute({command:xe.Open,config:{...s,keys:i.keys}}),c}async write(e,n){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const r=await this.adapter.adapt(e,n);this.stream.send({command:xe.Write,frame:r.toPayload()})}async setAuthority(e,n){if(this.closeErr!=null)throw this.closeErr;const r=yS.parse([e,n]),s={keys:await this.adapter.adaptParams(r.keys),authorities:r.authorities};await this.execute({command:xe.SetAuthority,config:s})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),x.ZERO):(await this.execute({command:xe.Commit})).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(Bs.matches(this.closeErr))return null;throw this.closeErr}const[n,r]=await this.stream.receive();r!=null?this.closeErr=ze.matches(r)?new Bs:r:this.closeErr=Ue.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=Ue.decode(r?.err);if(i!=null&&await this.closeInternal(i),r?.command==e.command)return r}}};const mS=t=>({type:"framer",key:t.toString()});let hu=class{streamClient;retriever;deleter;constructor(t,e,n){this.streamClient=t,this.retriever=n,this.deleter=new KO(e)}async openIterator(t,e,n){return await $r._open(t,e,this.retriever,this.streamClient,n)}async openWriter(t){return await lu._open(this.retriever,this.streamClient,t)}async openStreamer(t){return await au(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,autoIndexPersistInterval:E.MAX});return await i.write(s),await i.close()}const r=await this.openWriter({start:t,channels:e,mode:pn.Persist,errOnUnauthorized:!0,autoIndexPersistInterval:E.MAX});await r.write(e,n),await r.close()}async read(t,e){const{single:n}=ve(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}=ve(t),r=await this.readLatestNFrame(t,e);return n?r.get(t):r}async readLatestNFrame(t,e){const n=await this.openIterator(B.MAX,t,{chunkSize:e}),r=new ce;if(e>0)try{await n.seekLast(),await n.prev(pr),r.push(n.value)}finally{await n.close()}return r}async delete(t,e){const{normalized:n,variant:r}=ve(t),s=new B(e);return r==="keys"?await this.deleter.delete({keys:n,bounds:s}):await this.deleter.delete({names:n,bounds:s})}};const gS=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:uS,AUTO_SPAN:pr,Client:hu,Frame:ce,HardenedStreamer:Mr,Iterator:$r,ObservableStreamer:iu,Writer:lu,WriterClosedError:Bs,WriterCommand:xe,WriterMode:pn,createStreamOpener:su,frameZ:Cr,ontologyID:mS,openStreamer:au,seriesFromPayload:Xl,seriesToPayload:Ql,streamerConfigZ:Ma,writerConfigZ:cu},Symbol.toStringTag,{value:"Module"})),wS=me.ABSOLUTE_AUTHORITY,bS=me.ZERO_AUTHORITY,vS=me.stateZ(a.z.number()),zS=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()})`,TS=a.z.object({transfers:a.z.array(me.transferZ(D))});class du extends iu{states;codec;constructor(e){super(e,n=>{const r=this.codec.decode(n.series[0].buffer,TS);return this.merge(r),[r.transfers,!0]}),this.states=new Map,this.codec=new dt.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 fu="sy_node_1_control";let pu=class{framer;constructor(t){this.framer=t}async openStateTracker(){const t=await Mr.open(async e=>await this.framer.openStreamer(e),fu);return new du(t)}};const OS=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:wS,CONTROL_STATE_CHANNEL_NAME:fu,Client:pu,StateTracker:du,ZERO_AUTHORITY:bS,stateZ:vS,transferString:zS},Symbol.toStringTag,{value:"Module"}));let SS=class{tasks;racks;devices;constructor(t,e,n){this.tasks=t,this.racks=e,this.devices=n}};const Oe=a.z.uint32(),yu=a.z.object({rack:Oe}),mu=Lt.statusZ(yu),Ur=a.z.object({key:Oe,name:a.z.string(),status:sn.nullToUndefined(mu)}),gu=Ur.partial({key:!0}),wu=t=>t?dt.JSON_CODEC.decodeString(t,Te.unknownZ):{},Ft=a.z.string(),bu=a.z.object({rack:Oe,device:Ft}),vu=Lt.statusZ(bu),Pr=a.z.object({key:Ft,rack:Oe.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:Te.unknownZ.or(a.z.string().transform(wu)),status:sn.nullToUndefined(vu)}),zu=Pr.extend({properties:a.z.unknown().transform(t=>dt.JSON_CODEC.encodeString(t))}),kS="sy_device_set",NS="sy_device_delete",ES="sy_device_status",AS="/hardware/device/retrieve",IS="/hardware/device/create",xS="/hardware/device/delete",CS=a.z.object({devices:zu.array()}),jS=a.z.object({devices:Pr.array()}),$S=a.z.object({keys:Ft.array()}),MS=a.z.object({}),US=a.z.object({keys:Ft.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:Oe.array().optional(),searchTerm:a.z.string().optional(),limit:a.z.number().optional(),offset:a.z.number().optional(),includeStatus:a.z.boolean().optional()}),PS=a.z.object({devices:b.nullableZ(Pr)}),_S=a.z.object({key:Ft,includeStatus:a.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),RS=a.z.union([_S,US]);let Tu=class{client;constructor(t){this.client=t}async retrieve(t){const e=typeof t=="object"&&"key"in t,n=await g(this.client,AS,t,RS,PS);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 g(this.client,IS,{devices:b.toArray(t)},CS,jS)).devices;return e?n[0]:n}async delete(t){await g(this.client,xS,{keys:b.toArray(t)},$S,MS)}};const ZS=t=>({type:"device",key:t}),LS=Object.freeze(Object.defineProperty({__proto__:null,Client:Tu,DELETE_CHANNEL_NAME:NS,SET_CHANNEL_NAME:kS,STATUS_CHANNEL_NAME:ES,deviceZ:Pr,keyZ:Ft,newZ:zu,ontologyID:ZS,statusDetailsSchema:bu,statusZ:vu},Symbol.toStringTag,{value:"Module"})),DS="/hardware/rack/retrieve",BS="/hardware/rack/create",FS="/hardware/rack/delete",qS="sy_rack_status",YS="sy_rack_set",VS="sy_rack_delete",WS=a.z.object({keys:Oe.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()}),HS=a.z.object({racks:b.nullableZ(Ur)}),GS=a.z.union([a.z.object({key:Oe,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}))]),KS=WS,JS=a.z.union([GS,KS]),XS=a.z.object({racks:gu.array()}),QS=a.z.object({racks:Ur.array()}),e0=a.z.object({keys:Oe.array()}),t0=a.z.object({});let Ou=class{client;tasks;constructor(t,e){this.client=t,this.tasks=e}async delete(t){await g(this.client,FS,{keys:b.toArray(t)},e0,t0)}async create(t){const e=!Array.isArray(t),n=await g(this.client,BS,{racks:b.toArray(t)},XS,QS),r=this.sugar(n.racks);return e?r[0]:r}async retrieve(t){const e="key"in t||"name"in t,n=await g(this.client,DS,t,JS,HS),r=this.sugar(n.racks);return ue("Rack",t,r,e),e?r[0]:r}sugar(t){const e=!Array.isArray(t),n=b.toArray(t).map(({key:r,name:s,status:i})=>new Su(r,s,this.tasks,i));return e?n[0]:n}};class Su{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 n0=t=>({type:"rack",key:t.toString()}),r0=Object.freeze(Object.defineProperty({__proto__:null,Client:Ou,DELETE_CHANNEL_NAME:VS,Rack:Su,SET_CHANNEL_NAME:YS,STATUS_CHANNEL_NAME:qS,keyZ:Oe,newZ:gu,ontologyID:n0,rackZ:Ur,statusDetailsSchema:yu,statusZ:mu},Symbol.toStringTag,{value:"Module"})),Pe=a.z.union([a.z.string(),a.z.bigint().transform(t=>t.toString()),a.z.number().transform(t=>t.toString())]),ku=t=>a.z.object({task:Pe,running:a.z.boolean(),data:t}),Ua=t=>Lt.statusZ(ku(t)),Un=(t={typeSchema:a.z.string(),configSchema:a.z.unknown(),statusDataSchema:a.z.unknown()})=>a.z.object({key:Pe,name:a.z.string(),type:t.typeSchema,internal:a.z.boolean().optional(),config:a.z.string().transform(wu).or(t.configSchema),status:Ua(t.statusDataSchema).optional().nullable(),snapshot:a.z.boolean().optional()}),Nu=t=>Un(t).omit({key:!0}).extend({key:Pe.transform(e=>e.toString()).optional(),config:a.z.unknown().transform(e=>dt.JSON_CODEC.encodeString(e))}),s0=a.z.object({task:Pe,type:a.z.string(),key:a.z.string(),args:Te.unknownZ.or(a.z.string().transform(je)).or(a.z.array(a.z.unknown())).or(a.z.null()).optional()}),a0=t=>Number(BigInt(t)>>32n),Fs="sy_task_status",qs="sy_task_cmd",i0="sy_task_set",o0="sy_task_delete",at=new Error("Task not created"),Eu=async(t,e)=>{const n=await e.retrieveParents(Pa(t));return n.length===0?null:n[0]};class Au{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw at;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw at;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw at;return this.rangeClient_}constructor({key:e,type:n,name:r,config:s,internal:i=!1,snapshot:o=!1,status:c},l,u,h,f){this.key=e,this.name=r,this.type=n,this.config=s,this.schemas=l??{typeSchema:a.z.string(),configSchema:a.z.unknown(),statusDataSchema:a.z.unknown()},this.internal=i,this.snapshot=o,this.status=c,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=f}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return Pa(this.key)}async executeCommand(e){return await Cu({...e,frameClient:this.frameClient,task:this.key})}async executeCommandSync(e){return await ju({...e,frameClient:this.frameClient,task:this.key,name:this.name,statusDataZ:this.schemas?.statusDataSchema})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw at;return this.snapshot?await Eu(this.key,this.ontologyClient):null}}const c0=a.z.object({rack:Oe.optional(),keys:Pe.array().optional(),names:a.z.string().array().optional(),types:a.z.string().array().optional(),includeStatus:a.z.boolean().optional(),internal:a.z.boolean().optional(),snapshot:a.z.boolean().optional(),searchTerm:a.z.string().optional(),offset:a.z.number().optional(),limit:a.z.number().optional()}),Iu=a.z.union([a.z.object({key:Pe,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:Oe.optional()}).transform(({type:t,rack:e})=>({types:[t],rack:e}))]),l0=c0,u0=a.z.union([Iu,l0]),h0=t=>a.z.object({tasks:b.nullableZ(Un(t))}),d0="/hardware/task/retrieve",f0="/hardware/task/create",p0="/hardware/task/delete",y0="/hardware/task/copy",m0=t=>a.z.object({tasks:Nu(t).array()}),g0=t=>a.z.object({tasks:Un(t).array()}),w0=a.z.object({keys:Pe.array()}),b0=a.z.object({}),v0=a.z.object({key:Pe,name:a.z.string(),snapshot:a.z.boolean()}),z0=t=>a.z.object({task:Un(t)});let xu=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=m0(e),s=g0(e),i=await g(this.client,f0,{tasks:b.toArray(t)},r,s),o=this.sugar(i.tasks,e);return n?o[0]:o}async delete(t){await g(this.client,p0,{keys:b.toArray(t)},w0,b0)}async retrieve({schemas:t,...e}){const n=Iu.safeParse(e).success,r=(await g(this.client,d0,e,u0,h0(t))).tasks,s=this.sugar(r,t);return ue("Task",e,s,n),n?s[0]:s}async copy(t,e,n){const r=z0(),s=await g(this.client,y0,{key:t,name:e,snapshot:n},v0,r);return this.sugar(s.task)}async retrieveSnapshottedTo(t){if(this.ontologyClient==null)throw at;return await Eu(t,this.ontologyClient)}sugar(t,e){const n=!Array.isArray(t),r=b.toArray(t).map(({key:s,name:i,type:o,config:c,status:l,internal:u,snapshot:h})=>new Au({key:s,name:i,type:o,config:c,internal:u,snapshot:h,status:l},e,this.frameClient,this.ontologyClient,this.rangeClient));return n?r[0]:r}async executeCommand(t){return"commands"in t?await _a({...t,frameClient:this.frameClient}):await Cu({...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 $u({...t,frameClient:this.frameClient,name:n})}const e=async()=>{const{task:n}=t;return(await this.retrieve({key:n})).name};return await ju({frameClient:this.frameClient,name:e,...t})}};const Pa=t=>({type:"task",key:t}),Cu=async({frameClient:t,task:e,type:n,args:r})=>(await _a({frameClient:t,commands:[{args:r,task:e,type:n}]}))[0],_a=async({frameClient:t,commands:e})=>{if(t==null)throw at;const n=await t.openWriter(qs),r=e.map(s=>({...s,key:gy.create()}));return await n.write(qs,r),await n.close(),r.map(s=>s.key)},ju=async({frameClient:t,task:e,type:n,timeout:r,name:s,statusDataZ:i,args:o})=>(await $u({frameClient:t,commands:[{args:o,task:e,type:n}],timeout:r,statusDataZ:i,name:s}))[0],$u=async({frameClient:t,commands:e,timeout:n=E.seconds(10),statusDataZ:r,name:s})=>{if(t==null)throw at;const i=await t.openStreamer(Fs),o=await _a({frameClient:t,commands:e}),c=new E(n);let l=[],u;const h=new Promise((f,d)=>{u=setTimeout(()=>{(async()=>{const O=e.map(C=>C.task);d(await T0("command",s,c,O))})()},c.milliseconds)});try{for(;;){const f=await Promise.race([i.read(),h]),d=Ua(r).parse(f.at(-1)[Fs]);if(o.includes(d.key)&&(l=[...l.filter(O=>O.key!==d.key),d],l.length===o.length))return l}}finally{clearTimeout(u),i.close()}},T0=async(t,e,n,r)=>{const s=Xf.capitalize(t),i=n.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=b.toArray(await e());const c=Cs.naturalLanguageJoin(o);return new Error(`${s} command to ${c} timed out after ${i}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${s} command to task with key ${Cs.naturalLanguageJoin(r)} timed out after ${i}`)}},O0=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:qs,Client:xu,DELETE_CHANNEL_NAME:o0,SET_CHANNEL_NAME:i0,STATUS_CHANNEL_NAME:Fs,Task:Au,commandZ:s0,keyZ:Pe,newZ:Nu,ontologyID:Pa,rackKey:a0,statusDetailsZ:ku,statusZ:Ua,taskZ:Un},Symbol.toStringTag,{value:"Module"})),et=Hc.keyZ,Pn=Hc.labelZ,S0="labeled_by",k0="sy_label_set",N0="sy_label_delete",Mu=Pn.extend({key:et.optional()}),E0=a.object({labels:Mu.array()}),A0=a.object({labels:Pn.array()}),I0=a.object({keys:et.array()}),Uu=a.object({id:R,labels:et.array(),replace:a.boolean().optional()}),x0=Uu.omit({replace:!0}),ns=a.object({}),C0="/label/create",j0="/label/delete",$0="/label/set",M0="/label/remove",U0="/label/retrieve",P0=a.object({keys:et.array().optional(),for:R.optional(),searchTerm:a.string().optional(),offset:a.number().optional(),limit:a.number().optional()}),_0=a.object({key:et}).transform(({key:t})=>({keys:[t]})),R0=a.union([_0,P0]),Z0=a.object({labels:b.nullableZ(Pn)});let Pu=class{type="label";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,n=await g(this.client,U0,t,R0,Z0);return ue("Label",t,n.labels,e),e?n.labels[0]:n.labels}async label(t,e,n={}){await g(this.client,$0,{id:t,labels:e,replace:n.replace},Uu,ns)}async remove(t,e){await g(this.client,M0,{id:t,labels:e},x0,ns)}async create(t){const e=Array.isArray(t),n=await g(this.client,C0,{labels:b.toArray(t)},E0,A0);return e?n.labels:n.labels[0]}async delete(t){await g(this.client,j0,{keys:b.toArray(t)},I0,ns)}};const L0=t=>({type:"label",key:t}),D0=Object.freeze(Object.defineProperty({__proto__:null,Client:Pu,DELETE_CHANNEL_NAME:N0,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:S0,SET_CHANNEL_NAME:k0,keyZ:et,labelZ:Pn,newZ:Mu,ontologyID:L0},Symbol.toStringTag,{value:"Module"})),Q=a.z.uuid(),Ra=a.z.string().min(1),_n=a.z.object({key:Q,name:Ra,timeRange:B.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()<=Es.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()>=Es.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:Pn.array().or(a.z.null().transform(()=>{})).optional(),get parent(){return _n.optional().nullable().transform(t=>t===void 0?null:t)}}),_u=_n.omit({parent:!0,labels:!0}).partial({key:!0}),B0="sy_range_alias_set",F0="sy_range_alias_delete",q0=a.z.object({range:Q,aliases:a.z.string().array()}),Y0=a.z.object({aliases:a.z.record(a.z.string(),D)}),V0=a.z.object({range:Q,aliases:a.z.record(D,a.z.string())}),W0=a.z.unknown(),H0=a.z.object({range:Q,channels:D.array()}),G0=a.z.unknown(),K0=a.z.object({range:Q}),J0=a.z.object({aliases:a.z.record(a.z.string(),a.z.string())}),X0=a.z.object({range:Q,channels:D.array()}),Q0=a.z.object({aliases:a.z.record(a.z.string(),a.z.string())});let st=class Tt{static SET_ENDPOINT="/range/alias/set";static RESOLVE_ENDPOINT="/range/alias/resolve";static LIST_ENDPOINT="/range/alias/list";static RETRIEVE_ENDPOINT="/range/alias/retrieve";static DELETE_ENDPOINT="/range/alias/delete";frameClient;cache=new Map;client;rangeKey;constructor(e,n,r){this.rangeKey=e,this.cache=new Map,this.client=r,this.frameClient=n}async resolve(e){const n=[],r=typeof e=="string",s={};if(r){const o=this.cache.get(e);if(o!=null)return o;n.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:n.push(o)});if(n.length===0)return s;const i=await g(this.client,Tt.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:n},q0,Y0);return Object.entries(i.aliases).forEach(([o,c])=>this.cache.set(o,c)),r?i.aliases[n[0]]:{...s,...i.aliases}}async set(e){await g(this.client,Tt.SET_ENDPOINT,{range:this.rangeKey,aliases:e},V0,W0)}async list(){return(await g(this.client,Tt.LIST_ENDPOINT,{range:this.rangeKey},K0,J0)).aliases}async retrieve(e){const n=typeof e=="number",r=await g(this.client,Tt.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:b.toArray(e)},X0,Q0);return n?r.aliases[e]:r.aliases}async delete(e){await g(this.client,Tt.DELETE_ENDPOINT,{range:this.rangeKey,channels:b.toArray(e)},H0,G0)}};const ek=a.z.object({alias:a.z.string().optional(),channel:D,range:Q}),Ru="---",tk=t=>`${t.range}${Ru}${t.channel}`,nk=t=>{const[e,n]=t.split(Ru);return{range:e,channel:Number(n)}},rk="sy_range_kv_set",sk="sy_range_kv_delete",Za=a.z.object({range:Q,key:a.z.string(),value:a.z.string()}),ak=({range:t,key:e})=>`${t}<--->${e}`,ik=a.z.object({range:Q,keys:a.z.string().array()}),ok=a.z.object({pairs:b.nullableZ(Za)}),ck=a.z.object({range:Q,pairs:Za.array()}),lk=a.z.object({range:Q,keys:a.z.string().array()});class ct{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 g(this.client,ct.GET_ENDPOINT,{range:this.rangeKey,keys:b.toArray(e)},ik,ok);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;Zo(e)?r=Object.entries(e).map(([s,i])=>({range:this.rangeKey,key:s,value:i})):r=[{range:this.rangeKey,key:e,value:n}],await g(this.client,ct.SET_ENDPOINT,{range:this.rangeKey,pairs:r},ck,a.z.unknown())}async delete(e){await g(this.client,ct.DELETE_ENDPOINT,{range:this.rangeKey,keys:b.toArray(e)},lk,a.z.unknown())}}const uk="sy_range_set",hk="sy_range_delete";class Zu{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:n=B.ZERO,key:r,color:s,parent:i,labels:o},{frameClient:c,kv:l,aliaser:u,channels:h,labelClient:f,ontologyClient:d,rangeClient:O}){this.key=r,this.name=e,this.timeRange=n,this.parent=i,this.labels=o,this.frameClient=c,this.color=s,this.kv=l,this.aliaser=u,this.channels=h,this.labelClient=f,this.ontologyClient=d,this.rangeClient=O}get ontologyID(){return St(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 Ke(`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:St(this.key)})}async addLabel(...e){await this.labelClient.label(St(this.key),e)}async removeLabel(...e){await this.labelClient.remove(St(this.key),e)}static sort(e,n){return B.sort(e.timeRange,n.timeRange)}}const dk=a.z.object({keys:Q.array().optional(),names:a.z.array(a.z.string()).optional(),searchTerm:a.z.string().optional(),overlapsWith:B.z.optional(),limit:a.z.number().int().optional(),offset:a.z.number().int().optional(),hasLabels:et.array().optional(),includeLabels:a.z.boolean().optional(),includeParent:a.z.boolean().optional()}),fk=dk.or(Q.array().transform(t=>({keys:t}))).or(Q.transform(t=>({keys:[t]}))).or(a.z.string().transform(t=>({names:[t]}))).or(a.z.string().array().transform(t=>({names:t}))).or(B.z.transform(t=>({overlapsWith:t}))),pk="/range/retrieve",yk=a.z.object({ranges:b.nullableZ(_n)});let Lu=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(b.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(b.toArray(t))}async retrieve(t){const e=typeof t=="string",{ranges:n}=await g(this.unaryClient,pk,t,fk,yk);return ue("Range",t,n,e),e?this.sugarMany(n)[0]:this.sugarMany(n)}getKV(t){return new ct(t,this.unaryClient)}async retrieveParent(t){const e=await this.ontologyClient.retrieveParents(St(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(Du(t))}async retrieveAlias(t,e){return await new st(t,this.frameClient,this.unaryClient).retrieve(e)}async retrieveAliases(t,e){return await new st(t,this.frameClient,this.unaryClient).retrieve(e)}async listAliases(t){return await new st(t,this.frameClient,this.unaryClient).list()}async setAlias(t,e,n){await new st(t,this.frameClient,this.unaryClient).set({[e]:n})}async deleteAlias(t,e){await new st(t,this.frameClient,this.unaryClient).delete(e)}sugarOne(t){return new Zu(t,{frameClient:this.frameClient,kv:new ct(t.key,this.unaryClient),aliaser:new st(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 B(t.data?.timeRange),color:t.data?.color,labels:[],parent:null})}};const St=t=>({type:"range",key:t}),mk=t=>({type:"range-alias",key:t}),Du=({data:t,id:{key:e},name:n})=>{const r=B.z.parse(t?.timeRange);return{key:e,name:n,timeRange:r,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},gk=a.z.object({ranges:_n.array()}),wk=a.z.object({parent:R.optional(),ranges:_u.array()}),bk=a.z.object({keys:Q.array()}),vk=a.z.object({}),zk=a.z.object({key:Q,name:Ra}),Tk=a.z.object({}),Ok="/range/create",Sk="/range/delete",kk="/range/rename";class Bu{client;constructor(e){this.client=e}async rename(e,n){await g(this.client,kk,{key:e,name:n},zk,Tk)}async create(e,n){return(await g(this.client,Ok,{ranges:e,...n},wk,gk)).ranges}async delete(e){await g(this.client,Sk,{keys:e},bk,vk)}}const Nk=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:st,Client:Lu,DELETE_ALIAS_CHANNEL_NAME:F0,DELETE_CHANNEL_NAME:hk,KV:ct,KV_DELETE_CHANNEL:sk,KV_SET_CHANNEL:rk,Range:Zu,SET_ALIAS_CHANNEL_NAME:B0,SET_CHANNEL_NAME:uk,Writer:Bu,aliasKey:tk,aliasOntologyID:mk,aliasZ:ek,convertOntologyResourceToPayload:Du,decodeDeleteAliasChange:nk,keyZ:Q,kvPairKey:ak,kvPairZ:Za,nameZ:Ra,newZ:_u,ontologyID:St,payloadZ:_n},Symbol.toStringTag,{value:"Module"})),Ek=t=>a.object({parent:R.optional(),statuses:Il(t).array()}),Ak=t=>a.object({statuses:Cn(t).array()}),Ik=a.object({keys:Ir.array()}),xk=a.object({}),Ck="/status/set",jk="/status/delete",$k="/status/retrieve",Mk=a.object({keys:Ir.array().optional(),searchTerm:a.string().optional(),offset:a.number().optional(),limit:a.number().optional(),includeLabels:a.boolean().optional(),hasLabels:et.array().optional()}),Uk=a.object({key:Ir,includeLabels:a.boolean().optional()}).transform(({key:t,includeLabels:e})=>({keys:[t],includeLabels:e})),Pk=a.union([Uk,Mk]),_k=t=>a.object({statuses:b.nullableZ(Cn(t))});let Fu=class{type="status";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,n=await g(this.client,$k,t,Pk,_k(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 g(this.client,Ck,{statuses:b.toArray(t),parent:e.parent},Ek(e.detailsSchema),Ak(e.detailsSchema))).statuses;return n?r:r[0]}async delete(t){await g(this.client,jk,{keys:b.toArray(t)},Ik,xk)}};const Rk=Object.freeze(Object.defineProperty({__proto__:null,Client:Fu,DELETE_CHANNEL_NAME:ST,SET_CHANNEL_NAME:OT,keyZ:Ir,newZ:Il,ontologyID:kT,statusZ:Cn},Symbol.toStringTag,{value:"Module"})),Zk="/api/v1/";class Lk{url;unary;stream;secure;constructor(e,n={},r=!1){this.secure=r,this.url=e.child(Zk);const s=new dt.JSONCodec;this.unary=Pf(new Uf(this.url,s,this.secure),n),this.stream=new ar(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const pt=a.z.uuid(),_r=a.z.object({key:pt,name:a.z.string(),data:Te.unknownZ.or(a.z.string().transform(je))}),qu=_r.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),$e=a.z.uuid(),Rr=a.z.object({key:$e,name:a.z.string().min(1,"Name is required"),layout:Te.unknownZ.or(a.z.string().transform(je))}),Yu=Rr.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),Vu=Rr.omit({layout:!0}).extend({layout:a.z.string().transform(je)}),Dk="/workspace/lineplot/retrieve",Bk="/workspace/lineplot/create",Fk="/workspace/lineplot/rename",qk="/workspace/lineplot/set-data",Yk="/workspace/lineplot/delete",Vk=a.z.object({key:pt,name:a.z.string()}),Wk=a.z.object({key:pt,data:a.z.string()}),Hk=a.z.object({keys:pt.array()}),Gk=a.z.object({keys:pt.array()}),Wu=a.z.object({key:pt}).transform(({key:t})=>({keys:[t]})),Hu=a.z.union([Wu,Gk]),Kk=a.z.object({linePlots:b.nullableZ(_r)}),Jk=a.z.object({workspace:$e,linePlots:qu.array()}),Xk=a.z.object({linePlots:_r.array()}),rs=a.z.object({});let Gu=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await g(this.client,Bk,{workspace:t,linePlots:b.toArray(e)},Jk,Xk);return n?r.linePlots:r.linePlots[0]}async rename(t,e){await g(this.client,Fk,{key:t,name:e},Vk,rs)}async setData(t,e){await g(this.client,qk,{key:t,data:JSON.stringify(e)},Wk,rs)}async retrieve(t){const e=Wu.safeParse(t).success,n=await g(this.client,Dk,t,Hu,Kk);return ue("LinePlot",t,n.linePlots,e),e?n.linePlots[0]:n.linePlots}async delete(t){await g(this.client,Yk,{keys:b.toArray(t)},Hk,rs)}};const Qk=t=>({type:"lineplot",key:t}),eN=Object.freeze(Object.defineProperty({__proto__:null,Client:Gu,keyZ:pt,linePlotZ:_r,newZ:qu,ontologyID:Qk,retrieveArgsZ:Hu},Symbol.toStringTag,{value:"Module"})),yt=a.z.uuid(),Zr=a.z.object({key:yt,name:a.z.string(),data:Te.unknownZ.or(a.z.string().transform(je))}),Ku=Zr.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),tN="/workspace/log/retrieve",nN="/workspace/log/create",rN="/workspace/log/rename",sN="/workspace/log/set-data",aN="/workspace/log/delete",iN=a.z.object({key:yt,name:a.z.string()}),oN=a.z.object({key:yt,data:a.z.string()}),cN=a.z.object({keys:yt.array()}),lN=a.z.object({keys:yt.array()}),Ju=a.z.object({key:yt}).transform(({key:t})=>({keys:[t]})),Xu=a.z.union([Ju,lN]),uN=a.z.object({logs:b.nullableZ(Zr)}),hN=a.z.object({workspace:$e,logs:Ku.array()}),dN=a.z.object({logs:Zr.array()}),ss=a.z.object({});let Qu=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await g(this.client,nN,{workspace:t,logs:b.toArray(e)},hN,dN);return n?r.logs:r.logs[0]}async rename(t,e){await g(this.client,rN,{key:t,name:e},iN,ss)}async setData(t,e){await g(this.client,sN,{key:t,data:JSON.stringify(e)},oN,ss)}async retrieve(t){const e=Ju.safeParse(t).success,n=await g(this.client,tN,t,Xu,uN);return ue("Log",t,n.logs,e),e?n.logs[0]:n.logs}async delete(t){await g(this.client,aN,{keys:b.toArray(t)},cN,ss)}};const fN=t=>({type:"log",key:t}),pN=Object.freeze(Object.defineProperty({__proto__:null,Client:Qu,keyZ:yt,logZ:Zr,newZ:Ku,ontologyID:fN,retrieveArgsZ:Xu},Symbol.toStringTag,{value:"Module"})),tt=a.z.uuid(),Lr=a.z.object({key:tt,name:a.z.string(),data:Te.unknownZ.or(a.z.string().transform(je)),snapshot:a.z.boolean()}),eh=Lr.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),La=Lr.extend({data:a.z.string().transform(je)}),qt=a.z.uuid(),th=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()}),nh=a.z.object({key:a.z.string(),name:a.z.string(),regions:th.array()}),rh=a.z.object({key:a.z.string(),position:ha.xy,orientation:Bp.outer}),yN=a.z.object({zoom:a.z.number().positive().default(1),position:ha.xy}),sh=a.z.object({svg:a.z.string().min(1,"SVG is required"),states:nh.array(),variant:a.z.string().min(1,"Variant is required"),handles:rh.array(),scale:a.z.number().positive().default(1),scaleStroke:a.z.boolean().default(!1),previewViewport:yN.default({zoom:1,position:{x:0,y:0}})}),Dr=a.z.object({key:qt,version:a.z.literal(1).optional().default(1),name:a.z.string().min(1,"Name is required"),data:sh}),ah=Dr.partial({key:!0}),mN="/workspace/schematic/symbol/retrieve",gN="/workspace/schematic/symbol/create",wN="/workspace/schematic/symbol/rename",bN="/workspace/schematic/symbol/delete",vN="/workspace/schematic/symbol/retrieve_group",zN=a.z.object({symbols:ah.array(),parent:R}),TN=a.z.object({key:qt,name:a.z.string()}),ON=a.z.object({keys:qt.array()}),SN=a.z.object({keys:qt.array().optional(),searchTerm:a.z.string().optional(),offset:a.z.number().optional(),limit:a.z.number().optional()}),kN=a.z.object({key:qt}).transform(({key:t})=>({keys:[t]})),NN=a.z.union([kN,SN]),EN=a.z.object({symbols:b.nullableZ(Dr)}),AN=a.z.object({symbols:Dr.array()}),to=a.z.object({}),IN=a.z.object({}),xN=a.z.object({group:Or}),CN="sy_schematic_symbol_set",jN="sy_schematic_symbol_delete";let ih=class{client;constructor(t){this.client=t}async create(t){const e="symbols"in t,n=e?t.symbols:[t],r=await g(this.client,gN,{symbols:n,parent:t.parent},zN,AN);return e?r.symbols:r.symbols[0]}async rename(t,e){await g(this.client,wN,{key:t,name:e},TN,to)}async retrieve(t){const e="key"in t,n=await g(this.client,mN,t,NN,EN);return ue("Schematic Symbol",t,n.symbols,e),e?n.symbols[0]:n.symbols}async delete(t){await g(this.client,bN,{keys:b.toArray(t)},ON,to)}async retrieveGroup(){return(await g(this.client,vN,{},IN,xN)).group}};const $N=t=>({type:"schematic_symbol",key:t}),MN=Object.freeze(Object.defineProperty({__proto__:null,Client:ih,DELETE_CHANNEL_NAME:jN,SET_CHANNEL_NAME:CN,handleZ:rh,keyZ:qt,newZ:ah,ontologyID:$N,regionZ:th,specZ:sh,stateZ:nh,symbolZ:Dr},Symbol.toStringTag,{value:"Module"})),UN="/workspace/schematic/retrieve",PN="/workspace/schematic/create",_N="/workspace/schematic/rename",RN="/workspace/schematic/set-data",ZN="/workspace/schematic/delete",LN="/workspace/schematic/copy",DN=a.z.object({key:tt,name:a.z.string()}),BN=a.z.object({key:tt,data:a.z.string()}),FN=a.z.object({keys:tt.array()}),qN=a.z.object({key:tt,name:a.z.string(),snapshot:a.z.boolean()}),YN=a.z.object({keys:tt.array()}),oh=a.z.object({key:tt}).transform(({key:t})=>({keys:[t]})),ch=a.z.union([oh,YN]),VN=a.z.object({schematics:b.nullableZ(La)}),WN=a.z.object({workspace:$e,schematics:eh.array()}),HN=a.z.object({schematics:La.array()}),GN=a.z.object({schematic:Lr}),as=a.z.object({});let lh=class{symbols;client;constructor(t){this.client=t,this.symbols=new ih(t)}async create(t,e){const n=Array.isArray(e),r=await g(this.client,PN,{workspace:t,schematics:b.toArray(e)},WN,HN);return n?r.schematics:r.schematics[0]}async rename(t,e){await g(this.client,_N,{key:t,name:e},DN,as)}async setData(t,e){await g(this.client,RN,{key:t,data:JSON.stringify(e)},BN,as)}async retrieve(t){const e=oh.safeParse(t).success,n=await g(this.client,UN,t,ch,VN);return ue("Schematic",t,n.schematics,e),e?n.schematics[0]:n.schematics}async delete(t){await g(this.client,ZN,{keys:b.toArray(t)},FN,as)}async copy(t){return(await g(this.client,LN,t,qN,GN)).schematic}};const KN=t=>({type:"schematic",key:t}),JN=Object.freeze(Object.defineProperty({__proto__:null,Client:lh,keyZ:tt,newZ:eh,ontologyID:KN,remoteZ:La,retrieveArgsZ:ch,schematicZ:Lr,symbol:MN},Symbol.toStringTag,{value:"Module"})),mt=a.z.uuid(),Da=a.z.object({key:mt,name:a.z.string(),data:Te.unknownZ.or(a.z.string().transform(je))}),uh=Da.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),Ba=Da.extend({data:a.z.string().transform(je)}),XN="/workspace/table/retrieve",QN="/workspace/table/create",eE="/workspace/table/rename",tE="/workspace/table/set-data",nE="/workspace/table/delete",rE=a.z.object({key:mt,name:a.z.string()}),sE=a.z.object({key:mt,data:a.z.string()}),aE=a.z.object({keys:mt.array()}),iE=a.z.object({keys:mt.array()}),hh=a.z.object({key:mt}).transform(({key:t})=>({keys:[t]})),dh=a.z.union([hh,iE]),oE=a.z.object({tables:b.nullableZ(Ba)}),cE=a.z.object({workspace:$e,tables:uh.array()}),lE=a.z.object({tables:Ba.array()}),is=a.z.object({});let fh=class{client;constructor(t){this.client=t}async create(t,e){const n=Array.isArray(e),r=await g(this.client,QN,{workspace:t,tables:b.toArray(e)},cE,lE);return n?r.tables:r.tables[0]}async rename(t,e){await g(this.client,eE,{key:t,name:e},rE,is)}async setData(t,e){await g(this.client,tE,{key:t,data:JSON.stringify(e)},sE,is)}async retrieve(t){const e=hh.safeParse(t).success,n=await g(this.client,XN,t,dh,oE);return ue("Table",t,n.tables,e),e?n.tables[0]:n.tables}async delete(t){await g(this.client,nE,{keys:b.toArray(t)},aE,is)}};const uE=t=>({type:"table",key:t}),hE=Object.freeze(Object.defineProperty({__proto__:null,Client:fh,keyZ:mt,newZ:uh,ontologyID:uE,remoteZ:Ba,retrieveArgsZ:dh,tableZ:Da},Symbol.toStringTag,{value:"Module"})),no="/workspace/retrieve",dE="/workspace/create",fE="/workspace/rename",pE="/workspace/set-layout",yE="/workspace/delete",ro=a.z.object({keys:$e.array().optional(),searchTerm:a.z.string().optional(),author:Qe.optional(),offset:a.z.number().optional(),limit:a.z.number().optional()}),mE=a.z.object({workspaces:Yu.array()}),gE=a.z.object({key:$e,name:a.z.string()}),wE=a.z.object({key:$e,layout:Te.unknownZ.transform(t=>JSON.stringify(t))}),bE=a.z.object({keys:$e.array()}),so=a.z.object({workspaces:b.nullableZ(Rr)}),vE=a.z.object({workspaces:Vu.array()}),os=a.z.object({}),zE="sy_workspace_set",TE="sy_workspace_delete";class ph{schematics;lineplots;logs;tables;client;constructor(e){this.client=e,this.schematics=new lh(e),this.lineplots=new Gu(e),this.logs=new Qu(e),this.tables=new fh(e)}async create(e){const n=Array.isArray(e),r=await g(this.client,dE,{workspaces:b.toArray(e)},mE,vE);return n?r.workspaces:r.workspaces[0]}async rename(e,n){await g(this.client,fE,{key:e,name:n},gE,os)}async setLayout(e,n){await g(this.client,pE,{key:e,layout:n},wE,os)}async retrieve(e){let n;const r=typeof e!="string";typeof e=="string"||Array.isArray(e)?n={keys:b.toArray(e)}:n=e;const s=await g(this.client,no,n,ro,so);return r?s.workspaces:s.workspaces[0]}async retrieveByAuthor(e){return(await g(this.client,no,{author:e},ro,so)).workspaces}async delete(e){await g(this.client,yE,{keys:b.toArray(e)},bE,os)}}const OE=t=>({type:"workspace",key:t}),SE=Object.freeze(Object.defineProperty({__proto__:null,Client:ph,DELETE_CHANNEL_NAME:TE,SET_CHANNEL_NAME:zE,keyZ:$e,newZ:Yu,ontologyID:OE,remoteZ:Vu,workspaceZ:Rr},Symbol.toStringTag,{value:"Module"})),yh=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:E.z.default(E.seconds(30)),secure:a.z.boolean().optional().default(!1),name:a.z.string().optional(),retry:$c.breakerConfigZ.optional()});class kE extends hu{createdAt;props;ranges;channels;auth;users;access;connectivity;ontology;workspaces;labels;statuses;hardware;control;arcs;static connectivity=fr;transport;clientVersion="0.47.0";constructor(e){const n=yh.parse(e),{host:r,port:s,username:i,password:o,connectivityPollFrequency:c,secure:l,retry:u}=n,h=new Lk(new rn({host:r,port:Number(s)}),u,l);h.use(vg);let f;i!=null&&o!=null&&(f=new qO(h.unary,{username:i,password:o}),h.use(f.middleware()));const d=new xa(new $n(h.unary)),O=new Gl(h.unary,d);super(h.stream,h.unary,d),this.createdAt=x.now(),this.props=n,this.auth=f,this.transport=h,this.channels=new Vl(this,d,h.unary,O),this.connectivity=new fr(h.unary,c,this.clientVersion,n.name),this.control=new pu(this),this.ontology=new rl(h.unary,this);const C=new Bu(this.transport.unary);this.labels=new Pu(this.transport.unary),this.statuses=new Fu(this.transport.unary),this.ranges=new Lu(this,C,this.transport.unary,d,this.labels,this.ontology),this.access=new dw(this.transport.unary),this.users=new Jl(this.transport.unary),this.workspaces=new ph(this.transport.unary);const j=new Tu(this.transport.unary),w=new xu(this.transport.unary,this,this.ontology,this.ranges),v=new Ou(this.transport.unary,w);this.hardware=new SS(w,v,j),this.arcs=new Rl(this.transport.unary,this.transport.stream)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}E.seconds(1);let NE=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=EE(e,this.sender),r=new AE(n);return this.handlers.set(e,r),r}};const EE=(t,e)=>(n,r)=>e({type:t,payload:n},r);class AE{_send;handler;constructor(e){this._send=e,this.handler=null}send(e,n=[]){this._send(e,n)}handle(e){this.handler=e}}const Ys=(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}},IE=a.z.object({l0:A.Lr.colorZ,l1:A.Lr.colorZ,l2:A.Lr.colorZ,l3:A.Lr.colorZ,l4:A.Lr.colorZ,l5:A.Lr.colorZ,l6:A.Lr.colorZ,l7:A.Lr.colorZ,l8:A.Lr.colorZ,l9:A.Lr.colorZ,l10:A.Lr.colorZ,l11:A.Lr.colorZ}),fe=(t,e)=>[t[0],t[1],e,t[3]],xE=a.z.object({m2:A.Lr.colorZ,m1:A.Lr.colorZ,z:A.Lr.colorZ,p1:A.Lr.colorZ,p2:A.Lr.colorZ}),Kn=xE.or(A.Lr.colorZ.transform(t=>{const e=A.Lr.hsla(t);return{m2:A.Lr.fromHSLA(fe(e,40)),m1:A.Lr.fromHSLA(fe(e,45)),z:t,p1:A.Lr.fromHSLA(fe(e,55)),p2:A.Lr.fromHSLA(fe(e,65))}})),mh=a.z.object({name:a.z.string(),key:a.z.string(),colors:a.z.object({border:A.Lr.colorZ,primary:Kn,gray:IE,error:Kn,secondary:Kn,warning:Kn,palettes:a.z.record(a.z.string(),A.Lr.paletteZ),visualization:a.z.object({palettes:a.z.record(a.z.string(),a.z.array(A.Lr.colorZ))}).optional().default({palettes:{}}),white:A.Lr.colorZ,black:A.Lr.colorZ,text:A.Lr.colorZ,textInverted:A.Lr.colorZ,textOnPrimary:A.Lr.colorZ.optional().default(A.Lr.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:De.specZ,h2:De.specZ,h3:De.specZ,h4:De.specZ,h5:De.specZ,p:De.specZ,small:De.specZ})}).transform(t=>((t.colors.textOnPrimary==null||A.Lr.isZero(t.colors.textOnPrimary))&&(t.colors.textOnPrimary=A.Lr.pickByContrast(t.colors.primary.z,t.colors.text,t.colors.textInverted)),t)),CE='"Inter Variable", sans-serif',jE='"Geist Mono", monospace',$E=6,Vt=[357,91,55,1],Wt=[48,90,55,1],ME=["#FEFEFE","#FAFAFA","#F2F2F2","#ECECEC","#E4E4E4","#D1D1D1","#BCBCBC","#ACACAC","#8F8F8F","#4F4F4F","#292929","#050505"],Ht=Object.fromEntries(ME.map((t,e)=>[`l${e}`,t])),UE=()=>typeof window>"u"?!1:window.devicePixelRatio>1,PE=UE(),Vs={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:Ht,border:Ht.l4,error:{m2:A.Lr.fromHSLA(fe(Vt,30)),m1:A.Lr.fromHSLA(fe(Vt,40)),z:A.Lr.fromHSLA(Vt),p1:A.Lr.fromHSLA(fe(Vt,65)),p2:A.Lr.fromHSLA(fe(Vt,77))},warning:{m2:A.Lr.fromHSLA(fe(Wt,30)),m1:A.Lr.fromHSLA(fe(Wt,40)),z:A.Lr.fromHSLA(Wt),p1:A.Lr.fromHSLA(fe(Wt,65)),p2:A.Lr.fromHSLA(fe(Wt,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:Ht.l11,textInverted:Ht.l0,textOnPrimary:Ht.l0},sizes:{base:$E,border:{radius:3,width:PE?.5:1,thickWidth:1},schematic:{elementStrokeWidth:2}},typography:{family:CE,codeFamily:jE,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}}},gh=Object.freeze({...Vs,key:"synnaxLight",name:"Synnax Light"}),_E=["#020202","#080808","#151515","#202020","#272727","#3B3B3B","#4A4A4A","#5C5C5C","#767676","#959595","#dadada","#FAFAFA"],Gt=Object.fromEntries(_E.map((t,e)=>[`l${e}`,t])),wh=Object.freeze({...Vs,key:"synnaxDark",name:"Synnax Dark",colors:{...Vs.colors,gray:Gt,logo:"var(--pluto-text-color)",border:Gt.l4,text:Gt.l11,textInverted:Gt.l0,textOnPrimary:Gt.l11}}),RE={synnaxDark:wh,synnaxLight:gh},bh=["tiny","small","medium","large","huge"],vh=a.z.enum(bh),ZE=t=>vh.safeParse(t).success;class jt{_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 jt(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}static NOOP=new jt("","","")}const Ws=["debug","info","warn","error"],zh=t=>{const e=Ws.indexOf(t);return({level:n})=>Ws.indexOf(n)>=e},LE=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 $t{meta=jt.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 $t({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,Jn(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,Jn(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,Jn(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,Jn(n)))}static NOOP=new $t}const Jn=t=>typeof t=="function"?t():t;var DE=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},it="1.9.0",ao=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function BE(t){var e=new Set([t]),n=new Set,r=t.match(ao);if(!r)return function(){return!1};var s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(s.prerelease!=null)return function(c){return c===t};function i(c){return n.add(c),!1}function o(c){return e.add(c),!0}return function(c){if(e.has(c))return!0;if(n.has(c))return!1;var l=c.match(ao);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||s.major!==u.major?i(c):s.major===0?s.minor===u.minor&&s.patch<=u.patch?o(c):i(c):s.minor<=u.minor?o(c):i(c)}}var FE=BE(it),qE=it.split(".")[0],yn=Symbol.for("opentelemetry.js.api."+qE),mn=DE;function Fa(t,e,n,r){var s;r===void 0&&(r=!1);var i=mn[yn]=(s=mn[yn])!==null&&s!==void 0?s:{version:it};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!==it){var o=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+it);return n.error(o.stack||o.message),!1}return i[t]=e,n.debug("@opentelemetry/api: Registered a global for "+t+" v"+it+"."),!0}function gn(t){var e,n,r=(e=mn[yn])===null||e===void 0?void 0:e.version;if(!(!r||!FE(r)))return(n=mn[yn])===null||n===void 0?void 0:n[t]}function qa(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+it+".");var n=mn[yn];n&&delete n[t]}var YE=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},VE=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))},WE=(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 Kt("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Kt("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Kt("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Kt("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Kt("verbose",this._namespace,e)},t})();function Kt(t,e,n){var r=gn("diag");if(r)return n.unshift(e),r[t].apply(r,VE([],YE(n),!1))}var oe;(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"})(oe||(oe={}));function HE(t,e){t<oe.NONE?t=oe.NONE:t>oe.ALL&&(t=oe.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",oe.ERROR),warn:n("warn",oe.WARN),info:n("info",oe.INFO),debug:n("debug",oe.DEBUG),verbose:n("verbose",oe.VERBOSE)}}var GE=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},KE=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))},JE="diag",wn=(function(){function t(){function e(s){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var c=gn("diag");if(c)return c[s].apply(c,KE([],GE(i),!1))}}var n=this,r=function(s,i){var o,c,l;if(i===void 0&&(i={logLevel:oe.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=gn("diag"),f=HE((c=i.logLevel)!==null&&c!==void 0?c:oe.INFO,s);if(h&&!i.suppressOverrideMessage){var d=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";h.warn("Current logger will be overwritten from "+d),f.warn("Current logger will overwrite one already registered from "+d)}return Fa("diag",f,n,!0)};n.setLogger=r,n.disable=function(){qa(JE,n)},n.createComponentLogger=function(s){return new WE(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})(),XE=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},QE=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.")},eA=(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=XE(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=QE(r),c=o.next();!c.done;c=o.next()){var l=c.value;i._entries.delete(l)}}catch(u){e={error:u}}finally{try{c&&!c.done&&(n=o.return)&&n.call(o)}finally{if(e)throw e.error}}return i},t.prototype.clear=function(){return new t},t})();wn.instance();function tA(t){return t===void 0&&(t={}),new eA(new Map(Object.entries(t)))}function nA(t){return Symbol.for(t)}var rA=(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})(),sA=new rA,aA={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},iA={set:function(t,e,n){t!=null&&(t[e]=n)}},oA=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},cA=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))},lA=(function(){function t(){}return t.prototype.active=function(){return sA},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,cA([r],oA(s),!1))},t.prototype.bind=function(e,n){return n},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),uA=function(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(c){o={error:c}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},hA=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))},cs="context",dA=new lA,Th=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Fa(cs,e,wn.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,hA([e,n,r],uA(i),!1))},t.prototype.bind=function(e,n){return this._getContextManager().bind(e,n)},t.prototype._getContextManager=function(){return gn(cs)||dA},t.prototype.disable=function(){this._getContextManager().disable(),qa(cs,wn.instance())},t})(),Hs;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Hs||(Hs={}));var fA=Th.getInstance(),pA=(function(){function t(){}return t.prototype.inject=function(e,n){},t.prototype.extract=function(e,n){return e},t.prototype.fields=function(){return[]},t})(),Ya=nA("OpenTelemetry Baggage Key");function Oh(t){return t.getValue(Ya)||void 0}function yA(){return Oh(Th.getInstance().active())}function mA(t,e){return t.setValue(Ya,e)}function gA(t){return t.deleteValue(Ya)}var ls="propagation",wA=new pA,bA=(function(){function t(){this.createBaggage=tA,this.getBaggage=Oh,this.getActiveBaggage=yA,this.setBaggage=mA,this.deleteBaggage=gA}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return Fa(ls,e,wn.instance())},t.prototype.inject=function(e,n,r){return r===void 0&&(r=iA),this._getGlobalPropagator().inject(e,n,r)},t.prototype.extract=function(e,n,r){return r===void 0&&(r=aA),this._getGlobalPropagator().extract(e,n,r)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){qa(ls,wn.instance())},t.prototype._getGlobalPropagator=function(){return gn(ls)||wA},t})(),vA=bA.getInstance();const io=["bench","debug","prod"],zA=t=>e=>io.indexOf(e)>=io.indexOf(t);class bn{meta=jt.NOOP;otelTracer;filter;constructor(e,n=zA("debug")){this.otelTracer=e,this.filter=n}child(e){const n=new bn(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 Gs(e,this.otelTracer.startSpan(e));return i.start(),()=>i.end()}return s?r(new Sh(e)):this.otelTracer.startActiveSpan(e,i=>{const o=new Gs(e,i);return r(o)})}propagate(e){if(this.meta.noop)return;const n=fA.active();vA.inject(n,e,{set:(r,s,i)=>{r[s]=i}})}static NOOP=new bn}class Gs{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:Hs.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 Sh{key;constructor(e){this.key=e}set(){}recordError(e){}}class Mt{meta;T;L;constructor({key:e="",serviceName:n="",logger:r=$t.NOOP,tracer:s=bn.NOOP,noop:i=!1,__meta:o}){this.meta=o??new jt(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 Mt({__meta:n,tracer:this.T,logger:this.L})}static NOOP=new Mt({noop:!0})}const TA=Mt.NOOP,kh=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:Mt,LOG_LEVELS:Ws,Logger:$t,NOOP:TA,NoopSpan:Sh,Tracer:bn,_Span:Gs,logLevelKeyFiler:LE,logThresholdFilter:zh},Symbol.toStringTag,{value:"Module"})),us=(t,e)=>t instanceof Error?(t.message=`[${e}] - ${t.message}`,t):new Error(e??"unknown error",{cause:t});class Va{type;key;sender;_internalState;_state;_prevState;_deleted=!1;parentCtxValues;childCtxValues;childCtxChangedKeys;instrumentation;schema=void 0;constructor({key:e,type:n,sender:r,instrumentation:s,parentCtxValues:i}){this.type=n,this.key=e,this.sender=r,this._internalState={},this.instrumentation=s.child(this.toString()),this.parentCtxValues=new Map,i?.forEach((o,c)=>this.parentCtxValues.set(c,o)),this.childCtxValues=new Map,this.childCtxChangedKeys=new Set}get _schema(){if(this.schema==null)throw new V(`[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=De.executeSetter(e,this.state);this._prevState=A.Qr(this._state),this._state=Ys(this._schema,n,`${this.toString()}`),this.sender.send({variant:"update",key:this.key,state:this._state})}get state(){if(this._state==null)throw new le(`[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 xt(`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=Ys(this._schema,n,`${this.toString()}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:_h.T.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 us(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 us(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 us(n,`[${this.toString()}:delete]`)}}afterUpdate(e){}afterDelete(e){}validatePath(e){if(e.length===0)throw new le(`[Leaf.setState] - ${this.toString()} received an empty path`);const n=e[e.length-1];if(e.length>1)throw new le(`[Leaf.setState] - ${this.toString()} received a subPath ${e.join(".")} but is a leaf`);if(n!==this.key)throw new le(`[Leaf.setState] - ${this.toString()} received a key ${n} but expected ${this.key}`)}}class Rn extends Va{_children=new Map;get children(){return Array.from(this._children.values())}getChild(e){return this._children.get(e)??null}childrenOfType(...e){return this.children.filter(n=>e.includes(n.type))}_updateState(e){const{path:n,type:r,create:s}=e;if(this.deleted)return;const i=this.parsePath(n);if(i.length===0){if(this.childCtxChangedKeys.clear(),super._updateState(e),this.childCtxChangedKeys.size==0)return;this.updateChildContexts();return}const c=i[0],l=this.getChild(c);if(l!=null)return l._updateState({...e,path:i});if(i.length>1){const h=n.slice(0,n.indexOf(c)+1).join("."),f=n.join(".");throw new le(`Child of ${this.toString()} at path ${h} does not exist,
66
- but an extended path ${f} 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(d=>`${d.type}:${d.key}`).join(".")}
71
-
72
- `)}const u=s(this.childCtx());u._updateState({...e,path:i}),this._children.set(c,u)}_updateContext(e){super._updateContext(e),this.updateChildContexts()}childCtx(){return{get:e=>this.childCtxValues.get(e)??this.parentCtxValues.get(e),forEach:e=>{this.childCtxValues.forEach((n,r)=>e(n,r,this.childCtxValues)),this.parentCtxValues.forEach((n,r)=>{this.childCtxValues.has(r)||e(n,r,this.parentCtxValues)})}}}updateChildContexts(){const e=this.childCtx();this.children.forEach(n=>n._updateContext(e))}_delete(e){const n=this.parsePath(e);if(n.length===0){for(const s of this.children)s._delete([s.key]);this._children.clear(),super._delete([this.key])}const r=this.getChild(n[0]);if(r!=null){if(n.length>1)return r._delete(n);this._children.delete(r.key),r._delete(n)}}parsePath(e,n){const[r,...s]=e;if(r==null)throw new Error(`Composite ${this.toString()} received an empty path${n!=null?` for ${n}`:""}`);if(r!==this.key)throw new le(`[Composite.getRequiredKey] - ${this.toString()} received a key ${r} but expected ${this.key}`);return s}}const OA=a.z.object({}),SA=()=>{throw new Error("should not call create")};class Ye extends Rn{static TYPE="root";static KEY="root";comms;registry;schema=OA;constructor({comms:e,instrumentation:n=kh.Instrumentation.NOOP,registry:r}){super({key:Ye.KEY,type:Ye.TYPE,sender:e,instrumentation:n,parentCtxValues:null}),this.comms=e,this.registry=r}static render(e){const n=new Ye(e);return n._updateState({path:[Ye.KEY],type:"",state:{},create:SA}),n.comms.handle(r=>{try{n.handle(r)}catch(s){const i={name:"unknown",message:JSON.stringify(s),stack:"unknown"};s instanceof Error&&(i.name=s.name,i.message=s.message,i.stack=s.stack),n.comms.send({variant:"error",error:i})}}),n}handle(e){const{path:n,variant:r,type:s}=e;if(r==="delete"){this._delete(n);return}const{state:i}=e;this._updateState({path:n,type:s,state:i,create:o=>{const c=n[n.length-1];return this.create({key:c,type:s,parentCtxValues:o})}})}create({key:e,type:n,parentCtxValues:r}){const s=this.registry[n];if(s==null)throw new le(`[Root.create] - ${n} not found in registry`);return new s({key:e,type:n,sender:this.comms,instrumentation:this.instrumentation,parentCtxValues:r})}}const Nh=Ye.render.bind(Ye),kA=Object.freeze(Object.defineProperty({__proto__:null,Composite:Rn,Leaf:Va,Root:Ye,render:Nh},Symbol.toStringTag,{value:"Module"})),NA=(t,e)=>Array.isArray(e)?e.some(n=>n.matches(t)):e?.matches(t)??!1,Eh=(t,e,n)=>{const r=A.Yr.fromException(t,e);return console.error(r),NA(t,n)?null:r},Ah=(t,e,n,r)=>{if(typeof t=="function")return!0;const s=Eh(t,n,r);return s!=null&&e(s),!1},Ih=async(t,e,n,r)=>{try{const s=t();s!=null&&await s}catch(s){const i=Eh(s,n,r);if(i!=null)return e(i)}},xh=t=>(e,n,r)=>{Ah(e,t,n,r)&&Ih(e,t,n,r)},Ch=t=>async(e,n,r)=>{Ah(e,t,n,r)&&await Ih(e,t,n,r)},jh=a.z.object({statuses:A.Yr.statusZ().array()}),yr="status.aggregator";class Ks extends Rn{static TYPE="status.Aggregator";schema=jh;afterUpdate(e){e.wasSetPreviously(yr)||e.set(yr,{add:this.add.bind(this),create:A.Yr.create})}add(e){this.setState(n=>({...n,statuses:[...n.statuses,A.Yr.create(e)]}))}}const Wa=t=>t.get(yr).add,EA=t=>{const e=t.getOptional(yr);return e!=null?e.add:()=>{}},$h=t=>xh(Wa(t)),AA=t=>Ch(Wa(t)),IA={[Ks.TYPE]:Ks},Js="pluto-theming-context",Mh=a.z.object({name:a.z.string(),url:a.z.string()}),xA=a.z.object({theme:mh,fontURLs:a.z.array(Mh)});class vn extends Rn{static TYPE="theming.Provider";static z=xA;schema=vn.z;afterUpdate(e){if(e.getOptional(Js)!=null&&this.state.theme.key===this.prevState.theme.key)return;e.set(Js,this.state.theme),$h(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 CA=t=>t.get(Js),jA={[vn.TYPE]:vn};exports.$I=Rg;exports.AI=Jg;exports.Aggregator=Ks;exports.Bt=le;exports.Composite=Rn;exports.DI=yO;exports.EI=gg;exports.GI=LS;exports.JI=r0;exports.JS=yh;exports.Leaf=Va;exports.O=Mt;exports.Pr=xt;exports.Provider=vn;exports.QI=O0;exports.REGISTRY=jA;exports.REGISTRY$1=IA;exports.SIZES=bh;exports.SYNNAX_DARK=wh;exports.SYNNAX_LIGHT=gh;exports.SYNNAX_THEMES=RE;exports.UI=PO;exports.VI=OS;exports.W=V;exports.XS=kE;exports._=$t;exports._I=qT;exports.aether=kA;exports.aggregatorStateZ=jh;exports.be=zh;exports.createAsyncErrorHandler=Ch;exports.createErrorHandler=xh;exports.d=NE;exports.fA=JN;exports.fontSpecZ=Mh;exports.g=kh;exports.iA=Rk;exports.isSize=ZE;exports.j=P;exports.k=E;exports.nA=Nk;exports.nt=Ke;exports.oA=eN;exports.pA=hE;exports.prettyParse=Ys;exports.qI=gS;exports.render=Nh;exports.size=vh;exports.tA=D0;exports.themeZ=mh;exports.uA=pN;exports.use=CA;exports.useAdder=Wa;exports.useAsyncErrorHandler=AA;exports.useErrorHandler=$h;exports.useOptionalAdder=EA;exports.y=x;exports.yA=SE;