@synnaxlabs/pluto 0.44.2 → 0.44.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/dist/Animated-BDoJWl9g.cjs +1 -0
  2. package/dist/{Animated-D5cL3URg.js → Animated-fI-NFaha.js} +2 -2
  3. package/dist/{symbols-Lz5vQQDw.js → Editable-C1g_CFYk.js} +7836 -7781
  4. package/dist/{symbols-B15FeAg9.cjs → Editable-DUtJOqJ5.cjs} +45 -45
  5. package/dist/LinePlot-6cl8_hmn.cjs +53 -0
  6. package/dist/{provider-Bp-CLkh2.js → LinePlot-Ck0rhtFk.js} +4563 -4484
  7. package/dist/{Toggle-Dol9oHzM.js → Toggle-DEJ8Uvun.js} +1 -1
  8. package/dist/Toggle-DUKDeqpe.cjs +1 -0
  9. package/dist/{Video-Cm8ZBqid.js → Video-B6tujjr8.js} +1 -1
  10. package/dist/{Video-BidrtYj_.cjs → Video-BjRd9sFv.cjs} +1 -1
  11. package/dist/button.cjs +1 -1
  12. package/dist/button.js +1 -1
  13. package/dist/color.cjs +1 -1
  14. package/dist/color.js +1 -1
  15. package/dist/css-DI0uCCGq.cjs +8 -0
  16. package/dist/{css-Dl9aM7Jz.js → css-DvIPI3Qm.js} +1407 -1248
  17. package/dist/css.cjs +1 -1
  18. package/dist/css.js +2 -2
  19. package/dist/dialog.cjs +1 -1
  20. package/dist/dialog.js +1 -1
  21. package/dist/eraser-B03ej59l.cjs +63 -0
  22. package/dist/{eraser-CZknVTjw.js → eraser-CnRJY__h.js} +6002 -5625
  23. package/dist/ether.cjs +1 -1
  24. package/dist/ether.js +66 -63
  25. package/dist/{external-DOd9BcLC.js → external-B3dPSZUg.js} +7 -8
  26. package/dist/external-BEd3F7zY.cjs +1 -0
  27. package/dist/external-BS9S-b49.cjs +1 -0
  28. package/dist/external-BVDQNHbo.cjs +1 -0
  29. package/dist/external-BenP6Hcm.cjs +1 -0
  30. package/dist/external-Blrrgnzw.cjs +1 -0
  31. package/dist/{external-b2X_jilF.js → external-BzV_PGNe.js} +2 -2
  32. package/dist/{external-DnnHYQqD.js → external-C2iqWGd2.js} +32 -32
  33. package/dist/external-CAAPXpVr.cjs +1 -0
  34. package/dist/{external-BYJw6DJV.js → external-CKhbbig_.js} +25 -25
  35. package/dist/external-CNF5TNBY.cjs +1 -0
  36. package/dist/{external-B5RyMtMy.js → external-D16M7vHB.js} +9 -9
  37. package/dist/{external-pm79tCDD.js → external-D6hAP7eJ.js} +16 -16
  38. package/dist/external-D98a3YQJ.cjs +1 -0
  39. package/dist/external-DKh0JhWO.cjs +1 -0
  40. package/dist/external-DNO3FJLl.cjs +1 -0
  41. package/dist/{external-BJ91nMtQ.cjs → external-DOEaBrpz.cjs} +2 -2
  42. package/dist/external-DRuZ24L7.js +78 -0
  43. package/dist/{external-B_NFroo8.js → external-Daage1AI.js} +4 -4
  44. package/dist/{external-CU_XHLqP.js → external-Db9iKa8k.js} +3 -3
  45. package/dist/{external-B8qSW3N8.js → external-Dfr7xymv.js} +3 -3
  46. package/dist/external-DwRvB5ZT.cjs +1 -0
  47. package/dist/{external-CJZTgfAH.js → external-GR-20z_c.js} +10 -10
  48. package/dist/external-I_-aclFy.cjs +1 -0
  49. package/dist/{external-Ylv9Wts9.js → external-R9a28aP6.js} +55 -56
  50. package/dist/external-dew29Q0v.js +42 -0
  51. package/dist/flex.cjs +1 -1
  52. package/dist/flex.js +1 -1
  53. package/dist/{fontString-Bm52S4Lo.js → fontString-CW0wLG5g.js} +2 -2
  54. package/dist/{fontString-BptzSQcY.cjs → fontString-aK--tYMM.cjs} +1 -1
  55. package/dist/header.cjs +1 -1
  56. package/dist/header.js +1 -1
  57. package/dist/index.cjs +7 -7
  58. package/dist/index.js +10255 -10189
  59. package/dist/input.cjs +1 -1
  60. package/dist/input.js +1 -1
  61. package/dist/list.cjs +1 -1
  62. package/dist/list.js +1 -1
  63. package/dist/menu.cjs +1 -1
  64. package/dist/menu.js +1 -1
  65. package/dist/pluto.css +1 -1
  66. package/dist/src/channel/AliasInput.d.ts +3 -1
  67. package/dist/src/channel/AliasInput.d.ts.map +1 -1
  68. package/dist/src/channel/Select.d.ts.map +1 -1
  69. package/dist/src/channel/external.d.ts +0 -2
  70. package/dist/src/channel/external.d.ts.map +1 -1
  71. package/dist/src/channel/queries.d.ts +84 -6
  72. package/dist/src/channel/queries.d.ts.map +1 -1
  73. package/dist/src/dialog/Frame.d.ts.map +1 -1
  74. package/dist/src/flux/Provider.d.ts +9 -7
  75. package/dist/src/flux/Provider.d.ts.map +1 -1
  76. package/dist/src/flux/aether/external.d.ts +4 -3
  77. package/dist/src/flux/aether/external.d.ts.map +1 -1
  78. package/dist/src/flux/aether/provider.d.ts +31 -25
  79. package/dist/src/flux/aether/provider.d.ts.map +1 -1
  80. package/dist/src/flux/core/client.d.ts +21 -0
  81. package/dist/src/flux/core/client.d.ts.map +1 -0
  82. package/dist/src/flux/core/external.d.ts +4 -0
  83. package/dist/src/flux/core/external.d.ts.map +1 -0
  84. package/dist/src/flux/core/index.d.ts +2 -0
  85. package/dist/src/flux/core/index.d.ts.map +1 -0
  86. package/dist/src/flux/core/params.d.ts.map +1 -0
  87. package/dist/src/flux/core/store.d.ts +128 -0
  88. package/dist/src/flux/core/store.d.ts.map +1 -0
  89. package/dist/src/flux/core/store.spec.d.ts +2 -0
  90. package/dist/src/flux/core/store.spec.d.ts.map +1 -0
  91. package/dist/src/flux/core/streamer.d.ts +31 -0
  92. package/dist/src/flux/core/streamer.d.ts.map +1 -0
  93. package/dist/src/flux/core/streamer.spec.d.ts.map +1 -0
  94. package/dist/src/flux/external.d.ts +3 -5
  95. package/dist/src/flux/external.d.ts.map +1 -1
  96. package/dist/src/flux/form.d.ts +43 -11
  97. package/dist/src/flux/form.d.ts.map +1 -1
  98. package/dist/src/flux/list.d.ts +13 -13
  99. package/dist/src/flux/list.d.ts.map +1 -1
  100. package/dist/src/flux/result.d.ts +10 -9
  101. package/dist/src/flux/result.d.ts.map +1 -1
  102. package/dist/src/flux/retrieve.d.ts +22 -41
  103. package/dist/src/flux/retrieve.d.ts.map +1 -1
  104. package/dist/src/flux/update.d.ts +25 -7
  105. package/dist/src/flux/update.d.ts.map +1 -1
  106. package/dist/src/form/Context.d.ts +6 -2
  107. package/dist/src/form/Context.d.ts.map +1 -1
  108. package/dist/src/form/state.d.ts +4 -1
  109. package/dist/src/form/state.d.ts.map +1 -1
  110. package/dist/src/form/use.d.ts +1 -0
  111. package/dist/src/form/use.d.ts.map +1 -1
  112. package/dist/src/hardware/device/queries.d.ts +12 -4
  113. package/dist/src/hardware/device/queries.d.ts.map +1 -1
  114. package/dist/src/hardware/rack/external.d.ts +0 -3
  115. package/dist/src/hardware/rack/external.d.ts.map +1 -1
  116. package/dist/src/hardware/rack/queries.d.ts +13 -0
  117. package/dist/src/hardware/rack/queries.d.ts.map +1 -1
  118. package/dist/src/hardware/task/queries.d.ts +34 -6
  119. package/dist/src/hardware/task/queries.d.ts.map +1 -1
  120. package/dist/src/hooks/index.d.ts +1 -0
  121. package/dist/src/hooks/index.d.ts.map +1 -1
  122. package/dist/src/hooks/useDestructors.d.ts +7 -0
  123. package/dist/src/hooks/useDestructors.d.ts.map +1 -0
  124. package/dist/src/icon/registry.d.ts +1 -0
  125. package/dist/src/icon/registry.d.ts.map +1 -1
  126. package/dist/src/label/queries.d.ts +21 -19
  127. package/dist/src/label/queries.d.ts.map +1 -1
  128. package/dist/src/menu/ContextMenu.d.ts +1 -0
  129. package/dist/src/menu/ContextMenu.d.ts.map +1 -1
  130. package/dist/src/mosaic/Mosaic.d.ts +1 -1
  131. package/dist/src/mosaic/Mosaic.d.ts.map +1 -1
  132. package/dist/src/mosaic/tree.d.ts.map +1 -1
  133. package/dist/src/ontology/queries.d.ts +19 -4
  134. package/dist/src/ontology/queries.d.ts.map +1 -1
  135. package/dist/src/pluto/Pluto.d.ts +23 -2
  136. package/dist/src/pluto/Pluto.d.ts.map +1 -1
  137. package/dist/src/pluto/aether/pluto.d.ts.map +1 -1
  138. package/dist/src/ranger/aether/index.d.ts +2 -0
  139. package/dist/src/ranger/aether/index.d.ts.map +1 -0
  140. package/dist/src/ranger/aether/queries.d.ts +11 -0
  141. package/dist/src/ranger/aether/queries.d.ts.map +1 -0
  142. package/dist/src/ranger/queries.d.ts +31 -25
  143. package/dist/src/ranger/queries.d.ts.map +1 -1
  144. package/dist/src/select/Button.d.ts +3 -2
  145. package/dist/src/select/Button.d.ts.map +1 -1
  146. package/dist/src/select/use.d.ts +7 -4
  147. package/dist/src/select/use.d.ts.map +1 -1
  148. package/dist/src/showcase/TextShowcase.d.ts.map +1 -1
  149. package/dist/src/state/state.d.ts +1 -1
  150. package/dist/src/state/state.d.ts.map +1 -1
  151. package/dist/src/status/Aggregator.d.ts +3 -0
  152. package/dist/src/status/Aggregator.d.ts.map +1 -1
  153. package/dist/src/status/Summary.d.ts.map +1 -1
  154. package/dist/src/status/aether/aggregator.d.ts +2 -12
  155. package/dist/src/status/aether/aggregator.d.ts.map +1 -1
  156. package/dist/src/status/aether/errorHandler.d.ts +15 -0
  157. package/dist/src/status/aether/errorHandler.d.ts.map +1 -0
  158. package/dist/src/status/aether/errorHandler.spec.d.ts +2 -0
  159. package/dist/src/status/aether/errorHandler.spec.d.ts.map +1 -0
  160. package/dist/src/status/aether/external.d.ts +3 -0
  161. package/dist/src/status/aether/external.d.ts.map +1 -0
  162. package/dist/src/status/aether/index.d.ts +1 -1
  163. package/dist/src/status/aether/index.d.ts.map +1 -1
  164. package/dist/src/synnax/Provider.d.ts.map +1 -1
  165. package/dist/src/synnax/aether/provider.d.ts +6 -6
  166. package/dist/src/telem/aether/remote.d.ts +4 -4
  167. package/dist/src/telem/aether/transformers.d.ts +0 -2
  168. package/dist/src/telem/aether/transformers.d.ts.map +1 -1
  169. package/dist/src/telem/aether/transformers.spec.d.ts +2 -0
  170. package/dist/src/telem/aether/transformers.spec.d.ts.map +1 -0
  171. package/dist/src/testutil/Synnax.d.ts +6 -1
  172. package/dist/src/testutil/Synnax.d.ts.map +1 -1
  173. package/dist/src/text/Editable.d.ts.map +1 -1
  174. package/dist/src/text/external.d.ts +0 -1
  175. package/dist/src/text/external.d.ts.map +1 -1
  176. package/dist/src/triggers/Text.d.ts.map +1 -1
  177. package/dist/src/triggers/triggers.d.ts +3 -0
  178. package/dist/src/triggers/triggers.d.ts.map +1 -1
  179. package/dist/src/viewport/SelectMode.d.ts +10 -2
  180. package/dist/src/viewport/SelectMode.d.ts.map +1 -1
  181. package/dist/src/vis/diagram/Diagram.d.ts.map +1 -1
  182. package/dist/src/vis/legend/Simple.d.ts.map +1 -1
  183. package/dist/src/vis/line/aether/line.d.ts +0 -1
  184. package/dist/src/vis/line/aether/line.d.ts.map +1 -1
  185. package/dist/src/vis/lineplot/Legend.d.ts.map +1 -1
  186. package/dist/src/vis/lineplot/aether/XAxis.d.ts +2 -2
  187. package/dist/src/vis/lineplot/aether/YAxis.d.ts +2 -2
  188. package/dist/src/vis/lineplot/aether/axis.d.ts +2 -2
  189. package/dist/src/vis/lineplot/aether/axis.d.ts.map +1 -1
  190. package/dist/src/vis/lineplot/range/aether/provider.d.ts +6 -18
  191. package/dist/src/vis/lineplot/range/aether/provider.d.ts.map +1 -1
  192. package/dist/src/vis/schematic/Forms.d.ts.map +1 -1
  193. package/dist/src/vis/value/TelemForm.d.ts.map +1 -1
  194. package/dist/src/workspace/queries.d.ts +8 -0
  195. package/dist/src/workspace/queries.d.ts.map +1 -1
  196. package/dist/tabs.cjs +1 -1
  197. package/dist/tabs.js +1 -1
  198. package/dist/text.cjs +1 -1
  199. package/dist/text.js +2 -2
  200. package/dist/theming.cjs +1 -1
  201. package/dist/theming.js +2 -2
  202. package/dist/tree.cjs +1 -1
  203. package/dist/tree.js +1 -1
  204. package/dist/triggers.cjs +1 -1
  205. package/dist/triggers.js +1 -1
  206. package/dist/{units-HcS_zslH.js → units-Dh7MflIZ.js} +3 -3
  207. package/dist/units-WWUmv-rf.cjs +1 -0
  208. package/dist/video.cjs +1 -1
  209. package/dist/video.js +1 -1
  210. package/package.json +6 -6
  211. package/dist/Animated-DnsZ5vvU.cjs +0 -1
  212. package/dist/Menu-C-MABQ1r.js +0 -61
  213. package/dist/Menu-vR5-lqo4.cjs +0 -1
  214. package/dist/Toggle-Ckdi4fKV.cjs +0 -1
  215. package/dist/css-9yccD6t_.cjs +0 -8
  216. package/dist/eraser-CLWNvWDn.cjs +0 -63
  217. package/dist/external-BGCkpetp.cjs +0 -1
  218. package/dist/external-CS6l_QN4.cjs +0 -1
  219. package/dist/external-CVNscTLA.js +0 -42
  220. package/dist/external-CY2bvy20.cjs +0 -1
  221. package/dist/external-CkvXTCCL.cjs +0 -1
  222. package/dist/external-ClD4VLgc.cjs +0 -1
  223. package/dist/external-CtooTI5M.cjs +0 -1
  224. package/dist/external-DFsKdN71.cjs +0 -1
  225. package/dist/external-DNHOS3w0.cjs +0 -1
  226. package/dist/external-DPqPAgoV.cjs +0 -1
  227. package/dist/external-DXY1bIut.cjs +0 -1
  228. package/dist/external-DZqxSCvz.cjs +0 -1
  229. package/dist/external-_eEnQPcq.cjs +0 -1
  230. package/dist/external-xfHaehZH.js +0 -75
  231. package/dist/provider-DBSsDoFS.cjs +0 -53
  232. package/dist/src/channel/AliasContext.d.ts +0 -19
  233. package/dist/src/channel/AliasContext.d.ts.map +0 -1
  234. package/dist/src/channel/AliasProvider.d.ts +0 -6
  235. package/dist/src/channel/AliasProvider.d.ts.map +0 -1
  236. package/dist/src/flux/Context.d.ts +0 -4
  237. package/dist/src/flux/Context.d.ts.map +0 -1
  238. package/dist/src/flux/aether/listeners.d.ts +0 -16
  239. package/dist/src/flux/aether/listeners.d.ts.map +0 -1
  240. package/dist/src/flux/aether/params.d.ts.map +0 -1
  241. package/dist/src/flux/aether/streamer.d.ts +0 -22
  242. package/dist/src/flux/aether/streamer.d.ts.map +0 -1
  243. package/dist/src/flux/aether/streamer.spec.d.ts.map +0 -1
  244. package/dist/src/flux/aether/types.d.ts +0 -13
  245. package/dist/src/flux/aether/types.d.ts.map +0 -1
  246. package/dist/src/flux/listeners.d.ts +0 -4
  247. package/dist/src/flux/listeners.d.ts.map +0 -1
  248. package/dist/src/flux/listeners.spec.d.ts +0 -2
  249. package/dist/src/flux/listeners.spec.d.ts.map +0 -1
  250. package/dist/src/flux/useMountListeners.d.ts +0 -7
  251. package/dist/src/flux/useMountListeners.d.ts.map +0 -1
  252. package/dist/src/hardware/rack/synchronizers.d.ts +0 -3
  253. package/dist/src/hardware/rack/synchronizers.d.ts.map +0 -1
  254. package/dist/src/hardware/rack/use.d.ts +0 -3
  255. package/dist/src/hardware/rack/use.d.ts.map +0 -1
  256. package/dist/src/hardware/rack/useStatus.d.ts +0 -3
  257. package/dist/src/hardware/rack/useStatus.d.ts.map +0 -1
  258. package/dist/src/text/symbols.d.ts +0 -3
  259. package/dist/src/text/symbols.d.ts.map +0 -1
  260. package/dist/units-BGkvnLO-.cjs +0 -1
  261. /package/dist/src/flux/{aether → core}/params.d.ts +0 -0
  262. /package/dist/src/flux/{aether → core}/streamer.spec.d.ts +0 -0
