@synnaxlabs/pluto 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/dist/{Animated-ByIJT_wA.js → Animated-CBm9-vEt.js} +3 -3
  2. package/dist/{Animated-BOjwPkTJ.cjs → Animated-Cv0kRBvj.cjs} +1 -1
  3. package/dist/{Item-Bamd13Tl.cjs → Item-D4eTqW7p.cjs} +1 -1
  4. package/dist/{Item-CQ2ZuDfi.js → Item-DfHOrsI4.js} +9 -9
  5. package/dist/{LinePlot-Ci-61YDW.js → LinePlot-BLovx_K1.js} +1779 -1706
  6. package/dist/LinePlot-BXBKDBXS.cjs +56 -0
  7. package/dist/{Link-Cm6yn4zC.cjs → Link-CcELhLK5.cjs} +1 -1
  8. package/dist/{Link-ZlOdu4jA.js → Link-DsUveQ8_.js} +2 -2
  9. package/dist/Pack-SDIuOEWr.cjs +1 -0
  10. package/dist/Pack-meMPpnLE.js +143 -0
  11. package/dist/Toggle--8qqNnzb.cjs +163 -0
  12. package/dist/{Toggle-DlYB4nmh.js → Toggle-Bkpw4raJ.js} +15326 -15675
  13. package/dist/Video-D9_mAnaf.cjs +1 -0
  14. package/dist/Video-M2UhBzQi.js +9 -0
  15. package/dist/{aggregator-CWsCIyed.js → aggregator-BpyoaCoW.js} +2941 -2922
  16. package/dist/aggregator-By11htYo.cjs +77 -0
  17. package/dist/align.cjs +1 -1
  18. package/dist/align.js +1 -1
  19. package/dist/button.cjs +1 -1
  20. package/dist/button.js +1 -1
  21. package/dist/color.cjs +1 -1
  22. package/dist/color.js +1 -1
  23. package/dist/{css-Bo-hsQHb.cjs → css-CRd0zXr-.cjs} +1 -1
  24. package/dist/{css-Csw1Dn4s.js → css-CxwKC6TD.js} +216 -216
  25. package/dist/css.cjs +1 -1
  26. package/dist/css.js +2 -2
  27. package/dist/dropdown.cjs +1 -1
  28. package/dist/dropdown.js +1 -1
  29. package/dist/ether.cjs +1 -1
  30. package/dist/ether.js +58 -56
  31. package/dist/{external-DsJYjdNk.cjs → external---lrKeGh.cjs} +1 -1
  32. package/dist/{external-CyPQsB1T.cjs → external--jF6DCow.cjs} +1 -1
  33. package/dist/{external-DXD4PtTK.js → external-BDI5gGZT.js} +2 -2
  34. package/dist/external-BDxOWeCJ.js +34 -0
  35. package/dist/{external-2PznkZYs.js → external-BOqGZoJO.js} +113 -112
  36. package/dist/external-BXEbAbxf.cjs +1 -0
  37. package/dist/external-BdhgaSFj.cjs +1 -0
  38. package/dist/external-BlB1LKU5.cjs +1 -0
  39. package/dist/external-ByzAGKGm.cjs +1 -0
  40. package/dist/{external-BTnFzhMM.js → external-BzzIJ4wP.js} +4 -5
  41. package/dist/external-CDa3lybi.js +277 -0
  42. package/dist/{external-4ikhWnyq.js → external-CEAUuDRU.js} +2 -2
  43. package/dist/{external-vYsKqfFS.js → external-Cc7R9gIf.js} +186 -187
  44. package/dist/{external-BpeQ9rNJ.js → external-CqOmm0mk.js} +88 -88
  45. package/dist/{external-DIwKYTmY.js → external-CsLjI7EJ.js} +2 -2
  46. package/dist/{external-C_th4MW9.cjs → external-DN8Ec8n8.cjs} +1 -1
  47. package/dist/{external-CyYaJ5TW.js → external-DSHJn336.js} +5 -5
  48. package/dist/{external-vMTeF1dc.cjs → external-DaTbvfth.cjs} +1 -1
  49. package/dist/external-Dqh2Lbnl.cjs +1 -0
  50. package/dist/{external-VEFOprRU.cjs → external-Dvj3Y4C_.cjs} +1 -1
  51. package/dist/external-NDebmx0l.js +123 -0
  52. package/dist/external-biLn9KfP.cjs +1 -0
  53. package/dist/{external-rGv5AzBK.js → external-hZWRSBEb.js} +14 -14
  54. package/dist/external-mT9bNf0F.cjs +1 -0
  55. package/dist/header.cjs +1 -1
  56. package/dist/header.js +1 -1
  57. package/dist/index.cjs +13 -13
  58. package/dist/index.js +6746 -6604
  59. package/dist/input.cjs +1 -1
  60. package/dist/input.js +1 -1
  61. package/dist/{jsx-runtime-Dx-03ztt.js → jsx-runtime-Bdg6XQ1m.js} +134 -134
  62. package/dist/jsx-runtime-D8EVjfnb.cjs +31 -0
  63. package/dist/list.cjs +1 -1
  64. package/dist/list.js +1 -1
  65. package/dist/menu.cjs +1 -1
  66. package/dist/menu.js +1 -1
  67. package/dist/pluto.css +1 -1
  68. package/dist/src/aether/aether/index.d.ts +1 -2
  69. package/dist/src/aether/aether/index.d.ts.map +1 -1
  70. package/dist/src/aether/main.d.ts +18 -19
  71. package/dist/src/aether/main.d.ts.map +1 -1
  72. package/dist/src/alamos/Provider.d.ts +2 -4
  73. package/dist/src/alamos/Provider.d.ts.map +1 -1
  74. package/dist/src/align/Center.d.ts +2 -3
  75. package/dist/src/align/Center.d.ts.map +1 -1
  76. package/dist/src/align/Pack.d.ts +1 -2
  77. package/dist/src/align/Pack.d.ts.map +1 -1
  78. package/dist/src/align/Space.d.ts +1 -1
  79. package/dist/src/align/Space.d.ts.map +1 -1
  80. package/dist/src/breadcrumb/Breadcrumb.d.ts.map +1 -1
  81. package/dist/src/button/Button.d.ts +4 -4
  82. package/dist/src/button/Button.d.ts.map +1 -1
  83. package/dist/src/button/Icon.d.ts +2 -2
  84. package/dist/src/button/Icon.d.ts.map +1 -1
  85. package/dist/src/button/Toggle.d.ts +3 -3
  86. package/dist/src/button/Toggle.d.ts.map +1 -1
  87. package/dist/src/channel/LinePlot.d.ts.map +1 -1
  88. package/dist/src/channel/Select.d.ts +2 -0
  89. package/dist/src/channel/Select.d.ts.map +1 -1
  90. package/dist/src/color/core/external.d.ts +1 -0
  91. package/dist/src/color/core/external.d.ts.map +1 -1
  92. package/dist/src/color/core/transformColorsToHex.d.ts +6 -0
  93. package/dist/src/color/core/transformColorsToHex.d.ts.map +1 -0
  94. package/dist/src/color/external.d.ts +1 -0
  95. package/dist/src/color/external.d.ts.map +1 -1
  96. package/dist/src/divider/index.d.ts +1 -2
  97. package/dist/src/divider/index.d.ts.map +1 -1
  98. package/dist/src/dropdown/index.d.ts +1 -2
  99. package/dist/src/dropdown/index.d.ts.map +1 -1
  100. package/dist/src/form/Field.d.ts +6 -6
  101. package/dist/src/form/Field.d.ts.map +1 -1
  102. package/dist/src/form/synced.d.ts.map +1 -1
  103. package/dist/src/generic/Generic.d.ts +1 -1
  104. package/dist/src/generic/Generic.d.ts.map +1 -1
  105. package/dist/src/hardware/device/Select.d.ts.map +1 -1
  106. package/dist/src/haul/Haul.d.ts +3 -3
  107. package/dist/src/haul/Haul.d.ts.map +1 -1
  108. package/dist/src/hooks/ref.d.ts +5 -5
  109. package/dist/src/hooks/ref.d.ts.map +1 -1
  110. package/dist/src/hooks/useCursorDrag/useVirtualCursorDragWebKit.d.ts.map +1 -1
  111. package/dist/src/index.d.ts +2 -3
  112. package/dist/src/index.d.ts.map +1 -1
  113. package/dist/src/input/Date.d.ts +2 -1
  114. package/dist/src/input/Date.d.ts.map +1 -1
  115. package/dist/src/input/Numeric.d.ts +2 -1
  116. package/dist/src/input/Numeric.d.ts.map +1 -1
  117. package/dist/src/input/Switch.d.ts +2 -1
  118. package/dist/src/input/Switch.d.ts.map +1 -1
  119. package/dist/src/input/Text.d.ts +2 -1
  120. package/dist/src/input/Text.d.ts.map +1 -1
  121. package/dist/src/input/TextArea.d.ts +3 -3
  122. package/dist/src/input/TextArea.d.ts.map +1 -1
  123. package/dist/src/input/Time.d.ts +1 -1
  124. package/dist/src/input/Time.d.ts.map +1 -1
  125. package/dist/src/input/types.d.ts +2 -2
  126. package/dist/src/input/types.d.ts.map +1 -1
  127. package/dist/src/label/Select.d.ts.map +1 -1
  128. package/dist/src/list/Hover.d.ts.map +1 -1
  129. package/dist/src/list/Selector.d.ts.map +1 -1
  130. package/dist/src/menu/ContextMenu.d.ts +2 -2
  131. package/dist/src/menu/ContextMenu.d.ts.map +1 -1
  132. package/dist/src/mosaic/Mosaic.d.ts +2 -5
  133. package/dist/src/mosaic/Mosaic.d.ts.map +1 -1
  134. package/dist/src/nav/Drawer.d.ts +1 -3
  135. package/dist/src/nav/Drawer.d.ts.map +1 -1
  136. package/dist/src/os/Controls/index.d.ts +2 -3
  137. package/dist/src/os/Controls/index.d.ts.map +1 -1
  138. package/dist/src/ranger/SelectLabel.d.ts.map +1 -1
  139. package/dist/src/resize/Core.d.ts +2 -2
  140. package/dist/src/resize/Core.d.ts.map +1 -1
  141. package/dist/src/resize/Multiple.d.ts +1 -1
  142. package/dist/src/resize/Multiple.d.ts.map +1 -1
  143. package/dist/src/select/Alignment.d.ts.map +1 -1
  144. package/dist/src/select/ComponentSize.d.ts +1 -1
  145. package/dist/src/select/ComponentSize.d.ts.map +1 -1
  146. package/dist/src/select/Multiple.d.ts +13 -12
  147. package/dist/src/select/Multiple.d.ts.map +1 -1
  148. package/dist/src/select/Select.spec.d.ts.map +1 -1
  149. package/dist/src/select/Single.d.ts +2 -2
  150. package/dist/src/select/Single.d.ts.map +1 -1
  151. package/dist/src/select/external.d.ts +1 -1
  152. package/dist/src/select/external.d.ts.map +1 -1
  153. package/dist/src/status/Aggregator.d.ts +6 -4
  154. package/dist/src/status/Aggregator.d.ts.map +1 -1
  155. package/dist/src/synnax/Provider.d.ts +2 -4
  156. package/dist/src/synnax/Provider.d.ts.map +1 -1
  157. package/dist/src/table/Table.d.ts +4 -6
  158. package/dist/src/table/Table.d.ts.map +1 -1
  159. package/dist/src/table/cells/Cells.d.ts +4 -4
  160. package/dist/src/tabs/Selector.d.ts.map +1 -1
  161. package/dist/src/telem/Provider.d.ts +2 -4
  162. package/dist/src/telem/Provider.d.ts.map +1 -1
  163. package/dist/src/telem/aether/convertSeries.d.ts +20 -6
  164. package/dist/src/telem/aether/convertSeries.d.ts.map +1 -1
  165. package/dist/src/telem/aether/pipeline.d.ts +16 -16
  166. package/dist/src/telem/aether/remote.d.ts.map +1 -1
  167. package/dist/src/telem/aether/telem.d.ts +30 -30
  168. package/dist/src/telem/client/cache/dynamic.d.ts.map +1 -1
  169. package/dist/src/telem/client/cache/index.d.ts +1 -2
  170. package/dist/src/telem/client/cache/index.d.ts.map +1 -1
  171. package/dist/src/telem/client/cache/static.d.ts.map +1 -1
  172. package/dist/src/telem/control/Chip.d.ts +2 -3
  173. package/dist/src/telem/control/Chip.d.ts.map +1 -1
  174. package/dist/src/telem/control/Controller.d.ts +2 -4
  175. package/dist/src/telem/control/Controller.d.ts.map +1 -1
  176. package/dist/src/telem/control/Indicator.d.ts +2 -4
  177. package/dist/src/telem/control/Indicator.d.ts.map +1 -1
  178. package/dist/src/telem/control/Legend.d.ts +2 -3
  179. package/dist/src/telem/control/Legend.d.ts.map +1 -1
  180. package/dist/src/telem/control/StateProvider.d.ts +2 -4
  181. package/dist/src/telem/control/StateProvider.d.ts.map +1 -1
  182. package/dist/src/telem/control/aether/chip.d.ts +16 -16
  183. package/dist/src/telem/control/aether/controller.d.ts.map +1 -1
  184. package/dist/src/telem/control/aether/indicator.d.ts +16 -16
  185. package/dist/src/telem/control/aether/state.d.ts.map +1 -1
  186. package/dist/src/text/DateTime.d.ts +3 -6
  187. package/dist/src/text/DateTime.d.ts.map +1 -1
  188. package/dist/src/text/Editable.d.ts.map +1 -1
  189. package/dist/src/text/Link.d.ts +3 -5
  190. package/dist/src/text/Link.d.ts.map +1 -1
  191. package/dist/src/text/Text.d.ts +1 -1
  192. package/dist/src/text/Text.d.ts.map +1 -1
  193. package/dist/src/theming/Provider.d.ts +1 -3
  194. package/dist/src/theming/Provider.d.ts.map +1 -1
  195. package/dist/src/theming/aether/index.d.ts +1 -2
  196. package/dist/src/theming/aether/index.d.ts.map +1 -1
  197. package/dist/src/theming/aether/provider.d.ts +315 -315
  198. package/dist/src/theming/core/theme.d.ts +116 -116
  199. package/dist/src/theming/core/theme.d.ts.map +1 -1
  200. package/dist/src/tooltip/wrap.d.ts +2 -2
  201. package/dist/src/tooltip/wrap.d.ts.map +1 -1
  202. package/dist/src/tree/Tree.d.ts +1 -1
  203. package/dist/src/tree/Tree.d.ts.map +1 -1
  204. package/dist/src/tree/core.d.ts.map +1 -1
  205. package/dist/src/triggers/Provider.d.ts.map +1 -1
  206. package/dist/src/triggers/hooks.d.ts +2 -2
  207. package/dist/src/triggers/hooks.d.ts.map +1 -1
  208. package/dist/src/util/removeProps.d.ts.map +1 -1
  209. package/dist/src/video/Video.d.ts +2 -2
  210. package/dist/src/video/Video.d.ts.map +1 -1
  211. package/dist/src/viewport/Mask.d.ts +2 -1
  212. package/dist/src/viewport/Mask.d.ts.map +1 -1
  213. package/dist/src/viewport/use.d.ts +3 -3
  214. package/dist/src/viewport/use.d.ts.map +1 -1
  215. package/dist/src/vis/button/aether/button.d.ts +8 -8
  216. package/dist/src/vis/canvas/Canvas.d.ts +2 -4
  217. package/dist/src/vis/canvas/Canvas.d.ts.map +1 -1
  218. package/dist/src/vis/diagram/Diagram.d.ts +2 -1
  219. package/dist/src/vis/diagram/Diagram.d.ts.map +1 -1
  220. package/dist/src/vis/diagram/aether/Diagram.d.ts.map +1 -1
  221. package/dist/src/vis/diagram/edge/paths.d.ts.map +1 -1
  222. package/dist/src/vis/eraser/use.d.ts +5 -6
  223. package/dist/src/vis/eraser/use.d.ts.map +1 -1
  224. package/dist/src/vis/light/aether/light.d.ts +8 -8
  225. package/dist/src/vis/line/Line.d.ts +4 -4
  226. package/dist/src/vis/line/Line.d.ts.map +1 -1
  227. package/dist/src/vis/line/aether/line.d.ts +24 -16
  228. package/dist/src/vis/line/aether/line.d.ts.map +1 -1
  229. package/dist/src/vis/lineplot/Axis.d.ts +2 -1
  230. package/dist/src/vis/lineplot/Axis.d.ts.map +1 -1
  231. package/dist/src/vis/lineplot/Legend.d.ts +1 -1
  232. package/dist/src/vis/lineplot/Legend.d.ts.map +1 -1
  233. package/dist/src/vis/lineplot/Line.d.ts +4 -4
  234. package/dist/src/vis/lineplot/Line.d.ts.map +1 -1
  235. package/dist/src/vis/lineplot/LinePlot.d.ts +4 -5
  236. package/dist/src/vis/lineplot/LinePlot.d.ts.map +1 -1
  237. package/dist/src/vis/lineplot/Title.d.ts.map +1 -1
  238. package/dist/src/vis/lineplot/Viewport.d.ts +2 -2
  239. package/dist/src/vis/lineplot/Viewport.d.ts.map +1 -1
  240. package/dist/src/vis/lineplot/aether/LinePlot.d.ts.map +1 -1
  241. package/dist/src/vis/lineplot/aether/axis.d.ts.map +1 -1
  242. package/dist/src/vis/lineplot/aether/index.d.ts +1 -2
  243. package/dist/src/vis/lineplot/aether/index.d.ts.map +1 -1
  244. package/dist/src/vis/lineplot/range/Annotation.d.ts +3 -4
  245. package/dist/src/vis/lineplot/range/Annotation.d.ts.map +1 -1
  246. package/dist/src/vis/lineplot/range/Provider.d.ts +4 -4
  247. package/dist/src/vis/lineplot/range/Provider.d.ts.map +1 -1
  248. package/dist/src/vis/lineplot/range/aether/annotation.d.ts.map +1 -1
  249. package/dist/src/vis/lineplot/tooltip/Tooltip.d.ts +4 -4
  250. package/dist/src/vis/lineplot/tooltip/Tooltip.d.ts.map +1 -1
  251. package/dist/src/vis/log/Log.d.ts +3 -4
  252. package/dist/src/vis/log/Log.d.ts.map +1 -1
  253. package/dist/src/vis/log/aether/Log.d.ts +12 -12
  254. package/dist/src/vis/measure/Measure.d.ts +4 -4
  255. package/dist/src/vis/measure/Measure.d.ts.map +1 -1
  256. package/dist/src/vis/measure/aether/measure.d.ts.map +1 -1
  257. package/dist/src/vis/rule/Rule.d.ts +4 -4
  258. package/dist/src/vis/rule/Rule.d.ts.map +1 -1
  259. package/dist/src/vis/rule/aether/aether.d.ts +1 -1
  260. package/dist/src/vis/rule/aether/aether.d.ts.map +1 -1
  261. package/dist/src/vis/schematic/Symbols.d.ts.map +1 -1
  262. package/dist/src/vis/schematic/primitives/Primitives.d.ts.map +1 -1
  263. package/dist/src/vis/setpoint/aether/setpoint.d.ts +16 -16
  264. package/dist/src/vis/toggle/aether/toggle.d.ts +16 -16
  265. package/dist/src/vis/value/aether/value.d.ts +24 -24
  266. package/dist/src/vis/value/use.d.ts +8 -8
  267. package/dist/tabs.cjs +1 -1
  268. package/dist/tabs.js +1 -1
  269. package/dist/text.cjs +1 -1
  270. package/dist/text.js +2 -2
  271. package/dist/theming.cjs +1 -1
  272. package/dist/theming.js +2 -2
  273. package/dist/transformColorsToHex-1p-bBtDw.cjs +1 -0
  274. package/dist/transformColorsToHex-CjnZ3Lo3.js +14 -0
  275. package/dist/tree.cjs +1 -1
  276. package/dist/tree.js +1 -1
  277. package/dist/triggers.cjs +1 -1
  278. package/dist/triggers.js +1 -1
  279. package/dist/{units-CJ76Jzvw.js → units-Bz3KAVba.js} +1 -1
  280. package/dist/{units-CXFC0OLO.cjs → units-Cq6pBqSd.cjs} +1 -1
  281. package/dist/video.cjs +1 -1
  282. package/dist/video.js +1 -1
  283. package/package.json +13 -15
  284. package/dist/LinePlot-D4V1ltNT.cjs +0 -24
  285. package/dist/Pack-CyaEXvnu.cjs +0 -1
  286. package/dist/Pack-DNCFnyuR.js +0 -140
  287. package/dist/Toggle-vgmhy8wZ.cjs +0 -163
  288. package/dist/Video-g30B90s-.cjs +0 -1
  289. package/dist/Video-jaT7Y97L.js +0 -14
  290. package/dist/aggregator-DX8ts24k.cjs +0 -77
  291. package/dist/external-BS9Bfsj3.cjs +0 -1
  292. package/dist/external-Bt_kX5KM.cjs +0 -1
  293. package/dist/external-CEcxrva2.js +0 -254
  294. package/dist/external-CMEDU76u.cjs +0 -1
  295. package/dist/external-CWincA61.cjs +0 -1
  296. package/dist/external-Dn4tpDVi.js +0 -32
  297. package/dist/external-Dtr4ZxR6.cjs +0 -1
  298. package/dist/external-IztUjYjX.cjs +0 -1
  299. package/dist/external-WZW4OBZx.js +0 -91
  300. package/dist/external-kAduhcvp.cjs +0 -1
  301. package/dist/jsx-runtime-DGh1k5sI.cjs +0 -31
@@ -1,77 +0,0 @@
1
- "use strict";var Rc=Object.defineProperty;var $c=(r,e,t)=>e in r?Rc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var T=(r,e,t)=>$c(r,typeof e!="symbol"?e+"":e,t);const i=require("zod"),p=require("./css-Bo-hsQHb.cjs"),qn=require("react"),Gt=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Mc=Object.defineProperty,Dc=(r,e,t)=>e in r?Mc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Vt=(r,e,t)=>Dc(r,typeof e!="symbol"?e+"":e,t);let Bc=class{constructor(){Vt(this,"contentType","application/json"),Vt(this,"decoder"),Vt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const s=JSON.parse(e),n=p.C(s);return t!=null?t.parse(n):n}encodeString(e){const t=p.k(e);return JSON.stringify(t,(s,n)=>ArrayBuffer.isView(n)?Array.from(n):Gt(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},jc=class{constructor(){Vt(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const s=new TextDecoder().decode(e);return this.decodeString(s,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Gt(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),s=[t.join(",")];return e.forEach(n=>{const a=t.map(o=>JSON.stringify(n[o]??""));s.push(a.join(","))}),s.join(`
2
- `)}decodeString(e,t){const[s,...n]=e.trim().split(`
3
- `).map(c=>c.trim());if(s.length===0)return t!=null?t.parse({}):{};const a=s.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),n.forEach(c=>{const l=c.split(",").map(d=>d.trim());a.forEach((d,f)=>{const h=this.parseValue(l[f]);h!=null&&o[d].push(h)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},Pc=class{constructor(){Vt(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const s=new TextDecoder().decode(e);return t!=null?t.parse(s):s}};const zr=new Bc;new jc;new Pc;const dn=r=>[...new Set(r)],_a=r=>r!=null&&typeof r=="object"&&"toString"in r,Uc=r=>{if(_a(r))return(r==null?void 0:r.toString().length)===0;switch(typeof r){case"string":return r.length===0;case"number":return r===0;case"bigint":return r===0n;case"boolean":return!r;case"undefined":return!0;case"object":return r===null}},gs=(r,e=!1)=>{const t=_a(r)?"stringer":typeof r;let s;switch(t){case"string":s=(n,a)=>n.localeCompare(a);break;case"stringer":s=(n,a)=>n.toString().localeCompare(a.toString());break;case"number":s=(n,a)=>Number(n)-Number(a);break;case"bigint":s=(n,a)=>BigInt(n)-BigInt(a)>0n?1:-1;break;case"boolean":s=(n,a)=>Number(n)-Number(a);break;case"undefined":s=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Fa(s):s},Lc=(r,e,t)=>{const s=gs(e[r],t);return(n,a)=>s(n[r],a[r])},_c=(r,e)=>r.length!==e.length?r.length-e.length:r.every((t,s)=>t===e[s])?0:-1,Ya=(r,e)=>{if(r.length!==e.length)return r.length-e.length;if(r.length===0)return 0;const t=gs(r[0]),s=[...r].sort(t),n=[...e].sort(t);return s.every((a,o)=>a===n[o])?0:-1},Yc=(r,e)=>{const t=dn(r),s=dn(e);return Ya(t,s)},Fc=(r,e)=>r===e?0:r==="first"&&e==="last"?1:-1,Fa=r=>(e,t)=>r(t,e),ft=0,Er=-1,Nr=1,qa=r=>r<ft,Ga=r=>r>ft,qc=r=>r>=ft,Va=r=>r===ft,Gc=(r,e)=>{const t=/([a-zA-Z]+)|(\d+)/g,s=r.replace(/[\s_.-]+/g,"").match(t),n=e.replace(/[\s_.-]+/g,"").match(t);if(!s||!n)return 0;for(let a=0;a<Math.min(s.length,n.length);a++){const o=s[a],c=n[a];if(isNaN(Number(o))&&isNaN(Number(c))){const l=o.localeCompare(c);if(l!==0)return l}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const l=Number(o)-Number(c);if(l!==0)return l}else return isNaN(Number(o))?-1:1}return s.length-n.length},Vc=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:ft,GREATER_THAN:Nr,LESS_THAN:Er,isEqualTo:Va,isGreaterThan:Ga,isGreaterThanEqual:qc,isLessThan:qa,newF:gs,newFieldF:Lc,order:Fc,primitiveArrays:_c,reverseF:Fa,stringsWithNumbers:Gc,uniqueUnorderedPrimitiveArrays:Yc,unorderedPrimitiveArrays:Ya},Symbol.toStringTag,{value:"Module"})),Wa=(r,e,t=".")=>{const s=r.split(t);return s.map((n,a)=>{const o=e(n,a,s);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(n=>n!=null).join(t)},Gn=(r,e,t={optional:!1,separator:"."})=>{t.separator??(t.separator=".");const{optional:s,getter:n=(c,l)=>c[l]}=t,a=e.split(t.separator);if(a.length===1&&a[0]==="")return r;let o=r;for(const c of a){const l=n(o,c);if(l==null){if(s)return null;throw new Error(`Path ${e} does not exist. ${c} is null`)}o=l}return o},Wc=(r,e,t)=>{const s=e.split(".");let n=r;for(let a=0;a<s.length-1;a++){const o=s[a];n[o]??(n[o]={}),n=n[o]}try{n[s[s.length-1]]=t}catch(a){throw console.error("failed to set value",t,"at path",e,"on object",r),a}},Zc=(r,e)=>{const t=e.split(".");let s=r;for(let n=0;n<t.length-1;n++){const a=t[n];if(s[a]==null)return;s=s[a]}if(Array.isArray(s)){const n=parseInt(t[t.length-1]);if(isNaN(n))return;s.splice(n,1);return}delete s[t[t.length-1]]},Kc=(r,e)=>{const t=r.split(".");return e<0?t[t.length+e]:t[e]},Jc=(r,e)=>{try{return Gn(r,e),!0}catch{return!1}},Hc=(r,e)=>{if(e.length===0)return!0;const t=r.split("."),s=e.split(".");if(s.length>t.length)return!1;for(let n=0;n<s.length;n++){const a=t[n],o=s[n];if(o!=="*"&&a!==o)return!1}return!0},Za=r=>Wa(r,(e,t,s)=>{const n=t===s.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(s[t+1]));return a&&(e="element"),n||o?e:[e,"shape"]}),Ti=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},Xc=(r,e,t)=>Gn(Ti(r,"shape"),Za(e),{...t,getter:Ti}),Qc=(r,e)=>t=>{const s=e.find(n=>n.safeParse(t).success);return s==null?null:r(s.parse(t))},Ka=i.z.bigint().or(i.z.string().transform(BigInt)),eu=Object.freeze(Object.defineProperty({__proto__:null,bigInt:Ka,getFieldSchema:Xc,getFieldSchemaPath:Za,transformer:Qc},Symbol.toStringTag,{value:"Module"}));var tu=Object.defineProperty,ru=(r,e,t)=>e in r?tu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g=(r,e,t)=>ru(r,typeof e!="symbol"?e+"":e,t);let su=(r,e=21)=>(t=e)=>{let s="",n=t|0;for(;n--;)s+=r[Math.random()*r.length|0];return s};const nu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ja=su(nu,11),Ha=Object.freeze(Object.defineProperty({__proto__:null,id:Ja},Symbol.toStringTag,{value:"Module"})),iu=i.z.enum(["static","dynamic"]),Xa=(r,e)=>{const t=new V(e);if(![Z.DAY,Z.HOUR,Z.MINUTE,Z.SECOND,Z.MILLISECOND,Z.MICROSECOND,Z.NANOSECOND].some(n=>n.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const s=r.valueOf()%t.valueOf();return r instanceof V?new V(s):new Z(s)},U=class z{constructor(e,t="UTC"){if(g(this,"value"),g(this,"encodeValue",!0),e==null)this.value=z.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*z.MILLISECOND.valueOf();else if(typeof e=="string")this.value=z.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=z.parseDate(e);else{let s=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(s=z.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=z.MAX:e=z.MIN)),this.value=BigInt(e.valueOf())+s}}static parseDate([e=1970,t=1,s=1]){const n=new Date(e,t-1,s,0,0,0,0);return new z(BigInt(n.getTime())*z.MILLISECOND.valueOf()).truncate(z.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[s,n,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=z.hours(parseInt(s??"00")).add(z.minutes(parseInt(n??"00"))).add(z.seconds(parseInt(o??"00"))).add(z.milliseconds(parseInt(c??"00")));return t==="local"&&(l=l.add(z.utcOffset)),l.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return z.parseTimeString(e,t);const s=new Date(e);return e.includes(":")||s.setUTCHours(0,0,0,0),new z(BigInt(s.getTime())*z.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(z.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const s=this.toISOString(t);return e?s.slice(11,23):s.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),s=e.toLocaleString("default",{day:"numeric"});return`${t} ${s}`}static get utcOffset(){return new Z(BigInt(new Date().getTimezoneOffset())*z.MINUTE.valueOf())}static since(e){return new z().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new z(e).valueOf()}span(e){return this.range(e).span}range(e){return new at(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new z(e).valueOf()}afterEq(e){return this.valueOf()>=new z(e).valueOf()}before(e){return this.valueOf()<new z(e).valueOf()}beforeEq(e){return this.valueOf()<=new z(e).valueOf()}add(e){return new z(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new z(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(Z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(Z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(Z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(Z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new z(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new z(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new z(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new z(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new z(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new z(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new z(t)}toString(){return this.date().toISOString()}remainder(e){return Xa(this,e)}get isToday(){return this.truncate(Z.DAY).equals(z.now().truncate(Z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new z(new Date)}static max(...e){let t=z.MIN;for(const s of e){const n=new z(s);n.after(t)&&(t=n)}return t}static min(...e){let t=z.MAX;for(const s of e){const n=new z(s);n.before(t)&&(t=n)}return t}static nanoseconds(e){return new z(e)}static microseconds(e){return z.nanoseconds(e*1e3)}static milliseconds(e){return z.microseconds(e*1e3)}static seconds(e){return z.milliseconds(e*1e3)}static minutes(e){return z.seconds(e*60)}static hours(e){return z.minutes(e*60)}static days(e){return z.hours(e*24)}};g(U,"NANOSECOND",U.nanoseconds(1)),g(U,"MICROSECOND",U.microseconds(1)),g(U,"MILLISECOND",U.milliseconds(1)),g(U,"SECOND",U.seconds(1)),g(U,"MINUTE",U.minutes(1)),g(U,"HOUR",U.hours(1)),g(U,"DAY",U.days(1)),g(U,"MAX",new U((1n<<63n)-1n)),g(U,"MIN",new U(0)),g(U,"ZERO",new U(0)),g(U,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new U(r.value)),i.z.string().transform(r=>new U(BigInt(r))),i.z.instanceof(Number).transform(r=>new U(r)),i.z.number().transform(r=>new U(r)),i.z.instanceof(U)]));let V=U;const L=class A{constructor(e){g(this,"value"),g(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof A?e:e instanceof ss?e.period:e instanceof V?new A(e):["number","bigint"].includes(typeof e)?A.seconds(e):new A(e)}static fromMilliseconds(e){return e instanceof A?e:e instanceof ss?e.period:e instanceof V?new A(e):["number","bigint"].includes(typeof e)?A.milliseconds(e):new A(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new A(e).valueOf()}greaterThan(e){return this.valueOf()>new A(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new A(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new A(e).valueOf()}remainder(e){return Xa(this,e)}truncate(e){return new A(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(A.DAY),t=this.truncate(A.HOUR),s=this.truncate(A.MINUTE),n=this.truncate(A.SECOND),a=this.truncate(A.MILLISECOND),o=this.truncate(A.MICROSECOND),c=this.truncate(A.NANOSECOND),l=e,d=t.sub(e),f=s.sub(t),h=n.sub(s),I=a.sub(n),j=o.sub(a),ie=c.sub(o);let P="";return l.isZero||(P+=`${l.days}d `),d.isZero||(P+=`${d.hours}h `),f.isZero||(P+=`${f.minutes}m `),h.isZero||(P+=`${h.seconds}s `),I.isZero||(P+=`${I.milliseconds}ms `),j.isZero||(P+=`${j.microseconds}µs `),ie.isZero||(P+=`${ie.nanoseconds}ns`),P.trim()}mult(e){return new A(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(A.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(A.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(A.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(A.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(A.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(A.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new A(e).valueOf()}add(e){return new A(this.valueOf()+new A(e).valueOf())}sub(e){return new A(this.valueOf()-new A(e).valueOf())}static nanoseconds(e=1){return new A(e)}static microseconds(e=1){return A.nanoseconds(p.M(e,1e3))}static milliseconds(e=1){return A.microseconds(p.M(e,1e3))}static seconds(e=1){return A.milliseconds(p.M(e,1e3))}static minutes(e=1){return A.seconds(p.M(e,60))}static hours(e){return A.minutes(p.M(e,60))}static days(e){return A.hours(p.M(e,24))}};g(L,"NANOSECOND",L.nanoseconds(1)),g(L,"MICROSECOND",L.microseconds(1)),g(L,"MILLISECOND",L.milliseconds(1)),g(L,"SECOND",L.seconds(1)),g(L,"MINUTE",L.minutes(1)),g(L,"HOUR",L.hours(1)),g(L,"DAY",L.days(1)),g(L,"MAX",new L((1n<<63n)-1n)),g(L,"MIN",new L(0)),g(L,"ZERO",new L(0)),g(L,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new L(r.value)),i.z.string().transform(r=>new L(BigInt(r))),i.z.instanceof(Number).transform(r=>new L(r)),i.z.number().transform(r=>new L(r)),i.z.instanceof(L)]));let Z=L;const Et=class Ir extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Ir(e).valueOf()}get period(){return Z.seconds(1/this.valueOf())}sampleCount(e){return new Z(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new ce(t).valueOf()}span(e){return Z.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Ir(e)}static khz(e){return Ir.hz(e*1e3)}};g(Et,"z",i.z.union([i.z.number().transform(r=>new Et(r)),i.z.instanceof(Number).transform(r=>new Et(r)),i.z.instanceof(Et)]));let ss=Et;const te=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Ht(e*this.valueOf())}};g(te,"UNKNOWN",new te(0)),g(te,"BIT128",new te(16)),g(te,"BIT64",new te(8)),g(te,"BIT32",new te(4)),g(te,"BIT16",new te(2)),g(te,"BIT8",new te(1)),g(te,"z",i.z.union([i.z.number().transform(r=>new te(r)),i.z.instanceof(Number).transform(r=>new te(r)),i.z.instanceof(te)]));let ce=te;const ze=class xr{constructor(e,t){g(this,"start"),g(this,"end"),typeof e=="object"&&"start"in e?(this.start=new V(e.start),this.end=new V(e.end)):(this.start=new V(e),this.end=new V(t))}get span(){return new Z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new xr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=Z.ZERO){e=e.makeValid();const s=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(s.start)||s.end.equals(e.start))return!1;const n=V.max(s.start,e.start),a=V.min(s.end,e.end);return a.before(n)?!1:new Z(a.sub(n)).greaterThanOrEqual(t)}roughlyEquals(e,t){let s=this.start.sub(e.start).valueOf(),n=this.end.sub(e.end).valueOf();return s<0&&(s=-s),n<0&&(n=-n),s<=t.valueOf()&&n<=t.valueOf()}contains(e){return e instanceof xr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new xr(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};g(ze,"MAX",new ze(V.MIN,V.MAX)),g(ze,"MIN",new ze(V.MAX,V.MIN)),g(ze,"ZERO",new ze(V.ZERO,V.ZERO)),g(ze,"z",i.z.union([i.z.object({start:V.z,end:V.z}).transform(r=>new ze(r.start,r.end)),i.z.instanceof(ze)]));let at=ze;const m=class Ee extends String{constructor(e){if(e instanceof Ee||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=Ee.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(Ee.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=Ee.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(Ee.JSON)||this.equals(Ee.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Ee.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Ee.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return Ee.BIG_INT_TYPES.some(e=>e.equals(this))}};g(m,"UNKNOWN",new m("unknown")),g(m,"FLOAT64",new m("float64")),g(m,"FLOAT32",new m("float32")),g(m,"INT64",new m("int64")),g(m,"INT32",new m("int32")),g(m,"INT16",new m("int16")),g(m,"INT8",new m("int8")),g(m,"UINT64",new m("uint64")),g(m,"UINT32",new m("uint32")),g(m,"UINT16",new m("uint16")),g(m,"UINT8",new m("uint8")),g(m,"BOOLEAN",m.UINT8),g(m,"TIMESTAMP",new m("timestamp")),g(m,"UUID",new m("uuid")),g(m,"STRING",new m("string")),g(m,"JSON",new m("json")),g(m,"ARRAY_CONSTRUCTORS",new Map([[m.UINT8.toString(),Uint8Array],[m.UINT16.toString(),Uint16Array],[m.UINT32.toString(),Uint32Array],[m.UINT64.toString(),BigUint64Array],[m.FLOAT32.toString(),Float32Array],[m.FLOAT64.toString(),Float64Array],[m.INT8.toString(),Int8Array],[m.INT16.toString(),Int16Array],[m.INT32.toString(),Int32Array],[m.INT64.toString(),BigInt64Array],[m.TIMESTAMP.toString(),BigInt64Array],[m.STRING.toString(),Uint8Array],[m.JSON.toString(),Uint8Array],[m.UUID.toString(),Uint8Array]])),g(m,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,m.UINT8],[Uint16Array.name,m.UINT16],[Uint32Array.name,m.UINT32],[BigUint64Array.name,m.UINT64],[Float32Array.name,m.FLOAT32],[Float64Array.name,m.FLOAT64],[Int8Array.name,m.INT8],[Int16Array.name,m.INT16],[Int32Array.name,m.INT32],[BigInt64Array.name,m.INT64]])),g(m,"DENSITIES",new Map([[m.UINT8.toString(),ce.BIT8],[m.UINT16.toString(),ce.BIT16],[m.UINT32.toString(),ce.BIT32],[m.UINT64.toString(),ce.BIT64],[m.FLOAT32.toString(),ce.BIT32],[m.FLOAT64.toString(),ce.BIT64],[m.INT8.toString(),ce.BIT8],[m.INT16.toString(),ce.BIT16],[m.INT32.toString(),ce.BIT32],[m.INT64.toString(),ce.BIT64],[m.TIMESTAMP.toString(),ce.BIT64],[m.STRING.toString(),ce.UNKNOWN],[m.JSON.toString(),ce.UNKNOWN],[m.UUID.toString(),ce.BIT128]])),g(m,"ALL",[m.UNKNOWN,m.FLOAT64,m.FLOAT32,m.INT64,m.INT32,m.INT16,m.INT8,m.UINT64,m.UINT32,m.UINT16,m.UINT8,m.TIMESTAMP,m.UUID,m.STRING,m.JSON]),g(m,"BIG_INT_TYPES",[m.INT64,m.UINT64,m.TIMESTAMP]),g(m,"z",i.z.union([i.z.string().transform(r=>new m(r)),i.z.instanceof(m)]));let D=m;const ae=class H extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return H.bytes(this.valueOf()+e.valueOf())}sub(e){return H.bytes(this.valueOf()-e.valueOf())}truncate(e){return new H(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return H.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/H.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/H.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/H.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/H.TERABYTE.valueOf()}toString(){const e=this.truncate(H.TERABYTE),t=this.truncate(H.GIGABYTE),s=this.truncate(H.MEGABYTE),n=this.truncate(H.KILOBYTE),a=this.truncate(H.BYTE),o=e,c=t.sub(e),l=s.sub(t),d=n.sub(s),f=a.sub(n);let h="";return o.isZero||(h+=`${o.terabytes}TB `),c.isZero||(h+=`${c.gigabytes}GB `),l.isZero||(h+=`${l.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new H(e)}static kilobytes(e=1){return H.bytes(e.valueOf()*1e3)}static megabytes(e=1){return H.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return H.megabytes(e.valueOf()*1e3)}static terabytes(e){return H.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};g(ae,"BYTE",new ae(1)),g(ae,"KILOBYTE",ae.kilobytes(1)),g(ae,"MEGABYTE",ae.megabytes(1)),g(ae,"GIGABYTE",ae.gigabytes(1)),g(ae,"TERABYTE",ae.terabytes(1)),g(ae,"ZERO",new ae(0)),g(ae,"z",i.z.union([i.z.number().transform(r=>new ae(r)),i.z.instanceof(ae)]));let Ht=ae;const au=i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]),Qa=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof V||r instanceof Z||r instanceof Date},ou=(r,e,t,s=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(s):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(s.valueOf()):It(t,-s).valueOf(),lu=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof eo?!0:Qa(r),Ue=-1,fn={[Symbol.iterator]:()=>fn,next:()=>({done:!0,value:void 0})},cu=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),uu=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),pn=10,Nt=class Ne{constructor(e){g(this,"key",""),g(this,"isSynnaxSeries",!0),g(this,"dataType"),g(this,"sampleOffset"),g(this,"gl"),g(this,"_data"),g(this,"_timeRange"),g(this,"alignment",0n),g(this,"_cachedMin"),g(this,"_cachedMax"),g(this,"writePos",Ue),g(this,"_refCount",0),g(this,"_cachedLength"),g(this,"_cachedIndexes"),lu(e)&&(e={data:e});const{dataType:t,timeRange:s,sampleOffset:n=0,glBufferUsage:a="static",alignment:o=0n,key:c=Ja()}=e,l=e.data??[];if(l instanceof Ne||typeof l=="object"&&"isSynnaxSeries"in l&&l.isSynnaxSeries===!0){const h=l;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this._timeRange=h._timeRange,this.alignment=h.alignment,this._cachedMin=h._cachedMin,this._cachedMax=h._cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this._cachedLength=h._cachedLength;return}const d=Qa(l),f=Array.isArray(l);if(t!=null)this.dataType=new D(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let h=l;if(!d){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");h=l[0]}if(typeof h=="string")this.dataType=D.STRING;else if(typeof h=="number")this.dataType=D.FLOAT64;else if(typeof h=="bigint")this.dataType=D.INT64;else if(typeof h=="boolean")this.dataType=D.BOOLEAN;else if(h instanceof V||h instanceof Date||h instanceof V)this.dataType=D.TIMESTAMP;else if(typeof h=="object")this.dataType=D.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new D(l)}if(!f&&!d)this._data=l;else{let h=d?[l]:l;const I=h[0];(I instanceof V||I instanceof Date||I instanceof Z)&&(h=h.map(j=>new V(j).valueOf())),this.dataType.equals(D.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(`${h.join(`
4
- `)}
5
- `).buffer):this.dataType.equals(D.JSON)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(`${h.map(j=>zr.encodeString(j)).join(`
6
- `)}
7
- `).buffer):this._data=new this.dataType.Array(h).buffer}this.key=c,this.alignment=o,this.sampleOffset=n??0,this._timeRange=s,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...s}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const n=new new D(t).Array(e),a=new Ne({data:n.buffer,dataType:t,...s});return a.writePos=0,a}static generateTimestamps(e,t,s){const n=s.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(s.add(t.span(o)).valueOf());return new Ne({data:a,dataType:D.TIMESTAMP,timeRange:n})}get refCount(){return this._refCount}static fromStrings(e,t){const s=new TextEncoder().encode(`${e.join(`
8
- `)}
9
- `);return new Ne({data:s,dataType:D.STRING,timeRange:t})}static fromJSON(e,t){const s=new TextEncoder().encode(`${e.map(n=>zr.encodeString(n)).join(`
10
- `)}
11
- `);return new Ne({data:s,dataType:D.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array 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===Ue)return 0;const t=this.byteCapacity.valueOf()-this.writePos,s=e.subBytes(0,t);return this.writeToUnderlyingData(s),this.writePos+=s.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=s.length,this.calculateCachedLength()),s.length}writeFixed(e){if(this.writePos===Ue)return 0;const t=this.capacity-this.writePos,s=e.sub(0,t);return this.writeToUnderlyingData(s),this._cachedLength=void 0,this.maybeRecomputeMinMax(s),this.writePos+=s.length,s.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===Ue?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(D.STRING,D.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
12
- `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(D.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=D.UUID.density.valueOf(),t=Array(this.length);for(let s=0;s<this.length;s++){const n=this.underlyingData.slice(s*e,(s+1)*e),a=Array.from(new Uint8Array(n.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[s]=a}return t}parseJSON(e){if(!this.dataType.equals(D.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
13
- `).slice(0,-1).map(t=>e.parse(zr.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Ht(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ue?this.byteCapacity:this.dataType.isVariable?new Ht(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ue?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((s,n)=>{s===pn&&(e++,t.push(n+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const s=new e.Array(this.length);for(let n=0;n<this.length;n++)s[n]=ou(this.dataType,e,this.data[n],t);return new Ne({data:s.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(D.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,s)=>t>s?t:s)}else{const e=this.data;this._cachedMax=e.reduce((t,s)=>t>s?t:s)}return this._cachedMax}get max(){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._cachedMax=this.calcRawMax()),It(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(D.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,s)=>t<s?t:s)}else{const e=this.data;this._cachedMin=e.reduce((t,s)=>t<s?t:s)}return this._cachedMin}get min(){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._cachedMin=this.calcRawMin()),It(this._cachedMin,this.sampleOffset))}get bounds(){return p.i(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return It(this.max,-this.min)}atAlignment(e,t){const s=Number(e-this.alignment);if(s<0||s>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${s}`);return}return this.at(s,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const s=this.data[e];if(s==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return It(s,this.sampleOffset)}atVariable(e,t){let s=0,n=0;if(this._cachedIndexes!=null)s=this._cachedIndexes[e],n=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]===pn){if(e===0){n=o;break}s=o+1,e--}if(n===0&&(n=this.data.length),s>=n||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(s,n);return this.dataType.equals(D.STRING)?new TextDecoder().decode(a):p.C(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,s=this.length-1;const n=gs(e);for(;t<=s;){const a=Math.floor((t+s)/2),o=n(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:s=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(D.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:s,prevBuffer:n}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==n)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Ue){n===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(n).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,s==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ue}as(e){if(e==="string"){if(!this.dataType.equals(D.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(D.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:ki(this.alignmentBounds.lower),upper:ki(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return p.i(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new hu(this);return this.dataType.equals(D.JSON)?new du(e):e}return new fu(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Si(this,e,t??this.length)}subAlignmentIterator(e,t){return new Si(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const s=this.data.subarray(e,t);return new Ne({data:s,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,s){if(t<=0&&(s==null||s>=this.length))return this;let n;return e?n=this.data.subarray(t,s):n=this.data.slice(t,s),new Ne({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new Ne({data:this.buffer,dataType:this.dataType,timeRange:at.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};g(Nt,"crudeZ",i.z.object({timeRange:at.z.optional(),dataType:D.z,alignment:Ka.optional(),data:i.z.union([cu,uu,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:iu.optional().default("static").optional()})),g(Nt,"z",Nt.crudeZ.transform(r=>new Nt(r)));let eo=Nt,Si=class{constructor(e,t,s){g(this,"series"),g(this,"end"),g(this,"index"),this.series=e;const n=p.i(0,e.length);this.end=p.T(n,s),this.index=p.T(n,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}},hu=class{constructor(e){if(g(this,"series"),g(this,"index"),g(this,"decoder"),!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,t=this.series.data;for(;this.index<t.length&&t[this.index]!==pn;)this.index++;const s=this.index;return e===s?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,s))})}[Symbol.iterator](){return this}};var zi,Ei;let du=class{constructor(e){g(this,"wrapped"),g(this,zi,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:zr.decodeString(e.value)}}[(Ei=Symbol.iterator,zi=Symbol.toStringTag,Ei)](){return this}};var Ni,Ii;class fu{constructor(e){g(this,"series"),g(this,"index"),g(this,Ni,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Ii=Symbol.iterator,Ni=Symbol.toStringTag,Ii)](){return this}}const It=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);let pu=class{constructor(e){if(g(this,"series"),e.length!==0){const t=e[0].dataType;for(let s=1;s<e.length;s++)if(!e[s].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new D(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?D.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?at.ZERO:new at(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?p.i(0n,0n):p.i(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const s of this.series)if(p.a(s.alignmentBounds,e))return s.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const s of this.series){if(e<s.length)return s.at(e,t);e-=s.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new $s(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return fn;let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)s+=o.length;else if(p.a(o.alignmentBounds,e)){s+=Number(e-o.alignment);break}}let n=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)n+=o.length;else if(p.a(o.alignmentBounds,t)){n+=Number(t-o.alignment);break}}return new $s(this,s,n)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return fn;let s=0;for(let n=0;n<this.series.length;n++){const a=this.series[n];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)s+=a.length;else if(p.a(a.alignmentBounds,e)){s+=Number(e-a.alignment);break}}return new $s(this,s,s+t)}get byteLength(){return new Ht(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const s of this.series)e.set(s.data,t),t+=s.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const s=this.series.map(n=>n.alignmentBounds);return p.U(s,e,t)}distance(e,t){const s=this.series.map(n=>n.alignmentBounds);return p.V(s,e,t)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new gu(this.series)}};var xi,Ai;let gu=class{constructor(e){g(this,"series"),g(this,"seriesIndex"),g(this,"internal"),g(this,xi,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(Ai=Symbol.iterator,xi=Symbol.toStringTag,Ai)](){return this}},$s=class{constructor(e,t,s){g(this,"series"),g(this,"index"),g(this,"end"),this.series=e,this.end=s,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};const ki=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},yu=(r,e)=>{let t=null;return e===0?r:(...s)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...s),e)}},mu=(r,e)=>{let t=null;return e===0?r:(...s)=>{t===null&&(t=setTimeout(()=>{r(...s),t=null},e))}},wu=r=>JSON.parse(JSON.stringify(r)),bu=(r,...e)=>(e.forEach(t=>{let s=r;const n=t.split(".");n.forEach((a,o)=>{o===n.length-1?delete s[a]:a in s&&(s=s[a])})}),r),vu=(r,e,t="")=>{const s={},n=(a,o,c)=>{if(typeof a!=typeof o||a===null||o===null){s[c]=[a,o];return}if(typeof a=="object"&&typeof o=="object")if(Array.isArray(a)&&Array.isArray(o)){if(a.length!==o.length){s[c]=[a,o];return}for(let l=0;l<a.length;l++)n(a[l],o[l],`${c}[${l}]`)}else new Set([...Object.keys(a),...Object.keys(o)]).forEach(l=>{n(a[l],o[l],c!==""?`${c}.${l}`:l)});else a!==o&&(s[c]=[a,o])};return n(r,e,t),s},gn=(r,e)=>{const t=Array.isArray(r),s=Array.isArray(e);if(t!==s)return!1;if(t&&s){const o=r,c=e;if(o.length!==c.length)return!1;for(let l=0;l<o.length;l++)if(!gn(o[l],c[l]))return!1;return!0}if(r==null||e==null||typeof r!="object"||typeof e!="object")return r===e;if("equals"in r)return r.equals(e);const n=Object.keys(r),a=Object.keys(e);if(n.length!==a.length)return!1;for(const o of n){const c=r[o],l=e[o];if(typeof c=="object"&&typeof l=="object"){if(!gn(c,l))return!1}else if(c!==l)return!1}return!0},to=(r,e)=>{if(typeof r!="object"||r==null)return r===e;const t=Object.keys(r),s=Object.keys(e);if(s.length>t.length)return!1;for(const n of s){const a=r[n],o=e[n];if(typeof a=="object"&&typeof o=="object"){if(!to(a,o))return!1}else if(a!==o)return!1}return!0},yn=(r,...e)=>{if(e.length===0)return r;const t=e.shift();if(Gt(r)&&Gt(t))for(const s in t)try{Gt(t[s])?(s in r||Object.assign(r,{[s]:{}}),yn(r[s],t[s])):Object.assign(r,{[s]:t[s]})}catch(n){throw n instanceof TypeError?new TypeError(`.${s}: ${n.message}`):n}return yn(r,...e)},Ou=(r,e,t)=>{const s=(n,a,o)=>{for(const c in a){const l=a[c];if(o!=null&&o.shape[c]){const d=o.shape[c].safeParse(l);d.success&&(n[c]=d.data)}else typeof l=="object"&&!Array.isArray(l)&&l!==null&&o&&o.shape&&o.shape[c]&&(n[c]||(n[c]={}),s(n[c],l,o.shape[c]))}return n};return s({...r},e,t)},ro=Object.freeze(Object.defineProperty({__proto__:null,copy:wu,deleteD:bu,difference:vu,element:Kc,equal:gn,get:Gn,has:Jc,override:yn,overrideValidItems:Ou,partialEqual:to,pathsMatch:Hc,remove:Zc,set:Wc,transformPath:Wa},Symbol.toStringTag,{value:"Module"}));i.z.object({key:i.z.string(),value:i.z.string()});i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const so=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Tu=so(),no=["MacOS","Windows","Linux","Docker"],Su=["macos","windows","linux","docker"],zu={macos:"MacOS",windows:"Windows",linux:"Linux",docker:"Docker"},Eu=i.z.enum(no).or(i.z.enum(Su).transform(r=>zu[r]));let Ms;const Nu=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},Iu=(r={})=>{const{force:e,default:t}=r;return e??Ms??(Ms=Nu(),Ms??t)},io=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:no,RUNTIME:Tu,detect:so,getOS:Iu,osZ:Eu},Symbol.toStringTag,{value:"Module"})),xu=r=>Array.isArray(r)?r:[r],Au=r=>Array.isArray(r)?r:r===null?[]:[r];var ku=Object.defineProperty,Cu=(r,e,t)=>e in r?ku(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xt=(r,e,t)=>Cu(r,typeof e!="symbol"?e+"":e,t);const Ru=(...r)=>r.map(ao).join(""),ao=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),$u=r=>r.endsWith("/")?r.slice(0,-1):r,Ci=class mn{constructor({host:e,port:t,protocol:s="",pathPrefix:n=""}){xt(this,"protocol"),xt(this,"host"),xt(this,"port"),xt(this,"path"),this.protocol=s,this.host=e,this.port=t,this.path=ao(n)}replace(e){return new mn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new mn({...this,pathPrefix:Ru(this.path,e)})}toString(){return $u(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};xt(Ci,"UNKNOWN",new Ci({host:"unknown",port:0}));var Mu=Object.defineProperty,Du=(r,e,t)=>e in r?Mu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ns=(r,e,t)=>Du(r,typeof e!="symbol"?e+"":e,t);let Bu=class{constructor(e){ns(this,"sender"),ns(this,"handlers"),this.sender=e,this.handlers=new Map}handle({data:e}){var t;const s=(t=this.handlers.get(e.type))==null?void 0:t.handler;s==null?console.warn(`No handler for ${e.type}`):s(e.payload)}route(e){const t=ju(e,this.sender),s=new Pu(t);return this.handlers.set(e,s),s}};const ju=(r,e)=>(t,s)=>e({type:r,payload:t},s);let Pu=class{constructor(e){ns(this,"_send"),ns(this,"handler"),this._send=e,this.handler=null}send(e,t=[]){this._send(e,t)}handle(e){this.handler=e}};var Uu=Object.defineProperty,Lu=(r,e,t)=>e in r?Uu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e,t)=>Lu(r,typeof e!="symbol"?e+"":e,t);i.z.object({interval:Z.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()});const Ze=class extends Number{};Ar(Ze,"Absolute",255),Ar(Ze,"Default",1),Ar(Ze,"z",i.z.union([i.z.instanceof(Ze),i.z.number().int().min(0).max(255).transform(r=>new Ze(r)),i.z.instanceof(Number).transform(r=>new Ze(r))]));let oo=Ze;const lo=i.z.object({name:i.z.string(),key:i.z.string()}),_u=r=>i.z.object({subject:lo,resource:r,authority:oo.z}),Yu=(...r)=>e=>e.filter(t=>{let s=!1;return t.to!=null&&(s=r.includes(t.to.resource)),t.from!=null&&!s&&(s=r.includes(t.from.resource)),s}),Fu=Object.freeze(Object.defineProperty({__proto__:null,Authority:oo,filterTransfersByChannelKey:Yu,stateZ:_u,subjectZ:lo},Symbol.toStringTag,{value:"Module"})),co=class At extends Error{constructor(){super(At.MESSAGE)}matches(e){return typeof e=="string"?e.includes(At.MESSAGE):e instanceof At||e.message.includes(At.MESSAGE)}};Ar(co,"MESSAGE","canceled");let qu=co;new qu;const Gu=r=>r?-1:1,wn=i.z.string().regex(/^\d+\.\d+\.\d+$/),ir=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const s=wn.parse(r),n=wn.parse(e),[a,o,c]=s.split(".").map(Number),[l,d,f]=n.split(".").map(Number);if(t.checkMajor){if(a<l)return Er;if(a>l)return Nr}if(t.checkMinor){if(o<d)return Er;if(o>d)return Nr}if(t.checkPatch){if(c<f)return Er;if(c>f)return Nr}return ft},Vu=(r,e,t={})=>Va(ir(r,e,t)),uo=(r,e,t={})=>Ga(ir(r,e,t)),Wu=(r,e,t={})=>qa(ir(r,e,t)),Zu=({name:r,migrate:e})=>t=>{try{const s=e(t);return console.log(`${r} migrated: ${t.version} -> ${s.version}`),s}catch(s){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(s),s}},Ku=({name:r,migrations:e,targetSchema:t,defaultVersion:s,def:n})=>{const a=Object.keys(e).sort(ir).pop();if(a==null)return d=>{if(d.version??(d.version=s),d.version!==n.version)return console.log(`${r} version ${d.version} is newer than latest version of ${n.version}.
14
- Returning default instead.
15
- `),n;try{return t!=null?t.parse(d):d}catch(f){return console.log(`${r} failed to parse default. Exiting with default`),console.error(f),n}};const o=Object.keys(e).length;let c=!1;const l=d=>{try{if(o===0||uo(d.version,a))return console.log(c?`${r} ${d.version} now up to date`:`${r} version ${d.version} is up to date with target version ${n.version}`),d;const f=d.version,h=e[f],I=h(d);return c=!0,l(I)}catch(f){return console.log(`${r} failed to migrate from ${d.version} to ${a}`),console.error(f),n}};return d=>{try{if(d.version==null)if(s!=null)console.log(`${r} version is null. Setting version to default of ${s}`),d.version=s;else return console.log(`${r} version is null and no default version set. Exiting with default`),n;return l(d)}catch(f){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(f),n}}},Ju=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:ir,createMigration:Zu,migrator:Ku,semVerNewer:uo,semVerOlder:Wu,semVerZ:wn,versionsEqual:Vu},Symbol.toStringTag,{value:"Module"})),Hu=r=>{if(r===void 0||typeof r=="string"||typeof r=="number")return r;if(r.toString===void 0)throw new Error("invalid renderer");return r.toString()},Xu=r=>Array.isArray(r)?[...r]:typeof r=="object"&&r!==null?{...r}:r,Vn=r=>typeof r=="function",Wn=(r,e)=>Vn(r)?r(e):r,ar=r=>ho(r)?r():r,ho=r=>typeof r=="function",fo=({initial:r,value:e,onChange:t})=>{const[s,n]=qn.useState(ar(e??r));return e!=null&&t!=null?[e,t]:[s,n]},po=({initial:r,value:e,onChange:t})=>{const[s,n]=qn.useState(ar(e??r));return e!=null&&t!=null?[e,t]:[s,n]},Qu=(r,e)=>{const[t,s]=qn.useState(()=>{const n=localStorage.getItem(e);return n==null?ar(r):JSON.parse(n)});return[t,n=>{s(n),localStorage.setItem(e,JSON.stringify(n))}]},eh=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:ar,executeSetter:Wn,isInitialSetter:ho,isSetter:Vn,usePassthrough:fo,usePersisted:Qu,usePurePassthrough:po},Symbol.toStringTag,{value:"Module"})),go=["h1","h2","h3","h4","h5","p","small"],th=i.z.enum(go),rh={h1:"h2",h2:"h3",h3:"h4",h4:"h5",h5:"p",p:"small",small:"small"},sh=r=>rh[r],nh={h1:"h1",h2:"h1",h3:"h2",h4:"h3",h5:"h4",p:"h5",small:"p"},ih=r=>nh[r],ah=["normal","bold","bolder","lighter"],oh=i.z.union([i.z.number(),i.z.enum(ah)]),Fe=i.z.object({size:i.z.number(),weight:i.z.union([i.z.number(),i.z.string()]),lineHeight:i.z.number(),textTransform:i.z.string().optional()}),yo={small:"small",medium:"p",large:"h5",huge:"h2"},lh={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"};let Ri=null;const ch=()=>(Ri??(Ri=document.createElement("canvas")),Ri),uh=(r,e,t)=>{if(io.RUNTIME==="node")return{width:0,height:0};t??(t=ch().getContext("2d")),t.font=e;const s=t.measureText(r);return{width:Math.trunc(Math.abs(s.actualBoundingBoxLeft)+Math.abs(s.actualBoundingBoxRight)),height:Math.trunc(Math.abs(s.actualBoundingBoxAscent)+Math.abs(s.actualBoundingBoxDescent))}},hh=i.z.object({l0:p.Color.z,l1:p.Color.z,l2:p.Color.z,l3:p.Color.z,l4:p.Color.z,l5:p.Color.z,l6:p.Color.z,l7:p.Color.z,l8:p.Color.z,l9:p.Color.z,l10:p.Color.z}),be=(r,e)=>[r[0],r[1],e,r[3]],dh=i.z.object({m2:p.Color.z,m1:p.Color.z,z:p.Color.z,p1:p.Color.z,p2:p.Color.z}),yr=dh.or(p.Color.z.transform(r=>{const e=r.hsla;return{m2:new p.Color(p.fromHSLA(be(e,40))),m1:new p.Color(p.fromHSLA(be(e,45))),z:r,p1:new p.Color(p.fromHSLA(be(e,55))),p2:new p.Color(p.fromHSLA(be(e,65)))}})),mo=i.z.object({name:i.z.string(),key:i.z.string(),colors:i.z.object({border:p.Color.z,primary:yr,gray:hh,error:yr,secondary:yr,warning:yr,palettes:i.z.record(p.paletteZ),visualization:i.z.object({palettes:i.z.record(i.z.array(p.Color.z))}).optional().default({palettes:{}}),white:p.Color.z,black:p.Color.z,text:p.Color.z,textInverted:p.Color.z,textOnPrimary:p.Color.z.optional().default(p.ZERO),logo:i.z.string()}),sizes:i.z.object({base:i.z.number(),border:i.z.object({radius:i.z.number(),width:i.z.number()}),schematic:i.z.object({elementStrokeWidth:i.z.number()})}),typography:i.z.object({family:i.z.string(),codeFamily:i.z.string(),h1:Fe,h2:Fe,h3:Fe,h4:Fe,h5:Fe,p:Fe,small:Fe})}).transform(r=>((r.colors.textOnPrimary==null||r.colors.textOnPrimary.isZero)&&(r.colors.textOnPrimary=r.colors.primary.z.pickByContrast(r.colors.text,r.colors.textInverted)),r)),fh="'Inter Variable', sans-serif",ph="'Geist Mono', monospace",gh=6,wt=[357,91,55,1],bt=[58,100,50,1],yh=["#FDFDFD","#FAFAFA","#F3F3F3","#EAEAEA","#D8D8D8","#ADADAD","#878787","#616161","#404040","#1C1C1C","#050505"],vt=Object.fromEntries(yh.map((r,e)=>[`l${e}`,r])),bn={key:"synnaxBase",name:"Synnax Base",colors:{primary:{m2:"#041B3D",m1:"#164FA0",z:"#3774D0",p1:"#5E94EE",p2:"#8AB8FF"},secondary:{m2:"#2D8F4E",m1:"#38B261",z:"#50C878",p1:"#73D393",p2:"#96DEAE"},gray:vt,border:vt.l3,error:{m2:p.fromHSLA(be(wt,30)),m1:p.fromHSLA(be(wt,40)),z:p.fromHSLA(wt),p1:p.fromHSLA(be(wt,65)),p2:p.fromHSLA(be(wt,77))},warning:{m2:p.fromHSLA(be(bt,30)),m1:p.fromHSLA(be(bt,40)),z:p.fromHSLA(bt),p1:p.fromHSLA(be(bt,65)),p2:p.fromHSLA(be(bt,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:vt.l9,textInverted:vt.l0,textOnPrimary:vt.l0},sizes:{base:gh,border:{radius:3,width:1},schematic:{elementStrokeWidth:2}},typography:{family:fh,codeFamily:ph,h1:{size:7,weight:"500",lineHeight:7*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:1.9166666*1.5}}},wo=Object.freeze({...bn,key:"synnaxLight",name:"Synnax Light"}),mh=["#020202","#0A0A0A","#131313","#1E1E1E","#2E2E2E","#444444","#646464","#8A8A8A","#AFAFAF","#D5D5D5","#FDFDFD"],Ot=Object.fromEntries(mh.map((r,e)=>[`l${e}`,r])),bo=Object.freeze({...bn,key:"synnaxDark",name:"Synnax Dark",colors:{...bn.colors,gray:Ot,logo:"var(--pluto-text-color)",border:Ot.l3,text:Ot.l9,textInverted:Ot.l0,textOnPrimary:Ot.l10}}),wh={synnaxDark:bo,synnaxLight:wo},bh=["small","medium","large","huge"],vh=i.z.enum(bh),Oh=r=>vh.safeParse(r).success,Th=(r,{level:e,weight:t,code:s})=>{const{typography:n,sizes:{base:a}}=r,o=n[Oh(e)?yo[e]:e].size,c=(a*o).toFixed(1),l=s?n.codeFamily:n.family,[d,f]=l.split(", ");return t!=null?` ${t} ${c}px ${d}, ${f}`:` ${c}px ${l}`};var Sh=Object.defineProperty,zh=(r,e,t)=>e in r?Sh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>zh(r,typeof e!="symbol"?e+"":e,t);const S=r=>Array.isArray(r)?r:[r];var Eh=Object.defineProperty,Nh=(r,e,t)=>e in r?Eh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,B=(r,e,t)=>Nh(r,typeof e!="symbol"?e+"":e,t);const Ih=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},vo=r=>{const e=(t,s=vn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,s));if(!Ds(t))return t;s=kh(s);const n={},a=t;return Object.keys(a).forEach(o=>{let c=a[o];const l=r(o);s.recursive&&(Ds(c)?Mi(c,s.keepTypesOnRecursion)||(c=e(c,s)):s.recursiveInArray&&$i(c)&&(c=[...c].map(d=>{let f=d;return Ds(d)?Mi(f,s.keepTypesOnRecursion)||(f=e(d,s)):$i(d)&&(f=e({key:d},s).key),f}))),n[l]=c}),n};return e},Oo=vo(Ih),xh=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,s)=>`${t}_${s.toLowerCase()}`),Ah=vo(xh),vn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},kh=(r=vn)=>(r.recursive==null?r=vn:r.recursiveInArray??(r.recursiveInArray=!1),r),$i=r=>r!=null&&Array.isArray(r),Ds=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Mi=(r,e)=>(e||[]).some(t=>r instanceof t),To=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Ch=Object.defineProperty,Rh=(r,e,t)=>e in r?Ch(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Wt=(r,e,t)=>Rh(r,typeof e!="symbol"?e+"":e,t);let $h=class{constructor(){Wt(this,"contentType","application/json"),Wt(this,"decoder"),Wt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r)).buffer}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),s=Oo(t);return e!=null?e.parse(s):s}encodeString(r){const e=Ah(r);return JSON.stringify(e,(t,s)=>ArrayBuffer.isView(s)?Array.from(s):To(s)&&"encode_value"in s?typeof s.value=="bigint"?s.value.toString():s.value:typeof s=="bigint"?s.toString():s)}static registerCustomType(){}},Mh=class{constructor(){Wt(this,"contentType","text/csv")}encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e).buffer}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!To(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(s=>{const n=e.map(a=>JSON.stringify(s[a]??""));t.push(n.join(","))}),t.join(`
16
- `)}decodeString(r,e){const[t,...s]=r.trim().split(`
17
- `).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const n=t.split(",").map(o=>o.trim()),a={};return n.forEach(o=>{a[o]=[]}),s.forEach(o=>{const c=o.split(",").map(l=>l.trim());n.forEach((l,d)=>{const f=this.parseValue(c[d]);f!=null&&a[l].push(f)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},Dh=class{constructor(){Wt(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r).buffer}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const kr=new $h;new Mh;new Dh;const Bh=r=>r!=null&&typeof r=="object"&&"toString"in r,jh=(r,e=!1)=>{const t=Bh(r)?"stringer":typeof r;let s;switch(t){case"string":s=(n,a)=>n.localeCompare(a);break;case"stringer":s=(n,a)=>n.toString().localeCompare(a.toString());break;case"number":s=(n,a)=>Number(n)-Number(a);break;case"bigint":s=(n,a)=>BigInt(n)-BigInt(a)>0n?1:-1;break;case"boolean":s=(n,a)=>Number(n)-Number(a);break;case"undefined":s=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Ph(s):s},Ph=r=>(e,t)=>r(t,e),ys=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const So=i.z.object({width:i.z.number(),height:i.z.number()}),Uh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Lh=["width","height"];i.z.enum(Lh);const _h=["start","center","end"],Yh=["signedWidth","signedHeight"];i.z.enum(Yh);const is=i.z.object({x:i.z.number(),y:i.z.number()}),Fh=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),qh=["x","y"],zo=i.z.enum(qh),Eo=["top","right","bottom","left"];i.z.enum(Eo);const Gh=["left","right"],No=i.z.enum(Gh),Vh=["top","bottom"],Io=i.z.enum(Vh),xo=["center"],Di=i.z.enum(xo),Wh=[...Eo,...xo],Ao=i.z.enum(Wh);i.z.enum(_h);const Zh=["first","last"];i.z.enum(Zh);const Kh=i.z.object({lower:i.z.number(),upper:i.z.number()}),Jh=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([Kh,ys]);i.z.union([Jh,ys]);i.z.union([zo,Ao]);i.z.union([zo,Ao,i.z.instanceof(String)]);const Hh=r=>typeof r=="bigint"||r instanceof BigInt,et=(r,e)=>Hh(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),Xe=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Bi(r);return Bi(t)},Bi=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,ji=(r,e)=>{const t=Xe(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};i.z.object({x:No.or(Di),y:Io.or(Di)});const Xh=i.z.object({x:No,y:Io}),Qh=Object.freeze({x:"left",y:"top"}),ed=(r,e)=>r.x===e.x&&r.y===e.y,Pi=i.z.union([i.z.number(),is,ys,So,Uh,Fh]),td=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Ui=Object.freeze({x:0,y:0}),mr=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:mr,left:mr,width:mr,height:mr});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:is,two:is,root:Xh});const Zn=(r,e,t=0,s=0,n)=>{const a={one:{...Ui},two:{...Ui},root:n??Qh};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+s},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:n??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+s}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},Bs=r=>{const e=Zn(r);return{lower:e.one.x,upper:e.two.x}},js=r=>{const e=Zn(r);return{lower:e.one.y,upper:e.two.y}},rd=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,sd=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([So,sd,is,ys]);var nd=Object.defineProperty,id=(r,e,t)=>e in r?nd(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Be=(r,e,t)=>id(r,typeof e!="symbol"?e+"":e,t);const ad=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;i.z.object({offset:Pi,scale:Pi});i.z.object({offset:i.z.number(),scale:i.z.number()});const od=r=>(e,t,s,n)=>t==="dimension"?[e,s]:[e,n?s-r:s+r],ld=r=>(e,t,s,n)=>[e,n?s/r:s*r],cd=r=>(e,t,s)=>{if(e===null)return[r,s];const{lower:n,upper:a}=e,{lower:o,upper:c}=r,l=a-n,d=c-o;if(t==="dimension")return[r,s*(d/l)];const f=(s-n)*(d/l)+o;return[r,f]},ud=r=>(e,t,s)=>[r,s],hd=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:s,upper:n}=r;return[r,n-(t-s)]},dd=r=>(e,t,s)=>{const{lower:n,upper:a}=r;return s=ad(s,n,a),[e,s]},On=class kt{constructor(){Be(this,"ops",[]),Be(this,"currBounds",null),Be(this,"currType",null),Be(this,"reversed",!1),this.ops=[]}static translate(e){return new kt().translate(e)}static magnify(e){return new kt().magnify(e)}static scale(e,t){return new kt().scale(e,t)}translate(e){const t=this.new(),s=od(e);return s.type="translate",t.ops.push(s),t}magnify(e){const t=this.new(),s=ld(e);return s.type="magnify",t.ops.push(s),t}scale(e,t){const s=Xe(e,t),n=this.new(),a=cd(s);return a.type="scale",n.ops.push(a),n}clamp(e,t){const s=Xe(e,t),n=this.new(),a=dd(s);return a.type="clamp",n.ops.push(a),n}reBound(e,t){const s=Xe(e,t),n=this.new(),a=ud(s);return a.type="re-bound",n.ops.push(a),n}invert(){const e=hd();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new kt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([s,n],a)=>a(s,e,n,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((s,n)=>{if(s.type==="scale"||t.some(([o,c])=>n>=o&&n<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>n);a!==-1&&t.push([n,a])}),t.forEach(([s,n])=>{const a=e.ops.slice(s,n);a.unshift(e.ops[n]),e.ops.splice(s,n-s+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};Be(On,"IDENTITY",new On);let Li=On;const _i=class Me{constructor(e=new Li,t=new Li,s=null){Be(this,"x"),Be(this,"y"),Be(this,"currRoot"),this.x=e,this.y=t,this.currRoot=s}static translate(e,t){return new Me().translate(e,t)}static translateX(e){return new Me().translateX(e)}static translateY(e){return new Me().translateY(e)}static clamp(e){return new Me().clamp(e)}static magnify(e){return new Me().magnify(e)}static scale(e){return new Me().scale(e)}static reBound(e){return new Me().reBound(e)}translate(e,t){const s=td(e,t),n=this.copy();return n.x=this.x.translate(s.x),n.y=this.y.translate(s.y),n}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(rd(e)){const s=this.currRoot;return t.currRoot=e.root,s!=null&&!ed(s,e.root)&&(s.x!==e.root.x&&(t.x=t.x.invert()),s.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Bs(e)),t.y=t.y.scale(js(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Bs(e)),t.y=this.y.reBound(js(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Bs(e)),t.y=this.y.clamp(js(e)),t}copy(){const e=new Me;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 Zn(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})}}};Be(_i,"IDENTITY",new _i);const fd=i.z.bigint().or(i.z.string().transform(BigInt));var pd=Object.defineProperty,gd=(r,e,t)=>e in r?pd(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,v=(r,e,t)=>gd(r,typeof e!="symbol"?e+"":e,t);let yd=(r,e=21)=>(t=e)=>{let s="",n=t|0;for(;n--;)s+=r[Math.random()*r.length|0];return s};const md="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wd=yd(md,11),bd=i.z.enum(["static","dynamic"]),ko=(r,e)=>{const t=new K(e);if(![W.DAY,W.HOUR,W.MINUTE,W.SECOND,W.MILLISECOND,W.MICROSECOND,W.NANOSECOND].some(n=>n.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const s=r.valueOf()%t.valueOf();return r instanceof K?new K(s):new W(s)},_=class E{constructor(e,t="UTC"){if(v(this,"value"),v(this,"encodeValue",!0),e==null)this.value=E.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*E.MILLISECOND.valueOf();else if(typeof e=="string")this.value=E.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=E.parseDate(e);else{let s=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(s=E.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=E.MAX:e=E.MIN)),this.value=BigInt(e.valueOf())+s}}static parseDate([e=1970,t=1,s=1]){const n=new Date(e,t-1,s,0,0,0,0);return new E(BigInt(n.getTime())*E.MILLISECOND.valueOf()).truncate(E.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[s,n,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=E.hours(parseInt(s??"00")).add(E.minutes(parseInt(n??"00"))).add(E.seconds(parseInt(o??"00"))).add(E.milliseconds(parseInt(c??"00")));return t==="local"&&(l=l.add(E.utcOffset)),l.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return E.parseTimeString(e,t);const s=new Date(e);return e.includes(":")||s.setUTCHours(0,0,0,0),new E(BigInt(s.getTime())*E.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(E.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const s=this.toISOString(t);return e?s.slice(11,23):s.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),s=e.toLocaleString("default",{day:"numeric"});return`${t} ${s}`}static get utcOffset(){return new W(BigInt(new Date().getTimezoneOffset())*E.MINUTE.valueOf())}static since(e){return new E().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new E(e).valueOf()}span(e){return this.range(e).span}range(e){return new Kn(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new E(e).valueOf()}afterEq(e){return this.valueOf()>=new E(e).valueOf()}before(e){return this.valueOf()<new E(e).valueOf()}beforeEq(e){return this.valueOf()<=new E(e).valueOf()}add(e){return new E(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new E(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(W.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(W.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(W.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(W.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new E(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new E(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new E(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new E(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new E(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new E(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new E(t)}toString(){return this.date().toISOString()}remainder(e){return ko(this,e)}get isToday(){return this.truncate(W.DAY).equals(E.now().truncate(W.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new E(new Date)}static max(...e){let t=E.MIN;for(const s of e){const n=new E(s);n.after(t)&&(t=n)}return t}static min(...e){let t=E.MAX;for(const s of e){const n=new E(s);n.before(t)&&(t=n)}return t}static nanoseconds(e){return new E(e)}static microseconds(e){return E.nanoseconds(e*1e3)}static milliseconds(e){return E.microseconds(e*1e3)}static seconds(e){return E.milliseconds(e*1e3)}static minutes(e){return E.seconds(e*60)}static hours(e){return E.minutes(e*60)}static days(e){return E.hours(e*24)}};v(_,"NANOSECOND",_.nanoseconds(1)),v(_,"MICROSECOND",_.microseconds(1)),v(_,"MILLISECOND",_.milliseconds(1)),v(_,"SECOND",_.seconds(1)),v(_,"MINUTE",_.minutes(1)),v(_,"HOUR",_.hours(1)),v(_,"DAY",_.days(1)),v(_,"MAX",new _((1n<<63n)-1n)),v(_,"MIN",new _(0)),v(_,"ZERO",new _(0)),v(_,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new _(r.value)),i.z.string().transform(r=>new _(BigInt(r))),i.z.instanceof(Number).transform(r=>new _(r)),i.z.number().transform(r=>new _(r)),i.z.instanceof(_)]));let K=_;const Y=class k{constructor(e){v(this,"value"),v(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof k?e:e instanceof Yi?e.period:e instanceof K?new k(e):["number","bigint"].includes(typeof e)?k.seconds(e):new k(e)}static fromMilliseconds(e){return e instanceof k?e:e instanceof Yi?e.period:e instanceof K?new k(e):["number","bigint"].includes(typeof e)?k.milliseconds(e):new k(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new k(e).valueOf()}greaterThan(e){return this.valueOf()>new k(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new k(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new k(e).valueOf()}remainder(e){return ko(this,e)}truncate(e){return new k(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(k.DAY),t=this.truncate(k.HOUR),s=this.truncate(k.MINUTE),n=this.truncate(k.SECOND),a=this.truncate(k.MILLISECOND),o=this.truncate(k.MICROSECOND),c=this.truncate(k.NANOSECOND),l=e,d=t.sub(e),f=s.sub(t),h=n.sub(s),I=a.sub(n),j=o.sub(a),ie=c.sub(o);let P="";return l.isZero||(P+=`${l.days}d `),d.isZero||(P+=`${d.hours}h `),f.isZero||(P+=`${f.minutes}m `),h.isZero||(P+=`${h.seconds}s `),I.isZero||(P+=`${I.milliseconds}ms `),j.isZero||(P+=`${j.microseconds}µs `),ie.isZero||(P+=`${ie.nanoseconds}ns`),P.trim()}mult(e){return new k(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(k.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(k.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(k.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(k.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(k.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(k.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new k(e).valueOf()}add(e){return new k(this.valueOf()+new k(e).valueOf())}sub(e){return new k(this.valueOf()-new k(e).valueOf())}static nanoseconds(e=1){return new k(e)}static microseconds(e=1){return k.nanoseconds(et(e,1e3))}static milliseconds(e=1){return k.microseconds(et(e,1e3))}static seconds(e=1){return k.milliseconds(et(e,1e3))}static minutes(e=1){return k.seconds(et(e,60))}static hours(e){return k.minutes(et(e,60))}static days(e){return k.hours(et(e,24))}};v(Y,"NANOSECOND",Y.nanoseconds(1)),v(Y,"MICROSECOND",Y.microseconds(1)),v(Y,"MILLISECOND",Y.milliseconds(1)),v(Y,"SECOND",Y.seconds(1)),v(Y,"MINUTE",Y.minutes(1)),v(Y,"HOUR",Y.hours(1)),v(Y,"DAY",Y.days(1)),v(Y,"MAX",new Y((1n<<63n)-1n)),v(Y,"MIN",new Y(0)),v(Y,"ZERO",new Y(0)),v(Y,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new Y(r.value)),i.z.string().transform(r=>new Y(BigInt(r))),i.z.instanceof(Number).transform(r=>new Y(r)),i.z.number().transform(r=>new Y(r)),i.z.instanceof(Y)]));let W=Y;const Ct=class Cr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Cr(e).valueOf()}get period(){return W.seconds(1/this.valueOf())}sampleCount(e){return new W(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new ue(t).valueOf()}span(e){return W.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Cr(e)}static khz(e){return Cr.hz(e*1e3)}};v(Ct,"z",i.z.union([i.z.number().transform(r=>new Ct(r)),i.z.instanceof(Number).transform(r=>new Ct(r)),i.z.instanceof(Ct)]));let Yi=Ct;const re=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Tn(e*this.valueOf())}};v(re,"UNKNOWN",new re(0)),v(re,"BIT128",new re(16)),v(re,"BIT64",new re(8)),v(re,"BIT32",new re(4)),v(re,"BIT16",new re(2)),v(re,"BIT8",new re(1)),v(re,"z",i.z.union([i.z.number().transform(r=>new re(r)),i.z.instanceof(Number).transform(r=>new re(r)),i.z.instanceof(re)]));let ue=re;const Ie=class Rr{constructor(e,t){v(this,"start"),v(this,"end"),typeof e=="object"&&"start"in e?(this.start=new K(e.start),this.end=new K(e.end)):(this.start=new K(e),this.end=new K(t))}get span(){return new W(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 Rr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=W.ZERO){e=e.makeValid();const s=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(s.start)||s.end.equals(e.start))return!1;const n=K.max(s.start,e.start),a=K.min(s.end,e.end);return a.before(n)?!1:new W(a.sub(n)).greaterThanOrEqual(t)}roughlyEquals(e,t){let s=this.start.sub(e.start).valueOf(),n=this.end.sub(e.end).valueOf();return s<0&&(s=-s),n<0&&(n=-n),s<=t.valueOf()&&n<=t.valueOf()}contains(e){return e instanceof Rr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Rr(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};v(Ie,"MAX",new Ie(K.MIN,K.MAX)),v(Ie,"MIN",new Ie(K.MAX,K.MIN)),v(Ie,"ZERO",new Ie(K.ZERO,K.ZERO)),v(Ie,"z",i.z.union([i.z.object({start:K.z,end:K.z}).transform(r=>new Ie(r.start,r.end)),i.z.instanceof(Ie)]));let Kn=Ie;const w=class xe extends String{constructor(e){if(e instanceof xe||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=xe.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(xe.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=xe.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(xe.JSON)||this.equals(xe.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(xe.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=xe.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return xe.BIG_INT_TYPES.some(e=>e.equals(this))}};v(w,"UNKNOWN",new w("unknown")),v(w,"FLOAT64",new w("float64")),v(w,"FLOAT32",new w("float32")),v(w,"INT64",new w("int64")),v(w,"INT32",new w("int32")),v(w,"INT16",new w("int16")),v(w,"INT8",new w("int8")),v(w,"UINT64",new w("uint64")),v(w,"UINT32",new w("uint32")),v(w,"UINT16",new w("uint16")),v(w,"UINT8",new w("uint8")),v(w,"BOOLEAN",w.UINT8),v(w,"TIMESTAMP",new w("timestamp")),v(w,"UUID",new w("uuid")),v(w,"STRING",new w("string")),v(w,"JSON",new w("json")),v(w,"ARRAY_CONSTRUCTORS",new Map([[w.UINT8.toString(),Uint8Array],[w.UINT16.toString(),Uint16Array],[w.UINT32.toString(),Uint32Array],[w.UINT64.toString(),BigUint64Array],[w.FLOAT32.toString(),Float32Array],[w.FLOAT64.toString(),Float64Array],[w.INT8.toString(),Int8Array],[w.INT16.toString(),Int16Array],[w.INT32.toString(),Int32Array],[w.INT64.toString(),BigInt64Array],[w.TIMESTAMP.toString(),BigInt64Array],[w.STRING.toString(),Uint8Array],[w.JSON.toString(),Uint8Array],[w.UUID.toString(),Uint8Array]])),v(w,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,w.UINT8],[Uint16Array.name,w.UINT16],[Uint32Array.name,w.UINT32],[BigUint64Array.name,w.UINT64],[Float32Array.name,w.FLOAT32],[Float64Array.name,w.FLOAT64],[Int8Array.name,w.INT8],[Int16Array.name,w.INT16],[Int32Array.name,w.INT32],[BigInt64Array.name,w.INT64]])),v(w,"DENSITIES",new Map([[w.UINT8.toString(),ue.BIT8],[w.UINT16.toString(),ue.BIT16],[w.UINT32.toString(),ue.BIT32],[w.UINT64.toString(),ue.BIT64],[w.FLOAT32.toString(),ue.BIT32],[w.FLOAT64.toString(),ue.BIT64],[w.INT8.toString(),ue.BIT8],[w.INT16.toString(),ue.BIT16],[w.INT32.toString(),ue.BIT32],[w.INT64.toString(),ue.BIT64],[w.TIMESTAMP.toString(),ue.BIT64],[w.STRING.toString(),ue.UNKNOWN],[w.JSON.toString(),ue.UNKNOWN],[w.UUID.toString(),ue.BIT128]])),v(w,"ALL",[w.UNKNOWN,w.FLOAT64,w.FLOAT32,w.INT64,w.INT32,w.INT16,w.INT8,w.UINT64,w.UINT32,w.UINT16,w.UINT8,w.TIMESTAMP,w.UUID,w.STRING,w.JSON]),v(w,"BIG_INT_TYPES",[w.INT64,w.UINT64,w.TIMESTAMP]),v(w,"z",i.z.union([i.z.string().transform(r=>new w(r)),i.z.instanceof(w)]));let F=w;const oe=class X extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return X.bytes(this.valueOf()+e.valueOf())}sub(e){return X.bytes(this.valueOf()-e.valueOf())}truncate(e){return new X(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return X.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/X.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/X.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/X.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/X.TERABYTE.valueOf()}toString(){const e=this.truncate(X.TERABYTE),t=this.truncate(X.GIGABYTE),s=this.truncate(X.MEGABYTE),n=this.truncate(X.KILOBYTE),a=this.truncate(X.BYTE),o=e,c=t.sub(e),l=s.sub(t),d=n.sub(s),f=a.sub(n);let h="";return o.isZero||(h+=`${o.terabytes}TB `),c.isZero||(h+=`${c.gigabytes}GB `),l.isZero||(h+=`${l.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new X(e)}static kilobytes(e=1){return X.bytes(e.valueOf()*1e3)}static megabytes(e=1){return X.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return X.megabytes(e.valueOf()*1e3)}static terabytes(e){return X.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};v(oe,"BYTE",new oe(1)),v(oe,"KILOBYTE",oe.kilobytes(1)),v(oe,"MEGABYTE",oe.megabytes(1)),v(oe,"GIGABYTE",oe.gigabytes(1)),v(oe,"TERABYTE",oe.terabytes(1)),v(oe,"ZERO",new oe(0)),v(oe,"z",i.z.union([i.z.number().transform(r=>new oe(r)),i.z.instanceof(oe)]));let Tn=oe;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Co=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof K||r instanceof W||r instanceof Date},vd=(r,e,t,s=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(s):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(s.valueOf()):$t(t,-s).valueOf(),Od=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof zd?!0:Co(r),Le=-1,Td=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Sd=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Sn=10,Rt=class Ae{constructor(e){v(this,"key",""),v(this,"isSynnaxSeries",!0),v(this,"dataType"),v(this,"sampleOffset"),v(this,"gl"),v(this,"_data"),v(this,"_timeRange"),v(this,"alignment",0n),v(this,"_cachedMin"),v(this,"_cachedMax"),v(this,"writePos",Le),v(this,"_refCount",0),v(this,"_cachedLength"),v(this,"_cachedIndexes"),Od(e)&&(e={data:e});const{dataType:t,timeRange:s,sampleOffset:n=0,glBufferUsage:a="static",alignment:o=0n,key:c=wd()}=e,l=e.data??[];if(l instanceof Ae||typeof l=="object"&&"isSynnaxSeries"in l&&l.isSynnaxSeries===!0){const h=l;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this._timeRange=h._timeRange,this.alignment=h.alignment,this._cachedMin=h._cachedMin,this._cachedMax=h._cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this._cachedLength=h._cachedLength;return}const d=Co(l),f=Array.isArray(l);if(t!=null)this.dataType=new F(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let h=l;if(!d){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");h=l[0]}if(typeof h=="string")this.dataType=F.STRING;else if(typeof h=="number")this.dataType=F.FLOAT64;else if(typeof h=="bigint")this.dataType=F.INT64;else if(typeof h=="boolean")this.dataType=F.BOOLEAN;else if(h instanceof K||h instanceof Date||h instanceof K)this.dataType=F.TIMESTAMP;else if(typeof h=="object")this.dataType=F.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new F(l)}if(!f&&!d)this._data=l;else{let h=d?[l]:l;const I=h[0];(I instanceof K||I instanceof Date||I instanceof W)&&(h=h.map(j=>new K(j).valueOf())),this.dataType.equals(F.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(`${h.join(`
18
- `)}
19
- `).buffer):this.dataType.equals(F.JSON)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(`${h.map(j=>kr.encodeString(j)).join(`
20
- `)}
21
- `).buffer):this._data=new this.dataType.Array(h).buffer}this.key=c,this.alignment=o,this.sampleOffset=n??0,this._timeRange=s,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...s}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const n=new new F(t).Array(e),a=new Ae({data:n.buffer,dataType:t,...s});return a.writePos=0,a}static generateTimestamps(e,t,s){const n=s.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(s.add(t.span(o)).valueOf());return new Ae({data:a,dataType:F.TIMESTAMP,timeRange:n})}get refCount(){return this._refCount}static fromStrings(e,t){const s=new TextEncoder().encode(`${e.join(`
22
- `)}
23
- `);return new Ae({data:s,dataType:F.STRING,timeRange:t})}static fromJSON(e,t){const s=new TextEncoder().encode(`${e.map(n=>kr.encodeString(n)).join(`
24
- `)}
25
- `);return new Ae({data:s,dataType:F.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Le)return 0;const t=this.byteCapacity.valueOf()-this.writePos,s=e.subBytes(0,t);return this.writeToUnderlyingData(s),this.writePos+=s.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=s.length,this.calculateCachedLength()),s.length}writeFixed(e){if(this.writePos===Le)return 0;const t=this.capacity-this.writePos,s=e.sub(0,t);return this.writeToUnderlyingData(s),this._cachedLength=void 0,this.maybeRecomputeMinMax(s),this.writePos+=s.length,s.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Le?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(F.STRING,F.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
26
- `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(F.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=F.UUID.density.valueOf(),t=Array(this.length);for(let s=0;s<this.length;s++){const n=this.underlyingData.slice(s*e,(s+1)*e),a=Array.from(new Uint8Array(n.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[s]=a}return t}parseJSON(e){if(!this.dataType.equals(F.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
27
- `).slice(0,-1).map(t=>e.parse(kr.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Tn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Le?this.byteCapacity:this.dataType.isVariable?new Tn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Le?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((s,n)=>{s===Sn&&(e++,t.push(n+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const s=new e.Array(this.length);for(let n=0;n<this.length;n++)s[n]=vd(this.dataType,e,this.data[n],t);return new Ae({data:s.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(F.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,s)=>t>s?t:s)}else{const e=this.data;this._cachedMax=e.reduce((t,s)=>t>s?t:s)}return this._cachedMax}get max(){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._cachedMax=this.calcRawMax()),$t(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(F.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,s)=>t<s?t:s)}else{const e=this.data;this._cachedMin=e.reduce((t,s)=>t<s?t:s)}return this._cachedMin}get min(){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._cachedMin=this.calcRawMin()),$t(this._cachedMin,this.sampleOffset))}get bounds(){return Xe(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return $t(this.max,-this.min)}atAlignment(e,t){const s=Number(e-this.alignment);if(s<0||s>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${s}`);return}return this.at(s,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const s=this.data[e];if(s==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return $t(s,this.sampleOffset)}atVariable(e,t){let s=0,n=0;if(this._cachedIndexes!=null)s=this._cachedIndexes[e],n=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]===Sn){if(e===0){n=o;break}s=o+1,e--}if(n===0&&(n=this.data.length),s>=n||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(s,n);return this.dataType.equals(F.STRING)?new TextDecoder().decode(a):Oo(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,s=this.length-1;const n=jh(e);for(;t<=s;){const a=Math.floor((t+s)/2),o=n(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:s=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(F.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:s,prevBuffer:n}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==n)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Le){n===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(n).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,s==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Le}as(e){if(e==="string"){if(!this.dataType.equals(F.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(F.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Zi(this.alignmentBounds.lower),upper:Zi(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return Xe(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Ed(this);return this.dataType.equals(F.JSON)?new Nd(e):e}return new Id(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Fi(this,e,t??this.length)}subAlignmentIterator(e,t){return new Fi(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const s=this.data.subarray(e,t);return new Ae({data:s,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,s){if(t<=0&&(s==null||s>=this.length))return this;let n;return e?n=this.data.subarray(t,s):n=this.data.slice(t,s),new Ae({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new Ae({data:this.buffer,dataType:this.dataType,timeRange:Kn.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};v(Rt,"crudeZ",i.z.object({timeRange:Kn.z.optional(),dataType:F.z,alignment:fd.optional(),data:i.z.union([Td,Sd,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:bd.optional().default("static").optional()})),v(Rt,"z",Rt.crudeZ.transform(r=>new Rt(r)));let zd=Rt;class Fi{constructor(e,t,s){v(this,"series"),v(this,"end"),v(this,"index"),this.series=e;const n=Xe(0,e.length);this.end=ji(n,s),this.index=ji(n,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}class Ed{constructor(e){if(v(this,"series"),v(this,"index"),v(this,"decoder"),!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,t=this.series.data;for(;this.index<t.length&&t[this.index]!==Sn;)this.index++;const s=this.index;return e===s?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,s))})}[Symbol.iterator](){return this}}var qi,Gi;class Nd{constructor(e){v(this,"wrapped"),v(this,qi,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:kr.decodeString(e.value)}}[(Gi=Symbol.iterator,qi=Symbol.toStringTag,Gi)](){return this}}var Vi,Wi;class Id{constructor(e){v(this,"series"),v(this,"index"),v(this,Vi,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Wi=Symbol.iterator,Vi=Symbol.toStringTag,Wi)](){return this}}const $t=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e),Zi=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};i.z.object({key:i.z.string(),value:i.z.string()});i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const Ro=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",xd=Ro(),$o=["MacOS","Windows","Linux","Docker"],Ad=["macos","windows","linux","docker"],kd={macos:"MacOS",windows:"Windows",linux:"Linux",docker:"Docker"},Cd=i.z.enum($o).or(i.z.enum(Ad).transform(r=>kd[r]));let Ps;const Rd=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},$d=(r={})=>{const{force:e,default:t}=r;return e??Ps??(Ps=Rd(),Ps??t)},Mo=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:$o,RUNTIME:xd,detect:Ro,getOS:$d,osZ:Cd},Symbol.toStringTag,{value:"Module"}));var Md=Object.defineProperty,Dd=(r,e,t)=>e in r?Md(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Mt=(r,e,t)=>Dd(r,typeof e!="symbol"?e+"":e,t);const Bd=(...r)=>r.map(Do).join(""),Do=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),jd=r=>r.endsWith("/")?r.slice(0,-1):r,Pd=(r,e="")=>r===null?"":`?${Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,s])=>`${e}${t}=${s}`).join("&")}`,zn=class En{constructor({host:e,port:t,protocol:s="",pathPrefix:n=""}){Mt(this,"protocol"),Mt(this,"host"),Mt(this,"port"),Mt(this,"path"),this.protocol=s,this.host=e,this.port=t,this.path=Do(n)}replace(e){return new En({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new En({...this,pathPrefix:Bd(this.path,e)})}toString(){return jd(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Mt(zn,"UNKNOWN",new zn({host:"unknown",port:0}));let Ud=zn;var Ld=Object.defineProperty,_d=(r,e,t)=>e in r?Ld(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$r=(r,e,t)=>_d(r,typeof e!="symbol"?e+"":e,t);const Yd=async r=>await new Promise(e=>setTimeout(e,W.fromMilliseconds(r).milliseconds)),Fd=i.z.object({interval:W.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),qd=(r={})=>{const e=r.sleepFn||Yd,t=r.maxRetries??5,s=r.scale??1;let n=0,a=new W(r.interval??W.milliseconds(1));return async()=>n>=t?!1:(await e(a),a=a.mult(s),n++,!0)},Gd=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:Fd,create:qd},Symbol.toStringTag,{value:"Module"})),tt=class extends Number{};$r(tt,"Absolute",255),$r(tt,"Default",1),$r(tt,"z",i.z.union([i.z.instanceof(tt),i.z.number().int().min(0).max(255).transform(r=>new tt(r)),i.z.instanceof(Number).transform(r=>new tt(r))]));i.z.object({name:i.z.string(),key:i.z.string()});const Bo=class Dt extends Error{constructor(){super(Dt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Dt.MESSAGE):e instanceof Dt||e.message.includes(Dt.MESSAGE)}};$r(Bo,"MESSAGE","canceled");let Vd=Bo;new Vd;i.z.string().regex(/^\d+\.\d+\.\d+$/);const pe=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);let Se=class extends Error{constructor(){super(...arguments),B(this,"discriminator","FreighterError"),B(this,"type","")}};const Wd=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},Ki="unknown",Ji="nil",Zd="freighter",or=i.z.object({type:i.z.string(),data:i.z.string()});class Kd{constructor(){B(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Ji,data:""};if(Wd(e))for(const t of this.providers){const s=t.encode(e);if(s!=null)return s}return{type:Ki,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Ji)return null;if(e.type===Ki)return new Hi(e.data);for(const t of this.providers){const s=t.decode(e);if(s!=null)return s}return new Hi(e.data)}}const jo=new Kd,Po=({encode:r,decode:e})=>jo.register({encode:r,decode:e}),as=r=>jo.decode(r);class Hi extends Se{constructor(){super(...arguments),B(this,"type","unknown")}}const ms="freighter.",Mr=class Uo extends Se{constructor(){super("EOF"),B(this,"type",Uo.TYPE)}};B(Mr,"TYPE",`${ms}eof`),B(Mr,"matches",pe(Mr.TYPE));let qe=Mr;const Dr=class Lo extends Se{constructor(){super("StreamClosed"),B(this,"type",Lo.TYPE)}};B(Dr,"TYPE",`${ms}stream_closed`),B(Dr,"matches",pe(Dr.TYPE));let ot=Dr;const Br=class _o extends Se{constructor(e={}){const{message:t="Unreachable",url:s=Ud.UNKNOWN}=e;super(t),B(this,"type",_o.TYPE),B(this,"url"),this.url=s}};B(Br,"TYPE",`${ms}unreachable`),B(Br,"matches",pe(Br.TYPE));let Ge=Br;const Jd=r=>{if(!r.type.startsWith(Zd))return null;if(qe.matches(r))return{type:qe.TYPE,data:"EOF"};if(ot.matches(r))return{type:ot.TYPE,data:"StreamClosed"};if(Ge.matches(r))return{type:Ge.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Hd=r=>{if(!r.type.startsWith(ms))return null;switch(r.type){case qe.TYPE:return new qe;case ot.TYPE:return new ot;case Ge.TYPE:return new Ge;default:throw new Error(`Unknown error type: ${r.data}`)}};Po({encode:Jd,decode:Hd});let Yo=class{constructor(){B(this,"middleware",[])}use(...r){this.middleware.push(...r)}async executeMiddleware(r,e){let t=0;const s=async n=>{if(t===this.middleware.length)return await e(n);const a=this.middleware[t];return t++,await a(n,s)};return await s(r)}};const Fo="Content-Type",Xi=r=>{if(Mo.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),s=new t.Agent({rejectUnauthorized:!1});return async(n,a)=>await e(n,{...a,agent:s})};class Xd extends Yo{constructor(e,t,s=!1){return super(),B(this,"endpoint"),B(this,"encoder"),B(this,"fetch"),this.endpoint=e.replace({protocol:s?"https":"http"}),this.encoder=t,this.fetch=Xi(this.endpoint.protocol),new Proxy(this,{get:(n,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(n,a,o)})}get headers(){return{[Fo]:this.encoder.contentType}}async send(e,t,s,n){t=s==null?void 0:s.parse(t);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(t??{});const[,l]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async d=>{const f={...d,params:{}};c.headers={...this.headers,...d.params};let h;try{h=await Xi(d.protocol)(d.target,c)}catch(j){let ie=j;return ie.message==="Load failed"&&(ie=new Ge({url:o})),[f,ie]}const I=await h.arrayBuffer();if(h!=null&&h.ok)return n!=null&&(a=this.encoder.decode(I,n)),[f,null];try{if(h.status!==400)return[f,new Error(h.statusText)];const j=this.encoder.decode(I,or),ie=as(j);return[f,ie]}catch(j){return[f,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${j.message}`)]}});return[a,l]}}const Qd=(r,e)=>{class t{constructor(n){B(this,"wrapped"),this.wrapped=n}use(...n){this.wrapped.use(...n)}async send(n,a,o,c){const l=Gd.create(e);do{const[d,f]=await this.wrapped.send(n,a,o,c);if(f==null||!Ge.matches(f))return[d,f];if(!await l())return[d,f]}while(!0)}}return new t(r)},O=async(r,e,t,s,n)=>{const[a,o]=await r.send(e,t,s,n);if(o!=null)throw o;return a},ef=()=>Mo.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),tf=i.z.object({type:i.z.union([i.z.literal("data"),i.z.literal("close"),i.z.literal("open")]),payload:i.z.unknown().optional(),error:i.z.optional(or)});class rf{constructor(e,t,s,n){B(this,"encoder"),B(this,"reqSchema"),B(this,"resSchema"),B(this,"ws"),B(this,"serverClosed"),B(this,"sendClosed"),B(this,"receiveDataQueue",[]),B(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=s,this.resSchema=n,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 as(e.error)}return null}send(e){if(this.serverClosed!=null)return new qe;if(this.sendClosed)throw new ot;return this.ws.send(this.encoder.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");return this.serverClosed=as(e.error),[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.encoder.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((e,t)=>this.receiveCallbacksQueue.push({resolve:e,reject:t}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,tf)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:lf(e)?qe.TYPE:ot.TYPE,data:""}})}}const sf="freighterctx",nf=1e3,af=1001,of=[nf,af],lf=r=>of.includes(r.code),qo=class Go extends Yo{constructor(e,t,s=!1){super(),B(this,"baseUrl"),B(this,"encoder"),this.baseUrl=e.replace({protocol:s?"wss":"ws"}),this.encoder=t}async stream(e,t,s){const n=ef();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async c=>{const l=n(this.buildURL(e,c)),d={...c,params:{}};l.binaryType=Go.MESSAGE_TYPE;const f=await this.wrapSocket(l,t,s);return f instanceof Error?[d,f]:(a=f,[d,null])});if(o!=null)throw o;return a}buildURL(e,t){const s=Pd({[Fo]:this.encoder.contentType,...t.params},sf);return this.baseUrl.child(e).toString()+s}async wrapSocket(e,t,s){return await new Promise(n=>{e.onopen=()=>{const a=new rf(e,this.encoder,t,s);a.receiveOpenAck().then(o=>{o!=null?n(o):n(a)}).catch(o=>n(o))},e.onerror=a=>{const o=a;n(new Error(o.message))}})}};B(qo,"MESSAGE_TYPE","arraybuffer");let cf=qo;const Nn=i.z.union([i.z.literal("all"),i.z.literal("create"),i.z.literal("delete"),i.z.literal("retrieve"),i.z.literal("update")]),uf=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Vo=r=>{const e=(t,s=In)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,s));if(!Us(t))return t;s=ff(s);const n={},a=t;return Object.keys(a).forEach(o=>{let c=a[o];const l=r(o);s.recursive&&(Us(c)?ea(c,s.keepTypesOnRecursion)||(c=e(c,s)):s.recursiveInArray&&Qi(c)&&(c=[...c].map(d=>{let f=d;return Us(d)?ea(f,s.keepTypesOnRecursion)||(f=e(d,s)):Qi(d)&&(f=e({key:d},s).key),f}))),n[l]=c}),n};return e},Wo=Vo(uf),hf=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,s)=>`${t}_${s.toLowerCase()}`),df=Vo(hf),In={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},ff=(r=In)=>(r.recursive==null?r=In:r.recursiveInArray??(r.recursiveInArray=!1),r),Qi=r=>r!=null&&Array.isArray(r),Us=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),ea=(r,e)=>(e||[]).some(t=>r instanceof t),Jn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var pf=Object.defineProperty,gf=(r,e,t)=>e in r?pf(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Zt=(r,e,t)=>gf(r,typeof e!="symbol"?e+"":e,t);let Zo=class{constructor(){Zt(this,"contentType","application/json"),Zt(this,"decoder"),Zt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r)).buffer}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),s=Wo(t);return e!=null?e.parse(s):s}encodeString(r){const e=df(r);return JSON.stringify(e,(t,s)=>ArrayBuffer.isView(s)?Array.from(s):Jn(s)&&"encode_value"in s?typeof s.value=="bigint"?s.value.toString():s.value:typeof s=="bigint"?s.toString():s)}static registerCustomType(){}},Ko=class{constructor(){Zt(this,"contentType","text/csv")}encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e).buffer}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!Jn(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(s=>{const n=e.map(a=>JSON.stringify(s[a]??""));t.push(n.join(","))}),t.join(`
28
- `)}decodeString(r,e){const[t,...s]=r.trim().split(`
29
- `).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const n=t.split(",").map(o=>o.trim()),a={};return n.forEach(o=>{a[o]=[]}),s.forEach(o=>{const c=o.split(",").map(l=>l.trim());n.forEach((l,d)=>{const f=this.parseValue(c[d]);f!=null&&a[l].push(f)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},Jo=class{constructor(){Zt(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r).buffer}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const it=new Zo,yf=new Ko,mf=new Jo,wf=[it],pt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ko,CSV_CODEC:yf,ENCODERS:wf,JSONCodec:Zo,JSON_CODEC:it,TEXT_CODEC:mf,TextCodec:Jo},Symbol.toStringTag,{value:"Module"})),ta=r=>[...new Set(r)],bf=r=>r!=null&&typeof r=="object"&&"toString"in r,vf=(r,e=!1)=>{const t=bf(r)?"stringer":typeof r;let s;switch(t){case"string":s=(n,a)=>n.localeCompare(a);break;case"stringer":s=(n,a)=>n.toString().localeCompare(a.toString());break;case"number":s=(n,a)=>Number(n)-Number(a);break;case"bigint":s=(n,a)=>BigInt(n)-BigInt(a)>0n?1:-1;break;case"boolean":s=(n,a)=>Number(n)-Number(a);break;case"undefined":s=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Of(s):s},Of=r=>(e,t)=>r(t,e),ws=0,Ls=-1,_s=1,Tf=r=>r<ws,Sf=r=>r>ws,zf=r=>r===ws,bs=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const Ho=i.z.object({width:i.z.number(),height:i.z.number()}),Ef=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),Nf=["width","height"];i.z.enum(Nf);const If=["start","center","end"],xf=["signedWidth","signedHeight"];i.z.enum(xf);const os=i.z.object({x:i.z.number(),y:i.z.number()}),Af=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),kf=["x","y"],Xo=i.z.enum(kf),Qo=["top","right","bottom","left"];i.z.enum(Qo);const Cf=["left","right"],el=i.z.enum(Cf),Rf=["top","bottom"],tl=i.z.enum(Rf),rl=["center"],ra=i.z.enum(rl),$f=[...Qo,...rl],sl=i.z.enum($f);i.z.enum(If);const Mf=["first","last"];i.z.enum(Mf);const Df=i.z.object({lower:i.z.number(),upper:i.z.number()}),Bf=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([Df,bs]);i.z.union([Bf,bs]);i.z.union([Xo,sl]);i.z.union([Xo,sl,i.z.instanceof(String)]);const gt=r=>typeof r=="bigint"||r instanceof BigInt,Ys=(r,e)=>gt(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),jf=(r,e)=>gt(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),sa=(r,e)=>gt(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),Pf=(r,e)=>gt(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),Uf=r=>gt(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,rt=(r,e)=>gt(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),de=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return na(r);return na(t)},na=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,ia=(r,e)=>{const t=de(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},wr=(r,e)=>{const t=de(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const s=de(e);return s.lower>=t.lower&&s.upper<=t.upper},Lf=(r,e,t)=>{const s=r.map(c=>de(c)),n=t>0?1:t<0?-1:0;if(n===0)return e;let a=t,o=e;for(;sa(a,0)===!1;){const c=s.findIndex(l=>n>0?o>=l.lower&&o<l.upper:o>l.lower&&o<=l.upper);if(c!==-1){const l=s[c];let d;if(n>0?d=Ys(l.upper,o):d=Ys(o,l.lower),d>0){const f=Pf(Uf(a),d);if(o=jf(o,n>0?f:-f),a=Ys(a,n>0?f:-f),sa(a,0))return o;continue}}if(n>0){const l=s.filter(d=>d.lower>o);if(l.length>0)o=l[0].lower;else return o}else{const l=s.filter(d=>d.upper<o);if(l.length>0)o=l[l.length-1].upper;else return o}}return o},_f=(r,e,t)=>{const s=r.map(o=>de(o));if(e===t)return typeof e=="bigint"?0n:0;const n=e<t?de([e,t]):de([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of s){const c=o.lower>n.lower?o.lower:n.lower,l=o.upper<n.upper?o.upper:n.upper;if(c<l){const d=l-c;a=a+d}}return a};i.z.object({x:el.or(ra),y:tl.or(ra)});const Yf=i.z.object({x:el,y:tl}),Ff=Object.freeze({x:"left",y:"top"}),qf=(r,e)=>r.x===e.x&&r.y===e.y,aa=i.z.union([i.z.number(),os,bs,Ho,Ef,Af]),Gf=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},oa=Object.freeze({x:0,y:0}),br=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:br,left:br,width:br,height:br});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:os,two:os,root:Yf});const Hn=(r,e,t=0,s=0,n)=>{const a={one:{...oa},two:{...oa},root:n??Ff};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+s},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:n??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+s}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},Fs=r=>{const e=Hn(r);return{lower:e.one.x,upper:e.two.x}},qs=r=>{const e=Hn(r);return{lower:e.one.y,upper:e.two.y}},Vf=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Wf=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Ho,Wf,os,bs]);var Zf=Object.defineProperty,Kf=(r,e,t)=>e in r?Zf(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,je=(r,e,t)=>Kf(r,typeof e!="symbol"?e+"":e,t);const Jf=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;i.z.object({offset:aa,scale:aa});i.z.object({offset:i.z.number(),scale:i.z.number()});const Hf=r=>(e,t,s,n)=>t==="dimension"?[e,s]:[e,n?s-r:s+r],Xf=r=>(e,t,s,n)=>[e,n?s/r:s*r],Qf=r=>(e,t,s)=>{if(e===null)return[r,s];const{lower:n,upper:a}=e,{lower:o,upper:c}=r,l=a-n,d=c-o;if(t==="dimension")return[r,s*(d/l)];const f=(s-n)*(d/l)+o;return[r,f]},ep=r=>(e,t,s)=>[r,s],tp=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:s,upper:n}=r;return[r,n-(t-s)]},rp=r=>(e,t,s)=>{const{lower:n,upper:a}=r;return s=Jf(s,n,a),[e,s]},xn=class Bt{constructor(){je(this,"ops",[]),je(this,"currBounds",null),je(this,"currType",null),je(this,"reversed",!1),this.ops=[]}static translate(e){return new Bt().translate(e)}static magnify(e){return new Bt().magnify(e)}static scale(e,t){return new Bt().scale(e,t)}translate(e){const t=this.new(),s=Hf(e);return s.type="translate",t.ops.push(s),t}magnify(e){const t=this.new(),s=Xf(e);return s.type="magnify",t.ops.push(s),t}scale(e,t){const s=de(e,t),n=this.new(),a=Qf(s);return a.type="scale",n.ops.push(a),n}clamp(e,t){const s=de(e,t),n=this.new(),a=rp(s);return a.type="clamp",n.ops.push(a),n}reBound(e,t){const s=de(e,t),n=this.new(),a=ep(s);return a.type="re-bound",n.ops.push(a),n}invert(){const e=tp();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Bt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([s,n],a)=>a(s,e,n,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((s,n)=>{if(s.type==="scale"||t.some(([o,c])=>n>=o&&n<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>n);a!==-1&&t.push([n,a])}),t.forEach(([s,n])=>{const a=e.ops.slice(s,n);a.unshift(e.ops[n]),e.ops.splice(s,n-s+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};je(xn,"IDENTITY",new xn);let la=xn;const ca=class De{constructor(e=new la,t=new la,s=null){je(this,"x"),je(this,"y"),je(this,"currRoot"),this.x=e,this.y=t,this.currRoot=s}static translate(e,t){return new De().translate(e,t)}static translateX(e){return new De().translateX(e)}static translateY(e){return new De().translateY(e)}static clamp(e){return new De().clamp(e)}static magnify(e){return new De().magnify(e)}static scale(e){return new De().scale(e)}static reBound(e){return new De().reBound(e)}translate(e,t){const s=Gf(e,t),n=this.copy();return n.x=this.x.translate(s.x),n.y=this.y.translate(s.y),n}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Vf(e)){const s=this.currRoot;return t.currRoot=e.root,s!=null&&!qf(s,e.root)&&(s.x!==e.root.x&&(t.x=t.x.invert()),s.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Fs(e)),t.y=t.y.scale(qs(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Fs(e)),t.y=this.y.reBound(qs(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Fs(e)),t.y=this.y.clamp(qs(e)),t}copy(){const e=new De;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 Hn(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})}}};je(ca,"IDENTITY",new ca);const sp=i.z.bigint().or(i.z.string().transform(BigInt));var np=Object.defineProperty,ip=(r,e,t)=>e in r?np(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e,t)=>ip(r,typeof e!="symbol"?e+"":e,t);let ap=(r,e=21)=>(t=e)=>{let s="",n=t|0;for(;n--;)s+=r[Math.random()*r.length|0];return s};const op="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nl=ap(op,11),lp=Object.freeze(Object.defineProperty({__proto__:null,id:nl},Symbol.toStringTag,{value:"Module"})),cp=i.z.enum(["static","dynamic"]),il=(r,e)=>{const t=new R(e);if(![x.DAY,x.HOUR,x.MINUTE,x.SECOND,x.MILLISECOND,x.MICROSECOND,x.NANOSECOND].some(n=>n.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const s=r.valueOf()%t.valueOf();return r instanceof R?new R(s):new x(s)},q=class N{constructor(e,t="UTC"){if(y(this,"value"),y(this,"encodeValue",!0),e==null)this.value=N.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*N.MILLISECOND.valueOf();else if(typeof e=="string")this.value=N.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=N.parseDate(e);else{let s=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(s=N.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=N.MAX:e=N.MIN)),this.value=BigInt(e.valueOf())+s}}static parseDate([e=1970,t=1,s=1]){const n=new Date(e,t-1,s,0,0,0,0);return new N(BigInt(n.getTime())*N.MILLISECOND.valueOf()).truncate(N.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[s,n,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let l=N.hours(parseInt(s??"00")).add(N.minutes(parseInt(n??"00"))).add(N.seconds(parseInt(o??"00"))).add(N.milliseconds(parseInt(c??"00")));return t==="local"&&(l=l.add(N.utcOffset)),l.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return N.parseTimeString(e,t);const s=new Date(e);return e.includes(":")||s.setUTCHours(0,0,0,0),new N(BigInt(s.getTime())*N.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(N.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const s=this.toISOString(t);return e?s.slice(11,23):s.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),s=e.toLocaleString("default",{day:"numeric"});return`${t} ${s}`}static get utcOffset(){return new x(BigInt(new Date().getTimezoneOffset())*N.MINUTE.valueOf())}static since(e){return new N().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new N(e).valueOf()}span(e){return this.range(e).span}range(e){return new ne(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new N(e).valueOf()}afterEq(e){return this.valueOf()>=new N(e).valueOf()}before(e){return this.valueOf()<new N(e).valueOf()}beforeEq(e){return this.valueOf()<=new N(e).valueOf()}add(e){return new N(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new N(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(x.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(x.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(x.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(x.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new N(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new N(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new N(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new N(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new N(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new N(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new N(t)}toString(){return this.date().toISOString()}remainder(e){return il(this,e)}get isToday(){return this.truncate(x.DAY).equals(N.now().truncate(x.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new N(new Date)}static max(...e){let t=N.MIN;for(const s of e){const n=new N(s);n.after(t)&&(t=n)}return t}static min(...e){let t=N.MAX;for(const s of e){const n=new N(s);n.before(t)&&(t=n)}return t}static nanoseconds(e){return new N(e)}static microseconds(e){return N.nanoseconds(e*1e3)}static milliseconds(e){return N.microseconds(e*1e3)}static seconds(e){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.hours(e*24)}};y(q,"NANOSECOND",q.nanoseconds(1)),y(q,"MICROSECOND",q.microseconds(1)),y(q,"MILLISECOND",q.milliseconds(1)),y(q,"SECOND",q.seconds(1)),y(q,"MINUTE",q.minutes(1)),y(q,"HOUR",q.hours(1)),y(q,"DAY",q.days(1)),y(q,"MAX",new q((1n<<63n)-1n)),y(q,"MIN",new q(0)),y(q,"ZERO",new q(0)),y(q,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new q(r.value)),i.z.string().transform(r=>new q(BigInt(r))),i.z.instanceof(Number).transform(r=>new q(r)),i.z.number().transform(r=>new q(r)),i.z.instanceof(q)]));let R=q;const G=class C{constructor(e){y(this,"value"),y(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof C?e:e instanceof Xt?e.period:e instanceof R?new C(e):["number","bigint"].includes(typeof e)?C.seconds(e):new C(e)}static fromMilliseconds(e){return e instanceof C?e:e instanceof Xt?e.period:e instanceof R?new C(e):["number","bigint"].includes(typeof e)?C.milliseconds(e):new C(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new C(e).valueOf()}greaterThan(e){return this.valueOf()>new C(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new C(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new C(e).valueOf()}remainder(e){return il(this,e)}truncate(e){return new C(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(C.DAY),t=this.truncate(C.HOUR),s=this.truncate(C.MINUTE),n=this.truncate(C.SECOND),a=this.truncate(C.MILLISECOND),o=this.truncate(C.MICROSECOND),c=this.truncate(C.NANOSECOND),l=e,d=t.sub(e),f=s.sub(t),h=n.sub(s),I=a.sub(n),j=o.sub(a),ie=c.sub(o);let P="";return l.isZero||(P+=`${l.days}d `),d.isZero||(P+=`${d.hours}h `),f.isZero||(P+=`${f.minutes}m `),h.isZero||(P+=`${h.seconds}s `),I.isZero||(P+=`${I.milliseconds}ms `),j.isZero||(P+=`${j.microseconds}µs `),ie.isZero||(P+=`${ie.nanoseconds}ns`),P.trim()}mult(e){return new C(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(C.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(C.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(C.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(C.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(C.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(C.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new C(e).valueOf()}add(e){return new C(this.valueOf()+new C(e).valueOf())}sub(e){return new C(this.valueOf()-new C(e).valueOf())}static nanoseconds(e=1){return new C(e)}static microseconds(e=1){return C.nanoseconds(rt(e,1e3))}static milliseconds(e=1){return C.microseconds(rt(e,1e3))}static seconds(e=1){return C.milliseconds(rt(e,1e3))}static minutes(e=1){return C.seconds(rt(e,60))}static hours(e){return C.minutes(rt(e,60))}static days(e){return C.hours(rt(e,24))}};y(G,"NANOSECOND",G.nanoseconds(1)),y(G,"MICROSECOND",G.microseconds(1)),y(G,"MILLISECOND",G.milliseconds(1)),y(G,"SECOND",G.seconds(1)),y(G,"MINUTE",G.minutes(1)),y(G,"HOUR",G.hours(1)),y(G,"DAY",G.days(1)),y(G,"MAX",new G((1n<<63n)-1n)),y(G,"MIN",new G(0)),y(G,"ZERO",new G(0)),y(G,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new G(r.value)),i.z.string().transform(r=>new G(BigInt(r))),i.z.instanceof(Number).transform(r=>new G(r)),i.z.number().transform(r=>new G(r)),i.z.instanceof(G)]));let x=G;const jt=class jr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new jr(e).valueOf()}get period(){return x.seconds(1/this.valueOf())}sampleCount(e){return new x(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new he(t).valueOf()}span(e){return x.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new jr(e)}static khz(e){return jr.hz(e*1e3)}};y(jt,"z",i.z.union([i.z.number().transform(r=>new jt(r)),i.z.instanceof(Number).transform(r=>new jt(r)),i.z.instanceof(jt)]));let Xt=jt;const se=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new lt(e*this.valueOf())}};y(se,"UNKNOWN",new se(0)),y(se,"BIT128",new se(16)),y(se,"BIT64",new se(8)),y(se,"BIT32",new se(4)),y(se,"BIT16",new se(2)),y(se,"BIT8",new se(1)),y(se,"z",i.z.union([i.z.number().transform(r=>new se(r)),i.z.instanceof(Number).transform(r=>new se(r)),i.z.instanceof(se)]));let he=se;const ke=class Pr{constructor(e,t){y(this,"start"),y(this,"end"),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(t))}get span(){return new x(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Pr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=x.ZERO){e=e.makeValid();const s=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(s.start)||s.end.equals(e.start))return!1;const n=R.max(s.start,e.start),a=R.min(s.end,e.end);return a.before(n)?!1:new x(a.sub(n)).greaterThanOrEqual(t)}roughlyEquals(e,t){let s=this.start.sub(e.start).valueOf(),n=this.end.sub(e.end).valueOf();return s<0&&(s=-s),n<0&&(n=-n),s<=t.valueOf()&&n<=t.valueOf()}contains(e){return e instanceof Pr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Pr(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}};y(ke,"MAX",new ke(R.MIN,R.MAX)),y(ke,"MIN",new ke(R.MAX,R.MIN)),y(ke,"ZERO",new ke(R.ZERO,R.ZERO)),y(ke,"z",i.z.union([i.z.object({start:R.z,end:R.z}).transform(r=>new ke(r.start,r.end)),i.z.instanceof(ke)]));let ne=ke;const up=(r,e)=>r.start.before(e.start)?-1:r.start.after(e.start)?1:r.end.before(e.end)?-1:r.end.after(e.end)?1:0,b=class Ce extends String{constructor(e){if(e instanceof Ce||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=Ce.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(Ce.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=Ce.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(Ce.JSON)||this.equals(Ce.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Ce.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Ce.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return Ce.BIG_INT_TYPES.some(e=>e.equals(this))}};y(b,"UNKNOWN",new b("unknown")),y(b,"FLOAT64",new b("float64")),y(b,"FLOAT32",new b("float32")),y(b,"INT64",new b("int64")),y(b,"INT32",new b("int32")),y(b,"INT16",new b("int16")),y(b,"INT8",new b("int8")),y(b,"UINT64",new b("uint64")),y(b,"UINT32",new b("uint32")),y(b,"UINT16",new b("uint16")),y(b,"UINT8",new b("uint8")),y(b,"BOOLEAN",b.UINT8),y(b,"TIMESTAMP",new b("timestamp")),y(b,"UUID",new b("uuid")),y(b,"STRING",new b("string")),y(b,"JSON",new b("json")),y(b,"ARRAY_CONSTRUCTORS",new Map([[b.UINT8.toString(),Uint8Array],[b.UINT16.toString(),Uint16Array],[b.UINT32.toString(),Uint32Array],[b.UINT64.toString(),BigUint64Array],[b.FLOAT32.toString(),Float32Array],[b.FLOAT64.toString(),Float64Array],[b.INT8.toString(),Int8Array],[b.INT16.toString(),Int16Array],[b.INT32.toString(),Int32Array],[b.INT64.toString(),BigInt64Array],[b.TIMESTAMP.toString(),BigInt64Array],[b.STRING.toString(),Uint8Array],[b.JSON.toString(),Uint8Array],[b.UUID.toString(),Uint8Array]])),y(b,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,b.UINT8],[Uint16Array.name,b.UINT16],[Uint32Array.name,b.UINT32],[BigUint64Array.name,b.UINT64],[Float32Array.name,b.FLOAT32],[Float64Array.name,b.FLOAT64],[Int8Array.name,b.INT8],[Int16Array.name,b.INT16],[Int32Array.name,b.INT32],[BigInt64Array.name,b.INT64]])),y(b,"DENSITIES",new Map([[b.UINT8.toString(),he.BIT8],[b.UINT16.toString(),he.BIT16],[b.UINT32.toString(),he.BIT32],[b.UINT64.toString(),he.BIT64],[b.FLOAT32.toString(),he.BIT32],[b.FLOAT64.toString(),he.BIT64],[b.INT8.toString(),he.BIT8],[b.INT16.toString(),he.BIT16],[b.INT32.toString(),he.BIT32],[b.INT64.toString(),he.BIT64],[b.TIMESTAMP.toString(),he.BIT64],[b.STRING.toString(),he.UNKNOWN],[b.JSON.toString(),he.UNKNOWN],[b.UUID.toString(),he.BIT128]])),y(b,"ALL",[b.UNKNOWN,b.FLOAT64,b.FLOAT32,b.INT64,b.INT32,b.INT16,b.INT8,b.UINT64,b.UINT32,b.UINT16,b.UINT8,b.TIMESTAMP,b.UUID,b.STRING,b.JSON]),y(b,"BIG_INT_TYPES",[b.INT64,b.UINT64,b.TIMESTAMP]),y(b,"z",i.z.union([i.z.string().transform(r=>new b(r)),i.z.instanceof(b)]));let $=b;const le=class Q extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Q.bytes(this.valueOf()+e.valueOf())}sub(e){return Q.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Q(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Q.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Q.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Q.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Q.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Q.TERABYTE.valueOf()}toString(){const e=this.truncate(Q.TERABYTE),t=this.truncate(Q.GIGABYTE),s=this.truncate(Q.MEGABYTE),n=this.truncate(Q.KILOBYTE),a=this.truncate(Q.BYTE),o=e,c=t.sub(e),l=s.sub(t),d=n.sub(s),f=a.sub(n);let h="";return o.isZero||(h+=`${o.terabytes}TB `),c.isZero||(h+=`${c.gigabytes}GB `),l.isZero||(h+=`${l.megabytes}MB `),d.isZero||(h+=`${d.kilobytes}KB `),(!f.isZero||h==="")&&(h+=`${f.valueOf()}B`),h.trim()}static bytes(e=1){return new Q(e)}static kilobytes(e=1){return Q.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Q.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Q.megabytes(e.valueOf()*1e3)}static terabytes(e){return Q.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};y(le,"BYTE",new le(1)),y(le,"KILOBYTE",le.kilobytes(1)),y(le,"MEGABYTE",le.megabytes(1)),y(le,"GIGABYTE",le.gigabytes(1)),y(le,"TERABYTE",le.terabytes(1)),y(le,"ZERO",new le(0)),y(le,"z",i.z.union([i.z.number().transform(r=>new le(r)),i.z.instanceof(le)]));let lt=le;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const al=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof R||r instanceof x||r instanceof Date},hp=(r,e,t,s=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(s):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(s.valueOf()):Ut(t,-s).valueOf(),dp=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Je?!0:al(r),_e=-1,An={[Symbol.iterator]:()=>An,next:()=>({done:!0,value:void 0})},fp=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),pp=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),kn=10,Pt=class Re{constructor(e){y(this,"key",""),y(this,"isSynnaxSeries",!0),y(this,"dataType"),y(this,"sampleOffset"),y(this,"gl"),y(this,"_data"),y(this,"_timeRange"),y(this,"alignment",0n),y(this,"_cachedMin"),y(this,"_cachedMax"),y(this,"writePos",_e),y(this,"_refCount",0),y(this,"_cachedLength"),y(this,"_cachedIndexes"),dp(e)&&(e={data:e});const{dataType:t,timeRange:s,sampleOffset:n=0,glBufferUsage:a="static",alignment:o=0n,key:c=nl()}=e,l=e.data??[];if(l instanceof Re||typeof l=="object"&&"isSynnaxSeries"in l&&l.isSynnaxSeries===!0){const h=l;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this._timeRange=h._timeRange,this.alignment=h.alignment,this._cachedMin=h._cachedMin,this._cachedMax=h._cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this._cachedLength=h._cachedLength;return}const d=al(l),f=Array.isArray(l);if(t!=null)this.dataType=new $(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let h=l;if(!d){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");h=l[0]}if(typeof h=="string")this.dataType=$.STRING;else if(typeof h=="number")this.dataType=$.FLOAT64;else if(typeof h=="bigint")this.dataType=$.INT64;else if(typeof h=="boolean")this.dataType=$.BOOLEAN;else if(h instanceof R||h instanceof Date||h instanceof R)this.dataType=$.TIMESTAMP;else if(typeof h=="object")this.dataType=$.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new $(l)}if(!f&&!d)this._data=l;else{let h=d?[l]:l;const I=h[0];(I instanceof R||I instanceof Date||I instanceof x)&&(h=h.map(j=>new R(j).valueOf())),this.dataType.equals($.STRING)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(`${h.join(`
30
- `)}
31
- `).buffer):this.dataType.equals($.JSON)?(this._cachedLength=h.length,this._data=new TextEncoder().encode(`${h.map(j=>it.encodeString(j)).join(`
32
- `)}
33
- `).buffer):this._data=new this.dataType.Array(h).buffer}this.key=c,this.alignment=o,this.sampleOffset=n??0,this._timeRange=s,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...s}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const n=new new $(t).Array(e),a=new Re({data:n.buffer,dataType:t,...s});return a.writePos=0,a}static generateTimestamps(e,t,s){const n=s.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(s.add(t.span(o)).valueOf());return new Re({data:a,dataType:$.TIMESTAMP,timeRange:n})}get refCount(){return this._refCount}static fromStrings(e,t){const s=new TextEncoder().encode(`${e.join(`
34
- `)}
35
- `);return new Re({data:s,dataType:$.STRING,timeRange:t})}static fromJSON(e,t){const s=new TextEncoder().encode(`${e.map(n=>it.encodeString(n)).join(`
36
- `)}
37
- `);return new Re({data:s,dataType:$.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===_e)return 0;const t=this.byteCapacity.valueOf()-this.writePos,s=e.subBytes(0,t);return this.writeToUnderlyingData(s),this.writePos+=s.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=s.length,this.calculateCachedLength()),s.length}writeFixed(e){if(this.writePos===_e)return 0;const t=this.capacity-this.writePos,s=e.sub(0,t);return this.writeToUnderlyingData(s),this._cachedLength=void 0,this.maybeRecomputeMinMax(s),this.writePos+=s.length,s.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===_e?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches($.STRING,$.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
38
- `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals($.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=$.UUID.density.valueOf(),t=Array(this.length);for(let s=0;s<this.length;s++){const n=this.underlyingData.slice(s*e,(s+1)*e),a=Array.from(new Uint8Array(n.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[s]=a}return t}parseJSON(e){if(!this.dataType.equals($.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
39
- `).slice(0,-1).map(t=>e.parse(it.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new lt(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===_e?this.byteCapacity:this.dataType.isVariable?new lt(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===_e?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((s,n)=>{s===kn&&(e++,t.push(n+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const s=new e.Array(this.length);for(let n=0;n<this.length;n++)s[n]=hp(this.dataType,e,this.data[n],t);return new Re({data:s.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals($.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,s)=>t>s?t:s)}else{const e=this.data;this._cachedMax=e.reduce((t,s)=>t>s?t:s)}return this._cachedMax}get max(){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._cachedMax=this.calcRawMax()),Ut(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals($.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,s)=>t<s?t:s)}else{const e=this.data;this._cachedMin=e.reduce((t,s)=>t<s?t:s)}return this._cachedMin}get min(){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._cachedMin=this.calcRawMin()),Ut(this._cachedMin,this.sampleOffset))}get bounds(){return de(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return Ut(this.max,-this.min)}atAlignment(e,t){const s=Number(e-this.alignment);if(s<0||s>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${s}`);return}return this.at(s,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const s=this.data[e];if(s==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return Ut(s,this.sampleOffset)}atVariable(e,t){let s=0,n=0;if(this._cachedIndexes!=null)s=this._cachedIndexes[e],n=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){n=o;break}s=o+1,e--}if(n===0&&(n=this.data.length),s>=n||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(s,n);return this.dataType.equals($.STRING)?new TextDecoder().decode(a):Wo(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,s=this.length-1;const n=vf(e);for(;t<=s;){const a=Math.floor((t+s)/2),o=n(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:s=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals($.FLOAT32))throw new Error("Only FLOAT32 arrays can be used in WebGL");const{buffer:t,bufferUsage:s,prevBuffer:n}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==n)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==_e){n===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(n).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,s==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=_e}as(e){if(e==="string"){if(!this.dataType.equals($.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals($.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:ma(this.alignmentBounds.lower),upper:ma(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return de(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new gp(this);return this.dataType.equals($.JSON)?new yp(e):e}return new mp(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ua(this,e,t??this.length)}subAlignmentIterator(e,t){return new ua(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const s=this.data.subarray(e,t);return new Re({data:s,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,s){if(t<=0&&(s==null||s>=this.length))return this;let n;return e?n=this.data.subarray(t,s):n=this.data.slice(t,s),new Re({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new Re({data:this.buffer,dataType:this.dataType,timeRange:ne.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};y(Pt,"crudeZ",i.z.object({timeRange:ne.z.optional(),dataType:$.z,alignment:sp.optional(),data:i.z.union([fp,pp,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:cp.optional().default("static").optional()})),y(Pt,"z",Pt.crudeZ.transform(r=>new Pt(r)));let Je=Pt,ua=class{constructor(r,e,t){y(this,"series"),y(this,"end"),y(this,"index"),this.series=r;const s=de(0,r.length);this.end=ia(s,t),this.index=ia(s,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class gp{constructor(e){if(y(this,"series"),y(this,"index"),y(this,"decoder"),!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,t=this.series.data;for(;this.index<t.length&&t[this.index]!==kn;)this.index++;const s=this.index;return e===s?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,s))})}[Symbol.iterator](){return this}}var ha,da;class yp{constructor(e){y(this,"wrapped"),y(this,ha,"JSONSeriesIterator"),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)}}[(da=Symbol.iterator,ha=Symbol.toStringTag,da)](){return this}}var fa,pa;class mp{constructor(e){y(this,"series"),y(this,"index"),y(this,fa,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(pa=Symbol.iterator,fa=Symbol.toStringTag,pa)](){return this}}const Ut=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);class wp{constructor(e){if(y(this,"series"),e.length!==0){const t=e[0].dataType;for(let s=1;s<e.length;s++)if(!e[s].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new $(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?$.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?ne.ZERO:new ne(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?de(0n,0n):de(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const s of this.series)if(wr(s.alignmentBounds,e))return s.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const s of this.series){if(e<s.length)return s.at(e,t);e-=s.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new Gs(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return An;let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)s+=o.length;else if(wr(o.alignmentBounds,e)){s+=Number(e-o.alignment);break}}let n=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)n+=o.length;else if(wr(o.alignmentBounds,t)){n+=Number(t-o.alignment);break}}return new Gs(this,s,n)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return An;let s=0;for(let n=0;n<this.series.length;n++){const a=this.series[n];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)s+=a.length;else if(wr(a.alignmentBounds,e)){s+=Number(e-a.alignment);break}}return new Gs(this,s,s+t)}get byteLength(){return new lt(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const s of this.series)e.set(s.data,t),t+=s.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const s=this.series.map(n=>n.alignmentBounds);return Lf(s,e,t)}distance(e,t){const s=this.series.map(n=>n.alignmentBounds);return _f(s,e,t)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new bp(this.series)}}var ga,ya;class bp{constructor(e){y(this,"series"),y(this,"seriesIndex"),y(this,"internal"),y(this,ga,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(ya=Symbol.iterator,ga=Symbol.toStringTag,ya)](){return this}}let Gs=class{constructor(r,e,t){y(this,"series"),y(this,"index"),y(this,"end"),this.series=r,this.end=t,this.index=e}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};const ma=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},vp=(r,e)=>{let t=null;return e===0?r:(...s)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...s),e)}};i.z.object({key:i.z.string(),value:i.z.string()});var Op=Object.defineProperty,Tp=(r,e,t)=>e in r?Op(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ur=(r,e,t)=>Tp(r,typeof e!="symbol"?e+"":e,t);let Sp=class{constructor(r,e){Ur(this,"handlers"),Ur(this,"transform"),Ur(this,"closer"),this.transform=r,this.handlers=e??new Map}onChange(r){return this.handlers.set(r,null),()=>this.handlers.delete(r)}notify(r){let e=r;if(this.transform!=null){const[t,s]=this.transform(r);if(!s)return;e=t}this.handlers.forEach((t,s)=>s(e))}setCloser(r){this.closer=r}async close(){var r;return await((r=this.closer)==null?void 0:r.call(this))}},zp=class{constructor(r){Ur(this,"handlers"),this.handlers=r??new Map}onChange(r){return this.handlers.set(r,null),()=>this.handlers.delete(r)}notify(r){this.handlers.forEach((e,t)=>t(r))}};const Qe=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:zp,Observer:Sp},Symbol.toStringTag,{value:"Module"})),lr=i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown()),Ep=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Ep();const Np=["MacOS","Windows","Linux","Docker"],Ip=["macos","windows","linux","docker"],xp={macos:"MacOS",windows:"Windows",linux:"Linux",docker:"Docker"};i.z.enum(Np).or(i.z.enum(Ip).transform(r=>xp[r]));var Ap=Object.defineProperty,kp=(r,e,t)=>e in r?Ap(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Lt=(r,e,t)=>kp(r,typeof e!="symbol"?e+"":e,t);const Cp=(...r)=>r.map(ol).join(""),ol=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Rp=r=>r.endsWith("/")?r.slice(0,-1):r,Cn=class Rn{constructor({host:e,port:t,protocol:s="",pathPrefix:n=""}){Lt(this,"protocol"),Lt(this,"host"),Lt(this,"port"),Lt(this,"path"),this.protocol=s,this.host=e,this.port=t,this.path=ol(n)}replace(e){return new Rn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Rn({...this,pathPrefix:Cp(this.path,e)})}toString(){return Rp(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Lt(Cn,"UNKNOWN",new Cn({host:"unknown",port:0}));let $p=Cn;var Mp=Object.defineProperty,Dp=(r,e,t)=>e in r?Mp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Lr=(r,e,t)=>Dp(r,typeof e!="symbol"?e+"":e,t);const Bp=async r=>await new Promise(e=>setTimeout(e,x.fromMilliseconds(r).milliseconds)),jp=i.z.object({interval:x.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Pp=(r={})=>{const e=r.sleepFn||Bp,t=r.maxRetries??5,s=r.scale??1;let n=0,a=new x(r.interval??x.milliseconds(1));return async()=>n>=t?!1:(await e(a),a=a.mult(s),n++,!0)},Up=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:jp,create:Pp},Symbol.toStringTag,{value:"Module"})),Ke=class extends Number{};Lr(Ke,"Absolute",255),Lr(Ke,"Default",1),Lr(Ke,"z",i.z.union([i.z.instanceof(Ke),i.z.number().int().min(0).max(255).transform(r=>new Ke(r)),i.z.instanceof(Number).transform(r=>new Ke(r))]));let ll=Ke;const cl=i.z.object({name:i.z.string(),key:i.z.string()}),Lp=r=>i.z.object({subject:cl,resource:r,authority:ll.z}),_p=(...r)=>e=>e.filter(t=>{let s=!1;return t.to!=null&&(s=r.includes(t.to.resource)),t.from!=null&&!s&&(s=r.includes(t.from.resource)),s}),ct=Object.freeze(Object.defineProperty({__proto__:null,Authority:ll,filterTransfersByChannelKey:_p,stateZ:Lp,subjectZ:cl},Symbol.toStringTag,{value:"Module"})),ul=class _t extends Error{constructor(){super(_t.MESSAGE)}matches(e){return typeof e=="string"?e.includes(_t.MESSAGE):e instanceof _t||e.message.includes(_t.MESSAGE)}};Lr(ul,"MESSAGE","canceled");let Yp=ul;new Yp;const $n=i.z.string().regex(/^\d+\.\d+\.\d+$/),cr=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const s=$n.parse(r),n=$n.parse(e),[a,o,c]=s.split(".").map(Number),[l,d,f]=n.split(".").map(Number);if(t.checkMajor){if(a<l)return Ls;if(a>l)return _s}if(t.checkMinor){if(o<d)return Ls;if(o>d)return _s}if(t.checkPatch){if(c<f)return Ls;if(c>f)return _s}return ws},Fp=(r,e,t={})=>zf(cr(r,e,t)),hl=(r,e,t={})=>Sf(cr(r,e,t)),qp=(r,e,t={})=>Tf(cr(r,e,t)),Gp=({name:r,migrate:e})=>t=>{try{const s=e(t);return console.log(`${r} migrated: ${t.version} -> ${s.version}`),s}catch(s){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(s),s}},Vp=({name:r,migrations:e,targetSchema:t,defaultVersion:s,def:n})=>{const a=Object.keys(e).sort(cr).pop();if(a==null)return d=>{if(d.version??(d.version=s),d.version!==n.version)return console.log(`${r} version ${d.version} is newer than latest version of ${n.version}.
40
- Returning default instead.
41
- `),n;try{return t!=null?t.parse(d):d}catch(f){return console.log(`${r} failed to parse default. Exiting with default`),console.error(f),n}};const o=Object.keys(e).length;let c=!1;const l=d=>{try{if(o===0||hl(d.version,a))return console.log(c?`${r} ${d.version} now up to date`:`${r} version ${d.version} is up to date with target version ${n.version}`),d;const f=d.version,h=e[f],I=h(d);return c=!0,l(I)}catch(f){return console.log(`${r} failed to migrate from ${d.version} to ${a}`),console.error(f),n}};return d=>{try{if(d.version==null)if(s!=null)console.log(`${r} version is null. Setting version to default of ${s}`),d.version=s;else return console.log(`${r} version is null and no default version set. Exiting with default`),n;return l(d)}catch(f){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(f),n}}},wa=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:cr,createMigration:Gp,migrator:Vp,semVerNewer:hl,semVerOlder:qp,semVerZ:$n,versionsEqual:Fp},Symbol.toStringTag,{value:"Module"})),Ve="sy.",_r=class dl extends Se{constructor(){super(...arguments),u(this,"type",dl.TYPE)}};u(_r,"TYPE",`${Ve}validation`),u(_r,"matches",pe(_r.TYPE));let J=_r;const Yr=class fl extends J{constructor(e,t){super(`${e}: ${t}`),u(this,"type",fl.TYPE),u(this,"field"),u(this,"message"),this.field=e,this.message=t}};u(Yr,"TYPE",`${J.TYPE}.field`),u(Yr,"matches",pe(Yr.TYPE));let ba=Yr;const Fr=class pl extends Se{constructor(){super(...arguments),u(this,"type",pl.TYPE)}};u(Fr,"TYPE",`${Ve}auth`),u(Fr,"matches",pe(Fr.TYPE));let ls=Fr;const qr=class gl extends ls{constructor(){super(...arguments),u(this,"type",gl.TYPE)}};u(qr,"TYPE",`${ls.TYPE}.invalid-token`),u(qr,"matches",pe(qr.TYPE));let Mn=qr;const Gr=class yl extends Se{constructor(e){super(`
42
- Unexpected error encountered:
43
-
44
- ${e}
45
-
46
- Please report this to the Synnax team.
47
- `),u(this,"type",yl.TYPE)}};u(Gr,"TYPE",`${Ve}unexpected`),u(Gr,"matches",pe(Gr.TYPE));let we=Gr;const Vr=class ml extends Se{constructor(){super(...arguments),u(this,"type",ml.TYPE)}};u(Vr,"TYPE",`${Ve}query`),u(Vr,"matches",pe(Vr.TYPE));let Te=Vr;const Wr=class wl extends Te{constructor(){super(...arguments),u(this,"type",wl.TYPE)}};u(Wr,"TYPE",`${Te.TYPE}.not_found`),u(Wr,"matches",pe(Wr.TYPE));let ut=Wr;const Zr=class bl extends Te{constructor(){super(...arguments),u(this,"type",bl.TYPE)}};u(Zr,"TYPE",`${Te.TYPE}.multiple_results`),u(Zr,"matches",pe(Zr.TYPE));let ht=Zr;const Kr=class vl extends Se{constructor(e,t){super(e),u(this,"type",vl.TYPE),u(this,"path"),this.path=t}};u(Kr,"TYPE",`${Ve}route`),u(Kr,"matches",pe(Kr.TYPE));let va=Kr;const Jr=class Ol extends Se{constructor(){super(...arguments),u(this,"type",Ol.TYPE)}};u(Jr,"TYPE",`${Ve}control`),u(Jr,"matches",pe(Jr.TYPE));let cs=Jr;const Hr=class Tl extends cs{constructor(){super(...arguments),u(this,"type",Tl.TYPE)}};u(Hr,"TYPE",`${cs.TYPE}.unauthorized`),u(Hr,"matches",pe(Hr.TYPE));let Oa=Hr;const Vs=class Sl extends Se{constructor(){super(...arguments),u(this,"type",Sl.TYPE)}};u(Vs,"TYPE",`${Ve}contiguity`),u(Vs,"matches",pe(Vs.TYPE));const Wp=r=>{if(!r.type.startsWith(Ve))return null;if(r.type.startsWith(J.TYPE)){if(r.type===ba.TYPE){const e=r.data.split(": ");return e.length<2?new J(r.data):new ba(e[0],e[1])}return new J(r.data)}return r.type.startsWith(ls.TYPE)?r.type.startsWith(Mn.TYPE)?new Mn(r.data):new ls(r.data):r.type.startsWith(we.TYPE)?new we(r.data):r.type.startsWith(Te.TYPE)?r.type.startsWith(ut.TYPE)?new ut(r.data):r.type.startsWith(ht.TYPE)?new ht(r.data):new Te(r.data):r.type.startsWith(cs.TYPE)?r.type.startsWith(Oa.TYPE)?new Oa(r.data):new cs(r.data):r.type.startsWith(va.TYPE)?new va(r.data,r.data):new we(r.data)},Zp=()=>{throw new Error("Not implemented")};Po({encode:Zp,decode:Wp});const Kp=async(r,e)=>{const[t,s]=await e(r);return s==null?[t,s]:s instanceof Ge?[t,new Ge({message:`Cannot reach cluster at ${s.url.host}:${s.url.port}`,url:s.url})]:[t,s]};class zl{constructor(e,t){u(this,"key"),u(this,"name"),this.key=t,this.name=e}get ontologyID(){return new M({type:"group",key:this.key})}}const Jp=i.z.string().uuid(),El=i.z.object({key:Jp,name:i.z.string()}),vs=i.z.union([i.z.literal("label"),i.z.literal("log"),i.z.literal("allow_all"),i.z.literal("builtin"),i.z.literal("cluster"),i.z.literal("channel"),i.z.literal("node"),i.z.literal("group"),i.z.literal("range"),i.z.literal("framer"),i.z.literal("range-alias"),i.z.literal("user"),i.z.literal("workspace"),i.z.literal("schematic"),i.z.literal("lineplot"),i.z.literal("rack"),i.z.literal("device"),i.z.literal("task"),i.z.literal("policy"),i.z.literal("table")]),ye=i.z.object({type:vs,key:i.z.string()}),Hp=i.z.string().transform(r=>{const[e,t]=r.split(":");return{type:vs.parse(e),key:t??""}}),Yt=i.z.union([Hp,ye]),Xr=class Nl{constructor(e){if(u(this,"type"),u(this,"key"),e instanceof Nl){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,s]=e.split(":");this.type=t,this.key=s??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};u(Xr,"z",i.z.union([i.z.instanceof(Xr),Yt.transform(r=>new Xr(r))]));let M=Xr;new M({type:"builtin",key:"root"});const Xp=i.z.object({type:i.z.number()}),Qp=i.z.object({type:vs,fields:i.z.record(Xp)}),eg=i.z.object({id:M.z,name:i.z.string(),schema:Qp.optional().nullable(),data:i.z.record(i.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r}));i.z.object({from:M.z,type:i.z.string(),to:M.z});const Ta=r=>{const[e,t,s]=r.split("->");return{from:new M(e),type:t,to:new M(s)}},tg=i.z.object({group:El}),rg=i.z.object({parent:ye,key:i.z.string().uuid().optional(),name:i.z.string()}),sg=i.z.object({key:i.z.string(),name:i.z.string()}),ng=i.z.object({keys:i.z.array(i.z.string())});var Ye;let ig=(Ye=class{constructor(r){u(this,"client"),this.client=r}async create(r,e,t){return(await O(this.client,Ye.ENDPOINT,{parent:r,name:e,key:t},rg,tg)).group}async rename(r,e){await O(this.client,Ye.ENDPOINT_RENAME,{key:r,name:e},sg,i.z.object({}))}async delete(r){await O(this.client,Ye.ENDPOINT_DELETE,{keys:r},ng,i.z.object({}))}},u(Ye,"ENDPOINT","/ontology/create-group"),u(Ye,"ENDPOINT_RENAME","/ontology/rename-group"),u(Ye,"ENDPOINT_DELETE","/ontology/delete-group"),Ye),ag=class{constructor(r){u(this,"creator"),this.creator=new ig(r)}async create(r,e,t){return this.sugar(await this.creator.create(r,e,t))}async rename(r,e){return await this.creator.rename(r,e)}async delete(...r){return await this.creator.delete(r)}sugar(r){return new zl(r.name,r.key)}};const Ws={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},Sa=i.z.object({id:ye,children:ye.array()}),og=i.z.object({from:ye,to:ye,children:ye.array()});let lg=class{constructor(r){u(this,"client"),this.client=r}async addChildren(r,...e){await O(this.client,Ws.ADD_CHILDREN,{id:new M(r).payload,children:e.map(t=>new M(t).payload)},Sa,i.z.object({}))}async removeChildren(r,...e){await O(this.client,Ws.REMOVE_CHILDREN,{id:new M(r).payload,children:e.map(t=>new M(t).payload)},Sa,i.z.object({}))}async moveChildren(r,e,...t){const s={from:new M(r).payload,to:new M(e).payload,children:t.map(n=>new M(n).payload)};await O(this.client,Ws.MOVE_CHILDREN,s,og,i.z.object({}))}};const cg="/ontology/retrieve",ug=i.z.object({ids:ye.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),includeSchema:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),term:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),types:vs.array().optional()}),hg=i.z.object({resources:eg.array()}),Zs=r=>S(r).map(e=>new M(e).payload);let dg=class{constructor(r,e){u(this,"type","ontology"),u(this,"groups"),u(this,"client"),u(this,"writer"),u(this,"framer"),this.client=r,this.writer=new lg(r),this.groups=new ag(r),this.framer=e}async search(r,e){return await this.execRetrieve({term:r,...e})}async retrieve(r,e){const t=await this.execRetrieve({ids:Zs(r),...e});if(Array.isArray(r))return t;if(t.length===0)throw new Te(`No resource found with ID ${r.toString()}`);return t[0]}async page(r,e,t){return await this.execRetrieve({offset:r,limit:e,...t})}async retrieveChildren(r,e){return await this.execRetrieve({ids:Zs(r),children:!0,...e})}async retrieveParents(r,e){return await this.execRetrieve({ids:Zs(r),parents:!0,...e})}async addChildren(r,...e){return await this.writer.addChildren(r,...e)}async removeChildren(r,...e){return await this.writer.removeChildren(r,...e)}async moveChildren(r,e,...t){return await this.writer.moveChildren(r,e,...t)}async openChangeTracker(){return await Os.open(this.framer,this)}async openDependentTracker(r){return await Xn.open(r,this.framer,this)}newSearcherWithOptions(r){return{type:this.type,search:e=>this.search(e,r),retrieve:e=>this.retrieve(e,r),page:(e,t)=>this.page(e,t,r)}}async execRetrieve(r){const{resources:e}=await O(this.client,cg,r,ug,hg);return e}};const za="sy_ontology_resource_set",Ea="sy_ontology_resource_delete",Na="sy_ontology_relationship_set",Ia="sy_ontology_relationship_delete";class Os{constructor(e,t){u(this,"relationships"),u(this,"resources"),u(this,"resourceObs"),u(this,"relationshipObs"),u(this,"streamer"),u(this,"client"),u(this,"closePromise"),this.relationshipObs=new Qe.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Qe.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),s=this.parseResourceDeletes(e);t.concat(s).length>0&&this.resourceObs.notify(t.concat(s));const n=this.parseRelationshipSets(e),a=this.parseRelationshipDeletes(e);n.concat(a).length>0&&this.relationshipObs.notify(n.concat(a))}parseRelationshipSets(e){const t=e.get(Na);return t.length===0?[]:Array.from(t.as("string")).map(s=>({variant:"set",key:Ta(s),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Ia);return t.length===0?[]:Array.from(t.as("string")).map(s=>({variant:"delete",key:Ta(s)}))}async parseResourceSets(e){const t=e.get(za);if(t.length===0)return[];const s=Array.from(t.as("string")).map(n=>new M(n));try{return(await this.client.retrieve(s)).map(n=>({variant:"set",key:n.id,value:n}))}catch(n){if(n instanceof Te)return[];throw n}}parseResourceDeletes(e){const t=e.get(Ea);return t.length===0?[]:Array.from(t.as("string")).map(s=>({variant:"delete",key:new M(s)}))}static async open(e,t){const s=await e.openStreamer([za,Ea,Na,Ia]);return new Os(s,t)}}const xa=r=>r==="from"?"to":"from";class Xn extends Qe.Observer{constructor({target:e,dependents:t,relationshipType:s="parent",relationshipDirection:n="from",resourceType:a},o,c){super(),u(this,"internal"),u(this,"target"),u(this,"relDir"),u(this,"resourceType"),u(this,"dependents"),u(this,"client"),u(this,"relType"),u(this,"handleResourceChange",l=>{this.dependents=this.dependents.map(d=>{const f=l.find(h=>h.key.toString()==d.id.toString());return f==null||f.variant==="delete"?d:f.value}),this.notify(this.dependents)}),u(this,"handleRelationshipChange",l=>{const d=l.filter(h=>h.variant==="delete"&&h.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||h.key[xa(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(h=>!d.some(I=>I.key.to.toString()===h.id.toString()&&I.key.type===this.relType));const f=l.filter(h=>h.variant==="set"&&h.key.type===this.relType&&h.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||h.key[xa(this.relDir)].type===this.resourceType));if(f.length===0)return this.notify(this.dependents);this.client.retrieve(f.map(h=>h.key.to)).then(h=>{this.dependents=this.dependents.concat(h),this.notify(this.dependents)})}),this.resourceType=a,this.internal=o,this.target=e,this.dependents=t,this.resourceType!=null&&(this.dependents=this.dependents.filter(l=>l.id.type===this.resourceType)),this.client=c,this.relType=s,this.relDir=n,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(e,t,s){const n=await Os.open(t,s);return new Xn(e,n,s)}async close(){await this.internal.close()}}const fe=r=>i.z.union([i.z.null().transform(()=>[]),r.array()]),Ts=i.z.string().uuid(),fg=i.z.object({key:Ts.optional(),subjects:Yt.array().or(Yt),objects:Yt.array().or(Yt),actions:Nn.array().or(Nn)}),Qn=i.z.object({key:Ts,subjects:fe(ye),objects:fe(ye),actions:fe(Nn)}),pg="allow_all";new M({type:pg,key:""});const gg=i.z.object({keys:Ts.array().optional(),subjects:ye.array().optional()}),yg=i.z.object({policies:fe(Qn)}),mg="/access/policy/retrieve";let wg=class{constructor(r){u(this,"client"),this.client=r}async retrieve(r){return(await O(this.client,mg,r,gg,yg)).policies}};const bg=i.z.object({policies:Qn.partial({key:!0}).array()}),vg=i.z.object({policies:Qn.array()}),Og=i.z.object({keys:Ts.array()}),Tg=i.z.object({}),Sg="/access/policy/create",zg="/access/policy/delete";let Eg=class{constructor(r){u(this,"client"),this.client=r}async create(r){const e=fg.array().parse(S(r)).map(t=>({objects:S(t.objects),actions:S(t.actions),subjects:S(t.subjects)}));return(await O(this.client,Sg,{policies:e},bg,vg)).policies}async delete(r){await O(this.client,zg,{keys:S(r)},Og,Tg)}},Ng=class{constructor(r){u(this,"retriever"),u(this,"writer"),this.retriever=new wg(r),this.writer=new Eg(r)}async create(r){const e=Array.isArray(r),t=await this.writer.create(r);return e?t:t[0]}async retrieve(r){const e=Array.isArray(r),t=await this.retriever.retrieve({keys:S(r)});return e?t:t[0]}async retrieveFor(r){const e=S(r).map(t=>new M(t).payload);return await this.retriever.retrieve({subjects:e})}async delete(r){await this.writer.delete(r)}},Ig=class{constructor(r){u(this,"policy"),this.policy=new Ng(r)}};const We=i.z.number(),ur=i.z.object({name:i.z.string(),key:i.z.number(),rate:Xt.z,dataType:$.z,leaseholder:i.z.number(),index:i.z.number(),isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional()}),Il=ur.extend({key:i.z.number().optional(),leaseholder:i.z.number().optional(),index:i.z.number().optional(),rate:Xt.z.optional().default(0),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional().default(!1),virtual:i.z.boolean().optional().default(!1)}),xl="channel",xg=r=>new M({type:xl,key:r.toString()}),Ag=new Error("request for lock canceled");var kg=function(r,e,t,s){function n(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(s.next(f))}catch(h){o(h)}}function l(f){try{d(s.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):n(f.value).then(c,l)}d((s=s.apply(r,e||[])).next())})};class Cg{constructor(e,t=Ag){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((s,n)=>{const a={resolve:s,reject:n,weight:e,priority:t},o=Al(this._queue,c=>t<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return kg(this,arguments,void 0,function*(t,s=1,n=0){const[a,o]=yield this.acquire(s,n);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(s=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Rg(this._weightedWaiters[e-1],{resolve:s,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(s=>s.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const s=this._weightedWaiters[t-1];if(!s)continue;const n=s.findIndex(a=>a.priority<=e);(n===-1?s:s.splice(0,n)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Rg(r,e){const t=Al(r,s=>e.priority<=s.priority);r.splice(t+1,0,e)}function Al(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var $g=function(r,e,t,s){function n(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(s.next(f))}catch(h){o(h)}}function l(f){try{d(s.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):n(f.value).then(c,l)}d((s=s.apply(r,e||[])).next())})};class Mg{constructor(e){this._semaphore=new Cg(1,e)}acquire(){return $g(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const Ss=(r,e,{convertNumericStrings:t=!0}={})=>{const s=!Array.isArray(r);let n=S(r);const a=n[0],o=typeof a;let c;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,n=n.map(l=>parseInt(l))):c=e[o],{single:s,variant:c,normalized:n,actual:r}},zs=(r,e,t,s)=>{if(s){if(t.length===0)throw new ut(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new ht(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Dg=i.z.object({leaseholder:i.z.number().optional(),keys:i.z.number().array().optional(),names:i.z.string().array().optional(),search:i.z.string().optional(),rangeKey:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),dataTypes:$.z.array().optional(),notDataTypes:$.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional()}),Bg=i.z.object({channels:fe(ur)}),Pe=r=>Ss(r,{number:"keys",string:"names"}),kl=class Cl{constructor(e){u(this,"client"),this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const s=Pe(e),{variant:n}=s;let{normalized:a}=s;return n==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[n]:a,...t})}async page(e,t,s){return await this.execute({offset:e,limit:t,...s})}async execute(e){const[t,s]=await this.client.send(Cl.ENDPOINT,e,Dg,Bg);if(s!=null)throw s;return t.channels}};u(kl,"ENDPOINT","/channel/retrieve");let ei=kl;class ti{constructor(e){u(this,"cache"),u(this,"namesToKeys"),u(this,"wrapped"),this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,s){return await this.wrapped.page(e,t,s)}async retrieve(e,t){const{normalized:s}=Ss(e,{string:"names",number:"keys"}),n=[],a=[];if(s.forEach(c=>{const l=this.get(c);l!=null?n.push(...l):a.push(c)}),a.length===0)return n;const o=await this.wrapped.retrieve(a,t);return this.set(o),n.concat(o)}delete(e){const{variant:t,normalized:s}=Pe(e);t==="names"?s.forEach(n=>{const a=this.namesToKeys.get(n);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(n))}):s.forEach(n=>{const a=this.cache.get(n);a!=null&&(this.cache.delete(n),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((s,n)=>{const a=t[n],o=this.cache.get(s);if(o==null)return;this.cache.delete(s);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(s),c.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(s,o);const l=this.namesToKeys.get(a);l==null?this.namesToKeys.set(a,new Set([s])):l.add(s)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const s=this.namesToKeys.get(t.name);s==null?this.namesToKeys.set(t.name,new Set([t.key])):s.add(t.key)})}get(e){if(typeof e=="number"){const n=this.cache.get(e);return n==null?void 0:[n]}const t=this.namesToKeys.get(e);if(t==null)return;const s=[];if(t.forEach(n=>{const a=this.cache.get(n);a!=null&&s.push(a)}),s.length!==0)return s}}class Rl{constructor(e,t){u(this,"mu",new Mg),u(this,"requests",new Map),u(this,"wrapped"),u(this,"debouncedRun"),this.wrapped=e,this.debouncedRun=vp(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,s){return await this.wrapped.page(e,t,s)}async retrieve(e){const{normalized:t,variant:s}=Pe(e);return s==="names"?await this.wrapped.retrieve(t):await new Promise((n,a)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:n,reject:a}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,s)=>s.forEach(n=>e.add(n)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((s,n)=>s.resolve(t.filter(a=>n.includes(a.key))))}catch(t){this.requests.forEach(s=>s.reject(t))}finally{this.requests.clear()}})}}const $l=async(r,e)=>{const{normalized:t}=Pe(e),s=await r.retrieve(t),n=[];if(t.forEach(a=>{s.find(o=>o.name===a||o.key===a)==null&&n.push(a)}),n.length>0)throw new Te(`Could not find channels: ${JSON.stringify(n)}`);return s};class Ml{constructor({dataType:e,rate:t,name:s,leaseholder:n=0,key:a=0,isIndex:o=!1,index:c=0,internal:l=!1,virtual:d=!1,frameClient:f,alias:h}){u(this,"_frameClient"),u(this,"key"),u(this,"name"),u(this,"rate"),u(this,"dataType"),u(this,"leaseholder"),u(this,"index"),u(this,"isIndex"),u(this,"internal"),u(this,"alias"),u(this,"virtual"),this.key=a,this.name=s,this.rate=new Xt(t??0),this.dataType=new $(e),this.leaseholder=n,this.index=c,this.isIndex=o,this.internal=l,this.alias=h,this.virtual=d,this._frameClient=f??null}get framer(){if(this._frameClient==null)throw new J("cannot read from a channel that has not been created");return this._frameClient}get payload(){return ur.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal})}get ontologyID(){return new M({type:"channel",key:this.key.toString()})}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const jg="/channel/retrieve-group",Pg=i.z.object({}),Ug=i.z.object({group:El});let Dl=class{constructor(r,e,t,s){u(this,"type","channel"),u(this,"frameClient"),u(this,"client"),u(this,"retriever"),u(this,"writer"),this.frameClient=r,this.retriever=e,this.client=t,this.writer=s}async create(r,e={}){const{retrieveIfNameExists:t=!1}=e,s=!Array.isArray(r);let n=S(r),a=[];if(t){const o=await this.retriever.retrieve(n.map(l=>l.name)),c=new Set(o.map(l=>l.name));n=n.filter(l=>!c.has(l.name)),a=this.sugar(o)}return a=a.concat(this.sugar(await this.writer.create(n))),s?a[0]:a}async retrieve(r,e){const t=!Array.isArray(r),s=this.sugar(await this.retriever.retrieve(r,e));return zs("channel",r,s,t),t?s[0]:s}async search(r,e){return this.sugar(await this.retriever.search(r,e))}async delete(r){const{normalized:e,variant:t}=Pe(r);return t==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(r,e){return await this.writer.rename(S(r),S(e))}newSearcherWithOptions(r){return{type:this.type,search:async e=>await this.search(e,r),retrieve:async e=>await this.retrieve(e,r),page:async(e,t)=>await this.page(e,t,r)}}async page(r,e,t){return this.sugar(await this.retriever.page(r,e,t))}createDebouncedBatchRetriever(r=10){return new ti(new Rl(new ei(this.client),r))}sugar(r){const{frameClient:e}=this;return r.map(t=>new Ml({...t,frameClient:e}))}async retrieveGroup(){const r=await O(this.client,jg,{},Pg,Ug);return new zl(r.group.name,r.group.key)}};const Lg=i.z.object({channels:Il.array()}),_g=i.z.object({channels:ur.array()}),Yg=i.z.object({keys:We.array().optional(),names:i.z.string().array().optional()}),Fg=i.z.object({}),qg=i.z.object({keys:We.array(),names:i.z.string().array()}),Gg=i.z.object({}),Vg="/channel/create",Wg="/channel/delete",Zg="/channel/rename";let Bl=class{constructor(r,e){u(this,"client"),u(this,"cache"),this.client=r,this.cache=e}async create(r){const{channels:e}=await O(this.client,Vg,{channels:r},Lg,_g);return this.cache.set(e),e}async delete(r){await O(this.client,Wg,r,Yg,Fg),r.keys!=null&&this.cache.delete(r.keys),r.names!=null&&this.cache.delete(r.names)}async rename(r,e){await O(this.client,Zg,{keys:r,names:e},qg,Gg),this.cache.rename(r,e)}};const Kg=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:ti,Channel:Ml,Client:Dl,ClusterRetriever:ei,DebouncedBatchRetriever:Rl,ONTOLOGY_TYPE:xl,Writer:Bl,analyzeChannelParams:Pe,keyZ:We,newPayload:Il,ontologyID:xg,payload:ur,retrieveRequired:$l},Symbol.toStringTag,{value:"Module"})),hr=i.z.string().uuid(),Es=i.z.object({key:hr,username:i.z.string().min(1),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!0)}),Jg=Es.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:i.z.string().min(1)}),Hg=i.z.object({keys:hr.array().optional(),usernames:i.z.string().array().optional()}),Xg=i.z.object({users:fe(Es)}),Qg="/user/retrieve";let ey=class{constructor(r){u(this,"client"),this.client=r}async retrieve(r){return(await O(this.client,Qg,r,Hg,Xg)).users}};const ty=i.z.object({users:Jg.array()}),ry=i.z.object({users:Es.array()}),sy=i.z.object({key:hr,username:i.z.string().min(1)}),ny=i.z.object({}),iy=i.z.object({key:hr,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),ay=i.z.object({}),oy=i.z.object({keys:hr.array()}),ly=i.z.object({}),cy="/user/create",uy="/user/change-username",hy="/user/rename",dy="/user/delete";let fy=class{constructor(r){u(this,"client"),this.client=r}async create(r){return(await O(this.client,cy,{users:S(r)},ty,ry)).users}async changeUsername(r,e){await O(this.client,uy,{key:r,username:e},sy,ny)}async rename(r,e,t){await O(this.client,hy,{key:r,firstName:e,lastName:t},iy,ay)}async delete(r){await O(this.client,dy,{keys:S(r)},oy,ly)}},py=class{constructor(r){u(this,"reader"),u(this,"writer"),this.writer=new fy(r),this.reader=new ey(r)}async create(r){const e=Array.isArray(r),t=await this.writer.create(r);return e?t:t[0]}async changeUsername(r,e){await this.writer.changeUsername(r,e)}async retrieve(r){const e=Array.isArray(r),t=await this.reader.retrieve({keys:S(r)});if(e)return t;if(t.length===0)throw new ut(`No user with key ${r} found`);if(t.length>1)throw new ht(`Multiple users found with key ${r}`);return t[0]}async retrieveByName(r){const e=Array.isArray(r),t=await this.reader.retrieve({usernames:S(r)});if(e)return t;if(t.length===0)throw new ut(`No user with username ${r} found`);if(t.length>1)throw new ht(`Multiple users found with username ${r}`);return t[0]}async rename(r,e,t){await this.writer.rename(r,e,t)}async delete(r){await this.writer.delete(r)}};const gy=i.z.object({username:i.z.string(),password:i.z.string()}),yy=i.z.object({token:i.z.string(),user:Es}),Aa="/auth/login",my=3,wy="/auth/change-password",by=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),vy=i.z.object({});let Oy=class{constructor(r,e){u(this,"token"),u(this,"client"),u(this,"credentials"),u(this,"authenticating"),u(this,"authenticated"),u(this,"user"),u(this,"retryCount"),this.client=r,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(r){if(!this.authenticated)throw new Error("Not authenticated");await O(this.client,wy,{username:this.credentials.username,password:this.credentials.password,newPassword:r},by,vy),this.credentials.password=r}middleware(){const r=async(e,t)=>{if(!this.authenticated&&!e.target.endsWith(Aa)){this.authenticating??(this.authenticating=new Promise((o,c)=>{this.client.send(Aa,this.credentials,gy,yy).then(([l,d])=>{if(d!=null)return o(d);this.token=l==null?void 0:l.token,this.user=l==null?void 0:l.user,this.authenticated=!0,o(null)}).catch(c)}));const a=await this.authenticating;if(a!=null)return[e,a]}e.params.Authorization=`Bearer ${this.token}`;const[s,n]=await t(e);return Mn.matches(n)&&this.retryCount<my?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,r(e,t)):(this.retryCount=0,[s,n])};return r}};const Ty=["disconnected","connecting","connected","failed"],Sy=i.z.enum(Ty),zy=i.z.object({status:Sy,error:i.z.instanceof(Error).optional(),message:i.z.string().optional(),clusterKey:i.z.string(),clientVersion:i.z.string(),clientServerCompatible:i.z.boolean(),nodeVersion:i.z.string().optional()}),Ey=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),jl={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.37.0"},ka=(r,e,t)=>{const s=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
48
- This may cause compatibility issues. We recommend updating the ${s}. For more information, see
49
- https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${s}-version`},Qr=class Pl{constructor(e,t=x.seconds(30),s,n){u(this,"_state"),u(this,"pollFrequency",x.seconds(30)),u(this,"client"),u(this,"name"),u(this,"interval"),u(this,"clientVersion"),u(this,"onChangeHandlers",[]),u(this,"versionWarned",!1),this._state={...jl},this.client=e,this.pollFrequency=t,this.clientVersion=s,this.name=n,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var e;const t=this._state.status;try{const[s,n]=await this.client.send(Pl.ENDPOINT,{},i.z.object({}),Ey);if(n!=null)throw n;const a=s.nodeVersion,o=this.clientVersion,c=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,c||(console.warn(ka(null,o,!0)),this.versionWarned=!0)):wa.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,c||(console.warn(ka(a,o,wa.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=s.clusterKey,this._state.nodeVersion=s.nodeVersion,this._state.clientVersion=this.clientVersion}catch(s){this._state.status="failed",this._state.error=s,this._state.message=(e=this.state.error)==null?void 0:e.message}return this.onChangeHandlers.length>0&&t!==this._state.status&&this.onChangeHandlers.forEach(s=>s(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};u(Qr,"ENDPOINT","/connectivity/check"),u(Qr,"DEFAULT",jl),u(Qr,"connectionStateZ",zy);let Ul=Qr;const Ny=i.z.object({keys:We.array().optional(),bounds:ne.z,names:i.z.string().array().optional()}),Iy=i.z.object({}),xy="/frame/delete";class Ay{constructor(e){u(this,"client"),this.client=e}async delete(e){await O(this.client,xy,e,Ny,Iy)}}const Ca=r=>{const e=S(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Ra=(r,e)=>{const t=S(r);if(t.length===e.length)return;const s=Ca(r);throw Ca===null?new J("[Frame] - channel keys or names must be provided when constructing a frame."):new J(`[Frame] - ${s}s and series must be the same length.
50
- Got ${t.length} ${s}s and ${e.length} series.`)};let ve=class st{constructor(e=[],t=[]){if(u(this,"columns",[]),u(this,"series",[]),e instanceof st){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,n)=>this.push(n,...S(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e;s.series??(s.series=[]),s.keys??(s.keys=[]);const n=s.series.map(a=>ky(a));Ra(s.keys,n),s.keys.forEach((a,o)=>this.push(a,n[o]))}else Object.entries(e).forEach(([s,n])=>{const a=parseInt(s);if(!isNaN(a))return this.push(a,...S(n));this.push(s,...S(n))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=S(t),n=S(e);Ra(n,s),s.forEach((a,o)=>this.push(n[o],a));return}throw new J(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
51
- payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
52
- 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 we("colType is not key");return this.columns??[]}get uniqueKeys(){return ta(this.keys)}get names(){if(this.colType==="key")throw new we("colType is not name");return this.columns??[]}get uniqueNames(){return ta(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Cy(e)),keys:this.keys}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return ne.ZERO;const s=R.min(...this.series.map(a=>a.timeRange.start)),n=R.max(...this.series.map(a=>a.timeRange.end));return new ne(s,n)}const t=this.get(e);return t==null?ne.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new wp(this.series.filter((t,s)=>this.columns[s]===e))}push(e,...t){if(e instanceof st){if(this.colType!==null&&e.colType!==this.colType)throw new J("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new J("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new J("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new st([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new st;return this.forEach((s,n,a)=>t.push(...e(s,n,a))),t}forEach(e){this.columns.forEach((t,s)=>{const n=this.series[s];e(t,n,s)})}at(e,t=!1){const s={};return this.uniqueColumns.forEach(n=>{s[n]=this.get(n).at(e,t)}),s}filter(e){const t=new st;return this.columns.forEach((s,n)=>{const a=this.series[n];e(s,a,n)&&t.push(s,a)}),t}get byteLength(){return new lt(this.series.reduce((e,t)=>e.add(t.byteLength),lt.ZERO))}get digest(){const e={};return this.keys.forEach((t,s)=>{const n=this.series[s].digest;t in e?e[t].push(n):e[t]=[n]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}};const ri=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().optional().default([])]),series:i.z.union([i.z.null().transform(()=>[]),Je.crudeZ.array().optional().default([])])}),ky=r=>{const{dataType:e,data:t,timeRange:s,alignment:n}=r;return new Je({data:t,dataType:e,timeRange:s,glBufferUsage:"static",alignment:n})},Cy=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class Ns{constructor(e){u(this,"adapter"),u(this,"retriever"),u(this,"keys"),this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const s=new Ns(e);return await s.update(t),s}async update(e){const{variant:t,normalized:s}=Pe(e);if(t==="keys"){this.adapter=null,this.keys=s;return}const n=await this.retriever.retrieve(s),a=new Map;this.adapter=a,s.forEach(o=>{const c=n.find(l=>l.name===o);if(c==null)throw new Error(`Channel ${o} not found`);a.set(c.key,c.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((s,n)=>{if(typeof s=="number"){const a=t.get(s);if(a==null)throw new Error(`Channel ${s} not found`);return[a,n]}return[s,n]})}}class si{constructor(e){u(this,"adapter"),u(this,"retriever"),u(this,"keys"),this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const s=new si(e);return await s.update(t),s}async adaptObjectKeys(e){const t={};for(const[s,n]of Object.entries(e))t[await this.adaptToKey(s)]=n;return t}async update(e){const t=await $l(this.retriever,e);this.adapter=new Map(t.map(s=>[s.name,s.key])),this.keys=t.map(s=>s.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new J(`
53
- Received a single channel name or key but no series.
54
- `);if(Array.isArray(t)){if(t.some(l=>l instanceof Je||Array.isArray(l)))throw new J(`
55
- Received a single channel name or key but multiple series.
56
- `);t=t}const o=await this.fetchChannel(e),c=new Je({data:t,dataType:o.dataType});return new ve(o.key,c)}if(Array.isArray(e)){if(t==null)throw new J(`
57
- Received an array of channel names or keys but no series.
58
- `);if(!Array.isArray(t))throw new J(`
59
- Received an array of channel names or keys but no array of series.
60
- `);const o=[],c=[];for(let l=0;l<e.length;l++){const d=await this.fetchChannel(e[l]);if(l>=t.length)throw new J(`
61
- Received an array of channel names or keys but not enough series.
62
- `);const f=new Je({data:t[l],dataType:d.dataType});o.push(d.key),c.push(f)}return new ve(o,c)}if(e instanceof ve||e instanceof Map){const o=new ve(e);if(this.adapter==null)return o;const c=o.columns.map(l=>{var d;const f=typeof l=="string"?(d=this.adapter)==null?void 0:d.get(l):l;if(f==null)throw new J(`
63
- Channel ${l} was not provided in the list of channels when opening the writer
64
- `);return f});return new ve(c,o.series)}const s=[],n=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,l]=a[o],d=await this.fetchChannel(c),f=new Je({data:l,dataType:d.dataType});s.push(d.key),n.push(f)}return new ve(s,n)}}class ni{constructor(e,t){u(this,"name"),u(this,"stream"),this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
65
- Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(qe.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const $a=new x(-1);var ii=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(ii||{}),Ll=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Ll||{});const Ry=i.z.object({command:i.z.nativeEnum(ii),span:x.z.optional(),bounds:ne.z.optional(),stamp:R.z.optional(),keys:i.z.number().array().optional(),chunkSize:i.z.number().optional()}),$y=i.z.object({variant:i.z.nativeEnum(Ll),ack:i.z.boolean(),command:i.z.nativeEnum(ii),error:or.optional().nullable(),frame:ri.optional()}),_l=class Dn{constructor(e,t){u(this,"stream"),u(this,"adapter"),u(this,"value"),this.stream=new ni("Iterator",e),this.value=new ve,this.adapter=t}static async _open(e,t,s,n,a={}){const o=await Ns.open(s,t),c=await n.stream(Dn.ENDPOINT,Ry,$y),l=new Dn(c,o);return await l.execute({command:0,keys:o.keys,bounds:new ne(e),chunkSize:a.chunkSize??1e5}),l}async next(e=$a){return await this.execute({command:1,span:new x(e)})}async prev(e=$a){return await this.execute({command:2,span:new x(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new R(e)})}async seekGE(e){return await this.execute({command:6,stamp:new R(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new Dy(this)}async execute(e){for(this.stream.send(e),this.value=new ve;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new ve(t.frame)))}}};u(_l,"ENDPOINT","/frame/iterate");let My=_l;class Dy{constructor(e){u(this,"iter"),u(this,"open",!1),this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const By=i.z.object({keys:i.z.number().array(),downsampleFactor:i.z.number()}),jy=i.z.object({frame:ri,error:or.optional().nullable()}),Py="/frame/stream";class ai{constructor(e,t){u(this,"stream"),u(this,"adapter"),u(this,"downsampleFactor"),this.stream=new ni("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,t,{channels:s,downsampleFactor:n}){const a=await Ns.open(e,s),o=await t.stream(Py,By,jy),c=new ai(o,a);o.send({keys:a.keys,downsampleFactor:n??1});const[,l]=await o.receive();if(l!=null)throw l;return c}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(qe.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new ve((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}}let dt=class extends Qe.Observer{constructor(e,t){super(t),u(this,"streamer"),u(this,"closePromise"),this.streamer=e,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}};var oi=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.Error=3]="Error",r[r.SetAuthority=4]="SetAuthority",r))(oi||{}),Qt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(Qt||{});const Uy=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in Qt)return r;throw new Error(`invalid writer mode: ${r}`)}};new x(-1);const Ly=i.z.object({start:R.z.optional(),controlSubject:ct.subjectZ.optional(),keys:i.z.number().array().optional(),authorities:ct.Authority.z.array().optional(),mode:i.z.nativeEnum(Qt).optional(),errOnUnauthorized:i.z.boolean().optional(),enableAutoCommit:i.z.boolean().optional(),autoIndexPersistInterval:x.z.optional()}),_y=i.z.object({command:i.z.nativeEnum(oi),config:Ly.optional(),frame:ri.optional()}),Yy=i.z.object({ack:i.z.boolean(),command:i.z.nativeEnum(oi),error:or.optional().nullable()});var Tt;let Fy=(Tt=class{constructor(r,e){u(this,"stream"),u(this,"adapter"),this.stream=new ni("Writer",r),this.adapter=e}static async _open(r,e,{channels:t,start:s=R.now(),authorities:n=ct.Authority.Absolute,controlSubject:a,mode:o=1,errOnUnauthorized:c=!1,enableAutoCommit:l=!1,autoIndexPersistInterval:d=x.SECOND}){const f=await si.open(r,t),h=await e.stream(Tt.ENDPOINT,_y,Yy),I=new Tt(h,f);return await I.execute({command:0,config:{start:new R(s),keys:f.keys,controlSubject:a,authorities:S(n),mode:Uy(o),errOnUnauthorized:c,enableAutoCommit:l,autoIndexPersistInterval:d}}),I}async write(r,e){const t=await this.adapter.adapt(r,e);return this.stream.send({command:1,frame:t.toPayload()}),!0}async setAuthority(r,e){let t;if(typeof r=="number"&&e==null)t={keys:[],authorities:[r]};else{let s;typeof r=="string"||typeof r=="number"?s={[r]:e}:s=r,s=await this.adapter.adaptObjectKeys(s),t={keys:Object.keys(s).map(n=>Number(n)),authorities:Object.values(s)}}return(await this.execute({command:4,config:t})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const r=await this.execute({command:3});return r.error!=null?as(r.error):null}async close(){await this.stream.closeAndAck()}async execute(r){for(this.stream.send(r);;){const e=await this.stream.receive();if(e.command===r.command)return e;console.warn("writer received unexpected response",e)}}get errorAccumulated(){return this.stream.received()}},u(Tt,"ENDPOINT","/frame/write"),Tt),qy=class{constructor(r,e,t){u(this,"streamClient"),u(this,"retriever"),u(this,"deleter"),this.streamClient=r,this.retriever=t,this.deleter=new Ay(e)}async openIterator(r,e,t){return await My._open(r,e,this.retriever,this.streamClient,t)}async openWriter(r){return(Array.isArray(r)||typeof r!="object")&&(r={channels:r}),await Fy._open(this.retriever,this.streamClient,r)}async openStreamer(r){return(Array.isArray(r)||typeof r!="object")&&(r={channels:r,downsampleFactor:1}),await ai._open(this.retriever,this.streamClient,r)}async write(r,e,t){if(t==null){const n=e,a=await this.openWriter({start:r,channels:Object.keys(n),mode:Qt.Persist});try{await a.write(n),await a.commit()}finally{await a.close()}return}const s=await this.openWriter({start:r,channels:e,mode:Qt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:x.MAX});try{await s.write(e,t)}finally{await s.close()}}async read(r,e){const{single:t}=Pe(e),s=await this.readFrame(r,e);return t?s.get(e):s}async readFrame(r,e){const t=await this.openIterator(r,e),s=new ve;try{for await(const n of t)s.push(n)}finally{await t.close()}return s}async delete(r,e){const{normalized:t,variant:s}=Pe(r);return s==="keys"?await this.deleter.delete({keys:t,bounds:e}):await this.deleter.delete({names:t,bounds:e})}};const Gy=ct.Authority,Vy=ct.stateZ(i.z.number()),Wy=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`};class Yl extends dt{constructor(e){super(e,t=>{const s=this.codec.decode(t.series[0].buffer);return this.merge(s),[s.transfers,!0]}),u(this,"states"),u(this,"codec"),this.states=new Map,this.codec=new pt.JSONCodec}subjects(){const e=new Map;return this.states.forEach(t=>e.set(t.subject.key,t.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(t=>{t.from==null&&t.to==null&&console.warn("Invalid transfer: ",t),t.to==null?this.states.delete(t.from.resource):this.states.set(t.to.resource,t.to)})}}const Zy="sy_node_1_control";let Fl=class{constructor(r){u(this,"framer"),this.framer=r}async openStateTracker(){const r=await this.framer.openStreamer(Zy);return new Yl(r)}};const Ky=Object.freeze(Object.defineProperty({__proto__:null,Authority:Gy,Client:Fl,StateTracker:Yl,stateZ:Vy,transferString:Wy},Symbol.toStringTag,{value:"Module"}));let Jy=class{constructor(r,e,t){u(this,"tasks"),u(this,"racks"),u(this,"devices"),this.tasks=r,this.racks=e,this.devices=t}};const dr=i.z.number(),li=i.z.object({key:dr,name:i.z.string()}),Hy=li.partial({key:!0}),ci=i.z.string(),Is=i.z.object({key:ci,rack:dr,name:i.z.string(),make:i.z.string(),model:i.z.string(),location:i.z.string(),configured:i.z.boolean().optional(),properties:i.z.record(i.z.unknown()).or(i.z.string().transform(r=>r===""?{}:pt.JSON_CODEC.decodeString(r)))}),Xy=Is.extend({properties:i.z.unknown().transform(r=>pt.JSON_CODEC.encodeString(r))}),yt=async(r,e,t,s)=>{const n=await r.openStreamer([e,t]),a=o=>{const c=[];return t!=null&&c.push(...o.get(t).series.flatMap(l=>s("delete",l))),e!=null&&c.push(...o.get(e).series.flatMap(l=>s("set",l))),[c,c.length>0]};return new dt(n,a)},Qy="sy_device_set",em="sy_device_delete",Ks="/hardware/device/retrieve",tm="/hardware/device/create",rm="/hardware/device/delete",sm=i.z.object({devices:Xy.array()}),nm=i.z.object({devices:Is.array()}),im=i.z.object({keys:ci.array()}),am=i.z.object({}),Js=i.z.object({search:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),keys:ci.array().optional(),names:i.z.string().array().optional(),makes:i.z.string().array().optional()}),Hs=i.z.object({devices:fe(Is)});let om=class{constructor(r,e){u(this,"type","device"),u(this,"client"),u(this,"frameClient"),this.client=r,this.frameClient=e}async retrieve(r,e){const t=!Array.isArray(r),s=await O(this.client,Ks,{keys:S(r),...e},Js,Hs);return zs("Device",r,s.devices,t),t?s.devices[0]:s.devices}async search(r,e){return(await O(this.client,Ks,{search:r,...e},Js,Hs)).devices}async page(r,e,t){return(await O(this.client,Ks,{offset:r,limit:e,...t},Js,Hs)).devices}async create(r){const e=!Array.isArray(r),t=await O(this.client,tm,{devices:S(r)},sm,nm);return e?t.devices[0]:t.devices}async delete(r){await O(this.client,rm,{keys:S(r)},im,am)}async openDeviceTracker(){return await yt(this.frameClient,Qy,em,lm)}newSearcherWithOptions(r){return{type:this.type,search:async e=>await this.search(e,r),retrieve:async e=>await this.retrieve(e,r),page:async(e,t)=>await this.page(e,t,r)}}};const lm=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(Is).map(t=>({variant:r,key:t.key,value:t})),Xs="/hardware/rack/retrieve",cm="/hardware/rack/create",um="/hardware/rack/delete",Qs=i.z.object({keys:dr.array().optional(),names:i.z.string().array().optional(),search:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),en=i.z.object({racks:fe(li)}),hm=i.z.object({racks:Hy.array()}),dm=i.z.object({racks:li.array()}),fm=i.z.object({keys:dr.array()}),pm=i.z.object({});let gm=class{constructor(r,e,t){u(this,"type","rack"),u(this,"client"),u(this,"frameClient"),u(this,"tasks"),this.client=r,this.frameClient=e,this.tasks=t}async delete(r){await O(this.client,um,{keys:S(r)},fm,pm)}async create(r){const e=!Array.isArray(r),t=await O(this.client,cm,{racks:S(r)},hm,dm),s=this.sugar(t.racks);return e?s[0]:s}async search(r){const e=await O(this.client,Xs,{search:r},Qs,en);return this.sugar(e.racks)}async page(r,e){const t=await O(this.client,Xs,{offset:r,limit:e},Qs,en);return this.sugar(t.racks)}async retrieve(r){const{variant:e,normalized:t,single:s}=Ss(r,{string:"names",number:"keys"}),n=await O(this.client,Xs,{[e]:t},Qs,en),a=this.sugar(n.racks);return zs("Rack",r,a,s),s?a[0]:a}sugar(r){return r.map(({key:e,name:t})=>new ym(e,t,this.tasks))}};class ym{constructor(e,t,s){u(this,"key"),u(this,"name"),u(this,"tasks"),this.key=e,this.name=t,this.tasks=s}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const mt=i.z.union([i.z.string(),i.z.bigint().transform(r=>r.toString()),i.z.number().transform(r=>r.toString())]),us=i.z.object({task:mt,variant:i.z.string(),key:i.z.string().optional(),details:i.z.record(i.z.unknown()).or(i.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(i.z.array(i.z.unknown())).or(i.z.null())}),xs=i.z.object({key:mt,name:i.z.string(),type:i.z.string(),internal:i.z.boolean().optional(),config:i.z.record(i.z.unknown()).or(i.z.string().transform(r=>r===""?{}:pt.JSON_CODEC.decodeString(r))),state:us.optional().nullable(),snapshot:i.z.boolean().optional()}),mm=xs.omit({key:!0}).extend({key:mt.transform(r=>r.toString()).optional(),config:i.z.unknown().transform(r=>pt.JSON_CODEC.encodeString(r))}),ql=i.z.object({task:mt,type:i.z.string(),key:i.z.string(),args:i.z.record(i.z.unknown()).or(i.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),Kt="sy_task_state",nt="sy_task_cmd",St=new Error("Task not created");class wm{constructor(e,t,s,n,a=!1,o=!1,c,l=null,d=null,f=null){u(this,"key"),u(this,"name"),u(this,"internal"),u(this,"type"),u(this,"config"),u(this,"snapshot"),u(this,"state"),u(this,"frameClient"),u(this,"ontologyClient"),u(this,"rangeClient"),this.key=e,this.name=t,this.type=s,this.config=n,this.internal=a,this.snapshot=o,c!==null&&(this.state=c),this.frameClient=l,this.ontologyClient=d,this.rangeClient=f}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return new M({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw St;const s=await this.frameClient.openWriter(nt),n=lp.id();return await s.write(nt,[{task:this.key,type:e,key:n,args:t}]),await s.close(),n}async executeCommandSync(e,t,s){if(this.frameClient==null)throw St;const n=await this.frameClient.openStreamer(Kt),a=await this.executeCommand(e,t);let o;const c=new Promise(l=>setTimeout(()=>l(!1),new x(s).milliseconds));for(;;){const l=await Promise.any([n.read(),c]);if(l===!1)throw new Error("Command timed out");const d=us.safeParse(l.at(-1).sy_task_state);if(d.success){if(o=d.data,o.key===a)break}else console.error(d.error)}return n.close(),o}async openStateObserver(){if(this.frameClient==null)throw St;return new dt(await this.frameClient.openStreamer(Kt),e=>{const t=e.get(Kt);if(t.length===0)return[null,!1];const s=us.safeParse(t.at(-1));if(!s.success)return console.error(s.error),[null,!1];const n=s.data;return n.task!==this.key?[null,!1]:[n,!0]})}async openCommandObserver(){if(this.frameClient==null)throw St;return new dt(await this.frameClient.openStreamer(nt),e=>{const t=e.get(nt);if(t.length===0)return[null,!1];const s=ql.safeParse(t.at(-1));if(!s.success)return console.error(s.error),[null,!1];const n=s.data;return n.task!==this.key?[null,!1]:[n,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw St;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const bm=i.z.object({rack:dr.optional(),keys:i.z.string().array().optional(),names:i.z.string().array().optional(),offset:i.z.number().optional(),limit:i.z.number().optional(),includeState:i.z.boolean().optional()}),vm=i.z.object({tasks:fe(xs)}),Om="/hardware/task/retrieve",Tm="/hardware/task/create",Sm="/hardware/task/delete",zm="/hardware/task/copy",Em=i.z.object({tasks:mm.array()}),Nm=i.z.object({tasks:xs.array()}),Im=i.z.object({keys:mt.array()}),xm=i.z.object({}),Am=i.z.object({key:mt,name:i.z.string(),snapshot:i.z.boolean()}),km=i.z.object({task:xs});let Cm=class{constructor(r,e,t,s){u(this,"type","task"),u(this,"client"),u(this,"frameClient"),u(this,"ontologyClient"),u(this,"rangeClient"),this.client=r,this.frameClient=e,this.ontologyClient=t,this.rangeClient=s}async create(r){const e=!Array.isArray(r),t=await O(this.client,Tm,{tasks:S(r)},Em,Nm),s=this.sugar(t.tasks);return e?s[0]:s}async delete(r){await O(this.client,Sm,{keys:S(r)},Im,xm)}async search(r){return await this.execRetrieve({keys:[r]})}async page(r,e){return await this.execRetrieve({offset:r,limit:e})}async list(r={}){return this.sugar(await this.execRetrieve(r))}async retrieve(r,e){const{single:t,normalized:s,variant:n}=Ss(r,{number:"rack",string:"keys"},{convertNumericStrings:!1}),a={...e};n==="rack"?a.rack=r:a.keys=s;const o=await this.execRetrieve(a),c=this.sugar(o);return t&&n!=="rack"?c[0]:c}async copy(r,e,t){const s=await O(this.client,zm,{key:r,name:e,snapshot:t},Am,km);return this.sugar([s.task])[0]}async retrieveByName(r,e){const t=await this.execRetrieve({names:[r],rack:e});return zs("Task",r,t,!0),this.sugar(t)[0]}async execRetrieve(r){return(await O(this.client,Om,r,bm,vm)).tasks}sugar(r){return r.map(({key:e,name:t,type:s,config:n,state:a,internal:o,snapshot:c})=>new wm(e,t,s,n,o,c,a,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await yt(this.frameClient,"sy_task_set","sy_task_delete",(r,e)=>Array.from(e).map(t=>({variant:r,key:t.toString(),value:t.toString()})))}async openStateObserver(){return new dt(await this.frameClient.openStreamer(Kt),r=>{const e=r.get(Kt);if(e.length===0)return[null,!1];const t=us.safeParse(e.at(-1));return t.success?[t.data,!0]:(console.error(t.error),[null,!1])})}async openCommandObserver(){return new dt(await this.frameClient.openStreamer(nt),r=>{const e=r.get(nt);if(e.length===0)return[null,!1];const t=ql.safeParse(e.at(-1));return t.success?[t.data,!0]:(console.error(t.error),[null,!1])})}};const fr=i.z.string().uuid(),As=i.z.object({key:fr,name:i.z.string().min(1),color:i.z.string()}),Rm=i.z.object({keys:fr.array().optional(),for:ye.optional(),search:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),$m=i.z.object({labels:fe(As)}),Gl=class Vl{constructor(e){u(this,"client"),this.client=e}async retrieve(e){const t=S(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,s]=await this.client.send(Vl.ENDPOINT,e,Rm,$m);if(s!=null)throw s;return t.labels}};u(Gl,"ENDPOINT","/label/retrieve");let Mm=Gl;const Dm=As.extend({key:fr.optional()}),Bm=i.z.object({labels:Dm.array()}),jm=i.z.object({labels:As.array()}),Pm=i.z.object({keys:fr.array()}),Wl=i.z.object({id:ye,labels:fr.array(),replace:i.z.boolean().optional()}),Um=Wl.omit({replace:!0}),tn=i.z.object({}),Lm="/label/create",_m="/label/delete",Ym="/label/set",Fm="/label/remove";let qm=class{constructor(r){u(this,"client"),this.client=r}async create(r){return(await O(this.client,Lm,{labels:S(r)},Bm,jm)).labels}async delete(r){await O(this.client,_m,{keys:S(r)},Pm,tn)}async set(r,e,{replace:t}={}){await O(this.client,Ym,{id:r,labels:e,replace:t},Wl,tn)}async remove(r,e){await O(this.client,Fm,{id:r,labels:e},Um,tn)}};const Gm="sy_label_set",Vm="sy_label_delete";let Wm=class{constructor(r,e,t){u(this,"type","label"),u(this,"retriever"),u(this,"writer"),u(this,"frameClient"),u(this,"ontology"),this.writer=new qm(r),this.retriever=new Mm(r),this.frameClient=e,this.ontology=t}async search(r){return await this.retriever.search(r)}async retrieve(r){const e=Array.isArray(r),t=await this.retriever.retrieve(r);return e?t:t[0]}async retrieveFor(r){return await this.retriever.retrieveFor(new M(r))}async label(r,e,t={}){await this.writer.set(new M(r),e,t)}async removeLabels(r,e){await this.writer.remove(new M(r),e)}async page(r,e){return await this.retriever.page(r,e)}async create(r){const e=Array.isArray(r),t=await this.writer.create(r);return e?t:t[0]}async delete(r){await this.writer.delete(r)}async openChangeTracker(){return await yt(this.frameClient,Gm,Vm,Zm)}async trackLabelsOf(r){const e=new Qe.Observer,t=(await this.retrieveFor(r)).map(s=>({id:new M({key:s.key,type:"label"}),key:s.key,name:s.name,data:s}));return(await this.ontology.openDependentTracker({target:new M(r),dependents:t,relationshipType:"labeled_by"})).onChange(s=>e.notify(s.map(n=>{var a,o;return{key:n.id.key,color:(a=n.data)==null?void 0:a.color,name:(o=n.data)==null?void 0:o.name}}))),e}};const Zm=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(As).map(t=>({variant:r,key:t.key,value:t})),ge=i.z.string().uuid(),pr=i.z.object({key:ge,name:i.z.string().min(1),timeRange:ne.z,color:i.z.string().optional()}),Zl=pr.extend({key:i.z.string().uuid().optional()}),Kl=r=>{const e=S(r),t=e.length===0;let s=!1;return t||(s=ge.safeParse(e[0]).success),{single:!Array.isArray(r),variant:s?"keys":"names",normalized:e,actual:r,empty:t}},Jl="range",Hl="range-alias",Km=r=>new M({type:Jl,key:r}),Jm=r=>new M({type:Hl,key:r}),Hm="sy_range_alias_set",Xm="sy_range_alias_delete",Qm=i.z.object({range:ge,aliases:i.z.string().array()}),ew=i.z.object({aliases:i.z.record(i.z.string(),We)}),tw=i.z.object({range:ge,aliases:i.z.record(We.or(i.z.string()),i.z.string())}),rw=i.z.unknown(),sw=i.z.object({range:ge,channels:We.array()}),nw=i.z.unknown(),iw=i.z.object({range:ge}),aw=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),Ft=class qt{constructor(e,t,s){u(this,"frameClient"),u(this,"cache",new Map),u(this,"client"),u(this,"rangeKey"),this.rangeKey=e,this.cache=new Map,this.client=s,this.frameClient=t}async resolve(e){const t=[],s=typeof e=="string",n={};if(s){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?n[o]=c:t.push(o)});if(t.length===0)return n;const a=await O(this.client,qt.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Qm,ew);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),s?a.aliases[t[0]]:{...n,...a.aliases}}async set(e){await O(this.client,qt.SET_ENDPOINT,{range:this.rangeKey,aliases:e},tw,rw)}async list(){return(await O(this.client,qt.LIST_ENDPOINT,{range:this.rangeKey},iw,aw)).aliases}async delete(e){await O(this.client,qt.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},sw,nw)}async openChangeTracker(){return await yt(this.frameClient,Hm,Xm,uw(this.rangeKey))}};u(Ft,"SET_ENDPOINT","/range/alias/set"),u(Ft,"RESOLVE_ENDPOINT","/range/alias/resolve"),u(Ft,"LIST_ENDPOINT","/range/alias/list"),u(Ft,"DELETE_ENDPOINT","/range/alias/delete");let ow=Ft;const lw=i.z.object({range:ge,channel:We,alias:i.z.string()}),cw="---",uw=r=>(e,t)=>e==="delete"?t.toStrings().filter(s=>s.split(cw)[0]===r).map(s=>({variant:e,key:s,value:void 0})):t.parseJSON(lw).map(s=>({variant:e,key:s.alias,value:s})),hw=i.z.object({range:ge,keys:i.z.string().array()}),ui=i.z.object({range:ge,key:i.z.string(),value:i.z.string()}),dw=i.z.object({pairs:fe(ui)}),fw=i.z.object({range:ge,pairs:ui.array()}),pw=i.z.object({range:ge,keys:i.z.string().array()}),es=class ts{constructor(e,t,s){u(this,"rangeKey"),u(this,"client"),u(this,"frameClient"),this.rangeKey=e,this.client=t,this.frameClient=s}async get(e){const t=await O(this.client,ts.GET_ENDPOINT,{range:this.rangeKey,keys:S(e)},hw,dw);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(s=>[s.key,s.value]))}async list(){return this.get([])}async set(e,t=""){let s;Jn(e)?s=Object.entries(e).map(([n,a])=>({range:this.rangeKey,key:n,value:a})):s=[{range:this.rangeKey,key:e,value:t}],await O(this.client,ts.SET_ENDPOINT,{range:this.rangeKey,pairs:s},fw,i.z.unknown())}async delete(e){await O(this.client,ts.DELETE_ENDPOINT,{range:this.rangeKey,keys:S(e)},pw,i.z.unknown())}async openTracker(){return await yt(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(s=>{const[n,a]=s.split("<--->",2);return{variant:e,key:s,value:{range:n,key:a,value:""}}}):t.parseJSON(ui).map(s=>({variant:e,key:`${s.range}${s.key}`,value:s})))}};u(es,"GET_ENDPOINT","/range/kv/get"),u(es,"SET_ENDPOINT","/range/kv/set"),u(es,"DELETE_ENDPOINT","/range/kv/delete");let Bn=es;const rn=r=>new M({type:"range",key:r});class Xl{constructor(e,t=ne.ZERO,s,n,a,o,c,l,d,f,h){u(this,"key"),u(this,"name"),u(this,"kv"),u(this,"timeRange"),u(this,"color"),u(this,"channels"),u(this,"aliaser"),u(this,"frameClient"),u(this,"labelClient"),u(this,"ontologyClient"),u(this,"rangeClient"),this.key=s,this.name=e,this.timeRange=t,this.frameClient=a,this.color=n,this.kv=o,this.aliaser=c,this.channels=l,this.labelClient=d,this.ontologyClient=f,this.rangeClient=h}get ontologyID(){return new M({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const s=await this.channels.retrieve(e);if(s.length===0)throw new Te(`Channel ${e} does not exist`);await this.aliaser.set({[s[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(rn(this.key))}async addLabel(...e){await this.labelClient.label(rn(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(rn(this.key),e)}async openChildRangeTracker(){const e=new Qe.Observer,t=(await this.retrieveChildren()).map(n=>{const a=new M({key:n.key,type:"range"});return{id:a,key:a.toString(),name:n.name,data:n.payload}}),s=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return s.onChange(n=>e.notify(this.rangeClient.resourcesToRanges(n))),e.setCloser(async()=>await s.close()),e}async openParentRangeTracker(){const e=new Qe.Observer,t=await this.retrieveParent();if(t==null)return null;const s=new M({key:t.key,type:"range"}),n={id:s,key:s.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[n],relationshipDirection:"to"});return a.onChange(o=>{const c=this.rangeClient.resourcesToRanges(o);if(c.length===0)return;const l=c[0];e.notify(l)}),e.setCloser(async()=>await a.close()),e}}const gw=(r,e)=>up(r.timeRange,e.timeRange),yw=i.z.object({keys:ge.array().optional(),names:i.z.array(i.z.string()).optional(),term:i.z.string().optional(),overlapsWith:ne.z.optional(),limit:i.z.number().int().optional(),offset:i.z.number().int().optional()}),mw="/range/retrieve",ww=i.z.object({ranges:fe(pr)});let Ql=class{constructor(r,e,t,s,n,a){u(this,"type","range"),u(this,"frameClient"),u(this,"writer"),u(this,"unaryClient"),u(this,"channels"),u(this,"labelClient"),u(this,"ontologyClient"),this.frameClient=r,this.writer=e,this.unaryClient=t,this.channels=s,this.labelClient=n,this.ontologyClient=a}async create(r,e){const t=!Array.isArray(r),s=this.sugarMany(await this.writer.create(S(r),e));return t?s[0]:s}async rename(r,e){await this.writer.rename(r,e)}async delete(r){await this.writer.delete(S(r))}async search(r){return this.sugarMany(await this.execRetrieve({term:r}))}async page(r,e){return this.sugarMany(await this.execRetrieve({offset:r,limit:e}))}async retrieve(r){if(typeof r=="object"&&"start"in r)return await this.execRetrieve({overlapsWith:new ne(r)});const{single:e,actual:t,variant:s,normalized:n,empty:a}=Kl(r);if(a)return[];const o=await this.execRetrieve({[s]:n});if(!e)return o;if(o.length===0)throw new ut(`range matching ${t} not found`);if(o.length>1)throw new ht(`multiple ranges matching ${t} found`);return o[0]}getKV(r){return new Bn(r,this.unaryClient,this.frameClient)}async execRetrieve(r){const{ranges:e}=await O(this.unaryClient,mw,r,yw,ww);return this.sugarMany(e)}async retrieveParent(r){const e=await this.ontologyClient.retrieveParents({key:r,type:"range"});if(e.length===0)return null;const t=e[0];return t.id.type!=="range"?null:await this.retrieve(t.id.key)}sugarOne(r){return new Xl(r.name,r.timeRange,r.key,r.color,this.frameClient,new Bn(r.key,this.unaryClient,this.frameClient),new ow(r.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(r){return r.map(e=>this.sugarOne(e))}async openTracker(){return await yt(this.frameClient,"sy_range_set","sy_range_delete",(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):this.sugarMany(e.parseJSON(pr)).map(t=>({variant:r,key:t.key,value:t})))}resourcesToRanges(r){return r.map(e=>this.resourceToRange(e))}resourceToRange(r){var e,t,s;return this.sugarOne({key:r.id.key,name:(e=r.data)==null?void 0:e.name,timeRange:new ne((t=r.data)==null?void 0:t.timeRange),color:(s=r.data)==null?void 0:s.color})}};const bw=i.z.object({ranges:pr.array()}),vw=i.z.object({parent:ye.optional(),ranges:Zl.array()}),Ow=i.z.object({keys:ge.array()}),Tw=i.z.object({}),Sw=i.z.object({key:ge,name:i.z.string()}),zw=i.z.object({}),Ew="/range/create",Nw="/range/delete",Iw="/range/rename";class ec{constructor(e){u(this,"client"),this.client=e}async rename(e,t){await O(this.client,Iw,{key:e,name:t},Sw,zw)}async create(e,t){return(await O(this.client,Ew,{ranges:e,...t},vw,bw)).ranges}async delete(e){await O(this.client,Nw,{keys:e},Ow,Tw)}}const xw=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:Hl,Client:Ql,KV:Bn,ONTOLOGY_TYPE:Jl,Range:Xl,Writer:ec,analyzeParams:Kl,keyZ:ge,newPayloadZ:Zl,payloadZ:pr,rangeAliasOntologyID:Jm,rangeOntologyID:Km,sort:gw},Symbol.toStringTag,{value:"Module"})),Aw="/api/v1/";class kw{constructor(e,t={},s=!1){u(this,"url"),u(this,"unary"),u(this,"stream"),u(this,"secure"),this.secure=s,this.url=e.child(Aw);const n=new pt.JSONCodec;this.unary=Qd(new Xd(this.url,n,this.secure),t),this.stream=new cf(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const ks=i.z.string().uuid(),hi=i.z.object({key:i.z.string(),name:i.z.string(),data:lr.or(i.z.string().transform(r=>JSON.parse(r)))}),Cw="/workspace/lineplot/retrieve",Rw="/workspace/lineplot/create",$w="/workspace/lineplot/rename",Mw="/workspace/lineplot/set-data",Dw="/workspace/lineplot/delete",Bw=hi.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),jw=i.z.object({keys:ks.array()}),Pw=i.z.object({workspace:i.z.string(),linePlots:Bw.array()}),Uw=i.z.object({key:ks,name:i.z.string()}),Lw=i.z.object({key:ks,data:i.z.string()}),_w=i.z.object({keys:ks.array()}),Yw=i.z.object({linePlots:fe(hi)}),Fw=i.z.object({linePlots:hi.array()}),sn=i.z.object({});let qw=class{constructor(r){u(this,"client"),this.client=r}async create(r,e){const t=Array.isArray(e),s=S(e),n=await O(this.client,Rw,{workspace:r,linePlots:s},Pw,Fw);return t?n.linePlots:n.linePlots[0]}async rename(r,e){await O(this.client,$w,{key:r,name:e},Uw,sn)}async setData(r,e){await O(this.client,Mw,{key:r,data:JSON.stringify(e)},Lw,sn)}async retrieve(r){const e=Array.isArray(r),t=S(r),s=await O(this.client,Cw,{keys:t},jw,Yw);return e?s.linePlots:s.linePlots[0]}async delete(r){const e=S(r);await O(this.client,Dw,{keys:e},_w,sn)}};i.z.string().uuid();const di=i.z.object({key:i.z.string(),name:i.z.string(),data:lr.or(i.z.string().transform(r=>JSON.parse(r)))}),Gw="/workspace/log/retrieve",Vw="/workspace/log/create",Ww="/workspace/log/rename",Zw="/workspace/log/set-data",Kw="/workspace/log/delete",Jw=di.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Hw=i.z.object({keys:i.z.string().array()}),Xw=i.z.object({workspace:i.z.string(),logs:Jw.array()}),Qw=i.z.object({key:i.z.string(),name:i.z.string()}),eb=i.z.object({key:i.z.string(),data:i.z.string()}),tb=i.z.object({keys:i.z.string().array()}),rb=i.z.object({logs:di.array()}),sb=i.z.object({logs:di.array()}),nn=i.z.object({});let nb=class{constructor(r){u(this,"client"),this.client=r}async create(r,e){const t=Array.isArray(e),s=S(e),n=await O(this.client,Vw,{workspace:r,logs:s},Xw,sb);return t?n.logs:n.logs[0]}async rename(r,e){await O(this.client,Ww,{key:r,name:e},Qw,nn)}async setData(r,e){await O(this.client,Zw,{key:r,data:JSON.stringify(e)},eb,nn)}async retrieve(r){const e=Array.isArray(r),t=S(r),s=await O(this.client,Gw,{keys:t},Hw,rb);return e?s.logs:s.logs[0]}async delete(r){const e=S(r);await O(this.client,Kw,{keys:e},tb,nn)}};i.z.string().uuid();const tc=i.z.object({key:i.z.string(),name:i.z.string(),data:lr.or(i.z.string().transform(r=>JSON.parse(r))),snapshot:i.z.boolean()}),rc=i.z.object({key:i.z.string(),name:i.z.string(),snapshot:i.z.boolean(),data:i.z.string().transform(r=>JSON.parse(r))}),ib="/workspace/schematic/retrieve",ab="/workspace/schematic/create",ob="/workspace/schematic/rename",lb="/workspace/schematic/set-data",cb="/workspace/schematic/delete",ub="/workspace/schematic/copy",hb=tc.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),db=i.z.object({keys:i.z.string().array()}),fb=i.z.object({workspace:i.z.string(),schematics:hb.array()}),pb=i.z.object({key:i.z.string(),name:i.z.string()}),gb=i.z.object({key:i.z.string(),data:i.z.string()}),yb=i.z.object({keys:i.z.string().array()}),mb=i.z.object({key:i.z.string(),name:i.z.string(),snapshot:i.z.boolean()}),wb=i.z.object({schematics:fe(rc)}),bb=i.z.object({schematics:rc.array()}),vb=i.z.object({schematic:tc}),an=i.z.object({});let Ob=class{constructor(r){u(this,"client"),this.client=r}async create(r,e){const t=Array.isArray(e),s=S(e),n=await O(this.client,ab,{workspace:r,schematics:s},fb,bb);return t?n.schematics:n.schematics[0]}async rename(r,e){await O(this.client,ob,{key:r,name:e},pb,an)}async setData(r,e){await O(this.client,lb,{key:r,data:JSON.stringify(e)},gb,an)}async retrieve(r){const e=Array.isArray(r),t=S(r),s=await O(this.client,ib,{keys:t},db,wb);return e?s.schematics:s.schematics[0]}async delete(r){const e=S(r);await O(this.client,cb,{keys:e},yb,an)}async copy(r,e,t){return(await O(this.client,ub,{key:r,name:e,snapshot:t},mb,vb)).schematic}};i.z.string().uuid();const Tb=i.z.object({key:i.z.string(),name:i.z.string(),data:lr.or(i.z.string().transform(r=>JSON.parse(r)))}),Sb="/workspace/table/retrieve",zb="/workspace/table/create",Eb="/workspace/table/rename",Nb="/workspace/table/set-data",Ib="/workspace/table/delete",xb=Tb.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),sc=i.z.object({key:i.z.string(),name:i.z.string(),data:i.z.string().transform(r=>JSON.parse(r))}),Ab=i.z.object({keys:i.z.string().array()}),kb=i.z.object({workspace:i.z.string(),tables:xb.array()}),Cb=i.z.object({key:i.z.string(),name:i.z.string()}),Rb=i.z.object({key:i.z.string(),data:i.z.string()}),$b=i.z.object({keys:i.z.string().array()}),Mb=i.z.object({tables:sc.array()}),Db=i.z.object({tables:sc.array()}),on=i.z.object({});let Bb=class{constructor(r){u(this,"client"),this.client=r}async create(r,e){const t=Array.isArray(e),s=S(e),n=await O(this.client,zb,{workspace:r,tables:s},kb,Db);return t?n.tables:n.tables[0]}async rename(r,e){await O(this.client,Eb,{key:r,name:e},Cb,on)}async setData(r,e){await O(this.client,Nb,{key:r,data:JSON.stringify(e)},Rb,on)}async retrieve(r){const e=Array.isArray(r),t=S(r),s=await O(this.client,Sb,{keys:t},Ab,Mb);return e?s.tables:s.tables[0]}async delete(r){const e=S(r);await O(this.client,Ib,{keys:e},$b,on)}};i.z.string().uuid();const nc=r=>JSON.parse(r),fi=i.z.object({key:i.z.string(),name:i.z.string(),layout:lr.or(i.z.string().transform(r=>nc(r)))}),vr="/workspace/retrieve",jb="/workspace/create",Pb="/workspace/rename",Ub="/workspace/set-layout",Lb="/workspace/delete",_b=fi.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Yb=fi.omit({layout:!0}).extend({layout:i.z.string().transform(r=>nc(r))}),Or=i.z.object({keys:i.z.string().array().optional(),search:i.z.string().optional(),author:i.z.string().uuid().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),Fb=i.z.object({workspaces:_b.array()}),qb=i.z.object({key:i.z.string(),name:i.z.string()}),Gb=i.z.object({key:i.z.string(),layout:i.z.string()}),Vb=i.z.object({keys:i.z.string().array()}),Tr=i.z.object({workspaces:fe(fi)}),Wb=i.z.object({workspaces:Yb.array()}),ln=i.z.object({});class Zb{constructor(e){u(this,"type","workspace"),u(this,"schematic"),u(this,"linePlot"),u(this,"log"),u(this,"table"),u(this,"client"),this.client=e,this.schematic=new Ob(e),this.linePlot=new qw(e),this.log=new nb(e),this.table=new Bb(e)}async create(e){const t=Array.isArray(e),s=S(e),n=await O(this.client,jb,{workspaces:s},Fb,Wb);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await O(this.client,Pb,{key:e,name:t},qb,ln)}async setLayout(e,t){await O(this.client,Ub,{key:e,layout:JSON.stringify(t)},Gb,ln)}async retrieve(e){const t=Array.isArray(e),s=S(e),n=await O(this.client,vr,{keys:s},Or,Tr);return t?n.workspaces:n.workspaces[0]}async retrieveByAuthor(e){return(await O(this.client,vr,{author:e},Or,Tr)).workspaces}async search(e){return(await O(this.client,vr,{search:e},Or,Tr)).workspaces}async page(e,t){return(await O(this.client,vr,{offset:e,limit:t},Or,Tr)).workspaces}async delete(e){const t=S(e);await O(this.client,Lb,{keys:t},Vb,ln)}}const ic=i.z.object({host:i.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:i.z.number({required_error:"Port is required"}).or(i.z.string({required_error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:x.z.default(x.seconds(30)),secure:i.z.boolean().optional().default(!1),name:i.z.string().optional(),retry:Up.breakerConfig.optional()});class ac extends qy{constructor(e){const t=ic.parse(e),{host:s,port:n,username:a,password:o,connectivityPollFrequency:c,secure:l,retry:d}=t,f=new kw(new $p({host:s,port:Number(n)}),d,l);f.use(Kp);let h;a!=null&&o!=null&&(h=new Oy(f.unary,{username:a,password:o}),f.use(h.middleware()));const I=new ti(new ei(f.unary)),j=new Bl(f.unary,I);super(f.stream,f.unary,I),u(this,"createdAt"),u(this,"props"),u(this,"ranges"),u(this,"channels"),u(this,"auth"),u(this,"user"),u(this,"access"),u(this,"connectivity"),u(this,"ontology"),u(this,"workspaces"),u(this,"labels"),u(this,"hardware"),u(this,"control"),u(this,"transport"),u(this,"clientVersion","0.37.0"),this.createdAt=R.now(),this.props=t,this.auth=h,this.transport=f,this.channels=new Dl(this,I,f.unary,j),this.connectivity=new Ul(f.unary,c,this.clientVersion,t.name),this.control=new Fl(this),this.ontology=new dg(f.unary,this);const ie=new ec(this.transport.unary);this.labels=new Wm(this.transport.unary,this,this.ontology),this.ranges=new Ql(this,ie,this.transport.unary,I,this.labels,this.ontology),this.access=new Ig(this.transport.unary),this.user=new py(this.transport.unary),this.workspaces=new Zb(this.transport.unary);const P=new om(this.transport.unary,this),Oi=new Cm(this.transport.unary,this,this.ontology,this.ranges),Cc=new gm(this.transport.unary,this,Oi);this.hardware=new Jy(Oi,Cc,P)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}u(ac,"connectivity",Ul);const Kb=ct.Authority,jn=(r,e,t="")=>{try{return r.parse(e)}catch(s){if(s instanceof i.z.ZodError){const n=s.errors.map(a=>a.path.length===0?a.message:`${a.path.join(".")}: ${a.message}`);throw new Error(`${t} - ${n.join(`
66
- `)}`)}else throw s}};var Jb=Object.defineProperty,Hb=(r,e,t)=>e in r?Jb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ee=(r,e,t)=>Hb(r,typeof e!="symbol"?e+"":e,t);const Pn=class oc{constructor(e,t,s="",n=!1){ee(this,"_noop",!1),ee(this,"key"),ee(this,"path"),ee(this,"serviceName"),this.key=e,this.path=t,this.serviceName=s,this._noop=n}child(e){return new oc(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}};ee(Pn,"NOOP",new Pn("","",""));let pi=Pn;const Un=["debug","info","warn","error"],Xb=r=>{const e=Un.indexOf(r);return({level:t})=>Un.indexOf(t)>=e},Qb=r=>{const{include:e,exclude:t}=r;return({path:s})=>!(e!=null&&!e.some(n=>s.startsWith(n))||t!=null&&t.some(n=>s.startsWith(n)))},Ln=class lc{constructor(e={}){ee(this,"meta",pi.NOOP),ee(this,"filters");const{filters:t=[]}=e;this.filters=t}filter(e){return!this.meta.noop&&this.filters.every(t=>t({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const t=new lc({filters:this.filters});return t.meta=e,t}debug(e,t,s=!1){!this.filter("debug")&&!s||(t==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,Sr(t)))}info(e,t,s=!1){!this.filter("info")&&!s||(t==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,Sr(t)))}warn(e,t,s=!1){!this.filter("warn")&&!s||(t==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,Sr(t)))}error(e,t,s=!1){!this.filter("error")&&!s||(t==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,Sr(t)))}};ee(Ln,"NOOP",new Ln);let cc=Ln;const Sr=r=>typeof r=="function"?r():r;var ev=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},He="1.9.0",Ma=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function tv(r){var e=new Set([r]),t=new Set,s=r.match(Ma);if(!s)return function(){return!1};var n={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};if(n.prerelease!=null)return function(c){return c===r};function a(c){return t.add(c),!1}function o(c){return e.add(c),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var l=c.match(Ma);if(!l)return a(c);var d={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return d.prerelease!=null||n.major!==d.major?a(c):n.major===0?n.minor===d.minor&&n.patch<=d.patch?o(c):a(c):n.minor<=d.minor?o(c):a(c)}}var rv=tv(He),sv=He.split(".")[0],er=Symbol.for("opentelemetry.js.api."+sv),tr=ev;function gi(r,e,t,s){var n;s===void 0&&(s=!1);var a=tr[er]=(n=tr[er])!==null&&n!==void 0?n:{version:He};if(!s&&a[r]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(o.stack||o.message),!1}if(a.version!==He){var o=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+r+" does not match previously registered API v"+He);return t.error(o.stack||o.message),!1}return a[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+He+"."),!0}function rr(r){var e,t,s=(e=tr[er])===null||e===void 0?void 0:e.version;if(!(!s||!rv(s)))return(t=tr[er])===null||t===void 0?void 0:t[r]}function yi(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+He+".");var t=tr[er];t&&delete t[r]}var nv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),n,a=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(c){o={error:c}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return a},iv=function(r,e,t){if(arguments.length===2)for(var s=0,n=e.length,a;s<n;s++)(a||!(s in e))&&(a||(a=Array.prototype.slice.call(e,0,s)),a[s]=e[s]);return r.concat(a||Array.prototype.slice.call(e))},av=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return zt("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return zt("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return zt("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return zt("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return zt("verbose",this._namespace,e)},r}();function zt(r,e,t){var s=rr("diag");if(s)return t.unshift(e),s[r].apply(s,iv([],nv(t),!1))}var me;(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(me||(me={}));function ov(r,e){r<me.NONE?r=me.NONE:r>me.ALL&&(r=me.ALL),e=e||{};function t(s,n){var a=e[s];return typeof a=="function"&&r>=n?a.bind(e):function(){}}return{error:t("error",me.ERROR),warn:t("warn",me.WARN),info:t("info",me.INFO),debug:t("debug",me.DEBUG),verbose:t("verbose",me.VERBOSE)}}var lv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),n,a=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(c){o={error:c}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return a},cv=function(r,e,t){if(arguments.length===2)for(var s=0,n=e.length,a;s<n;s++)(a||!(s in e))&&(a||(a=Array.prototype.slice.call(e,0,s)),a[s]=e[s]);return r.concat(a||Array.prototype.slice.call(e))},uv="diag",sr=function(){function r(){function e(n){return function(){for(var a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];var c=rr("diag");if(c)return c[n].apply(c,cv([],lv(a),!1))}}var t=this,s=function(n,a){var o,c,l;if(a===void 0&&(a={logLevel:me.INFO}),n===t){var d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((o=d.stack)!==null&&o!==void 0?o:d.message),!1}typeof a=="number"&&(a={logLevel:a});var f=rr("diag"),h=ov((c=a.logLevel)!==null&&c!==void 0?c:me.INFO,n);if(f&&!a.suppressOverrideMessage){var I=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";f.warn("Current logger will be overwritten from "+I),h.warn("Current logger will overwrite one already registered from "+I)}return gi("diag",h,t,!0)};t.setLogger=s,t.disable=function(){yi(uv,t)},t.createComponentLogger=function(n){return new av(n)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}(),hv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),n,a=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(c){o={error:c}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return a},dv=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},fv=function(){function r(e){this._entries=e?new Map(e):new Map}return r.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},r.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=hv(e,2),s=t[0],n=t[1];return[s,n]})},r.prototype.setEntry=function(e,t){var s=new r(this._entries);return s._entries.set(e,t),s},r.prototype.removeEntry=function(e){var t=new r(this._entries);return t._entries.delete(e),t},r.prototype.removeEntries=function(){for(var e,t,s=[],n=0;n<arguments.length;n++)s[n]=arguments[n];var a=new r(this._entries);try{for(var o=dv(s),c=o.next();!c.done;c=o.next()){var l=c.value;a._entries.delete(l)}}catch(d){e={error:d}}finally{try{c&&!c.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return a},r.prototype.clear=function(){return new r},r}();sr.instance();function pv(r){return r===void 0&&(r={}),new fv(new Map(Object.entries(r)))}function gv(r){return Symbol.for(r)}var yv=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(s){return t._currentContext.get(s)},t.setValue=function(s,n){var a=new r(t._currentContext);return a._currentContext.set(s,n),a},t.deleteValue=function(s){var n=new r(t._currentContext);return n._currentContext.delete(s),n}}return r}(),mv=new yv,wv={get:function(r,e){if(r!=null)return r[e]},keys:function(r){return r==null?[]:Object.keys(r)}},bv={set:function(r,e,t){r!=null&&(r[e]=t)}},vv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),n,a=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(c){o={error:c}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return a},Ov=function(r,e,t){if(arguments.length===2)for(var s=0,n=e.length,a;s<n;s++)(a||!(s in e))&&(a||(a=Array.prototype.slice.call(e,0,s)),a[s]=e[s]);return r.concat(a||Array.prototype.slice.call(e))},Tv=function(){function r(){}return r.prototype.active=function(){return mv},r.prototype.with=function(e,t,s){for(var n=[],a=3;a<arguments.length;a++)n[a-3]=arguments[a];return t.call.apply(t,Ov([s],vv(n),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}(),Sv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var s=t.call(r),n,a=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(c){o={error:c}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return a},zv=function(r,e,t){if(arguments.length===2)for(var s=0,n=e.length,a;s<n;s++)(a||!(s in e))&&(a||(a=Array.prototype.slice.call(e,0,s)),a[s]=e[s]);return r.concat(a||Array.prototype.slice.call(e))},cn="context",Ev=new Tv,uc=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return gi(cn,e,sr.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,s){for(var n,a=[],o=3;o<arguments.length;o++)a[o-3]=arguments[o];return(n=this._getContextManager()).with.apply(n,zv([e,t,s],Sv(a),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return rr(cn)||Ev},r.prototype.disable=function(){this._getContextManager().disable(),yi(cn,sr.instance())},r}(),_n;(function(r){r[r.UNSET=0]="UNSET",r[r.OK=1]="OK",r[r.ERROR=2]="ERROR"})(_n||(_n={}));var Nv=uc.getInstance(),Iv=function(){function r(){}return r.prototype.inject=function(e,t){},r.prototype.extract=function(e,t){return e},r.prototype.fields=function(){return[]},r}(),mi=gv("OpenTelemetry Baggage Key");function hc(r){return r.getValue(mi)||void 0}function xv(){return hc(uc.getInstance().active())}function Av(r,e){return r.setValue(mi,e)}function kv(r){return r.deleteValue(mi)}var un="propagation",Cv=new Iv,Rv=function(){function r(){this.createBaggage=pv,this.getBaggage=hc,this.getActiveBaggage=xv,this.setBaggage=Av,this.deleteBaggage=kv}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalPropagator=function(e){return gi(un,e,sr.instance())},r.prototype.inject=function(e,t,s){return s===void 0&&(s=bv),this._getGlobalPropagator().inject(e,t,s)},r.prototype.extract=function(e,t,s){return s===void 0&&(s=wv),this._getGlobalPropagator().extract(e,t,s)},r.prototype.fields=function(){return this._getGlobalPropagator().fields()},r.prototype.disable=function(){yi(un,sr.instance())},r.prototype._getGlobalPropagator=function(){return rr(un)||Cv},r}(),$v=Rv.getInstance();const Da=["bench","debug","prod"],Mv=r=>e=>Da.indexOf(e)>=Da.indexOf(r),Yn=class dc{constructor(e,t=Mv("debug")){ee(this,"meta",pi.NOOP),ee(this,"tracer"),ee(this,"filter"),this.tracer=e,this.filter=t}child(e){const t=new dc(this.tracer,this.filter);return t.meta=e,t}debug(e,t){return this.trace(e,"debug",t)}bench(e,t){return this.trace(e,"bench",t)}prod(e,t){return this.trace(e,"prod",t)}trace(e,t,s){return this.meta.noop||!this.filter(t)?s(new gc(e)):this.tracer.startActiveSpan(e,n=>{const a=new pc(e,n),o=s(a);return n.end(),o})}propagate(e){if(this.meta.noop)return;const t=Nv.active();$v.inject(t,e,{set:(s,n,a)=>{s[n]=a}})}};ee(Yn,"NOOP",new Yn);let fc=Yn;class pc{constructor(e,t){ee(this,"key"),ee(this,"otel"),this.key=e,this.otel=t}set(e,t){this.otel.setAttribute(e,t)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:_n.ERROR}))}}class gc{constructor(e){ee(this,"key"),this.key=e}set(){}recordError(e){}}const Fn=class yc{constructor({key:e="",serviceName:t="",logger:s=cc.NOOP,tracer:n=fc.NOOP,noop:a=!1,__meta:o}){ee(this,"meta"),ee(this,"T"),ee(this,"L"),this.meta=o??new pi(e,e,t,a),this.T=n.child(this.meta),this.L=s.child(this.meta)}child(e){const t=this.meta.child(e);return new yc({__meta:t,tracer:this.T,logger:this.L})}};ee(Fn,"NOOP",new Fn({noop:!0}));let wi=Fn;const Dv=wi.NOOP,mc=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:wi,LOG_LEVELS:Un,Logger:cc,NOOP:Dv,NoopSpan:gc,Tracer:fc,_Span:pc,logLevelKeyFiler:Qb,logThresholdFilter:Xb},Symbol.toStringTag,{value:"Module"})),Bv=new Error("request for lock canceled");var jv=function(r,e,t,s){function n(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(s.next(f))}catch(h){o(h)}}function l(f){try{d(s.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):n(f.value).then(c,l)}d((s=s.apply(r,e||[])).next())})};class Pv{constructor(e,t=Bv){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((s,n)=>{const a={resolve:s,reject:n,weight:e,priority:t},o=wc(this._queue,c=>t<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return jv(this,arguments,void 0,function*(t,s=1,n=0){const[a,o]=yield this.acquire(s,n);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(s=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Uv(this._weightedWaiters[e-1],{resolve:s,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(s=>s.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const s=this._weightedWaiters[t-1];if(!s)continue;const n=s.findIndex(a=>a.priority<=e);(n===-1?s:s.splice(0,n)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Uv(r,e){const t=wc(r,s=>e.priority<=s.priority);r.splice(t+1,0,e)}function wc(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Lv=function(r,e,t,s){function n(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(s.next(f))}catch(h){o(h)}}function l(f){try{d(s.throw(f))}catch(h){o(h)}}function d(f){f.done?a(f.value):n(f.value).then(c,l)}d((s=s.apply(r,e||[])).next())})};class bi{constructor(e){this._semaphore=new Pv(1,e)}acquire(){return Lv(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}class Cs{constructor(e,t,s=new Map){T(this,"providers");T(this,"registry");T(this,"sender");T(this,"changedKeys");this.providers=s,this.registry=t,this.changedKeys=[],this.sender=e}propagateState(e,t,s=[]){this.sender.send({key:e,state:t},s)}copyAndMerge(e){const t=new Cs(this.sender,this.registry,new Map);return e==null||e.providers.forEach((s,n)=>t.providers.set(n,s)),this.providers.forEach((s,n)=>t.providers.set(n,s)),t.changedKeys=[],t}get changed(){return this.changedKeys.length>0}set(e,t,s=!0){this.providers.set(e,t),s&&this.changedKeys.push(e)}setIfNotHas(e,t){this.providers.has(e)||this.set(e,t)}async create(e){const t=this.registry[e.type];if(t==null)throw new Error(`[AetherRoot.create] - could not find component ${e.type}`);const s=new t(e);return await s.internalUpdate(e),s}getOptional(e){return this.providers.get(e)??null}has(e){return this.providers.has(e)}get(e){const t=this.getOptional(e);if(t==null)throw new Error(`[AetherRoot.get] - could not find provider ${e}`);return t}}class Rs{constructor(e){T(this,"type");T(this,"key");T(this,"_ctx");T(this,"_internalState");T(this,"_state");T(this,"_prevState");T(this,"_deleted",!1);T(this,"instrumentation");T(this,"schema");this.type=e.type,this.key=e.path[0],this._ctx=e.ctx,this._internalState={},this.instrumentation=e.instrumentation.child(`${this.type}(${this.key})`)}get _schema(){if(this.schema==null)throw new J(`[AetherLeaf] - expected subclass to define component schema, but none was found.
67
- Make sure to defne a property 'schema' on the class.`);return this.schema}setState(e){const t=Wn(e,this._state);this._prevState={...this._state},this._state=jn(this._schema,t,`${this.type}:${this.key}`),this.ctx.propagateState(this.key,t)}get ctx(){if(this._ctx==null)throw new we("context not defined");return this._ctx}get state(){if(this._state==null)throw new we("state not defined");return this._state}get internal(){return this._internalState}get prevState(){return this._prevState}get deleted(){return this._deleted}async internalUpdate({variant:e,path:t,ctx:s,state:n}){if(!this.deleted){if(this._ctx=s,e==="state"){this.validatePath(t);const a=jn(this._schema,n,`${this.type}:${this.key}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:ro.difference(this.state,a)})):this.instrumentation.L.debug("setting initial state",{state:n}),this._prevState=this._state??a,this._state=a}else this.instrumentation.L.debug("updating context");await this.afterUpdate()}}async internalDelete(e){this.validatePath(e),this._deleted=!0,await this.afterDelete()}beforeUpdate(){}async afterUpdate(){}async afterDelete(){}validatePath(e){if(e.length===0)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received an empty path`);const t=e[e.length-1];if(e.length>1)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received a subPath ${e.join(".")} but is a leaf`);if(t!==this.key)throw new we(`[Leaf.setState] - ${this.type}:${this.key} received a key ${t} but expected ${this.key}`)}}class gr extends Rs{constructor(t){super(t);T(this,"_children");this._children=new Map}get children(){return Array.from(this._children.values())}async internalUpdate(t){const{variant:s,path:n}=t;if(s==="context")return this._ctx=t.ctx.copyAndMerge(this._ctx),await this.updateContext({...t,ctx:this.ctx});const[a,o]=this.getRequiredKey(n),c={...t,ctx:this.ctx};return o.length===0?await this.updateThis(a,c):await this.updateChild(o,c)}async updateContext(t){await super.internalUpdate(t);for(const s of this.children)await s.internalUpdate({...t,ctx:this.ctx,variant:"context"})}async updateChild(t,s){const n=t[0],a=this.getChild(n);if(a!=null)return await a.internalUpdate({...s,path:t});if(t.length>1)throw new Error(`[Composite.setState] - ${this.type}:${this.key} could not find child with key ${n} while updating `);this._children.set(n,await s.ctx.create({...s,path:t}))}async updateThis(t,s){const n=s.ctx.copyAndMerge(this._ctx);if(t!==this.key)throw new we(`[Composite.update] - ${this.type}:${this.key} received a key ${t} but expected ${this.key}`);if(await super.internalUpdate({...s,ctx:n}),!!n.changed){this.instrumentation.L.debug("context changed",{changedKeys:n.changedKeys});for(const a of this.children)await a.internalUpdate({...s,ctx:this.ctx,variant:"context"})}}async internalDelete(t){const[s,n]=this.getRequiredKey(t);if(n.length===0){if(s!==this.key)throw new Error(`[Composite.delete] - ${this.type}:${this.key} received a key ${s} but expected ${this.key}`);const o=this.children;this._children=new Map;for(const c of o)await c.internalDelete([c.key]);await super.internalDelete([this.key])}const a=this.getChild(n[0]);a!=null&&(n.length>1?await a.internalDelete(n):(this._children.delete(a.key),await a.internalDelete(n)))}getRequiredKey(t,s){const[n,...a]=t;if(n==null)throw new Error(`Composite ${this.type}:${this.key} received an empty path${s!=null?` for ${s}`:""}`);return[n,a]}getChild(t){return this._children.get(t)??null}childrenOfType(...t){return this.children.filter(s=>t.includes(s.type))}}const _v=i.z.object({}),$e=class $e extends gr{constructor({worker:t,registry:s,instrumentation:n=mc.Instrumentation.NOOP}){const o={ctx:new Cs(t,s,new Map),...$e.ZERO_UPDATE,instrumentation:n};super(o);T(this,"wrap");T(this,"schema",$e.schema);T(this,"mu",new bi);this.mu.runExclusive(async()=>await this.internalUpdate(o)),this.wrap=t,this.wrap.handle(c=>{this.mu.runExclusive(async()=>await this.handle(c))})}async handle(t){if(t.variant==="delete")await this.internalDelete(t.path);else{const s={...t,variant:"state",ctx:this.ctx,instrumentation:this.instrumentation};await this.internalUpdate(s)}}};T($e,"TYPE","root"),T($e,"KEY","root"),T($e,"ZERO_UPDATE",{path:[$e.KEY],type:$e.TYPE,variant:"state",state:{}}),T($e,"schema",_v);let hs=$e;const bc=r=>new hs(r),Yv=Object.freeze(Object.defineProperty({__proto__:null,Composite:gr,Context:Cs,Leaf:Rs,Root:hs,render:bc},Symbol.toStringTag,{value:"Module"})),rs=(r,e)=>p.Eo.construct(p.Eo.left(r)-e.x,p.Eo.top(r)-e.y,p.Eo.width(r)+e.x*2,p.Eo.height(r)+e.y*2);class ds{constructor(e,t=p.b.XY.IDENTITY){T(this,"scale_");T(this,"wrapped");this.wrapped=e,this.scale_=t}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}reset(){this.wrapped.reset()}applyScale(e){return new ds(this,e)}get canvas(){return this.wrapped.canvas}get miterLimit(){return this.wrapped.miterLimit}set miterLimit(e){this.wrapped.miterLimit=this.scale_.x.dim(e)}get globalAlpha(){return this.wrapped.globalAlpha}set globalAlpha(e){this.wrapped.globalAlpha=e}get globalCompositeOperation(){return this.wrapped.globalCompositeOperation}set globalCompositeOperation(e){this.wrapped.globalCompositeOperation=e}get fillStyle(){return this.wrapped.fillStyle}set fillStyle(e){this.wrapped.fillStyle=e}get strokeStyle(){return this.wrapped.strokeStyle}set strokeStyle(e){this.wrapped.strokeStyle=e}drawImage(e,t,s,n,a,o,c,l,d){this.wrapped.drawImage(e,t,s,n,a,o,c,l,d)}beginPath(){this.wrapped.beginPath()}clip(e,t){this.wrapped.clip(e,t)}fill(e,t){if(e==null)return this.wrapped.fill();this.wrapped.fill(e,t)}isPointInPath(e,t,s,n){return this.wrapped.isPointInPath(e,t,s,n)}isPointInStroke(e,t,s){return this.wrapped.isPointInStroke(e,t,s)}stroke(e){if(e==null)return this.wrapped.stroke();this.wrapped.stroke(e)}createConicGradient(e,t,s){return this.wrapped.createConicGradient(e,t,s)}createLinearGradient(e,t,s,n){return this.wrapped.createLinearGradient(e,t,s,n)}createPattern(e,t){return this.wrapped.createPattern(e,t)}createRadialGradient(e,t,s,n,a,o){return this.wrapped.createRadialGradient(e,t,s,n,a,o)}get filter(){return this.wrapped.filter}set filter(e){this.wrapped.filter=e}createImageData(e,t,s){return this.wrapped.createImageData(e,t,s)}getImageData(e,t,s,n,a){return this.wrapped.getImageData(e,t,s,n,a)}putImageData(e,t,s,n,a,o,c){this.wrapped.putImageData(e,t,s,n,a,o,c)}get imageSmoothingEnabled(){return this.wrapped.imageSmoothingEnabled}set imageSmoothingEnabled(e){this.wrapped.imageSmoothingEnabled=e}get imageSmoothingQuality(){return this.wrapped.imageSmoothingQuality}set imageSmoothingQuality(e){this.wrapped.imageSmoothingQuality=e}arc(e,t,s,n,a,o){this.wrapped.arc(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),n,a,o)}arcTo(e,t,s,n,a){this.wrapped.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(s),this.scale_.y.pos(n),this.scale_.x.dim(a))}bezierCurveTo(e,t,s,n,a,o){this.wrapped.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(s),this.scale_.y.pos(n),this.scale_.x.pos(a),this.scale_.y.pos(o))}closePath(){this.wrapped.closePath()}ellipse(e,t,s,n,a,o,c,l){this.wrapped.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n),a,o,c,l)}lineTo(e,t){this.wrapped.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}moveTo(e,t){this.wrapped.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}quadraticCurveTo(e,t,s,n){this.wrapped.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(s),this.scale_.y.pos(n))}rect(e,t,s,n){this.wrapped.rect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n))}roundRect(e,t,s,n,a){this.wrapped.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n),typeof a=="number"?this.scale_.x.dim(a):a)}get lineCap(){return this.wrapped.lineCap}set lineCap(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.wrapped.lineJoin}set lineJoin(e){this.wrapped.lineJoin=e}get lineWidth(){return this.wrapped.lineWidth}set lineWidth(e){this.wrapped.lineWidth=this.scale_.x.dim(e)}getLineDash(){return this.wrapped.getLineDash()}setLineDash(e){const t=Array.from(e).map(s=>this.scale_.x.dim(s));this.wrapped.setLineDash(t)}clearRect(e,t,s,n){this.wrapped.clearRect(e,t,s,n)}fillRect(e,t,s,n){this.wrapped.fillRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n))}strokeRect(e,t,s,n){this.wrapped.strokeRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n))}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.wrapped.restore()}save(){this.wrapped.save()}fillText(e,t,s,n){this.wrapped.fillText(e,this.scale_.x.pos(t),this.scale_.y.pos(s),n!=null?this.scale_.x.dim(n):void 0)}measureText(e){this.wrapped.font=hn(this.wrapped.font,this.scale_.x.reverse());const t=this.wrapped.measureText(e);return this.wrapped.font=hn(this.wrapped.font,this.scale_.x),t}strokeText(e,t,s,n){this.wrapped.strokeText(e,this.scale_.x.pos(t),this.scale_.y.pos(s),n!=null?this.scale_.x.dim(n):void 0)}get direction(){return this.wrapped.direction}set direction(e){this.wrapped.direction=e}get font(){return this.wrapped.font}set font(e){this.wrapped.font=hn(e,this.scale_.x)}get fontKerning(){return this.wrapped.fontKerning}set fontKerning(e){this.wrapped.fontKerning=e}get textAlign(){return this.wrapped.textAlign}set textAlign(e){this.wrapped.textAlign=e}get textBaseline(){return this.wrapped.textBaseline}set textBaseline(e){this.wrapped.textBaseline=e}getTransform(){return this.wrapped.getTransform()}resetTransform(){this.wrapped.resetTransform()}rotate(e){this.wrapped.rotate(e)}scale(e,t){this.wrapped.scale(e,t)}scissor(e,t=p.G.ZERO){const s=new Fv(this.scale_);return e=rs(e,t),s.rect(...p.G.couple(p.Eo.topLeft(e)),...p._.couple(p.Eo.dims(e))),this.save(),this.clip(s.getPath()),()=>this.restore()}setTransform(e,t,s,n,a,o){this.wrapped.setTransform(e,t,s,n,a,o)}transform(e,t,s,n,a,o){this.wrapped.transform(e,t,s,n,a,o)}translate(e,t){this.wrapped.translate(e,t)}}const Ba=/(\d+(\.\d+)?)px/,hn=(r,e)=>{var n;const t=Number((n=r.match(Ba))==null?void 0:n[1]);if(t==null)return r;const s=e.dim(t);return r.replace(Ba,`${s}px`)};class Fv{constructor(e=p.b.XY.IDENTITY,t){T(this,"scale_");T(this,"path");this.scale_=e,t instanceof Path2D||typeof t=="string"?this.path=new Path2D(t):this.path=new Path2D}addPath(e,t){this.path.addPath(e,t)}arc(e,t,s,n,a,o){this.path.arc(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),n,a,o)}arcTo(e,t,s,n,a){this.path.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(s),this.scale_.y.pos(n),this.scale_.x.dim(a))}bezierCurveTo(e,t,s,n,a,o){this.path.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(s),this.scale_.y.pos(n),this.scale_.x.pos(a),this.scale_.y.pos(o))}closePath(){this.path.closePath()}ellipse(e,t,s,n,a,o,c,l){this.path.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n),a,o,c,l)}lineTo(e,t){this.path.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}moveTo(e,t){this.path.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}quadraticCurveTo(e,t,s,n){this.path.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(s),this.scale_.y.pos(n))}rect(e,t,s,n){this.path.rect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n))}roundRect(e,t,s,n,a){const o=this.scaleRadii(a);this.path.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(s),this.scale_.y.dim(n),o)}scaleRadii(e){return e==null?e:typeof e=="number"?this.scale_.x.dim(e):Array.isArray(e)?e.map(t=>this.scaleRadius(t)):this.scaleRadius(e)}scaleRadius(e){return typeof e=="number"?this.scale_.x.dim(e):{x:this.scale_.x.dim(e.x??0),y:this.scale_.y.dim(e.y??0)}}getPath(){return this.path}}const qv=`precision mediump float;
68
-
69
- void main(void) {
70
- gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
71
- }
72
- `,Gv=`attribute vec4 a_position;
73
-
74
- void main(void) {
75
- gl_Position = a_position;
76
- }
77
- `,ja=r=>new Error(`failed to compile webgl program: ${r}`),Vv=new Error("null shader encountered");class vc{constructor(e,t,s){T(this,"ctx");T(this,"prog");T(this,"vertShader");T(this,"fragShader");T(this,"uniformLocCache",new Map);this.ctx=e;const n=e.gl.createProgram();if(n==null)throw ja("failed to create program");this.prog=n,this.vertShader=t,this.fragShader=s,this.compile()}setAsActive(){return this.ctx.gl.useProgram(this.prog),()=>this.ctx.gl.useProgram(null)}uniformXY(e,t){this.ctx.gl.uniform2fv(this.getUniformLoc(e),p.G.couple(p.G.construct(t)))}uniformColor(e,t){this.ctx.gl.uniform4fv(this.getUniformLoc(e),t.rgba1)}getUniformLoc(e){const t=this.uniformLocCache.get(e);if(t!=null)return t;const s=this.ctx.gl.getUniformLocation(this.prog,e);if(s==null)throw new Error(`unexpected missing uniform ${e}`);return this.uniformLocCache.set(e,s),s}compile(){const e=this.ctx.gl;this.compileShader(this.vertShader,e.VERTEX_SHADER),this.compileShader(this.fragShader,e.FRAGMENT_SHADER),e.linkProgram(this.prog)}compileShader(e,t){const s=this.ctx.gl,n=s.createShader(t);if(n==null)throw Vv;if(s.shaderSource(n,e),s.compileShader(n),!s.getShaderParameter(n,s.COMPILE_STATUS)){const o=s.getShaderInfoLog(n);throw s.deleteShader(n),ja(o??"unknown")}s.attachShader(this.prog,n)}}const Wv=new Float32Array([0,0,0,0,0,0]);class Zv extends vc{constructor(t){super(t,Gv,qv);T(this,"positionBuffer");const s=t.gl.createBuffer();if(s==null)throw new we("webgl: failed to create buffer");this.positionBuffer=s,t.gl.bindBuffer(t.gl.ARRAY_BUFFER,this.positionBuffer),t.gl.bufferData(t.gl.ARRAY_BUFFER,Wv,t.gl.STATIC_DRAW)}exec(){const{gl:t}=this.ctx,s=t.getAttribLocation(this.prog,"a_position");t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer);const n=t.createVertexArray();t.bindVertexArray(n),t.enableVertexAttribArray(s),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0),this.setAsActive(),t.drawArrays(t.TRIANGLES,0,3)}}const Pa={high:1,low:0},Ua=ss.hz(45);class Oc{constructor(e){T(this,"mutex",new bi);T(this,"requests",new Map);T(this,"cleanup",new Map);T(this,"afterRender");this.start(),this.afterRender=e}async set(e){let t;e.priority==="high"&&(t=await this.mutex.acquire());const s=this.requests.get(e.key);if(s==null)this.requests.set(e.key,e);else{const n=Pa[e.priority]>=Pa[s.priority],a=e.canvases.length>=s.canvases.length;n&&a&&this.requests.set(e.key,e)}t==null||t()}async render(){await this.mutex.runExclusive(async()=>{var a;const e=performance.now(),{requests:t}=this;if(t.size===0)return;await this.runCleanupsSync(),await this.renderSync();const s=performance.now(),n=Z.milliseconds(s-e);n.greaterThan(Ua.period)&&console.warn(`Render loop for ${this.requests.size} took longer than ${Ua.period.toString()} to execute: ${n.milliseconds}`),this.requests.clear(),(a=this.afterRender)==null||a.call(this)})}async runCleanupsSync(){const{cleanup:e,requests:t}=this;for(const[s,n]of e.entries()){const a=t.get(s);a!=null&&(await n(a),e.delete(s))}}async renderSync(){const{requests:e}=this;for(const t of e.values())try{const s=await t.render();s!=null&&this.cleanup.set(t.key,s)}catch(s){console.error(s)}}async start(){do{try{await this.render()}catch(e){console.error(e)}await this.sleep()}while(!0)}async sleep(){return await new Promise(requestAnimationFrame)}}const La=r=>(r.textRendering="optimizeSpeed",r.imageSmoothingEnabled=!1,r);var Oe;let Tc=(Oe=class{constructor(e,t,s,n){T(this,"glCanvas");T(this,"upper2dCanvas");T(this,"lower2dCanvas");T(this,"gl");T(this,"lower2d");T(this,"upper2d");T(this,"region");T(this,"dpr");T(this,"loop");T(this,"clearProgram");T(this,"os");this.upper2dCanvas=s,this.lower2dCanvas=t,this.glCanvas=e,this.os=n;const a=this.lower2dCanvas.getContext("2d");if(a==null)throw new Error("Could not get 2D context");this.lower2d=La(new ds(a));const o=this.upper2dCanvas.getContext("2d");if(o==null)throw new Error("Could not get 2D context");this.upper2d=La(new ds(o));const c={preserveDrawingBuffer:!0,powerPreference:"high-performance",stencil:!1,depth:!1},l=this.glCanvas.getContext("webgl2",c);if(l==null)throw new Error("Could not get WebGL context");l.disable(l.DEPTH_TEST),l.disable(l.STENCIL_TEST),l.disable(l.CULL_FACE),l.disable(l.DITHER),this.gl=l,this.glCanvas.oncontextlost=console.log;const d=()=>{this.gl.flush(),this.gl.finish()};this.loop=new Oc(d),this.region=p.Eo.ZERO,this.dpr=1,this.os==="Windows"&&(this.clearProgram=new Zv(this))}static create(e,t,s,n,a){const o=new Oe(t,s,n,a);return e.set(Oe.CONTEXT_KEY,o),o}static useOptional(e){return e.getOptional(Oe.CONTEXT_KEY)}static use(e){return e.get(Oe.CONTEXT_KEY)}update(e){e.set(Oe.CONTEXT_KEY,this)}resize(e,t){p.Eo.equals(this.region,e)&&this.dpr===t||(this.region=e,this.dpr=t,this.resizeCanvas(this.glCanvas),this.resizeCanvas(this.upper2dCanvas),this.resizeCanvas(this.lower2dCanvas),this.lower2d.scale(this.dpr,this.dpr),this.upper2d.scale(this.dpr,this.dpr),this.gl.viewport(0,0,p.Eo.width(e)*t,p.Eo.height(e)*t))}resizeCanvas(e){e.width=p.Eo.width(this.region)*this.dpr,e.height=p.Eo.height(this.region)*this.dpr}get aspect(){return p.Eo.aspect(this.region)}scaleRegion(e){return new p.b.XY(p.b.Scale.scale(0,1).scale(p.Eo.width(e)).translate(p.Eo.left(e)).reBound(p.Eo.width(this.region)).scale(-1,1),p.b.Scale.scale(0,1).scale(p.Eo.height(e)).invert().translate(p.Eo.top(e)).reBound(p.Eo.height(this.region)).scale(-1,1).invert())}scissor(e,t=p.G.ZERO,s){const n=[];return s.includes("upper2d")&&n.push(this.upper2d.scissor(e,t)),s.includes("lower2d")&&n.push(this.lower2d.scissor(e,t)),s.includes("gl")&&n.push(this.scissorGL(e,t)),()=>n.forEach(a=>a())}scissorGL(e,t=p.G.ZERO){return this.gl.enable(this.gl.SCISSOR_TEST),e=rs(e,t),this.gl.scissor(p.Eo.left(e)*this.dpr,(p.Eo.height(this.region)-p.Eo.bottom(e))*this.dpr,p.Eo.width(e)*this.dpr,p.Eo.height(e)*this.dpr),()=>this.gl.disable(this.gl.SCISSOR_TEST)}erase(e,t=p.G.ZERO,...s){t=p.G.construct(t),s.length===0&&(s=["upper2d","lower2d","gl"]),s.includes("upper2d")&&this.eraseCanvas(this.upper2d,e,t),s.includes("lower2d")&&this.eraseCanvas(this.lower2d,e,t),s.includes("gl")&&this.eraseGL(e,t)}eraseGL(e,t=p.G.ZERO){var a;const{gl:s}=this,n=this.scissorGL(rs(e,t));s.clearColor(...p.ZERO.rgba1),s.clear(s.COLOR_BUFFER_BIT),this.os==="Windows"&&((a=this.clearProgram)==null||a.exec()),n()}eraseCanvas(e,t,s=p.G.ZERO){const n=rs(t,s);e.clearRect(...p.G.couple(p.Eo.topLeft(n)),...p._.couple(p.Eo.dims(n)))}},T(Oe,"CONTEXT_KEY",p.CSS.B("render-context")),Oe),Sc=class{constructor(){T(this,"prevErase",p.Eo.ZERO)}erase(e,t,s,n,a){!p.Eo.equals(s,t)&&!p.Eo.equals(this.prevErase,s)?(e.erase(s,n,...a),this.prevErase=s):e.erase(t,n,...a)}};const zc=i.z.object({region:p.Eo.box,enabled:i.z.boolean().optional().default(!1)});class fs extends Rs{constructor(){super(...arguments);T(this,"schema",zc);T(this,"eraser",new Sc)}async afterUpdate(){this.deleted||(this.internal.render=Tc.use(this.ctx),await this.internal.render.loop.set({key:`${this.type}-${this.key}`,render:this.render.bind(this),priority:"high",canvases:["gl","lower2d","upper2d"]}))}async afterDelete(){await this.internal.render.loop.set({key:`${this.type}-${this.key}`,render:this.render.bind(this),priority:"high",canvases:["gl","lower2d","upper2d"]})}async render(){this.deleted||!this.state.enabled||this.internal.render.erase(this.state.region,p.G.construct(0),"gl","lower2d","upper2d")}}T(fs,"TYPE","eraser");const Kv={[fs.TYPE]:fs},Ec="pluto-theming-context",Nc=i.z.object({name:i.z.string(),url:i.z.string()}),Jv=i.z.object({theme:mo,fontURLs:i.z.array(Nc)}),Jt=class Jt extends gr{constructor(){super(...arguments);T(this,"schema",Jt.z)}async afterUpdate(){this.ctx.set(Ec,this.state.theme),await this.loadFonts()}async loadFonts(){await Promise.all(this.state.fontURLs.map(async({name:t,url:s})=>{const n=new FontFace(t,`url(${s})`);await n.load(),self.fonts.add(n)}))}};T(Jt,"TYPE","theming.Provider"),T(Jt,"z",Jv);let nr=Jt;const Hv=r=>r.get(Ec),Xv={[nr.TYPE]:nr},Ic=["success","error","warning","info","loading","disabled","secondary"],xc=i.z.enum(Ic),Ac=i.z.object({key:i.z.string(),variant:xc,message:i.z.string(),description:i.z.string().optional(),time:V.z,data:i.z.record(i.z.unknown()).optional()}),kc=i.z.object({statuses:Ac.array()}),vi="status.aggregator";class ps extends gr{constructor(){super(...arguments);T(this,"schema",kc)}async afterUpdate(){this.ctx.set(vi,this)}add(t){this.setState(s=>({...s,statuses:[...s.statuses,{time:V.now(),...t,key:Ha.id()}]}))}}T(ps,"TYPE","status.Aggregator");const Qv=r=>{const e=r.get(vi);return e.add.bind(e)},eO=r=>{const e=r.getOptional(vi);return e!=null?e.add.bind(e):()=>{}},tO={[ps.TYPE]:ps};exports.A=xu;exports.Aggregator=ps;exports.B=wi;exports.ComponentSizeLevels=yo;exports.Composite=gr;exports.Context=Tc;exports.Dt=pu;exports.E=at;exports.Eraser=Sc;exports.Eraser$1=fs;exports.F=Vc;exports.F$1=ss;exports.GLProgram=vc;exports.K=Gu;exports.LEVELS=go;exports.Leaf=Rs;exports.LevelComponentSizes=lh;exports.Loop=Oc;exports.Lt=au;exports.Mutex=bi;exports.N=eu;exports.Op=Kb;exports.Provider=nr;exports.REGISTRY=Xv;exports.REGISTRY$1=Kv;exports.REGISTRY$2=tO;exports.Re=we;exports.S=io;exports.S$1=x;exports.SYNNAX_DARK=bo;exports.SYNNAX_LIGHT=wo;exports.SYNNAX_THEMES=wh;exports.U=J;exports.U$1=Fu;exports.V=eo;exports.V$1=ne;exports.VARIANTS=Ic;exports.X=Ju;exports.Xg=Ky;exports.Y=Hu;exports.Yg=Kg;exports._=ro;exports.aether=Yv;exports.aggregatorStateZ=kc;exports.b=ce;exports.dg=ic;exports.dimensions=uh;exports.downLevel=sh;exports.dp=xw;exports.ee=Xu;exports.eraserStateZ=zc;exports.executeInitialSetter=ar;exports.executeSetter=Wn;exports.fg=ac;exports.fontSpecZ=Nc;exports.fontString=Th;exports.g=D;exports.g$1=mc;exports.isSetter=Vn;exports.k=R;exports.l=Bu;exports.levelZ=th;exports.m=V;exports.n=dn;exports.ne=Te;exports.o=yu;exports.o$1=Au;exports.prettyParse=jn;exports.r=mu;exports.render=bc;exports.specZ=Fe;exports.specZ$1=Ac;exports.state=eh;exports.themeZ=mo;exports.upLevel=ih;exports.use=Hv;exports.useAggregate=Qv;exports.useOptionalAggregate=eO;exports.usePassthrough=fo;exports.usePurePassthrough=po;exports.variantZ=xc;exports.w=Z;exports.w$1=Uc;exports.weightZ=oh;exports.x=Ht;exports.xt=Ha;