@@ -0,0 +1,63 @@
1
+ "use strict";const s=require("zod"),f=require("./css-DI0uCCGq.cjs"),ts=require("react"),Bl=t=>{const e=t.replace(/_[a-z]/g,r=>r[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Ra=t=>{const e=(r,n=wn)=>{if(typeof r=="string")return t(r);if(Array.isArray(r))return r.map(o=>e(o,n));if(!Gr(r))return r;n=Zl(n);const a={},i=r;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=t(o);n.recursive&&(Gr(l)?Ds(l)||(l=e(l,n)):n.recursiveInArray&&Ps(l)&&(l=[...l].map(u=>{let h=u;return Gr(u)?Ds(h)||(h=e(u,n)):Ps(u)&&(h=e({key:u},n).key),h}))),a[c]=l}),a)};return e},Ua=Ra(Bl),$l=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}_${n.toLowerCase()}`),Fl=Ra($l),ql=[Number,String,Uint8Array],wn={recursive:!0,recursiveInArray:!0},Zl=(t=wn)=>(t.recursive==null?t=wn:t.recursiveInArray??=!1,t),Ps=t=>t!=null&&Array.isArray(t),Gr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Ds=t=>ql.some(e=>t instanceof e);let Yl=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t))}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const r=JSON.parse(t),n=Ua(r);return e!=null?e.parse(n):n}encodeString(t){const e=Fl(t);return JSON.stringify(e,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}};const bn=new Yl;let ht=class{value;constructor(t){this.value=t}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const Vl=t=>t!=null&&typeof t=="object"&&"toString"in t,Hl=(t,e=!1)=>{const r=Vl(t)?"stringer":typeof t;let n;switch(r){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${r}`),()=>-1}return e?_l(n):n},_l=t=>(e,r)=>t(r,e),xr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ma=s.z.object({width:s.z.number(),height:s.z.number()}),Wl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Gl=["width","height"];s.z.enum(Gl);const Kl=["start","center","end"],Jl=["signedWidth","signedHeight"];s.z.enum(Jl);const vr=s.z.object({x:s.z.number(),y:s.z.number()}),Xl=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Ql=["x","y"],La=s.z.enum(Ql),Pa=["top","right","bottom","left"];s.z.enum(Pa);const ec=["left","right"],Da=s.z.enum(ec),tc=["top","bottom"],Ba=s.z.enum(tc),$a=["center"],Bs=s.z.enum($a),rc=[...Pa,...$a],Fa=s.z.enum(rc);s.z.enum(Kl);const nc=["first","last"];s.z.enum(nc);const sc=s.z.object({lower:s.z.number(),upper:s.z.number()}),ac=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([sc,xr]);s.z.union([ac,xr]);s.z.enum([...La.options,...Fa.options]);s.z.union([La,Fa,s.z.instanceof(String)]);const Cr=t=>(e,r)=>{if(typeof e=="bigint"){if(ic(r))return t(e,BigInt(r));const n=t(Number(e),Number(r));return typeof n=="number"?BigInt(Math.round(n)):n}return t(Number(e),Number(r))},Ir=Cr((t,e)=>t-e),jr=Cr((t,e)=>t+e),ic=t=>typeof t=="bigint"?!0:Number.isInteger(t),de=Cr((t,e)=>t*e),Rr=Cr((t,e)=>t/e),qe=(t,e,r)=>{const n={};if(typeof e=="object"&&(r=e,e=void 0),r={makeValid:!0,...r},typeof t=="number"||typeof t=="bigint")e!=null?(n.lower=t,n.upper=e):(n.lower=typeof t=="bigint"?0n:0,n.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=t}else n.lower=t.lower,n.upper=t.upper;return r?.makeValid?oc(n):n},oc=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,$s=(t,e)=>{const r=qe(t);return e<r.lower?r.lower:e>=r.upper?r.upper-(typeof r.upper=="number"?1:1n):e};s.z.object({x:Da.or(Bs),y:Ba.or(Bs)});const lc=s.z.object({x:Da,y:Ba}),cc=Object.freeze({x:"left",y:"top"}),uc=(t,e)=>t.x===e.x&&t.y===e.y,Fs=s.z.union([s.z.number(),vr,xr,Ma,Wl,Xl]),hc=(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}},qs=Object.freeze({x:0,y:0}),ar=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:ar,left:ar,width:ar,height:ar});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:vr,two:vr,root:lc});const rs=(t,e,r=0,n=0,a)=>{const i={one:{...qs},two:{...qs},root:a??cc};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:t,y:e},i.two={x:i.one.x+r,y:i.one.y+n},i}return"one"in t&&"two"in t&&"root"in t?{...t,root:a??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(i.one={x:t.left,y:t.top},i.two={x:t.right,y:t.bottom},i):(i.one=t,e==null?i.two={x:i.one.x+r,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+r}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},Kr=t=>{const e=rs(t);return{lower:e.one.x,upper:e.two.x}},Jr=t=>{const e=rs(t);return{lower:e.one.y,upper:e.two.y}},dc=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,fc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ma,fc,vr,xr]);const pc=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:Fs,scale:Fs});s.z.object({offset:s.z.number(),scale:s.z.number()});const yc=t=>(e,r,n,a)=>r==="dimension"?[e,n]:[e,a?n-t:n+t],gc=t=>(e,r,n,a)=>[e,a?n/t:n*t],mc=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=t,c=i-a,u=l-o;if(r==="dimension")return[t,n*(u/c)];const h=(n-a)*(u/c)+o;return[t,h]},wc=t=>(e,r,n)=>[t,n],bc=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:a}=t;return[t,a-(r-n)]},vc=t=>(e,r,n)=>{const{lower:a,upper:i}=t;return n=pc(n,a,i),[e,n]};let Zs=class We{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new We().translate(e)}static magnify(e){return new We().magnify(e)}static scale(e,r){return new We().scale(e,r)}translate(e){const r=this.new(),n=yc(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=gc(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=qe(e,r),a=this.new(),i=mc(n);return i.type="scale",a.ops.push(i),a}clamp(e,r){const n=qe(e,r),a=this.new(),i=vc(n);return i.type="clamp",a.ops.push(i),a}reBound(e,r){const n=qe(e,r),a=this.new(),i=wc(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=bc();e.type="invert";const r=this.new();return r.ops.push(e),r}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new We;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,r){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||r.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&r.push([a,i])}),r.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new We};(class ie{x;y;currRoot;constructor(e=new Zs,r=new Zs,n=null){this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new ie().translate(e,r)}static translateX(e){return new ie().translateX(e)}static translateY(e){return new ie().translateY(e)}static clamp(e){return new ie().clamp(e)}static magnify(e){return new ie().magnify(e)}static scale(e){return new ie().scale(e)}static reBound(e){return new ie().reBound(e)}translate(e,r){const n=hc(e,r),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(dc(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!uc(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(Kr(e)),r.y=r.y.scale(Jr(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(Kr(e)),r.y=this.y.reBound(Jr(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(Kr(e)),r.y=this.y.clamp(Jr(e)),r}copy(){const e=new ie;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return rs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new ie});let qa=(t,e=21)=>(r=e)=>{let n="",a=r|0;for(;a--;)n+=t[Math.random()*t.length|0];return n};const Za="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Tc=`0123456789${Za}`,Oc=11,Sc=qa(Za,1),zc=qa(Tc,Oc-1),Ec=()=>`${Sc()}${zc()}`,Nc=(t,e)=>r=>r instanceof e||typeof r=="object"&&r!==null&&"discriminator"in r&&r.discriminator===t,Ac=s.z.enum(["static","dynamic"]),kc=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),Ya=(t,e)=>{const r=new R(e);if(![A.DAY,A.HOUR,A.MINUTE,A.SECOND,A.MILLISECOND,A.MICROSECOND,A.NANOSECOND].some(a=>a.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof R?new R(n):new A(n)};let R=class w extends ht{constructor(e,r="UTC"){if(e==null)super(w.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*w.MILLISECOND.valueOf());else if(typeof e=="string")super(w.parseDateTimeString(e,r).valueOf());else if(Array.isArray(e))super(w.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=w.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=w.MAX:e=w.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,r=1,n=1]){const a=new Date(e,r-1,n,0,0,0,0);return new w(BigInt(a.getTime())*w.MILLISECOND.valueOf()).truncate(w.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,a,i]=e.split(":");let o="00",l="00";i!=null&&([o,l]=i.split("."));let c=w.hours(parseInt(n??"00")).add(w.minutes(parseInt(a??"00"))).add(w.seconds(parseInt(o??"00"))).add(w.milliseconds(parseInt(l??"00")));return r==="local"&&(c=c.add(w.utcOffset)),c.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return w.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new w(BigInt(n.getTime())*w.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(w.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new A(BigInt(new Date().getTimezoneOffset())*w.MINUTE.valueOf())}static since(e){return new w().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new w(e).valueOf()}span(e){return this.range(e).span}range(e){return new Et(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new w(e).valueOf()}afterEq(e){return this.valueOf()>=new w(e).valueOf()}before(e){return this.valueOf()<new w(e).valueOf()}beforeEq(e){return this.valueOf()<=new w(e).valueOf()}add(e){return new w(jr(this.valueOf(),new A(e).valueOf()))}sub(e){return new w(Ir(this.valueOf(),new A(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(A.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(A.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(A.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(A.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(w.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(w.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const r=this.date();return r.setUTCFullYear(e),new w(r)}get month(){return this.date().getUTCMonth()}setMonth(e){const r=this.date();return r.setUTCMonth(e),new w(r)}get day(){return this.date().getUTCDate()}setDay(e){const r=this.date();return r.setUTCDate(e),new w(r)}get hour(){return this.date().getUTCHours()}setHour(e){const r=this.date();return r.setUTCHours(e),new w(r,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const r=this.date();return r.setUTCMinutes(e),new w(r)}get second(){return this.date().getUTCSeconds()}setSecond(e){const r=this.date();return r.setUTCSeconds(e),new w(r)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const r=this.date();return r.setUTCMilliseconds(e),new w(r)}toString(){return this.date().toISOString()}remainder(e){return Ya(this,e)}get isToday(){return this.truncate(A.DAY).equals(w.now().truncate(A.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new w(new Date)}static max(...e){let r=w.MIN;for(const n of e){const a=new w(n);a.after(r)&&(r=a)}return r}static min(...e){let r=w.MAX;for(const n of e){const a=new w(n);a.before(r)&&(r=a)}return r}static nanoseconds(e,r="UTC"){return new w(e,r)}static NANOSECOND=w.nanoseconds(1);static microseconds(e,r="UTC"){return w.nanoseconds(e*1e3,r)}static MICROSECOND=w.microseconds(1);static milliseconds(e,r="UTC"){return w.microseconds(e*1e3,r)}static MILLISECOND=w.milliseconds(1);static seconds(e,r="UTC"){return w.milliseconds(e*1e3,r)}static SECOND=w.seconds(1);static minutes(e,r="UTC"){return w.seconds(e*60,r)}static MINUTE=w.minutes(1);static hours(e,r="UTC"){return w.minutes(e*60,r)}static HOUR=w.hours(1);static days(e,r="UTC"){return w.hours(e*24,r)}static DAY=w.days(1);static MAX=new w((1n<<63n)-1n);static MIN=new w(0);static ZERO=new w(0);static z=s.z.union([s.z.instanceof(w),s.z.object({value:s.z.bigint()}).transform(e=>new w(e.value)),s.z.string().transform(e=>new w(BigInt(e))),s.z.number().transform(e=>new w(e)),s.z.bigint().transform(e=>new w(e)),s.z.date().transform(e=>new w(e)),s.z.custom(e=>e instanceof A).transform(e=>new w(e)),kc.transform(e=>new w(e))]);static sort(e,r){return Number(e.valueOf()-r.valueOf())}},A=class v extends ht{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof Xr?e.period:e instanceof R?new v(e):["number","bigint"].includes(typeof e)?v.seconds(e):new v(e)}static fromMilliseconds(e){return e instanceof v?e:e instanceof Xr?e.period:e instanceof R?new v(e):["number","bigint"].includes(typeof e)?v.milliseconds(e):new v(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new v(e).valueOf()}greaterThan(e){return this.valueOf()>new v(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new v(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new v(e).valueOf()}remainder(e){return Ya(this,e)}truncate(e){return new v(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(v.DAY),r=this.truncate(v.HOUR),n=this.truncate(v.MINUTE),a=this.truncate(v.SECOND),i=this.truncate(v.MILLISECOND),o=this.truncate(v.MICROSECOND),l=this.truncate(v.NANOSECOND),c=e,u=r.sub(e),h=n.sub(r),p=a.sub(n),d=i.sub(a),S=o.sub(i),N=l.sub(o);let x="";return c.isZero||(x+=`${c.days}d `),u.isZero||(x+=`${u.hours}h `),h.isZero||(x+=`${h.minutes}m `),p.isZero||(x+=`${p.seconds}s `),d.isZero||(x+=`${d.milliseconds}ms `),S.isZero||(x+=`${S.microseconds}µs `),N.isZero||(x+=`${N.nanoseconds}ns`),x.trim()}mult(e){return new v(de(this.valueOf(),e))}div(e){return new v(Rr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new v(e).valueOf()}add(e){return new v(this.valueOf()+new v(e).valueOf())}sub(e){return new v(this.valueOf()-new v(e).valueOf())}static nanoseconds(e=1){return new v(e)}static NANOSECOND=v.nanoseconds(1);static microseconds(e=1){return v.nanoseconds(de(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(de(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(de(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(de(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(de(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(de(e,24))}static DAY=v.days(1);static MAX=new v((1n<<63n)-1n);static MIN=new v(0);static ZERO=new v(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new v(e.value)),s.z.string().transform(e=>new v(BigInt(e))),s.z.number().transform(e=>new v(e)),s.z.bigint().transform(e=>new v(e)),s.z.instanceof(v),s.z.instanceof(R).transform(e=>new v(e)),s.z.custom(e=>e instanceof Xr).transform(e=>new v(e))])},Xr=class oe extends ht{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new oe(e).valueOf()}get period(){return A.seconds(1/this.valueOf())}sampleCount(e){return new A(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new H(r).valueOf()}span(e){return A.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}add(e){return new oe(jr(this.valueOf(),e.valueOf()))}sub(e){return new oe(Ir(this.valueOf(),e.valueOf()))}mult(e){return new oe(de(this.valueOf(),e))}div(e){return new oe(Rr(this.valueOf(),e))}static hz(e){return new oe(e)}static khz(e){return oe.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new oe(e)),s.z.instanceof(oe)])},H=class G extends ht{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new vn(e*this.valueOf())}add(e){return new G(jr(this.valueOf(),e.valueOf()))}sub(e){return new G(Ir(this.valueOf(),e.valueOf()))}mult(e){return new G(de(this.valueOf(),e))}div(e){return new G(Rr(this.valueOf(),e))}static UNKNOWN=new G(0);static BIT128=new G(16);static BIT64=new G(8);static BIT32=new G(4);static BIT16=new G(2);static BIT8=new G(1);static z=s.z.union([s.z.number().transform(e=>new G(e)),s.z.instanceof(G)])},Et=class le{start;end;constructor(e,r){typeof e=="object"&&"start"in e?(this.start=new R(e.start),this.end=new R(e.end)):(this.start=new R(e),this.end=new R(r))}get span(){return new A(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new le(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,r=A.ZERO){if(r.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=r.valueOf()&&a<=r.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,r=A.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const a=R.max(n.start,e.start),i=R.min(n.end,e.end);return i.before(a)?!1:new A(i.sub(a)).greaterThanOrEqual(r)}contains(e){return e instanceof le?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new le(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}static max(...e){return new le(R.min(...e.map(r=>r.start)),R.max(...e.map(r=>r.end)))}static MAX=new le(R.MIN,R.MAX);static MIN=new le(R.MAX,R.MIN);static ZERO=new le(R.ZERO,R.ZERO);static z=s.z.union([s.z.object({start:R.z,end:R.z}).transform(e=>new le(e.start,e.end)),s.z.instanceof(le)]);static sort(e,r){return R.sort(e.start,r.start)||R.sort(e.end,r.end)}},P=class y extends ht{constructor(e){if(e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const r=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r==null)throw new Error(`unable to find data type for ${e.toString()}`);super(r.valueOf())}}get Array(){const e=y.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),H.BIT8],[y.UINT16.toString(),H.BIT16],[y.UINT32.toString(),H.BIT32],[y.UINT64.toString(),H.BIT64],[y.FLOAT32.toString(),H.BIT32],[y.FLOAT64.toString(),H.BIT64],[y.INT8.toString(),H.BIT8],[y.INT16.toString(),H.BIT16],[y.INT32.toString(),H.BIT32],[y.INT64.toString(),H.BIT64],[y.TIMESTAMP.toString(),H.BIT64],[y.STRING.toString(),H.UNKNOWN],[y.JSON.toString(),H.UNKNOWN],[y.UUID.toString(),H.BIT128]]);static ALL=[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON];static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new y(e)),s.z.instanceof(y)])},vn=class I extends ht{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new I(jr(this.valueOf(),e.valueOf()))}sub(e){return new I(Ir(this.valueOf(),e.valueOf()))}mult(e){return new I(de(this.valueOf(),e))}div(e){return new I(Rr(this.valueOf(),e))}truncate(e){return new I(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return I.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),r=this.truncate(I.GIGABYTE),n=this.truncate(I.MEGABYTE),a=this.truncate(I.KILOBYTE),i=this.truncate(I.BYTE),o=e,l=r.sub(e),c=n.sub(r),u=a.sub(n),h=i.sub(a);let p="";return o.isZero||(p+=`${o.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),c.isZero||(p+=`${c.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new I(e)}static BYTE=new I(1);static kilobytes(e=1){return I.bytes(e.valueOf()*1e3)}static KILOBYTE=I.kilobytes(1);static megabytes(e=1){return I.kilobytes(e.valueOf()*1e3)}static MEGABYTE=I.megabytes(1);static gigabytes(e=1){return I.megabytes(e.valueOf()*1e3)}static GIGABYTE=I.gigabytes(1);static terabytes(e){return I.gigabytes(e.valueOf()*1e3)}static TERABYTE=I.terabytes(1);static ZERO=new I(0);static z=s.z.union([s.z.number().transform(e=>new I(e)),s.z.instanceof(I)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Va=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof R||t instanceof A||t instanceof Date},xc=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r.valueOf())-BigInt(n.valueOf()):fr(r,-n),fr=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),Cc=/^(?:[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 Ic(t){return typeof t=="string"&&Cc.test(t)}const F=[];for(let t=0;t<256;++t)F.push((t+256).toString(16).slice(1));function jc(t,e=0){return(F[t[e+0]]+F[t[e+1]]+F[t[e+2]]+F[t[e+3]]+"-"+F[t[e+4]]+F[t[e+5]]+"-"+F[t[e+6]]+F[t[e+7]]+"-"+F[t[e+8]]+F[t[e+9]]+"-"+F[t[e+10]]+F[t[e+11]]+F[t[e+12]]+F[t[e+13]]+F[t[e+14]]+F[t[e+15]]).toLowerCase()}function Rc(t,e=0){const r=jc(t,e);if(!Ic(r))throw TypeError("Stringified UUID is invalid");return r}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ha=(t,e)=>Rc(t,e),Se=-1,Uc=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Mc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Tn=10,Lc=(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`)},_a="sy_x_telem_series";let Wa=class Ae{key;discriminator=_a;dataType;sampleOffset;gl;_data;timeRange=Et.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Se;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:Et.z.optional(),dataType:P.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Uc,Mc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Ac.optional().default("static").optional()});static z=Ae.crudeZ.transform(e=>new Ae(e));constructor(e){Pc(e)&&(e={data:e}),e.data??=[];const{dataType:r,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:l=1n,key:c=Ec(),data:u}=e;if(Dc(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=Va(u),p=Array.isArray(u);if(r!=null)this.dataType=new P(r);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(p||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=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 R||d instanceof Date||d instanceof R)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(!p&&!h)this._data=u;else if(p&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[u]:u;const S=d[0];(S instanceof R||S instanceof Date||S instanceof A)&&(d=d.map(N=>new R(N).valueOf())),this.dataType.equals(P.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
2
+ `)}
3
+ `).buffer):this.dataType.equals(P.JSON)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(N=>bn.encodeString(N)).join(`
4
+ `)}
5
+ `).buffer):this.dataType.usesBigInt&&typeof S=="number"?this._data=new this.dataType.Array(d.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof S=="bigint"?this._data=new this.dataType.Array(d.map(Number)).buffer:this._data=new this.dataType.Array(d).buffer}this.key=c,this.alignment=o,this.alignmentMultiple=l,this.sampleOffset=a??0,this.timeRange=n??Et.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:r,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new P(r).Array(e),i=new Ae({data:a.buffer,dataType:r,...n});return i.writePos=0,i}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Se)return 0;const r=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,r);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===Se)return 0;const r=this.capacity-this.writePos,n=e.sub(0,r);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Se?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
6
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(P.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(r=>e.parse(bn.decodeString(r)))}get byteCapacity(){return new vn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Se?this.byteCapacity:this.dataType.isVariable?new vn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Se?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const r=[0];return this.data.forEach((n,a)=>{n===Tn&&(e++,r.push(a+1))}),this._cachedIndexes=r,this.cachedLength=e,e}convert(e,r=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=xc(this.dataType,e,this.data[a],r);return new Ae({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(P.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),fr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(P.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),fr(this.cachedMin,this.sampleOffset))}get bounds(){return qe(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const r=e.cachedMin??e.calcRawMin();r<this.cachedMin&&(this.cachedMin=r)}if(this.cachedMax!=null){const r=e.cachedMax??e.calcRawMax();r>this.cachedMax&&(this.cachedMax=r)}}atAlignment(e,r){const n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(r===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,r)}at(e,r=!1){if(this.dataType.isVariable)return this.atVariable(e,r??!1);if(this.dataType.equals(P.UUID))return this.atUUID(e,r);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return fr(n,this.sampleOffset)}atUUID(e,r){e<0&&(e=this.length+e);const n=Ha(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(r)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,r){let n=0,a=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],a=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Tn){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(P.STRING)?new TextDecoder().decode(i):Ua(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let r=0,n=this.length-1;const a=Hl(e);for(;r<=n;){const i=Math.floor((r+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?r=i+1:n=i-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(P.FLOAT32)&&!this.dataType.equals(P.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:a}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Se){a===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(a).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,i,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Se}as(e){return Lc(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Vs(this.alignmentBounds.lower),upper:Vs(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return qe(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 Bc(this);return this.dataType.equals(P.JSON)?new $c(e):e}return this.dataType.equals(P.UUID)?new Fc(this):new qc(this)}slice(e,r){return this.sliceSub(!1,e,r)}sub(e,r){return this.sliceSub(!0,e,r)}subIterator(e,r){return new Ys(this,e,r??this.length)}subAlignmentIterator(e,r){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),a=Math.ceil(Number(r-this.alignment)/Number(this.alignmentMultiple));return new Ys(this,n,a)}subBytes(e,r){if(e>=0&&(r==null||r>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,r);return new Ae({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,r,n){if(r<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(r,n):a=this.data.slice(r,n),new Ae({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(r)})}reAlign(e){return new Ae({data:this.buffer,dataType:this.dataType,timeRange:Et.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(r=>r.toString());else{for(let r=0;r<5;r++)e+=`${this.at(r)?.toString()}`,e+=",";e+="...,";for(let r=-5;r<0;r++)e+=this.at(r)?.toString(),r<-1&&(e+=",")}return e+="])",e}};const Pc=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Wa?!0:Va(t),Dc=Nc(_a,Wa);class Ys{series;end;index;constructor(e,r,n){this.series=e;const a=qe(0,e.length+1);this.end=$s(a,n),this.index=$s(a,r)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class Bc{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,r=this.series.data;for(;this.index<r.length&&r[this.index]!==Tn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}}let $c=class Ga{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:bn.decodeString(e.value,Ga.schema)}}};class Fc{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=Ha(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let qc=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 Vs=t=>{const e=t>>32n,r=t&0xffffffffn;return{domain:e,sample:r}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const Zc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Zc();const Yc=["macOS","Windows","Linux"],Vc=["macos","windows","linux"],Hc={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(Yc).or(s.z.enum(Vc).transform(t=>Hc[t]));const _c=(...t)=>t.map(Ka).join(""),Ka=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Wc=t=>t.endsWith("/")?t.slice(0,-1):t,Gc=(t,e="")=>t===null?"":`?${Object.entries(t).filter(([,r])=>r==null?!1:Array.isArray(r)?r.length>0:!0).map(([r,n])=>`${e}${r}=${n}`).join("&")}`;let Kc=class pr{protocol;host;port;path;constructor({host:e,port:r,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=r,this.path=Ka(a)}replace(e){return new pr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new pr({...this,pathPrefix:_c(this.path,e)})}toString(){return Wc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new pr({host:"unknown",port:0})};const Jc=async t=>await new Promise(e=>setTimeout(e,A.fromMilliseconds(t).milliseconds));class Xc{config;retries;interval;constructor(e){this.config={baseInterval:new A(e?.baseInterval??A.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Jc},this.retries=0,this.interval=new A(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:r,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(r),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Qc=s.z.object({baseInterval:A.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),eu=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Xc,breakerConfigZ:Qc},Symbol.toStringTag,{value:"Module"})),tu=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Ja=s.z.string().regex(tu),rt=s.z.number().min(0).max(255),Xa=s.z.number().min(0).max(1),Qa=s.z.tuple([rt,rt,rt,Xa]),ru=s.z.tuple([rt,rt,rt]),nu=s.z.object({rgba255:Qa}),su=s.z.number().min(0).max(360),au=s.z.number().min(0).max(100),iu=s.z.number().min(0).max(100),ou=s.z.tuple([su,au,iu,Xa]),ns=s.z.union([Ja,ru,Qa,ou,nu]),lu=ns.transform(t=>ss(t)),ss=(t,e=1)=>{if(t=ns.parse(t),typeof t=="string")return cu(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},cu=(t,e=1)=>(t=Ja.parse(t),t=uu(t),[ir(t,0),ir(t,2),ir(t,4),t.length===8?ir(t,6)/255:e]),ir=(t,e)=>parseInt(t.slice(e,e+2),16),uu=t=>t.startsWith("#")?t.slice(1):t;ss("#000000");ss("#ffffff");const hu=s.z.object({key:s.z.string(),color:ns,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(hu);const du=s.z.object({key:s.z.string(),name:s.z.string(),color:lu});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(du)});s.z.int().min(0).max(255);s.z.object({name:s.z.string(),key:s.z.string()});const fu=t=>Object.getOwnPropertySymbols(globalThis).includes(t),pu=(t,e)=>{const r=Symbol.for(t);if(!fu(r)){const n=e();Object.defineProperty(globalThis,r,{value:n})}return()=>globalThis[r]},ei="sy_x_error",yu=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),qt=t=>class Nt extends Error{static discriminator=ei;discriminator=Nt.discriminator;static TYPE=t;type=Nt.TYPE;static matches=yu(t);matches=Nt.matches;constructor(r,n){super(r,n),this.name=Nt.TYPE}static sub(r){return qt(`${t}.${r}`)}},ti=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==ei)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Ge="unknown",On="nil";class gu{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:On,data:""};if(ti(e))for(const r of this.providers){const n=r.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Ge,data:e.message};if(typeof e=="string")return{type:Ge,data:e};try{return{type:Ge,data:JSON.stringify(e)}}catch{return{type:Ge,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===On)return null;if(e.type===Ge)return new Sn(e.data);for(const r of this.providers){const n=r.decode(e);if(n!=null)return n}return new Sn(e.data)}}const as=pu("synnax-error-registry",()=>new gu),mu=({encode:t,decode:e})=>as().register({encode:t,decode:e}),wu=t=>as().encode(t),bu=t=>t==null?null:as().decode(t);class Sn extends qt("unknown"){}const vu=s.z.object({type:s.z.string(),data:s.z.string()});class Tu extends qt("canceled"){}class Ou extends qt("not_implemented"){}const Ue=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Tu,NONE:On,NotImplemented:Ou,UNKNOWN:Ge,Unknown:Sn,createTyped:qt,decode:bu,encode:wu,isTyped:ti,payloadZ:vu,register:mu},Symbol.toStringTag,{value:"Module"})),Su=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),ri=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),zu=ri.extend({result:s.json()}),Eu=ri.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),Nu=s.union([zu,Eu]);s.union([Su,Nu]);s.z.string().regex(/^\d+\.\d+\.\d+$/);const Au=["standard","scientific","engineering"];s.z.enum(Au);s.z.enum(["success","info","warning","error","loading","disabled"]);let Zt=class extends Ue.createTyped("freighter"){},ne=class extends Zt.sub("eof"){constructor(){super("EOF")}},st=class extends Zt.sub("stream_closed"){constructor(){super("StreamClosed")}},Me=class extends Zt.sub("unreachable"){url;constructor(t={}){const{message:e="Unreachable",url:r=Kc.UNKNOWN}=t;super(e),this.url=r}};const ku=t=>{if(!t.type.startsWith(Zt.TYPE))return null;if(ne.matches(t))return{type:ne.TYPE,data:"EOF"};if(st.matches(t))return{type:st.TYPE,data:"StreamClosed"};if(Me.matches(t))return{type:Me.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},xu=t=>{if(!t.type.startsWith(Zt.TYPE))return null;switch(t.type){case ne.TYPE:return new ne;case st.TYPE:return new st;case Me.TYPE:return new Me;default:throw new Ue.Unknown(`Unknown error type: ${t.data}`)}};Ue.register({encode:ku,decode:xu});class ni{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,r){let n=0;const a=async i=>{if(n===this.middleware.length)return await r(i);const o=this.middleware[n];return n++,await o(i,a)};return await a(e)}}const si="Content-Type",Cu=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Iu=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&Cu.has(e))return!0;if(t.name==="TypeError"){const r=String(t.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(r))return!0}return t?.name==="AbortError"||t?.code,!1},ju=400;class Ru extends ni{endpoint;encoder;constructor(e,r,n=!1){return super(),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=r,new Proxy(this,{get:(a,i,o)=>i==="endpoint"?this.endpoint:Reflect.get(a,i,o)})}get headers(){return{[si]:this.encoder.contentType}}async send(e,r,n,a){r=n?.parse(r);let i=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(r??{});const[,c]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async u=>{const h={...u,params:{}};l.headers={...this.headers,...u.params};let p;try{p=await fetch(u.target,l)}catch(S){if(!(S instanceof Error))throw S;return[h,Iu(S)?new Me({url:o}):S]}const d=await p.arrayBuffer();if(p?.ok)return a!=null&&(i=this.encoder.decode(d,a)),[h,null];try{if(p.status!==ju)return[h,new Error(p.statusText)];const S=this.encoder.decode(d,Ue.payloadZ),N=Ue.decode(S);return[h,N]}catch(S){return[h,new Error(`[freighter] - failed to decode error: ${p.statusText}: ${S.message}`)]}});if(c!=null)return[null,c];if(i==null)throw new Error("Response must be defined");return[i,null]}}const Uu=(t,e)=>{class r{wrapped;constructor(a){this.wrapped=a}use(...a){this.wrapped.use(...a)}async send(a,i,o,l){const c=new eu.Breaker(e);do{const[u,h]=await this.wrapped.send(a,i,o,l);if(h==null)return[u,null];if(!Me.matches(h))return[null,h];if(console.warn(`[freighter] ${c.retryMessage}`,h),!await c.wait())return[u,h]}while(!0)}}return new r(t)},m=async(t,e,r,n,a)=>{const[i,o]=await t.send(e,r,n,a);if(o!=null)throw o;return i},Mu=s.z.object({type:s.z.enum(["data","close","open"]),payload:s.z.unknown(),error:s.z.optional(Ue.payloadZ)});class Lu{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,r,n,a){this.codec=r,this.reqSchema=n,this.resSchema=a,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return Ue.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ne;if(this.sendClosed)throw new st;return this.ws.send(this.codec.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");if(this.serverClosed=Ue.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((e,r)=>this.receiveCallbacksQueue.push({resolve:e,reject:r}))}addMessage(e){const r=this.receiveCallbacksQueue.shift();r!=null?r.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,Mu))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Du?ne.TYPE:st.TYPE,data:""}})}}const Pu="freighterctx",Du=1e3;let Bu=class zn extends ni{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,r,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=r}withCodec(e){const r=new zn(this.baseUrl,e,this.secure);return r.use(...this.middleware),r}async stream(e,r,n){let a;const[,i]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const l=new WebSocket(this.buildURL(e,o)),c={...o,params:{}};l.binaryType=zn.MESSAGE_TYPE;const u=await this.wrapSocket(l,r,n);return u instanceof Error?[c,u]:(a=u,[c,null])});if(i!=null)throw i;return a}buildURL(e,r){const n=Gc({[si]:this.encoder.contentType,...r.params},Pu);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,r,n){return await new Promise(a=>{e.onopen=()=>{const i=new Lu(e,this.encoder,r,n);i.receiveOpenAck().then(o=>{o!=null?a(o):a(i)}).catch(o=>a(o))},e.onerror=i=>{const o=i;a(new Error(o.message))}})}};const $u=t=>Array.isArray(t)?t:t==null?[]:[t],O=Object.freeze(Object.defineProperty({__proto__:null,toArray:$u},Symbol.toStringTag,{value:"Module"})),Fu=t=>{const e=t.replace(/_[a-z]/g,r=>r[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},is=t=>{const e=(r,n=En)=>{if(typeof r=="string")return t(r);if(Array.isArray(r))return r.map(o=>e(o,n));if(!Qr(r))return r;n=Vu(n);const a={},i=r;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=t(o);n.recursive&&(Qr(l)?_s(l)||(l=e(l,n)):n.recursiveInArray&&Hs(l)&&(l=[...l].map(u=>{let h=u;return Qr(u)?_s(h)||(h=e(u,n)):Hs(u)&&(h=e({key:u},n).key),h}))),a[c]=l}),a)};return e},os=is(Fu),qu=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}_${n.toLowerCase()}`),ai=is(qu),Zu=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),Yu=[Number,String,Uint8Array],En={recursive:!0,recursiveInArray:!0},Vu=(t=En)=>(t.recursive==null?t=En:t.recursiveInArray??=!1,t),Hs=t=>t!=null&&Array.isArray(t),Qr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),_s=t=>Yu.some(e=>t instanceof e),Hu=t=>t.replace(/\s+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}-${n.toLowerCase()}`).toLowerCase(),_u=is(Hu),Wu=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:ai,capitalize:Zu,snakeToCamel:os,toKebab:_u},Symbol.toStringTag,{value:"Module"})),ii=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);let oi=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t))}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const r=JSON.parse(t),n=os(r);return e!=null?e.parse(n):n}encodeString(t){const e=ai(t);return JSON.stringify(e,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}},li=class{contentType="text/csv";encode(t){const e=this.encodeString(t);return new TextEncoder().encode(e)}decode(t,e){const r=new TextDecoder().decode(t);return this.decodeString(r,e)}encodeString(t){if(!Array.isArray(t)||t.length===0||!ii(t[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(t[0]),r=[e.join(",")];return t.forEach(n=>{const a=e.map(i=>JSON.stringify(n[i]??""));r.push(a.join(","))}),r.join(`
7
+ `)}decodeString(t,e){const[r,...n]=t.trim().split(`
8
+ `).map(o=>o.trim());if(r.length===0)return e!=null?e.parse({}):{};const a=r.split(",").map(o=>o.trim()),i={};return a.forEach(o=>{i[o]=[]}),n.forEach(o=>{const l=o.split(",").map(c=>c.trim());a.forEach((c,u)=>{const h=this.parseValue(l[u]);h!=null&&i[c].push(h)})}),e!=null?e.parse(i):i}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}},ci=class{contentType="text/plain";encode(t){if(typeof t!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(t)}decode(t,e){const r=new TextDecoder().decode(t);return e!=null?e.parse(r):r}};const It=new oi,Gu=new li,Ku=new ci,Ju=[It],Ve=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:li,CSV_CODEC:Gu,ENCODERS:Ju,JSONCodec:oi,JSON_CODEC:It,TEXT_CODEC:Ku,TextCodec:ci},Symbol.toStringTag,{value:"Module"})),Nn=t=>[...new Set(t)],Xu=(t,e,r=!0)=>{const n=new Map;return t.forEach(a=>{const i=e(a);if(n.has(i)){if(r)return;n.delete(i)}n.set(i,a)}),Array.from(n.values())},Ws=Object.freeze(Object.defineProperty({__proto__:null,by:Xu,unique:Nn},Symbol.toStringTag,{value:"Module"}));class dt{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const Qu=t=>t!=null&&typeof t=="object"&&"toString"in t,Ur=(t,e=!1)=>{const r=Qu(t)?"stringer":typeof t;let n;switch(r){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${r}`),()=>-1}return e?hi(n):n},eh=(t,e,r)=>{const n=Ur(e[t],r);return(a,i)=>n(a[t],i[t])},th=(t,e)=>t.length!==e.length?t.length-e.length:t.every((r,n)=>r===e[n])?0:-1,ui=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const r=Ur(t[0]),n=[...t].sort(r),a=[...e].sort(r);return n.every((i,o)=>i===a[o])?0:-1},rh=(t,e)=>{const r=Nn(t),n=Nn(e);return ui(r,n)},nh=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,hi=t=>(e,r)=>t(r,e),ft=0,yr=-1,gr=1,di=t=>t<ft,fi=t=>t>ft,sh=t=>t>=ft,pi=t=>t===ft,ah=(t,e)=>{const r=/([a-zA-Z]+)|(\d+)/g,n=t.replace(/[\s_.-]+/g,"").match(r),a=e.replace(/[\s_.-]+/g,"").match(r);if(!n||!a)return 0;for(let i=0;i<Math.min(n.length,a.length);i++){const o=n[i],l=a[i];if(isNaN(Number(o))&&isNaN(Number(l))){const c=o.localeCompare(l);if(c!==0)return c}else if(!isNaN(Number(o))&&!isNaN(Number(l))){const c=Number(o)-Number(l);if(c!==0)return c}else return isNaN(Number(o))?-1:1}return n.length-a.length},Gs=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:ft,GREATER_THAN:gr,LESS_THAN:yr,isEqualTo:pi,isGreaterThan:fi,isGreaterThanEqual:sh,isLessThan:di,newF:Ur,newFieldF:eh,order:nh,primitiveArrays:th,reverseF:hi,stringsWithNumbers:ah,uniqueUnorderedPrimitiveArrays:rh,unorderedPrimitiveArrays:ui},Symbol.toStringTag,{value:"Module"})),Mr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const yi=s.z.object({width:s.z.number(),height:s.z.number()}),ih=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),oh=["width","height"];s.z.enum(oh);const lh=["start","center","end"],ch=["signedWidth","signedHeight"];s.z.enum(ch);const Tr=s.z.object({x:s.z.number(),y:s.z.number()}),uh=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),hh=["x","y"],gi=s.z.enum(hh),mi=["top","right","bottom","left"];s.z.enum(mi);const dh=["left","right"],wi=s.z.enum(dh),fh=["top","bottom"],bi=s.z.enum(fh),vi=["center"],Ks=s.z.enum(vi),ph=[...mi,...vi],Ti=s.z.enum(ph);s.z.enum(lh);const yh=["first","last"];s.z.enum(yh);const gh=s.z.object({lower:s.z.number(),upper:s.z.number()}),mh=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([gh,Mr]);s.z.union([mh,Mr]);s.z.enum([...gi.options,...Ti.options]);s.z.union([gi,Ti,s.z.instanceof(String)]);const Yt=t=>(e,r)=>{if(typeof e=="bigint"){if(Oi(r))return t(e,BigInt(r));const n=t(Number(e),Number(r));return typeof n=="number"?BigInt(Math.round(n)):n}return t(Number(e),Number(r))},Ze=Yt((t,e)=>t-e),Vt=Yt((t,e)=>t+e),Js=(t,e)=>{const r=typeof t=="bigint";return r&&typeof e=="bigint"?t===e:r&&Oi(e)?t===BigInt(e):t===e},wh=Yt((t,e)=>t<=e?t:e),Oi=t=>typeof t=="bigint"?!0:Number.isInteger(t),bh=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,fe=Yt((t,e)=>t*e),Lr=Yt((t,e)=>t/e),Z=(t,e,r)=>{const n={};if(typeof e=="object"&&(r=e,e=void 0),r={makeValid:!0,...r},typeof t=="number"||typeof t=="bigint")e!=null?(n.lower=t,n.upper=e):(n.lower=typeof t=="bigint"?0n:0,n.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=t}else n.lower=t.lower,n.upper=t.upper;return r?.makeValid?vh(n):n},vh=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Xs=(t,e)=>{const r=Z(t);return e<r.lower?r.lower:e>=r.upper?r.upper-(typeof r.upper=="number"?1:1n):e},or=(t,e)=>{const r=Z(t);if(typeof e=="number"||typeof e=="bigint")return e>=r.lower&&e<r.upper;const n=Z(e);return n.lower>=r.lower&&n.upper<=r.upper},Th=t=>({lower:Math.min(...t.map(e=>Z(e).lower)),upper:Math.max(...t.map(e=>Z(e).upper))}),Oh=(t,e,r)=>{const n=t.map(l=>Z(l)),a=r>0?1:r<0?-1:0;if(a===0)return e;let i=r,o=e;for(;Js(i,0)===!1;){const l=n.findIndex(c=>a>0?o>=c.lower&&o<c.upper:o>c.lower&&o<=c.upper);if(l!==-1){const c=n[l];let u;if(a>0?u=Ze(c.upper,o):u=Ze(o,c.lower),u>0){const h=wh(bh(i),u);if(o=Vt(o,a>0?h:-h),i=Ze(i,a>0?h:-h),Js(i,0))return o;continue}}if(a>0){const c=n.filter(u=>u.lower>o);if(c.length>0)o=c[0].lower;else return o}else{const c=n.filter(u=>u.upper<o);if(c.length>0)o=c[c.length-1].upper;else return o}}return o},Sh=(t,e,r)=>{const n=t.map(o=>Z(o));if(e===r)return typeof e=="bigint"?0n:0;const a=e<r?Z([e,r]):Z([r,e]);let i=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>a.lower?o.lower:a.lower,c=o.upper<a.upper?o.upper:a.upper;if(l<c){const u=c-l;i=i+u}}return i};s.z.object({x:wi.or(Ks),y:bi.or(Ks)});const zh=s.z.object({x:wi,y:bi}),Eh=Object.freeze({x:"left",y:"top"}),Nh=(t,e)=>t.x===e.x&&t.y===e.y,Qs=s.z.union([s.z.number(),Tr,Mr,yi,ih,uh]),Ah=(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}},ea=Object.freeze({x:0,y:0}),lr=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:lr,left:lr,width:lr,height:lr});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Tr,two:Tr,root:zh});const ls=(t,e,r=0,n=0,a)=>{const i={one:{...ea},two:{...ea},root:a??Eh};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:t,y:e},i.two={x:i.one.x+r,y:i.one.y+n},i}return"one"in t&&"two"in t&&"root"in t?{...t,root:a??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(i.one={x:t.left,y:t.top},i.two={x:t.right,y:t.bottom},i):(i.one=t,e==null?i.two={x:i.one.x+r,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+r}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},en=t=>{const e=ls(t);return{lower:e.one.x,upper:e.two.x}},tn=t=>{const e=ls(t);return{lower:e.one.y,upper:e.two.y}},kh=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,xh=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([yi,xh,Tr,Mr]);const Ch=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:Qs,scale:Qs});s.z.object({offset:s.z.number(),scale:s.z.number()});const Ih=t=>(e,r,n,a)=>r==="dimension"?[e,n]:[e,a?n-t:n+t],jh=t=>(e,r,n,a)=>[e,a?n/t:n*t],Rh=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=t,c=i-a,u=l-o;if(r==="dimension")return[t,n*(u/c)];const h=(n-a)*(u/c)+o;return[t,h]},Uh=t=>(e,r,n)=>[t,n],Mh=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:a}=t;return[t,a-(r-n)]},Lh=t=>(e,r,n)=>{const{lower:a,upper:i}=t;return n=Ch(n,a,i),[e,n]};let ta=class Ke{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Ke().translate(e)}static magnify(e){return new Ke().magnify(e)}static scale(e,r){return new Ke().scale(e,r)}translate(e){const r=this.new(),n=Ih(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=jh(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=Z(e,r),a=this.new(),i=Rh(n);return i.type="scale",a.ops.push(i),a}clamp(e,r){const n=Z(e,r),a=this.new(),i=Lh(n);return i.type="clamp",a.ops.push(i),a}reBound(e,r){const n=Z(e,r),a=this.new(),i=Uh(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=Mh();e.type="invert";const r=this.new();return r.ops.push(e),r}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Ke;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,r){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||r.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&r.push([a,i])}),r.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Ke};(class ce{x;y;currRoot;constructor(e=new ta,r=new ta,n=null){this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new ce().translate(e,r)}static translateX(e){return new ce().translateX(e)}static translateY(e){return new ce().translateY(e)}static clamp(e){return new ce().clamp(e)}static magnify(e){return new ce().magnify(e)}static scale(e){return new ce().scale(e)}static reBound(e){return new ce().reBound(e)}translate(e,r){const n=Ah(e,r),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(kh(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!Nh(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(en(e)),r.y=r.y.scale(tn(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(en(e)),r.y=this.y.reBound(tn(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(en(e)),r.y=this.y.clamp(tn(e)),r}copy(){const e=new ce;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 ls(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 ce});let Si=(t,e=21)=>(r=e)=>{let n="",a=r|0;for(;a--;)n+=t[Math.random()*t.length|0];return n};const zi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ph=`0123456789${zi}`,Ei=11,Dh=Si(zi,1),Bh=Si(Ph,Ei-1),cs=()=>`${Dh()}${Bh()}`,$h=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:Ei,create:cs},Symbol.toStringTag,{value:"Module"})),Fh=(t,e)=>r=>r instanceof e||typeof r=="object"&&r!==null&&"discriminator"in r&&r.discriminator===t,qh=s.z.enum(["static","dynamic"]),Zh=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),Ni=(t,e)=>{const r=new E(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(a=>a.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof E?new E(n):new z(n)};let E=class b extends dt{constructor(e,r="UTC"){if(e==null)super(b.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*b.MILLISECOND.valueOf());else if(typeof e=="string")super(b.parseDateTimeString(e,r).valueOf());else if(Array.isArray(e))super(b.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,r=1,n=1]){const a=new Date(e,r-1,n,0,0,0,0);return new b(BigInt(a.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,a,i]=e.split(":");let o="00",l="00";i!=null&&([o,l]=i.split("."));let c=b.hours(parseInt(n??"00")).add(b.minutes(parseInt(a??"00"))).add(b.seconds(parseInt(o??"00"))).add(b.milliseconds(parseInt(l??"00")));return r==="local"&&(c=c.add(b.utcOffset)),c.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new b(BigInt(n.getTime())*b.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(b.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new z(BigInt(new Date().getTimezoneOffset())*b.MINUTE.valueOf())}static since(e){return new b().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new b(e).valueOf()}span(e){return this.range(e).span}range(e){return new M(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new b(e).valueOf()}afterEq(e){return this.valueOf()>=new b(e).valueOf()}before(e){return this.valueOf()<new b(e).valueOf()}beforeEq(e){return this.valueOf()<=new b(e).valueOf()}add(e){return new b(Vt(this.valueOf(),new z(e).valueOf()))}sub(e){return new b(Ze(this.valueOf(),new z(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(b.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const r=this.date();return r.setUTCFullYear(e),new b(r)}get month(){return this.date().getUTCMonth()}setMonth(e){const r=this.date();return r.setUTCMonth(e),new b(r)}get day(){return this.date().getUTCDate()}setDay(e){const r=this.date();return r.setUTCDate(e),new b(r)}get hour(){return this.date().getUTCHours()}setHour(e){const r=this.date();return r.setUTCHours(e),new b(r,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const r=this.date();return r.setUTCMinutes(e),new b(r)}get second(){return this.date().getUTCSeconds()}setSecond(e){const r=this.date();return r.setUTCSeconds(e),new b(r)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const r=this.date();return r.setUTCMilliseconds(e),new b(r)}toString(){return this.date().toISOString()}remainder(e){return Ni(this,e)}get isToday(){return this.truncate(z.DAY).equals(b.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new b(new Date)}static max(...e){let r=b.MIN;for(const n of e){const a=new b(n);a.after(r)&&(r=a)}return r}static min(...e){let r=b.MAX;for(const n of e){const a=new b(n);a.before(r)&&(r=a)}return r}static nanoseconds(e,r="UTC"){return new b(e,r)}static NANOSECOND=b.nanoseconds(1);static microseconds(e,r="UTC"){return b.nanoseconds(e*1e3,r)}static MICROSECOND=b.microseconds(1);static milliseconds(e,r="UTC"){return b.microseconds(e*1e3,r)}static MILLISECOND=b.milliseconds(1);static seconds(e,r="UTC"){return b.milliseconds(e*1e3,r)}static SECOND=b.seconds(1);static minutes(e,r="UTC"){return b.seconds(e*60,r)}static MINUTE=b.minutes(1);static hours(e,r="UTC"){return b.minutes(e*60,r)}static HOUR=b.hours(1);static days(e,r="UTC"){return b.hours(e*24,r)}static DAY=b.days(1);static MAX=new b((1n<<63n)-1n);static MIN=new b(0);static ZERO=new b(0);static z=s.z.union([s.z.instanceof(b),s.z.object({value:s.z.bigint()}).transform(e=>new b(e.value)),s.z.string().transform(e=>new b(BigInt(e))),s.z.number().transform(e=>new b(e)),s.z.bigint().transform(e=>new b(e)),s.z.date().transform(e=>new b(e)),s.z.custom(e=>e instanceof z).transform(e=>new b(e)),Zh.transform(e=>new b(e))]);static sort(e,r){return Number(e.valueOf()-r.valueOf())}},z=class T extends dt{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof T?e:e instanceof rn?e.period:e instanceof E?new T(e):["number","bigint"].includes(typeof e)?T.seconds(e):new T(e)}static fromMilliseconds(e){return e instanceof T?e:e instanceof rn?e.period:e instanceof E?new T(e):["number","bigint"].includes(typeof e)?T.milliseconds(e):new T(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new T(e).valueOf()}greaterThan(e){return this.valueOf()>new T(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new T(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new T(e).valueOf()}remainder(e){return Ni(this,e)}truncate(e){return new T(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(T.DAY),r=this.truncate(T.HOUR),n=this.truncate(T.MINUTE),a=this.truncate(T.SECOND),i=this.truncate(T.MILLISECOND),o=this.truncate(T.MICROSECOND),l=this.truncate(T.NANOSECOND),c=e,u=r.sub(e),h=n.sub(r),p=a.sub(n),d=i.sub(a),S=o.sub(i),N=l.sub(o);let x="";return c.isZero||(x+=`${c.days}d `),u.isZero||(x+=`${u.hours}h `),h.isZero||(x+=`${h.minutes}m `),p.isZero||(x+=`${p.seconds}s `),d.isZero||(x+=`${d.milliseconds}ms `),S.isZero||(x+=`${S.microseconds}µs `),N.isZero||(x+=`${N.nanoseconds}ns`),x.trim()}mult(e){return new T(fe(this.valueOf(),e))}div(e){return new T(Lr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(T.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(T.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(T.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(T.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(T.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new T(e).valueOf()}add(e){return new T(this.valueOf()+new T(e).valueOf())}sub(e){return new T(this.valueOf()-new T(e).valueOf())}static nanoseconds(e=1){return new T(e)}static NANOSECOND=T.nanoseconds(1);static microseconds(e=1){return T.nanoseconds(fe(e,1e3))}static MICROSECOND=T.microseconds(1);static milliseconds(e=1){return T.microseconds(fe(e,1e3))}static MILLISECOND=T.milliseconds(1);static seconds(e=1){return T.milliseconds(fe(e,1e3))}static SECOND=T.seconds(1);static minutes(e=1){return T.seconds(fe(e,60))}static MINUTE=T.minutes(1);static hours(e){return T.minutes(fe(e,60))}static HOUR=T.hours(1);static days(e){return T.hours(fe(e,24))}static DAY=T.days(1);static MAX=new T((1n<<63n)-1n);static MIN=new T(0);static ZERO=new T(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new T(e.value)),s.z.string().transform(e=>new T(BigInt(e))),s.z.number().transform(e=>new T(e)),s.z.bigint().transform(e=>new T(e)),s.z.instanceof(T),s.z.instanceof(E).transform(e=>new T(e)),s.z.custom(e=>e instanceof rn).transform(e=>new T(e))])},rn=class ue extends dt{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ue(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new _(r).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}add(e){return new ue(Vt(this.valueOf(),e.valueOf()))}sub(e){return new ue(Ze(this.valueOf(),e.valueOf()))}mult(e){return new ue(fe(this.valueOf(),e))}div(e){return new ue(Lr(this.valueOf(),e))}static hz(e){return new ue(e)}static khz(e){return ue.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new ue(e)),s.z.instanceof(ue)])},_=class K extends dt{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new at(e*this.valueOf())}add(e){return new K(Vt(this.valueOf(),e.valueOf()))}sub(e){return new K(Ze(this.valueOf(),e.valueOf()))}mult(e){return new K(fe(this.valueOf(),e))}div(e){return new K(Lr(this.valueOf(),e))}static UNKNOWN=new K(0);static BIT128=new K(16);static BIT64=new K(8);static BIT32=new K(4);static BIT16=new K(2);static BIT8=new K(1);static z=s.z.union([s.z.number().transform(e=>new K(e)),s.z.instanceof(K)])},M=class he{start;end;constructor(e,r){typeof e=="object"&&"start"in e?(this.start=new E(e.start),this.end=new E(e.end)):(this.start=new E(e),this.end=new E(r))}get span(){return new z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new he(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,r=z.ZERO){if(r.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=r.valueOf()&&a<=r.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,r=z.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const a=E.max(n.start,e.start),i=E.min(n.end,e.end);return i.before(a)?!1:new z(i.sub(a)).greaterThanOrEqual(r)}contains(e){return e instanceof he?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new he(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}static max(...e){return new he(E.min(...e.map(r=>r.start)),E.max(...e.map(r=>r.end)))}static MAX=new he(E.MIN,E.MAX);static MIN=new he(E.MAX,E.MIN);static ZERO=new he(E.ZERO,E.ZERO);static z=s.z.union([s.z.object({start:E.z,end:E.z}).transform(e=>new he(e.start,e.end)),s.z.instanceof(he)]);static sort(e,r){return E.sort(e.start,r.start)||E.sort(e.end,r.end)}},k=class g extends dt{constructor(e){if(e instanceof g||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const r=g.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r==null)throw new Error(`unable to find data type for ${e.toString()}`);super(r.valueOf())}}get Array(){const e=g.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(g.JSON)||this.equals(g.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(g.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=g.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(g.UINT8)||this.equals(g.UINT16)||this.equals(g.UINT32)||this.equals(g.UINT64)}get isSignedInteger(){return this.equals(g.INT8)||this.equals(g.INT16)||this.equals(g.INT32)||this.equals(g.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(g.INT32)&&e.equals(g.FLOAT64)||this.equals(g.INT8)&&e.equals(g.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return g.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new g("unknown");static FLOAT64=new g("float64");static FLOAT32=new g("float32");static INT64=new g("int64");static INT32=new g("int32");static INT16=new g("int16");static INT8=new g("int8");static UINT64=new g("uint64");static UINT32=new g("uint32");static UINT16=new g("uint16");static UINT8=new g("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new g("timestamp");static UUID=new g("uuid");static STRING=new g("string");static JSON=new g("json");static ARRAY_CONSTRUCTORS=new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]]);static DENSITIES=new Map([[g.UINT8.toString(),_.BIT8],[g.UINT16.toString(),_.BIT16],[g.UINT32.toString(),_.BIT32],[g.UINT64.toString(),_.BIT64],[g.FLOAT32.toString(),_.BIT32],[g.FLOAT64.toString(),_.BIT64],[g.INT8.toString(),_.BIT8],[g.INT16.toString(),_.BIT16],[g.INT32.toString(),_.BIT32],[g.INT64.toString(),_.BIT64],[g.TIMESTAMP.toString(),_.BIT64],[g.STRING.toString(),_.UNKNOWN],[g.JSON.toString(),_.UNKNOWN],[g.UUID.toString(),_.BIT128]]);static ALL=[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON];static BIG_INT_TYPES=[g.INT64,g.UINT64,g.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new g(e)),s.z.instanceof(g)])},at=class j extends dt{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new j(Vt(this.valueOf(),e.valueOf()))}sub(e){return new j(Ze(this.valueOf(),e.valueOf()))}mult(e){return new j(fe(this.valueOf(),e))}div(e){return new j(Lr(this.valueOf(),e))}truncate(e){return new j(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return j.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/j.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/j.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/j.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/j.TERABYTE.valueOf()}toString(){const e=this.truncate(j.TERABYTE),r=this.truncate(j.GIGABYTE),n=this.truncate(j.MEGABYTE),a=this.truncate(j.KILOBYTE),i=this.truncate(j.BYTE),o=e,l=r.sub(e),c=n.sub(r),u=a.sub(n),h=i.sub(a);let p="";return o.isZero||(p+=`${o.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),c.isZero||(p+=`${c.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new j(e)}static BYTE=new j(1);static kilobytes(e=1){return j.bytes(e.valueOf()*1e3)}static KILOBYTE=j.kilobytes(1);static megabytes(e=1){return j.kilobytes(e.valueOf()*1e3)}static MEGABYTE=j.megabytes(1);static gigabytes(e=1){return j.megabytes(e.valueOf()*1e3)}static GIGABYTE=j.gigabytes(1);static terabytes(e){return j.gigabytes(e.valueOf()*1e3)}static TERABYTE=j.terabytes(1);static ZERO=new j(0);static z=s.z.union([s.z.number().transform(e=>new j(e)),s.z.instanceof(j)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Ai=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof E||t instanceof z||t instanceof Date},Yh=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r.valueOf())-BigInt(n.valueOf()):mr(r,-n),mr=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),Vh=/^(?:[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 Hh(t){return typeof t=="string"&&Vh.test(t)}const q=[];for(let t=0;t<256;++t)q.push((t+256).toString(16).slice(1));function _h(t,e=0){return(q[t[e+0]]+q[t[e+1]]+q[t[e+2]]+q[t[e+3]]+"-"+q[t[e+4]]+q[t[e+5]]+"-"+q[t[e+6]]+q[t[e+7]]+"-"+q[t[e+8]]+q[t[e+9]]+"-"+q[t[e+10]]+q[t[e+11]]+q[t[e+12]]+q[t[e+13]]+q[t[e+14]]+q[t[e+15]]).toLowerCase()}function Wh(t,e=0){const r=_h(t,e);if(!Hh(r))throw TypeError("Stringified UUID is invalid");return r}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const ki=(t,e)=>Wh(t,e),ze=-1,An={[Symbol.iterator]:()=>An,next:()=>({done:!0,value:void 0})},Gh=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Kh=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),kn=10,xi=(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`)},Ci="sy_x_telem_series";let Ie=class ke{key;discriminator=Ci;dataType;sampleOffset;gl;_data;timeRange=M.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=ze;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:M.z.optional(),dataType:k.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Gh,Kh,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:qh.optional().default("static").optional()});static z=ke.crudeZ.transform(e=>new ke(e));constructor(e){Jh(e)&&(e={data:e}),e.data??=[];const{dataType:r,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:l=1n,key:c=cs(),data:u}=e;if(Ii(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=Ai(u),p=Array.isArray(u);if(r!=null)this.dataType=new k(r);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(p||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=k.STRING;else if(typeof d=="number")this.dataType=k.FLOAT64;else if(typeof d=="bigint")this.dataType=k.INT64;else if(typeof d=="boolean")this.dataType=k.BOOLEAN;else if(d instanceof E||d instanceof Date||d instanceof E)this.dataType=k.TIMESTAMP;else if(typeof d=="object")this.dataType=k.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new k(u)}if(!p&&!h)this._data=u;else if(p&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[u]:u;const S=d[0];(S instanceof E||S instanceof Date||S instanceof z)&&(d=d.map(N=>new E(N).valueOf())),this.dataType.equals(k.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
9
+ `)}
10
+ `).buffer):this.dataType.equals(k.JSON)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(N=>It.encodeString(N)).join(`
11
+ `)}
12
+ `).buffer):this.dataType.usesBigInt&&typeof S=="number"?this._data=new this.dataType.Array(d.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof S=="bigint"?this._data=new this.dataType.Array(d.map(Number)).buffer:this._data=new this.dataType.Array(d).buffer}this.key=c,this.alignment=o,this.alignmentMultiple=l,this.sampleOffset=a??0,this.timeRange=n??M.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:r,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new k(r).Array(e),i=new ke({data:a.buffer,dataType:r,...n});return i.writePos=0,i}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===ze)return 0;const r=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,r);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===ze)return 0;const r=this.capacity-this.writePos,n=e.sub(0,r);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===ze?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
13
+ `).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(k.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(r=>e.parse(It.decodeString(r)))}get byteCapacity(){return new at(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ze?this.byteCapacity:this.dataType.isVariable?new at(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ze?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const r=[0];return this.data.forEach((n,a)=>{n===kn&&(e++,r.push(a+1))}),this._cachedIndexes=r,this.cachedLength=e,e}convert(e,r=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=Yh(this.dataType,e,this.data[a],r);return new ke({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(k.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),mr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(k.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),mr(this.cachedMin,this.sampleOffset))}get bounds(){return Z(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const r=e.cachedMin??e.calcRawMin();r<this.cachedMin&&(this.cachedMin=r)}if(this.cachedMax!=null){const r=e.cachedMax??e.calcRawMax();r>this.cachedMax&&(this.cachedMax=r)}}atAlignment(e,r){const n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(r===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,r)}at(e,r=!1){if(this.dataType.isVariable)return this.atVariable(e,r??!1);if(this.dataType.equals(k.UUID))return this.atUUID(e,r);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return mr(n,this.sampleOffset)}atUUID(e,r){e<0&&(e=this.length+e);const n=ki(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(r)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,r){let n=0,a=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],a=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===kn){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(k.STRING)?new TextDecoder().decode(i):os(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let r=0,n=this.length-1;const a=Ur(e);for(;r<=n;){const i=Math.floor((r+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?r=i+1:n=i-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(k.FLOAT32)&&!this.dataType.equals(k.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:a}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==ze){a===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(a).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,i,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ze}as(e){return xi(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:na(this.alignmentBounds.lower),upper:na(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return Z(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 Xh(this);return this.dataType.equals(k.JSON)?new Qh(e):e}return this.dataType.equals(k.UUID)?new ed(this):new td(this)}slice(e,r){return this.sliceSub(!1,e,r)}sub(e,r){return this.sliceSub(!0,e,r)}subIterator(e,r){return new ra(this,e,r??this.length)}subAlignmentIterator(e,r){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),a=Math.ceil(Number(r-this.alignment)/Number(this.alignmentMultiple));return new ra(this,n,a)}subBytes(e,r){if(e>=0&&(r==null||r>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,r);return new ke({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,r,n){if(r<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(r,n):a=this.data.slice(r,n),new ke({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(r)})}reAlign(e){return new ke({data:this.buffer,dataType:this.dataType,timeRange:M.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(r=>r.toString());else{for(let r=0;r<5;r++)e+=`${this.at(r)?.toString()}`,e+=",";e+="...,";for(let r=-5;r<0;r++)e+=this.at(r)?.toString(),r<-1&&(e+=",")}return e+="])",e}};const Jh=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Ie?!0:Ai(t),Ii=Fh(Ci,Ie);class ra{series;end;index;constructor(e,r,n){this.series=e;const a=Z(0,e.length+1);this.end=Xs(a,n),this.index=Xs(a,r)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let Xh=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]!==kn;)this.index++;const r=this.index;return t===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(t,r))})}},Qh=class ji{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:It.decodeString(e.value,ji.schema)}}};class ed{series;index;data;density;constructor(e){if(!e.dataType.equals(k.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=k.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=ki(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let td=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)}}},rd=class{series;constructor(t=[]){if(t.length!==0){const e=t[0].dataType;for(let r=1;r<t.length;r++)if(!t[r].dataType.equals(e))throw new Error("[multi-series] - series must have the same data type")}this.series=t}as(t){return xi(t,this.dataType),this}get dataType(){return this.series.length===0?k.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?M.ZERO:new M(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?Z(0n,0n):Z(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(t){const e=()=>new Error(`cannot push a ${t.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),r=t.dataType.equals(this.dataType);if(Ii(t)){if(this.series.length!==0&&!r)throw e();this.series.push(t)}else{if(this.series.length!==0&&t.series.length!==0&&!r)throw e();this.series.push(...t.series)}}get length(){return this.series.reduce((t,e)=>t+e.length,0)}atAlignment(t,e){for(const r of this.series)if(or(r.alignmentBounds,t))return r.atAlignment(t,e);if(e)throw new Error(`[series] - no value at alignment ${t}`)}at(t,e=!1){t<0&&(t=this.length+t);for(const r of this.series){if(t<r.length)return r.at(t,e);t-=r.length}if(e)throw new Error(`[series] - no value at index ${t}`)}subIterator(t,e){return new nn(this,t,e??this.length)}subAlignmentIterator(t,e){if(t>=this.alignmentBounds.upper||e<=this.alignmentBounds.lower)return An;let r=0;for(let a=0;a<this.series.length;a++){const i=this.series[a];if(t<i.alignment)break;if(t>=i.alignmentBounds.upper)r+=i.length;else if(or(i.alignmentBounds,t)){r+=Math.ceil(Number(t-i.alignment)/Number(i.alignmentMultiple));break}}let n=0;for(let a=0;a<this.series.length;a++){const i=this.series[a];if(e<i.alignment)break;if(e>=i.alignmentBounds.upper)n+=i.length;else if(or(i.alignmentBounds,e)){n+=Math.ceil(Number(e-i.alignment)/Number(i.alignmentMultiple));break}}return new nn(this,r,n)}subAlignmentSpanIterator(t,e){if(t>=this.alignmentBounds.upper)return An;e=Math.min(e,Number(this.distance(t,this.alignmentBounds.upper)));let r=0;for(let n=0;n<this.series.length;n++){const a=this.series[n];if(t<a.alignment)break;if(t>=a.alignmentBounds.upper)r+=a.length;else if(or(a.alignmentBounds,t)){r+=Number(t-a.alignment);break}}return new nn(this,r,r+e)}updateGLBuffer(t){this.series.forEach(e=>e.updateGLBuffer(t))}get bounds(){return Th(this.series.map(t=>t.bounds))}get byteLength(){return new at(this.series.reduce((t,e)=>t+e.byteLength.valueOf(),0))}get data(){const t=new this.dataType.Array(this.length);let e=0;for(const r of this.series)t.set(r.data,e),e+=r.length;return new this.dataType.Array(t.buffer)}traverseAlignment(t,e){const r=this.series.map(n=>n.alignmentBounds);return Oh(r,t,e)}acquire(t){this.series.forEach(e=>e.acquire(t))}release(){this.series.forEach(t=>t.release())}distance(t,e){const r=this.series.map(n=>n.alignmentBounds);return Sh(r,t,e)}parseJSON(t){if(!this.dataType.equals(k.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(e=>e.parseJSON(t))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new nd(this.series)}toStrings(){return this.series.flatMap(t=>t.toStrings())}},nd=class{series;seriesIndex;internal;constructor(t){this.series=t,this.seriesIndex=0,this.internal=t[0][Symbol.iterator]()}next(){const t=this.internal.next();return t.done===!1?t:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}};class nn{series;index;end;constructor(e,r,n){this.series=e,this.end=n,this.index=r}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const na=t=>{const e=t>>32n,r=t&0xffffffffn;return{domain:e,sample:r}},sd=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},ad=(t,e,r=".")=>{const n=t.split(r);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(r)}).filter(a=>a!=null).join(r)},id=(t,e)=>{if(!Array.isArray(t))return t[e];const r=t[e];if(r!=null||t.length==0)return r;const n=t[0];if(typeof n=="object"&&"key"in n)return t.find(a=>a.key===e)},od=(t,e,r={optional:!1,separator:"."})=>{r.separator??=".";const{optional:n,getter:a=id}=r,i=e.split(r.separator);if(i.length===1&&i[0]==="")return t;let o=t;for(const l of i){const c=a(o,l);if(c==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=c}return o};s.z.object({key:s.z.string(),value:s.z.string()});class ld{handlers;transform;closer;constructor(e,r){this.transform=e,this.handlers=r??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let r=e;if(this.transform!=null){const[n,a]=this.transform(e);if(!a)return;r=n}this.handlers.forEach((n,a)=>a(r))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}let cd=class{handlers;constructor(t){this.handlers=t??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){this.handlers.forEach((e,r)=>r(t))}};const ud=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:cd,Observer:ld},Symbol.toStringTag,{value:"Module"})),hd=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),us=t=>Object.entries(t),dd=(t,e)=>Object.fromEntries(us(t).map(([r,n])=>[r,e(n,r)])),fd=t=>Object.fromEntries(us(t).filter(([e,r])=>r!==void 0)),ve=Object.freeze(Object.defineProperty({__proto__:null,entries:us,map:dd,purgeUndefined:fd,unknownZ:hd},Symbol.toStringTag,{value:"Module"})),pd=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";pd();const yd=["macOS","Windows","Linux"],gd=["macos","windows","linux"],md={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(yd).or(s.z.enum(gd).transform(t=>md[t]));const wd=(...t)=>t.map(Ri).join(""),Ri=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),bd=t=>t.endsWith("/")?t.slice(0,-1):t;class kt{protocol;host;port;path;constructor({host:e,port:r,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=r,this.path=Ri(a)}replace(e){return new kt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new kt({...this,pathPrefix:wd(this.path,e)})}toString(){return bd(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new kt({host:"unknown",port:0})}const vd=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),Td=t=>s.array(t).or(t.transform(e=>[e])),Ui=t=>ad(t,(e,r,n)=>{const a=r===n.length-1,i=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[r+1]));return i&&(e="element"),a||o?e:[e,"shape"]}),sa=(t,e)=>{if(t==null)return null;const r=t[e];return r==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:r},Od=(t,e,r)=>e===""?t:od(sa(t,"shape"),Ui(e),{...r,getter:sa}),xt=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:Od,getFieldSchemaPath:Ui,nullToUndefined:vd,toArray:Td},Symbol.toStringTag,{value:"Module"})),Sd=async t=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(t).milliseconds));class zd{config;retries;interval;constructor(e){this.config={baseInterval:new z(e?.baseInterval??z.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Sd},this.retries=0,this.interval=new z(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:r,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(r),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Ed=s.z.object({baseInterval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Mi=Object.freeze(Object.defineProperty({__proto__:null,Breaker:zd,breakerConfigZ:Ed},Symbol.toStringTag,{value:"Module"})),Nd=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Li=s.z.string().regex(Nd),nt=s.z.number().min(0).max(255),Pi=s.z.number().min(0).max(1),Di=s.z.tuple([nt,nt,nt,Pi]),Ad=s.z.tuple([nt,nt,nt]),kd=s.z.object({rgba255:Di}),xd=s.z.number().min(0).max(360),Cd=s.z.number().min(0).max(100),Id=s.z.number().min(0).max(100),jd=s.z.tuple([xd,Cd,Id,Pi]),hs=s.z.union([Li,Ad,Di,jd,kd]),Rd=hs.transform(t=>ds(t)),ds=(t,e=1)=>{if(t=hs.parse(t),typeof t=="string")return Ud(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},Ud=(t,e=1)=>(t=Li.parse(t),t=Md(t),[cr(t,0),cr(t,2),cr(t,4),t.length===8?cr(t,6)/255:e]),cr=(t,e)=>parseInt(t.slice(e,e+2),16),Md=t=>t.startsWith("#")?t.slice(1):t;ds("#000000");ds("#ffffff");const Ld=s.z.object({key:s.z.string(),color:hs,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(Ld);const Pd=s.z.object({key:s.z.string(),name:s.z.string(),color:Rd});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(Pd)});const Bi=s.z.int().min(0).max(255),$i=255,Fi=0,Dd={lower:Fi,upper:$i+1},qi=s.z.object({name:s.z.string(),key:s.z.string()}),jt=t=>s.z.object({subject:qi,resource:t,authority:Bi}),Bd=(...t)=>e=>e.filter(r=>{let n=!1;return r.to!=null&&(n=t.includes(r.to.resource)),r.from!=null&&!n&&(n=t.includes(r.from.resource)),n}),Zi=t=>s.z.object({from:jt(t),to:s.z.null()}),Yi=t=>s.z.object({from:s.z.null(),to:jt(t)}),$d=t=>s.z.union([Zi(t),Yi(t),s.z.object({from:jt(t),to:jt(t)})]),ee=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:$i,AUTHORITY_BOUNDS:Dd,ZERO_AUTHORITY:Fi,acquireZ:Yi,authorityZ:Bi,filterTransfersByChannelKey:Bd,releaseZ:Zi,stateZ:jt,subjectZ:qi,transferZ:$d},Symbol.toStringTag,{value:"Module"})),Fd=t=>Object.getOwnPropertySymbols(globalThis).includes(t),qd=(t,e)=>{const r=Symbol.for(t);if(!Fd(r)){const n=e();Object.defineProperty(globalThis,r,{value:n})}return()=>globalThis[r]},Vi="sy_x_error",Zd=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),Ht=t=>class At extends Error{static discriminator=Vi;discriminator=At.discriminator;static TYPE=t;type=At.TYPE;static matches=Zd(t);matches=At.matches;constructor(r,n){super(r,n),this.name=At.TYPE}static sub(r){return Ht(`${t}.${r}`)}},Hi=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Vi)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Je="unknown",xn="nil";class Yd{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:xn,data:""};if(Hi(e))for(const r of this.providers){const n=r.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Je,data:e.message};if(typeof e=="string")return{type:Je,data:e};try{return{type:Je,data:JSON.stringify(e)}}catch{return{type:Je,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===xn)return null;if(e.type===Je)return new Cn(e.data);for(const r of this.providers){const n=r.decode(e);if(n!=null)return n}return new Cn(e.data)}}const fs=qd("synnax-error-registry",()=>new Yd),Vd=({encode:t,decode:e})=>fs().register({encode:t,decode:e}),Hd=t=>fs().encode(t),_d=t=>t==null?null:fs().decode(t);class Cn extends Ht("unknown"){}const Wd=s.z.object({type:s.z.string(),data:s.z.string()});class Gd extends Ht("canceled"){}class Kd extends Ht("not_implemented"){}const be=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Gd,NONE:xn,NotImplemented:Kd,UNKNOWN:Je,Unknown:Cn,createTyped:Ht,decode:_d,encode:Hd,isTyped:Hi,payloadZ:Wd,register:Vd},Symbol.toStringTag,{value:"Module"})),Jd=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),_i=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),Xd=_i.extend({result:s.json()}),Qd=_i.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),ef=s.union([Xd,Qd]);s.union([Jd,ef]);const In=s.z.string().regex(/^\d+\.\d+\.\d+$/),_t=(t,e,r={})=>{r.checkMajor??=!0,r.checkMinor??=!0,r.checkPatch??=!0;const n=In.parse(t),a=In.parse(e),[i,o,l]=n.split(".").map(Number),[c,u,h]=a.split(".").map(Number);if(r.checkMajor){if(i<c)return yr;if(i>c)return gr}if(r.checkMinor){if(o<u)return yr;if(o>u)return gr}if(r.checkPatch){if(l<h)return yr;if(l>h)return gr}return ft},tf=(t,e,r={})=>pi(_t(t,e,r)),Wi=(t,e,r={})=>fi(_t(t,e,r)),rf=(t,e,r={})=>di(_t(t,e,r)),nf=({name:t,migrate:e})=>r=>{try{const n=e(r);return console.log(`${t} migrated: ${r.version} -> ${n.version}`),n}catch(n){throw console.log(`${t} failed to migrate from ${r.version}`),console.error(n),n}},sf=({name:t,migrations:e,targetSchema:r,defaultVersion:n,def:a})=>{const i=Object.keys(e).sort(_t).pop();if(i==null)return u=>{if(u.version??=n,u.version!==a.version)return console.log(`${t} version ${u.version} is newer than latest version of ${a.version}.
14
+ Returning default instead.
15
+ `),a;try{return r!=null?r.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),a}};const o=Object.keys(e).length;let l=!1;const c=u=>{try{if(o===0||Wi(u.version,i))return console.log(l?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${a.version}`),u;const h=u.version,p=e[h],d=p(u);return l=!0,c(d)}catch(h){return console.log(`${t} failed to migrate from ${u.version} to ${i}`),console.error(h),a}};return u=>{try{if(u.version==null)if(n!=null)console.log(`${t} version is null. Setting version to default of ${n}`),u.version=n;else return console.log(`${t} version is null and no default version set. Exiting with default`),a;return c(u)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),a}}},aa=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:_t,createMigration:nf,migrator:sf,semVerNewer:Wi,semVerOlder:rf,semVerZ:In,versionsEqual:tf},Symbol.toStringTag,{value:"Module"})),af=["standard","scientific","engineering"];s.z.enum(af);const Gi=s.z.enum(["success","info","warning","error","loading","disabled"]),of=t=>s.z.object({key:s.z.string(),variant:Gi,message:s.z.string(),description:s.z.string().optional(),time:E.z,details:t??s.z.unknown().optional()}),lf=(t,e)=>{if(!(t instanceof Error))throw t;return Ki({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??""}})},Ki=t=>({key:cs(),time:E.now(),...t}),cf=(t,e=[])=>Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0,Wt=Object.freeze(Object.defineProperty({__proto__:null,create:Ki,filterVariant:cf,fromException:lf,statusZ:of,variantZ:Gi},Symbol.toStringTag,{value:"Module"})),uf=(t,e="")=>{if(typeof t=="string")return t;const r=t.length;return r===0?e:r===1?t[0]:r===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[r-1]}`},hf=t=>{const e=t.split(" "),r=new Set,n=e.map(o=>o.charAt(0).toLowerCase()).join("");r.add(n.replace(/-/g,"_")),r.add(n.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const a=/\d+/g;t.match(a)&&e.forEach((o,l)=>{if(a.test(o)){const c=e.map((u,h)=>h!==l?u.charAt(0).toLowerCase():u).join("");r.add(c.replace(/-/g,"_")),r.add(c.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const i=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return r.add(i.join("").replace(/-/g,"_")),r.add(i.join("_").replace(/-/g,"_")),Array.from(r).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},df=(t,e)=>t.startsWith(e)?t.slice(e.length):t,jn=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:hf,naturalLanguageJoin:uf,trimPrefix:df},Symbol.toStringTag,{value:"Module"})),ff="all",pf="create",yf="delete",gf="retrieve",mf="update",Rn=s.z.enum([ff,pf,yf,gf,mf]);let pe=class extends be.createTyped("sy"){},$=class extends pe.sub("validation"){};class Rt extends $.sub("path"){path;error;static encodedSchema=s.z.object({path:s.z.string().array(),error:be.payloadZ});constructor(e,r){const n=O.toArray(e);super(`${n.join(".")}: ${r.message}`),this.path=n.flatMap(a=>a.split(".")),this.error=r}static decode(e){const r=Rt.encodedSchema.parse(JSON.parse(e.data));return new Rt(r.path,be.decode(r.error))}}class Or extends pe.sub("auth"){}class Un extends Or.sub("invalid_token"){}class Mn extends Or.sub("expired_token"){}class W extends pe.sub("unexpected"){constructor(e){super(`
16
+ Unexpected error encountered:
17
+
18
+ ${e}
19
+
20
+ Please report this to the Synnax team.
21
+ `)}}class Le extends pe.sub("query"){}class it extends Le.sub("not_found"){}class Sr extends Le.sub("multiple_results"){}class ia extends pe.sub("route"){path;constructor(e,r){super(e),this.path=r}}class Ln extends pe.sub("control"){}class oa extends Ln.sub("unauthorized"){}class wf extends pe.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class lT extends pe.sub("contiguity"){}const bf=t=>t.type.startsWith(pe.TYPE)?t.type.startsWith($.TYPE)?t.type===Rt.TYPE?Rt.decode(t):new $(t.data):t.type.startsWith(Or.TYPE)?t.type.startsWith(Un.TYPE)?new Un(t.data):t.type.startsWith(Mn.TYPE)?new Mn(t.data):new Or(t.data):t.type.startsWith(W.TYPE)?new W(t.data):t.type.startsWith(Le.TYPE)?t.type.startsWith(it.TYPE)?new it(t.data):t.type.startsWith(Sr.TYPE)?new Sr(t.data):new Le(t.data):t.type.startsWith(Ln.TYPE)?t.type.startsWith(oa.TYPE)?new oa(t.data):new Ln(t.data):t.type.startsWith(ia.TYPE)?new ia(t.data,t.data):new W(t.data):null,vf=()=>{throw new be.NotImplemented};be.register({encode:vf,decode:bf});const Tf=async(t,e)=>{const[r,n]=await e(t);return n==null?[r,n]:n instanceof Me?[r,new Me({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[r,n]};class Ji{key;name;constructor(e,r){this.key=r,this.name=e}get ontologyID(){return Of(this.key)}}const Of=t=>({type:"group",key:t}),Pr=s.z.uuid(),ps=s.z.string(),Xi=s.z.object({key:Pr,name:ps}),Qi="builtin",Sf="cluster",zf="node",Dr=s.z.enum(["label","log","allow_all","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","table"]),Ef=s.z.string().transform(t=>{const[e,r]=t.split(":");return{type:Dr.parse(e),key:r??""}}),U=s.z.object({type:Dr,key:s.z.string()}).or(Ef),Nf={type:Qi,key:"root"},Ut=t=>`${t.type}:${t.key}`,Af=(t,e)=>t.type===e.type&&t.key===e.key,eo=t=>{const e=O.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:r})=>r):e.map(r=>U.parse(r))},to=s.z.object({id:U,name:s.z.string(),data:ve.unknownZ.optional().nullable()}).transform(t=>({key:Ut(t.id),...t})),kf=t=>t==="to"?"from":"to",xf=s.z.object({from:U,type:s.z.string(),to:U}).or(s.z.string().transform(t=>{const[e,r,n]=t.split("->");return{from:U.parse(e),type:r,to:U.parse(n)}})),Cf=t=>`${Ut(t.from)}->${t.type}->${Ut(t.to)}`,If="parent",jf=(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),Rf=s.z.object({group:Xi}),Uf=s.z.object({parent:U,key:Pr.optional(),name:ps}),Mf=s.z.object({key:Pr,name:ps}),Lf=s.z.object({keys:s.z.array(Pr)});let Pf=class wr{static CREATE_ENDPOINT="/ontology/create-group";static RENAME_ENDPOINT="/ontology/rename-group";static DELETE_ENDPOINT="/ontology/delete-group";client;constructor(e){this.client=e}async create(e,r,n){return(await m(this.client,wr.CREATE_ENDPOINT,{parent:e,name:r,key:n},Uf,Rf)).group}async rename(e,r){await m(this.client,wr.RENAME_ENDPOINT,{key:e,name:r},Mf,s.z.object({}))}async delete(e){await m(this.client,wr.DELETE_ENDPOINT,{keys:e},Lf,s.z.object({}))}},Df=class{creator;constructor(t){this.creator=new Pf(t)}async create(t,e,r){return this.sugar(await this.creator.create(t,e,r))}async rename(t,e){return await this.creator.rename(t,e)}async delete(...t){return await this.creator.delete(t)}sugar(t){return new Ji(t.name,t.key)}};const Bf="/ontology/add-children",$f="/ontology/remove-children",Ff="/ontology/move-children",la=s.z.object({id:U,children:U.array()}),qf=s.z.object({from:U,to:U,children:U.array()}),sn=s.z.object({});let Zf=class{client;constructor(t){this.client=t}async addChildren(t,...e){await m(this.client,Bf,{id:t,children:e},la,sn)}async removeChildren(t,...e){await m(this.client,$f,{id:t,children:e},la,sn)}async moveChildren(t,e,...r){await m(this.client,Ff,{from:t,to:e,children:r},qf,sn)}};const Yf="/ontology/retrieve",Vf=s.z.object({ids:U.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:Dr.array().optional()}),Hf=s.z.object({resources:to.array()});let ro=class{type="ontology";groups;client;writer;framer;constructor(t,e){this.client=t,this.writer=new Zf(t),this.groups=new Df(t),this.framer=e}async retrieve(t,e){if(!Array.isArray(t)&&typeof t=="object"&&!("key"in t))return this.execRetrieve(t);const r=eo(t),n=await this.execRetrieve({ids:r,...e});if(Array.isArray(t))return n;if(n.length===0)throw new Le(`No resource found with ID ${jn.naturalLanguageJoin(r.map(a=>Ut(a)))}`);return n[0]}async retrieveChildren(t,e){return await this.execRetrieve({ids:O.toArray(t),children:!0,...e})}async retrieveParents(t,e){return await this.execRetrieve({ids:O.toArray(t),parents:!0,...e})}async addChildren(t,...e){return await this.writer.addChildren(t,...e)}async removeChildren(t,...e){return await this.writer.removeChildren(t,...e)}async moveChildren(t,e,...r){return await this.writer.moveChildren(t,e,...r)}async execRetrieve(t){const{resources:e}=await m(this.client,Yf,t,Vf,Hf);return e}};const _f="sy_ontology_resource_set",Wf="sy_ontology_resource_delete",Gf="sy_ontology_relationship_set",Kf="sy_ontology_relationship_delete",Jf=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Qi,CLUSTER_TYPE:Sf,Client:ro,NODE_TYPE:zf,PARENT_OF_RELATIONSHIP_TYPE:If,RELATIONSHIP_DELETE_CHANNEL_NAME:Kf,RELATIONSHIP_SET_CHANNEL_NAME:Gf,RESOURCE_DELETE_CHANNEL_NAME:Wf,RESOURCE_SET_CHANNEL_NAME:_f,ROOT_ID:Nf,idToString:Ut,idZ:U,idsEqual:Af,matchRelationship:jf,oppositeRelationshipDirection:kf,parseIDs:eo,relationshipToString:Cf,relationshipZ:xf,resourceTypeZ:Dr,resourceZ:to},Symbol.toStringTag,{value:"Module"})),Y=t=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),t.array()]),Gt=s.z.uuid(),ys=s.z.object({key:Gt,subjects:Y(U),objects:Y(U),actions:Y(Rn)}),Xf=s.z.object({key:Gt.optional(),subjects:U.array().or(U),objects:U.array().or(U),actions:Rn.array().or(Rn)}),Qf=s.z.object({keys:Gt.array().optional(),subjects:U.array().optional()}),ep=s.z.object({key:Gt}).transform(({key:t})=>({keys:[t]})),tp=s.z.union([s.z.object({for:U}).transform(({for:t})=>({subjects:[t]})),s.z.object({for:U.array()}).transform(({for:t})=>({subjects:t})),Qf]),rp=s.z.union([ep,tp]),np=s.z.object({policies:Y(ys)}),sp=s.z.object({policies:ys.partial({key:!0}).array()}),ap=s.z.object({policies:ys.array()}),ip=s.z.object({keys:Gt.array()}),op=s.z.object({}),lp="/access/policy/retrieve",cp="/access/policy/create",up="/access/policy/delete";let hp=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),r=Xf.array().parse(O.toArray(t)).map(a=>({objects:O.toArray(a.objects),actions:O.toArray(a.actions),subjects:O.toArray(a.subjects)})),n=await m(this.client,cp,{policies:r},sp,ap);return e?n.policies:n.policies[0]}async retrieve(t){const e="key"in t,r=await m(this.client,lp,t,rp,np);return e?r.policies[0]:r.policies}async delete(t){await m(this.client,up,{keys:O.toArray(t)},ip,op)}},dp=class{policy;constructor(t){this.policy=new hp(t)}};const D=s.z.number(),we=s.z.string(),no=Wt.statusZ(),pt=s.z.object({name:we,key:D,dataType:k.z,leaseholder:s.z.number(),index:D,isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:Y(D),status:no.optional()}),so=pt.extend({key:D.optional(),leaseholder:s.z.number().optional(),index:D.optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1),expression:s.z.string().optional().default(""),requires:Y(D).optional().default([])}),He=s.z.union([xt.toArray(D),xt.toArray(we),xt.toArray(pt).transform(t=>t.map(e=>e.key))]),fp=new Error("request for lock canceled");var pp=function(t,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(h){try{u(n.next(h))}catch(p){o(p)}}function c(h){try{u(n.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):a(h.value).then(l,c)}u((n=n.apply(t,e||[])).next())})};class yp{constructor(e,r=fp){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,a)=>{const i={resolve:n,reject:a,weight:e,priority:r},o=ao(this._queue,l=>r<=l.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return pp(this,arguments,void 0,function*(r,n=1,a=0){const[i,o]=yield this.acquire(n,a);try{return yield r(i)}finally{o()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),gp(this._weightedWaiters[e-1],{resolve:n,priority:r})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let r=this._value;r>0;r--){const n=this._weightedWaiters[r-1];if(!n)continue;const a=n.findIndex(i=>i.priority<=e);(a===-1?n:n.splice(0,a)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}}function gp(t,e){const r=ao(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function ao(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var mp=function(t,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(h){try{u(n.next(h))}catch(p){o(p)}}function c(h){try{u(n.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):a(h.value).then(l,c)}u((n=n.apply(t,e||[])).next())})};class wp{constructor(e){this._semaphore=new yp(1,e)}acquire(){return mp(this,arguments,void 0,function*(e=0){const[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const bp=(t,e,{convertNumericStrings:r=!0}={})=>{const n=!Array.isArray(t);let a=O.toArray(t);const i=a[0],o=typeof i;let l;return o==="string"&&r&&!isNaN(parseInt(i))&&"number"in e?(l=e.number,a=a.map(c=>parseInt(c))):l=e[o],{single:n,variant:l,normalized:a,actual:t}},yt=(t,e,r,n)=>{if(n){if(r.length===0)throw new it(`${t} not found matching ${JSON.stringify(e)}`);if(r.length>1)throw new Sr(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${r.length}`)}},vp=s.z.object({leaseholder:s.z.number().optional(),keys:D.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:k.z.array().optional(),notDataTypes:k.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional(),calculated:s.z.boolean().optional()}),Tp=s.z.object({channels:Y(pt)}),re=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]),bp(t,{number:"keys",string:"names"}));class Kt{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,r){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const n=re(e),{variant:a}=n;let{normalized:i}=n;return a==="keys"&&i.indexOf(0)!==-1&&(i=i.filter(o=>o!==0)),i.length===0?[]:await this.execute({[a]:i,...r})}async execute(e){const[r,n]=await this.client.send(Kt.ENDPOINT,e,vp,Tp);if(n!=null)throw n;return r.channels}}class gs{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,r){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n}=re(e),a=[],i=[];if(n.forEach(l=>{const c=this.get(l);c!=null?a.push(...c):i.push(l)}),i.length===0)return a;const o=await this.wrapped.retrieve(i,r);return this.set(o),a.concat(o)}delete(e){const{variant:r,normalized:n}=re(e);r==="names"?n.forEach(a=>{const i=this.namesToKeys.get(a);i!=null&&(i.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(a))}):n.forEach(a=>{const i=this.cache.get(a);i!=null&&(this.cache.delete(a),this.namesToKeys.delete(i.name))})}rename(e,r){e.forEach((n,a)=>{const i=r[a],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(o.name)),o.name=i,this.cache.set(n,o);const c=this.namesToKeys.get(i);c==null?this.namesToKeys.set(i,new Set([n])):c.add(n)})}set(e){e.forEach(r=>{this.cache.set(r.key,r);const n=this.namesToKeys.get(r.name);n==null?this.namesToKeys.set(r.name,new Set([r.key])):n.add(r.key)})}get(e){if(typeof e=="number"){const a=this.cache.get(e);return a==null?void 0:[a]}const r=this.namesToKeys.get(e);if(r==null)return;const n=[];if(r.forEach(a=>{const i=this.cache.get(a);i!=null&&n.push(i)}),n.length!==0)return n}}class io{mu=new wp;requests=new Map;wrapped;debouncedRun;constructor(e,r){this.wrapped=e,this.debouncedRun=sd(()=>{this.run()},r)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:r,variant:n}=re(e);return n==="names"?await this.wrapped.retrieve(r):await new Promise((a,i)=>{this.mu.runExclusive(()=>{this.requests.set(r,{resolve:a,reject:i}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((r,n)=>n.forEach(a=>e.add(a)));try{const r=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,a)=>n.resolve(r.filter(i=>a.includes(i.key))))}catch(r){this.requests.forEach(n=>n.reject(r))}finally{this.requests.clear()}})}}const oo=async(t,e)=>{const{normalized:r}=re(e),n=await t.retrieve(r),a=[];if(r.forEach(i=>{n.find(o=>o.name===i||o.key===i)==null&&a.push(i)}),a.length>0)throw new Le(`Could not find channels: ${JSON.stringify(a)}`);return n},Op="sy_channel_set",Sp="sy_channel_delete";class Pn{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;requires;status;constructor({dataType:e,name:r,leaseholder:n=0,key:a=0,isIndex:i=!1,index:o=0,internal:l=!1,virtual:c=!1,frameClient:u,alias:h,status:p,expression:d="",requires:S=[]}){this.key=a,this.name=r,this.dataType=new k(e),this.leaseholder=n,this.index=o,this.isIndex=i,this.internal=l,this.alias=h,this.virtual=c,this.expression=d,this.requires=S??[],p!=null&&(this.status=Wt.create(p)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new $("cannot read from a channel that has not been created");return this._frameClient}get payload(){return pt.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,requires:this.requires,status:this.status})}get isCalculated(){return zr(this.payload)}get ontologyID(){return uo(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,r){return await this.framer.write(e,this.key,r)}}const zp="sy_calculation_status",Ep="/channel/retrieve-group",Np=s.z.object({}),Ap=s.z.object({group:Xi});let lo=class{type="channel";frameClient;client;retriever;writer;constructor(t,e,r,n){this.frameClient=t,this.retriever=e,this.client=r,this.writer=n}async create(t,e={}){const{retrieveIfNameExists:r=!1}=e,n=!Array.isArray(t);let a=O.toArray(t),i=[];if(r){const o=await this.retriever.retrieve(a.map(c=>c.name)),l=new Set(o.map(c=>c.name));a=a.filter(c=>!l.has(c.name)),i=this.sugar(o)}return i=i.concat(this.sugar(await this.writer.create(a))),n?i[0]:i}async retrieve(t,e){if(typeof t=="object"&&!Array.isArray(t))return this.sugar(await this.retriever.retrieve(t));const r=!Array.isArray(t),n=this.sugar(await this.retriever.retrieve(t,e));return yt("channel",t,n,r),r?n[0]:n}async delete(t){const{normalized:e,variant:r}=re(t);return r==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(t,e){return await this.writer.rename(O.toArray(t),O.toArray(e))}createDebouncedBatchRetriever(t=10){return new gs(new io(new Kt(this.client),t))}sugar(t){const{frameClient:e}=this;return Array.isArray(t)?t.map(r=>new Pn({...r,frameClient:e})):new Pn({...t,frameClient:e})}async retrieveGroup(){const t=await m(this.client,Ep,{},Np,Ap);return new Ji(t.group.name,t.group.key)}};const zr=({virtual:t,expression:e})=>t&&e!=="",co=async(t,e)=>{if(!zr(e))return e.index;for(const r of e.requires){const n=await t(r);if(n==null)return null;if(!n.virtual)return n.index}for(const r of e.requires){const n=await t(r);if(n==null)return null;if(zr(n)){const a=await co(t,n);if(a!=null)return a}}return null},uo=t=>({type:"channel",key:t.toString()}),kp=s.z.object({channels:so.array()}),xp=s.z.object({channels:pt.array()}),Cp=s.z.object({keys:D.array().optional(),names:we.array().optional()}),Ip=s.z.object({}),jp=s.z.object({keys:D.array(),names:we.array()}),Rp=s.z.object({}),Up="/channel/create",Mp="/channel/delete",Lp="/channel/rename";let ho=class{client;cache;constructor(t,e){this.client=t,this.cache=e}async create(t){const{channels:e}=await m(this.client,Up,{channels:t.map(r=>({...r,dataType:r.dataType}))},kp,xp);return this.cache.set(e),e}async delete(t){await m(this.client,Mp,t,Cp,Ip),t.keys!=null&&this.cache.delete(t.keys),t.names!=null&&this.cache.delete(t.names)}async rename(t,e){await m(this.client,Lp,{keys:t,names:e},jp,Rp),this.cache.rename(t,e)}};const Pp=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:zp,CacheRetriever:gs,Channel:Pn,Client:lo,ClusterRetriever:Kt,DELETE_CHANNEL_NAME:Sp,DebouncedBatchRetriever:io,SET_CHANNEL_NAME:Op,Writer:ho,analyzeParams:re,isCalculated:zr,keyZ:D,nameZ:we,newZ:so,ontologyID:uo,paramsZ:He,payloadZ:pt,resolveCalculatedIndex:co,retrieveRequired:oo,statusZ:no},Symbol.toStringTag,{value:"Module"})),_e=s.z.uuid(),Br=s.z.object({key:_e,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),Dp=Br.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Bp=s.z.object({keys:_e.array().optional(),usernames:s.z.string().array().optional()}),$p=s.z.object({key:_e}).transform(({key:t})=>({keys:[t]})),Fp=s.z.object({username:s.z.string()}).transform(({username:t})=>({usernames:[t]})),qp=s.z.object({usernames:s.z.string().array()}).transform(({usernames:t})=>({usernames:t})),Zp=s.z.union([$p,Fp,qp,Bp]),Yp=s.z.object({users:Y(Br)}),Vp=s.z.object({users:Dp.array()}),Hp=s.z.object({users:Br.array()}),_p=s.z.object({key:_e,username:s.z.string().min(1)}),Wp=s.z.object({}),Gp=s.z.object({key:_e,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Kp=s.z.object({}),Jp=s.z.object({keys:_e.array()}),Xp=s.z.object({}),Qp="/user/retrieve",ey="/user/create",ty="/user/change-username",ry="/user/rename",ny="/user/delete";let sy=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),r=await m(this.client,ey,{users:O.toArray(t)},Vp,Hp);return e?r.users:r.users[0]}async changeUsername(t,e){await m(this.client,ty,{key:t,username:e},_p,Wp)}async retrieve(t){const e="key"in t||"username"in t,r=await m(this.client,Qp,t,Zp,Yp);if(!e)return r.users;if(r.users.length===0){const n="key"in t?`key ${t.key}`:`username ${t.username}`;throw new it(`No user with ${n} found`)}if(r.users.length>1){const n="key"in t?`key ${t.key}`:`username ${t.username}`;throw new Sr(`Multiple users found with ${n}`)}return r.users[0]}async rename(t,e,r){await m(this.client,ry,{key:t,firstName:e,lastName:r},Gp,Kp)}async delete(t){await m(this.client,ny,{keys:O.toArray(t)},Jp,Xp)}};const ay=s.z.object({username:s.z.string(),password:s.z.string()}),iy=s.z.object({token:s.z.string(),user:Br}),ca="/auth/login",oy=3,ly="/auth/change-password",cy=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),uy=s.z.object({}),hy=[Un,Mn];let dy=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(t,e){this.client=t,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(t){if(!this.authenticated)throw new Error("Not authenticated");await m(this.client,ly,{username:this.credentials.username,password:this.credentials.password,newPassword:t},cy,uy),this.credentials.password=t}middleware(){const t=async(e,r)=>{if(!this.authenticated&&!e.target.endsWith(ca)){this.authenticating??=new Promise((o,l)=>{this.client.send(ca,this.credentials,ay,iy).then(([c,u])=>{if(u!=null)return o(u);this.token=c?.token,this.user=c?.user,this.authenticated=!0,o(null)}).catch(l)});const i=await this.authenticating;if(i!=null)return[e,i]}e.params.Authorization=`Bearer ${this.token}`;const[n,a]=await r(e);return hy.some(i=>i.matches(a))&&this.retryCount<oy?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,t(e,r)):(this.retryCount=0,[n,a])};return t}};const fy=s.z.enum(["disconnected","connecting","connected","failed"]),py=s.z.object({status:fy,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),yy=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),ua={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.44.3"},ha=(t,e,r)=>{const n=r?"cluster":"client";return`Synnax cluster node version ${t!=null?`${t} `:""}is too ${r?"old":"new"} for client version ${e}.
22
+ This may cause compatibility issues. We recommend updating the ${n}. For more information, see
23
+ https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`};class Er{static ENDPOINT="/connectivity/check";static DEFAULT=ua;_state;pollFrequency=z.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=py;versionWarned=!1;constructor(e,r=z.seconds(30),n,a){this._state={...ua},this.client=e,this.pollFrequency=r,this.clientVersion=n,this.name=a,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const[r,n]=await this.client.send(Er.ENDPOINT,{},s.z.object({}),yy);if(n!=null)throw n;const a=r.nodeVersion,i=this.clientVersion,o=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,o||(console.warn(ha(null,i,!0)),this.versionWarned=!0)):aa.versionsEqual(i,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,o||(console.warn(ha(a,i,aa.semVerNewer(i,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=r.clusterKey,this._state.nodeVersion=r.nodeVersion,this._state.clientVersion=this.clientVersion}catch(r){this._state.status="failed",this._state.error=r,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(r=>r(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const gy=s.z.object({keys:D.array().optional(),bounds:M.z,names:we.array().optional()}),my=s.z.object({}),wy="/frame/delete";class by{client;constructor(e){this.client=e}async delete(e){await m(this.client,wy,e,gy,my)}}const da=t=>{const e=O.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},fa=(t,e)=>{const r=O.toArray(t);if(r.length===e.length)return;const n=da(t);throw da===null?new $("[Frame] - channel keys or names must be provided when constructing a frame."):new $(`[Frame] - ${n}s and series must be the same length.
24
+ Got ${r.length} ${n}s and ${e.length} series.`)};let X=class Xe{columns=[];series=[];constructor(e=[],r=[]){if(e instanceof Xe){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((n,a)=>this.push(a,...O.toArray(n)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const n=e;n.series??=[],n.keys??=[];const a=n.series.map(i=>fo(i));fa(n.keys,a),n.keys.forEach((i,o)=>this.push(i,a[o]))}else Object.entries(e).forEach(([n,a])=>{const i=parseInt(n);if(!isNaN(i))return this.push(i,...O.toArray(a));this.push(n,...O.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const n=O.toArray(r),a=O.toArray(e);fa(a,n),n.forEach((i,o)=>this.push(a[o],i));return}throw new $(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
25
+ payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
26
+ name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new W("colType is not key");return this.columns??[]}get uniqueKeys(){return Ws.unique(this.keys)}get names(){if(this.colType==="key")throw new W("colType is not name");return this.columns??[]}get uniqueNames(){return Ws.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>po(e)),keys:[...this.keys]}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(r=>r.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return M.ZERO;const n=E.min(...this.series.map(i=>i.timeRange.start)),a=E.max(...this.series.map(i=>i.timeRange.end));return new M(n,a)}const r=this.get(e);return r==null?M.ZERO:r.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(r=>e.includes(r)):new rd(this.series.filter((r,n)=>this.columns[n]===e))}push(e,...r){if(e instanceof Xe){if(this.colType!==null&&e.colType!==this.colType)throw new $("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...r),typeof e=="string"&&this.colType==="key")throw new $("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new $("keyVariant must match");this.columns.push(...Array.from({length:r.length},()=>e))}}concat(e){return new Xe([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const r=new Xe;return this.forEach((n,a,i)=>r.push(...e(n,a,i))),r}forEach(e){this.columns.forEach((r,n)=>{const a=this.series[n];e(r,a,n)})}at(e,r=!1){const n={};return this.uniqueColumns.forEach(a=>{n[a]=this.get(a).at(e,r)}),n}filter(e){const r=new Xe;return this.columns.forEach((n,a)=>{const i=this.series[a];e(n,i,a)&&r.push(n,i)}),r}get byteLength(){return new at(this.series.reduce((e,r)=>e.add(r.byteLength),at.ZERO))}get digest(){const e={};return this.keys.forEach((r,n)=>{const a=this.series[n].digest;r in e?e[r].push(a):e[r]=[a]}),e}get length(){return this.series.reduce((e,r)=>e+r.length,0)}toString(){let e=`Frame{
27
+ `;return this.uniqueColumns.forEach(r=>{e+=` ${r}: ${this.get(r).series.map(n=>n.toString()).join(",")}
28
+ `}),e+="}",e}};const $r=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),Ie.crudeZ.array().optional().default([])])}),fo=t=>{const{dataType:e,data:r,timeRange:n,alignment:a}=t;return new Ie({data:r,dataType:e,timeRange:n,glBufferUsage:"static",alignment:a})},po=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var ot=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(ot||{}),Mt=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Mt||{});const vy=new z(-1);class Dn extends pe.sub("writer_closed"){constructor(){super("WriterClosed")}}const Ty=s.z.enum(Mt).or(s.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),yo=s.z.object({start:E.z.optional(),controlSubject:ee.subjectZ.optional(),authorities:s.z.union([ee.authorityZ.transform(t=>[t]),ee.authorityZ.array()]).default([ee.ABSOLUTE_AUTHORITY]),mode:Ty.default(1),errOnUnauthorized:s.z.boolean().default(!1),enableAutoCommit:s.z.boolean().default(!1),autoIndexPersistInterval:z.z.default(z.SECOND),useHighPerformanceCodec:s.z.boolean().default(!0)}),Oy=yo.extend({keys:D.array().optional()}),pa=yo.extend({channels:He}),go=pa.or(He.transform(t=>pa.parse({channels:t,start:E.now()}))),Sy=s.z.object({command:s.z.enum(ot),config:Oy.optional(),frame:$r.optional(),buffer:s.z.instanceof(Uint8Array).optional()}),zy=s.z.object({command:s.z.enum(ot),end:E.z,err:be.payloadZ.optional()}),Ey=s.z.tuple([s.z.union([s.z.record(D.or(we),ee.authorityZ),D.or(we),ee.authorityZ]),ee.authorityZ.optional()]).transform(([t,e])=>{if(ee.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(D.or(we).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const r=t;return{keys:Object.keys(r),authorities:Object.values(r)}});let mo=class Bn{static ENDPOINT="/frame/write";stream;adapter;closeErr=null;constructor(e,r){this.stream=e,this.adapter=r}static async _open(e,r,n){const a=go.parse(n),i=await ws.open(e,a.channels);a.useHighPerformanceCodec&&(r=r.withCodec(new Iy(i.codec)));const o=await r.stream(Bn.ENDPOINT,Sy,zy),l=new Bn(o,i);return await l.execute({command:0,config:{...a,keys:i.keys}}),l}async write(e,r){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const n=await this.adapter.adapt(e,r);this.stream.send({command:1,frame:n.toPayload()})}async setAuthority(e,r){if(this.closeErr!=null)throw this.closeErr;const n=Ey.parse([e,r]),a={keys:await this.adapter.adaptParams(n.keys),authorities:n.authorities};await this.execute({command:3,config:a})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),E.ZERO):(await this.execute({command:2})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(Dn.matches(this.closeErr))return null;throw this.closeErr}const[r,n]=await this.stream.receive();n!=null?this.closeErr=ne.matches(n)?new Dn:n:this.closeErr=be.decode(r?.err)}}async execute(e){const r=this.stream.send(e);for(r!=null&&await this.closeInternal(r);;){const[n,a]=await this.stream.receive();a!=null&&await this.closeInternal(a);const i=be.decode(n?.err);if(i!=null&&await this.closeInternal(i),n?.command==e.command)return n}}};const ya=t=>t.data.byteLength/t.dataType.density.valueOf(),Ny=t=>{const{keys:e,series:r}=t;e.forEach((n,a)=>{r[a].key=n}),r.sort((n,a)=>n.key-a.key),e.sort((n,a)=>n-a),r.forEach(n=>delete n.key)},ga=5,ma=4,wa=3,ba=2,va=1,Ta=0,ae=k.TIMESTAMP.density.valueOf(),Ee=8,Ne=4,an=4,on=4,Ay=1;class wo{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],r=[]){(e.length>0||r.length>0)&&this.update(e,r)}update(e,r){this.seqNum++;const n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((a,i)=>{const o=r[i];n.keyDataTypes.set(a,o),o.isVariable&&(n.hasVariableDataTypes=!0)}),n.keys.sort(),this.states.set(this.seqNum,n),this.currState=n}throwIfNotUpdated(e){if(this.seqNum<1)throw new $(`
29
+ The codec has not been updated with a list of channels and data types.
30
+ Please call the update method before calling ${e}.
31
+ `)}encode(e,r=0){this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),Ny(n);let a=-1,i,o,l,c=r+Ay+on,u=!this.currState?.hasVariableDataTypes,h=!0,p=!0,d=!0,S=!0,N=!0;n.keys.length!==this.currState?.keys.length&&(d=!1,c+=n.keys.length*an),n.series.forEach((L,se)=>{const te=ya(L),bt=n.keys[se],De=this.currState?.keyDataTypes.get(bt);if(De==null)throw new $(`Channel ${bt} was not provided in the list of channels when opening the writer`);if(!De.equals(L.dataType))throw new $(`Series data type of ${L.dataType.toString()} does not match the data type of ${De.toString()} for channel ${bt}`);if(c+=L.data.byteLength,a===-1){a=te,i=L.timeRange?.start,o=L.timeRange?.end,l=BigInt(L.alignment??0n);return}a!==te&&(u=!1),(i?.valueOf()!==L.timeRange?.start.valueOf()||o?.valueOf()!==L.timeRange?.end.valueOf())&&(h=!1),l!==BigInt(L.alignment??0)&&(S=!1)}),p=h&&i==null&&o==null,N=S&&(l===void 0||l===0n),u?c+=Ne:c+=n.keys.length*Ne,p||(h?c+=ae*2:c+=n.keys.length*ae*2),N||(S?c+=Ee:c+=n.keys.length*Ee);const x=new Uint8Array(c),B=new DataView(x.buffer);let C=r;return x[C]=Number(N)<<ga|Number(S)<<ma|Number(u)<<wa|Number(h)<<ba|Number(p)<<va|Number(d)<<Ta,C++,B.setUint32(C,this.seqNum,!0),C+=on,u&&(B.setUint32(C,a,!0),C+=Ne),h&&!p&&(B.setBigUint64(C,i?.valueOf()??0n,!0),B.setBigUint64(C,o?.valueOf()??0n,!0),C+=ae*2),S&&!N&&(B.setBigUint64(C,l??0n,!0),C+=Ee),n.series.forEach((L,se)=>{if(d||(B.setUint32(C,n.keys[se],!0),C+=an),!u){let te=L.data.byteLength;L.dataType.isVariable||(te=ya(L)),B.setUint32(C,te,!0),C+=Ne}x.set(new Uint8Array(L.data),C),C+=L.data.byteLength,!h&&!p&&(B.setBigUint64(C,L.timeRange?.start.valueOf()??0n,!0),B.setBigUint64(C,L.timeRange?.end.valueOf()??0n,!0),C+=ae*2),!S&&!N&&(B.setBigUint64(C,L.alignment??0n,!0),C+=Ee)}),x}decode(e,r=0){this.throwIfNotUpdated("decode");const n=e instanceof Uint8Array?e:new Uint8Array(e),a={keys:[],series:[]};let i=r,o=0,l=0,c,u,h;const p=new DataView(n.buffer,n.byteOffset,n.byteLength),d=!!(n[i]>>ga&1),S=!!(n[i]>>ma&1),N=!!(n[i]>>wa&1),x=!!(n[i]>>ba&1),B=!!(n[i]>>va&1),C=!!(n[i]>>Ta&1);i++;const L=p.getUint32(i,!0);i+=on;const se=this.states.get(L);if(se==null)return a;if(N){if(i+Ne>p.byteLength)return a;o=p.getUint32(i,!0),i+=Ne}if(x&&!B){if(i+ae>p.byteLength)return a;c=new E(p.getBigUint64(i,!0)),i+=ae,u=new E(p.getBigUint64(i,!0)),i+=ae}if(S&&!d){if(i+Ee>p.byteLength)return a;h=p.getBigUint64(i,!0),i+=Ee}return C&&(a.keys=[...se.keys]),se.keys.forEach((te,bt)=>{if(!C){if(i>=p.byteLength||p.getUint32(i,!0)!==te)return;i+=an,a.keys.push(te)}const De=se.keyDataTypes.get(te);if(l=0,N)l=o;else{if(i+Ne>p.byteLength)return;l=p.getUint32(i,!0),i+=Ne}let sr=l;if(De.isVariable||(sr*=De.density.valueOf()),i+sr>p.byteLength){a.keys.splice(bt,1);return}const Be={dataType:De,data:n.slice(i,i+sr).buffer};if(i+=sr,!x&&!B){if(i+ae*2>p.byteLength)return;const Pl=p.getBigUint64(i,!0);i+=ae;const Dl=p.getBigUint64(i,!0);i+=ae,Be.timeRange=new M({start:Pl,end:Dl})}else B?Be.timeRange=new M({start:0n,end:0n}):Be.timeRange=new M({start:c?.valueOf()??0n,end:u?.valueOf()??0n});if(!S&&!d){if(i+Ee>p.byteLength)return;h=p.getBigUint64(i,!0),i+=Ee,Be.alignment=h}else d?Be.alignment=0n:Be.alignment=h;a.series.push(Be)}),a}}const ms=254,ky=new Uint8Array([ms]),xy=255,Cy=new Uint8Array([xy]),bo="application/sy-framer";class Iy{contentType=bo;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=Ve.JSON_CODEC}encode(e){const r=e;if(r.type=="close"||r.payload?.command!=ot.Write){const a=this.lowPerfCodec.encode(r),i=new Uint8Array({length:a.byteLength+1});return i.set(ky,0),i.set(new Uint8Array(a),1),i}const n=this.base.encode(r.payload?.frame,1);return n.set(Cy,0),n}decode(e,r){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ms)return this.lowPerfCodec.decode(e.slice(1),r);const n={type:"data"},a=this.base.decode(e,1);return n.payload={command:ot.Write,frame:a},n}}class jy{contentType=bo;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=Ve.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,r){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ms?this.lowPerfCodec.decode(e.slice(1),r):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Fr{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new wo}static async open(e,r){const n=new Fr(e);return await n.update(r),n}async update(e){const{variant:r,normalized:n}=re(e),a=await this.retriever.retrieve(n),i=a.map(l=>l.key);if(Gs.uniqueUnorderedPrimitiveArrays(this.keys,i)===Gs.EQUAL)return!1;if(this.codec.update(i,a.map(l=>l.dataType)),r==="keys")return this.adapter=null,this.keys=n,!0;const o=new Map;return this.adapter=o,n.forEach(l=>{const c=a.find(u=>u.name===l);if(c==null)throw new Error(`Channel ${l} not found`);o.set(c.key,c.name)}),this.keys=Array.from(this.adapter.keys()),!0}adapt(e){if(this.adapter==null)return e;const r=this.adapter;return e.map((n,a)=>{if(typeof n=="number"){const i=r.get(n);if(i==null)throw new Error(`Channel ${n} not found`);return[i,a]}return[n,a]})}}class ws{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new wo}static async open(e,r){const n=new ws(e);return await n.update(r),n}async adaptParams(e){const r=He.parse(e);return await Promise.all(r.map(async n=>await this.adaptToKey(n)))}async update(e){const r=await oo(this.retriever,e),n=r.map(c=>c.key),a=new Set(this.keys),i=new Set(n),o=!i.isSubsetOf(a),l=!a.isSubsetOf(i);return o||l?(this.adapter=new Map(r.map(c=>[c.name,c.key])),this.keys=n,this.codec.update(this.keys,r.map(c=>c.dataType)),!0):!1}async fetchChannel(e){const r=await this.retriever.retrieve(e);if(r.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return r[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,r){if(typeof e=="string"||typeof e=="number"){if(r==null)throw new $(`
32
+ Received a single channel name or key but no series.
33
+ `);if(Array.isArray(r)){if(r.some(c=>c instanceof Ie||Array.isArray(c)))throw new $(`
34
+ Received a single channel name or key but multiple series.
35
+ `);r=r}const o=await this.fetchChannel(e),l=new Ie({data:r,dataType:o.dataType});return new X(o.key,l)}if(Array.isArray(e)){if(r==null)throw new $(`
36
+ Received an array of channel names or keys but no series.
37
+ `);if(!Array.isArray(r))throw new $(`
38
+ Received an array of channel names or keys but no array of series.
39
+ `);const o=[],l=[];for(let c=0;c<e.length;c++){const u=await this.fetchChannel(e[c]);if(c>=r.length)throw new $(`
40
+ Received an array of channel names or keys but not enough series.
41
+ `);const h=new Ie({data:r[c],dataType:u.dataType});o.push(u.key),l.push(h)}return new X(o,l)}if(e instanceof X||e instanceof Map){const o=new X(e);if(this.adapter==null)return o;const l=o.columns.map(c=>{const u=typeof c=="string"?this.adapter?.get(c):c;if(u==null)throw new $(`
42
+ Channel ${c} was not provided in the list of channels when opening the writer
43
+ `);return u});return new X(l,o.series)}const n=[],a=[],i=Object.entries(e);for(let o=0;o<i.length;o++){const[l,c]=i[o],u=await this.fetchChannel(l),h=new Ie({data:c,dataType:u.dataType});n.push(u.key),a.push(h)}return new X(n,a)}}class vo{name;stream;constructor(e,r){this.stream=r,this.name=e}async receive(){const[e,r]=await this.stream.receive();if(r!=null)throw r;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,r]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
44
+ Please report this error to the Synnax team.`),r!=null){if(ne.matches(r))return;throw r}}}closeSend(){this.stream.closeSend()}send(e){const r=this.stream.send(e);if(r!=null)throw r}}const Nr=new z(-1);var bs=(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))(bs||{}),To=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(To||{});const Ry=s.z.object({command:s.z.enum(bs),span:z.z.optional(),bounds:M.z.optional(),stamp:E.z.optional(),keys:D.array().optional(),chunkSize:s.z.number().optional()}),Uy=s.z.object({variant:s.z.enum(To),ack:s.z.boolean(),command:s.z.enum(bs),error:be.payloadZ.optional().nullable(),frame:$r.optional()});class Lt{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,r){this.stream=new vo("Iterator",e),this.value=new X,this.adapter=r}static async _open(e,r,n,a,i={}){const o=await Fr.open(n,r),l=await a.stream(Lt.ENDPOINT,Ry,Uy),c=new Lt(l,o);return await c.execute({command:0,keys:o.keys,bounds:new M(e),chunkSize:i.chunkSize??1e5}),c}async next(e=Nr){return await this.execute({command:1,span:new z(e)})}async prev(e=Nr){return await this.execute({command:2,span:new z(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new E(e)})}async seekGE(e){return await this.execute({command:6,stamp:new E(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new My(this)}async execute(e){for(this.stream.send(e),this.value=new X;;){const r=await this.stream.receive();if(r.variant===1)return r.ack;this.value.push(this.adapter.adapt(new X(r.frame)))}}}class My{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 Ly=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),Py=s.z.object({frame:$r}),Dy="/frame/stream",Oa=s.z.object({channels:He,downsampleFactor:s.z.number().optional().default(1),useHighPerformanceCodec:s.z.boolean().optional().default(!0)}),vs=Oa.or(He.transform(t=>Oa.parse({channels:t}))),Oo=(t,e)=>async r=>{const n=vs.parse(r),a=await Fr.open(t,n.channels);n.useHighPerformanceCodec&&(e=e.withCodec(new jy(a.codec)));const i=await e.stream(Dy,Ly,Py),o=new By(i,a);i.send({keys:a.keys,downsampleFactor:n.downsampleFactor??1});const[,l]=await i.receive();if(l!=null)throw l;return o},So=async(t,e,r)=>await Oo(t,e)(r);class By{stream;adapter;downsampleFactor;constructor(e,r){this.stream=new vo("Streamer",e),this.adapter=r,this.downsampleFactor=1}get keys(){return this.adapter.keys}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ne.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new X((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e)&&this.stream.send({keys:this.adapter.keys,downsampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class qr{wrapped_=null;breaker;opener;config;constructor(e,r,n={}){this.opener=e,this.config=vs.parse(r);const{maxRetries:a=5e3,baseInterval:i=z.seconds(1),scale:o=1}=n??{};this.breaker=new Mi.Breaker({maxRetries:a,baseInterval:i,scale:o})}static async open(e,r,n){const a=new qr(e,r,n);return await a.runStreamer(),a}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=He.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(ne.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(ne.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 zo extends ud.Observer{streamer;closePromise;constructor(e,r){super(r),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}const $y=t=>({type:"framer",key:t.toString()});let Eo=class{streamClient;retriever;deleter;constructor(t,e,r){this.streamClient=t,this.retriever=r,this.deleter=new by(e)}async openIterator(t,e,r){return await Lt._open(t,e,this.retriever,this.streamClient,r)}async openWriter(t){return await mo._open(this.retriever,this.streamClient,t)}async openStreamer(t){return await So(this.retriever,this.streamClient,t)}async write(t,e,r){if(r==null){const a=e,i=await this.openWriter({start:t,channels:Object.keys(a),mode:Mt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});return await i.write(a),await i.close()}const n=await this.openWriter({start:t,channels:e,mode:Mt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});await n.write(e,r),await n.close()}async read(t,e){const{single:r}=re(e),n=await this.readFrame(t,e);return r?n.get(e):n}async readFrame(t,e){const r=await this.openIterator(t,e),n=new X;try{for await(const a of r)n.push(a)}finally{await r.close()}return n}async readLatest(t,e=1){const{single:r}=re(t),n=await this.readLatestNFrame(t,e);return r?n.get(t):n}async readLatestNFrame(t,e){const r=await this.openIterator(M.MAX,t,{chunkSize:e}),n=new X;if(e>0)try{await r.seekLast(),await r.prev(Nr),n.push(r.value)}finally{await r.close()}return n}async delete(t,e){const{normalized:r,variant:n}=re(t);return n==="keys"?await this.deleter.delete({keys:r,bounds:e}):await this.deleter.delete({names:r,bounds:e})}};const Fy=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:vy,AUTO_SPAN:Nr,Client:Eo,Frame:X,HardenedStreamer:qr,Iterator:Lt,ObservableStreamer:zo,Writer:mo,WriterClosedError:Dn,WriterCommand:ot,WriterMode:Mt,createStreamOpener:Oo,frameZ:$r,ontologyID:$y,openStreamer:So,seriesFromPayload:fo,seriesToPayload:po,streamerConfigZ:vs,writerConfigZ:go},Symbol.toStringTag,{value:"Module"})),qy=ee.ABSOLUTE_AUTHORITY,Zy=ee.ZERO_AUTHORITY,Yy=ee.stateZ(s.z.number()),Vy=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()})`,Hy=s.z.object({transfers:s.z.array(ee.transferZ(D))});class No extends zo{states;codec;constructor(e){super(e,r=>{const n=this.codec.decode(r.series[0].buffer,Hy);return this.merge(n),[n.transfers,!0]}),this.states=new Map,this.codec=new Ve.JSONCodec}subjects(){const e=new Map;return this.states.forEach(r=>e.set(r.subject.key,r.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(r=>{r.from==null&&r.to==null&&console.warn("Invalid transfer: ",r),r.to==null?this.states.delete(r.from.resource):this.states.set(r.to.resource,r.to)})}}const Ao="sy_node_1_control";let ko=class{framer;constructor(t){this.framer=t}async openStateTracker(){const t=await qr.open(async e=>await this.framer.openStreamer(e),Ao);return new No(t)}};const _y=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:qy,CONTROL_STATE_CHANNEL_NAME:Ao,Client:ko,StateTracker:No,ZERO_AUTHORITY:Zy,stateZ:Yy,transferString:Vy},Symbol.toStringTag,{value:"Module"}));let Wy=class{tasks;racks;devices;constructor(t,e,r){this.tasks=t,this.racks=e,this.devices=r}};const ye=s.z.uint32(),xo=Wt.statusZ(s.z.object({rack:ye})),Zr=s.z.object({key:ye,name:s.z.string(),status:xt.nullToUndefined(xo)}),Co=Zr.partial({key:!0}),Io=t=>t?Ve.JSON_CODEC.decodeString(t,ve.unknownZ):{},gt=s.z.string(),jo=Wt.statusZ(s.z.object({rack:ye,device:gt})),Yr=s.z.object({key:gt,rack:ye,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:ve.unknownZ.or(s.z.string().transform(Io)),status:xt.nullToUndefined(jo)}),Ro=Yr.extend({properties:s.z.unknown().transform(t=>Ve.JSON_CODEC.encodeString(t))}),Gy="sy_device_set",Ky="sy_device_delete",Jy="sy_device_status",Xy="/hardware/device/retrieve",Qy="/hardware/device/create",eg="/hardware/device/delete",tg=s.z.object({devices:Ro.array()}),rg=s.z.object({devices:Yr.array()}),ng=s.z.object({keys:gt.array()}),sg=s.z.object({}),ag=s.z.object({keys:gt.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional(),models:s.z.string().array().optional(),locations:s.z.string().array().optional(),racks:ye.array().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),ig=s.z.object({devices:Y(Yr)}),og=s.z.object({key:gt,includeStatus:s.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),lg=s.z.union([og,ag]);let Uo=class{type="device";client;constructor(t){this.client=t}async retrieve(t){const e=typeof t=="object"&&"key"in t,r=await m(this.client,Xy,t,lg,ig);yt("Device",t,r.devices,e);const n=r.devices;return e?n[0]:n}async create(t){const e=!Array.isArray(t),r=(await m(this.client,Qy,{devices:O.toArray(t)},tg,rg)).devices;return e?r[0]:r}async delete(t){await m(this.client,eg,{keys:O.toArray(t)},ng,sg)}};const cg=t=>({type:"device",key:t}),ug=Object.freeze(Object.defineProperty({__proto__:null,Client:Uo,DELETE_CHANNEL_NAME:Ky,SET_CHANNEL_NAME:Gy,STATUS_CHANNEL_NAME:Jy,deviceZ:Yr,keyZ:gt,newZ:Ro,ontologyID:cg,statusZ:jo},Symbol.toStringTag,{value:"Module"})),hg="/hardware/rack/retrieve",dg="/hardware/rack/create",fg="/hardware/rack/delete",pg="sy_rack_status",yg="sy_rack_set",gg="sy_rack_delete",mg=s.z.object({keys:ye.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),embedded:s.z.boolean().optional(),hostIsNode:s.z.boolean().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),wg=s.z.object({racks:Y(Zr)}),bg=s.z.union([s.z.object({key:ye,includeStatus:s.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),vg=mg,Tg=s.z.union([bg,vg]),Og=s.z.object({racks:Co.array()}),Sg=s.z.object({racks:Zr.array()}),zg=s.z.object({keys:ye.array()}),Eg=s.z.object({});let Mo=class{type="rack";client;tasks;constructor(t,e){this.client=t,this.tasks=e}async delete(t){await m(this.client,fg,{keys:O.toArray(t)},zg,Eg)}async create(t){const e=!Array.isArray(t),r=await m(this.client,dg,{racks:O.toArray(t)},Og,Sg),n=this.sugar(r.racks);return e?n[0]:n}async retrieve(t){const e="key"in t||"name"in t,r=await m(this.client,hg,t,Tg,wg),n=this.sugar(r.racks);return yt("Rack",t,n,e),e?n[0]:n}sugar(t){const e=!Array.isArray(t),r=O.toArray(t).map(({key:n,name:a,status:i})=>new Lo(n,a,this.tasks,i));return e?r[0]:r}};class Lo{key;name;status;tasks;constructor(e,r,n,a){this.key=e,this.name=r,this.tasks=n,this.status=a}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,r){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,r)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const Ng=t=>({type:"rack",key:t.toString()}),Ag=Object.freeze(Object.defineProperty({__proto__:null,Client:Mo,DELETE_CHANNEL_NAME:gg,Rack:Lo,SET_CHANNEL_NAME:yg,STATUS_CHANNEL_NAME:pg,keyZ:ye,newZ:Co,ontologyID:Ng,rackZ:Zr,statusZ:xo},Symbol.toStringTag,{value:"Module"})),Te=t=>t?JSON.parse(t):{},Oe=s.z.union([s.z.string(),s.z.bigint().transform(t=>t.toString()),s.z.number().transform(t=>t.toString())]),Po=t=>s.z.object({task:Oe,running:s.z.boolean(),data:t}),Ts=t=>Wt.statusZ(Po(t)),Jt=(t={typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()})=>s.z.object({key:Oe,name:s.z.string(),type:t.typeSchema,internal:s.z.boolean().optional(),config:s.z.string().transform(Io).or(t.configSchema),status:Ts(t.statusDataSchema).optional().nullable(),snapshot:s.z.boolean().optional()}),Do=t=>Jt(t).omit({key:!0}).extend({key:Oe.transform(e=>e.toString()).optional(),config:s.z.unknown().transform(e=>Ve.JSON_CODEC.encodeString(e))}),kg=s.z.object({task:Oe,type:s.z.string(),key:s.z.string(),args:ve.unknownZ.or(s.z.string().transform(Te)).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),xg=t=>Number(BigInt(t)>>32n),$n="sy_task_status",Fn="sy_task_cmd",Cg="sy_task_set",Ig="sy_task_delete",$e=new Error("Task not created"),Bo=async(t,e)=>{const r=await e.retrieveParents(Os(t));return r.length===0?null:r[0]};class $o{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw $e;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw $e;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw $e;return this.rangeClient_}constructor({key:e,type:r,name:n,config:a,internal:i=!1,snapshot:o=!1,status:l},c,u,h,p){this.key=e,this.name=n,this.type=r,this.config=a,this.schemas=c??{typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()},this.internal=i,this.snapshot=o,this.status=l,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=p}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return Os(this.key)}async executeCommand(e,r){return await qo(this.frameClient,this.key,e,r)}async executeCommandSync(e,r,n){return await Zo(this.frameClient,this.key,e,r,this.name,this.schemas?.statusDataSchema,n)}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw $e;return this.snapshot?await Bo(this.key,this.ontologyClient):null}}const jg=s.z.object({rack:ye.optional(),keys:Oe.array().optional(),names:s.z.string().array().optional(),types:s.z.string().array().optional(),includeStatus:s.z.boolean().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Rg=s.z.union([s.z.object({key:Oe,includeStatus:s.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),Ug=jg,Mg=s.z.union([Rg,Ug]),Lg=t=>s.z.object({tasks:Y(Jt(t))}),Pg="/hardware/task/retrieve",Dg="/hardware/task/create",Bg="/hardware/task/delete",$g="/hardware/task/copy",Fg=t=>s.z.object({tasks:Do(t).array()}),qg=t=>s.z.object({tasks:Jt(t).array()}),Zg=s.z.object({keys:Oe.array()}),Yg=s.z.object({}),Vg=s.z.object({key:Oe,name:s.z.string(),snapshot:s.z.boolean()}),Hg=t=>s.z.object({task:Jt(t)});let Fo=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(t,e,r,n){this.client=t,this.frameClient=e,this.ontologyClient=r,this.rangeClient=n}async create(t,e){const r=!Array.isArray(t),n=Fg(e),a=qg(e),i=await m(this.client,Dg,{tasks:O.toArray(t)},n,a),o=this.sugar(i.tasks,e);return r?o[0]:o}async delete(t){await m(this.client,Bg,{keys:O.toArray(t)},Zg,Yg)}async retrieve({schemas:t,...e}){const r="key"in e||"name"in e,n=(await m(this.client,Pg,e,Mg,Lg(t))).tasks,a=this.sugar(n,t);return yt("Task",e,a,r),r?a[0]:a}async copy(t,e,r){const n=Hg(),a=await m(this.client,$g,{key:t,name:e,snapshot:r},Vg,n);return this.sugar(a.task)}async retrieveSnapshottedTo(t){if(this.ontologyClient==null)throw $e;return await Bo(t,this.ontologyClient)}sugar(t,e){const r=!Array.isArray(t),n=O.toArray(t).map(({key:a,name:i,type:o,config:l,status:c,internal:u,snapshot:h})=>new $o({key:a,name:i,type:o,config:l,internal:u,snapshot:h,status:c},e,this.frameClient,this.ontologyClient,this.rangeClient));return r?n[0]:n}async executeCommand(t,e,r){if(Array.isArray(t))return await Ss(this.frameClient,t);if(e==null)throw new Error("Type is required");return await qo(this.frameClient,t,e,r)}async executeCommandSync(t,e,r,n,a,i=s.z.unknown()){if(Array.isArray(t)){const l=async()=>(await this.retrieve({keys:t.map(c=>c.task)})).map(c=>c.name);return await Yo(this.frameClient,t,e,i,l)}const o=async()=>(await this.retrieve({key:t})).name;return await Zo(this.frameClient,t,e,r,a??o,i,n)}};const Os=t=>({type:"task",key:t}),qo=async(t,e,r,n)=>(await Ss(t,[{args:n,task:e,type:r}]))[0],Ss=async(t,e)=>{if(t==null)throw $e;const r=await t.openWriter(Fn),n=e.map(a=>({...a,key:$h.create()}));return await r.write(Fn,n),await r.close(),n.map(a=>a.key)},Zo=async(t,e,r,n,a,i,o)=>(await Yo(t,[{args:o,task:e,type:r}],n,i,a))[0],Yo=async(t,e,r,n,a)=>{if(t==null)throw $e;const i=await t.openStreamer($n),o=await Ss(t,e),l=new z(r);let c=[],u;const h=new Promise((p,d)=>{u=setTimeout(()=>{(async()=>{const S=e.map(N=>N.task);d(await _g("command",a,l,S))})()},l.milliseconds)});try{for(;;){const p=await Promise.race([i.read(),h]),d=Ts(n).parse(p.at(-1)[$n]);if(o.includes(d.key)&&(c=[...c.filter(S=>S.key!==d.key),d],c.length===o.length))return c}}finally{clearTimeout(u),i.close()}},_g=async(t,e,r,n)=>{const a=Wu.capitalize(t),i=r.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=O.toArray(await e());const l=jn.naturalLanguageJoin(o);return new Error(`${a} command to ${l} timed out after ${i}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${a} command to task with key ${jn.naturalLanguageJoin(n)} timed out after ${i}`)}},Wg=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:Fn,Client:Fo,DELETE_CHANNEL_NAME:Ig,SET_CHANNEL_NAME:Cg,STATUS_CHANNEL_NAME:$n,Task:$o,commandZ:kg,keyZ:Oe,newZ:Do,ontologyID:Os,rackKey:xg,statusDetailsZ:Po,statusZ:Ts,taskZ:Jt},Symbol.toStringTag,{value:"Module"})),Pe=s.z.uuid(),Xt=s.z.object({key:Pe,name:s.z.string().min(1),color:s.z.string()}),Gg="labeled_by",Kg="sy_label_set",Jg="sy_label_delete",Vo=Xt.extend({key:Pe.optional()}),Xg=s.object({labels:Vo.array()}),Qg=s.object({labels:Xt.array()}),em=s.object({keys:Pe.array()}),Ho=s.object({id:U,labels:Pe.array(),replace:s.boolean().optional()}),tm=Ho.omit({replace:!0}),ln=s.object({}),rm="/label/create",nm="/label/delete",sm="/label/set",am="/label/remove",im="/label/retrieve",om=s.object({keys:Pe.array().optional(),for:U.optional(),searchTerm:s.string().optional(),offset:s.number().optional(),limit:s.number().optional()}),lm=s.object({key:Pe}).transform(({key:t})=>({keys:[t]})),cm=s.union([lm,om]),um=s.object({labels:Y(Xt)});let _o=class{type="label";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,r=await m(this.client,im,t,cm,um);return yt("Label",t,r.labels,e),e?r.labels[0]:r.labels}async label(t,e,r={}){await m(this.client,sm,{id:t,labels:e,replace:r.replace},Ho,ln)}async remove(t,e){await m(this.client,am,{id:t,labels:e},tm,ln)}async create(t){const e=Array.isArray(t),r=await m(this.client,rm,{labels:O.toArray(t)},Xg,Qg);return e?r.labels:r.labels[0]}async delete(t){await m(this.client,nm,{keys:O.toArray(t)},em,ln)}};const hm=t=>({type:"label",key:t}),dm=Object.freeze(Object.defineProperty({__proto__:null,Client:_o,DELETE_CHANNEL_NAME:Jg,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:Gg,SET_CHANNEL_NAME:Kg,keyZ:Pe,labelZ:Xt,newZ:Vo,ontologyID:hm},Symbol.toStringTag,{value:"Module"})),V=s.z.uuid(),zs=s.z.string().min(1),Qt=s.z.object({key:V,name:zs,timeRange:M.z,color:s.z.string().optional(),labels:Xt.array().or(s.z.null().transform(()=>{})).optional(),get parent(){return Qt.optional().nullable().transform(t=>t===void 0?null:t)}}),Wo=Qt.omit({parent:!0,labels:!0}).partial({key:!0}),fm="sy_range_alias_set",pm="sy_range_alias_delete",ym=s.z.object({range:V,aliases:s.z.string().array()}),gm=s.z.object({aliases:s.z.record(s.z.string(),D)}),mm=s.z.object({range:V,aliases:s.z.record(D.or(s.z.string()),s.z.string())}),wm=s.z.unknown(),bm=s.z.object({range:V,channels:D.array()}),vm=s.z.unknown(),Tm=s.z.object({range:V}),Om=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),Sm=s.z.object({range:V,channels:D.array()}),zm=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())});let Qe=class et{static SET_ENDPOINT="/range/alias/set";static RESOLVE_ENDPOINT="/range/alias/resolve";static LIST_ENDPOINT="/range/alias/list";static RETRIEVE_ENDPOINT="/range/alias/retrieve";static DELETE_ENDPOINT="/range/alias/delete";frameClient;cache=new Map;client;rangeKey;constructor(e,r,n){this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=r}async resolve(e){const r=[],n=typeof e=="string",a={};if(n){const o=this.cache.get(e);if(o!=null)return o;r.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?a[o]=l:r.push(o)});if(r.length===0)return a;const i=await m(this.client,et.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:r},ym,gm);return Object.entries(i.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?i.aliases[r[0]]:{...a,...i.aliases}}async set(e){await m(this.client,et.SET_ENDPOINT,{range:this.rangeKey,aliases:e},mm,wm)}async list(){return(await m(this.client,et.LIST_ENDPOINT,{range:this.rangeKey},Tm,Om)).aliases}async retrieve(e){const r=typeof e=="number",n=await m(this.client,et.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:O.toArray(e)},Sm,zm);return r?n.aliases[e]:n.aliases}async delete(e){await m(this.client,et.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},bm,vm)}};const Em=s.z.object({alias:s.z.string().optional(),channel:D,range:V}),Go="---",Nm=t=>`${t.range}${Go}${t.channel}`,Am=t=>{const[e,r]=t.split(Go);return{range:e,channel:Number(r)}},km="sy_range_kv_set",xm="sy_range_kv_delete",Es=s.z.object({range:V,key:s.z.string(),value:s.z.string()}),Cm=({range:t,key:e})=>`${t}<--->${e}`,Im=s.z.object({range:V,keys:s.z.string().array()}),jm=s.z.object({pairs:Y(Es)}),Rm=s.z.object({range:V,pairs:Es.array()}),Um=s.z.object({range:V,keys:s.z.string().array()});class Ye{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,r){this.rangeKey=e,this.client=r}async get(e){const r=await m(this.client,Ye.GET_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},Im,jm);return typeof e=="string"?r.pairs[0].value:Object.fromEntries(r.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,r=""){let n;ii(e)?n=Object.entries(e).map(([a,i])=>({range:this.rangeKey,key:a,value:i})):n=[{range:this.rangeKey,key:e,value:r}],await m(this.client,Ye.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Rm,s.z.unknown())}async delete(e){await m(this.client,Ye.DELETE_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},Um,s.z.unknown())}}const Mm="sy_range_set",Lm="sy_range_delete";class Ko{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:r=M.ZERO,key:n,color:a,parent:i,labels:o},{frameClient:l,kv:c,aliaser:u,channels:h,labelClient:p,ontologyClient:d,rangeClient:S}){this.key=n,this.name=e,this.timeRange=r,this.parent=i,this.labels=o,this.frameClient=l,this.color=a,this.kv=c,this.aliaser=u,this.channels=h,this.labelClient=p,this.ontologyClient=d,this.rangeClient=S}get ontologyID(){return tt(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,r){const n=await this.channels.retrieve(e);if(n.length===0)throw new Le(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:r})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(r=>r.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:tt(this.key)})}async addLabel(...e){await this.labelClient.label(tt(this.key),e)}async removeLabel(...e){await this.labelClient.remove(tt(this.key),e)}static sort(e,r){return M.sort(e.timeRange,r.timeRange)}}const Pm=s.z.object({keys:V.array().optional(),names:s.z.array(s.z.string()).optional(),searchTerm:s.z.string().optional(),overlapsWith:M.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional(),hasLabels:Pe.array().optional(),includeLabels:s.z.boolean().optional(),includeParent:s.z.boolean().optional()}),Dm=Pm.or(V.array().transform(t=>({keys:t}))).or(V.transform(t=>({keys:[t]}))).or(s.z.string().transform(t=>({names:[t]}))).or(s.z.string().array().transform(t=>({names:t}))).or(M.z.transform(t=>({overlapsWith:t}))),Bm="/range/retrieve",$m=s.z.object({ranges:Y(Qt)});let Jo=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(t,e,r,n,a,i){this.frameClient=t,this.writer=e,this.unaryClient=r,this.channels=n,this.labelClient=a,this.ontologyClient=i}async create(t,e){const r=!Array.isArray(t),n=this.sugarMany(await this.writer.create(O.toArray(t),e));return r?n[0]:n}async rename(t,e){await this.writer.rename(t,e)}async delete(t){await this.writer.delete(O.toArray(t))}async retrieve(t){const e=typeof t=="string",{ranges:r}=await m(this.unaryClient,Bm,t,Dm,$m);return yt("Range",t,r,e),e?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(t){return new Ye(t,this.unaryClient)}async retrieveParent(t){const e=await this.ontologyClient.retrieveParents(tt(t));if(e.length===0)return null;const r=e[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOntologyResource(t){return this.sugarOne(Xo(t))}async retrieveAlias(t,e){return await new Qe(t,this.frameClient,this.unaryClient).retrieve(e)}async retrieveAliases(t,e){return await new Qe(t,this.frameClient,this.unaryClient).retrieve(e)}async listAliases(t){return await new Qe(t,this.frameClient,this.unaryClient).list()}async setAlias(t,e,r){await new Qe(t,this.frameClient,this.unaryClient).set({[e]:r})}sugarOne(t){return new Ko(t,{frameClient:this.frameClient,kv:new Ye(t.key,this.unaryClient),aliaser:new Qe(t.key,this.frameClient,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(t){return t.map(e=>this.sugarOne(e))}resourceToRange(t){return this.sugarOne({key:t.id.key,name:t.data?.name,timeRange:new M(t.data?.timeRange),color:t.data?.color,labels:[],parent:null})}};const tt=t=>({type:"range",key:t}),Fm=t=>({type:"range-alias",key:t}),Xo=({data:t,id:{key:e},name:r})=>{const n=M.z.parse(t?.timeRange);return{key:e,name:r,timeRange:n,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},qm=s.z.object({ranges:Qt.array()}),Zm=s.z.object({parent:U.optional(),ranges:Wo.array()}),Ym=s.z.object({keys:V.array()}),Vm=s.z.object({}),Hm=s.z.object({key:V,name:zs}),_m=s.z.object({}),Wm="/range/create",Gm="/range/delete",Km="/range/rename";class Qo{client;constructor(e){this.client=e}async rename(e,r){await m(this.client,Km,{key:e,name:r},Hm,_m)}async create(e,r){return(await m(this.client,Wm,{ranges:e,...r},Zm,qm)).ranges}async delete(e){await m(this.client,Gm,{keys:e},Ym,Vm)}}const Jm=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:Qe,Client:Jo,DELETE_ALIAS_CHANNEL_NAME:pm,DELETE_CHANNEL_NAME:Lm,KV:Ye,KV_DELETE_CHANNEL:xm,KV_SET_CHANNEL:km,Range:Ko,SET_ALIAS_CHANNEL_NAME:fm,SET_CHANNEL_NAME:Mm,Writer:Qo,aliasKey:Nm,aliasOntologyID:Fm,aliasZ:Em,convertOntologyResourceToPayload:Xo,decodeDeleteAliasChange:Am,keyZ:V,kvPairKey:Cm,kvPairZ:Es,nameZ:zs,newZ:Wo,ontologyID:tt,payloadZ:Qt},Symbol.toStringTag,{value:"Module"})),Xm="/api/v1/";class Qm{url;unary;stream;secure;constructor(e,r={},n=!1){this.secure=n,this.url=e.child(Xm);const a=new Ve.JSONCodec;this.unary=Uu(new Ru(this.url,a,this.secure),r),this.stream=new Bu(this.url,a,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const er=s.z.uuid(),Ns=s.z.object({key:er,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te))}),ew=Ns.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ge=s.z.uuid(),Vr=s.z.object({key:ge,name:s.z.string(),layout:ve.unknownZ.or(s.z.string().transform(Te))}),el=Vr.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),tl=Vr.omit({layout:!0}).extend({layout:s.z.string().transform(Te)}),tw="/workspace/lineplot/retrieve",rw="/workspace/lineplot/create",nw="/workspace/lineplot/rename",sw="/workspace/lineplot/set-data",aw="/workspace/lineplot/delete",iw=s.z.object({keys:er.array()}),ow=s.z.object({workspace:ge,linePlots:ew.array()}),lw=s.z.object({key:er,name:s.z.string()}),cw=s.z.object({key:er,data:s.z.string()}),uw=s.z.object({keys:er.array()}),hw=s.z.object({linePlots:Y(Ns)}),dw=s.z.object({linePlots:Ns.array()}),cn=s.z.object({});let fw=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,rw,{workspace:t,linePlots:O.toArray(e)},ow,dw);return r?n.linePlots:n.linePlots[0]}async rename(t,e){await m(this.client,nw,{key:t,name:e},lw,cn)}async setData(t,e){await m(this.client,sw,{key:t,data:JSON.stringify(e)},cw,cn)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,tw,{keys:O.toArray(t)},iw,hw);return e?r.linePlots:r.linePlots[0]}async delete(t){await m(this.client,aw,{keys:O.toArray(t)},uw,cn)}};const tr=s.z.uuid(),As=s.z.object({key:tr,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te))}),pw=As.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),yw="/workspace/log/retrieve",gw="/workspace/log/create",mw="/workspace/log/rename",ww="/workspace/log/set-data",bw="/workspace/log/delete",vw=s.z.object({keys:tr.array()}),Tw=s.z.object({workspace:ge,logs:pw.array()}),Ow=s.z.object({key:tr,name:s.z.string()}),Sw=s.z.object({key:tr,data:s.z.string()}),zw=s.z.object({keys:tr.array()}),Ew=s.z.object({logs:As.array()}),Nw=s.z.object({logs:As.array()}),un=s.z.object({});let Aw=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,gw,{workspace:t,logs:O.toArray(e)},Tw,Nw);return r?n.logs:n.logs[0]}async rename(t,e){await m(this.client,mw,{key:t,name:e},Ow,un)}async setData(t,e){await m(this.client,ww,{key:t,data:JSON.stringify(e)},Sw,un)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,yw,{keys:O.toArray(t)},vw,Ew);return e?r.logs:r.logs[0]}async delete(t){await m(this.client,bw,{keys:O.toArray(t)},zw,un)}};const mt=s.z.uuid(),ks=s.z.object({key:mt,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te)),snapshot:s.z.boolean()}),kw=ks.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),rl=ks.extend({data:s.z.string().transform(Te)}),xw="/workspace/schematic/retrieve",Cw="/workspace/schematic/create",Iw="/workspace/schematic/rename",jw="/workspace/schematic/set-data",Rw="/workspace/schematic/delete",Uw="/workspace/schematic/copy",Mw=s.z.object({keys:mt.array()}),Lw=s.z.object({workspace:ge,schematics:kw.array()}),Pw=s.z.object({key:mt,name:s.z.string()}),Dw=s.z.object({key:mt,data:s.z.string()}),Bw=s.z.object({keys:mt.array()}),$w=s.z.object({key:mt,name:s.z.string(),snapshot:s.z.boolean()}),Fw=s.z.object({schematics:Y(rl)}),qw=s.z.object({schematics:rl.array()}),Zw=s.z.object({schematic:ks}),hn=s.z.object({});let Yw=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,Cw,{workspace:t,schematics:O.toArray(e)},Lw,qw);return r?n.schematics:n.schematics[0]}async rename(t,e){await m(this.client,Iw,{key:t,name:e},Pw,hn)}async setData(t,e){await m(this.client,jw,{key:t,data:JSON.stringify(e)},Dw,hn)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,xw,{keys:O.toArray(t)},Mw,Fw);return e?r.schematics:r.schematics[0]}async delete(t){await m(this.client,Rw,{keys:O.toArray(t)},Bw,hn)}async copy(t,e,r){return(await m(this.client,Uw,{key:t,name:e,snapshot:r},$w,Zw)).schematic}};const rr=s.z.uuid(),nl=s.z.object({key:rr,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te))}),Vw=nl.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),sl=nl.extend({data:s.z.string().transform(Te)}),Hw="/workspace/table/retrieve",_w="/workspace/table/create",Ww="/workspace/table/rename",Gw="/workspace/table/set-data",Kw="/workspace/table/delete",Jw=s.z.object({keys:rr.array()}),Xw=s.z.object({workspace:ge,tables:Vw.array()}),Qw=s.z.object({key:rr,name:s.z.string()}),eb=s.z.object({key:rr,data:s.z.string()}),tb=s.z.object({keys:rr.array()}),rb=s.z.object({tables:sl.array()}),nb=s.z.object({tables:sl.array()}),dn=s.z.object({});let sb=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,_w,{workspace:t,tables:O.toArray(e)},Xw,nb);return r?n.tables:n.tables[0]}async rename(t,e){await m(this.client,Ww,{key:t,name:e},Qw,dn)}async setData(t,e){await m(this.client,Gw,{key:t,data:JSON.stringify(e)},eb,dn)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,Hw,{keys:O.toArray(t)},Jw,rb);return e?r.tables:r.tables[0]}async delete(t){await m(this.client,Kw,{keys:O.toArray(t)},tb,dn)}};const Sa="/workspace/retrieve",ab="/workspace/create",ib="/workspace/rename",ob="/workspace/set-layout",lb="/workspace/delete",za=s.z.object({keys:ge.array().optional(),searchTerm:s.z.string().optional(),author:_e.optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),cb=s.z.object({workspaces:el.array()}),ub=s.z.object({key:ge,name:s.z.string()}),hb=s.z.object({key:ge,layout:s.z.string()}),db=s.z.object({keys:ge.array()}),Ea=s.z.object({workspaces:Y(Vr)}),fb=s.z.object({workspaces:tl.array()}),fn=s.z.object({}),pb="sy_workspace_set",yb="sy_workspace_delete";class al{type="workspace";schematic;linePlot;log;table;client;constructor(e){this.client=e,this.schematic=new Yw(e),this.linePlot=new fw(e),this.log=new Aw(e),this.table=new sb(e)}async create(e){const r=Array.isArray(e),n=await m(this.client,ab,{workspaces:O.toArray(e)},cb,fb);return r?n.workspaces:n.workspaces[0]}async rename(e,r){await m(this.client,ib,{key:e,name:r},ub,fn)}async setLayout(e,r){await m(this.client,ob,{key:e,layout:JSON.stringify(r)},hb,fn)}async retrieve(e){let r;const n=typeof e!="string";typeof e=="string"||Array.isArray(e)?r={keys:O.toArray(e)}:r=e;const a=await m(this.client,Sa,r,za,Ea);return n?a.workspaces:a.workspaces[0]}async retrieveByAuthor(e){return(await m(this.client,Sa,{author:e},za,Ea)).workspaces}async delete(e){await m(this.client,lb,{keys:O.toArray(e)},db,fn)}}const gb=t=>({type:"workspace",key:t}),mb=Object.freeze(Object.defineProperty({__proto__:null,Client:al,DELETE_CHANNEL_NAME:yb,SET_CHANNEL_NAME:pb,keyZ:ge,newZ:el,ontologyID:gb,remoteZ:tl,workspaceZ:Vr},Symbol.toStringTag,{value:"Module"})),il=s.z.object({host:s.z.string({error:"Host is required"}).min(1,"Host is required"),port:s.z.number({error:"Port is required"}).or(s.z.string({error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:z.z.default(z.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:Mi.breakerConfigZ.optional()});class wb extends Eo{createdAt;props;ranges;channels;auth;user;access;connectivity;ontology;workspaces;labels;hardware;control;static connectivity=Er;transport;clientVersion="0.44.3";constructor(e){const r=il.parse(e),{host:n,port:a,username:i,password:o,connectivityPollFrequency:l,secure:c,retry:u}=r,h=new Qm(new kt({host:n,port:Number(a)}),u,c);h.use(Tf);let p;i!=null&&o!=null&&(p=new dy(h.unary,{username:i,password:o}),h.use(p.middleware()));const d=new gs(new Kt(h.unary)),S=new ho(h.unary,d);super(h.stream,h.unary,d),this.createdAt=E.now(),this.props=r,this.auth=p,this.transport=h,this.channels=new lo(this,d,h.unary,S),this.connectivity=new Er(h.unary,l,this.clientVersion,r.name),this.control=new ko(this),this.ontology=new ro(h.unary,this);const N=new Qo(this.transport.unary);this.labels=new _o(this.transport.unary),this.ranges=new Jo(this,N,this.transport.unary,d,this.labels,this.ontology),this.access=new dp(this.transport.unary),this.user=new sy(this.transport.unary),this.workspaces=new al(this.transport.unary);const x=new Uo(this.transport.unary),B=new Fo(this.transport.unary,this,this.ontology,this.ranges),C=new Mo(this.transport.unary,B);this.hardware=new Wy(B,C,x)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}z.seconds(1);const bb=t=>Array.isArray(t)?t:t==null?[]:[t],vb=Object.freeze(Object.defineProperty({__proto__:null,toArray:bb},Symbol.toStringTag,{value:"Module"})),pn=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Tb=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},Ob=(t,e)=>{let r=null;return e===0?t:(...n)=>{r===null&&(r=setTimeout(()=>{t(...n),r=null},e))}},ol=(t,e,r=".")=>{const n=t.split(r);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(r)}).filter(a=>a!=null).join(r)},xs=(t,e)=>{if(!Array.isArray(t))return t[e];const r=t[e];if(r!=null||t.length==0)return r;const n=t[0];if(typeof n=="object"&&"key"in n)return t.find(a=>a.key===e)},Sb=(t,e)=>{const r=t.split(".");return r.forEach((n,a)=>{e=xs(e,n),e!=null&&typeof e=="object"&&"key"in e&&(r[a]=e.key)}),r.join(".")},Cs=(t,e,r={optional:!1,separator:"."})=>{r.separator??=".";const{optional:n,getter:a=xs}=r,i=e.split(r.separator);if(i.length===1&&i[0]==="")return t;let o=t;for(const l of i){const c=a(o,l);if(c==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=c}return o},zb=t=>{for(const e of t)if(isNaN(parseInt(e)))return null;return parseInt(t)},Eb=(t,e,r)=>{const n=e.split(".");let a=t;for(let i=0;i<n.length-1;i++){const o=n[i],l=xs(a,o);if(l==null)throw new Error(`Path ${e} does not exist. ${o} is null`);a=l}try{if(!Array.isArray(a)){a[n[n.length-1]]=r;return}if(a.length===0)return;const i=zb(n[n.length-1]);if(i==null){const o=a[0];if(typeof o=="object"&&"key"in o){const l=a.findIndex(c=>c.key===n[n.length-1]);if(l!==-1){a[l]=r;return}}return}a[i]=r}catch(i){throw console.error("failed to set value",r,"at path",e,"on object",t),i}},Nb=(t,e)=>{const r=e.split(".");let n=t;for(let a=0;a<r.length-1;a++){const i=r[a];if(n[i]==null)return;n=n[i]}if(Array.isArray(n)){const a=parseInt(r[r.length-1]);if(isNaN(a))return;n.splice(a,1);return}delete n[r[r.length-1]]},Ab=(t,e)=>{const r=t.split(".");return e<0?r[r.length+e]:r[e]},kb=(t,e)=>{try{return Cs(t,e),!0}catch{return!1}},xb=(t,e)=>{if(e.length===0)return!0;const r=t.split("."),n=e.split(".");if(n.length>r.length)return!1;for(let a=0;a<n.length;a++){const i=r[a],o=n[a];if(o!=="*"&&i!==o)return!1}return!0},Cb=t=>{try{return structuredClone(t)}catch{return console.warn("Failed to deep copy object, falling back to JSON.parse(JSON.stringify)",t),console.trace(),JSON.parse(JSON.stringify(t))}},Ib=(t,...e)=>(e.forEach(r=>{let n=t;const a=r.split(".");a.forEach((i,o)=>{typeof n!="object"||n===null||(o===a.length-1?delete n[i]:i in n&&(n=n[i]))})}),t),jb=(t,e,r="")=>{const n={},a=(i,o,l)=>{if(typeof i!=typeof o||i===null||o===null){n[l]=[i,o];return}if(typeof i=="object"&&typeof o=="object")if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length){n[l]=[i,o];return}for(let c=0;c<i.length;c++)a(i[c],o[c],`${l}[${c}]`)}else new Set([...Object.keys(i),...Object.keys(o)]).forEach(c=>{a(i[c],o[c],l!==""?`${l}.${c}`:c)});else i!==o&&(n[l]=[i,o])};return a(t,e,r),n},qn=(t,e)=>{const r=Array.isArray(t),n=Array.isArray(e);if(r!==n)return!1;if(r&&n){const o=t,l=e;if(o.length!==l.length)return!1;for(let c=0;c<o.length;c++)if(!qn(o[c],l[c]))return!1;return!0}if(t==null||e==null||typeof t!="object"||typeof e!="object")return t===e;if("equals"in t)return t.equals(e);const a=Object.keys(t),i=Object.keys(e);if(a.length!==i.length)return!1;for(const o of a){const l=t[o],c=e[o];if(typeof l=="object"&&typeof c=="object"){if(!qn(l,c))return!1}else if(l!==c)return!1}return!0},ll=(t,e)=>{if(typeof t!="object"||t==null)return t===e;const r=Object.keys(t),n=Object.keys(e);if(n.length>r.length)return!1;for(const a of n){const i=t[a],o=e[a];if(typeof i=="object"&&typeof o=="object"){if(!ll(i,o))return!1}else if(i!==o)return!1}return!0},Zn=(t,...e)=>{if(e.length===0)return t;const r=e.shift();if(pn(t)&&pn(r))for(const n in r)try{pn(r[n])?(n in t||Object.assign(t,{[n]:{}}),Zn(t[n],r[n])):Object.assign(t,{[n]:r[n]})}catch(a){throw a instanceof TypeError?new TypeError(`.${n}: ${a.message}`):a}return Zn(t,...e)},Rb=(t,e,r)=>{const n=(a,i,o)=>{if(o.def?.type==="union")return o.def.options.reduce((l,c)=>n(l,i,c),a);if(o.def?.type==="intersection"){const l=n(a,i,o.def.left);return n(l,i,o.def.right)}for(const l in i){const c=i[l];let u=o?.shape;if(u!=null)for(;u!=null;){if(u[l]!=null){const h=u[l].safeParse(c);if(h.success){a[l]=h.data;break}}u=u.def?.shape}typeof c=="object"&&!Array.isArray(c)&&c!==null&&o&&o.shape&&o.shape[l]&&(a[l]||={},n(a[l],c,o.shape[l]))}return a};return n({...t},e,r)},cl=Object.freeze(Object.defineProperty({__proto__:null,copy:Cb,deleteD:Ib,difference:jb,element:Ab,equal:qn,get:Cs,has:kb,override:Zn,overrideValidItems:Rb,partialEqual:ll,pathsMatch:xb,remove:Nb,resolvePath:Sb,set:Eb,transformPath:ol},Symbol.toStringTag,{value:"Module"}));let Ub=class{sender;handlers;constructor(e){this.sender=e,this.handlers=new Map}handle({data:e}){const r=this.handlers.get(e.type)?.handler;r==null?console.warn(`No handler for ${e.type}`):r(e.payload)}route(e){const r=Mb(e,this.sender),n=new Lb(r);return this.handlers.set(e,n),n}};const Mb=(t,e)=>(r,n)=>e({type:t,payload:r},n);class Lb{_send;handler;constructor(e){this._send=e,this.handler=null}send(e,r=[]){this._send(e,r)}handle(e){this.handler=e}}const Yn=(t,e,r="")=>{try{return t.parse(e)}catch(n){if(n instanceof s.z.ZodError){const a=n.issues.map(i=>i.path.length===0?i.message:`${i.path.join(".")}: ${i.message}`);throw new Error(`${r} - ${a.join(`
45
+ `)}`)}else throw n}},ul=t=>typeof t=="function",Is=(t,e)=>ul(t)?t(e):t,nr=t=>hl(t)?t():t,hl=t=>typeof t=="function",dl=({initial:t,value:e,onChange:r})=>{const[n,a]=ts.useState(nr(e??t));return e!=null&&r!=null?[e,r]:[n,a]},fl=({initial:t,value:e,onChange:r})=>{const[n,a]=ts.useState(nr(e??t));return e!=null&&r!=null?[e,r]:[n,a]},Pb=(t,e)=>{const[r,n]=ts.useState(()=>{const a=localStorage.getItem(e);return a==null?nr(t):JSON.parse(a)});return[r,a=>{n(a),localStorage.setItem(e,JSON.stringify(a))}]},Db=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:nr,executeSetter:Is,isInitialSetter:hl,isSetter:ul,usePassthrough:dl,usePersisted:Pb,usePurePassthrough:fl},Symbol.toStringTag,{value:"Module"}));let Na=null;const Bb=()=>(Na??=document.createElement("canvas"),Na),$b=(t,e,r)=>{if(f.S.RUNTIME==="node")return{width:0,height:0};r??=Bb().getContext("2d"),r.font=e;const n=r.measureText(t);return Hr(n)},Hr=t=>({width:Math.trunc(Math.abs(t.actualBoundingBoxLeft)+Math.abs(t.actualBoundingBoxRight)),height:Math.trunc(Math.abs(t.actualBoundingBoxAscent)+Math.abs(t.actualBoundingBoxDescent))}),Ct=["h1","h2","h3","h4","h5","p","small"],Fb=s.z.enum(Ct),qb=t=>{const e=Ct.indexOf(t);return e===-1||e===Ct.length-1?t:Ct[e+1]},Zb=s.z.union([s.z.number(),s.z.enum(["normal","bold","bolder","lighter"])]),xe=s.z.object({size:s.z.number(),weight:s.z.union([s.z.number(),s.z.string()]),lineHeight:s.z.number(),textTransform:s.z.string().optional()}),Yb={tiny:"small",small:"small",medium:"p",large:"h5",huge:"h2"},Vb={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"},Hb=s.z.object({l0:f.cr.colorZ,l1:f.cr.colorZ,l2:f.cr.colorZ,l3:f.cr.colorZ,l4:f.cr.colorZ,l5:f.cr.colorZ,l6:f.cr.colorZ,l7:f.cr.colorZ,l8:f.cr.colorZ,l9:f.cr.colorZ,l10:f.cr.colorZ,l11:f.cr.colorZ}),Q=(t,e)=>[t[0],t[1],e,t[3]],_b=s.z.object({m2:f.cr.colorZ,m1:f.cr.colorZ,z:f.cr.colorZ,p1:f.cr.colorZ,p2:f.cr.colorZ}),ur=_b.or(f.cr.colorZ.transform(t=>{const e=f.cr.hsla(t);return{m2:f.cr.fromHSLA(Q(e,40)),m1:f.cr.fromHSLA(Q(e,45)),z:t,p1:f.cr.fromHSLA(Q(e,55)),p2:f.cr.fromHSLA(Q(e,65))}})),pl=s.z.object({name:s.z.string(),key:s.z.string(),colors:s.z.object({border:f.cr.colorZ,primary:ur,gray:Hb,error:ur,secondary:ur,warning:ur,palettes:s.z.record(s.z.string(),f.cr.paletteZ),visualization:s.z.object({palettes:s.z.record(s.z.string(),s.z.array(f.cr.colorZ))}).optional().default({palettes:{}}),white:f.cr.colorZ,black:f.cr.colorZ,text:f.cr.colorZ,textInverted:f.cr.colorZ,textOnPrimary:f.cr.colorZ.optional().default(f.cr.ZERO),logo:s.z.string()}),sizes:s.z.object({base:s.z.number(),border:s.z.object({radius:s.z.number(),width:s.z.number(),thickWidth:s.z.number()}),schematic:s.z.object({elementStrokeWidth:s.z.number()})}),typography:s.z.object({family:s.z.string(),codeFamily:s.z.string(),h1:xe,h2:xe,h3:xe,h4:xe,h5:xe,p:xe,small:xe})}).transform(t=>((t.colors.textOnPrimary==null||f.cr.isZero(t.colors.textOnPrimary))&&(t.colors.textOnPrimary=f.cr.pickByContrast(t.colors.primary.z,t.colors.text,t.colors.textInverted)),t)),Wb="'Inter Variable', sans-serif",Gb="'Geist Mono', monospace",Kb=6,vt=[357,91,55,1],Tt=[48,90,55,1],Jb=["#FEFEFE","#FAFAFA","#F2F2F2","#ECECEC","#E4E4E4","#D1D1D1","#BCBCBC","#ACACAC","#8F8F8F","#4F4F4F","#292929","#050505"],Ot=Object.fromEntries(Jb.map((t,e)=>[`l${e}`,t])),Xb=()=>typeof window>"u"?!1:window.devicePixelRatio>1,Qb=Xb(),Vn={key:"synnaxBase",name:"Synnax Base",colors:{primary:{m2:"#041B3D",m1:"#356fc5",z:"#3774D0",p1:"#5E94EE",p2:"#8AB8FF"},secondary:{m2:"#2D8F4E",m1:"#38B261",z:"#50C878",p1:"#73D393",p2:"#96DEAE"},gray:Ot,border:Ot.l4,error:{m2:f.cr.fromHSLA(Q(vt,30)),m1:f.cr.fromHSLA(Q(vt,40)),z:f.cr.fromHSLA(vt),p1:f.cr.fromHSLA(Q(vt,65)),p2:f.cr.fromHSLA(Q(vt,77))},warning:{m2:f.cr.fromHSLA(Q(Tt,30)),m1:f.cr.fromHSLA(Q(Tt,40)),z:f.cr.fromHSLA(Tt),p1:f.cr.fromHSLA(Q(Tt,65)),p2:f.cr.fromHSLA(Q(Tt,75))},palettes:{recent:{key:"recent",name:"Recent",swatches:[]}},visualization:{palettes:{default:["#DC136C","#20A4F3","#7AC74F","#FFC43D","#FE5F55","#8075FF","#D90429","#f7aef8","#f18f01","#791e94","#279af1","#d9fff5","#ff6b6b","#52ffb8"]}},logo:"url(#synnax-linear-gradient)",white:"#FFFFFF",black:"#000000",text:Ot.l11,textInverted:Ot.l0,textOnPrimary:Ot.l0},sizes:{base:Kb,border:{radius:3,width:Qb?.5:1,thickWidth:1},schematic:{elementStrokeWidth:2}},typography:{family:Wb,codeFamily:Gb,h1:{size:6,weight:"500",lineHeight:6*1.5},h2:{size:4.5,weight:"medium",lineHeight:4.5*1.5},h3:{size:3.5,weight:"medium",lineHeight:3.5*1.5},h4:{size:2.6666,weight:"medium",lineHeight:2.6666*1.5},h5:{size:2.333333,weight:450,lineHeight:2.333333*1.5},p:{size:2.1666666666,weight:"regular",lineHeight:2*1.5},small:{size:1.916666,weight:"regular",lineHeight:2.3333333}}},yl=Object.freeze({...Vn,key:"synnaxLight",name:"Synnax Light"}),ev=["#020202","#080808","#151515","#242424","#2F2F2F","#3B3B3B","#4A4A4A","#5C5C5C","#767676","#959595","#dadada","#FAFAFA"],St=Object.fromEntries(ev.map((t,e)=>[`l${e}`,t])),gl=Object.freeze({...Vn,key:"synnaxDark",name:"Synnax Dark",colors:{...Vn.colors,gray:St,logo:"var(--pluto-text-color)",border:St.l3,text:St.l11,textInverted:St.l0,textOnPrimary:St.l11}}),tv={synnaxDark:gl,synnaxLight:yl},ml=["tiny","small","medium","large","huge"],wl=s.z.enum(ml),rv=t=>wl.safeParse(t).success;class lt{_noop=!1;key;path;serviceName;constructor(e,r,n="",a=!1){this.key=e,this.path=r,this.serviceName=n,this._noop=a}child(e){return new lt(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}static NOOP=new lt("","","")}const Hn=["debug","info","warn","error"],bl=t=>{const e=Hn.indexOf(t);return({level:r})=>Hn.indexOf(r)>=e},nv=t=>{const{include:e,exclude:r}=t;return({path:n})=>!(e!=null&&!e.some(a=>n.startsWith(a))||r!=null&&r.some(a=>n.startsWith(a)))};class ct{meta=lt.NOOP;filters;constructor(e={}){const{filters:r=[]}=e;this.filters=r}filter(e){return!this.meta.noop&&this.filters.every(r=>r({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const r=new ct({filters:this.filters});return r.meta=e,r}debug(e,r,n=!1){!this.filter("debug")&&!n||(r==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,hr(r)))}info(e,r,n=!1){!this.filter("info")&&!n||(r==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,hr(r)))}warn(e,r,n=!1){!this.filter("warn")&&!n||(r==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,hr(r)))}error(e,r,n=!1){!this.filter("error")&&!n||(r==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,hr(r)))}static NOOP=new ct}const hr=t=>typeof t=="function"?t():t;var sv=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Fe="1.9.0",Aa=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function av(t){var e=new Set([t]),r=new Set,n=t.match(Aa);if(!n)return function(){return!1};var a={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(a.prerelease!=null)return function(l){return l===t};function i(l){return r.add(l),!1}function o(l){return e.add(l),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(Aa);if(!c)return i(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||a.major!==u.major?i(l):a.major===0?a.minor===u.minor&&a.patch<=u.patch?o(l):i(l):a.minor<=u.minor?o(l):i(l)}}var iv=av(Fe),ov=Fe.split(".")[0],Pt=Symbol.for("opentelemetry.js.api."+ov),Dt=sv;function js(t,e,r,n){var a;n===void 0&&(n=!1);var i=Dt[Pt]=(a=Dt[Pt])!==null&&a!==void 0?a:{version:Fe};if(!n&&i[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(i.version!==Fe){var o=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+Fe);return r.error(o.stack||o.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Fe+"."),!0}function Bt(t){var e,r,n=(e=Dt[Pt])===null||e===void 0?void 0:e.version;if(!(!n||!iv(n)))return(r=Dt[Pt])===null||r===void 0?void 0:r[t]}function Rs(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Fe+".");var r=Dt[Pt];r&&delete r[t]}var lv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},cv=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},uv=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("verbose",this._namespace,e)},t}();function zt(t,e,r){var n=Bt("diag");if(n)return r.unshift(e),n[t].apply(n,cv([],lv(r),!1))}var J;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(J||(J={}));function hv(t,e){t<J.NONE?t=J.NONE:t>J.ALL&&(t=J.ALL),e=e||{};function r(n,a){var i=e[n];return typeof i=="function"&&t>=a?i.bind(e):function(){}}return{error:r("error",J.ERROR),warn:r("warn",J.WARN),info:r("info",J.INFO),debug:r("debug",J.DEBUG),verbose:r("verbose",J.VERBOSE)}}var dv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},fv=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},pv="diag",$t=function(){function t(){function e(a){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var l=Bt("diag");if(l)return l[a].apply(l,fv([],dv(i),!1))}}var r=this,n=function(a,i){var o,l,c;if(i===void 0&&(i={logLevel:J.INFO}),a===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof i=="number"&&(i={logLevel:i});var h=Bt("diag"),p=hv((l=i.logLevel)!==null&&l!==void 0?l:J.INFO,a);if(h&&!i.suppressOverrideMessage){var d=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";h.warn("Current logger will be overwritten from "+d),p.warn("Current logger will overwrite one already registered from "+d)}return js("diag",p,r,!0)};r.setLogger=n,r.disable=function(){Rs(pv,r)},r.createComponentLogger=function(a){return new uv(a)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),yv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},gv=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},mv=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=yv(e,2),n=r[0],a=r[1];return[n,a]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];var i=new t(this._entries);try{for(var o=gv(n),l=o.next();!l.done;l=o.next()){var c=l.value;i._entries.delete(c)}}catch(u){e={error:u}}finally{try{l&&!l.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return i},t.prototype.clear=function(){return new t},t}();$t.instance();function wv(t){return t===void 0&&(t={}),new mv(new Map(Object.entries(t)))}function bv(t){return Symbol.for(t)}var vv=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,a){var i=new t(r._currentContext);return i._currentContext.set(n,a),i},r.deleteValue=function(n){var a=new t(r._currentContext);return a._currentContext.delete(n),a}}return t}(),Tv=new vv,Ov={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},Sv={set:function(t,e,r){t!=null&&(t[e]=r)}},zv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},Ev=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},Nv=function(){function t(){}return t.prototype.active=function(){return Tv},t.prototype.with=function(e,r,n){for(var a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return r.call.apply(r,Ev([n],zv(a),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),Av=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},kv=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},yn="context",xv=new Nv,vl=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return js(yn,e,$t.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var a,i=[],o=3;o<arguments.length;o++)i[o-3]=arguments[o];return(a=this._getContextManager()).with.apply(a,kv([e,r,n],Av(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Bt(yn)||xv},t.prototype.disable=function(){this._getContextManager().disable(),Rs(yn,$t.instance())},t}(),_n;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(_n||(_n={}));var Cv=vl.getInstance(),Iv=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),Us=bv("OpenTelemetry Baggage Key");function Tl(t){return t.getValue(Us)||void 0}function jv(){return Tl(vl.getInstance().active())}function Rv(t,e){return t.setValue(Us,e)}function Uv(t){return t.deleteValue(Us)}var gn="propagation",Mv=new Iv,Lv=function(){function t(){this.createBaggage=wv,this.getBaggage=Tl,this.getActiveBaggage=jv,this.setBaggage=Rv,this.deleteBaggage=Uv}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return js(gn,e,$t.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=Sv),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=Ov),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){Rs(gn,$t.instance())},t.prototype._getGlobalPropagator=function(){return Bt(gn)||Mv},t}(),Pv=Lv.getInstance();const ka=["bench","debug","prod"],Dv=t=>e=>ka.indexOf(e)>=ka.indexOf(t);class Ft{meta=lt.NOOP;otelTracer;filter;constructor(e,r=Dv("debug")){this.otelTracer=e,this.filter=r}child(e){const r=new Ft(this.otelTracer,this.filter);return r.meta=e,r}debug(e,r){return this.trace(e,"debug",r)}bench(e,r){return this.trace(e,"bench",r)}prod(e,r){return this.trace(e,"prod",r)}trace(e,r,n){const a=this.meta.noop||!this.filter(r)||this.otelTracer==null;if(n==null){if(a)return()=>{};const i=new Wn(e,this.otelTracer.startSpan(e));return i.start(),()=>i.end()}return a?n(new Ol(e)):this.otelTracer.startActiveSpan(e,i=>{const o=new Wn(e,i);return n(o)})}propagate(e){if(this.meta.noop)return;const r=Cv.active();Pv.inject(r,e,{set:(n,a,i)=>{n[a]=i}})}static NOOP=new Ft}class Wn{key;otel;constructor(e,r){this.key=e,this.otel=r}set(e,r){this.otel.setAttribute(e,r)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:_n.ERROR}))}start(){performance.mark(`alamos.trace.start.${this.key}`)}end(){try{performance.mark(`alamos.trace.end.${this.key}`);const e=performance.measure(`alamos.trace.duration.${this.key}`,`alamos.trace.start.${this.key}`,`alamos.trace.end.${this.key}`);this.set("duration",e.duration),this.otel.end()}catch(e){console.error(e)}}}class Ol{key;constructor(e){this.key=e}set(){}recordError(e){}}class ut{meta;T;L;constructor({key:e="",serviceName:r="",logger:n=ct.NOOP,tracer:a=Ft.NOOP,noop:i=!1,__meta:o}){this.meta=o??new lt(e,e,r,i),this.T=a.child(this.meta),this.L=n.child(this.meta)}child(e){const r=this.meta.child(e);return new ut({__meta:r,tracer:this.T,logger:this.L})}static NOOP=new ut({noop:!0})}const Bv=ut.NOOP,je=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:ut,LOG_LEVELS:Hn,Logger:ct,NOOP:Bv,NoopSpan:Ol,Tracer:Ft,_Span:Wn,logLevelKeyFiler:nv,logThresholdFilter:bl},Symbol.toStringTag,{value:"Module"})),mn=(t,e)=>t instanceof Error?(t.message=`[${e}] - ${t.message}`,t):new Error(e??"unknown error",{cause:t});class _r{type;key;sender;_internalState;_state;_prevState;_deleted=!1;parentCtxValues;childCtxValues;childCtxChangedKeys;instrumentation;schema=void 0;constructor({key:e,type:r,sender:n,instrumentation:a,parentCtxValues:i}){this.type=r,this.key=e,this.sender=n,this._internalState={},this.instrumentation=a.child(this.toString()),this.parentCtxValues=new Map,i?.forEach((o,l)=>this.parentCtxValues.set(l,o)),this.childCtxValues=new Map,this.childCtxChangedKeys=new Set}get _schema(){if(this.schema==null)throw new $(`[AetherLeaf] - expected subclass to define component schema, but none was found.
46
+ Make sure to define a property 'schema' on the class.`);return this.schema}setState(e){const r=Is(e,this.state);this._prevState=f.yr(this._state),this._state=Yn(this._schema,r,`${this.toString()}`),this.sender.send({variant:"update",key:this.key,state:this._state})}get state(){if(this._state==null)throw new W(`[AetherLeaf] - state not defined in ${this.toString()}`);return this._state}get internal(){return this._internalState}get prevState(){if(this._prevState===void 0)throw new Error("prevState not defined");return this._prevState}get deleted(){return this._deleted}get ctx(){return{get:e=>{const r=this.parentCtxValues.get(e);if(r===void 0)throw new it(`Context value for ${e} not found on ${this.toString()}`);return r},getOptional:e=>this.parentCtxValues.get(e),has:e=>this.parentCtxValues.has(e),wasSetPreviously:e=>this.childCtxValues.has(e),set:(e,r,n=!0)=>{this.childCtxValues.set(e,r),n&&this.childCtxChangedKeys.add(e)}}}toString(){return`${this.type}(${this.key})`}_updateState({path:e,state:r}){if(!this.deleted)try{const n=this.instrumentation.T.debug(`${this.toString()}:updateState`);this.validatePath(e);const a=Yn(this._schema,r,`${this.toString()}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:cl.difference(this.state,a)})):this.instrumentation.L.debug("setting initial state",{state:r,path:e}),this._prevState=this._state??a,this._state=a,this.afterUpdate(this.ctx),n()}catch(n){throw mn(n,`${this.toString()}.updateState`)}}_updateContext(e){try{const r=this.instrumentation.T.debug(`${this.toString()}:updateContext`);e.forEach((n,a)=>this.parentCtxValues.set(a,n)),this.afterUpdate(this.ctx),r()}catch(r){throw mn(r,`${this.type}.${this.key}.updateContext`)}}_delete(e){try{const r=this.instrumentation.T.debug(`${this.toString()}:delete`);this.validatePath(e),this._deleted=!0,this.afterDelete(this.ctx),r()}catch(r){throw mn(r,`[${this.toString()}:delete]`)}}afterUpdate(e){}afterDelete(e){}validatePath(e){if(e.length===0)throw new W(`[Leaf.setState] - ${this.toString()} received an empty path`);const r=e[e.length-1];if(e.length>1)throw new W(`[Leaf.setState] - ${this.toString()} received a subPath ${e.join(".")} but is a leaf`);if(r!==this.key)throw new W(`[Leaf.setState] - ${this.toString()} received a key ${r} but expected ${this.key}`)}}class wt extends _r{_children=new Map;get children(){return Array.from(this._children.values())}getChild(e){return this._children.get(e)??null}childrenOfType(...e){return this.children.filter(r=>e.includes(r.type))}_updateState(e){const{path:r,type:n,create:a}=e;if(this.deleted)return;const i=this.parsePath(r);if(i.length===0){if(this.childCtxChangedKeys.clear(),super._updateState(e),this.childCtxChangedKeys.size==0)return;this.updateChildContexts();return}const l=i[0],c=this.getChild(l);if(c!=null)return c._updateState({...e,path:i});if(i.length>1){const h=r.slice(0,r.indexOf(l)+1).join("."),p=r.join(".");throw new W(`Child of ${this.toString()} at path ${h} does not exist,
47
+ but an extended path ${p} was provided. This means that the aether
48
+ tree is attempting to create a new child of type ${n} (or nested children)
49
+ on a child that does not exist.
50
+
51
+ Children present: ${this.children.map(d=>`${d.type}:${d.key}`).join(".")}
52
+
53
+ `)}const u=a(this.childCtx());u._updateState({...e,path:i}),this._children.set(l,u)}_updateContext(e){super._updateContext(e),this.updateChildContexts()}childCtx(){return{get:e=>this.childCtxValues.get(e)??this.parentCtxValues.get(e),forEach:e=>{this.childCtxValues.forEach((r,n)=>e(r,n,this.childCtxValues)),this.parentCtxValues.forEach((r,n)=>{this.childCtxValues.has(n)||e(r,n,this.parentCtxValues)})}}}updateChildContexts(){const e=this.childCtx();this.children.forEach(r=>r._updateContext(e))}_delete(e){const r=this.parsePath(e);if(r.length===0){for(const a of this.children)a._delete([a.key]);this._children.clear(),super._delete([this.key])}const n=this.getChild(r[0]);if(n!=null){if(r.length>1)return n._delete(r);this._children.delete(n.key),n._delete(r)}}parsePath(e,r){const[n,...a]=e;if(n==null)throw new Error(`Composite ${this.toString()} received an empty path${r!=null?` for ${r}`:""}`);if(n!==this.key)throw new W(`[Composite.getRequiredKey] - ${this.toString()} received a key ${n} but expected ${this.key}`);return a}}const $v=s.z.object({}),Fv=()=>{throw new Error("should not call create")};class Re extends wt{static TYPE="root";static KEY="root";comms;registry;schema=$v;constructor({comms:e,instrumentation:r=je.Instrumentation.NOOP,registry:n}){super({key:Re.KEY,type:Re.TYPE,sender:e,instrumentation:r,parentCtxValues:null}),this.comms=e,this.registry=n}static render(e){const r=new Re(e);return r._updateState({path:[Re.KEY],type:"",state:{},create:Fv}),r.comms.handle(n=>{try{r.handle(n)}catch(a){const i={name:"unknown",message:JSON.stringify(a),stack:"unknown"};a instanceof Error&&(i.name=a.name,i.message=a.message,i.stack=a.stack),r.comms.send({variant:"error",error:i})}}),r}handle(e){const{path:r,variant:n,type:a}=e;if(n==="delete"){this._delete(r);return}const{state:i}=e;this._updateState({path:r,type:a,state:i,create:o=>{const l=r[r.length-1];return this.create({key:l,type:a,parentCtxValues:o})}})}create({key:e,type:r,parentCtxValues:n}){const a=this.registry[r];if(a==null)throw new W(`[Root.create] - ${r} not found in registry`);return new a({key:e,type:r,sender:this.comms,instrumentation:this.instrumentation,parentCtxValues:n})}}const Sl=Re.render.bind(Re),qv=Object.freeze(Object.defineProperty({__proto__:null,Composite:wt,Leaf:_r,Root:Re,render:Sl},Symbol.toStringTag,{value:"Module"})),Zv=(t,e)=>Array.isArray(e)?e.some(r=>r.matches(t)):e?.matches(t)??!1,zl=(t,e,r)=>{const n=f.wr.fromException(t,e);return console.error(n),Zv(t,r)?null:n},El=(t,e,r,n)=>{if(typeof t=="function")return!0;const a=zl(t,r,n);return a!=null&&e(a),!1},Nl=async(t,e,r,n)=>{try{const a=t();a!=null&&await a}catch(a){const i=zl(a,r,n);if(i!=null)return e(i)}},Al=t=>(e,r,n)=>{El(e,t,r,n)&&Nl(e,t,r,n)},kl=t=>async(e,r,n)=>{El(e,t,r,n)&&await Nl(e,t,r,n)},xl=s.z.object({statuses:f.wr.statusZ().array()}),Ar="status.aggregator";class Gn extends wt{static TYPE="status.Aggregator";schema=xl;afterUpdate(e){e.wasSetPreviously(Ar)||e.set(Ar,{add:this.add.bind(this),create:f.wr.create})}add(e){this.setState(r=>({...r,statuses:[...r.statuses,f.wr.create(e)]}))}}const Wr=t=>t.get(Ar).add,Yv=t=>{const e=t.getOptional(Ar);return e!=null?e.add:()=>{}},Ms=t=>Al(Wr(t)),Vv=t=>kl(Wr(t)),Hv={[Gn.TYPE]:Gn},Kn="pluto-theming-context",Cl=s.z.object({name:s.z.string(),url:s.z.string()}),_v=s.z.object({theme:pl,fontURLs:s.z.array(Cl)});let Jn=class Il extends wt{static TYPE="theming.Provider";static z=_v;schema=Il.z;afterUpdate(e){if(e.getOptional(Kn)!=null&&this.state.theme.key===this.prevState.theme.key)return;e.set(Kn,this.state.theme),Ms(e)(async()=>{await this.loadFonts()},"failed to load theme fonts")}async loadFonts(){await Promise.all(this.state.fontURLs.map(async({name:e,url:r})=>{const n=new FontFace(e,`url(${r})`);try{await n.load(),self.fonts.add(n)}catch(a){console.error(a)}}))}};const Wv=t=>t.get(Kn),Gv={[Jn.TYPE]:Jn},jl=s.z.object({include:s.z.string().array().optional(),exclude:s.z.string().array().optional(),level:s.z.enum(je.LOG_LEVELS).optional().default("info")}),Xn="alamos-provider";class Qn extends wt{static TYPE="alamos.Provider";schema=jl;afterUpdate(e){if(e.getOptional(Xn)!=null)return;const n=[],{include:a,exclude:i,level:o}=this.state;(a!=null||i!=null)&&n.push(je.logLevelKeyFiler({include:a,exclude:i})),o!=null&&n.push(je.logThresholdFilter(o)),n.length===0&&n.push(()=>!1),this.internal.ins=new je.Instrumentation({key:"aether",logger:new je.Logger({filters:n})}),e.set(Xn,this.internal.ins)}}const Rl=(t,e)=>{const r=t.get(Xn);if(r==null)throw new Error("No instrumentation provider");return e==null?r:r.child(e)},Kv={[Qn.TYPE]:Qn},br=(t,e)=>f.Ho.construct(f.Ho.left(t)-e.x,f.Ho.top(t)-e.y,f.Ho.width(t)+e.x*2,f.Ho.height(t)+e.y*2);class kr{scale_;wrapped;atlasRegistry;cachedFont=null;cachedFillStyle=null;cachedStrokeStyle=null;cachedLineWidth=null;cachedGlobalAlpha=null;cachedTextAlign=null;cachedTextBaseline=null;cachedLineCap=null;cachedLineJoin=null;cachedMiterLimit=null;dpr;constructor(e,r,n,a=f.C.XY.IDENTITY){this.wrapped=e,this.scale_=a,this.atlasRegistry=r,this.dpr=n}get fontStretch(){return this.wrapped.fontStretch}set fontStretch(e){this.wrapped.fontStretch=e}get fontVariantCaps(){return this.wrapped.fontVariantCaps}set fontVariantCaps(e){this.wrapped.fontVariantCaps=e}isContextLost(){return this.wrapped.isContextLost()}get wordSpacing(){return this.wrapped.wordSpacing}set wordSpacing(e){this.wrapped.wordSpacing=e}get letterSpacing(){return this.wrapped.letterSpacing}set letterSpacing(e){this.wrapped.letterSpacing=e}get textRendering(){return this.wrapped.textRendering}set textRendering(e){this.wrapped.textRendering=e}checkAtlasFillStyle(e=!1){return e&&typeof this.fillStyle=="string"?[!0,this.fillStyle]:(e&&console.warn("attempted to use a text atlas with a gradient fill style. This is not supported. Falling back to default canvas fill."),[!1,null])}reset(){this.wrapped.reset()}applyScale(e){return new kr(this,this.atlasRegistry,this.dpr,e)}get canvas(){return this.wrapped.canvas}get miterLimit(){return this.cachedMiterLimit??this.wrapped.miterLimit}set miterLimit(e){const r=this.scale_.x.dim(e);r!==this.cachedMiterLimit&&(this.cachedMiterLimit=r,this.wrapped.miterLimit=r)}get globalAlpha(){return this.cachedGlobalAlpha??this.wrapped.globalAlpha}set globalAlpha(e){e!==this.cachedGlobalAlpha&&(this.cachedGlobalAlpha=e,this.wrapped.globalAlpha=e)}get globalCompositeOperation(){return this.wrapped.globalCompositeOperation}set globalCompositeOperation(e){this.wrapped.globalCompositeOperation=e}get fillStyle(){return this.cachedFillStyle??this.wrapped.fillStyle}set fillStyle(e){e!==this.cachedFillStyle&&(this.cachedFillStyle=e,this.wrapped.fillStyle=e)}get strokeStyle(){return this.cachedStrokeStyle??this.wrapped.strokeStyle}set strokeStyle(e){e!==this.cachedStrokeStyle&&(this.cachedStrokeStyle=e,this.wrapped.strokeStyle=e)}drawImage(e,r,n,a,i,o,l,c,u){this.wrapped.drawImage(e,r,n,a,i,o!=null?this.scale_.x.pos(o):o,l!=null?this.scale_.y.pos(l):l,c!=null?this.scale_.x.dim(c):c,u!=null?this.scale_.y.dim(u):u)}beginPath(){this.wrapped.beginPath()}clip(e,r){this.wrapped.clip(e,r)}fill(e,r){if(e==null)return this.wrapped.fill();this.wrapped.fill(e,r)}isPointInPath(e,r,n,a){return this.wrapped.isPointInPath(e,r,n,a)}isPointInStroke(e,r,n){return this.wrapped.isPointInStroke(e,r,n)}stroke(e){if(e==null)return this.wrapped.stroke();this.wrapped.stroke(e)}createConicGradient(e,r,n){return this.wrapped.createConicGradient(e,r,n)}createLinearGradient(e,r,n,a){return this.wrapped.createLinearGradient(e,r,n,a)}createPattern(e,r){return this.wrapped.createPattern(e,r)}createRadialGradient(e,r,n,a,i,o){return this.wrapped.createRadialGradient(e,r,n,a,i,o)}get filter(){return this.wrapped.filter}set filter(e){this.wrapped.filter=e}createImageData(e,r,n){return this.wrapped.createImageData(e,r,n)}getImageData(e,r,n,a,i){return this.wrapped.getImageData(e,r,n,a,i)}putImageData(e,r,n,a,i,o,l){this.wrapped.putImageData(e,r,n,a,i,o,l)}get imageSmoothingEnabled(){return this.wrapped.imageSmoothingEnabled}set imageSmoothingEnabled(e){this.wrapped.imageSmoothingEnabled=e}get imageSmoothingQuality(){return this.wrapped.imageSmoothingQuality}set imageSmoothingQuality(e){this.wrapped.imageSmoothingQuality=e}arc(e,r,n,a,i,o){this.wrapped.arc(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),a,i,o)}arcTo(e,r,n,a,i){this.wrapped.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,r,n,a,i,o){this.wrapped.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.wrapped.closePath()}ellipse(e,r,n,a,i,o,l,c){this.wrapped.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,r){this.wrapped.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}moveTo(e,r){this.wrapped.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}quadraticCurveTo(e,r,n,a){this.wrapped.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,r,n,a){this.wrapped.rect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,r,n,a,i){this.wrapped.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),typeof i=="number"?this.scale_.x.dim(i):i)}get lineCap(){return this.cachedLineCap??this.wrapped.lineCap}set lineCap(e){e!==this.cachedLineCap&&(this.cachedLineCap=e,this.wrapped.lineCap=e)}get lineDashOffset(){return this.wrapped.lineDashOffset}set lineDashOffset(e){this.wrapped.lineDashOffset=this.scale_.x.dim(e)}get lineJoin(){return this.cachedLineJoin??this.wrapped.lineJoin}set lineJoin(e){e!==this.cachedLineJoin&&(this.cachedLineJoin=e,this.wrapped.lineJoin=e)}get lineWidth(){return this.cachedLineWidth??this.wrapped.lineWidth}set lineWidth(e){const r=this.scale_.x.dim(e);r!==this.cachedLineWidth&&(this.cachedLineWidth=r,this.wrapped.lineWidth=r)}getLineDash(){return this.wrapped.getLineDash()}setLineDash(e){const r=Array.from(e).map(n=>this.scale_.x.dim(n));this.wrapped.setLineDash(r)}clearRect(e,r,n,a){this.wrapped.clearRect(e,r,n,a)}fillRect(e,r,n,a){this.wrapped.fillRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}strokeRect(e,r,n,a){this.wrapped.strokeRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}get shadowBlur(){return this.wrapped.shadowBlur}set shadowBlur(e){this.wrapped.shadowBlur=e}get shadowColor(){return this.wrapped.shadowColor}set shadowColor(e){this.wrapped.shadowColor=e}get shadowOffsetX(){return this.wrapped.shadowOffsetX}set shadowOffsetX(e){this.wrapped.shadowOffsetX=e}get shadowOffsetY(){return this.wrapped.shadowOffsetY}restore(){this.cachedFillStyle=null,this.cachedStrokeStyle=null,this.cachedLineWidth=null,this.cachedGlobalAlpha=null,this.cachedTextAlign=null,this.cachedTextBaseline=null,this.cachedLineCap=null,this.cachedLineJoin=null,this.cachedMiterLimit=null,this.cachedFont=null,this.wrapped.restore()}save(){this.wrapped.save()}fillText(e,r,n,a,i={}){const[o,l]=this.checkAtlasFillStyle(i.useAtlas);if(o){this.atlasRegistry.get({font:this.font,textColor:l}).fillText(this,e,r,n);return}this.wrapped.fillText(e,this.scale_.x.pos(r),this.scale_.y.pos(n),a!=null?this.scale_.x.dim(a):void 0)}measureText(e){return this.wrapped.measureText(e)}textDimensions(e,r={}){const[n,a]=this.checkAtlasFillStyle(r.useAtlas);return n?this.atlasRegistry.get({font:this.font,textColor:a}).measureText(e):Hr(this.measureText(e))}strokeText(e,r,n,a){this.wrapped.strokeText(e,this.scale_.x.pos(r),this.scale_.y.pos(n),a!=null?this.scale_.x.dim(a):void 0)}get direction(){return this.wrapped.direction}set direction(e){this.wrapped.direction=e}get font(){return this.cachedFont!=null?this.cachedFont:this.wrapped.font}set font(e){e!==this.cachedFont&&(this.cachedFont=e,this.wrapped.font=this.cachedFont)}get fontKerning(){return this.wrapped.fontKerning}set fontKerning(e){this.wrapped.fontKerning=e}get textAlign(){return this.cachedTextAlign??this.wrapped.textAlign}set textAlign(e){e!==this.cachedTextAlign&&(this.cachedTextAlign=e,this.wrapped.textAlign=e)}get textBaseline(){return this.cachedTextBaseline??this.wrapped.textBaseline}set textBaseline(e){e!==this.cachedTextBaseline&&(this.cachedTextBaseline=e,this.wrapped.textBaseline=e)}getTransform(){return this.wrapped.getTransform()}resetTransform(){this.wrapped.resetTransform()}rotate(e){this.wrapped.rotate(e)}scale(e,r){this.wrapped.scale(e,r),this.dpr=e}scissor(e,r=f.K.ZERO){const n=new Jv(this.scale_);return e=br(e,r),n.rect(...f.K.couple(f.Ho.topLeft(e)),...f._.couple(f.Ho.dims(e))),this.save(),this.clip(n.getPath()),()=>this.restore()}setTransform(e,r,n,a,i,o){this.wrapped.setTransform(e,r,n,a,i,o)}transform(e,r,n,a,i,o){this.wrapped.transform(e,r,n,a,i,o)}translate(e,r){this.wrapped.translate(e,r)}}class Jv{scale_;path;constructor(e=f.C.XY.IDENTITY,r){this.scale_=e,r instanceof Path2D||typeof r=="string"?this.path=new Path2D(r):this.path=new Path2D}addPath(e,r){this.path.addPath(e,r)}arc(e,r,n,a,i,o){this.path.arc(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),a,i,o)}arcTo(e,r,n,a,i){this.path.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,r,n,a,i,o){this.path.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.path.closePath()}ellipse(e,r,n,a,i,o,l,c){this.path.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,r){this.path.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}moveTo(e,r){this.path.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}quadraticCurveTo(e,r,n,a){this.path.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,r,n,a){this.path.rect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,r,n,a,i){const o=this.scaleRadii(i);this.path.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),o)}scaleRadii(e){return e==null?e:typeof e=="number"?this.scale_.x.dim(e):Array.isArray(e)?e.map(r=>this.scaleRadius(r)):this.scaleRadius(e)}scaleRadius(e){return typeof e=="number"?this.scale_.x.dim(e):{x:this.scale_.x.dim(e.x??0),y:this.scale_.y.dim(e.y??0)}}getPath(){return this.path}}const Xv=`precision mediump float;
54
+
55
+ void main(void) {
56
+ gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
57
+ }
58
+ `,Qv=`attribute vec4 a_position;
59
+
60
+ void main(void) {
61
+ gl_Position = a_position;
62
+ }
63
+ `,xa=t=>new Error(`failed to compile webgl program: ${t}`),eT=new Error("null shader encountered");let Ul=class{renderCtx;prog;vertShader;fragShader;uniformLocCache=new Map;constructor(e,r,n){this.renderCtx=e;const a=e.gl.createProgram();if(a==null)throw xa("failed to create program");this.prog=a,this.vertShader=r,this.fragShader=n,this.compile()}setAsActive(){return this.renderCtx.gl.useProgram(this.prog),()=>this.renderCtx.gl.useProgram(null)}uniformXY(e,r){this.renderCtx.gl.uniform2fv(this.getUniformLoc(e),f.K.couple(r))}uniformColor(e,r){this.renderCtx.gl.uniform4fv(this.getUniformLoc(e),f.cr.rgba1(r))}getUniformLoc(e){const r=this.uniformLocCache.get(e);if(r!=null)return r;const n=this.renderCtx.gl.getUniformLocation(this.prog,e);if(n==null)throw new Error(`unexpected missing uniform ${e}`);return this.uniformLocCache.set(e,n),n}compile(){const e=this.renderCtx.gl;this.compileShader(this.vertShader,e.VERTEX_SHADER),this.compileShader(this.fragShader,e.FRAGMENT_SHADER),e.linkProgram(this.prog)}compileShader(e,r){const n=this.renderCtx.gl,a=n.createShader(r);if(a==null)throw eT;if(n.shaderSource(a,e),n.compileShader(a),!n.getShaderParameter(a,n.COMPILE_STATUS)){const o=n.getShaderInfoLog(a);throw n.deleteShader(a),xa(o??"unknown")}n.attachShader(this.prog,a)}};const tT=new Float32Array([0,0,0,0,0,0]);class rT extends Ul{positionBuffer;constructor(e){super(e,Qv,Xv);const r=e.gl.createBuffer();if(r==null)throw new W("webgl: failed to create buffer");this.positionBuffer=r,e.gl.bindBuffer(e.gl.ARRAY_BUFFER,this.positionBuffer),e.gl.bufferData(e.gl.ARRAY_BUFFER,tT,e.gl.STATIC_DRAW)}exec(){const{gl:e}=this.renderCtx,r=e.getAttribLocation(this.prog,"a_position");e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer);const n=e.createVertexArray();e.bindVertexArray(n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),this.setAsActive(),e.drawArrays(e.TRIANGLES,0,3)}}const Ca={high:1,low:0};class Ml{requests=new Map;cleanup=new Map;afterRender;instrumentation;handleError;constructor({afterRender:e,instrumentation:r=je.Instrumentation.NOOP,handleError:n}){this.afterRender=e,this.instrumentation=r,this.handleError=n,this.start()}set(e){const r=this.requests.get(e.key);if(r==null)this.requests.set(e.key,e);else{const n=Ca[e.priority]>=Ca[r.priority],a=e.canvases.length>=r.canvases.length;n&&a&&this.requests.set(e.key,e)}}render(){const{requests:e}=this;e.size!==0&&(this.runCleanupsSync(),this.renderSync(),this.requests.clear(),this.afterRender?.())}runCleanupsSync(){const{cleanup:e,requests:r}=this;e.forEach((n,a)=>{const i=r.get(a);i!=null&&(n(i),e.delete(a))})}renderSync(){const{requests:e}=this;e.forEach(r=>{try{const n=r.render();n!=null&&this.cleanup.set(r.key,n)}catch(n){this.handleError(n,"render loop failed")}})}start(){const e=()=>{try{this.render()}catch(r){this.handleError(r,"render loop failed")}requestAnimationFrame(e)};requestAnimationFrame(e)}}const dr=2,me=2;class Ls{atlas;charDims;charMap;static DEFAULT_CHARS="0123456789.:-µmsNa∞ᴇ";constructor(e){const{font:r,characters:n=Ls.DEFAULT_CHARS,textColor:a}=e;this.charMap=new Map;const i=f.c.unique(Array.from(n)),l=new OffscreenCanvas(1,1).getContext("2d");l.font=r;const c=l.measureText("0");this.charDims=Hr(c),this.charDims.width+=dr,this.charDims.height+=dr;const u=i.length,h=this.charDims.width,p=this.charDims.height,d=Math.ceil(Math.sqrt(u)),S=Math.ceil(u/d);this.atlas=new OffscreenCanvas(h*d*me,p*(S+1)*me);const N=this.atlas.getContext("2d");N.scale(me,me),N.font=r,N.textBaseline="alphabetic",N.textAlign="left",N.fillStyle=f.cr.hex(a),N.clearRect(0,0,this.atlas.width,this.atlas.height),i.forEach((x,B)=>{const C=B%d,L=Math.floor(B/d),se=C*h,te=(L+1)*p;N.fillText(x,se,te),this.charMap.set(x,B)})}fillText(e,r,n,a){const{width:i,height:o}=this.charDims,l=Math.ceil(Math.sqrt(this.charMap.size));for(let c=0;c<r.length;c++){const u=r[c],h=this.charMap.get(u);if(h===void 0)continue;const p=h%l,d=Math.floor(h/l);e.drawImage(this.atlas,p*i*me,d*o*me+dr,i*me,o*me,n+c*i,a-o-dr/me,i,o)}}measureText(e){return{width:e.length*this.charDims.width,height:this.charDims.height}}}class nT{atlases;constructor(){this.atlases=new Map}get(e){const r=`${e.font}-${f.cr.hex(e.textColor)}-${e.characters}`;if(this.atlases.has(r))return this.atlases.get(r);const n=new Ls(e);return this.atlases.set(r,n),n}}const Ia=t=>(t.textRendering="optimizeSpeed",t.imageSmoothingEnabled=!1,t);class Ce{glCanvas;upper2dCanvas;lower2dCanvas;gl;lower2d;upper2d;region;dpr;loop;clearProgram;os;static CONTEXT_KEY=f.CSS.B("render-context");instrumentation;static create(e,r,n,a,i){const o=Rl(e,"render_context"),l=new Ce(r,n,a,i,o,Wr(e),Ms(e));return e.set(Ce.CONTEXT_KEY,l),l}constructor(e,r,n,a,i,o,l){this.upper2dCanvas=n,this.lower2dCanvas=r,this.glCanvas=e,this.os=a,this.instrumentation=i,this.dpr=1;const c=this.lower2dCanvas.getContext("2d");if(c==null)throw new Error("Could not get 2D context");const u=new nT;this.lower2d=Ia(new kr(c,u,this.dpr));const h=this.upper2dCanvas.getContext("2d");if(h==null)throw new Error("Could not get 2D context");this.upper2d=Ia(new kr(h,u,this.dpr));const p={preserveDrawingBuffer:!0,powerPreference:"high-performance",stencil:!1,depth:!1},d=this.glCanvas.getContext("webgl2",p);if(d==null)throw new Error("Could not get WebGL context");d.disable(d.DEPTH_TEST),d.disable(d.STENCIL_TEST),d.disable(d.CULL_FACE),d.disable(d.DITHER),this.gl=d,this.glCanvas.oncontextlost=()=>o({variant:"error",message:"WebGL context lost"});const S=()=>{this.gl.flush(),this.gl.finish()};this.loop=new Ml({afterRender:S,instrumentation:this.instrumentation,handleError:l}),this.region=f.Ho.ZERO,this.os==="Windows"&&(this.clearProgram=new rT(this))}static useOptional(e){return e.getOptional(Ce.CONTEXT_KEY)}static use(e){return e.get(Ce.CONTEXT_KEY)}update(e){e.set(Ce.CONTEXT_KEY,this)}resize(e,r){f.Ho.equals(this.region,e)&&this.dpr===r||(this.region=e,this.dpr=r,this.resizeCanvas(this.glCanvas),this.resizeCanvas(this.upper2dCanvas),this.resizeCanvas(this.lower2dCanvas),this.lower2d.scale(this.dpr,this.dpr),this.upper2d.scale(this.dpr,this.dpr),this.gl.viewport(0,0,f.Ho.width(e)*r,f.Ho.height(e)*r))}resizeCanvas(e){e.width=f.Ho.width(this.region)*this.dpr,e.height=f.Ho.height(this.region)*this.dpr}get aspect(){return f.Ho.aspect(this.region)}scaleRegion(e){return new f.C.XY(f.C.Scale.scale(0,1).scale(f.Ho.width(e)).translate(f.Ho.left(e)).reBound(f.Ho.width(this.region)).scale(-1,1),f.C.Scale.scale(0,1).scale(f.Ho.height(e)).invert().translate(f.Ho.top(e)).reBound(f.Ho.height(this.region)).scale(-1,1).invert())}scissor(e,r=f.K.ZERO,n){const a=[];return n.includes("upper2d")&&a.push(this.upper2d.scissor(e,r)),n.includes("lower2d")&&a.push(this.lower2d.scissor(e,r)),n.includes("gl")&&a.push(this.scissorGL(e,r)),()=>a.forEach(i=>i())}scissorGL(e,r=f.K.ZERO){return this.gl.enable(this.gl.SCISSOR_TEST),e=br(e,r),this.gl.scissor(f.Ho.left(e)*this.dpr,(f.Ho.height(this.region)-f.Ho.bottom(e))*this.dpr,f.Ho.width(e)*this.dpr,f.Ho.height(e)*this.dpr),()=>this.gl.disable(this.gl.SCISSOR_TEST)}erase(e,r=f.K.ZERO,...n){r=f.K.construct(r),n.length===0&&(n=["upper2d","lower2d","gl"]),n.includes("upper2d")&&this.eraseCanvas(this.upper2d,e,r),n.includes("lower2d")&&this.eraseCanvas(this.lower2d,e,r),n.includes("gl")&&this.eraseGL(e,r)}eraseGL(e,r=f.K.ZERO){const{gl:n}=this,a=this.scissorGL(br(e,r));n.clearColor(...f.cr.rgba1(f.cr.ZERO)),n.clear(n.COLOR_BUFFER_BIT),this.os==="Windows"&&this.clearProgram?.exec(),a()}eraseCanvas(e,r,n=f.K.ZERO){const a=br(r,n);e.clearRect(...f.K.couple(f.Ho.topLeft(a)),...f._.couple(f.Ho.dims(a)))}}const Ll=s.z.object({region:f.Ho.box,enabled:s.z.boolean().optional().default(!1)}),ja=["gl","lower2d","upper2d"];class es extends _r{static TYPE="eraser";schema=Ll;afterUpdate(e){this.deleted||(this.internal.renderCtx=Ce.use(e),this.renderOnLifecycleChange())}afterDelete(){this.renderOnLifecycleChange()}renderOnLifecycleChange(){this.internal.renderCtx.loop.set({key:`${this.type}-${this.key}`,render:this.render.bind(this),priority:"high",canvases:ja})}render(){this.deleted||!this.state.enabled||this.internal.renderCtx.erase(this.state.region,f.K.construct(0),...ja)}}const sT={[es.TYPE]:es};exports.Aggregator=Gn;exports.COMPONENT_SIZE_LEVELS=Yb;exports.Composite=wt;exports.Context=Ce;exports.Eraser=es;exports.GLProgram=Ul;exports.Iw=mb;exports.L=$;exports.LEVELS=Ct;exports.LEVEL_COMPONENT_SIZES=Vb;exports.Leaf=_r;exports.Lm=wf;exports.Loop=Ml;exports.N=cl;exports.O=ut;exports.O$1=z;exports.Provider=Jn;exports.Provider$1=Qn;exports.REGISTRY=Gv;exports.REGISTRY$1=Hv;exports.REGISTRY$2=sT;exports.REGISTRY$3=Kv;exports.S=E;exports.SIZES=ml;exports.SYNNAX_DARK=gl;exports.SYNNAX_LIGHT=yl;exports.SYNNAX_THEMES=tv;exports.Tm=il;exports.Ue=Le;exports.Vm=Jf;exports.Xm=Pp;exports._=ct;exports._t=it;exports.aether=qv;exports.aggregatorStateZ=xl;exports.be=bl;exports.c=Cs;exports.createAsyncErrorHandler=kl;exports.createErrorHandler=Al;exports.d=Ub;exports.dimensions=$b;exports.dimensionsFromMetrics=Hr;exports.downLevel=qb;exports.dw=Ag;exports.eraserStateZ=Ll;exports.executeInitialSetter=nr;exports.executeSetter=Is;exports.fontSpecZ=Cl;exports.g=je;exports.ht=W;exports.isSize=rv;exports.iw=_y;exports.k=k;exports.levelZ=Fb;exports.o=Tb;exports.p=ol;exports.prettyParse=Yn;exports.providerStateZ=jl;exports.pw=dm;exports.r=Ob;exports.render=Sl;exports.size=wl;exports.specZ=xe;exports.state=Db;exports.sw=Fy;exports.t=vb;exports.themeZ=pl;exports.use=Wv;exports.useAdder=Wr;exports.useAsyncErrorHandler=Vv;exports.useErrorHandler=Ms;exports.useInstrumentation=Rl;exports.useOptionalAdder=Yv;exports.usePassthrough=dl;exports.usePurePassthrough=fl;exports.uw=ug;exports.vm=wb;exports.weightZ=Zb;exports.ww=Jm;exports.yw=Wg;