@bitcobblers/wod-wiki-tools 0.48.2172 → 0.48.2174

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 (598) hide show
  1. package/dist/bin/wod.cjs +1 -1
  2. package/dist/bin/wod.cjs.map +1 -1
  3. package/dist/bin/wod.mjs +2 -2
  4. package/dist/{chunk-RSYQELVA.mjs → chunk-G2637PL3.mjs} +3 -3
  5. package/dist/chunk-G2637PL3.mjs.map +1 -0
  6. package/dist/{chunk-FPGYZPHY.mjs → chunk-TGTKA47R.mjs} +4 -4
  7. package/dist/{chunk-FPGYZPHY.mjs.map → chunk-TGTKA47R.mjs.map} +1 -1
  8. package/dist/index.cjs +1 -1
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.mjs +2 -2
  11. package/dist/{scaffoldFeed-ZBTA7E3I.mjs → scaffoldFeed-W43MCGRE.mjs} +3 -3
  12. package/dist/{scaffoldFeed-ZBTA7E3I.mjs.map → scaffoldFeed-W43MCGRE.mjs.map} +1 -1
  13. package/dist/web/playground/assets/{main-CpZctqfe.js → main-0VA1ZMB5.js} +7 -7
  14. package/dist/web/playground/assets/{statementBuilderFlow-D79YIu6s.js → statementBuilderFlow-B_qji59I.js} +2 -2
  15. package/dist/web/playground/index.html +1 -1
  16. package/dist/web/playground/seed/core/chunks/canvas.0fe6bf95.json +1 -0
  17. package/dist/web/playground/seed/core/chunks/{dashboards.939067cd.json → dashboards.a7a2b19d.json} +1 -1
  18. package/dist/web/playground/seed/core/chunks/{efforts.b23c229c.json → efforts.d8922596.json} +1 -1
  19. package/dist/web/playground/seed/core/chunks/{equipment.92b0064f.json → equipment.6c64a0b9.json} +1 -1
  20. package/dist/web/playground/seed/core/indexes/notebooks/canvas.json +181 -181
  21. package/dist/web/playground/seed/core/indexes/notebooks/dashboards.json +16 -16
  22. package/dist/web/playground/seed/core/indexes/notebooks/efforts.json +326 -326
  23. package/dist/web/playground/seed/core/indexes/notebooks/equipment.json +50 -50
  24. package/dist/web/playground/seed/core/manifest.json +29 -29
  25. package/dist/web/playground/seed/core/markdown/canvas/ai-first/README.json +1 -1
  26. package/dist/web/playground/seed/core/markdown/canvas/guide/README.json +4 -4
  27. package/dist/web/playground/seed/core/markdown/canvas/guide/clock.json +1 -1
  28. package/dist/web/playground/seed/core/markdown/canvas/guide/dashboards.json +2 -2
  29. package/dist/web/playground/seed/core/markdown/canvas/guide/metrics-summaries.json +7 -7
  30. package/dist/web/playground/seed/core/markdown/canvas/guide/metrics.json +12 -12
  31. package/dist/web/playground/seed/core/markdown/canvas/guide/protocols.json +20 -20
  32. package/dist/web/playground/seed/core/markdown/canvas/guide/sessions.json +30 -30
  33. package/dist/web/playground/seed/core/markdown/canvas/guide/start.json +10 -10
  34. package/dist/web/playground/seed/core/markdown/canvas/guide/structure.json +24 -24
  35. package/dist/web/playground/seed/core/markdown/canvas/guide/wql.json +5 -5
  36. package/dist/web/playground/seed/core/markdown/canvas/home/sample-script.json +4 -4
  37. package/dist/web/playground/seed/core/markdown/canvas/home/welcome-1.json +2 -2
  38. package/dist/web/playground/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
  39. package/dist/web/playground/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
  40. package/dist/web/playground/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
  41. package/dist/web/playground/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
  42. package/dist/web/playground/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
  43. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
  44. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-full-session.json +9 -9
  45. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
  46. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
  47. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-swimming.json +3 -3
  48. package/dist/web/playground/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
  49. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +4 -4
  50. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
  51. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
  52. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
  53. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-3.json +2 -2
  54. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
  55. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
  56. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
  57. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
  58. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
  59. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
  60. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
  61. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
  62. package/dist/web/playground/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
  63. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-1.json +4 -4
  64. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-2.json +5 -5
  65. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-3.json +10 -10
  66. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-4.json +4 -4
  67. package/dist/web/playground/seed/core/markdown/canvas/syntax/effort-notes.json +4 -4
  68. package/dist/web/playground/seed/core/markdown/canvas/syntax/frontmatter-summaries.json +4 -4
  69. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
  70. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
  71. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
  72. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
  73. package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
  74. package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
  75. package/dist/web/playground/seed/core/markdown/canvas/syntax/measurements.json +4 -4
  76. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
  77. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
  78. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
  79. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-4.json +5 -5
  80. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
  81. package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-sections.json +8 -8
  82. package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
  83. package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
  84. package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
  85. package/dist/web/playground/seed/core/markdown/canvas/syntax/named-groups.json +5 -5
  86. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
  87. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
  88. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
  89. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
  90. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
  91. package/dist/web/playground/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
  92. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
  93. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
  94. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
  95. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
  96. package/dist/web/playground/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
  97. package/dist/web/playground/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
  98. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
  99. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
  100. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-3.json +3 -3
  101. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
  102. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
  103. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
  104. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
  105. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
  106. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
  107. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
  108. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
  109. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
  110. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
  111. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
  112. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
  113. package/dist/web/playground/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
  114. package/dist/web/playground/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
  115. package/dist/web/playground/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
  116. package/dist/web/playground/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
  117. package/dist/web/playground/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
  118. package/dist/web/playground/seed/core/markdown/dashboards/training-block-review.json +11 -11
  119. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/air-squat.json +1 -1
  120. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/box-jump.json +1 -1
  121. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/broad-jump.json +1 -1
  122. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +1 -1
  123. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +1 -1
  124. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee.json +1 -1
  125. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +1 -1
  126. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +1 -1
  127. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ground-kong.json +1 -1
  128. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/jumping-jack.json +1 -1
  129. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/kong-walk.json +1 -1
  130. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/lunge.json +1 -1
  131. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/overhead-squat.json +1 -1
  132. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-roll.json +1 -1
  133. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-squat.json +1 -1
  134. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/pistol-squat.json +1 -1
  135. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/plank.json +1 -1
  136. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-burpee.json +1 -1
  137. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-jump.json +1 -1
  138. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +1 -1
  139. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/russian-twist.json +1 -1
  140. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/sit-up.json +1 -1
  141. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-clean.json +1 -1
  142. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-hold.json +1 -1
  143. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-snatch.json +1 -1
  144. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/tuck-jump.json +1 -1
  145. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-ball.json +1 -1
  146. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-burpee.json +1 -1
  147. package/dist/web/playground/seed/core/markdown/efforts/cycling/assault-bike.json +1 -1
  148. package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-moderate.json +1 -1
  149. package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-vigorous.json +1 -1
  150. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +1 -1
  151. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +1 -1
  152. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +1 -1
  153. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/dip.json +1 -1
  154. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/double-under.json +1 -1
  155. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-hold.json +1 -1
  156. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +1 -1
  157. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-walk.json +1 -1
  158. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jump-rope.json +1 -1
  159. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +1 -1
  160. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +1 -1
  161. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +1 -1
  162. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/muscle-up.json +1 -1
  163. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/pull-up.json +1 -1
  164. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/push-up.json +1 -1
  165. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +1 -1
  166. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/rope-climb.json +1 -1
  167. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +1 -1
  168. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +1 -1
  169. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +1 -1
  170. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +1 -1
  171. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +1 -1
  172. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +1 -1
  173. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +1 -1
  174. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +1 -1
  175. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +1 -1
  176. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +1 -1
  177. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +1 -1
  178. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +1 -1
  179. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +1 -1
  180. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +1 -1
  181. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +1 -1
  182. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +1 -1
  183. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +1 -1
  184. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +1 -1
  185. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +1 -1
  186. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +1 -1
  187. package/dist/web/playground/seed/core/markdown/efforts/recovery/rest.json +1 -1
  188. package/dist/web/playground/seed/core/markdown/efforts/recovery/stretching.json +1 -1
  189. package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing-sprint.json +1 -1
  190. package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing.json +1 -1
  191. package/dist/web/playground/seed/core/markdown/efforts/rowing/ski-erg.json +1 -1
  192. package/dist/web/playground/seed/core/markdown/efforts/running/backward-running.json +1 -1
  193. package/dist/web/playground/seed/core/markdown/efforts/running/running-6-mph.json +1 -1
  194. package/dist/web/playground/seed/core/markdown/efforts/running/running-8-mph.json +1 -1
  195. package/dist/web/playground/seed/core/markdown/efforts/running/running-sprint.json +1 -1
  196. package/dist/web/playground/seed/core/markdown/efforts/snatch.json +2 -2
  197. package/dist/web/playground/seed/core/markdown/efforts/strength/back-squat.json +1 -1
  198. package/dist/web/playground/seed/core/markdown/efforts/strength/bench-press.json +1 -1
  199. package/dist/web/playground/seed/core/markdown/efforts/strength/box-step-up.json +1 -1
  200. package/dist/web/playground/seed/core/markdown/efforts/strength/carioca.json +1 -1
  201. package/dist/web/playground/seed/core/markdown/efforts/strength/clean-and-jerk.json +1 -1
  202. package/dist/web/playground/seed/core/markdown/efforts/strength/cluster.json +1 -1
  203. package/dist/web/playground/seed/core/markdown/efforts/strength/dead-hang.json +1 -1
  204. package/dist/web/playground/seed/core/markdown/efforts/strength/deadlift.json +1 -1
  205. package/dist/web/playground/seed/core/markdown/efforts/strength/devils-press.json +1 -1
  206. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +1 -1
  207. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-clean.json +1 -1
  208. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-fly.json +1 -1
  209. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-row.json +1 -1
  210. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-snatch.json +1 -1
  211. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-thruster.json +1 -1
  212. package/dist/web/playground/seed/core/markdown/efforts/strength/elbows-to-knees.json +1 -1
  213. package/dist/web/playground/seed/core/markdown/efforts/strength/farmer-carry.json +1 -1
  214. package/dist/web/playground/seed/core/markdown/efforts/strength/frog-stand.json +1 -1
  215. package/dist/web/playground/seed/core/markdown/efforts/strength/front-squat.json +1 -1
  216. package/dist/web/playground/seed/core/markdown/efforts/strength/good-morning.json +1 -1
  217. package/dist/web/playground/seed/core/markdown/efforts/strength/hanging-leg-raise.json +1 -1
  218. package/dist/web/playground/seed/core/markdown/efforts/strength/hollow-rock.json +1 -1
  219. package/dist/web/playground/seed/core/markdown/efforts/strength/knees-to-elbows.json +1 -1
  220. package/dist/web/playground/seed/core/markdown/efforts/strength/l-sit.json +1 -1
  221. package/dist/web/playground/seed/core/markdown/efforts/strength/man-maker.json +1 -1
  222. package/dist/web/playground/seed/core/markdown/efforts/strength/medicine-ball-clean.json +1 -1
  223. package/dist/web/playground/seed/core/markdown/efforts/strength/overhead-press.json +1 -1
  224. package/dist/web/playground/seed/core/markdown/efforts/strength/parkour-vault.json +1 -1
  225. package/dist/web/playground/seed/core/markdown/efforts/strength/pig-flip.json +1 -1
  226. package/dist/web/playground/seed/core/markdown/efforts/strength/power-clean.json +1 -1
  227. package/dist/web/playground/seed/core/markdown/efforts/strength/power-snatch.json +1 -1
  228. package/dist/web/playground/seed/core/markdown/efforts/strength/push-jerk.json +1 -1
  229. package/dist/web/playground/seed/core/markdown/efforts/strength/push-press.json +1 -1
  230. package/dist/web/playground/seed/core/markdown/efforts/strength/romanian-deadlift.json +1 -1
  231. package/dist/web/playground/seed/core/markdown/efforts/strength/single-leg-deadlift.json +1 -1
  232. package/dist/web/playground/seed/core/markdown/efforts/strength/skull-crusher.json +1 -1
  233. package/dist/web/playground/seed/core/markdown/efforts/strength/slam-ball.json +1 -1
  234. package/dist/web/playground/seed/core/markdown/efforts/strength/sled-pull.json +1 -1
  235. package/dist/web/playground/seed/core/markdown/efforts/strength/sled-push.json +1 -1
  236. package/dist/web/playground/seed/core/markdown/efforts/strength/sumo-deadlift.json +1 -1
  237. package/dist/web/playground/seed/core/markdown/efforts/strength/thruster.json +1 -1
  238. package/dist/web/playground/seed/core/markdown/efforts/strength/triceps-extension.json +1 -1
  239. package/dist/web/playground/seed/core/markdown/efforts/strength/v-sit-hold.json +1 -1
  240. package/dist/web/playground/seed/core/markdown/efforts/strength/wall-walk.json +1 -1
  241. package/dist/web/playground/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +1 -1
  242. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +1 -1
  243. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-backstroke.json +1 -1
  244. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +1 -1
  245. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +1 -1
  246. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-butterfly.json +1 -1
  247. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +1 -1
  248. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +1 -1
  249. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dive-start.json +1 -1
  250. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +1 -1
  251. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-drafting.json +1 -1
  252. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +1 -1
  253. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-freestyle.json +1 -1
  254. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +1 -1
  255. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-kick.json +1 -1
  256. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-pull.json +1 -1
  257. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +1 -1
  258. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +1 -1
  259. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-sighting.json +1 -1
  260. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +1 -1
  261. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +1 -1
  262. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +1 -1
  263. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-vigorous.json +1 -1
  264. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming.json +1 -1
  265. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +1 -1
  266. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-circles.json +1 -1
  267. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-mill.json +1 -1
  268. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +1 -1
  269. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +1 -1
  270. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +1 -1
  271. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +1 -1
  272. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +1 -1
  273. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-flow.json +1 -1
  274. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +1 -1
  275. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +1 -1
  276. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +1 -1
  277. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +1 -1
  278. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +1 -1
  279. package/dist/web/playground/seed/core/markdown/efforts/walking/walking-3-mph.json +1 -1
  280. package/dist/web/playground/seed/core/markdown/equipment/air-bike.json +1 -1
  281. package/dist/web/playground/seed/core/markdown/equipment/barbell.json +1 -1
  282. package/dist/web/playground/seed/core/markdown/equipment/bench.json +1 -1
  283. package/dist/web/playground/seed/core/markdown/equipment/bike-erg.json +1 -1
  284. package/dist/web/playground/seed/core/markdown/equipment/climbing-rope.json +1 -1
  285. package/dist/web/playground/seed/core/markdown/equipment/clubs.json +1 -1
  286. package/dist/web/playground/seed/core/markdown/equipment/dumbbell.json +1 -1
  287. package/dist/web/playground/seed/core/markdown/equipment/ghd.json +1 -1
  288. package/dist/web/playground/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
  289. package/dist/web/playground/seed/core/markdown/equipment/jump-rope.json +1 -1
  290. package/dist/web/playground/seed/core/markdown/equipment/kettlebell.json +1 -1
  291. package/dist/web/playground/seed/core/markdown/equipment/macebell.json +1 -1
  292. package/dist/web/playground/seed/core/markdown/equipment/medicine-ball.json +1 -1
  293. package/dist/web/playground/seed/core/markdown/equipment/parallettes.json +1 -1
  294. package/dist/web/playground/seed/core/markdown/equipment/plyo-box.json +1 -1
  295. package/dist/web/playground/seed/core/markdown/equipment/pull-up-bar.json +1 -1
  296. package/dist/web/playground/seed/core/markdown/equipment/rower.json +1 -1
  297. package/dist/web/playground/seed/core/markdown/equipment/sandbag.json +1 -1
  298. package/dist/web/playground/seed/core/markdown/equipment/ski-erg.json +1 -1
  299. package/dist/web/playground/seed/core/markdown/equipment/slam-ball.json +1 -1
  300. package/dist/web/playground/seed/core/markdown/equipment/sled.json +1 -1
  301. package/dist/web/playground/seed/core/markdown/equipment/sledgehammer.json +1 -1
  302. package/dist/web/playground/seed/core/markdown/equipment/weight-vest.json +1 -1
  303. package/dist/web/playground/seed/core/report.html +13 -13
  304. package/dist/web/server/assets/{main-B0Fmx4cr.js → main-DoETdi1H.js} +7 -7
  305. package/dist/web/server/assets/{statementBuilderFlow-FcTG4fyZ.js → statementBuilderFlow-B039O6g3.js} +2 -2
  306. package/dist/web/server/index.html +1 -1
  307. package/dist/web/server/seed/core/chunks/canvas.0fe6bf95.json +1 -0
  308. package/dist/web/server/seed/core/chunks/{dashboards.939067cd.json → dashboards.a7a2b19d.json} +1 -1
  309. package/dist/web/server/seed/core/chunks/{efforts.b23c229c.json → efforts.d8922596.json} +1 -1
  310. package/dist/web/server/seed/core/chunks/{equipment.92b0064f.json → equipment.6c64a0b9.json} +1 -1
  311. package/dist/web/server/seed/core/indexes/notebooks/canvas.json +181 -181
  312. package/dist/web/server/seed/core/indexes/notebooks/dashboards.json +16 -16
  313. package/dist/web/server/seed/core/indexes/notebooks/efforts.json +326 -326
  314. package/dist/web/server/seed/core/indexes/notebooks/equipment.json +50 -50
  315. package/dist/web/server/seed/core/manifest.json +29 -29
  316. package/dist/web/server/seed/core/markdown/canvas/ai-first/README.json +1 -1
  317. package/dist/web/server/seed/core/markdown/canvas/guide/README.json +4 -4
  318. package/dist/web/server/seed/core/markdown/canvas/guide/clock.json +1 -1
  319. package/dist/web/server/seed/core/markdown/canvas/guide/dashboards.json +2 -2
  320. package/dist/web/server/seed/core/markdown/canvas/guide/metrics-summaries.json +7 -7
  321. package/dist/web/server/seed/core/markdown/canvas/guide/metrics.json +12 -12
  322. package/dist/web/server/seed/core/markdown/canvas/guide/protocols.json +20 -20
  323. package/dist/web/server/seed/core/markdown/canvas/guide/sessions.json +30 -30
  324. package/dist/web/server/seed/core/markdown/canvas/guide/start.json +10 -10
  325. package/dist/web/server/seed/core/markdown/canvas/guide/structure.json +24 -24
  326. package/dist/web/server/seed/core/markdown/canvas/guide/wql.json +5 -5
  327. package/dist/web/server/seed/core/markdown/canvas/home/sample-script.json +4 -4
  328. package/dist/web/server/seed/core/markdown/canvas/home/welcome-1.json +2 -2
  329. package/dist/web/server/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
  330. package/dist/web/server/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
  331. package/dist/web/server/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
  332. package/dist/web/server/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
  333. package/dist/web/server/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
  334. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
  335. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-full-session.json +9 -9
  336. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
  337. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
  338. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-swimming.json +3 -3
  339. package/dist/web/server/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
  340. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +4 -4
  341. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
  342. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
  343. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
  344. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-3.json +2 -2
  345. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
  346. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
  347. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
  348. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
  349. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
  350. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
  351. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
  352. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
  353. package/dist/web/server/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
  354. package/dist/web/server/seed/core/markdown/canvas/syntax/document-1.json +4 -4
  355. package/dist/web/server/seed/core/markdown/canvas/syntax/document-2.json +5 -5
  356. package/dist/web/server/seed/core/markdown/canvas/syntax/document-3.json +10 -10
  357. package/dist/web/server/seed/core/markdown/canvas/syntax/document-4.json +4 -4
  358. package/dist/web/server/seed/core/markdown/canvas/syntax/effort-notes.json +4 -4
  359. package/dist/web/server/seed/core/markdown/canvas/syntax/frontmatter-summaries.json +4 -4
  360. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
  361. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
  362. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
  363. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
  364. package/dist/web/server/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
  365. package/dist/web/server/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
  366. package/dist/web/server/seed/core/markdown/canvas/syntax/measurements.json +4 -4
  367. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
  368. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
  369. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
  370. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-4.json +5 -5
  371. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
  372. package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-sections.json +8 -8
  373. package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
  374. package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
  375. package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
  376. package/dist/web/server/seed/core/markdown/canvas/syntax/named-groups.json +5 -5
  377. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
  378. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
  379. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
  380. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
  381. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
  382. package/dist/web/server/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
  383. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
  384. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
  385. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
  386. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
  387. package/dist/web/server/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
  388. package/dist/web/server/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
  389. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
  390. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
  391. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-3.json +3 -3
  392. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
  393. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
  394. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
  395. package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
  396. package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
  397. package/dist/web/server/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
  398. package/dist/web/server/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
  399. package/dist/web/server/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
  400. package/dist/web/server/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
  401. package/dist/web/server/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
  402. package/dist/web/server/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
  403. package/dist/web/server/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
  404. package/dist/web/server/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
  405. package/dist/web/server/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
  406. package/dist/web/server/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
  407. package/dist/web/server/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
  408. package/dist/web/server/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
  409. package/dist/web/server/seed/core/markdown/dashboards/training-block-review.json +11 -11
  410. package/dist/web/server/seed/core/markdown/efforts/bodyweight/air-squat.json +1 -1
  411. package/dist/web/server/seed/core/markdown/efforts/bodyweight/box-jump.json +1 -1
  412. package/dist/web/server/seed/core/markdown/efforts/bodyweight/broad-jump.json +1 -1
  413. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +1 -1
  414. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +1 -1
  415. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee.json +1 -1
  416. package/dist/web/server/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +1 -1
  417. package/dist/web/server/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +1 -1
  418. package/dist/web/server/seed/core/markdown/efforts/bodyweight/ground-kong.json +1 -1
  419. package/dist/web/server/seed/core/markdown/efforts/bodyweight/jumping-jack.json +1 -1
  420. package/dist/web/server/seed/core/markdown/efforts/bodyweight/kong-walk.json +1 -1
  421. package/dist/web/server/seed/core/markdown/efforts/bodyweight/lunge.json +1 -1
  422. package/dist/web/server/seed/core/markdown/efforts/bodyweight/overhead-squat.json +1 -1
  423. package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-roll.json +1 -1
  424. package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-squat.json +1 -1
  425. package/dist/web/server/seed/core/markdown/efforts/bodyweight/pistol-squat.json +1 -1
  426. package/dist/web/server/seed/core/markdown/efforts/bodyweight/plank.json +1 -1
  427. package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-burpee.json +1 -1
  428. package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-jump.json +1 -1
  429. package/dist/web/server/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +1 -1
  430. package/dist/web/server/seed/core/markdown/efforts/bodyweight/russian-twist.json +1 -1
  431. package/dist/web/server/seed/core/markdown/efforts/bodyweight/sit-up.json +1 -1
  432. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-clean.json +1 -1
  433. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-hold.json +1 -1
  434. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-snatch.json +1 -1
  435. package/dist/web/server/seed/core/markdown/efforts/bodyweight/tuck-jump.json +1 -1
  436. package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-ball.json +1 -1
  437. package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-burpee.json +1 -1
  438. package/dist/web/server/seed/core/markdown/efforts/cycling/assault-bike.json +1 -1
  439. package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-moderate.json +1 -1
  440. package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-vigorous.json +1 -1
  441. package/dist/web/server/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +1 -1
  442. package/dist/web/server/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +1 -1
  443. package/dist/web/server/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +1 -1
  444. package/dist/web/server/seed/core/markdown/efforts/gymnastics/dip.json +1 -1
  445. package/dist/web/server/seed/core/markdown/efforts/gymnastics/double-under.json +1 -1
  446. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-hold.json +1 -1
  447. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +1 -1
  448. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-walk.json +1 -1
  449. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jump-rope.json +1 -1
  450. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +1 -1
  451. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +1 -1
  452. package/dist/web/server/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +1 -1
  453. package/dist/web/server/seed/core/markdown/efforts/gymnastics/muscle-up.json +1 -1
  454. package/dist/web/server/seed/core/markdown/efforts/gymnastics/pull-up.json +1 -1
  455. package/dist/web/server/seed/core/markdown/efforts/gymnastics/push-up.json +1 -1
  456. package/dist/web/server/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +1 -1
  457. package/dist/web/server/seed/core/markdown/efforts/gymnastics/rope-climb.json +1 -1
  458. package/dist/web/server/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +1 -1
  459. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +1 -1
  460. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +1 -1
  461. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +1 -1
  462. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +1 -1
  463. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +1 -1
  464. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +1 -1
  465. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +1 -1
  466. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +1 -1
  467. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +1 -1
  468. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +1 -1
  469. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +1 -1
  470. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +1 -1
  471. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +1 -1
  472. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +1 -1
  473. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +1 -1
  474. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +1 -1
  475. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +1 -1
  476. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +1 -1
  477. package/dist/web/server/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +1 -1
  478. package/dist/web/server/seed/core/markdown/efforts/recovery/rest.json +1 -1
  479. package/dist/web/server/seed/core/markdown/efforts/recovery/stretching.json +1 -1
  480. package/dist/web/server/seed/core/markdown/efforts/rowing/rowing-sprint.json +1 -1
  481. package/dist/web/server/seed/core/markdown/efforts/rowing/rowing.json +1 -1
  482. package/dist/web/server/seed/core/markdown/efforts/rowing/ski-erg.json +1 -1
  483. package/dist/web/server/seed/core/markdown/efforts/running/backward-running.json +1 -1
  484. package/dist/web/server/seed/core/markdown/efforts/running/running-6-mph.json +1 -1
  485. package/dist/web/server/seed/core/markdown/efforts/running/running-8-mph.json +1 -1
  486. package/dist/web/server/seed/core/markdown/efforts/running/running-sprint.json +1 -1
  487. package/dist/web/server/seed/core/markdown/efforts/snatch.json +2 -2
  488. package/dist/web/server/seed/core/markdown/efforts/strength/back-squat.json +1 -1
  489. package/dist/web/server/seed/core/markdown/efforts/strength/bench-press.json +1 -1
  490. package/dist/web/server/seed/core/markdown/efforts/strength/box-step-up.json +1 -1
  491. package/dist/web/server/seed/core/markdown/efforts/strength/carioca.json +1 -1
  492. package/dist/web/server/seed/core/markdown/efforts/strength/clean-and-jerk.json +1 -1
  493. package/dist/web/server/seed/core/markdown/efforts/strength/cluster.json +1 -1
  494. package/dist/web/server/seed/core/markdown/efforts/strength/dead-hang.json +1 -1
  495. package/dist/web/server/seed/core/markdown/efforts/strength/deadlift.json +1 -1
  496. package/dist/web/server/seed/core/markdown/efforts/strength/devils-press.json +1 -1
  497. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +1 -1
  498. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-clean.json +1 -1
  499. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-fly.json +1 -1
  500. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-row.json +1 -1
  501. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-snatch.json +1 -1
  502. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-thruster.json +1 -1
  503. package/dist/web/server/seed/core/markdown/efforts/strength/elbows-to-knees.json +1 -1
  504. package/dist/web/server/seed/core/markdown/efforts/strength/farmer-carry.json +1 -1
  505. package/dist/web/server/seed/core/markdown/efforts/strength/frog-stand.json +1 -1
  506. package/dist/web/server/seed/core/markdown/efforts/strength/front-squat.json +1 -1
  507. package/dist/web/server/seed/core/markdown/efforts/strength/good-morning.json +1 -1
  508. package/dist/web/server/seed/core/markdown/efforts/strength/hanging-leg-raise.json +1 -1
  509. package/dist/web/server/seed/core/markdown/efforts/strength/hollow-rock.json +1 -1
  510. package/dist/web/server/seed/core/markdown/efforts/strength/knees-to-elbows.json +1 -1
  511. package/dist/web/server/seed/core/markdown/efforts/strength/l-sit.json +1 -1
  512. package/dist/web/server/seed/core/markdown/efforts/strength/man-maker.json +1 -1
  513. package/dist/web/server/seed/core/markdown/efforts/strength/medicine-ball-clean.json +1 -1
  514. package/dist/web/server/seed/core/markdown/efforts/strength/overhead-press.json +1 -1
  515. package/dist/web/server/seed/core/markdown/efforts/strength/parkour-vault.json +1 -1
  516. package/dist/web/server/seed/core/markdown/efforts/strength/pig-flip.json +1 -1
  517. package/dist/web/server/seed/core/markdown/efforts/strength/power-clean.json +1 -1
  518. package/dist/web/server/seed/core/markdown/efforts/strength/power-snatch.json +1 -1
  519. package/dist/web/server/seed/core/markdown/efforts/strength/push-jerk.json +1 -1
  520. package/dist/web/server/seed/core/markdown/efforts/strength/push-press.json +1 -1
  521. package/dist/web/server/seed/core/markdown/efforts/strength/romanian-deadlift.json +1 -1
  522. package/dist/web/server/seed/core/markdown/efforts/strength/single-leg-deadlift.json +1 -1
  523. package/dist/web/server/seed/core/markdown/efforts/strength/skull-crusher.json +1 -1
  524. package/dist/web/server/seed/core/markdown/efforts/strength/slam-ball.json +1 -1
  525. package/dist/web/server/seed/core/markdown/efforts/strength/sled-pull.json +1 -1
  526. package/dist/web/server/seed/core/markdown/efforts/strength/sled-push.json +1 -1
  527. package/dist/web/server/seed/core/markdown/efforts/strength/sumo-deadlift.json +1 -1
  528. package/dist/web/server/seed/core/markdown/efforts/strength/thruster.json +1 -1
  529. package/dist/web/server/seed/core/markdown/efforts/strength/triceps-extension.json +1 -1
  530. package/dist/web/server/seed/core/markdown/efforts/strength/v-sit-hold.json +1 -1
  531. package/dist/web/server/seed/core/markdown/efforts/strength/wall-walk.json +1 -1
  532. package/dist/web/server/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +1 -1
  533. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +1 -1
  534. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-backstroke.json +1 -1
  535. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +1 -1
  536. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +1 -1
  537. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-butterfly.json +1 -1
  538. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +1 -1
  539. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +1 -1
  540. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dive-start.json +1 -1
  541. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +1 -1
  542. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-drafting.json +1 -1
  543. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +1 -1
  544. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-freestyle.json +1 -1
  545. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +1 -1
  546. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-kick.json +1 -1
  547. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-pull.json +1 -1
  548. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +1 -1
  549. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +1 -1
  550. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-sighting.json +1 -1
  551. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +1 -1
  552. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +1 -1
  553. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +1 -1
  554. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-vigorous.json +1 -1
  555. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming.json +1 -1
  556. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +1 -1
  557. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-circles.json +1 -1
  558. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-mill.json +1 -1
  559. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +1 -1
  560. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +1 -1
  561. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +1 -1
  562. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +1 -1
  563. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +1 -1
  564. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-flow.json +1 -1
  565. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +1 -1
  566. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +1 -1
  567. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +1 -1
  568. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +1 -1
  569. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +1 -1
  570. package/dist/web/server/seed/core/markdown/efforts/walking/walking-3-mph.json +1 -1
  571. package/dist/web/server/seed/core/markdown/equipment/air-bike.json +1 -1
  572. package/dist/web/server/seed/core/markdown/equipment/barbell.json +1 -1
  573. package/dist/web/server/seed/core/markdown/equipment/bench.json +1 -1
  574. package/dist/web/server/seed/core/markdown/equipment/bike-erg.json +1 -1
  575. package/dist/web/server/seed/core/markdown/equipment/climbing-rope.json +1 -1
  576. package/dist/web/server/seed/core/markdown/equipment/clubs.json +1 -1
  577. package/dist/web/server/seed/core/markdown/equipment/dumbbell.json +1 -1
  578. package/dist/web/server/seed/core/markdown/equipment/ghd.json +1 -1
  579. package/dist/web/server/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
  580. package/dist/web/server/seed/core/markdown/equipment/jump-rope.json +1 -1
  581. package/dist/web/server/seed/core/markdown/equipment/kettlebell.json +1 -1
  582. package/dist/web/server/seed/core/markdown/equipment/macebell.json +1 -1
  583. package/dist/web/server/seed/core/markdown/equipment/medicine-ball.json +1 -1
  584. package/dist/web/server/seed/core/markdown/equipment/parallettes.json +1 -1
  585. package/dist/web/server/seed/core/markdown/equipment/plyo-box.json +1 -1
  586. package/dist/web/server/seed/core/markdown/equipment/pull-up-bar.json +1 -1
  587. package/dist/web/server/seed/core/markdown/equipment/rower.json +1 -1
  588. package/dist/web/server/seed/core/markdown/equipment/sandbag.json +1 -1
  589. package/dist/web/server/seed/core/markdown/equipment/ski-erg.json +1 -1
  590. package/dist/web/server/seed/core/markdown/equipment/slam-ball.json +1 -1
  591. package/dist/web/server/seed/core/markdown/equipment/sled.json +1 -1
  592. package/dist/web/server/seed/core/markdown/equipment/sledgehammer.json +1 -1
  593. package/dist/web/server/seed/core/markdown/equipment/weight-vest.json +1 -1
  594. package/dist/web/server/seed/core/report.html +13 -13
  595. package/package.json +6 -6
  596. package/dist/chunk-RSYQELVA.mjs.map +0 -1
  597. package/dist/web/playground/seed/core/chunks/canvas.0caf5e93.json +0 -1
  598. package/dist/web/server/seed/core/chunks/canvas.0caf5e93.json +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-D0x8W9No.js","assets/rolldown-runtime-C0FnF6B9.js","assets/vendor-CelWxf33.css","assets/statementBuilderFlow-D79YIu6s.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-D0x8W9No.js","assets/rolldown-runtime-C0FnF6B9.js","assets/vendor-CelWxf33.css","assets/statementBuilderFlow-B_qji59I.js"])))=>i.map(i=>d[i]);
2
2
  import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{$ as n,$n as r,$r as i,$t as a,A as o,An as s,Ar as c,B as l,Bn as u,Br as d,Bt as f,C as p,Cn as m,Cr as h,Ct as g,D as _,Dn as v,Dr as y,E as b,En as x,Er as S,Et as C,F as w,Fn as T,Fr as E,Ft as D,G as O,Gn as k,Gr as A,Gt as j,H as M,Hn as N,Hr as P,Ht as F,I,In as L,Ir as R,It as ee,J as z,Jn as te,Jr as ne,Jt as re,K as ie,Kn as ae,Kr as oe,Kt as se,L as ce,Ln as B,Lr as le,Lt as V,M as ue,Mn as de,Mr as fe,N as pe,Nn as me,Nr as he,Nt as ge,O as _e,On as ve,Or as ye,P as be,Pn as xe,Pr as Se,Pt as Ce,Q as we,Qn as Te,Qr as Ee,Qt as De,R as Oe,Rn as ke,Rr as Ae,Rt as je,S as Me,Sn as Ne,Sr as Pe,St as Fe,T as Ie,Tn as Le,Tr as Re,Tt as ze,U as Be,Un as Ve,Ur as He,Ut as Ue,V as We,Vn as Ge,Vr as Ke,Vt as qe,W as Je,Wn as Ye,Wr as Xe,Wt as Ze,X as Qe,Xn as $e,Xr as et,Xt as tt,Y as nt,Yn as rt,Yr as it,Yt as at,Z as ot,Zn as st,Zr as ct,Zt as lt,_ as ut,_n as dt,_r as ft,_t as pt,a as mt,ai as ht,an as gt,ar as _t,at as vt,b as yt,bn as eee,br as bt,bt as xt,c as St,ci as Ct,cn as wt,cr as Tt,ct as Et,d as Dt,di as Ot,dn as kt,dr as At,dt as jt,ei as Mt,en as Nt,er as Pt,et as Ft,f as It,fi as Lt,fn as Rt,fr as zt,ft as tee,g as nee,gn as Bt,gr as ree,gt as Vt,h as Ht,hn as Ut,hr as Wt,ht as Gt,i as Kt,ii as qt,in as Jt,ir as Yt,it as Xt,j as Zt,jn as Qt,jr as $t,k as en,kn as tn,kr as nn,l as rn,li as an,ln as on,lr as sn,lt as cn,m as ln,mn as un,mr as dn,mt as fn,n as pn,ni as mn,nn as hn,nr as gn,nt as _n,o as vn,oi as yn,on as bn,or as xn,ot as Sn,p as Cn,pn as wn,pr as Tn,pt as En,q as Dn,qn as On,qr as kn,qt as An,r as iee,ri as jn,rn as Mn,rr as Nn,rt as Pn,s as Fn,si as In,sn as Ln,sr as Rn,st as zn,t as Bn,ti as Vn,tn as Hn,tr as Un,tt as Wn,u as Gn,ui as Kn,un as qn,ur as Jn,ut as Yn,v as Xn,vn as Zn,vr as Qn,vt as $n,w as er,wn as tr,wr as nr,x as rr,xn as ir,xr as ar,xt as or,y as sr,yn as cr,yr as lr,yt as ur,z as dr,zn as fr,zr as pr,zt as mr}from"./vendor-D0x8W9No.js";import{$ as hr,A as gr,B as H,C as _r,D as vr,E as yr,F as br,G as xr,H as Sr,I as Cr,J as wr,K as Tr,L as Er,M as Dr,N as Or,O as kr,P as Ar,Q as jr,R as Mr,S as Nr,T as Pr,U as Fr,V as Ir,W as Lr,X as Rr,Y as zr,Z as Br,_ as Vr,a as Hr,at as Ur,b as Wr,c as Gr,ct as Kr,d as qr,et as Jr,f as Yr,g as aee,h as Xr,i as Zr,it as Qr,j as $r,k as ei,l as ti,lt as ni,m as ri,n as ii,nt as ai,o as oi,ot as si,p as ci,q as li,r as ui,rt as di,s as fi,st as pi,t as mi,tt as hi,u as gi,ut as _i,v as vi,w as yi,x as bi,y as xi,z as Si}from"./vendor-codemirror-Bw_t2lTd.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Ci=Kn(),U=e(Lt(),1),W=Ee(),wi=(0,U.createContext)({theme:`system`,setTheme:()=>null});function Ti({children:e,defaultTheme:t=`system`,storageKey:n=`vite-ui-theme`}){let[r,i]=(0,U.useState)(()=>localStorage.getItem(n)||t);(0,U.useEffect)(()=>{let e=window.document.documentElement,t=()=>{if(e.classList.remove(`light`,`dark`),r===`system`){let t=window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`;e.classList.add(t);return}e.classList.add(r)};if(t(),r===`system`){let e=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>t();return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)}},[r]);let a=(0,U.useCallback)(e=>{localStorage.setItem(n,e),i(e)},[n]),o=(0,U.useMemo)(()=>({theme:r,setTheme:a}),[r,a]);return(0,W.jsx)(wi.Provider,{value:o,children:e})}var Ei=()=>{let e=(0,U.useContext)(wi);if(e===void 0)throw Error(`useTheme must be used within a ThemeProvider`);return e};function G(...e){return y(ct(e))}function Di(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t&=t}return Math.abs(t)}var Oi=ye(`inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,outline:`border border-input bg-background hover:bg-accent hover:text-accent-foreground`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-accent hover:text-accent-foreground`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-10 px-4 py-2`,sm:`h-9 rounded-md px-3`,lg:`h-11 rounded-md px-8`,icon:`h-11 w-11 min-h-11 min-w-11`}},defaultVariants:{variant:`default`,size:`default`}}),K=U.memo(U.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...i},a)=>{let o=r?nn:`button`;return(0,W.jsx)(et,{as:o,className:G(Oi({variant:t,size:n,className:e})),ref:a,...i})}));K.displayName=`Button`;var ki=[`parser`,`dialect`,`user-plan`,`runtime`,`user-entry`],Ai={parser:`parser`,compiler:`dialect`,dialect:`dialect`,hinted:`dialect`,"user-plan":`user-plan`,runtime:`runtime`,tracked:`runtime`,analyzed:`runtime`,"analyzed-estimated":`runtime`,execution:`runtime`,user:`user-entry`,collected:`user-entry`,diagnostic:`runtime`};function ji(e){return Ai[e??`parser`]??`parser`}var q=function(e){return e.Duration=`duration`,e.Spans=`spans`,e.SystemTime=`system-time`,e.Time=`time`,e.Elapsed=`elapsed`,e.Total=`total`,e.Rep=`rep`,e.Effort=`effort`,e.Equipment=`equipment`,e.Distance=`distance`,e.Rounds=`rounds`,e.CurrentRound=`current-round`,e.Action=`action`,e.Increment=`increment`,e.Group=`group`,e.Text=`text`,e.Resistance=`resistance`,e.Sound=`sound`,e.System=`system`,e.Label=`label`,e.Lap=`lap`,e.Metric=`metric`,e.Hint=`hint`,e.Custom=`custom`,e.Volume=`volume`,e.Intensity=`intensity`,e.Grade=`grade`,e.Load=`load`,e.Work=`work`,e.RIR=`rir`,e.SessionRPE=`session-rpe`,e.SessionLoad=`session-load`,e.METScore=`met-score`,e.TIS=`tis`,e.Calculated=`calculated`,e.Diagnostic=`diagnostic`,e.Choice=`choice`,e}({}),Mi={parser:0,dialect:1,"user-plan":2,runtime:3,"user-entry":4};function Ni(e){return e.ownershipLayer??ji(e.origin)}function Pi(e){return Mi[Ni(e)]??0}function Fi(e){return e.map((e,t)=>{let n=Ni(e);return{metric:e,type:e.type,layer:n,layerRank:Mi[n]??0,index:t,isSuppressor:e.action===`suppress`}})}function Ii(e,t){return t?e.filter(e=>!(t.types&&!t.types.includes(e.type)||t.layers&&!t.layers.includes(e.layer))):[...e]}function Li(e){let t=new Map;for(let n of e){let e=t.get(n.type);if(e){e.push(n);continue}t.set(n.type,[n])}return t}function Ri(e){let t;for(let n of e)n.isSuppressor||(t==null||n.layerRank>t)&&(t=n.layerRank);return t}function zi(e,t){return{metric:e.metric,type:e.type,layer:e.layer,outcome:t}}function Bi(e,t){return e.index-t.index}function Vi(e){let t=Fi(e);return{raw(e){return Ii(t,e).map(e=>e.metric)},visible(e){let n=Li(Ii(t,e)),r=[];for(let e of n.values()){if(e.some(e=>e.isSuppressor))continue;let t=Ri(e);if(t!=null)for(let n of e)!n.isSuppressor&&n.layerRank===t&&r.push(n)}return r.sort(Bi),r.map(e=>e.metric)},byLayer(e){let n=Ii(t,e),r={};for(let e of ki)r[e]=[];for(let e of n)r[e.layer].push(e.metric);for(let e of ki)r[e]?.length===0&&delete r[e];return r},promotionCandidates(e){let n=Li(Ii(t,e)),r=[];for(let e of n.values()){let t=e.filter(e=>e.isSuppressor),n=e.filter(e=>!e.isSuppressor);if(n.length===0)continue;if(t.length>0){let e=Math.max(...n.map(e=>e.layerRank)),i=Math.max(...t.map(e=>e.layerRank));for(let t of n)t.layerRank===e&&r.push({metric:t.metric,type:t.type,layer:t.layer,reason:`suppressed`,blockedByLayer:ki[i]});continue}let i=Ri(n);if(i==null)continue;let a=n.filter(e=>e.layerRank<i);if(a.length===0)continue;let o=Math.max(...a.map(e=>e.layerRank));for(let e of a)e.layerRank===o&&r.push({metric:e.metric,type:e.type,layer:e.layer,reason:`shadowed-by-higher-layer`,blockedByLayer:ki[i]})}return r.sort((e,t)=>{let n=(Mi[t.layer]??0)-(Mi[e.layer]??0);return n===0?0:n}),r},explain(e){let n=Li(Ii(t,e)),r=[];for(let[e,t]of n.entries()){let n=t.some(e=>e.isSuppressor),i=n?void 0:Ri(t),a=t.map(e=>e.isSuppressor?zi(e,`suppressor`):n?zi(e,`hidden-by-suppressor`):i!=null&&e.layerRank===i?zi(e,`visible`):zi(e,`hidden-by-layer`));r.push({type:e,winnerLayer:i==null?void 0:ki[i],suppressed:n,entries:a})}return r}}}function Hi(e,t){let n=[...e];return(t?.types?.includes(q.Hint)??!1)||(n=n.filter(e=>e.type!==q.Hint)),t?(t.origins&&(n=n.filter(e=>t.origins.includes(e.origin??`parser`))),t.types&&(n=n.filter(e=>t.types.includes(e.type))),t.excludeTypes&&(n=n.filter(e=>!t.excludeTypes.includes(e.type))),n):n}var Ui=class{resolve(e,t){return Vi(Hi(e,t)).visible()}resolveOne(e,t){return this.resolve(e,{types:[t]})[0]}resolveAll(e,t){let n=e.filter(e=>e.type===t);return n.length<=1?n:[...n].sort((e,t)=>Pi(t)-Pi(e))}};function Wi(e){let t=e.split(/[\s_\-\u2010-\u2015]+/).filter(Boolean),n=[];for(let e of t){let t=e.replace(/([\p{Ll}\p{Nd}])(\p{Lu})/gu,`$1\0$2`).replace(/(\p{Lu})(\p{Lu}\p{Ll})/gu,`$1\0$2`);for(let e of t.split(`\0`))e&&n.push(e)}return n}function Gi(e){let t=Wi(e);return t.length===0?``:t.map((e,t)=>{let n=e.toLowerCase();return t===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join(``)}function Ki(e){return e.split(`.`).map(Gi).filter(e=>e.length>0).join(`.`)}function qi(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(Array.isArray(e))return`array`;switch(typeof e){case`number`:return`number`;case`string`:return`string`;case`boolean`:return`boolean`;case`object`:return`object`;default:return`undefined`}}function Ji(e){return JSON.stringify([e.path,e.kind,e.dimension??null])}var Yi=class extends Error{code;constructor(e,t){super(t),this.name=`UnitConversionError`,this.code=e}},Xi=[{canonical:`m`,dimension:`distance`,factor:1,aliases:[`meter`,`meters`,`metre`,`metres`]},{canonical:`km`,dimension:`distance`,factor:1e3,aliases:[`kilometer`,`kilometers`,`kilometre`,`kilometres`]},{canonical:`cm`,dimension:`distance`,factor:.01,aliases:[`centimeter`,`centimeters`]},{canonical:`mm`,dimension:`distance`,factor:.001,aliases:[`millimeter`,`millimeters`]},{canonical:`ft`,dimension:`distance`,factor:.3048,aliases:[`foot`,`feet`]},{canonical:`in`,dimension:`distance`,factor:.0254,aliases:[`inch`,`inches`]},{canonical:`yd`,dimension:`distance`,factor:.9144,aliases:[`yard`,`yards`]},{canonical:`mi`,dimension:`distance`,factor:1609.344,aliases:[`mile`,`miles`]},{canonical:`kg`,dimension:`mass`,factor:1,aliases:[`kilogram`,`kilograms`,`kilo`,`kilos`]},{canonical:`g`,dimension:`mass`,factor:.001,aliases:[`gram`,`grams`]},{canonical:`lb`,dimension:`mass`,factor:.45359237,aliases:[`lbs`,`pound`,`pounds`]},{canonical:`ms`,dimension:`duration`,factor:.001,aliases:[`millisecond`,`milliseconds`]},{canonical:`s`,dimension:`duration`,factor:1,aliases:[`sec`,`secs`,`second`,`seconds`]},{canonical:`min`,dimension:`duration`,factor:60,aliases:[`mins`,`minute`,`minutes`]},{canonical:`h`,dimension:`duration`,factor:3600,aliases:[`hr`,`hrs`,`hour`,`hours`]},{canonical:`count`,dimension:`count`,factor:1},{canonical:`rep`,dimension:`count`,factor:1,aliases:[`reps`]},{canonical:`pull-up`,dimension:`count`,factor:1},{canonical:`thruster`,dimension:`count`,factor:1},{canonical:`problem`,dimension:`count`,factor:1},{canonical:`count/s`,dimension:`count-rate`,factor:1},{canonical:`bpm`,dimension:`count-rate`,factor:1/60},{canonical:`cal`,dimension:`energy`,factor:1,aliases:[`calorie`,`calories`]},{canonical:`kcal`,dimension:`energy`,factor:1e3,aliases:[`kilocalorie`,`kilocalories`]},{canonical:`m/s`,dimension:`speed`,factor:1},{canonical:`km/h`,dimension:`speed`,factor:1e3/3600,aliases:[`kmh`,`kph`]},{canonical:`mph`,dimension:`speed`,factor:1609.344/3600},{canonical:`min/km`,dimension:`pace`,factor:1},{canonical:`min/mi`,dimension:`pace`,factor:1e3/1609.344},{canonical:`s/m`,dimension:`pace`,factor:1/60},{canonical:`ratio`,dimension:`ratio`,factor:1,aliases:[`x`]},{canonical:`%`,dimension:`ratio`,factor:.01,aliases:[`pct`,`percent`]},{canonical:`au`,dimension:`ratio`,factor:1,aliases:[`AU`]},{canonical:`pts`,dimension:`ratio`,factor:1,aliases:[`point`,`points`]},{canonical:`rating`,dimension:`ratio`,factor:1,aliases:[`ratings`]}],Zi=(()=>{let e=new Map;for(let t of Xi){e.set(t.canonical.toLowerCase(),t);for(let n of t.aliases??[])e.has(n.toLowerCase())||e.set(n.toLowerCase(),t)}return e})();function Qi(e){if(typeof e==`string`)return Zi.get(e.trim().toLowerCase())}function $i(e){return Qi(e)?.dimension}var ea=Object.freeze({mass:`kg`,distance:`m`,duration:`s`,count:`count`,"count-rate":`count/s`,energy:`cal`,speed:`m/s`,pace:`min/km`,ratio:void 0});function ta(e){return ea[e]}function na(e,t,n){let r=Qi(t);if(!r)throw new Yi(`unknown-unit`,`Unknown unit "${t}"`);let i=Qi(n);if(!i)throw new Yi(`unknown-unit`,`Unknown unit "${n}"`);if(r.dimension!==i.dimension)throw new Yi(`dimension-mismatch`,`Cannot convert ${t} (${r.dimension}) to ${n} (${i.dimension})`);if(r.dimension===`ratio`&&r.canonical!==i.canonical&&r.canonical!==`ratio`&&i.canonical!==`ratio`)throw new Yi(`scale-mismatch`,`Named scales ${t} and ${n} are not interchangeable`);if(!Number.isFinite(e))throw new Yi(`non-finite`,`Non-finite value cannot be converted`);return e*r.factor/i.factor}var ra=`references`,ia=[`explicit`,`split`,`whole`,`default`,`none`];function aa(e){if(!e||typeof e!=`object`)return!1;let t=e;return(t.kind===`effort`||t.kind===`equipment`)&&typeof t.slug==`string`&&!!t.slug&&typeof t.label==`string`}function oa(e){return!e||typeof e!=`object`?!1:typeof e.reason==`string`}function sa(e){let t=e?.[ra];if(!t||typeof t!=`object`)return;let n=t;if(!(typeof n.matched!=`string`||!ia.includes(n.matched))&&typeof n.source==`string`&&!(n.refs!==void 0&&(!Array.isArray(n.refs)||!n.refs.every(aa)))&&!(n.diagnostics!==void 0&&(!Array.isArray(n.diagnostics)||!n.diagnostics.every(oa))))return t}var ca=class{line;startOffset;endOffset;length;columnStart;columnEnd;raw;constructor(e,t,n,r,i=0,a=0,o=``){this.line=e,this.startOffset=t,this.endOffset=n,this.length=r,this.columnStart=i,this.columnEnd=a,this.raw=o}},la=class e{_metrics;_indexedLength=0;_resolver=new Ui;id;constructor(t,n=`metrics`){if(this.id=n,t instanceof e){this._metrics=t.toArray(),this.syncIndexProperties();return}this._metrics=Array.isArray(t)?[...t]:[],this.syncIndexProperties()}static from(t,n=`metrics`){if(t instanceof e)return t.clone(n);if(Array.isArray(t))return new e(t,n);if(typeof t==`object`&&t&&`_metrics`in t){let r=t._metrics;if(Array.isArray(r))return new e(r,n)}return e.empty(n)}static empty(t=`metrics`){return new e(void 0,t)}clone(t=this.id){return new e(this._metrics,t)}get all(){return[...this._metrics]}get length(){return this._metrics.length}get size(){return this._metrics.length}get isEmpty(){return this._metrics.length===0}getByType(e){let t=this._metrics.filter(t=>t.type===e||t.name===e);return t.length<=1?t:[...t].sort((e,t)=>Pi(t)-Pi(e))}getFirst(e){let t=this.getByType(e);return t.length>0?t[0]:void 0}get(e){return this.getFirst(e)}has(e){return this._metrics.some(t=>t.type===e||t.name===e)}hasMetric(e){return this.has(e)}getDisplayMetrics(e){return this.resolve(e)}getMetric(e){return this._resolver.resolveOne(this._metrics,e)}getAllMetricsByType(e){return this.getByType(e)}get rawMetrics(){return this.toArray()}getAll(){return this.toArray()}getByOrigin(e){return this._metrics.filter(t=>(t.origin??`parser`)===e)}resolve(e){return this._resolver.resolve(this._metrics,e)}add(...e){return this._metrics.push(...e),this.syncIndexProperties(),this}remove(e){let t=[];return this._metrics=this._metrics.filter(n=>!e(n)||(t.push(n),!1)),this.syncIndexProperties(),t}removeByType(e){return this.remove(t=>t.type===e||t.name===e)}clear(){return this._metrics=[],this.syncIndexProperties(),this}replaceByType(e,...t){let n=this.removeByType(e);return this._metrics.push(...t),this.syncIndexProperties(),n}merge(t){let n=t instanceof e?t._metrics:Array.isArray(t)?t:t.metrics.toArray(),r=new Map;for(let e of n){let t=r.get(e.type)??[];t.push(e),r.set(e.type,t)}for(let[e,t]of r){let n=this._metrics.filter(t=>t.type===e);if(n.length===0){this._metrics.push(...t);continue}let r=Math.max(...n.map(e=>Pi(e))),i=Math.max(...t.map(e=>Pi(e)));i>r?(this._metrics=this._metrics.filter(t=>t.type!==e),this._metrics.push(...t)):i===r&&this._metrics.push(...t)}return this.syncIndexProperties(),this}[Symbol.iterator](){return this._metrics[Symbol.iterator]()}filter(e){return this._metrics.filter(e)}map(e){return this._metrics.map(e)}flatMap(e){return this._metrics.flatMap(e)}find(e){return this._metrics.find(e)}some(e){return this._metrics.some(e)}every(e){return this._metrics.every(e)}toArray(){return[...this._metrics]}get raw(){return this._metrics}syncIndexProperties(){for(let e=0;e<this._indexedLength;e++)delete this[e];for(let e=0;e<this._metrics.length;e++)this[e]=this._metrics[e];this._indexedLength=this._metrics.length}toString(){return`MetricContainer(${this._metrics.length})[${this._metrics.map(e=>e.type).join(`, `)}]`}},ua=class{exerciseId;line;text;raw;dialect;hasMetric(e){return this.metricContainer.hasMetric(e)}getDisplayMetrics(e){return this.metricContainer.getDisplayMetrics(e)}getMetric(e){return this.metricContainer.getMetric(e)}getAllMetricsByType(e){return this.metricContainer.getAllMetricsByType(e)}get rawMetrics(){return this.metricContainer.rawMetrics}get metricContainer(){return this.metrics instanceof la?this.metrics:la.from(this.metrics,this.id)}},da=class extends ua{id=0;parent;children=[];meta=new ca(0,0,0,0);_metrics=la.empty();metricMeta=new Map;isLeaf;get metrics(){return this._metrics}set metrics(e){this._metrics=la.from(e,this.id)}constructor(e){super(),e&&(Object.assign(this,e),e.metrics&&(this.metrics=la.from(e.metrics,this.id)),this.metricMeta||=new Map)}},fa=class e extends ua{static nextId=1e6;id;outputType;timeSpan;sourceStatementId;sourceBlockKey;stackLevel;metrics;metricMeta;completionReason;parent;children;isLeaf;meta;statement;timestamp;constructor(t,n,r){if(super(),t&&`outputType`in t&&`timeSpan`in t){let n=t;this.id=e.nextId++,this.outputType=n.outputType,this.timeSpan=n.timeSpan,this.sourceBlockKey=n.sourceBlockKey??``,this.sourceStatementId=n.sourceStatementId,this.line=n.line,this.text=n.text,this.dialect=n.dialect,this.stackLevel=n.stackLevel??0,this.metrics=la.from(n.metrics,this.id),this.metricMeta=n.metricMeta??new Map,this.completionReason=n.completionReason,this.parent=n.parent,this.children=n.children??[],this.isLeaf=this.children.length===0,this.meta=new ca(0,0,0,0)}else{let i=t;this.id=e.nextId++,this.statement=i,this.outputType=`segment`,this.timeSpan={started:r??Date.now()},this.sourceBlockKey=``,this.sourceStatementId=typeof i?.id==`number`?i.id:void 0,this.stackLevel=0,this.metrics=la.from(n,this.id),this.metricMeta=new Map,this.children=[],this.isLeaf=!0,this.meta=i?.meta??new ca(0,0,0,0),this.line=i?.line,this.text=i?.text,this.dialect=i?.dialect,this.timestamp=r??Date.now()}}static resetIdCounter(t=1e6){e.nextId=t}},pa=class{value;constructor(e){this.value=e??(typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():Math.random().toString(36).slice(2))}toString(){return this.value}valueOf(){return this.value}equals(e){return this.value===e?.value}};function ma(e){let t=new Map;for(let n of e)t.set(n.slug,n);return{resolve:e=>t.get(e),list:()=>[...t.values()]}}var ha=`tagReference`;function ga(e){let t=e?.[ha];if(!t||typeof t!=`object`)return;let n=t;if(!(typeof n.slug!=`string`||!n.slug)&&typeof n.label==`string`&&!(n.functions!==void 0&&!Array.isArray(n.functions))&&(n.soundProfileId===void 0||typeof n.soundProfileId==`string`))return t}function _a(e){let t=e.trim(),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619);return`bc-${(n>>>0).toString(16).padStart(8,`0`)}`}function va(e,t){let n=e.position??1/0,r=t.position??1/0;return n===r?e.createdAt===t.createdAt?e.id<t.id?-1:+(e.id>t.id):e.createdAt-t.createdAt:n-r}function ya(e){return[...e].sort(va)}function ba(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[];for(let t of ya(e)){let e=n.get(t.pageId);e&&r.push({pageId:e.id,noteId:t.noteId,position:t.position,createdAt:t.createdAt,date:e.date,slug:e.slug,title:e.title})}return r}function xa(e){let t={};for(let n of e)t.pageId===void 0&&(t.pageId=n.pageId),t.journalDate===void 0&&n.date&&(t.journalDate=n.date),t.pageSlug===void 0&&n.slug&&!n.date&&(t.pageSlug=n.slug);return t}var Sa=[`segment`,`system`,`load`,`event`,`compiler`,`completion`,`analytics`,`wellness`];function Ca(e){return e===`time`?`run`:e===`log`?`log`:null}function wa(e){let t=e.trim();return t.startsWith(`notebook/`)||t.startsWith(`notebook:`)?t.slice(9):t}function Ta(e){return`notebook/${wa(e)}`}function Ea(e,t){return t?t!==`feed`:e.seedOrigin!==`seed`&&e.feedOrigin!==`feed`}var Da=[{slug:`journal`,notebookId:`notebook/journal`,name:`Journal`,description:`Dated training log and scheduled workouts.`,icon:`📅`,href:`/journal`},{slug:`playground`,notebookId:`notebook/playground`,name:`Playground`,description:`Scratchpad workouts and timer experiments.`,icon:`🧪`,href:`/playgrounds`},{slug:`defaults`,notebookId:`notebook/defaults`,name:`Defaults`,description:`Starter notes — clone any of them into your own notebooks.`,icon:`📝`,href:`/notebook/defaults`},{slug:`guides`,notebookId:`notebook/guides`,name:`Guides`,description:`Built-in Whiteboard Language and WQL guides.`,icon:`📖`,href:`/notebook/guides`,feedEntryId:`core`,seedChunkId:`canvas`},{slug:`efforts`,notebookId:`notebook/efforts`,name:`Efforts`,description:`The effort library — every effort the parser and analytics resolve, across the canonical disciplines.`,icon:`🏋️`,href:`/efforts`,feedEntryId:`core`,seedChunkId:`efforts`},{slug:`equipment`,notebookId:`notebook/equipment`,name:`Equipment`,description:`The equipment library — gear definitions the language resolves.`,icon:`🔧`,href:`/equipment`,feedEntryId:`core`,seedChunkId:`equipment`},{slug:`dashboards`,notebookId:`notebook/dashboards`,name:`Dashboards`,description:`Prebuilt WQL dashboards — query compositions ready to open.`,icon:`📊`,href:`/dashboards`,feedEntryId:`core`,seedChunkId:`dashboards`}],Oa=[`playground-run-tip`,`attention`,`code-example`,`syntax-group`];function ka(e){let t=e.match(/^`{3,}(time|log)(?::([\w-]+))?\s*$/i);return t?{dialect:t[1].toLowerCase()===`time`?`time`:`log`,...t[2]?{sport:t[2]}:{}}:null}function Aa(e){let t=e.type?.toLowerCase();if(t===`youtube`||t===`strava`||t===`amazon`||t===`file`||t===`effort`||t===`equipment`)return t;let n=(e.url||e.link||``).replace(/^[a-z][a-z0-9+.-]*:\/\//i,``).split(/[/?#:]/,1)[0].toLowerCase();return n===`youtu.be`||n===`youtube.com`||n.endsWith(`.youtube.com`)?`youtube`:n===`strava.com`||n.endsWith(`.strava.com`)?`strava`:n===`amzn.to`||n===`amazon.com`||n.endsWith(`.amazon.com`)?`amazon`:[`baseAttributes`,`metrics.met`,`discipline`,`effortType`,`targetRPE`,`equipment`,`aliases`,`derivation`].some(t=>t in e)?`effort`:[`slug`,`label`,`registrySource`,`ownerNoteId`,`sourcePath`].some(t=>t in e)?`equipment`:`default`}function ja(e){return/^#{1,6}\s/.test(e)?`heading`:/^[-*+]\s|^\d+\.\s/.test(e)?`list`:/^>\s?/.test(e)?`blockquote`:e.startsWith(`|`)&&/^\|[\s:]*-+/m.test(e)?`table`:`paragraph`}function Ma(e,t={}){if(!e)return[];let n=e.split(/\r\n|\n|\r/),r=[],i=[],a=0;for(let t of n){r.push(a),a+=t.length;let n=e.startsWith(`\r
3
3
  `,a)?`\r
4
4
  `:/[\r\n]/.test(e[a]??``)?e[a]:``;i.push(n),a+=n.length}let o=[],s=Date.now(),c=!0,l=0;function u(t,a,o){let c=r[a],l=r[o]+n[o].length;return{id:crypto.randomUUID(),type:t,from:c,to:l,rawContent:e.slice(c,l),displayContent:e.slice(c,l),startLine:a,endLine:o,lineCount:o-a+1,version:1,createdAt:s,separatorAfter:i[o]}}for(;l<n.length;){let a=n[l].trim(),d=a.match(/^(`{3,}|~{3,})(.*)$/);if(d){let a=d[1],c=l+1,f=RegExp(`^${a[0]}{${a.length},}\\s*$`);for(;c<n.length&&!f.test(n[c].trim());)c++;let p=c<n.length,m=p?c:n.length-1,h=d[2].trim(),g=a[0]==="`"?ka(`\`\`\`${h}`):null,_=a[0]==="`"?h.match(/^widget:([\w-]+)$/):null,v=a[0]==="`"?h.match(/^query(?:[:\s](.*))?$/i):null,y=t.registeredWidgets??Oa,b=_&&(`has`in y?y.has(_[1]):y.includes(_[1])),x=p&&g?g.dialect:p&&b?`widget`:p&&v?`query`:`code`,S=u(x,l,m);S.contentFrom=r[l]+n[l].length+i[l].length,S.contentTo=p?r[c]:S.to,S.displayContent=e.slice(S.contentFrom,S.contentTo),g&&p&&(S.sport=g.sport,S.contentId=_a(S.displayContent),S.scriptBlock={id:S.id,contentId:S.contentId,dialect:g.dialect,sport:g.sport,startLine:l,endLine:m,content:S.displayContent,state:`idle`,version:1,createdAt:s}),x===`widget`&&_&&(S.widgetName=_[1]),x===`query`&&v&&(S.querySuffix=(v[1]??``).trim()),o.push(S),l=m+1;continue}if(a===`---`&&n[l+1]?.trim()){let t=l+1;for(;t<n.length&&n[t].trim()!==`---`&&!/^(`{3,}|~{3,})/.test(n[t].trim());)t++;let i=n.slice(l+1,t);if(n[t]?.trim()===`---`&&i.some(e=>/^[A-Za-z_][\w.-]*\s*:/.test(e.trim()))){let n=u(`frontmatter`,l,t);n.contentFrom=r[l+1],n.contentTo=r[t],n.displayContent=e.slice(n.contentFrom,n.contentTo),n.properties={};for(let e of i){let t=e.match(/^([^:]+):\s*(.*)$/);t&&(n.properties[t[1].trim()]=t[2].trim())}n.frontmatterType=Aa(n.properties),o.push(n),l=t+1;continue}}let f=a.match(/^(!)?\[([^\]]*)\]\((https?:\/\/[^)\s]+|\/[^)\s]+)\)$/);if(f){let e=u(`embed`,l,l),t=!!f[1];e.embed={type:t?`image`:/(?:youtube\.com|youtu\.be)/i.test(f[3])?`youtube`:`link`,label:f[2],url:f[3],isImage:t},o.push(e),l++;continue}let p=l;if(a)for(;p+1<n.length&&n[p+1].trim()&&!/^(?:`{3,}|~{3,}|---\s*$|!?\[[^\]]*\]\()/.test(n[p+1].trim());)p++;let m=u(a&&c?`title`:`markdown`,l,p);m.subtype=ja(m.displayContent.trim()),a&&(c=!1),o.push(m),l=p+1}return o}function Na(e){return e.type===`time`||e.type===`log`?`wod`:e.type===`query`||e.type===`widget`||e.type===`embed`?e.type:null}function Pa(e,t){if(!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw Error(`Invalid source revision`);let n=Object.create(null),r=Object.values(t.blocks??{}).filter(e=>e&&typeof e==`object`),i=t.createId??(()=>crypto.randomUUID());for(let a of Ma(e,t)){let e=Na(a);if(!e)continue;let o=r.filter(t=>t.from===a.from&&t.to===a.to&&t.kind===e),s=o.length===1?o[0]:void 0,c=s?.id??i();if(!c||Object.hasOwn(n,c))throw Error(`Duplicate block occurrence ID`);n[c]={id:c,kind:e,from:a.from,to:a.to,sourceRevision:t.sourceRevision,version:s?.version??1,...e===`wod`&&(a.type===`time`||a.type===`log`)?{dialect:a.type,...a.sport?{sport:a.sport}:{}}:{}}}return n}function Fa(e,t,n,r={}){if(typeof e!=`string`||!t||typeof t!=`object`||Array.isArray(t))throw Error(`Invalid Note source or blocks`);for(let[e,r]of Object.entries(t))if(!r||r.id!==e||!e||!Number.isSafeInteger(r.version)||r.version<1||r.sourceRevision!==n||!Number.isSafeInteger(r.from)||!Number.isSafeInteger(r.to))throw Error(`Invalid block identity, version or source revision`);let i=Pa(e,{...r,sourceRevision:n,blocks:t});if(Object.keys(i).length!==Object.keys(t).length)throw Error(`Incomplete actionable block map`);for(let[e,n]of Object.entries(t)){let t=i[e];if(!t||t.from!==n.from||t.to!==n.to||t.kind!==n.kind||t.dialect!==n.dialect||t.sport!==n.sport)throw Error(`Block does not match authored source`)}}function Ia(e,t){let n=0;for(let e of t){if(!Number.isSafeInteger(e.from)||!Number.isSafeInteger(e.to)||e.from<n||e.to<e.from||typeof e.insert!=`string`)throw Error(`Invalid source changes`);n=e.to}let r={};for(let n of Object.values(e)){let e=n.from,i=n.to,a=!1;for(let r of t){let t=r.insert.length-(r.to-r.from);if(r.from<=n.from&&r.to>=n.to||r.from<n.from&&r.to>n.from||r.from<n.to&&r.to>n.to){a=!0;break}r.to<=n.from?(e+=t,i+=t):r.from<n.to&&(i+=t)}a||(r[n.id]={...n,from:e,to:i})}return r}var La=/^[A-Za-z][\w.-]*$/,Ra=/^---\r?\n([\s\S]*?)\r?\n---/;function za(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ba(e){let t=e.trim();return t===``||t.startsWith(`#`)}function Va(e){return Array.isArray(e)}function Ha(e){if(e===``)return`""`;let t=!isNaN(Number(e)),n=/^(true|false|null|yes|no|on|off)$/i.test(e);return/[:"'\n#{}[\],&*?|<>=%!@`]/.test(e)||e!==e.trim()||e.startsWith(`-`)||t||n?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}"`:e}function Ua(e,t,n){let r=` `.repeat(e);return Va(n)?n.length===0?[`${r}${t}: []`]:[`${r}${t}:`,...n.map(e=>`${r} - ${typeof e==`number`?String(e):Ha(e)}`)]:[`${r}${t}: ${typeof n==`number`?String(n):Ha(n)}`]}function Wa(e,t,n,r){let i=[],a=r;for(let r=t;r<e.length;r++)r===e.length-1?i.push(...Ua(a,e[r],n)):i.push(`${` `.repeat(a)}${e[r]}:`),a+=2;return i}function Ga(e){let t=!1,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){i===`\\`?r++:i===`"`&&(n=!1);continue}if(t){i===`'`&&(t=!1);continue}if(i===`"`)n=!0;else if(i===`'`)t=!0;else if(i===`#`&&(r===0||/\s/.test(e[r-1])))return r}return-1}function Ka(e,t,n){let r=[t],i=[];for(let a=t+1;a<e.length;a++){let t=e[a];if(Ba(t)){i.push(a);continue}if(t.length-t.trimStart().length>n)r.push(...i,a),i=[];else break}return r}function qa(e,t,n,r,i){let a=RegExp(`^ {${n}}${za(t)}\\s*:`);for(let t=r;t<i;t++)if(a.test(e[t]))return t;return-1}function Ja(e,t,n){if(t.length===0||!t.every(e=>typeof e==`string`&&La.test(e)))return e;let r=e.includes(`\r
@@ -15,7 +15,7 @@ import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{$ as n,$n as r,
15
15
  `)}function sl(){return{id:`equipment-user-${C()}`,slug:``,label:``,aliases:[],registrySource:`user`}}function cl(e,t){let n=[];if(!e.match(Uc))return n.push(`Missing YAML frontmatter delimiters (---)`),{equipment:t??sl(),errors:n};let{meta:r,body:i}=qc(e),a=i.replace(/^\r?\n+/,``)||void 0,o=Jc(r,`type`),s=Jc(r,`id`),c=Jc(r,`slug`),l=Jc(r,`label`),u=Jc(r,`registrySource`),d=Jc(r,`createdAt`),f=Jc(r,`updatedAt`),p=Yc(r,`aliases`);return o!==`equipment`&&n.push("Missing or invalid discriminator: frontmatter must declare `type: equipment`"),(!c||!Wc.test(String(c)))&&n.push(`Invalid slug: must be a canonical slug (lowercase letters, numbers, hyphens)`),l||n.push(`Missing required field: label`),p===void 0?n.push("Invalid aliases: must be a list (`aliases:` followed by `- item` lines)"):n.push(...el(p,`aliases`)),u!==void 0&&u!==`bundled`&&u!==`user`&&n.push(`Invalid registrySource: must be 'bundled' or 'user'`),{equipment:{id:String(s??``)||t?.id||`equipment-user-${C()}`,slug:String(c??``),label:String(l??``),aliases:p??[],registrySource:u||t?.registrySource||`user`,...d?{createdAt:String(d)}:{},...f?{updatedAt:String(f)}:{},...a?{body:a}:{}},errors:n}}function ll(e){let t=[`---`];if(t.push(`type: equipment`),t.push(`id: ${e.id}`),t.push(`slug: ${e.slug}`),t.push(`label: ${Kc(e.label)}`),e.aliases.length>0){t.push(`aliases:`);for(let n of e.aliases)t.push(` - ${Kc(n)}`)}else t.push(`aliases: []`);return t.push(`registrySource: ${e.registrySource}`),e.createdAt&&t.push(`createdAt: ${e.createdAt}`),e.updatedAt&&t.push(`updatedAt: ${e.updatedAt}`),t.push(`---`),e.body&&(t.push(``),t.push(e.body)),t.join(`
16
16
  `)}function ul(e,t=`tag`){let n=[],r=e.match(Uc);if(!r)return n.push(`Missing YAML frontmatter delimiters (---)`),{tag:{id:`tag-${C()}`,slug:``,label:``,category:t,aliases:[],metrics:{},summaries:{},tags:[],functions:[]},errors:n};let i=r[1].split(/\r?\n/),{meta:a,body:o}=qc(e),s=o.replace(/^\r?\n+/,``)||void 0,c=String(Jc(a,`id`)??`tag-${C()}`),l=Jc(a,`label`)??Jc(a,`slug`)??``,u=String(l).trim(),d=String(Jc(a,`slug`)??u),f=String(Jc(a,`category`)??Jc(a,`type`)??t).trim()||t,p=Yc(a,`aliases`)??[],m=Yc(a,`tags`)??[],h=Yc(a,`functions`)??[];u||n.push(`Missing required field: label`);let g={},_={},v=Zc(i,`metrics`)??{};for(let[e,t]of Object.entries(v))(typeof t==`number`||typeof t==`string`)&&(g[e]=t);let y=Zc(i,`summaries`)??{};for(let[e,t]of Object.entries(y))(typeof t==`number`||typeof t==`string`)&&(_[e]=String(t));for(let[e,t]of Object.entries(a))if(e.startsWith(`metrics.`)){let n=e.slice(8).trim();n&&(g[n]=t)}else if(e.startsWith(`summaries.`)){let n=e.slice(10).trim();n&&!Array.isArray(t)&&(_[n]=String(t))}return{tag:{id:c,slug:d,label:u,category:f,aliases:p,metrics:g,summaries:_,tags:m,functions:h,...s?{body:s}:{}},errors:n}}function dl(e){let t=[`---`];if(t.push(`type: ${Kc(e.category||`tag`)}`),t.push(`id: ${e.id}`),t.push(`slug: ${Kc(e.slug||e.label)}`),t.push(`label: ${Kc(e.label)}`),e.aliases.length>0){t.push(`aliases:`);for(let n of e.aliases)t.push(` - ${Kc(n)}`)}else t.push(`aliases: []`);if(e.tags.length>0){t.push(`tags:`);for(let n of e.tags)t.push(` - ${Kc(n)}`)}if(e.functions.length>0){t.push(`functions:`);for(let n of e.functions)t.push(` - ${Kc(n)}`)}for(let[n,r]of Object.entries(e.metrics))if(Array.isArray(r)){t.push(`metrics.${n}:`);for(let e of r)t.push(` - ${Kc(e)}`)}else typeof r==`number`?t.push(`metrics.${n}: ${r}`):t.push(`metrics.${n}: ${Kc(String(r))}`);for(let[n,r]of Object.entries(e.summaries))t.push(`summaries.${n}: ${Kc(r)}`);if(t.push(`---`),e.body)t.push(``),t.push(e.body);else{let n=e.category&&e.category!==`tag`&&e.category!==`general`?`${e.category}:${e.slug||e.label}`:`tags:${e.slug||e.label}`;t.push(``),t.push(`# ${e.label}`),t.push(``),t.push("```query"),t.push(`:note{${n}}`),t.push("```")}return t.join(`
17
17
  `)}function fl(e){let t=[`---`];t.push(`type: tag-type`),t.push(`id: ${e.id||`tag-type-${e.name}`}`),t.push(`slug: ${Kc(e.name)}`),t.push(`label: ${Kc(e.label)}`),e.color&&t.push(`color: ${Kc(e.color)}`);for(let[n,r]of Object.entries(e.metrics??{}))t.push(`metrics.${n}: ${typeof r==`number`?r:Kc(String(r))}`);for(let[n,r]of Object.entries(e.summaries??{}))t.push(`summaries.${n}: ${Kc(r)}`);return t.push(`---`),e.body?(t.push(``),t.push(e.body)):(t.push(``),t.push(`# ${e.label}`),t.push(``),t.push("```query"),t.push(`:tag{type:${e.name}}`),t.push("```")),t.join(`
18
- `)}function pl(e){return cc(e).replace(/\s+/g,`-`)}var ml=class{registry;options;constructor(e,t){this.registry=e,this.options={defaultMet:t?.defaultMet??oc.defaultMet,defaultThreshold:t?.defaultThreshold??oc.defaultThreshold}}resolveBySlug(e){return this.registry.resolve(e)}resolveByAlias(e){let t=cc(e);for(let e of this.registry.list()){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}return null}resolveFuzzy(e,t){let n=t?.threshold??this.options.defaultThreshold,r=cc(e),i=this.resolveByAlias(e);if(i)return i;let a=[];for(let e of this.registry.list())for(let t of[e.label,...e.aliases])a.push({alias:t,effort:e});let o=lc(r,a.map(e=>e.alias),n);if(o){let e=a.find(e=>cc(e.alias)===cc(o.target));if(e)return e.effort}return this.createSyntheticEffort(e)}resolveEffort(e,t){let n=this.resolveBySlug(e)??this.resolveByAlias(e)??this.resolveFuzzy(e,{threshold:t?.threshold});return this.resolveDefinition(n,t)}resolveDefinition(e,t){return this.materialize(e,t?.modifiers??{},new Set)}list(){return this.registry.list()}materialize(e,t,n){if(n.has(e.slug))throw Error(`EffortResolver: circular effort derivation detected at "${e.slug}"`);n.add(e.slug);let r=e.derivation?.parentSlug?this.registry.resolve(e.derivation.parentSlug):null,i=r?this.materialize(r,t,n):null,a=i?.met??e.baseAttributes.met,o=e.derivation?.coefficients??{};for(let[e,n]of Object.entries(o))this.shouldApplyCoefficient(e,t)&&(a*=n);let s=e.derivation?.hardOverrides?.met;typeof s==`number`&&Number.isFinite(s)&&(a=s);let c=e.baseAttributes.discipline??i?.discipline,l=this.resolveDisciplineFactor(e,i),u=e.registrySource,d=u===`user`?`user`:u===`bundled`?`bundled`:`default`,f=u===`synthetic-unresolved`,p={...e,baseAttributes:{...e.baseAttributes,met:a,discipline:c,disciplineFactor:l,intensityTier:e.baseAttributes.intensityTier??i?.intensityTier}};return{effort:p,definition:e,slug:p.slug,label:p.label,met:a,baseAttributes:p.baseAttributes,discipline:c,disciplineFactor:l,intensityTier:p.baseAttributes.intensityTier,modifiers:{...t},registrySource:u,resolvedFrom:d,isEstimated:f}}shouldApplyCoefficient(e,t){if(e===`met`||e===`*`)return!0;for(let[n,r]of Object.entries(t))if(e===n||e===r||e===`${n}:${r}`||e===`${n}=${r}`)return!0;return!1}resolveDisciplineFactor(e,t){let n=e.derivation?.hardOverrides?.disciplineFactor;if(typeof n==`number`&&Number.isFinite(n))return n;let r=e.baseAttributes.disciplineFactor;if(typeof r==`number`&&Number.isFinite(r))return r;let i=e.baseAttributes.discipline??t?.discipline;return!i&&t?t.disciplineFactor:Hc(i)}createSyntheticEffort(e){let t=cc(e),n=pl(e);return{id:`synthetic-${C()}`,slug:n,label:t,aliases:[t],baseAttributes:{met:this.options.defaultMet,discipline:void 0,intensityTier:void 0},registrySource:`synthetic-unresolved`}}},hl=[{id:`fixture-running`,slug:`running-6-mph`,label:`Running (6 mph)`,aliases:[`run`,`jogging`,`treadmill`],baseAttributes:{met:9.8,discipline:`running`,intensityTier:`moderate`},registrySource:`bundled`},{id:`fixture-rowing`,slug:`rowing`,label:`Rowing`,aliases:[`row`,`rower`,`erg`],baseAttributes:{met:7,discipline:`rowing`,intensityTier:`high`},registrySource:`bundled`},{id:`fixture-back-squat`,slug:`back-squat`,label:`Back Squat`,aliases:[`squat`,`barbell squat`,`bs`],baseAttributes:{met:6,discipline:`strength`,intensityTier:`moderate`},registrySource:`bundled`},{id:`fixture-burpee`,slug:`burpee`,label:`Burpee`,aliases:[`burpees`],baseAttributes:{met:10,discipline:`bodyweight`,intensityTier:`high`},registrySource:`bundled`},{id:`fixture-plank`,slug:`plank`,label:`Plank`,aliases:[`planks`],baseAttributes:{met:3.5,discipline:`bodyweight`,intensityTier:`low`},registrySource:`bundled`}];[...hl];var gl=hl;gl.length;var _l=class{efforts=new Map;sourceFilter=null;initialized=!1;constructor(e){this.sourceFilter=e??null}async loadBundled(){for(let e of gl)(!this.sourceFilter||e.registrySource===this.sourceFilter)&&this.efforts.set(e.slug,e);this.initialized=!0}isInitialized(){return this.initialized}seed(e){for(let t of e)this.efforts.set(t.slug,t)}clear(){this.efforts.clear(),this.initialized=!1}resolve(e){return this.efforts.get(e)??null}resolveByAlias(e){let t=cc(e);for(let e of this.efforts.values()){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}return null}list(){return Array.from(this.efforts.values())}listByOrigin(e){return this.list().filter(t=>t.registrySource===e)}async upsert(e){if(e.registrySource!==`user`)throw Error(`InMemoryEffortRegistry.upsert: only user efforts can be written. Received registrySource="${e.registrySource}"`);this.efforts.set(e.slug,e)}async delete(e){let t=this.efforts.get(e);if(t&&t.registrySource!==`user`)throw Error(`InMemoryEffortRegistry.delete: cannot delete non-user effort "${e}"`);this.efforts.delete(e)}},vl=class{userItems=new Map;bundledItems=new Map;initialized=!1;initialBundled;storage;constructor(e){this.initialBundled=e?.bundled,this.storage=e?.storage}async loadBundled(e){let t=this.storage?await this.storage.load():[];this.bundledItems.clear();let n=e??this.initialBundled;if(n)for(let e of n){let t=this.bundledItems.get(e.slug);(!t||rc(e)>=rc(t))&&this.bundledItems.set(e.slug,e)}this.userItems.clear();for(let e of t)e.registrySource===`user`&&this.userItems.set(e.slug,e);this.initialized=!0}isInitialized(){return this.initialized}resolve(e){return this.userItems.get(e)??this.bundledItems.get(e)??null}resolveByAlias(e){let t=cc(e);for(let e of this.userItems.values()){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}let n=[...this.bundledItems.values()].filter(e=>!this.userItems.has(e.slug)).sort((e,t)=>rc(t)-rc(e));for(let e of n){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}return null}list(){let e=new Map(this.bundledItems);for(let t of this.userItems.values())e.set(t.slug,t);return[...e.values()]}listByOrigin(e){return e===`user`?[...this.userItems.values()]:[...this.bundledItems.values()]}async upsert(e){if(e.registrySource!==`user`)throw Error(`Cannot upsert property with registrySource '${e.registrySource}'; clone it as 'user' first`);this.userItems.set(e.slug,e),this.storage&&await this.storage.save(e)}async delete(e){if(!this.userItems.get(e))throw Error(`Cannot delete '${e}': not a user-owned record`);this.userItems.delete(e),this.storage&&await this.storage.delete(e)}},yl=class extends vl{constructor(e){super({storage:e?.storage})}},bl=class extends vl{constructor(e){super({bundled:e?.bundled,storage:e?.storage})}async loadBundled(e){this.bundledItems.clear();let t=e??this.initialBundled??gl;for(let e of t){let t=this.bundledItems.get(e.slug);(!t||rc(e)>=rc(t))&&this.bundledItems.set(e.slug,e)}if(this.userItems.clear(),this.storage)try{let e=await this.storage.load();for(let t of e)t.registrySource===`user`&&this.userItems.set(t.slug,t)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to load user efforts from storage adapter:`,e)}this.initialized=!0}isInitialized(){return this.initialized}listByOrigin(e){return e===`user`?Array.from(this.userItems.values()):e===`bundled`?Array.from(this.bundledItems.values()):this.list().filter(t=>t.registrySource===e)}async upsert(e){if(e.registrySource!==`user`)throw Error(`CompositeEffortRegistry.upsert: only user efforts can be written. Received registrySource="${e.registrySource}"`);if(this.userItems.set(e.slug,e),this.storage)try{await this.storage.save(e)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to persist effort to storage adapter:`,e)}}async delete(e){let t=this.resolve(e);if(t&&t.registrySource!==`user`)throw Error(`CompositeEffortRegistry.delete: cannot delete non-user effort "${e}"`);if(this.userItems.delete(e),this.storage)try{await this.storage.delete(e)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to delete effort from storage adapter:`,e)}}};async function xl(e,t,n){let r=n.trim();if(!r)throw Error(`Alias cannot be empty`);let i=e.resolve(t);if(!i)throw Error(`Effort "${t}" not found in registry`);let a=cc(r);if(cc(i.label)===a||i.aliases.some(e=>cc(e)===a))return i;let o=[...i.aliases,r],s=new Date().toISOString();if(i.registrySource===`bundled`){let t=typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`effort-user-${crypto.randomUUID()}`:`effort-user-${Date.now()}`,n={...i,id:t,registrySource:`user`,aliases:o,updatedAt:s,derivation:i.derivation??{parentSlug:i.slug,coefficients:{},hardOverrides:{}}};return await e.upsert(n),n}let c={...i,aliases:o,updatedAt:s};return await e.upsert(c),c}var Sl={debugMode:!1,enableLogging:!1,maxActionDepth:20},Cl=class e{started;ended;constructor(e,t){this.started=e,this.ended=t}static fromJSON(t){return new e(t.started,t.ended)}static fromDates(t,n){return new e(t.getTime(),n?.getTime())}get duration(){let e=this.ended??Date.now();return Math.max(0,e-this.started)}get isOpen(){return this.ended===void 0}get startDate(){return new Date(this.started)}get endDate(){return this.ended?new Date(this.ended):void 0}},wl=class e{_underlying;_frozenTime;constructor(e,t){this._underlying=e,this._frozenTime=t}get currentDate(){return this._frozenTime}now(){return this._frozenTime}nowMs(){return this._frozenTime.getTime()}get elapsed(){return this._underlying.elapsed}get isRunning(){return this._underlying.isRunning}get spans(){return this._underlying.spans}start(){return this._underlying.start()}stop(){return this._underlying.stop()}static at(t,n){return new e(t,n)}static now(t){return new e(t,t.currentDate)}},Tl=class{_spans=[];get currentDate(){return new Date}now(){return this.currentDate}nowMs(){return this.currentDate.getTime()}get isRunning(){return this._spans.length!==0&&this._spans[this._spans.length-1].isOpen}get spans(){return this._spans}get elapsed(){return this._spans.reduce((e,t)=>e+t.duration,0)}start(){let e=new Date;return this.isRunning?this._spans[this._spans.length-1].startDate:(this._spans.push(new Cl(e.getTime())),e)}stop(){let e=new Date;return this.isRunning&&(this._spans[this._spans.length-1].ended=e.getTime()),e}reset(){this._spans=[]}},El={now:()=>new Date,nowMs:()=>Date.now()},Dl=class{options;now;type=`next`;constructor(e,t=El){this.options=e,this.now=t}do(e){if(!this.validateRuntimeState(e))return[];let t=e.stack.current;if(!t)return[];try{let n={...e.clock?{clock:wl.now(e.clock)}:void 0,...this.options};return t.next(e,n)}catch(n){return e.errors&&Array.isArray(e.errors)&&e.errors.push({error:n,source:`NextAction`,timestamp:this.now.now(),blockKey:t.key.toString()}),[]}}validateRuntimeState(e){return!!e.stack}},Ol=class{error;source;context;type=`error`;constructor(e,t,n){this.error=e,this.source=t,this.context=n}do(e){let t=e;t.errors||=[];let n={error:this.error,source:this.source,timestamp:new Date,context:this.context};t.errors.push(n),console.error(`❌ Runtime Error from ${this.source}:`,this.error.message),this.context&&console.error(` Context:`,this.context)}},kl=class{error;source;type=`throw-error`;constructor(e,t){this.error=e,this.source=t}do(e){new Ol(this.error,this.source).do(e),e.eventBus.dispatch({name:`workout:error`,timestamp:e.clock.currentDate,data:{error:this.error,source:this.source}},e)}};function Al(e,t){return new kl(e,t)}var jl=class{_id;_name;constructor(e){this._id=e,this._name=`next-handler`}get id(){return this._id}set id(e){throw Error(`Cannot modify readonly property id`)}get name(){return this._name}set name(e){throw Error(`Cannot modify readonly property name`)}handler(e,t){return e.name===`next`?!t||!t.stack||t.stack.count===0?[Al(Error(`Invalid runtime state for next event`),`NextEventHandler`)]:[new Dl(void 0,t.nowProvider)]:[]}},Ml=class{type=`abort-session`;do(e){let t=0,n=[];for(;t<100&&e.stack.count>0;){let r=e.stack.current;if(!r)break;!r.isComplete&&typeof r.markComplete==`function`&&r.markComplete(`user-abort`);let i=(r.unmount(e,{createdAt:e.clock.currentDate})??[]).filter(e=>e.type!==`emit-event`);n.push(...i);let a=e.stack.pop();if(!a)break;a.dispose(e),a.context?.release?.(),t++}return n}},Nl=class{_id;constructor(e){this._id=e}get id(){return this._id}set id(e){throw Error(`Cannot modify readonly property id`)}get name(){return`abort-handler`}set name(e){throw Error(`Cannot modify readonly property name`)}handler(e,t){return e.name!==`abort`||!t||!t.stack||t.stack.count===0?[]:[new Ml]}},Pl=class{message;event;blockKey;blockLabel;stackLevel;extra;type=`emit-system-output`;constructor(e,t,n,r,i,a){this.message=e,this.event=t,this.blockKey=n,this.blockLabel=r,this.stackLevel=i,this.extra=a}do(e){let t=e.clock.currentDate,n={event:this.event,blockKey:this.blockKey,blockLabel:this.blockLabel,...this.extra},r={type:q.System,image:this.message,value:n,origin:`runtime`,timestamp:t},i=new fa({outputType:`system`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:this.blockKey,stackLevel:this.stackLevel??e.stack.count,metrics:[r]});return e.addOutput(i),[]}},Fl=class{_runtime;_workList=[];_iteration=0;_maxIterations;_snapshotClock;constructor(e,t=20){this._runtime=e,this._maxIterations=t,this._snapshotClock=wl.at(e.clock,e.clock.currentDate)}get script(){return this._runtime.script}get eventBus(){return this._runtime.eventBus}get stack(){return this._runtime.stack}get options(){return this._runtime.options}get jit(){return this._runtime.jit}get errors(){return this._runtime.errors}get analyticsContext(){return this._runtime.analyticsContext}get clock(){return this._snapshotClock}get nowProvider(){return this._runtime.nowProvider}addOutput(e){this._runtime.addOutput(e)}do(e){this._workList.unshift(e)}doAll(e){e.length!==0&&this._workList.unshift(...e)}handle(e){let t=this.eventBus.dispatch(e,this);if(t.length>0){let n=`source`in e&&typeof e.source==`string`?e.source:`event-bus`,r=new Pl(`event: ${e.name} → ${t.length} action(s)`,`event-action`,n,void 0,this.stack.count,{eventName:e.name,actionTypes:t.map(e=>e.type)});this.doAll([r,...t])}else this.doAll(t)}execute(e){for(this._workList.push(e);this._workList.length>0;){if(this._iteration>=this._maxIterations)throw Error(`[ExecutionContext] Max iterations reached (${this._maxIterations}). Aborting to prevent infinite loop.`);let e=this._workList.shift();this._iteration++;let t=e.do(this);t&&t.length>0&&this._workList.unshift(...t)}}},Il=e=>String(e).padStart(2,`0`),Ll=e=>String(e).padStart(3,`0`);function Rl(e){return`${Il(e.getHours())}:${Il(e.getMinutes())}:${Il(e.getSeconds())}.${Ll(e.getMilliseconds())}`}function zl(e){return(e+` `).slice(0,5)}function Bl(e){return(e+` `.repeat(24)).slice(0,24)}function Vl(e){if(!e)return`─`.repeat(52);let t=` ${e} `,n=Math.max(0,Math.floor((52-t.length)/2)),r=Math.max(0,52-t.length-n);return`${`─`.repeat(n)}${t}${`─`.repeat(r)}`}var Hl=class{_console=console;_enabled=!1;_history=[];_maxHistory=500;EVENT_STYLES={BOOT:`color: #3b82f6; font-weight: bold`,PUSH:`color: #a855f7; font-weight: bold`,POP:`color: #64748b`,NEXT:`color: #b45309; font-weight: bold`,EVNT:`color: #a855f7; font-weight: bold`,OUT:`color: #16a34a; font-weight: bold`,MEM:`color: #f59e0b`,TIME:`color: #3b82f6; font-weight: bold`,HALT:`color: #ef4444; font-weight: bold`,WARN:`color: #f59e0b; font-weight: bold`,ERR:`color: #ef4444; font-weight: bold`};constructor(){if(typeof window<`u`){let e=window;this._enabled=!!e.__WOD_DEBUG__}}get enabled(){return this._enabled}enable(){this._enabled=!0,this.writeLine(`BOOT`,`runtime:ready`,`logging enabled`)}disable(){this.writeLine(`HALT`,`runtime:logger`,`logging disabled`),this._enabled=!1}getHistory(){return[...this._history]}clearHistory(){this._history=[]}logBoot(e){this._enabled&&this.writeLine(`BOOT`,`runtime:ready`,e)}logPush(e,t,n){if(!this._enabled)return;let r=this.getBehaviorNames(e),i=[`d${n??`?`} ${e.blockType??`block`}`,r.length>0?`behaviors [${r.join(`, `)}]`:void 0,t?`parent ${t.slice(0,8)}`:void 0].filter(Boolean).join(` · `);this.writeLine(`PUSH`,e.label||e.blockType||`Block`,i),this.addToHistory(`info`,`push`,`PUSH ${e.label}`,{key:e.key.toString(),parentKey:t,behaviors:r,sourceIds:e.sourceIds})}logPop(e,t,n){this._enabled&&(this.writeLine(`POP`,e.label||e.blockType||`Block`,`d${n??`?`}${t?` `+t:``}`),this.addToHistory(`info`,`pop`,`POP ${e.label}`,{key:e.key.toString(),reason:t}))}logNext(e,t){if(!this._enabled||t.length===0)return;let n=t.map(e=>e.type||e.constructor?.name||`Action`);this.writeLine(`NEXT`,e.label||`Block`,`${n.length} action(s): [${n.join(`, `)}]`),this.addToHistory(`info`,`next`,`NEXT ${e.label}`,{key:e.key.toString(),actions:n})}logEvent(e,t){if(!this._enabled||t.length===0)return;let n=t.map(e=>e.type||e.constructor?.name||`Action`);this.writeLine(`EVNT`,e.name,`${n.length} action(s): [${n.join(`, `)}]`),this.addToHistory(`info`,`event`,`EVENT ${e.name}`,{eventName:e.name,eventData:e.data,actions:n})}logOutput(e){if(!this._enabled||e.outputType!==`segment`&&e.outputType!==`milestone`)return;let t=e.text||this.outputSubject(e.metrics);t&&(this.writeLine(`OUT`,t,e.outputType),this.addToHistory(`info`,`output`,`OUT ${t}`,{outputType:e.outputType,label:t}))}outputSubject(e){if(e){for(let t of e)if(t.type===`label`)return t.image||(t.value==null?``:String(t.value))||void 0}}logMemoryUpdate(e,t,n){if(!this._enabled)return;let r=typeof n==`object`&&n?this.summarizeObject(n):n;this.writeLine(`MEM`,t,`[${e.slice(0,8)}] ${Ul(r)}`),this.addToHistory(`debug`,`memory`,`MEMORY ${t}`,{blockKey:e,memoryType:t,value:r})}logAction(e,t){if(!this._enabled)return;let n=e.type||e.constructor?.name||`Action`;this.writeLine(`EVNT`,n,`d${t}`)}logMessage(e,t,n,r){this._enabled&&(this.writeLine(e===`error`?`ERR`:e===`warn`?`WARN`:`EVNT`,t,n),this.addToHistory(e,t,n,r))}logAlways(e,t,n,r){this.writeLine(e===`error`?`ERR`:e===`warn`?`WARN`:`EVNT`,t,n),this.addToHistory(e,t,n,r)}logRule(e){this._enabled&&this._console.log(`%c${Vl(e)}`,`color: #94a3b8`)}writeLine(e,t,n){let r=Rl(new Date);this._console.log(`${r} %c${zl(e)}%c ${Bl(t)}${n?` `+n:``}`,this.EVENT_STYLES[e],`color: inherit`)}getBehaviorNames(e){let t=e.behaviors;return!t||!Array.isArray(t)?[]:t.map(e=>e.constructor?.name||`Behavior`)}summarizeObject(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?`[${r.length} items]`:typeof r==`object`&&r?`{...}`:r;return t}addToHistory(e,t,n,r){this._history.push({timestamp:new Date,level:e,category:t,message:n,data:r}),this._history.length>this._maxHistory&&(this._history=this._history.slice(-this._maxHistory))}};function Ul(e){try{return JSON.stringify(e)??``}catch{return String(e)}}var Wl=new Hl;typeof window<`u`&&(window.RuntimeLogger=Wl);var Gl=class{_outputStatements=[];_outputListeners=new Set;_analyticsEngine=null;_analyticsFinalized=!1;_liveAnalytics=[];_clock=null;_stack=null;_script=null;attach(e){this._clock=e.clock,this._stack=e.stack,this._script=e.script}_requireClock(){if(!this._clock)throw Error(`[OutputEmitter] emission helper called before attach() — clock is not wired`);return this._clock}add(e){if(e.outputType===`system`&&this._outputListeners.size===0)return;let t=this._analyticsEngine?this._analyticsEngine.run(e):e;this._propagateSourceLine(t),Wl.logOutput(t),this._outputStatements.push(t);for(let e of this._outputListeners)try{e(t)}catch(e){console.error(`[OutputEmitter] Listener error:`,e)}}subscribe(e){this._outputListeners.add(e);let t=[...this._outputStatements];return t.length>0&&setTimeout(()=>{if(this._outputListeners.has(e))for(let n of t)e(n)},0),()=>this._outputListeners.delete(e)}getAll(){return[...this._outputStatements]}hasListeners(){return this._outputListeners.size>0}setAnalyticsEngine(e){this._analyticsEngine=e,e.setLiveOutputEmitter(e=>this.emitLiveAnalytics(e))}finalizeAnalytics(){if(!this._analyticsEngine||this._analyticsFinalized)return[];this._analyticsFinalized=!0;let e=this._analyticsEngine.finalize(),t=e.length>0?e:this._liveAnalytics;for(let e of t){this._outputStatements.push(e);for(let t of this._outputListeners)try{t(e)}catch(e){console.error(`[OutputEmitter] Finalize listener error:`,e)}}return this._liveAnalytics=[],t}emitLiveAnalytics(e){this._liveAnalytics=e;for(let t of e)for(let e of this._outputListeners)try{e(t)}catch(e){console.error(`[OutputEmitter] Live analytics listener error:`,e)}}getLiveAnalytics(){return[...this._liveAnalytics]}dispose(){this._outputStatements=[],this._outputListeners.clear(),this._analyticsFinalized=!1,this._liveAnalytics=[]}emitLoad(){if(!this._script)throw Error(`[OutputEmitter] emitLoad() called before attach() — script is not wired`);let e=this._script,t=this._requireClock().currentDate;for(let n of e.statements){let r=e.source.substring(n.meta.startOffset,n.meta.endOffset+1),i=la.from(n.metrics,n.id);i.add({type:q.Label,image:r||`Statement`,value:r,origin:`runtime`,timestamp:t});let a=0,o=n.parent,s=new Set;for(;o!==void 0&&!s.has(o);){s.add(o);let t=e.getId(o);if(t)a++,o=t.parent;else break}this.add(new fa({outputType:`load`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:`root`,sourceStatementId:n.id,stackLevel:a,metrics:i}))}}emitStackEvent(e){if(!this.hasListeners())return;let t=this._requireClock().currentDate,n=e.block,r=this._stack?.blocks??[],i={event:e.type,blockKey:n.key.toString(),blockLabel:n.label,actionType:e.type===`push`?`push-block`:`pop-block`};if(e.type===`push`){let e=r.length>1?r[1]:void 0;e&&(i.parentKey=e.key.toString())}else i.completionReason=n.completionReason??`normal`;let a={type:q.System,image:e.type===`push`?`push: ${n.label??n.blockType??`Block`} [${n.key.toString().slice(0,8)}]`:`pop: ${n.label??n.blockType??`Block`} [${n.key.toString().slice(0,8)}] reason=${n.completionReason??`normal`}`,value:i,origin:`runtime`,timestamp:t};this.add(new fa({outputType:`system`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:n.key.toString(),stackLevel:e.depth,metrics:la.empty(n.key.toString()).add(a)}))}emitSegmentFromResultMemory(e,t){let n=e.getMemoryByTag(`metric:result`),r=e.getMemoryByTag(`metric:display`);if(n.length===0)return;let i=this._requireClock().currentDate.getTime();for(let a=0;a<n.length;a++){let o=la.from(n[a].metrics,e.key.toString()),s=la.from(r[a]?.metrics,e.key.toString()),c=la.empty(e.key.toString()).add(...s.toArray()).add(...o.toArray());if(c.length===0)continue;let l=new Cl(e.executionTiming?.startTime?.getTime()??i,i);this.add(new fa({outputType:`segment`,completionReason:e.completionReason,timeSpan:l,sourceBlockKey:e.key.toString(),sourceStatementId:e.sourceIds?.[a]??e.sourceIds?.[0],stackLevel:t,metrics:c}))}}emitRuntimeEvent(e){let t=this._requireClock().currentDate,n=this._stack,r=n?.current?.key.toString()??`root`,i=la.empty(r).add({type:q.System,image:`event: ${e.name}`,value:{name:e.name,data:e.data,blockKey:r},origin:`runtime`,timestamp:t});this.add(new fa({outputType:`event`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:r,stackLevel:n?.count??0,metrics:i}))}emitCompilerBlock(e){let t=this._requireClock().currentDate,n=this._stack?.count??0,r=la.empty(e.key.toString()).add({type:q.Label,image:`Behaviors: ${e.behaviors.map(e=>e.constructor.name).join(`, `)}`,value:e.behaviors.map(e=>e.constructor.name),origin:`runtime`,timestamp:t});this.add(new fa({outputType:`compiler`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:e.key.toString(),stackLevel:n,metrics:r}))}_propagateSourceLine(e){if(e.sourceStatementId===void 0||e.line!==void 0)return;let t=this._script?.getId(e.sourceStatementId);t&&(e.line=t.line,e.text??=t.text,e.dialect??=t.dialect)}},Kl=class{_stackObservers=new Set;_logger;constructor(e){this._logger=e}subscribeToStack(e){return this._stackObservers.add(e),()=>{this._stackObservers.delete(e)}}emitStack(e){if(this._stackObservers.size!==0)for(let t of this._stackObservers)try{t(e)}catch(e){this._logger?.error?.(`[RuntimeObservers] Stack observer error:`,e)}}hasStackObserver(e){return this._stackObservers.has(e)}emitSettled(e,t,n){if(this._stackObservers.size===0||e.length===0)return;let r={type:`initial`,blocks:e,depth:t,clockTime:n};this.emitStack(r)}dispose(){this._stackObservers.clear()}get stackObserverCount(){return this._stackObservers.size}},ql=class{block;options;_type=`push-block`;constructor(e,t={}){this.block=e,this.options=t}get type(){return this._type}set type(e){throw Error(`Cannot modify readonly property type`)}do(e){if(!e.stack)return[];try{let t=this.options.startTime,n=this.options.clock??e.clock;!t&&n?.isRunning&&(t=n.currentDate);let r=t?{...this.options,startTime:t}:{...this.options},i=this.block;t&&(i.executionTiming={...i.executionTiming??{},startTime:t}),e.stack.push(this.block);let a=this.block.mount(e,r),o=e.stack.blocks.length>1?e.stack.blocks[1]?.key.toString():void 0;return Wl.logPush(this.block,o,e.stack.blocks.length),a}catch(t){let n=e;return typeof n.setError==`function`&&n.setError(t),[]}}},Jl=class{options;type=`pop-block`;constructor(e={}){this.options=e}do(e){let t=e.stack.current;if(!t)return[];let n=this.options.createdAt??e.clock.currentDate,r={...this.options,createdAt:n};t.executionTiming&&(t.executionTiming.createdAt=n),!t.isComplete&&typeof t.markComplete==`function`&&(t.markComplete(`forced-pop`),Wl.logPop(t,`forced-pop (incomplete block popped without next)`,e.stack.blocks.length));let i=t.unmount(e,r)??[],a=e.stack.pop();return a?(a.dispose(e),a.context?.release?.(),a.completionReason!==`forced-pop`&&Wl.logPop(a,a.completionReason,e.stack.blocks.length+1),e.stack.current?[...i,new Dl(r,e.nowProvider)]:i):[]}},Yl=class{script;eventBus;clock;stack;jit;errors=[];options;analyticsContext;_output=new Gl;_observers;_activeContext=null;_now;_stackSubscriptionUnsub=null;_nextHandlerUnsub=null;get nowProvider(){return this._now}_abortHandlerUnsub=null;constructor(e,t,n,r={},i=El){this.script=e,this.options={...Sl,...r},this._observers=new Kl(this.options.logger),this.stack=n.stack,this.clock=n.clock,this.eventBus=n.eventBus,this._now=i,this._nextHandlerUnsub=this.eventBus.register(`next`,new jl(`runtime-next-handler`),`runtime`,{scope:`global`}),this._abortHandlerUnsub=this.eventBus.register(`abort`,new Nl(`runtime-abort-handler`),`runtime`,{scope:`global`}),this.jit=t,this._output.attach({clock:this.clock,stack:this.stack,script:this.script}),this._stackSubscriptionUnsub=this.stack.subscribe(e=>{e.type===`pop`&&this._output.emitSegmentFromResultMemory(e.block,e.depth),(e.type===`push`||e.type===`pop`)&&this._output.emitStackEvent(e);let t={type:e.type===`initial`?`initial`:e.type,blocks:(e.type,e.blocks),affectedBlock:e.type===`initial`?void 0:e.block,depth:e.type===`initial`?e.blocks.length:e.depth,clockTime:this.clock.currentDate};this._observers.emitStack(t)}),this.clock.start(),this._output.emitLoad(),Wl.logBoot(`statements ${this.script.statements.length}`)}do(e){if(this._activeContext){this._activeContext.do(e);return}this._activeContext=new Fl(this,this.options.maxActionDepth??20);try{this._activeContext.execute(e)}finally{this._activeContext=null,this._notifyStackSettled()}}_buildInitialSnapshot(){let e=this.stack.blocks;return{type:`initial`,blocks:e,depth:e.length,clockTime:this.clock.currentDate}}_notifyStackSettled(){this._observers.emitSettled(this.stack.blocks,this.stack.count,this.clock.currentDate)}doAll(e){if(e.length!==0){if(this._activeContext){this._activeContext.doAll(e);return}this.do({type:`composite-doAll`,do:()=>e})}}handle(e){let t=this.eventBus.dispatch(e,this);(e.name!==`tick`||t.length>0)&&this._output.emitRuntimeEvent(e),t.length!==0&&this.doAll(t)}subscribeToOutput(e){return this._output.subscribe(e)}getOutputStatements(){return this._output.getAll()}getLiveAnalytics(){return this._output.getLiveAnalytics()}addOutput(e){this._output.add(e)}setAnalyticsEngine(e){this._output.setAnalyticsEngine(e)}finalizeAnalytics(){return this._output.finalizeAnalytics()}subscribeToStack(e){let t=this._observers.subscribeToStack(e);return setTimeout(()=>{if(this._observers.hasStackObserver(e))try{e(this._buildInitialSnapshot())}catch(e){console.error(`[RT] Stack observer error (initial):`,e)}},0),t}dispose(){for(this.clock.stop();this.stack.count>0;){let e=this.stack.current;if(e){try{e.unmount(this)}catch{}this.stack.pop();try{e.dispose(this)}catch{}}else this.stack.pop()}this._nextHandlerUnsub&&=(this._nextHandlerUnsub(),null),this._abortHandlerUnsub&&=(this._abortHandlerUnsub(),null),this._output.dispose(),this._stackSubscriptionUnsub&&=(this._stackSubscriptionUnsub(),null),this._observers.dispose(),this.eventBus.dispose()}pushBlock(e,t){let n=this.stack.current;this.options.hooks?.onBeforePush?.(e,n),this._output.emitCompilerBlock(e);let r=this.options.wrapper?.wrap?.(e,n)??e;this.do(new ql(r,t)),this.options.logger?.debug?.(`runtime.pushBlock`,{blockKey:e.key.toString(),parentKey:n?.key.toString()}),this.options.hooks?.onAfterPush?.(r,n)}popBlock(e){let t=this.stack.current;t&&(this.options.hooks?.onBeforePop?.(t),this.do(new Jl(e)),this.options.wrapper?.cleanup?.(t),this.options.hooks?.unregisterByOwner?.(t.key.toString()),this.options.logger?.debug?.(`runtime.popBlock`,{blockKey:t.key.toString(),stackDepth:this.stack.count}),this.options.hooks?.onAfterPop?.(t))}},Xl=class{_memory;ownerId;type;visibility;_logger;id=C();_subscriptions=[];constructor(e,t,n,r=`private`,i){this._memory=e,this.ownerId=t,this.type=n,this.visibility=r,this._logger=i}value(){return this.get()}get subscriptions(){return this._subscriptions}get(){return this._memory.get(this)}set(e){this._memory.set(this,e)}subscribe(e,t){let n=C(),r={id:n,callback:e,memoryId:this.id,createdAt:new Date};return this._subscriptions.push(r),t?.immediate&&e(this.get(),void 0),()=>this.unsubscribe(n)}unsubscribe(e){let t=this._subscriptions.findIndex(t=>t.id===e);t>=0&&this._subscriptions.splice(t,1)}hasSubscribers(){return this._subscriptions.length>0}notifySubscribers(e,t){for(let n of this._subscriptions)try{n.callback(e,t)}catch(e){this._logger?.error?.(`Error in memory subscription callback:`,e)}}},Zl=class{_references=[];allocate(e,t,n,r=`private`){let i=new Xl(this,t,e,r);return this._references.push({ref:i,data:n}),i}get(e){return this._references.find(t=>t.ref.id===e.id)?.data??void 0}set(e,t){let n=this._references.find(t=>t.ref.id===e.id);if(!n)throw Error(`Invalid memory reference: ${e.id}`);let r=n.data;n.data=t,e.hasSubscribers()&&e.notifySubscribers(t,r)}search(e){return this._references.map(e=>e.ref).filter(t=>!(e.id!==null&&e.id!==void 0&&e.id!==t.id||e.ownerId!==null&&e.ownerId!==void 0&&e.ownerId!==t.ownerId||e.type!==null&&e.type!==void 0&&e.type!==t.type||e.visibility!==null&&e.visibility!==void 0&&e.visibility!==t.visibility))}release(e){let t=this._references.findIndex(t=>t.ref.id===e.id);if(t>=0){let e=this._references[t],n=e.data,r=e.ref;r instanceof Xl&&r.hasSubscribers()&&r.notifySubscribers(void 0,n),this._references.splice(t,1)}}},Ql=function(e){return e.DISPLAY_STACK_STATE=`displaystack`,e.ACTION_STACK_STATE=`actions`,e.TIMER_PREFIX=`timer:`,e.HANDLER_PREFIX=`handler:`,e.METRIC_REPS=`metric:reps`,e.ANCHOR=`anchor`,e}({}),$l=class{timestamp;constructor(e=El){this.timestamp=e.now()}},eu=class extends $l{name=`memory:allocate`;data;constructor(e,t,n=El){super(n),this.data={ref:e,value:t}}},tu=class extends $l{name=`memory:set`;data;constructor(e,t,n,r=El){super(r),this.data={ref:e,value:t,oldValue:n}}},nu=class extends $l{name=`memory:release`;data;constructor(e,t,n=El){super(n),this.data={ref:e,lastValue:t}}},ru=class{runtime;ownerId;exerciseId;_references=[];_released=!1;_memory;constructor(e,t,n=``,r=[],i){this.runtime=e,this.ownerId=t,this.exerciseId=n,this._references=[...r],this._memory=i??new Zl}get references(){return[...this._references]}allocate(e,t,n=`private`){if(this._released)throw Error(`Cannot allocate on released context (ownerId: ${this.ownerId})`);let r=e,i=this._memory.allocate(r,this.ownerId,t,n);return this._references.push(i),this.runtime.eventBus.dispatch(new eu(i,t,this.runtime.nowProvider),this.runtime),i}get(e){let t=e;return this._references.find(e=>e.type===t)}getAll(e){let t=e;return this._references.filter(e=>e.type===t)}set(e,t){if(this._released)throw Error(`Cannot set on released context (ownerId: ${this.ownerId})`);let n=e.get();this._memory.set(e,t),this.runtime.eventBus.dispatch(new tu(e,t,n,this.runtime.nowProvider),this.runtime)}release(){if(!this._released){for(let e of this._references){let t=e.value();this._memory.release(e),this.runtime.eventBus.dispatch(new nu(e,t,this.runtime.nowProvider),this.runtime)}this._references=[],this._released=!0}}isReleased(){return this._released}getOrCreateAnchor(e){if(this._released)throw Error(`Cannot access anchor on released context (ownerId: ${this.ownerId})`);let t;for(let n of this.runtime.stack.blocks){let r=n.context.references.find(t=>t.id===e&&t.type===Ql.ANCHOR);if(r){t=r;break}}if(t)return this._references.find(e=>e.id===t.id)||this._references.push(t),t;let n=this._memory.allocate(Ql.ANCHOR,this.ownerId,void 0,`public`);return n.id=e,this._references.push(n),n}},iu=class{tag;_listeners=new Set;_metrics;_isDisposed=!1;constructor(e,t=la.empty()){this.tag=e,this._metrics=la.from(t,e)}get metrics(){return this._metrics}update(e){if(this._isDisposed){console.warn(`Attempted to update disposed MemoryLocation with tag '${this.tag}'`);return}let t=this._metrics;this._metrics=la.from(e,this.tag);for(let e of this._listeners)e(this._metrics,t)}subscribe(e){return this._isDisposed?(console.warn(`Attempted to subscribe to disposed MemoryLocation with tag '${this.tag}'`),()=>{}):(this._listeners.add(e),()=>this._listeners.delete(e))}dispose(){if(this._isDisposed)return;this._isDisposed=!0;let e=this._metrics;this._metrics=la.empty(this.tag);for(let t of this._listeners)t(this._metrics,e);this._listeners.clear()}},au=class{block;clock;stackLevel;runtime;subscriptions=[];_capabilities;constructor(e,t,n,r,i){this.block=e,this.clock=t,this.stackLevel=n,this.runtime=r,this._capabilities=i??new Set}get nowProvider(){return this.runtime.nowProvider}subscribe(e,t,n){let r=this,i={id:`behavior-${this.block.key.toString()}-${e}-${Date.now()}`,name:`BehaviorHandler-${this.block.label}-${e}`,handler:(e,n)=>t(e,Object.create(r,{clock:{value:n.clock,enumerable:!0,configurable:!0}}))},a=this.runtime.eventBus.register(e,i,this.block.key.toString(),{scope:n?.scope??`active`});return this.subscriptions.push({eventType:e,unsubscribe:a}),a}emitEvent(e){this.runtime.handle(e)}emitOutput(e,t,n){let r=this.clock.currentDate,i=this.block.getMemoryByTag(`time`),a=r.getTime(),o=r.getTime(),s=[];if(i.length>0){let e=i[0].metrics;if(e.length>0){let t=e[0].value;t?.spans&&t.spans.length>0&&(s=[...t.spans],a=s[0].started)}}let c=la.from(t,this.block.key.toString());if(c.length===0){let e=this.block.getMemoryByTag(`metric:display`);e.length>0&&(c=e[0].metrics.clone(this.block.key.toString()))}let l=c.map(e=>({...e,sourceBlockKey:e.sourceBlockKey??this.block.key.toString(),timestamp:e.timestamp??r})),u=new fa({outputType:e,timeSpan:new Cl(a,o),spans:s.length>0?s:void 0,sourceBlockKey:this.block.key.toString(),sourceStatementId:this.block.sourceIds?.[0],stackLevel:this.stackLevel,metrics:l,completionReason:n?.completionReason});this.addOutputToRuntime(u)}addOutputToRuntime(e){this.runtime.addOutput(e)}pushMemory(e,t){let n=new iu(e,t);return this.block.pushMemory(n),n}getMemoryByTag(e){return this.block.getMemoryByTag(e)}updateMemory(e,t){let n=this.block.getMemoryByTag(e);n.length>0&&n[0].update(t)}declareCapability(e){this._capabilities.add(e)}hasCapability(e){return this._capabilities.has(e)}getCapabilities(){return this._capabilities}markComplete(e){this.block.markComplete(e)}dispose(){for(let{unsubscribe:e}of this.subscriptions)try{e()}catch(e){this.runtime.options.logger?.error?.(`[BehaviorContext] Unsubscribe error:`,e)}this.subscriptions=[]}},hee=new Set([`metric:display`]),gee=new Set([`metric:result`]),_ee=new Set([`metric:promote`,`metric:rep-target`]),vee=new Set([`metric:tracked`,`metric:label`,`metric:next`]);function yee(e){if(hee.has(e))return`display`;if(gee.has(e))return`result`;if(_ee.has(e))return`promote`;if(vee.has(e)||e.startsWith(`metric:`))return`private`}var ou={display:`Display`,result:`Result`,promote:`Promote`,private:`Private`},su=class{behaviors=[];key;blockType;context;sourceIds;tagComposition;_memory=[];get label(){for(let e of this._memory)for(let t of e.metrics)if(t.type===q.Label)return t.image||t.value?.toString()||this.blockType||`Block`;return this.blockType||`Block`}_behaviorContext;executionTiming={};_isComplete=!1;_completionReason;_eventUnsubscribers=[];_runtime;constructor(e){let{runtime:t,sourceIds:n=[],behaviors:r=[],context:i,key:a,blockType:o,label:s,metrics:c,tagComposition:l}=e;if(this._runtime=t,this.sourceIds=n,this.behaviors=r,this.key=a??new pa,this.blockType=o,this.tagComposition=l,this.context=i??new ru(t,this.key.toString()),s&&this._memory.push(new iu(`metric:label`,[{type:q.Label,image:s,origin:`compiler`,value:s}])),c)for(let e of c)this._memory.push(new iu(`metric:display`,e))}pushMemory(e){this._memory.push(e)}mergeHints(e){if(!e||Object.keys(e).length===0)return;let t=this._memory.find(e=>e.tag===`metric:hint`),n=Object.entries(e).map(([e,t])=>({type:q.Hint,value:e,image:e,origin:`compiler`,timestamp:new Date}));if(t){let e=new Set(n.map(e=>e.value)),r=t.metrics.toArray().filter(t=>!(t.type===q.Hint&&e.has(t.value)));t.update([...r,...n])}else this._memory.push(new iu(`metric:hint`,n))}getMemoryByTag(e){return this._memory.filter(t=>t.tag===e)}getAllMemory(){return[...this._memory]}getMetricMemoryByVisibility(e){return this._memory.filter(t=>yee(t.tag)===e)}registerDefaultHandler(){}mount(e,t){this._runtime=e;let n=t?.clock??e.clock;this.executionTiming.startTime=t?.startTime??n.currentDate,this.registerDefaultHandler();let r=Math.max(0,e.stack.count-1);this._behaviorContext=new au(this,n,r,e);let i=[];for(let e of this.behaviors)if(e.onMount){let t=e.onMount(this._behaviorContext);t&&i.push(...t)}return i}inspectNext(e,t){if(!this._behaviorContext)return{complete:!1,actions:[]};let n=t?.clock??this._behaviorContext.clock,r=new au(this,n,this._behaviorContext.stackLevel,e,this._behaviorContext.getCapabilities()),i=this._isComplete,a=this._completionReason;for(let e of this.behaviors){let t=e;typeof t.prepareForNextCycle==`function`&&t.prepareForNextCycle()}let o=[];for(let e of this.behaviors)if(e.onNext){let t=e.onNext(r);t&&o.push(...t)}r.dispose(),this._isComplete&&!o.some(e=>e.type===`pop-block`)&&o.push(new Jl);let s={complete:this._isComplete,reason:this._completionReason,actions:o};return this._isComplete=i,this._completionReason=a,s}next(e,t){if(!this._behaviorContext)return Wl.logAlways(`warn`,`RuntimeBlock`,`next() called before mount()`),[];let n=t?.clock??this._behaviorContext.clock;this.emitNextSystemOutput(e,n);let r=this.inspectNext(e,t);return r.complete&&!this._isComplete&&this.markComplete(r.reason),Wl.logNext(this,[...r.actions]),r.actions}unmount(e,t){let n=t?.clock??e.clock;this.executionTiming.endTime=t?.createdAt??n.currentDate;let r=[],i=new au(this,n,this._behaviorContext?.stackLevel??0,e,this._behaviorContext?.getCapabilities());for(let e of this.behaviors)if(e.onUnmount){let t=e.onUnmount(i);t&&r.push(...t)}i.dispose();let a=e.eventBus.dispatch({name:`unmount`,timestamp:e.clock.currentDate,data:{blockKey:this.key.toString()}},e);a.length>0&&r.push(...a);for(let e of this._eventUnsubscribers)try{e()}catch(e){Wl.logAlways(`error`,`RuntimeBlock`,`Error unsubscribing event handler`,{error:e})}return this._eventUnsubscribers=[],this._behaviorContext&&=(this._behaviorContext.dispose(),void 0),r}dispose(e){let t=this._behaviorContext??new au(this,e.clock,0,e);for(let e of this.behaviors)e.onDispose&&e.onDispose(t);!this._behaviorContext&&t&&t.dispose();for(let e of this._memory)e.dispose();this._memory=[]}get isComplete(){return this._isComplete}get completionReason(){return this._completionReason}markComplete(e){this._isComplete=!0,this._completionReason=e}getBehavior(e){return this.behaviors.find(t=>t instanceof e)}emitNextSystemOutput(e,t){let n=t.currentDate,r={event:`next`,blockKey:this.key.toString(),blockLabel:this.label,actionType:`next`},i={type:q.System,image:`next: ${this.label??this.blockType??`Block`} [${this.key.toString().slice(0,8)}]`,value:r,origin:`runtime`,timestamp:n},a=new fa({outputType:`system`,timeSpan:new Cl(n.getTime(),n.getTime()),sourceBlockKey:this.key.toString(),stackLevel:e.stack.count,metrics:[i]});e.addOutput(a)}},bee=class{_blocks=[];_listeners=new Set;get blocks(){return[...this._blocks].reverse()}get count(){return this._blocks.length}get current(){if(this._blocks.length!==0)return this._blocks[this._blocks.length-1]}get keys(){return this.blocks.map(e=>e.key)}push(e){this._blocks.push(e),this.notify({type:`push`,block:e,depth:this._blocks.length,blocks:this.blocks})}pop(){let e=this._blocks.pop();return e&&this.notify({type:`pop`,block:e,depth:this._blocks.length,blocks:this.blocks}),e}clear(){for(;this._blocks.length>0;)this.pop()}subscribe(e){return this._listeners.add(e),e({type:`initial`,blocks:this.blocks}),()=>{this._listeners.delete(e)}}notify(e){for(let t of this._listeners)try{t(e)}catch(e){console.error(`Error in stack listener:`,e)}}};function cu(){if(typeof window<`u`){let e=window.__chromecast_senderClockTimeMs;if(typeof e==`function`)try{let t=e();if(Number.isFinite(t))return t}catch{}}return Date.now()}var xee=class{completionTime;wasComplete=!1;onMount(e){return[]}onNext(e){if(e.block.isComplete&&!this.wasComplete&&!this.completionTime){this.completionTime=new Date(e.clock.currentDate),this.wasComplete=!0;let t={type:q.SystemTime,image:this.completionTime.toISOString(),origin:`runtime`,value:{createdAt:this.completionTime.getTime(),timestamp:this.completionTime},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};e.pushMemory(`completion`,[t])}return[]}onUnmount(e){return[]}onDispose(e){}getCompletionTime(){return this.completionTime}},lu=`time`;function uu(e){return[new Cl(e)]}function du(e,t){return e.map((n,r)=>r===e.length-1&&n.ended===void 0?new Cl(n.started,t):n)}function fu(e,t){return[...e,new Cl(t)]}function pu(e){return e.getMemoryByTag(lu)[0]?.metrics[0]?.value}function mu(e,t){let n=e.getMemoryByTag(lu)[0]?.metrics[0],r=n?.value;if(!r||!n)return!1;let i=t(r.spans,e.clock.currentDate.getTime());return e.updateMemory(lu,[{...n,value:{...r,spans:i}}]),!0}var See=class{onMount(e){let t=e.clock.currentDate.getTime(),n=e.block.label,r={type:q.Time,image:`0:00`,origin:`runtime`,value:{spans:uu(t),direction:`up`,durationMs:void 0,label:n,role:`hidden`},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};return e.pushMemory(`time`,[r]),[]}onNext(e){return[]}onUnmount(e){let t=pu(e);return!t||t.spans.length===0||mu(e,du),[]}onDispose(e){}},hu=class{config;constructor(e={}){this.config=e}subscriptions=[];isPaused=!1;onMount(e){let t=e.clock.currentDate.getTime(),n=this.config.label??e.block.label,r=this.config.role===`hidden`?`auto`:this.config.role??`primary`;return e.pushMemory(`time`,[this.createFragment(e,{spans:uu(t),direction:`up`,durationMs:void 0,label:n,role:r})]),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||mu(t,du)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&mu(t,fu)&&(this.isPaused=!1),[]))),[]}onNext(e){return[]}onUnmount(e){return mu(e,du),[]}onDispose(e){for(let e of this.subscriptions)try{e()}catch{}this.subscriptions.length=0}createFragment(e,t){return{type:q.Time,image:`0:00`,origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}},gu=class{targetBlockKey;type=`clear-children`;constructor(e){this.targetBlockKey=e}do(e){let t=[],n=0;for(;n<20;){let r=e.stack.current;if(!r||r.key.toString()===this.targetBlockKey)break;let i=new Jl().do(e);for(let e of i)e.type!==`next`&&t.push(e);n++}return n>=20&&e.options.logger?.error?.(`[ClearChildrenAction] Max iterations reached, possible infinite loop`,Error(`Exceeded 20 pop iterations for target ${this.targetBlockKey}`)),e.stack.current?.key.toString()===this.targetBlockKey&&t.push(new Dl(void 0,e.nowProvider)),t}};function _u(e,t){let n=0;for(let r of e.spans){let e=r.ended??t;n+=e-r.started}return n}function vu(e){let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}var yu=class{current;total;sourceBlockKey;timestamp;type=q.CurrentRound;origin=`tracked`;value;image;constructor(e,t,n,r,i){this.current=e,this.total=t,this.sourceBlockKey=n,this.timestamp=r,this.value=e,this.image=i??(t===void 0?`Round ${e}`:`Round ${e} of ${t}`)}},bu=class{config;constructor(e){this.config=e}subscriptions=[];isPaused=!1;onMount(e){let t=e.clock.currentDate.getTime(),n=this.config.label??e.block.label,r=this.config.role===`hidden`?`auto`:this.config.role??`primary`,i=this.config.mode??`complete-block`;return e.pushMemory(`time`,[this.createFragment(e,{spans:uu(t),direction:`down`,durationMs:this.config.durationMs,label:n,role:r})]),this.config.durationMs<=0?(this.handleExpiry(e,i),[new gu(e.block.key.toString())]):(this.subscriptions.push(e.subscribe(`tick`,(e,t)=>i===`complete-block`&&t.block.isComplete||!this.hasExpired(t)?[]:(this.handleExpiry(t,i),[new gu(t.block.key.toString())]),{scope:`bubble`})),this.subscriptions.push(e.subscribe(`timer:reset`,(e,t)=>(i===`reset-interval`&&mu(t,(e,t)=>uu(t)),[]))),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||mu(t,du)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&mu(t,fu)&&(this.isPaused=!1),[]))),[])}onNext(e){if((this.config.mode??`complete-block`)===`complete-block`&&!e.block.isComplete&&this.hasExpired(e))return e.markComplete(`timer-expired`),[new Jl,new gu(e.block.key.toString())];if(this.config.required&&!e.block.isComplete)return e.emitEvent({name:`timer:skip-attempt`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),[];if(e.hasCapability(`childSelection`)||!this.config.restBlockFactory)return[];let t=pu(e);if(!t||t.direction!==`down`||!t.durationMs)return[];let n=this.getRemainingCountdownMs(e);return n>1e3?this.config.restBlockFactory(n,`Rest`):[]}onUnmount(e){return mu(e,du),[]}onDispose(e){for(let e of this.subscriptions)try{e()}catch{}this.subscriptions.length=0}handleExpiry(e,t){if(e.emitEvent({name:`timer:complete`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),t===`complete-block`)e.markComplete(`timer-expired`);else{if(mu(e,(e,t)=>uu(t)),e.hasCapability(`childSelection`))return;let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t){let n=new yu(t.current+1,t.total,e.block.key.toString(),e.clock.currentDate);e.updateMemory(`round`,[n])}let n=e.getMemoryByTag(`children:status`)[0],r={childIndex:0,totalChildren:n?.metrics[0]?.value?.totalChildren??0,allExecuted:!1,allCompleted:!1};n?.metrics[0]?e.updateMemory(`children:status`,[{...n.metrics[0],value:r}]):e.pushMemory(`children:status`,[{type:`status`,image:``,origin:`runtime`,value:r}])}}hasExpired(e){let t=pu(e);return!t||t.direction!==`down`||t.durationMs===void 0?!1:_u(t,e.nowProvider.nowMs())>=t.durationMs}getRemainingCountdownMs(e){let t=pu(e);if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=_u(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}createFragment(e,t){return{type:q.Time,image:xu(t.durationMs),origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}};function xu(e){if(!e||e===0)return`0:00`;let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}:${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`:`${r}:${i.toString().padStart(2,`0`)}`}var Su=class{config;_repScheme;_lastPromotedRound;constructor(e){this.config=e,this._repScheme=[...e.repScheme??[]]}get repScheme(){return this._repScheme}getRepsForRound(e){if(this._repScheme.length===0)return;let t=(e-1)%this._repScheme.length;return this._repScheme[t]}getRepsForCurrentRound(){return this._lastPromotedRound===void 0?this._repScheme[0]:this.getRepsForRound(this._lastPromotedRound)}getPromotedFragments(e,t){let n=la.empty(t.key.toString());if(this._repScheme.length>0){let r=t.getMemoryByTag(`round`)[0]?.metrics[0]?.current??1,i=this.getRepsForRound(r);i!==void 0&&n.add({type:q.Rep,image:i.toString(),origin:`compiler`,value:i,sourceBlockKey:t.key.toString(),timestamp:e.clock.currentDate})}for(let e of this.config.promotions){let r=this.findSourceFragmentInBlock(t,e);r&&n.add({...r,origin:e.origin??`compiler`})}return n}onMount(e){if(this._repScheme.length>0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0]?.current??1;this.promoteRepScheme(e,t)}return this.promoteFragments(e,this.config.promotions),[]}onNext(e){if(this._repScheme.length>0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];t&&t.current!==this._lastPromotedRound&&this.promoteRepScheme(e,t.current)}let t=this.config.promotions.filter(e=>e.enableDynamicUpdates);return this.promoteFragments(e,t),[]}onUnmount(e){return[]}onDispose(e){}promoteFragments(e,t){for(let n of t){let t=this.findSourceFragment(e,n);if(!t)continue;let r={...t,origin:n.origin??`runtime`};this.upsertPromotedFragment(e,r)}}promoteRepScheme(e,t){let n=this.getRepsForRound(t);if(n===void 0)return;this._lastPromotedRound=t;let r={type:q.Rep,image:n.toString(),origin:`runtime`,value:n,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};e.block.getMemoryByTag(`metric:rep-target`).length>0?e.updateMemory(`metric:rep-target`,[r]):e.pushMemory(`metric:rep-target`,[r])}findSourceFragment(e,t){return this.findSourceFragmentInBlock(e.block,t)}findSourceFragmentInBlock(e,t){let n=e.getAllMemory();for(let e of n){if(e.tag===`metric:promote`||e.tag===`metric:rep-target`||t.sourceTag&&e.tag!==t.sourceTag)continue;let n=e.metrics.find(e=>e.type===t.metricType);if(n)return n}}upsertPromotedFragment(e,t){let n=e.block.getMemoryByTag(`metric:promote`);if(n.length===0){e.pushMemory(`metric:promote`,[t]);return}let r=n[0].metrics.filter(e=>e.type!==t.type);e.updateMemory(`metric:promote`,[...r,t])}},Cu=class{config;unsubscribers=[];constructor(e){this.config={mode:e.mode,onNext:e.onNext??e.mode===`immediate`,onEvents:e.onEvents??[]}}onMount(e){if(this.config.mode!==`immediate`)return[];for(let t of this.config.onEvents){let n=e.subscribe(t,(e,t)=>(t.markComplete(`event:${e.name}`),[new Jl]));this.unsubscribers.push(n)}return[]}onNext(e){return this.config.mode===`deferred`?e.block.isComplete?[new Jl]:[]:this.config.onNext?(e.block.isComplete||e.markComplete(`user-advance`),[new Jl]):[]}onUnmount(e){return[]}onDispose(e){for(let e of this.unsubscribers)e();this.unsubscribers=[]}},wu=class{config;constructor(e={}){this.config=e}onMount(e){let t=this.createStaticLabels(e),n=this.createRoundLabel(e),r=t.clone();return n&&r.add(n),r.length>0&&e.pushMemory(`display`,r.toArray()),[]}onNext(e){let t=this.createRoundLabel(e);if(!t)return[];let n=e.block.getMemoryByTag(`display`);if(n.length===0)return e.pushMemory(`display`,[t]),[];let r=n[0].metrics.filter(e=>!this.isRoundRoleFragment(e));return e.updateMemory(`display`,[...r,t]),[]}onUnmount(e){return[]}onDispose(e){}createStaticLabels(e){let t=this.config.label??e.block.label,n=this.config.subtitle,r=this.config.actionDisplay,i=la.empty(e.block.key.toString());return t&&i.add(this.createTextMetric(e,t,`label`)),n&&i.add(this.createTextMetric(e,n,`subtitle`)),r&&i.add(this.createTextMetric(e,r,`action`)),i}createRoundLabel(e){if(this.config.showRoundDisplay===!1)return;let t=e.block.getMemoryByTag(`round`)[0];if(!t||t.metrics.length===0)return;let n=t.metrics[0];if(!n||typeof n.current!=`number`)return;let r=this.formatRound(n.current,n.total);return this.createTextMetric(e,r,`round`)}createTextMetric(e,t,n){return{type:q.Text,image:t,origin:`runtime`,value:{text:t,role:n},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}formatRound(e,t){return this.config.roundFormat?this.config.roundFormat(e,t):typeof t==`number`?`Round ${e} of ${t}`:`Round ${e}`}isRoundRoleFragment(e){return e.value?.role===`round`}},Tu=class{blockKey;nextStatementIds;type=`update-next-preview`;target;payload;constructor(e,t){this.blockKey=e,this.nextStatementIds=t,this.target=e,this.payload={nextStatementIds:t}}do(e){let t=e.stack.blocks.find(e=>e.key.toString()===this.blockKey);if(!t)return[];let n=t.getMemoryByTag(`metric:next`);if(this.nextStatementIds.length===0){for(let e of n)e.update([]);return[]}let r=e.script;if(!r)return[];let i=la.empty(this.blockKey);for(let e of this.nextStatementIds){let t=r.getId(e);t&&i.merge(t.metrics)}if(i.removeByType(q.Hint),i.length===0){for(let e of n)e.update([]);return[]}return n.length>0?n[0].update(i):t.pushMemory(new iu(`metric:next`,i)),[]}},Eu=`effort-data`;oc.defaultMet;function Du(e){return!!e&&typeof e==`object`&&`effort`in e&&`met`in e&&`disciplineFactor`in e}function Ou(e){if(Du(e))return e;let t=e,n=t.baseAttributes.discipline,r=t.baseAttributes.disciplineFactor??Hc(n);return{effort:t,definition:t,slug:t.slug,label:t.label,met:t.baseAttributes.met,baseAttributes:t.baseAttributes,discipline:n,disciplineFactor:r,intensityTier:t.baseAttributes.intensityTier,modifiers:{},registrySource:t.registrySource,resolvedFrom:t.registrySource===`user`?`user`:t.registrySource===`bundled`?`bundled`:`default`,isEstimated:t.registrySource===`synthetic-unresolved`}}function ku(e){let t;for(let n of e)if(n.type===`effort-data`&&n.value&&typeof n.value==`object`){let e=Ou(n.value);t={resolved:e,effort:e.effort,origin:n.origin}}return t}var J=[0,0,0,0,0],Au=[1,0,0,0,0],ju=[0,1,0,0,0],Mu=[0,0,1,0,0],Nu=[0,0,0,1,0],Pu=[0,0,0,0,1];function Fu(e,t){return[e[0]+t[0],e[1]+t[1],e[2]+t[2],e[3]+t[3],e[4]+t[4]]}function Iu(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2],e[3]-t[3],e[4]-t[4]]}function Lu(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]}function Ru(e){return Lu(e,J)}var zu=[`L`,`M`,`T`,`C`,`E`];function Bu(e){if(Ru(e))return`dimensionless`;let t=[];for(let n=0;n<5;n++){let r=e[n];r!==0&&t.push(r===1?zu[n]:`${zu[n]}^${r}`)}return t.join(`·`)}var Vu={pace:{dim:[-1,0,1,0,0],preferredUnits:[`min/km`,`sec/km`,`min/mi`]},speed:{dim:[1,0,-1,0,0],preferredUnits:[`m/s`,`km/h`]},volume:{dim:[0,1,0,1,0],preferredUnits:[`kg`,`lb`]},power:{dim:[0,1,-1,1,0],preferredUnits:[`kg/s`,`lb/s`]},time:{dim:Mu,preferredUnits:[`min`,`s`,`h`]},mass:{dim:ju,preferredUnits:[`kg`,`lb`]},length:{dim:Au,preferredUnits:[`m`,`km`,`mi`]},count:{dim:Nu,preferredUnits:[`reps`]},energy:{dim:Pu,preferredUnits:[`cal`,`kcal`]},dimensionless:{dim:J,preferredUnits:[`pts`,`AU`,`MET`,`ratio`]}};function Hu(e){for(let[t,n]of Object.entries(Vu))if(Lu(n.dim,e))return t}var Uu={reps:{dim:Nu,metricType:`rep`,unit:`reps`},elapsed:{dim:Mu,metricType:`elapsed`,unit:`ms`},distance:{dim:Au,metricType:`distance`,unit:`m`},resistance:{dim:ju,metricType:`resistance`,unit:`kg`},segmentVolume:{dim:[0,1,0,1,0],metricType:`segmentVolume`,unit:`kg`},metMinutes:{dim:Mu,metricType:`metMinutes`,unit:`min`},effortRpe:{dim:J,metricType:`effortRpe`},metMinutesEstimated:{dim:J,metricType:`metMinutesEstimated`},sessionRpe:{dim:J,metricType:`session-rpe`},climbSend:{dim:Nu,metricType:`climb-send-type`,unit:`count`},climbGrade:{dim:J,metricType:`climb-grade`}},Wu={effort:J,effortLabel:J,sessionRpe:J,"session.duration":Mu,"profile.vo2max":J},Gu={sum:!0,max:!0,min:!0,avg:!0,count:!0,last:!0},Ku={AU:!0,pts:!0,"MET-min":!0,ratio:!0},qu=.45359237,Ju=1609.344,Yu={ms:{dim:Mu,factor:1},s:{dim:Mu,factor:1e3},sec:{dim:Mu,factor:1e3},min:{dim:Mu,factor:6e4},h:{dim:Mu,factor:36e5},hr:{dim:Mu,factor:36e5},m:{dim:Au,factor:1},km:{dim:Au,factor:1e3},mi:{dim:Au,factor:Ju},kg:{dim:ju,factor:1},lb:{dim:ju,factor:qu},lbs:{dim:ju,factor:qu},rep:{dim:Nu,factor:1},reps:{dim:Nu,factor:1},cal:{dim:Pu,factor:1},kcal:{dim:Pu,factor:1e3},MET:{dim:J,factor:1},"%":{dim:J,factor:1},rating:{dim:J,factor:1},bpm:{dim:J,factor:1},count:{dim:Nu,factor:1},"m/s":{dim:[1,0,-1,0,0],factor:.001},"km/h":{dim:[1,0,-1,0,0],factor:1e3/36e5},"sec/km":{dim:[-1,0,1,0,0],factor:1},"min/km":{dim:[-1,0,1,0,0],factor:60},"min/mi":{dim:[-1,0,1,0,0],factor:6e4/Ju},"reps/min":{dim:[0,0,-1,1,0],factor:1/6e4},"kg/s":{dim:[0,1,-1,1,0],factor:.001},"lb/s":{dim:[0,1,-1,1,0],factor:qu/1e3}};function Xu(e){let t=Yu[e];if(t)return t;if(Ku[e])return{dim:J,factor:1}}function Zu(e,t,n){let r=Yu[n];if(!r)throw new Qu(`Unknown unit: ${n}`);if(!t)return e/r.factor;let i=Yu[t];if(!i)throw new Qu(`Unknown unit: ${t}`);if(!Lu(i.dim,r.dim))throw new Qu(`Cannot convert from ${t} to ${n}: dimension mismatch`);return e*i.factor/r.factor}var Qu=class extends Error{constructor(e){super(e),this.name=`CalcUnitError`}};function $u(e,t,n,r,i){if(Lu(i,J))return;let a=[];for(let[i,o]of[[e,t],[n,r]])!i||Lu(o,J)||a.push(i);let o=a.filter(e=>!Lu(Yu[e]?.dim??J,Nu)),s=o.length>0?o:a;return s.length>0?s.join(`·`):void 0}function ed(e,t,n,r){if(!Lu(r,J)){if(!t||Lu(n,J))return e;if(e)return`${e}/${t}`}}var td={kind:`absent`};function nd(e,t=J,n){return{kind:`number`,value:e,dim:t,unit:n}}function rd(e){return{kind:`string`,value:e}}function id(e){return e.kind===`number`?e.value!==0:e.kind===`string`?e.value.length>0:e.kind===`series`?e.points.size>0:e.kind===`period`&&e.days>0}var ad=class extends Error{constructor(e){super(e),this.name=`CalcEvalError`}};function od(e,t){switch(e.kind){case`literal`:return nd(e.value);case`period`:return{kind:`period`,days:e.days};case`string`:return rd(e.value);case`ref`:return t.resolveRef(e.name);case`filter`:throw new ad(`Exclusion filter is only valid as an aggregate argument`);case`wql`:if(!t.resolveWql)throw new ad(`WQL atom ${e.aggregator}:${e.metric} is store-scope only`);return t.resolveWql(e);case`unary`:{let n=od(e.arg,t);if(e.op===`not`)return nd(+!id(n));if(n.kind===`absent`)return td;if(n.kind!==`number`)throw new ad(`Unary minus requires a number`);return nd(-n.value,n.dim,n.unit)}case`binary`:return sd(e,t);case`call`:return dd(e,t)}}function sd(e,t){let{op:n}=e;if(n===`and`)return id(od(e.left,t))?nd(+!!id(od(e.right,t))):nd(0);if(n===`or`)return id(od(e.left,t))?nd(1):nd(+!!id(od(e.right,t)));let r=od(e.left,t),i=od(e.right,t);if(r.kind===`series`||i.kind===`series`)return cd(n,r,i);if(n===`==`||n===`!=`){let e=ld(r,i);return nd(n===`==`?+!!e:+!e)}if(r.kind===`absent`||i.kind===`absent`)return n===`<`||n===`<=`||n===`>`||n===`>=`?nd(0):td;if(r.kind!==`number`||i.kind!==`number`)throw new ad(`Operator '${n}' requires numbers`);switch(n){case`+`:case`-`:if(!Lu(r.dim,i.dim))throw new ad(`Dimension mismatch for '${n}': ${Bu(r.dim)} vs ${Bu(i.dim)}`);return nd(n===`+`?r.value+i.value:r.value-i.value,r.dim,r.unit??i.unit);case`*`:{let e=Fu(r.dim,i.dim);return nd(r.value*i.value,e,$u(r.unit,r.dim,i.unit,i.dim,e))}case`/`:{if(i.value===0)return td;let e=Iu(r.dim,i.dim);return nd(r.value/i.value,e,ed(r.unit,i.unit,i.dim,e))}case`<`:return nd(+(ud(r)<ud(i)));case`<=`:return nd(+(ud(r)<=ud(i)));case`>`:return nd(+(ud(r)>ud(i)));case`>=`:return nd(+(ud(r)>=ud(i)))}}function cd(e,t,n){if(e===`and`||e===`or`||e===`==`||e===`!=`||e===`<`||e===`<=`||e===`>`||e===`>=`)throw new ad(`Operator '${e}' is not defined on series`);if(t.kind===`absent`||n.kind===`absent`)return td;let r=t.kind===`series`?t:void 0,i=n.kind===`series`?n:void 0,a=e=>e.kind===`number`?e.value:void 0;if(!r&&a(t)===void 0||!i&&a(n)===void 0)throw new ad(`Operator '${e}' requires numbers or series`);let o=a(t),s=a(n),c=t.kind===`number`||t.kind===`series`?t.dim:void 0,l=n.kind===`number`||n.kind===`series`?n.dim:void 0;if((e===`+`||e===`-`)&&c&&l&&!Lu(c,l))throw new ad(`Dimension mismatch for '${e}': ${Bu(c)} vs ${Bu(l)}`);let u=e===`*`?Fu(c??J,l??J):e===`/`?Iu(c??J,l??J):c??l??J,d=(t,n)=>{switch(e){case`+`:return t+n;case`-`:return t-n;case`*`:return t*n;case`/`:return n===0?void 0:t/n;default:return}},f=new Map,p=r??i;for(let[e,t]of p.points){let n=r?t:o,a=i?i.points.get(e):s;if(a===void 0)continue;let c=d(n,a);c!==void 0&&Number.isFinite(c)&&f.set(e,c)}return{kind:`series`,points:f,dim:u}}function ld(e,t){return e.kind===`absent`||t.kind===`absent`?e.kind===t.kind:e.kind===`string`||t.kind===`string`?e.kind===`string`&&t.kind===`string`&&e.value===t.value:e.kind!==`number`||t.kind!==`number`?e.kind===t.kind:Lu(e.dim,t.dim)?ud(e)===ud(t):!1}function ud(e){if(!e.unit)return e.value;let t=Yu[e.unit];return t?e.value*t.factor:e.value}function dd(e,t){let{name:n,args:r}=e;if(n===`has`){if(r.length!==1)throw new ad(`has() takes one argument`);return nd(od(r[0],t).kind===`absent`?0:1)}if(n===`convert`){if(r.length!==2)throw new ad(`convert() takes (value, targetUnit)`);let e=md(r[1]),n=od(r[0],t);if(n.kind===`absent`)return td;if(n.kind!==`number`)throw new ad(`convert() requires a number`);let i=Yu[e];if(!i)throw new ad(`Unknown unit: ${e}`);if(!Lu(n.dim,i.dim))throw new ad(`convert() dimension mismatch: ${Bu(n.dim)} is not ${Bu(i.dim)}`);return nd(Zu(n.value,n.unit,e),i.dim,e)}let i=r.map(e=>e.kind===`filter`?td:od(e,t));if(fd[n]&&(r[0]?.kind===`ref`||r[0]?.kind===`filter`)){let e=t.callFunction?.(n,i,r);if(e!==void 0)return e}if(n===`windowMean`||n===`windowSum`||n===`windowSd`){let[e,t]=i;if(e?.kind===`absent`)return td;if(e?.kind!==`series`||t?.kind!==`period`)throw new ad(`${n}() takes (series, period)`);return pd(n,e,t.days)}if(n===`windowEwma`){let[e,t]=i;if(e?.kind===`absent`)return td;if(e?.kind!==`series`||t?.kind!==`period`)throw new ad(`windowEwma() takes (series, period)`);let n=1/t.days,r=0,a=new Map;for(let t of[...e.points.keys()].sort((e,t)=>e-t))r+=((e.points.get(t)??0)-r)*n,a.set(t,r);return{kind:`series`,points:a,dim:e.dim,unit:e.unit}}if(i[0]?.kind===`series`&&(n===`sum`||n===`mean`||n===`min`||n===`max`||n===`last`)){let e=i[0],t=[...e.points.values()];if(t.length===0)return td;switch(n){case`sum`:return nd(t.reduce((e,t)=>e+t,0),e.dim,e.unit);case`mean`:return nd(t.reduce((e,t)=>e+t,0)/t.length,e.dim,e.unit);case`min`:return nd(Math.min(...t),e.dim,e.unit);case`max`:return nd(Math.max(...t),e.dim,e.unit);case`last`:return nd(t[t.length-1],e.dim,e.unit)}}switch(n){case`min`:case`max`:{let e=hd(n,i);if(e.length===0)return td;let t=e.reduce((e,t)=>(n===`min`?ud(t)<ud(e):ud(t)>ud(e))?t:e);return nd(t.value,t.dim,t.unit)}case`abs`:{let[e]=hd(n,i,1);return nd(Math.abs(e.value),e.dim,e.unit)}case`round`:{let[e,t]=hd(n,i),r=10**(t?t.value:0);return nd(Math.round(e.value*r)/r,e.dim,e.unit)}case`floor`:{let[e]=hd(n,i,1);return nd(Math.floor(e.value),e.dim,e.unit)}case`ceil`:{let[e]=hd(n,i,1);return nd(Math.ceil(e.value),e.dim,e.unit)}case`clamp`:{let[e,t,r]=hd(n,i,3);return nd(Math.min(Math.max(e.value,t.value),r.value),e.dim,e.unit)}}let a=t.callFunction?.(n,i,r);if(a!==void 0)return a;throw new ad(`Unknown function: ${n}`)}var fd={sum:!0,max:!0,min:!0,avg:!0,count:!0,last:!0};function pd(e,t,n){let r=e=>t.points.get(e)??0,i=new Map;for(let a of t.points.keys()){let t=0;for(let e=0;e<n;e++)t+=r(a-e);if(e===`windowSum`){i.set(a,t);continue}let o=t/n;if(e===`windowMean`){i.set(a,o);continue}let s=0;for(let e=0;e<n;e++){let t=r(a-e)-o;s+=t*t}i.set(a,Math.sqrt(s/n))}return{kind:`series`,points:i,dim:t.dim,unit:t.unit}}function md(e){if(e.kind===`ref`)return e.name;if(e.kind===`string`)return e.value;throw new ad(`convert() target unit must be a unit name`)}function hd(e,t,n){let r=[];for(let n of t)if(n.kind!==`absent`){if(n.kind!==`number`)throw new ad(`${e}() requires numeric arguments`);r.push(n)}if(n!==void 0&&(t.length!==n||r.length!==n))throw new ad(`${e}() needs ${n} numeric argument(s), got ${r.length}`);return r}var gd=class extends Error{pos;constructor(e,t){super(`${e} (at ${t})`),this.pos=t,this.name=`CalcParseError`}},_d=/[A-Za-z_]/,vd=/[A-Za-z0-9_.]/;function yd(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===` `||r===` `||r===`
18
+ `)}function pl(e){return cc(e).replace(/\s+/g,`-`)}var ml=class{registry;options;constructor(e,t){this.registry=e,this.options={defaultMet:t?.defaultMet??oc.defaultMet,defaultThreshold:t?.defaultThreshold??oc.defaultThreshold}}resolveBySlug(e){return this.registry.resolve(e)}resolveByAlias(e){let t=cc(e);for(let e of this.registry.list()){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}return null}resolveFuzzy(e,t){let n=t?.threshold??this.options.defaultThreshold,r=cc(e),i=this.resolveByAlias(e);if(i)return i;let a=[];for(let e of this.registry.list())for(let t of[e.label,...e.aliases])a.push({alias:t,effort:e});let o=lc(r,a.map(e=>e.alias),n);if(o){let e=a.find(e=>cc(e.alias)===cc(o.target));if(e)return e.effort}return this.createSyntheticEffort(e)}resolveEffort(e,t){let n=this.resolveBySlug(e)??this.resolveByAlias(e)??this.resolveFuzzy(e,{threshold:t?.threshold});return this.resolveDefinition(n,t)}resolveDefinition(e,t){return this.materialize(e,t?.modifiers??{},new Set)}list(){return this.registry.list()}materialize(e,t,n){if(n.has(e.slug))throw Error(`EffortResolver: circular effort derivation detected at "${e.slug}"`);n.add(e.slug);let r=e.derivation?.parentSlug?this.registry.resolve(e.derivation.parentSlug):null,i=r?this.materialize(r,t,n):null,a=i?.met??e.baseAttributes.met,o=e.derivation?.coefficients??{};for(let[e,n]of Object.entries(o))this.shouldApplyCoefficient(e,t)&&(a*=n);let s=e.derivation?.hardOverrides?.met;typeof s==`number`&&Number.isFinite(s)&&(a=s);let c=e.baseAttributes.discipline??i?.discipline,l=this.resolveDisciplineFactor(e,i),u=e.registrySource,d=u===`user`?`user`:u===`bundled`?`bundled`:`default`,f=u===`synthetic-unresolved`,p={...e,baseAttributes:{...e.baseAttributes,met:a,discipline:c,disciplineFactor:l,intensityTier:e.baseAttributes.intensityTier??i?.intensityTier}};return{effort:p,definition:e,slug:p.slug,label:p.label,met:a,baseAttributes:p.baseAttributes,discipline:c,disciplineFactor:l,intensityTier:p.baseAttributes.intensityTier,modifiers:{...t},registrySource:u,resolvedFrom:d,isEstimated:f}}shouldApplyCoefficient(e,t){if(e===`met`||e===`*`)return!0;for(let[n,r]of Object.entries(t))if(e===n||e===r||e===`${n}:${r}`||e===`${n}=${r}`)return!0;return!1}resolveDisciplineFactor(e,t){let n=e.derivation?.hardOverrides?.disciplineFactor;if(typeof n==`number`&&Number.isFinite(n))return n;let r=e.baseAttributes.disciplineFactor;if(typeof r==`number`&&Number.isFinite(r))return r;let i=e.baseAttributes.discipline??t?.discipline;return!i&&t?t.disciplineFactor:Hc(i)}createSyntheticEffort(e){let t=cc(e),n=pl(e);return{id:`synthetic-${C()}`,slug:n,label:t,aliases:[t],baseAttributes:{met:this.options.defaultMet,discipline:void 0,intensityTier:void 0},registrySource:`synthetic-unresolved`}}},hl=[{id:`fixture-running`,slug:`running-6-mph`,label:`Running (6 mph)`,aliases:[`run`,`jogging`,`treadmill`],baseAttributes:{met:9.8,discipline:`running`,intensityTier:`moderate`},registrySource:`bundled`},{id:`fixture-rowing`,slug:`rowing`,label:`Rowing`,aliases:[`row`,`rower`,`erg`],baseAttributes:{met:7,discipline:`rowing`,intensityTier:`high`},registrySource:`bundled`},{id:`fixture-back-squat`,slug:`back-squat`,label:`Back Squat`,aliases:[`squat`,`barbell squat`,`bs`],baseAttributes:{met:6,discipline:`strength`,intensityTier:`moderate`},registrySource:`bundled`},{id:`fixture-burpee`,slug:`burpee`,label:`Burpee`,aliases:[`burpees`],baseAttributes:{met:10,discipline:`bodyweight`,intensityTier:`high`},registrySource:`bundled`},{id:`fixture-plank`,slug:`plank`,label:`Plank`,aliases:[`planks`],baseAttributes:{met:3.5,discipline:`bodyweight`,intensityTier:`low`},registrySource:`bundled`}];[...hl];var gl=hl;gl.length;var _l=class{efforts=new Map;sourceFilter=null;initialized=!1;constructor(e){this.sourceFilter=e??null}async loadBundled(){for(let e of gl)(!this.sourceFilter||e.registrySource===this.sourceFilter)&&this.efforts.set(e.slug,e);this.initialized=!0}isInitialized(){return this.initialized}seed(e){for(let t of e)this.efforts.set(t.slug,t)}clear(){this.efforts.clear(),this.initialized=!1}resolve(e){return this.efforts.get(e)??null}resolveByAlias(e){let t=cc(e);for(let e of this.efforts.values()){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}return null}list(){return Array.from(this.efforts.values())}listByOrigin(e){return this.list().filter(t=>t.registrySource===e)}async upsert(e){if(e.registrySource!==`user`)throw Error(`InMemoryEffortRegistry.upsert: only user efforts can be written. Received registrySource="${e.registrySource}"`);this.efforts.set(e.slug,e)}async delete(e){let t=this.efforts.get(e);if(t&&t.registrySource!==`user`)throw Error(`InMemoryEffortRegistry.delete: cannot delete non-user effort "${e}"`);this.efforts.delete(e)}},vl=class{userItems=new Map;bundledItems=new Map;initialized=!1;initialBundled;storage;constructor(e){this.initialBundled=e?.bundled,this.storage=e?.storage}async loadBundled(e){let t=this.storage?await this.storage.load():[];this.bundledItems.clear();let n=e??this.initialBundled;if(n)for(let e of n){let t=this.bundledItems.get(e.slug);(!t||rc(e)>=rc(t))&&this.bundledItems.set(e.slug,e)}this.userItems.clear();for(let e of t)e.registrySource===`user`&&this.userItems.set(e.slug,e);this.initialized=!0}isInitialized(){return this.initialized}resolve(e){return this.userItems.get(e)??this.bundledItems.get(e)??null}resolveByAlias(e){let t=cc(e);for(let e of this.userItems.values()){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}let n=[...this.bundledItems.values()].filter(e=>!this.userItems.has(e.slug)).sort((e,t)=>rc(t)-rc(e));for(let e of n){if(cc(e.label)===t)return e;for(let n of e.aliases)if(cc(n)===t)return e}return null}list(){let e=new Map(this.bundledItems);for(let t of this.userItems.values())e.set(t.slug,t);return[...e.values()]}listByOrigin(e){return e===`user`?[...this.userItems.values()]:[...this.bundledItems.values()]}async upsert(e){if(e.registrySource!==`user`)throw Error(`Cannot upsert property with registrySource '${e.registrySource}'; clone it as 'user' first`);this.userItems.set(e.slug,e),this.storage&&await this.storage.save(e)}async delete(e){if(!this.userItems.get(e))throw Error(`Cannot delete '${e}': not a user-owned record`);this.userItems.delete(e),this.storage&&await this.storage.delete(e)}},yl=class extends vl{constructor(e){super({storage:e?.storage})}},bl=class extends vl{constructor(e){super({bundled:e?.bundled,storage:e?.storage})}async loadBundled(e){this.bundledItems.clear();let t=e??this.initialBundled??gl;for(let e of t){let t=this.bundledItems.get(e.slug);(!t||rc(e)>=rc(t))&&this.bundledItems.set(e.slug,e)}if(this.userItems.clear(),this.storage)try{let e=await this.storage.load();for(let t of e)t.registrySource===`user`&&this.userItems.set(t.slug,t)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to load user efforts from storage adapter:`,e)}this.initialized=!0}isInitialized(){return this.initialized}listByOrigin(e){return e===`user`?Array.from(this.userItems.values()):e===`bundled`?Array.from(this.bundledItems.values()):this.list().filter(t=>t.registrySource===e)}async upsert(e){if(e.registrySource!==`user`)throw Error(`CompositeEffortRegistry.upsert: only user efforts can be written. Received registrySource="${e.registrySource}"`);if(this.userItems.set(e.slug,e),this.storage)try{await this.storage.save(e)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to persist effort to storage adapter:`,e)}}async delete(e){let t=this.resolve(e);if(t&&t.registrySource!==`user`)throw Error(`CompositeEffortRegistry.delete: cannot delete non-user effort "${e}"`);if(this.userItems.delete(e),this.storage)try{await this.storage.delete(e)}catch(e){console.warn(`[CompositeEffortRegistry] Failed to delete effort from storage adapter:`,e)}}};async function xl(e,t,n){let r=n.trim();if(!r)throw Error(`Alias cannot be empty`);let i=e.resolve(t);if(!i)throw Error(`Effort "${t}" not found in registry`);let a=cc(r);if(cc(i.label)===a||i.aliases.some(e=>cc(e)===a))return i;let o=[...i.aliases,r],s=new Date().toISOString();if(i.registrySource===`bundled`){let t=typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`effort-user-${crypto.randomUUID()}`:`effort-user-${Date.now()}`,n={...i,id:t,registrySource:`user`,aliases:o,updatedAt:s,derivation:i.derivation??{parentSlug:i.slug,coefficients:{},hardOverrides:{}}};return await e.upsert(n),n}let c={...i,aliases:o,updatedAt:s};return await e.upsert(c),c}var Sl={debugMode:!1,enableLogging:!1,maxActionDepth:20},Cl=class e{started;ended;constructor(e,t){this.started=e,this.ended=t}static fromJSON(t){return new e(t.started,t.ended)}static fromDates(t,n){return new e(t.getTime(),n?.getTime())}get duration(){let e=this.ended??Date.now();return Math.max(0,e-this.started)}get isOpen(){return this.ended===void 0}get startDate(){return new Date(this.started)}get endDate(){return this.ended?new Date(this.ended):void 0}},wl=class e{_underlying;_frozenTime;constructor(e,t){this._underlying=e,this._frozenTime=t}get currentDate(){return this._frozenTime}now(){return this._frozenTime}nowMs(){return this._frozenTime.getTime()}get elapsed(){return this._underlying.elapsed}get isRunning(){return this._underlying.isRunning}get spans(){return this._underlying.spans}start(){return this._underlying.start()}stop(){return this._underlying.stop()}static at(t,n){return new e(t,n)}static now(t){return new e(t,t.currentDate)}},Tl=class{_spans=[];get currentDate(){return new Date}now(){return this.currentDate}nowMs(){return this.currentDate.getTime()}get isRunning(){return this._spans.length!==0&&this._spans[this._spans.length-1].isOpen}get spans(){return this._spans}get elapsed(){return this._spans.reduce((e,t)=>e+t.duration,0)}start(){let e=new Date;return this.isRunning?this._spans[this._spans.length-1].startDate:(this._spans.push(new Cl(e.getTime())),e)}stop(){let e=new Date;return this.isRunning&&(this._spans[this._spans.length-1].ended=e.getTime()),e}reset(){this._spans=[]}},El={now:()=>new Date,nowMs:()=>Date.now()},Dl=class{options;now;type=`next`;constructor(e,t=El){this.options=e,this.now=t}do(e){if(!this.validateRuntimeState(e))return[];let t=e.stack.current;if(!t)return[];try{let n={...e.clock?{clock:wl.now(e.clock)}:void 0,...this.options};return t.next(e,n)}catch(n){return e.errors&&Array.isArray(e.errors)&&e.errors.push({error:n,source:`NextAction`,timestamp:this.now.now(),blockKey:t.key.toString()}),[]}}validateRuntimeState(e){return!!e.stack}},Ol=class{error;source;context;type=`error`;constructor(e,t,n){this.error=e,this.source=t,this.context=n}do(e){let t=e;t.errors||=[];let n={error:this.error,source:this.source,timestamp:new Date,context:this.context};t.errors.push(n),console.error(`❌ Runtime Error from ${this.source}:`,this.error.message),this.context&&console.error(` Context:`,this.context)}},kl=class{error;source;type=`throw-error`;constructor(e,t){this.error=e,this.source=t}do(e){new Ol(this.error,this.source).do(e),e.eventBus.dispatch({name:`workout:error`,timestamp:e.clock.currentDate,data:{error:this.error,source:this.source}},e)}};function Al(e,t){return new kl(e,t)}var jl=class{_id;_name;constructor(e){this._id=e,this._name=`next-handler`}get id(){return this._id}set id(e){throw Error(`Cannot modify readonly property id`)}get name(){return this._name}set name(e){throw Error(`Cannot modify readonly property name`)}handler(e,t){return e.name===`next`?!t||!t.stack||t.stack.count===0?[Al(Error(`Invalid runtime state for next event`),`NextEventHandler`)]:[new Dl(void 0,t.nowProvider)]:[]}},Ml=class{type=`abort-session`;do(e){let t=0,n=[];for(;t<100&&e.stack.count>0;){let r=e.stack.current;if(!r)break;!r.isComplete&&typeof r.markComplete==`function`&&r.markComplete(`user-abort`);let i=(r.unmount(e,{createdAt:e.clock.currentDate})??[]).filter(e=>e.type!==`emit-event`);n.push(...i);let a=e.stack.pop();if(!a)break;a.dispose(e),a.context?.release?.(),t++}return n}},Nl=class{_id;constructor(e){this._id=e}get id(){return this._id}set id(e){throw Error(`Cannot modify readonly property id`)}get name(){return`abort-handler`}set name(e){throw Error(`Cannot modify readonly property name`)}handler(e,t){return e.name!==`abort`||!t||!t.stack||t.stack.count===0?[]:[new Ml]}},Pl=class{message;event;blockKey;blockLabel;stackLevel;extra;type=`emit-system-output`;constructor(e,t,n,r,i,a){this.message=e,this.event=t,this.blockKey=n,this.blockLabel=r,this.stackLevel=i,this.extra=a}do(e){let t=e.clock.currentDate,n={event:this.event,blockKey:this.blockKey,blockLabel:this.blockLabel,...this.extra},r={type:q.System,image:this.message,value:n,origin:`runtime`,timestamp:t},i=new fa({outputType:`system`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:this.blockKey,stackLevel:this.stackLevel??e.stack.count,metrics:[r]});return e.addOutput(i),[]}},Fl=class{_runtime;_workList=[];_iteration=0;_maxIterations;_snapshotClock;constructor(e,t=20){this._runtime=e,this._maxIterations=t,this._snapshotClock=wl.at(e.clock,e.clock.currentDate)}get script(){return this._runtime.script}get eventBus(){return this._runtime.eventBus}get stack(){return this._runtime.stack}get options(){return this._runtime.options}get jit(){return this._runtime.jit}get errors(){return this._runtime.errors}get analyticsContext(){return this._runtime.analyticsContext}get clock(){return this._snapshotClock}get nowProvider(){return this._runtime.nowProvider}addOutput(e){this._runtime.addOutput(e)}do(e){this._workList.unshift(e)}doAll(e){e.length!==0&&this._workList.unshift(...e)}handle(e){let t=this.eventBus.dispatch(e,this);if(t.length>0){let n=`source`in e&&typeof e.source==`string`?e.source:`event-bus`,r=new Pl(`event: ${e.name} → ${t.length} action(s)`,`event-action`,n,void 0,this.stack.count,{eventName:e.name,actionTypes:t.map(e=>e.type)});this.doAll([r,...t])}else this.doAll(t)}execute(e){for(this._workList.push(e);this._workList.length>0;){if(this._iteration>=this._maxIterations)throw Error(`[ExecutionContext] Max iterations reached (${this._maxIterations}). Aborting to prevent infinite loop.`);let e=this._workList.shift();this._iteration++;let t=e.do(this);t&&t.length>0&&this._workList.unshift(...t)}}},Il=e=>String(e).padStart(2,`0`),Ll=e=>String(e).padStart(3,`0`);function Rl(e){return`${Il(e.getHours())}:${Il(e.getMinutes())}:${Il(e.getSeconds())}.${Ll(e.getMilliseconds())}`}function zl(e){return(e+` `).slice(0,5)}function Bl(e){return(e+` `.repeat(24)).slice(0,24)}function Vl(e){if(!e)return`─`.repeat(52);let t=` ${e} `,n=Math.max(0,Math.floor((52-t.length)/2)),r=Math.max(0,52-t.length-n);return`${`─`.repeat(n)}${t}${`─`.repeat(r)}`}var Hl=class{_console=console;_enabled=!1;_history=[];_maxHistory=500;EVENT_STYLES={BOOT:`color: #3b82f6; font-weight: bold`,PUSH:`color: #a855f7; font-weight: bold`,POP:`color: #64748b`,NEXT:`color: #b45309; font-weight: bold`,EVNT:`color: #a855f7; font-weight: bold`,OUT:`color: #16a34a; font-weight: bold`,MEM:`color: #f59e0b`,TIME:`color: #3b82f6; font-weight: bold`,HALT:`color: #ef4444; font-weight: bold`,WARN:`color: #f59e0b; font-weight: bold`,ERR:`color: #ef4444; font-weight: bold`};constructor(){if(typeof window<`u`){let e=window;this._enabled=!!e.__WOD_DEBUG__}}get enabled(){return this._enabled}enable(){this._enabled=!0,this.writeLine(`BOOT`,`runtime:ready`,`logging enabled`)}disable(){this.writeLine(`HALT`,`runtime:logger`,`logging disabled`),this._enabled=!1}getHistory(){return[...this._history]}clearHistory(){this._history=[]}logBoot(e){this._enabled&&this.writeLine(`BOOT`,`runtime:ready`,e)}logPush(e,t,n){if(!this._enabled)return;let r=this.getBehaviorNames(e),i=[`d${n??`?`} ${e.blockType??`block`}`,r.length>0?`behaviors [${r.join(`, `)}]`:void 0,t?`parent ${t.slice(0,8)}`:void 0].filter(Boolean).join(` · `);this.writeLine(`PUSH`,e.label||e.blockType||`Block`,i),this.addToHistory(`info`,`push`,`PUSH ${e.label}`,{key:e.key.toString(),parentKey:t,behaviors:r,sourceIds:e.sourceIds})}logPop(e,t,n){this._enabled&&(this.writeLine(`POP`,e.label||e.blockType||`Block`,`d${n??`?`}${t?` `+t:``}`),this.addToHistory(`info`,`pop`,`POP ${e.label}`,{key:e.key.toString(),reason:t}))}logNext(e,t){if(!this._enabled||t.length===0)return;let n=t.map(e=>e.type||e.constructor?.name||`Action`);this.writeLine(`NEXT`,e.label||`Block`,`${n.length} action(s): [${n.join(`, `)}]`),this.addToHistory(`info`,`next`,`NEXT ${e.label}`,{key:e.key.toString(),actions:n})}logEvent(e,t){if(!this._enabled||t.length===0)return;let n=t.map(e=>e.type||e.constructor?.name||`Action`);this.writeLine(`EVNT`,e.name,`${n.length} action(s): [${n.join(`, `)}]`),this.addToHistory(`info`,`event`,`EVENT ${e.name}`,{eventName:e.name,eventData:e.data,actions:n})}logOutput(e){if(!this._enabled||e.outputType!==`segment`&&e.outputType!==`milestone`)return;let t=e.text||this.outputSubject(e.metrics);t&&(this.writeLine(`OUT`,t,e.outputType),this.addToHistory(`info`,`output`,`OUT ${t}`,{outputType:e.outputType,label:t}))}outputSubject(e){if(e){for(let t of e)if(t.type===`label`)return t.image||(t.value==null?``:String(t.value))||void 0}}logMemoryUpdate(e,t,n){if(!this._enabled)return;let r=typeof n==`object`&&n?this.summarizeObject(n):n;this.writeLine(`MEM`,t,`[${e.slice(0,8)}] ${Ul(r)}`),this.addToHistory(`debug`,`memory`,`MEMORY ${t}`,{blockKey:e,memoryType:t,value:r})}logAction(e,t){if(!this._enabled)return;let n=e.type||e.constructor?.name||`Action`;this.writeLine(`EVNT`,n,`d${t}`)}logMessage(e,t,n,r){this._enabled&&(this.writeLine(e===`error`?`ERR`:e===`warn`?`WARN`:`EVNT`,t,n),this.addToHistory(e,t,n,r))}logAlways(e,t,n,r){this.writeLine(e===`error`?`ERR`:e===`warn`?`WARN`:`EVNT`,t,n),this.addToHistory(e,t,n,r)}logRule(e){this._enabled&&this._console.log(`%c${Vl(e)}`,`color: #94a3b8`)}writeLine(e,t,n){let r=Rl(new Date);this._console.log(`${r} %c${zl(e)}%c ${Bl(t)}${n?` `+n:``}`,this.EVENT_STYLES[e],`color: inherit`)}getBehaviorNames(e){let t=e.behaviors;return!t||!Array.isArray(t)?[]:t.map(e=>e.constructor?.name||`Behavior`)}summarizeObject(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?`[${r.length} items]`:typeof r==`object`&&r?`{...}`:r;return t}addToHistory(e,t,n,r){this._history.push({timestamp:new Date,level:e,category:t,message:n,data:r}),this._history.length>this._maxHistory&&(this._history=this._history.slice(-this._maxHistory))}};function Ul(e){try{return JSON.stringify(e)??``}catch{return String(e)}}var Wl=new Hl;typeof window<`u`&&(window.RuntimeLogger=Wl);var Gl=class{_outputStatements=[];_outputListeners=new Set;_analyticsEngine=null;_analyticsFinalized=!1;_liveAnalytics=[];_clock=null;_stack=null;_script=null;attach(e){this._clock=e.clock,this._stack=e.stack,this._script=e.script}_requireClock(){if(!this._clock)throw Error(`[OutputEmitter] emission helper called before attach() — clock is not wired`);return this._clock}add(e){if(e.outputType===`system`&&this._outputListeners.size===0)return;let t=this._analyticsEngine?this._analyticsEngine.run(e):e;this._propagateSourceLine(t),Wl.logOutput(t),this._outputStatements.push(t);for(let e of this._outputListeners)try{e(t)}catch(e){console.error(`[OutputEmitter] Listener error:`,e)}}subscribe(e){this._outputListeners.add(e);let t=[...this._outputStatements];return t.length>0&&setTimeout(()=>{if(this._outputListeners.has(e))for(let n of t)e(n)},0),()=>this._outputListeners.delete(e)}getAll(){return[...this._outputStatements]}hasListeners(){return this._outputListeners.size>0}setAnalyticsEngine(e){this._analyticsEngine=e,e.setLiveOutputEmitter(e=>this.emitLiveAnalytics(e))}finalizeAnalytics(){if(!this._analyticsEngine||this._analyticsFinalized)return[];this._analyticsFinalized=!0;let e=this._analyticsEngine.finalize(),t=e.length>0?e:this._liveAnalytics;for(let e of t){this._outputStatements.push(e);for(let t of this._outputListeners)try{t(e)}catch(e){console.error(`[OutputEmitter] Finalize listener error:`,e)}}return this._liveAnalytics=[],t}emitLiveAnalytics(e){this._liveAnalytics=e;for(let t of e)for(let e of this._outputListeners)try{e(t)}catch(e){console.error(`[OutputEmitter] Live analytics listener error:`,e)}}getLiveAnalytics(){return[...this._liveAnalytics]}dispose(){this._outputStatements=[],this._outputListeners.clear(),this._analyticsFinalized=!1,this._liveAnalytics=[]}emitLoad(){if(!this._script)throw Error(`[OutputEmitter] emitLoad() called before attach() — script is not wired`);let e=this._script,t=this._requireClock().currentDate;for(let n of e.statements){let r=e.source.substring(n.meta.startOffset,n.meta.endOffset+1),i=la.from(n.metrics,n.id);i.add({type:q.Label,image:r||`Statement`,value:r,origin:`runtime`,timestamp:t});let a=0,o=n.parent,s=new Set;for(;o!==void 0&&!s.has(o);){s.add(o);let t=e.getId(o);if(t)a++,o=t.parent;else break}this.add(new fa({outputType:`load`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:`root`,sourceStatementId:n.id,stackLevel:a,metrics:i}))}}emitStackEvent(e){if(!this.hasListeners())return;let t=this._requireClock().currentDate,n=e.block,r=this._stack?.blocks??[],i={event:e.type,blockKey:n.key.toString(),blockLabel:n.label,actionType:e.type===`push`?`push-block`:`pop-block`};if(e.type===`push`){let e=r.length>1?r[1]:void 0;e&&(i.parentKey=e.key.toString())}else i.completionReason=n.completionReason??`normal`;let a={type:q.System,image:e.type===`push`?`push: ${n.label??n.blockType??`Block`} [${n.key.toString().slice(0,8)}]`:`pop: ${n.label??n.blockType??`Block`} [${n.key.toString().slice(0,8)}] reason=${n.completionReason??`normal`}`,value:i,origin:`runtime`,timestamp:t};this.add(new fa({outputType:`system`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:n.key.toString(),stackLevel:e.depth,metrics:la.empty(n.key.toString()).add(a)}))}emitSegmentFromResultMemory(e,t){let n=e.getMemoryByTag(`metric:result`),r=e.getMemoryByTag(`metric:display`);if(n.length===0)return;let i=this._requireClock().currentDate.getTime();for(let a=0;a<n.length;a++){let o=la.from(n[a].metrics,e.key.toString()),s=la.from(r[a]?.metrics,e.key.toString()),c=la.empty(e.key.toString()).add(...s.toArray()).add(...o.toArray());if(c.length===0)continue;let l=new Cl(e.executionTiming?.startTime?.getTime()??i,i);this.add(new fa({outputType:`segment`,completionReason:e.completionReason,timeSpan:l,sourceBlockKey:e.key.toString(),sourceStatementId:e.sourceIds?.[a]??e.sourceIds?.[0],stackLevel:t,metrics:c}))}}emitRuntimeEvent(e){let t=this._requireClock().currentDate,n=this._stack,r=n?.current?.key.toString()??`root`,i=la.empty(r).add({type:q.System,image:`event: ${e.name}`,value:{name:e.name,data:e.data,blockKey:r},origin:`runtime`,timestamp:t});this.add(new fa({outputType:`event`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:r,stackLevel:n?.count??0,metrics:i}))}emitCompilerBlock(e){let t=this._requireClock().currentDate,n=this._stack?.count??0,r=la.empty(e.key.toString()).add({type:q.Label,image:`Behaviors: ${e.behaviors.map(e=>e.constructor.name).join(`, `)}`,value:e.behaviors.map(e=>e.constructor.name),origin:`runtime`,timestamp:t});this.add(new fa({outputType:`compiler`,timeSpan:new Cl(t.getTime(),t.getTime()),sourceBlockKey:e.key.toString(),stackLevel:n,metrics:r}))}_propagateSourceLine(e){if(e.sourceStatementId===void 0||e.line!==void 0)return;let t=this._script?.getId(e.sourceStatementId);t&&(e.line=t.line,e.text??=t.text,e.dialect??=t.dialect)}},Kl=class{_stackObservers=new Set;_logger;constructor(e){this._logger=e}subscribeToStack(e){return this._stackObservers.add(e),()=>{this._stackObservers.delete(e)}}emitStack(e){if(this._stackObservers.size!==0)for(let t of this._stackObservers)try{t(e)}catch(e){this._logger?.error?.(`[RuntimeObservers] Stack observer error:`,e)}}hasStackObserver(e){return this._stackObservers.has(e)}emitSettled(e,t,n){if(this._stackObservers.size===0||e.length===0)return;let r={type:`initial`,blocks:e,depth:t,clockTime:n};this.emitStack(r)}dispose(){this._stackObservers.clear()}get stackObserverCount(){return this._stackObservers.size}},ql=class{block;options;_type=`push-block`;constructor(e,t={}){this.block=e,this.options=t}get type(){return this._type}set type(e){throw Error(`Cannot modify readonly property type`)}do(e){if(!e.stack)return[];try{let t=this.options.startTime,n=this.options.clock??e.clock;!t&&n?.isRunning&&(t=n.currentDate);let r=t?{...this.options,startTime:t}:{...this.options},i=this.block;t&&(i.executionTiming={...i.executionTiming??{},startTime:t}),e.stack.push(this.block);let a=this.block.mount(e,r),o=e.stack.blocks.length>1?e.stack.blocks[1]?.key.toString():void 0;return Wl.logPush(this.block,o,e.stack.blocks.length),a}catch(t){let n=e;return typeof n.setError==`function`&&n.setError(t),[]}}},Jl=class{options;type=`pop-block`;constructor(e={}){this.options=e}do(e){let t=e.stack.current;if(!t)return[];let n=this.options.createdAt??e.clock.currentDate,r={...this.options,createdAt:n};t.executionTiming&&(t.executionTiming.createdAt=n),!t.isComplete&&typeof t.markComplete==`function`&&(t.markComplete(`forced-pop`),Wl.logPop(t,`forced-pop (incomplete block popped without next)`,e.stack.blocks.length));let i=t.unmount(e,r)??[],a=e.stack.pop();return a?(a.dispose(e),a.context?.release?.(),a.completionReason!==`forced-pop`&&Wl.logPop(a,a.completionReason,e.stack.blocks.length+1),e.stack.current?[...i,new Dl(r,e.nowProvider)]:i):[]}},Yl=class{script;eventBus;clock;stack;jit;errors=[];options;analyticsContext;_output=new Gl;_observers;_activeContext=null;_now;_stackSubscriptionUnsub=null;_nextHandlerUnsub=null;get nowProvider(){return this._now}_abortHandlerUnsub=null;constructor(e,t,n,r={},i=El){this.script=e,this.options={...Sl,...r},this._observers=new Kl(this.options.logger),this.stack=n.stack,this.clock=n.clock,this.eventBus=n.eventBus,this._now=i,this._nextHandlerUnsub=this.eventBus.register(`next`,new jl(`runtime-next-handler`),`runtime`,{scope:`global`}),this._abortHandlerUnsub=this.eventBus.register(`abort`,new Nl(`runtime-abort-handler`),`runtime`,{scope:`global`}),this.jit=t,this._output.attach({clock:this.clock,stack:this.stack,script:this.script}),this._stackSubscriptionUnsub=this.stack.subscribe(e=>{e.type===`pop`&&this._output.emitSegmentFromResultMemory(e.block,e.depth),(e.type===`push`||e.type===`pop`)&&this._output.emitStackEvent(e);let t={type:e.type===`initial`?`initial`:e.type,blocks:(e.type,e.blocks),affectedBlock:e.type===`initial`?void 0:e.block,depth:e.type===`initial`?e.blocks.length:e.depth,clockTime:this.clock.currentDate};this._observers.emitStack(t)}),this.clock.start(),this._output.emitLoad(),Wl.logBoot(`statements ${this.script.statements.length}`)}do(e){if(this._activeContext){this._activeContext.do(e);return}this._activeContext=new Fl(this,this.options.maxActionDepth??20);try{this._activeContext.execute(e)}finally{this._activeContext=null,this._notifyStackSettled()}}_buildInitialSnapshot(){let e=this.stack.blocks;return{type:`initial`,blocks:e,depth:e.length,clockTime:this.clock.currentDate}}_notifyStackSettled(){this._observers.emitSettled(this.stack.blocks,this.stack.count,this.clock.currentDate)}doAll(e){if(e.length!==0){if(this._activeContext){this._activeContext.doAll(e);return}this.do({type:`composite-doAll`,do:()=>e})}}handle(e){let t=this.eventBus.dispatch(e,this);(e.name!==`tick`||t.length>0)&&this._output.emitRuntimeEvent(e),t.length!==0&&this.doAll(t)}subscribeToOutput(e){return this._output.subscribe(e)}getOutputStatements(){return this._output.getAll()}getLiveAnalytics(){return this._output.getLiveAnalytics()}addOutput(e){this._output.add(e)}setAnalyticsEngine(e){this._output.setAnalyticsEngine(e)}finalizeAnalytics(){return this._output.finalizeAnalytics()}subscribeToStack(e){let t=this._observers.subscribeToStack(e);return setTimeout(()=>{if(this._observers.hasStackObserver(e))try{e(this._buildInitialSnapshot())}catch(e){console.error(`[RT] Stack observer error (initial):`,e)}},0),t}dispose(){for(this.clock.stop();this.stack.count>0;){let e=this.stack.current;if(e){try{e.unmount(this)}catch{}this.stack.pop();try{e.dispose(this)}catch{}}else this.stack.pop()}this._nextHandlerUnsub&&=(this._nextHandlerUnsub(),null),this._abortHandlerUnsub&&=(this._abortHandlerUnsub(),null),this._output.dispose(),this._stackSubscriptionUnsub&&=(this._stackSubscriptionUnsub(),null),this._observers.dispose(),this.eventBus.dispose()}pushBlock(e,t){let n=this.stack.current;this.options.hooks?.onBeforePush?.(e,n),this._output.emitCompilerBlock(e);let r=this.options.wrapper?.wrap?.(e,n)??e;this.do(new ql(r,t)),this.options.logger?.debug?.(`runtime.pushBlock`,{blockKey:e.key.toString(),parentKey:n?.key.toString()}),this.options.hooks?.onAfterPush?.(r,n)}popBlock(e){let t=this.stack.current;t&&(this.options.hooks?.onBeforePop?.(t),this.do(new Jl(e)),this.options.wrapper?.cleanup?.(t),this.options.hooks?.unregisterByOwner?.(t.key.toString()),this.options.logger?.debug?.(`runtime.popBlock`,{blockKey:t.key.toString(),stackDepth:this.stack.count}),this.options.hooks?.onAfterPop?.(t))}},Xl=class{_memory;ownerId;type;visibility;_logger;id=C();_subscriptions=[];constructor(e,t,n,r=`private`,i){this._memory=e,this.ownerId=t,this.type=n,this.visibility=r,this._logger=i}value(){return this.get()}get subscriptions(){return this._subscriptions}get(){return this._memory.get(this)}set(e){this._memory.set(this,e)}subscribe(e,t){let n=C(),r={id:n,callback:e,memoryId:this.id,createdAt:new Date};return this._subscriptions.push(r),t?.immediate&&e(this.get(),void 0),()=>this.unsubscribe(n)}unsubscribe(e){let t=this._subscriptions.findIndex(t=>t.id===e);t>=0&&this._subscriptions.splice(t,1)}hasSubscribers(){return this._subscriptions.length>0}notifySubscribers(e,t){for(let n of this._subscriptions)try{n.callback(e,t)}catch(e){this._logger?.error?.(`Error in memory subscription callback:`,e)}}},Zl=class{_references=[];allocate(e,t,n,r=`private`){let i=new Xl(this,t,e,r);return this._references.push({ref:i,data:n}),i}get(e){return this._references.find(t=>t.ref.id===e.id)?.data??void 0}set(e,t){let n=this._references.find(t=>t.ref.id===e.id);if(!n)throw Error(`Invalid memory reference: ${e.id}`);let r=n.data;n.data=t,e.hasSubscribers()&&e.notifySubscribers(t,r)}search(e){return this._references.map(e=>e.ref).filter(t=>!(e.id!==null&&e.id!==void 0&&e.id!==t.id||e.ownerId!==null&&e.ownerId!==void 0&&e.ownerId!==t.ownerId||e.type!==null&&e.type!==void 0&&e.type!==t.type||e.visibility!==null&&e.visibility!==void 0&&e.visibility!==t.visibility))}release(e){let t=this._references.findIndex(t=>t.ref.id===e.id);if(t>=0){let e=this._references[t],n=e.data,r=e.ref;r instanceof Xl&&r.hasSubscribers()&&r.notifySubscribers(void 0,n),this._references.splice(t,1)}}},Ql=function(e){return e.DISPLAY_STACK_STATE=`displaystack`,e.ACTION_STACK_STATE=`actions`,e.TIMER_PREFIX=`timer:`,e.HANDLER_PREFIX=`handler:`,e.METRIC_REPS=`metric:reps`,e.ANCHOR=`anchor`,e}({}),$l=class{timestamp;constructor(e=El){this.timestamp=e.now()}},eu=class extends $l{name=`memory:allocate`;data;constructor(e,t,n=El){super(n),this.data={ref:e,value:t}}},tu=class extends $l{name=`memory:set`;data;constructor(e,t,n,r=El){super(r),this.data={ref:e,value:t,oldValue:n}}},nu=class extends $l{name=`memory:release`;data;constructor(e,t,n=El){super(n),this.data={ref:e,lastValue:t}}},ru=class{runtime;ownerId;exerciseId;_references=[];_released=!1;_memory;constructor(e,t,n=``,r=[],i){this.runtime=e,this.ownerId=t,this.exerciseId=n,this._references=[...r],this._memory=i??new Zl}get references(){return[...this._references]}allocate(e,t,n=`private`){if(this._released)throw Error(`Cannot allocate on released context (ownerId: ${this.ownerId})`);let r=e,i=this._memory.allocate(r,this.ownerId,t,n);return this._references.push(i),this.runtime.eventBus.dispatch(new eu(i,t,this.runtime.nowProvider),this.runtime),i}get(e){let t=e;return this._references.find(e=>e.type===t)}getAll(e){let t=e;return this._references.filter(e=>e.type===t)}set(e,t){if(this._released)throw Error(`Cannot set on released context (ownerId: ${this.ownerId})`);let n=e.get();this._memory.set(e,t),this.runtime.eventBus.dispatch(new tu(e,t,n,this.runtime.nowProvider),this.runtime)}release(){if(!this._released){for(let e of this._references){let t=e.value();this._memory.release(e),this.runtime.eventBus.dispatch(new nu(e,t,this.runtime.nowProvider),this.runtime)}this._references=[],this._released=!0}}isReleased(){return this._released}getOrCreateAnchor(e){if(this._released)throw Error(`Cannot access anchor on released context (ownerId: ${this.ownerId})`);let t;for(let n of this.runtime.stack.blocks){let r=n.context.references.find(t=>t.id===e&&t.type===Ql.ANCHOR);if(r){t=r;break}}if(t)return this._references.find(e=>e.id===t.id)||this._references.push(t),t;let n=this._memory.allocate(Ql.ANCHOR,this.ownerId,void 0,`public`);return n.id=e,this._references.push(n),n}},iu=class{tag;_listeners=new Set;_metrics;_isDisposed=!1;constructor(e,t=la.empty()){this.tag=e,this._metrics=la.from(t,e)}get metrics(){return this._metrics}update(e){if(this._isDisposed){console.warn(`Attempted to update disposed MemoryLocation with tag '${this.tag}'`);return}let t=this._metrics;this._metrics=la.from(e,this.tag);for(let e of this._listeners)e(this._metrics,t)}subscribe(e){return this._isDisposed?(console.warn(`Attempted to subscribe to disposed MemoryLocation with tag '${this.tag}'`),()=>{}):(this._listeners.add(e),()=>this._listeners.delete(e))}dispose(){if(this._isDisposed)return;this._isDisposed=!0;let e=this._metrics;this._metrics=la.empty(this.tag);for(let t of this._listeners)t(this._metrics,e);this._listeners.clear()}},au=class{block;clock;stackLevel;runtime;subscriptions=[];_capabilities;constructor(e,t,n,r,i){this.block=e,this.clock=t,this.stackLevel=n,this.runtime=r,this._capabilities=i??new Set}get nowProvider(){return this.runtime.nowProvider}subscribe(e,t,n){let r=this,i={id:`behavior-${this.block.key.toString()}-${e}-${Date.now()}`,name:`BehaviorHandler-${this.block.label}-${e}`,handler:(e,n)=>t(e,Object.create(r,{clock:{value:n.clock,enumerable:!0,configurable:!0}}))},a=this.runtime.eventBus.register(e,i,this.block.key.toString(),{scope:n?.scope??`active`});return this.subscriptions.push({eventType:e,unsubscribe:a}),a}emitEvent(e){this.runtime.handle(e)}emitOutput(e,t,n){let r=this.clock.currentDate,i=this.block.getMemoryByTag(`time`),a=r.getTime(),o=r.getTime(),s=[];if(i.length>0){let e=i[0].metrics;if(e.length>0){let t=e[0].value;t?.spans&&t.spans.length>0&&(s=[...t.spans],a=s[0].started)}}let c=la.from(t,this.block.key.toString());if(c.length===0){let e=this.block.getMemoryByTag(`metric:display`);e.length>0&&(c=e[0].metrics.clone(this.block.key.toString()))}let l=c.map(e=>({...e,sourceBlockKey:e.sourceBlockKey??this.block.key.toString(),timestamp:e.timestamp??r})),u=new fa({outputType:e,timeSpan:new Cl(a,o),spans:s.length>0?s:void 0,sourceBlockKey:this.block.key.toString(),sourceStatementId:this.block.sourceIds?.[0],stackLevel:this.stackLevel,metrics:l,completionReason:n?.completionReason});this.addOutputToRuntime(u)}addOutputToRuntime(e){this.runtime.addOutput(e)}pushMemory(e,t){let n=new iu(e,t);return this.block.pushMemory(n),n}getMemoryByTag(e){return this.block.getMemoryByTag(e)}updateMemory(e,t){let n=this.block.getMemoryByTag(e);n.length>0&&n[0].update(t)}declareCapability(e){this._capabilities.add(e)}hasCapability(e){return this._capabilities.has(e)}getCapabilities(){return this._capabilities}markComplete(e){this.block.markComplete(e)}dispose(){for(let{unsubscribe:e}of this.subscriptions)try{e()}catch(e){this.runtime.options.logger?.error?.(`[BehaviorContext] Unsubscribe error:`,e)}this.subscriptions=[]}},hee=new Set([`metric:display`]),gee=new Set([`metric:result`]),_ee=new Set([`metric:promote`,`metric:rep-target`]),vee=new Set([`metric:tracked`,`metric:label`,`metric:next`]);function yee(e){if(hee.has(e))return`display`;if(gee.has(e))return`result`;if(_ee.has(e))return`promote`;if(vee.has(e)||e.startsWith(`metric:`))return`private`}var ou={display:`Display`,result:`Result`,promote:`Promote`,private:`Private`},su=class{behaviors=[];key;blockType;context;sourceIds;tagComposition;_memory=[];get label(){for(let e of this._memory)for(let t of e.metrics)if(t.type===q.Label)return t.image||t.value?.toString()||this.blockType||`Block`;return this.blockType||`Block`}_behaviorContext;executionTiming={};_isComplete=!1;_completionReason;_eventUnsubscribers=[];_runtime;constructor(e){let{runtime:t,sourceIds:n=[],behaviors:r=[],context:i,key:a,blockType:o,label:s,metrics:c,tagComposition:l}=e;if(this._runtime=t,this.sourceIds=n,this.behaviors=r,this.key=a??new pa,this.blockType=o,this.tagComposition=l,this.context=i??new ru(t,this.key.toString()),s&&this._memory.push(new iu(`metric:label`,[{type:q.Label,image:s,origin:`compiler`,value:s}])),c)for(let e of c)this._memory.push(new iu(`metric:display`,e))}pushMemory(e){this._memory.push(e)}mergeHints(e){if(!e||Object.keys(e).length===0)return;let t=this._memory.find(e=>e.tag===`metric:hint`),n=Object.entries(e).map(([e,t])=>({type:q.Hint,value:e,image:e,origin:`compiler`,timestamp:new Date}));if(t){let e=new Set(n.map(e=>e.value)),r=t.metrics.toArray().filter(t=>!(t.type===q.Hint&&e.has(t.value)));t.update([...r,...n])}else this._memory.push(new iu(`metric:hint`,n))}getMemoryByTag(e){return this._memory.filter(t=>t.tag===e)}getAllMemory(){return[...this._memory]}getMetricMemoryByVisibility(e){return this._memory.filter(t=>yee(t.tag)===e)}registerDefaultHandler(){}mount(e,t){this._runtime=e;let n=t?.clock??e.clock;this.executionTiming.startTime=t?.startTime??n.currentDate,this.registerDefaultHandler();let r=Math.max(0,e.stack.count-1);this._behaviorContext=new au(this,n,r,e);let i=[];for(let e of this.behaviors)if(e.onMount){let t=e.onMount(this._behaviorContext);t&&i.push(...t)}return i}inspectNext(e,t){if(!this._behaviorContext)return{complete:!1,actions:[]};let n=t?.clock??this._behaviorContext.clock,r=new au(this,n,this._behaviorContext.stackLevel,e,this._behaviorContext.getCapabilities()),i=this._isComplete,a=this._completionReason;for(let e of this.behaviors){let t=e;typeof t.prepareForNextCycle==`function`&&t.prepareForNextCycle()}let o=[];for(let e of this.behaviors)if(e.onNext){let t=e.onNext(r);t&&o.push(...t)}r.dispose(),this._isComplete&&!o.some(e=>e.type===`pop-block`)&&o.push(new Jl);let s={complete:this._isComplete,reason:this._completionReason,actions:o};return this._isComplete=i,this._completionReason=a,s}next(e,t){if(!this._behaviorContext)return Wl.logAlways(`warn`,`RuntimeBlock`,`next() called before mount()`),[];let n=t?.clock??this._behaviorContext.clock;this.emitNextSystemOutput(e,n);let r=this.inspectNext(e,t);return r.complete&&!this._isComplete&&this.markComplete(r.reason),Wl.logNext(this,[...r.actions]),r.actions}unmount(e,t){let n=t?.clock??e.clock;this.executionTiming.endTime=t?.createdAt??n.currentDate;let r=[],i=new au(this,n,this._behaviorContext?.stackLevel??0,e,this._behaviorContext?.getCapabilities());for(let e of this.behaviors)if(e.onUnmount){let t=e.onUnmount(i);t&&r.push(...t)}i.dispose();let a=e.eventBus.dispatch({name:`unmount`,timestamp:e.clock.currentDate,data:{blockKey:this.key.toString()}},e);a.length>0&&r.push(...a);for(let e of this._eventUnsubscribers)try{e()}catch(e){Wl.logAlways(`error`,`RuntimeBlock`,`Error unsubscribing event handler`,{error:e})}return this._eventUnsubscribers=[],this._behaviorContext&&=(this._behaviorContext.dispose(),void 0),r}dispose(e){let t=this._behaviorContext??new au(this,e.clock,0,e);for(let e of this.behaviors)e.onDispose&&e.onDispose(t);!this._behaviorContext&&t&&t.dispose();for(let e of this._memory)e.dispose();this._memory=[]}get isComplete(){return this._isComplete}get completionReason(){return this._completionReason}markComplete(e){this._isComplete=!0,this._completionReason=e}getBehavior(e){return this.behaviors.find(t=>t instanceof e)}emitNextSystemOutput(e,t){let n=t.currentDate,r={event:`next`,blockKey:this.key.toString(),blockLabel:this.label,actionType:`next`},i={type:q.System,image:`next: ${this.label??this.blockType??`Block`} [${this.key.toString().slice(0,8)}]`,value:r,origin:`runtime`,timestamp:n},a=new fa({outputType:`system`,timeSpan:new Cl(n.getTime(),n.getTime()),sourceBlockKey:this.key.toString(),stackLevel:e.stack.count,metrics:[i]});e.addOutput(a)}},bee=class{_blocks=[];_listeners=new Set;get blocks(){return[...this._blocks].reverse()}get count(){return this._blocks.length}get current(){if(this._blocks.length!==0)return this._blocks[this._blocks.length-1]}get keys(){return this.blocks.map(e=>e.key)}push(e){this._blocks.push(e),this.notify({type:`push`,block:e,depth:this._blocks.length,blocks:this.blocks})}pop(){let e=this._blocks.pop();return e&&this.notify({type:`pop`,block:e,depth:this._blocks.length,blocks:this.blocks}),e}clear(){for(;this._blocks.length>0;)this.pop()}subscribe(e){return this._listeners.add(e),e({type:`initial`,blocks:this.blocks}),()=>{this._listeners.delete(e)}}notify(e){for(let t of this._listeners)try{t(e)}catch(e){console.error(`Error in stack listener:`,e)}}};function cu(){if(typeof window<`u`){let e=window.__chromecast_senderClockTimeMs;if(typeof e==`function`)try{let t=e();if(Number.isFinite(t))return t}catch{}}return Date.now()}var xee=class{completionTime;wasComplete=!1;onMount(e){return[]}onNext(e){if(e.block.isComplete&&!this.wasComplete&&!this.completionTime){this.completionTime=new Date(e.clock.currentDate),this.wasComplete=!0;let t={type:q.SystemTime,image:this.completionTime.toISOString(),origin:`runtime`,value:{createdAt:this.completionTime.getTime(),timestamp:this.completionTime},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};e.pushMemory(`completion`,[t])}return[]}onUnmount(e){return[]}onDispose(e){}getCompletionTime(){return this.completionTime}},lu=`time`;function uu(e){return[new Cl(e)]}function du(e,t){return e.map((n,r)=>r===e.length-1&&n.ended===void 0?new Cl(n.started,t):n)}function fu(e,t){return[...e,new Cl(t)]}function pu(e){return e.getMemoryByTag(lu)[0]?.metrics[0]?.value}function mu(e,t){let n=e.getMemoryByTag(lu)[0]?.metrics[0],r=n?.value;if(!r||!n)return!1;let i=t(r.spans,e.clock.currentDate.getTime());return e.updateMemory(lu,[{...n,value:{...r,spans:i}}]),!0}var See=class{onMount(e){let t=e.clock.currentDate.getTime(),n=e.block.label,r={type:q.Time,image:`0:00`,origin:`runtime`,value:{spans:uu(t),direction:`up`,durationMs:void 0,label:n,role:`hidden`},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};return e.pushMemory(`time`,[r]),[]}onNext(e){return[]}onUnmount(e){let t=pu(e);return!t||t.spans.length===0||mu(e,du),[]}onDispose(e){}},hu=class{config;constructor(e={}){this.config=e}subscriptions=[];isPaused=!1;onMount(e){let t=e.clock.currentDate.getTime(),n=this.config.label??e.block.label,r=this.config.role===`hidden`?`auto`:this.config.role??`primary`;return e.pushMemory(`time`,[this.createFragment(e,{spans:uu(t),direction:`up`,durationMs:void 0,label:n,role:r})]),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||mu(t,du)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&mu(t,fu)&&(this.isPaused=!1),[]))),[]}onNext(e){return[]}onUnmount(e){return mu(e,du),[]}onDispose(e){for(let e of this.subscriptions)try{e()}catch{}this.subscriptions.length=0}createFragment(e,t){return{type:q.Time,image:`0:00`,origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}},gu=class{targetBlockKey;type=`clear-children`;constructor(e){this.targetBlockKey=e}do(e){let t=[],n=0;for(;n<20;){let r=e.stack.current;if(!r||r.key.toString()===this.targetBlockKey)break;let i=new Jl().do(e);for(let e of i)e.type!==`next`&&t.push(e);n++}return n>=20&&e.options.logger?.error?.(`[ClearChildrenAction] Max iterations reached, possible infinite loop`,Error(`Exceeded 20 pop iterations for target ${this.targetBlockKey}`)),e.stack.current?.key.toString()===this.targetBlockKey&&t.push(new Dl(void 0,e.nowProvider)),t}};function _u(e,t){let n=0;for(let r of e.spans){let e=r.ended??t;n+=e-r.started}return n}function vu(e){let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}var yu=class{current;total;sourceBlockKey;timestamp;type=q.CurrentRound;origin=`tracked`;value;image;constructor(e,t,n,r,i){this.current=e,this.total=t,this.sourceBlockKey=n,this.timestamp=r,this.value=e,this.image=i??(t===void 0?`Round ${e}`:`Round ${e} of ${t}`)}},bu=class{config;constructor(e){this.config=e}subscriptions=[];isPaused=!1;onMount(e){let t=e.clock.currentDate.getTime(),n=this.config.label??e.block.label,r=this.config.role===`hidden`?`auto`:this.config.role??`primary`,i=this.config.mode??`complete-block`;return e.pushMemory(`time`,[this.createFragment(e,{spans:uu(t),direction:`down`,durationMs:this.config.durationMs,label:n,role:r})]),this.config.durationMs<=0?(this.handleExpiry(e,i),[new gu(e.block.key.toString())]):(this.subscriptions.push(e.subscribe(`tick`,(e,t)=>i===`complete-block`&&t.block.isComplete||!this.hasExpired(t)?[]:(this.handleExpiry(t,i),[new gu(t.block.key.toString())]),{scope:`bubble`})),this.subscriptions.push(e.subscribe(`timer:reset`,(e,t)=>(i===`reset-interval`&&mu(t,(e,t)=>uu(t)),[]))),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||mu(t,du)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&mu(t,fu)&&(this.isPaused=!1),[]))),[])}onNext(e){if((this.config.mode??`complete-block`)===`complete-block`&&!e.block.isComplete&&this.hasExpired(e))return e.markComplete(`timer-expired`),[new Jl,new gu(e.block.key.toString())];if(this.config.required&&!e.block.isComplete)return e.emitEvent({name:`timer:skip-attempt`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),[];if(e.hasCapability(`childSelection`)||!this.config.restBlockFactory)return[];let t=pu(e);if(!t||t.direction!==`down`||!t.durationMs)return[];let n=this.getRemainingCountdownMs(e);return n>1e3?this.config.restBlockFactory(n,`Rest`):[]}onUnmount(e){return mu(e,du),[]}onDispose(e){for(let e of this.subscriptions)try{e()}catch{}this.subscriptions.length=0}handleExpiry(e,t){if(e.emitEvent({name:`timer:complete`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),t===`complete-block`)e.markComplete(`timer-expired`);else{if(mu(e,(e,t)=>uu(t)),e.hasCapability(`childSelection`))return;let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t){let n=new yu(t.current+1,t.total,e.block.key.toString(),e.clock.currentDate);e.updateMemory(`round`,[n])}let n=e.getMemoryByTag(`children:status`)[0],r={childIndex:0,totalChildren:n?.metrics[0]?.value?.totalChildren??0,allExecuted:!1,allCompleted:!1};n?.metrics[0]?e.updateMemory(`children:status`,[{...n.metrics[0],value:r}]):e.pushMemory(`children:status`,[{type:`status`,image:``,origin:`runtime`,value:r}])}}hasExpired(e){let t=pu(e);return!t||t.direction!==`down`||t.durationMs===void 0?!1:_u(t,e.nowProvider.nowMs())>=t.durationMs}getRemainingCountdownMs(e){let t=pu(e);if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=_u(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}createFragment(e,t){return{type:q.Time,image:xu(t.durationMs),origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}};function xu(e){if(!e||e===0)return`0:00`;let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}:${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`:`${r}:${i.toString().padStart(2,`0`)}`}var Su=class{config;_repScheme;_lastPromotedRound;constructor(e){this.config=e,this._repScheme=[...e.repScheme??[]]}get repScheme(){return this._repScheme}getRepsForRound(e){if(this._repScheme.length===0)return;let t=(e-1)%this._repScheme.length;return this._repScheme[t]}getRepsForCurrentRound(){return this._lastPromotedRound===void 0?this._repScheme[0]:this.getRepsForRound(this._lastPromotedRound)}getPromotedFragments(e,t){let n=la.empty(t.key.toString());if(this._repScheme.length>0){let r=t.getMemoryByTag(`round`)[0]?.metrics[0]?.current??1,i=this.getRepsForRound(r);i!==void 0&&n.add({type:q.Rep,image:i.toString(),origin:`compiler`,value:i,sourceBlockKey:t.key.toString(),timestamp:e.clock.currentDate})}for(let e of this.config.promotions){let r=this.findSourceFragmentInBlock(t,e);r&&n.add({...r,origin:e.origin??`compiler`})}return n}onMount(e){if(this._repScheme.length>0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0]?.current??1;this.promoteRepScheme(e,t)}return this.promoteFragments(e,this.config.promotions),[]}onNext(e){if(this._repScheme.length>0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];t&&t.current!==this._lastPromotedRound&&this.promoteRepScheme(e,t.current)}let t=this.config.promotions.filter(e=>e.enableDynamicUpdates);return this.promoteFragments(e,t),[]}onUnmount(e){return[]}onDispose(e){}promoteFragments(e,t){for(let n of t){let t=this.findSourceFragment(e,n);if(!t)continue;let r={...t,origin:n.origin??`runtime`};this.upsertPromotedFragment(e,r)}}promoteRepScheme(e,t){let n=this.getRepsForRound(t);if(n===void 0)return;this._lastPromotedRound=t;let r={type:q.Rep,image:n.toString(),origin:`runtime`,value:n,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate};e.block.getMemoryByTag(`metric:rep-target`).length>0?e.updateMemory(`metric:rep-target`,[r]):e.pushMemory(`metric:rep-target`,[r])}findSourceFragment(e,t){return this.findSourceFragmentInBlock(e.block,t)}findSourceFragmentInBlock(e,t){let n=e.getAllMemory();for(let e of n){if(e.tag===`metric:promote`||e.tag===`metric:rep-target`||t.sourceTag&&e.tag!==t.sourceTag)continue;let n=e.metrics.find(e=>e.type===t.metricType);if(n)return n}}upsertPromotedFragment(e,t){let n=e.block.getMemoryByTag(`metric:promote`);if(n.length===0){e.pushMemory(`metric:promote`,[t]);return}let r=n[0].metrics.filter(e=>e.type!==t.type);e.updateMemory(`metric:promote`,[...r,t])}},Cu=class{config;unsubscribers=[];constructor(e){this.config={mode:e.mode,onNext:e.onNext??e.mode===`immediate`,onEvents:e.onEvents??[]}}onMount(e){if(this.config.mode!==`immediate`)return[];for(let t of this.config.onEvents){let n=e.subscribe(t,(e,t)=>(t.markComplete(`event:${e.name}`),[new Jl]));this.unsubscribers.push(n)}return[]}onNext(e){return this.config.mode===`deferred`?e.block.isComplete?[new Jl]:[]:this.config.onNext?(e.block.isComplete||e.markComplete(`user-advance`),[new Jl]):[]}onUnmount(e){return[]}onDispose(e){for(let e of this.unsubscribers)e();this.unsubscribers=[]}},wu=class{config;constructor(e={}){this.config=e}onMount(e){let t=this.createStaticLabels(e),n=this.createRoundLabel(e),r=t.clone();return n&&r.add(n),r.length>0&&e.pushMemory(`display`,r.toArray()),[]}onNext(e){let t=this.createRoundLabel(e);if(!t)return[];let n=e.block.getMemoryByTag(`display`);if(n.length===0)return e.pushMemory(`display`,[t]),[];let r=n[0].metrics.filter(e=>!this.isRoundRoleFragment(e));return e.updateMemory(`display`,[...r,t]),[]}onUnmount(e){return[]}onDispose(e){}createStaticLabels(e){let t=this.config.label??e.block.label,n=this.config.subtitle,r=this.config.actionDisplay,i=la.empty(e.block.key.toString());return t&&i.add(this.createTextMetric(e,t,`label`)),n&&i.add(this.createTextMetric(e,n,`subtitle`)),r&&i.add(this.createTextMetric(e,r,`action`)),i}createRoundLabel(e){if(this.config.showRoundDisplay===!1)return;let t=e.block.getMemoryByTag(`round`)[0];if(!t||t.metrics.length===0)return;let n=t.metrics[0];if(!n||typeof n.current!=`number`)return;let r=this.formatRound(n.current,n.total);return this.createTextMetric(e,r,`round`)}createTextMetric(e,t,n){return{type:q.Text,image:t,origin:`runtime`,value:{text:t,role:n},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}formatRound(e,t){return this.config.roundFormat?this.config.roundFormat(e,t):typeof t==`number`?`Round ${e} of ${t}`:`Round ${e}`}isRoundRoleFragment(e){return e.value?.role===`round`}},Tu=class{blockKey;nextStatementIds;type=`update-next-preview`;target;payload;constructor(e,t){this.blockKey=e,this.nextStatementIds=t,this.target=e,this.payload={nextStatementIds:t}}do(e){let t=e.stack.blocks.find(e=>e.key.toString()===this.blockKey);if(!t)return[];let n=t.getMemoryByTag(`metric:next`);if(this.nextStatementIds.length===0){for(let e of n)e.update([]);return[]}let r=e.script;if(!r)return[];let i=la.empty(this.blockKey);for(let e of this.nextStatementIds){let t=r.getId(e);t&&i.merge(t.metrics)}if(i.removeByType(q.Hint),i.length===0){for(let e of n)e.update([]);return[]}return n.length>0?n[0].update(i):t.pushMemory(new iu(`metric:next`,i)),[]}},Eu=`effort-data`;oc.defaultMet;function Du(e){return!!e&&typeof e==`object`&&`effort`in e&&`met`in e&&`disciplineFactor`in e}function Ou(e){if(Du(e))return e;let t=e,n=t.baseAttributes.discipline,r=t.baseAttributes.disciplineFactor??Hc(n);return{effort:t,definition:t,slug:t.slug,label:t.label,met:t.baseAttributes.met,baseAttributes:t.baseAttributes,discipline:n,disciplineFactor:r,intensityTier:t.baseAttributes.intensityTier,modifiers:{},registrySource:t.registrySource,resolvedFrom:t.registrySource===`user`?`user`:t.registrySource===`bundled`?`bundled`:`default`,isEstimated:t.registrySource===`synthetic-unresolved`}}function ku(e){let t;for(let n of e)if(n.type===`effort-data`&&n.value&&typeof n.value==`object`){let e=Ou(n.value);t={resolved:e,effort:e.effort,origin:n.origin}}return t}var J=[0,0,0,0,0],Au=[1,0,0,0,0],ju=[0,1,0,0,0],Mu=[0,0,1,0,0],Nu=[0,0,0,1,0],Pu=[0,0,0,0,1];function Fu(e,t){return[e[0]+t[0],e[1]+t[1],e[2]+t[2],e[3]+t[3],e[4]+t[4]]}function Iu(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2],e[3]-t[3],e[4]-t[4]]}function Lu(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]}function Ru(e){return Lu(e,J)}var zu=[`L`,`M`,`T`,`C`,`E`];function Bu(e){if(Ru(e))return`dimensionless`;let t=[];for(let n=0;n<5;n++){let r=e[n];r!==0&&t.push(r===1?zu[n]:`${zu[n]}^${r}`)}return t.join(`·`)}var Vu={pace:{dim:[-1,0,1,0,0],preferredUnits:[`min/km`,`sec/km`,`min/mi`]},speed:{dim:[1,0,-1,0,0],preferredUnits:[`m/s`,`km/h`]},volume:{dim:[0,1,0,1,0],preferredUnits:[`kg`,`lb`]},power:{dim:[0,1,-1,1,0],preferredUnits:[`kg/s`,`lb/s`]},time:{dim:Mu,preferredUnits:[`min`,`s`,`h`]},mass:{dim:ju,preferredUnits:[`kg`,`lb`]},length:{dim:Au,preferredUnits:[`m`,`km`,`mi`]},count:{dim:Nu,preferredUnits:[`reps`]},energy:{dim:Pu,preferredUnits:[`cal`,`kcal`]},dimensionless:{dim:J,preferredUnits:[`pts`,`AU`,`MET`,`ratio`]}};function Hu(e){for(let[t,n]of Object.entries(Vu))if(Lu(n.dim,e))return t}var Uu={reps:{dim:Nu,metricType:`rep`,unit:`reps`},elapsed:{dim:Mu,metricType:`elapsed`,unit:`ms`},distance:{dim:Au,metricType:`distance`,unit:`m`},resistance:{dim:ju,metricType:`resistance`,unit:`kg`},segmentVolume:{dim:[0,1,0,1,0],metricType:`segmentVolume`,unit:`kg`},metMinutes:{dim:Mu,metricType:`metMinutes`,unit:`min`},effortRpe:{dim:J,metricType:`effortRpe`},metMinutesEstimated:{dim:J,metricType:`metMinutesEstimated`},sessionRpe:{dim:J,metricType:`session-rpe`},climbSend:{dim:Nu,metricType:`climb-send-type`,unit:`count`},climbGrade:{dim:J,metricType:`climb-grade`}},Wu={effort:J,effortLabel:J,sessionRpe:J,"session.duration":Mu,"profile.vo2max":J},Gu={sum:!0,max:!0,min:!0,avg:!0,count:!0,last:!0},Ku={AU:!0,pts:!0,"MET-min":!0,ratio:!0},qu=.45359237,Ju=1609.344,Yu={ms:{dim:Mu,factor:1},s:{dim:Mu,factor:1e3},sec:{dim:Mu,factor:1e3},min:{dim:Mu,factor:6e4},h:{dim:Mu,factor:36e5},hr:{dim:Mu,factor:36e5},m:{dim:Au,factor:1},km:{dim:Au,factor:1e3},mi:{dim:Au,factor:Ju},kg:{dim:ju,factor:1},lb:{dim:ju,factor:qu},lbs:{dim:ju,factor:qu},rep:{dim:Nu,factor:1},reps:{dim:Nu,factor:1},cal:{dim:Pu,factor:1},kcal:{dim:Pu,factor:1e3},MET:{dim:J,factor:1},"%":{dim:J,factor:1},rating:{dim:J,factor:1},bpm:{dim:J,factor:1},count:{dim:Nu,factor:1},"m/s":{dim:[1,0,-1,0,0],factor:.001},"km/h":{dim:[1,0,-1,0,0],factor:1e3/36e5},"sec/km":{dim:[-1,0,1,0,0],factor:1},"min/km":{dim:[-1,0,1,0,0],factor:60},"min/mi":{dim:[-1,0,1,0,0],factor:6e4/Ju},"reps/min":{dim:[0,0,-1,1,0],factor:1/6e4},"kg/s":{dim:[0,1,-1,1,0],factor:.001},"lb/s":{dim:[0,1,-1,1,0],factor:qu/1e3}};function Xu(e){let t=Yu[e];if(t)return t;if(Ku[e])return{dim:J,factor:1}}function Zu(e,t,n){let r=Yu[n];if(!r)throw new Qu(`Unknown unit: ${n}`);if(!t)return e/r.factor;let i=Yu[t];if(!i)throw new Qu(`Unknown unit: ${t}`);if(!Lu(i.dim,r.dim))throw new Qu(`Cannot convert from ${t} to ${n}: dimension mismatch`);return e*i.factor/r.factor}var Qu=class extends Error{constructor(e){super(e),this.name=`CalcUnitError`}};function $u(e,t,n,r,i){if(Lu(i,J))return e&&!n?e:n&&!e?n:Lu(t,r)?e??n:void 0;let a=[];for(let[i,o]of[[e,t],[n,r]])!i||Lu(o,J)||a.push(i);let o=a.filter(e=>!Lu(Yu[e]?.dim??J,Nu)),s=o.length>0?o:a;return s.length>0?s.join(`·`):void 0}function ed(e,t,n,r){if(!Lu(r,J)){if(!t||Lu(n,J))return e;if(e)return`${e}/${t}`}}var td={kind:`absent`};function nd(e,t=J,n){return{kind:`number`,value:e,dim:t,unit:n}}function rd(e){return{kind:`string`,value:e}}function id(e){return e.kind===`number`?e.value!==0:e.kind===`string`?e.value.length>0:e.kind===`series`?e.points.size>0:e.kind===`period`&&e.days>0}var ad=class extends Error{constructor(e){super(e),this.name=`CalcEvalError`}};function od(e,t){switch(e.kind){case`literal`:return nd(e.value);case`period`:return{kind:`period`,days:e.days};case`string`:return rd(e.value);case`ref`:return t.resolveRef(e.name);case`filter`:throw new ad(`Exclusion filter is only valid as an aggregate argument`);case`wql`:if(!t.resolveWql)throw new ad(`WQL atom ${e.aggregator}:${e.metric} is store-scope only`);return t.resolveWql(e);case`unary`:{let n=od(e.arg,t);if(e.op===`not`)return nd(+!id(n));if(n.kind===`absent`)return td;if(n.kind!==`number`)throw new ad(`Unary minus requires a number`);return nd(-n.value,n.dim,n.unit)}case`binary`:return sd(e,t);case`call`:return dd(e,t)}}function sd(e,t){let{op:n}=e;if(n===`and`)return id(od(e.left,t))?nd(+!!id(od(e.right,t))):nd(0);if(n===`or`)return id(od(e.left,t))?nd(1):nd(+!!id(od(e.right,t)));let r=od(e.left,t),i=od(e.right,t);if(r.kind===`series`||i.kind===`series`)return cd(n,r,i);if(n===`==`||n===`!=`){let e=ld(r,i);return nd(n===`==`?+!!e:+!e)}if(r.kind===`absent`||i.kind===`absent`)return n===`<`||n===`<=`||n===`>`||n===`>=`?nd(0):td;if(r.kind!==`number`||i.kind!==`number`)throw new ad(`Operator '${n}' requires numbers`);switch(n){case`+`:case`-`:if(!Lu(r.dim,i.dim))throw new ad(`Dimension mismatch for '${n}': ${Bu(r.dim)} vs ${Bu(i.dim)}`);return nd(n===`+`?r.value+i.value:r.value-i.value,r.dim,r.unit??i.unit);case`*`:{let e=Fu(r.dim,i.dim);return nd(r.value*i.value,e,$u(r.unit,r.dim,i.unit,i.dim,e))}case`/`:{if(i.value===0)return td;let e=Iu(r.dim,i.dim);return nd(r.value/i.value,e,ed(r.unit,i.unit,i.dim,e))}case`<`:return nd(+(ud(r)<ud(i)));case`<=`:return nd(+(ud(r)<=ud(i)));case`>`:return nd(+(ud(r)>ud(i)));case`>=`:return nd(+(ud(r)>=ud(i)))}}function cd(e,t,n){if(e===`and`||e===`or`||e===`==`||e===`!=`||e===`<`||e===`<=`||e===`>`||e===`>=`)throw new ad(`Operator '${e}' is not defined on series`);if(t.kind===`absent`||n.kind===`absent`)return td;let r=t.kind===`series`?t:void 0,i=n.kind===`series`?n:void 0,a=e=>e.kind===`number`?e.value:void 0;if(!r&&a(t)===void 0||!i&&a(n)===void 0)throw new ad(`Operator '${e}' requires numbers or series`);let o=a(t),s=a(n),c=t.kind===`number`||t.kind===`series`?t.dim:void 0,l=n.kind===`number`||n.kind===`series`?n.dim:void 0;if((e===`+`||e===`-`)&&c&&l&&!Lu(c,l))throw new ad(`Dimension mismatch for '${e}': ${Bu(c)} vs ${Bu(l)}`);let u=e===`*`?Fu(c??J,l??J):e===`/`?Iu(c??J,l??J):c??l??J,d=(t,n)=>{switch(e){case`+`:return t+n;case`-`:return t-n;case`*`:return t*n;case`/`:return n===0?void 0:t/n;default:return}},f=new Map,p=r??i;for(let[e,t]of p.points){let n=r?t:o,a=i?i.points.get(e):s;if(a===void 0)continue;let c=d(n,a);c!==void 0&&Number.isFinite(c)&&f.set(e,c)}return{kind:`series`,points:f,dim:u}}function ld(e,t){return e.kind===`absent`||t.kind===`absent`?e.kind===t.kind:e.kind===`string`||t.kind===`string`?e.kind===`string`&&t.kind===`string`&&e.value===t.value:e.kind!==`number`||t.kind!==`number`?e.kind===t.kind:Lu(e.dim,t.dim)?ud(e)===ud(t):!1}function ud(e){if(!e.unit)return e.value;let t=Yu[e.unit];return t?e.value*t.factor:e.value}function dd(e,t){let{name:n,args:r}=e;if(n===`has`){if(r.length!==1)throw new ad(`has() takes one argument`);return nd(od(r[0],t).kind===`absent`?0:1)}if(n===`convert`){if(r.length!==2)throw new ad(`convert() takes (value, targetUnit)`);let e=md(r[1]),n=od(r[0],t);if(n.kind===`absent`)return td;if(n.kind!==`number`)throw new ad(`convert() requires a number`);let i=Yu[e];if(!i)throw new ad(`Unknown unit: ${e}`);if(!Lu(n.dim,i.dim))throw new ad(`convert() dimension mismatch: ${Bu(n.dim)} is not ${Bu(i.dim)}`);return nd(Zu(n.value,n.unit,e),i.dim,e)}let i=r.map(e=>e.kind===`filter`?td:od(e,t));if(fd[n]&&(r[0]?.kind===`ref`||r[0]?.kind===`filter`)){let e=t.callFunction?.(n,i,r);if(e!==void 0)return e}if(n===`windowMean`||n===`windowSum`||n===`windowSd`){let[e,t]=i;if(e?.kind===`absent`)return td;if(e?.kind!==`series`||t?.kind!==`period`)throw new ad(`${n}() takes (series, period)`);return pd(n,e,t.days)}if(n===`windowEwma`){let[e,t]=i;if(e?.kind===`absent`)return td;if(e?.kind!==`series`||t?.kind!==`period`)throw new ad(`windowEwma() takes (series, period)`);let n=1/t.days,r=0,a=new Map;for(let t of[...e.points.keys()].sort((e,t)=>e-t))r+=((e.points.get(t)??0)-r)*n,a.set(t,r);return{kind:`series`,points:a,dim:e.dim,unit:e.unit}}if(i[0]?.kind===`series`&&(n===`sum`||n===`mean`||n===`min`||n===`max`||n===`last`)){let e=i[0],t=[...e.points.values()];if(t.length===0)return td;switch(n){case`sum`:return nd(t.reduce((e,t)=>e+t,0),e.dim,e.unit);case`mean`:return nd(t.reduce((e,t)=>e+t,0)/t.length,e.dim,e.unit);case`min`:return nd(Math.min(...t),e.dim,e.unit);case`max`:return nd(Math.max(...t),e.dim,e.unit);case`last`:return nd(t[t.length-1],e.dim,e.unit)}}switch(n){case`min`:case`max`:{let e=hd(n,i);if(e.length===0)return td;let t=e.reduce((e,t)=>(n===`min`?ud(t)<ud(e):ud(t)>ud(e))?t:e);return nd(t.value,t.dim,t.unit)}case`abs`:{let[e]=hd(n,i,1);return nd(Math.abs(e.value),e.dim,e.unit)}case`round`:{let[e,t]=hd(n,i),r=10**(t?t.value:0);return nd(Math.round(e.value*r)/r,e.dim,e.unit)}case`floor`:{let[e]=hd(n,i,1);return nd(Math.floor(e.value),e.dim,e.unit)}case`ceil`:{let[e]=hd(n,i,1);return nd(Math.ceil(e.value),e.dim,e.unit)}case`clamp`:{let[e,t,r]=hd(n,i,3);return nd(Math.min(Math.max(e.value,t.value),r.value),e.dim,e.unit)}}let a=t.callFunction?.(n,i,r);if(a!==void 0)return a;throw new ad(`Unknown function: ${n}`)}var fd={sum:!0,max:!0,min:!0,avg:!0,count:!0,last:!0};function pd(e,t,n){let r=e=>t.points.get(e)??0,i=new Map;for(let a of t.points.keys()){let t=0;for(let e=0;e<n;e++)t+=r(a-e);if(e===`windowSum`){i.set(a,t);continue}let o=t/n;if(e===`windowMean`){i.set(a,o);continue}let s=0;for(let e=0;e<n;e++){let t=r(a-e)-o;s+=t*t}i.set(a,Math.sqrt(s/n))}return{kind:`series`,points:i,dim:t.dim,unit:t.unit}}function md(e){if(e.kind===`ref`)return e.name;if(e.kind===`string`)return e.value;throw new ad(`convert() target unit must be a unit name`)}function hd(e,t,n){let r=[];for(let n of t)if(n.kind!==`absent`){if(n.kind!==`number`)throw new ad(`${e}() requires numeric arguments`);r.push(n)}if(n!==void 0&&(t.length!==n||r.length!==n))throw new ad(`${e}() needs ${n} numeric argument(s), got ${r.length}`);return r}var gd=class extends Error{pos;constructor(e,t){super(`${e} (at ${t})`),this.pos=t,this.name=`CalcParseError`}},_d=/[A-Za-z_]/,vd=/[A-Za-z0-9_.]/;function yd(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===` `||r===` `||r===`
19
19
  `||r===`\r`){n++;continue}if(r>=`0`&&r<=`9`||r===`.`&&e[n+1]>=`0`&&e[n+1]<=`9`){let r=/^\d*\.?\d+/.exec(e.slice(n)),i=n+r[0].length;if(e[i]===`d`&&!(i+1<e.length&&vd.test(e[i+1]))){t.push({t:`period`,v:parseFloat(r[0]),pos:n}),n=i+1;continue}t.push({t:`num`,v:parseFloat(r[0]),pos:n}),n=i;continue}if(r===`"`||r===`'`){let i=e.indexOf(r,n+1);if(i<0)throw new gd(`Unterminated string literal`,n);t.push({t:`str`,v:e.slice(n+1,i),pos:n}),n=i+1;continue}if(r===`{`){let r=e.indexOf(`}`,n+1);if(r<0)throw new gd(`Unterminated filter braces`,n);t.push({t:`brace`,v:e.slice(n+1,r),pos:n}),n=r+1;continue}if(_d.test(r)){let r=n+1;for(;r<e.length&&vd.test(e[r]);)r++;let i=e.slice(n,r);if(i===`without`){let i=/^\s*:\s*([^,)]+)/.exec(e.slice(r));if(i){t.push({t:`filter`,v:i[1].trim(),pos:n}),n=r+i[0].length;continue}}t.push({t:`ident`,v:i,pos:n}),n=r;continue}let i=e.slice(n,n+2);if(i===`==`||i===`!=`||i===`<=`||i===`>=`||i===`->`){t.push({t:`op`,v:i,pos:n}),n+=2;continue}if(`+-*/()<>=,:`.includes(r)){t.push({t:`op`,v:r,pos:n}),n++;continue}throw new gd(`Unexpected character '${r}'`,n)}return t.push({t:`eof`,pos:e.length}),t}var bd={or:1,and:2,"==":3,"!=":3,"<":3,"<=":3,">":3,">=":3,"+":4,"-":4,"*":5,"/":5},xd=class{tokens;pos=0;constructor(e){this.tokens=e}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}isOp(e){let t=this.peek();return t.t===`op`&&t.v===e}isIdent(e){let t=this.peek();return t.t===`ident`&&t.v===e}parseTop(){let e=this.parseExpression(),t=this.peek();if(t.t!==`eof`)throw new gd(`Unexpected trailing input`,t.pos);return e}expectOp(e){let t=this.next();if(t.t!==`op`||t.v!==e)throw new gd(`Expected '${e}'`,t.pos);return t}binaryOp(){let e=this.peek(),t=e.t===`op`||e.t===`ident`&&(e.v===`and`||e.v===`or`)?e.v:void 0;if(t===void 0)return;let n=bd[t];return n===void 0?void 0:{op:t,prec:n}}parseExpression(e=1){let t=this.parseUnary();for(;;){let n=this.binaryOp();if(!n||n.prec<e)return t;this.next();let r=this.parseExpression(n.prec+1);t={kind:`binary`,op:n.op,left:t,right:r}}}parseUnary(){let e=this.peek();return e.t===`op`&&e.v===`-`?(this.next(),{kind:`unary`,op:`-`,arg:this.parseUnary()}):e.t===`ident`&&e.v===`not`?(this.next(),{kind:`unary`,op:`not`,arg:this.parseUnary()}):this.parsePrimary()}parsePrimary(){let e=this.next();if(e.t===`num`)return{kind:`literal`,value:e.v};if(e.t===`period`)return{kind:`period`,days:e.v};if(e.t===`str`)return{kind:`string`,value:e.v};if(e.t===`op`&&e.v===`(`){let e=this.parseExpression();return this.expectOp(`)`),e}if(e.t===`op`&&e.v===`:`)throw new gd(`Unexpected ':'`,e.pos);if(e.t===`ident`){if(this.isOp(`:`)){this.next();let t=this.next();if(t.t!==`ident`)throw new gd(`Expected metric name after aggregator`,t.pos);let n,r,i=this.peek();if(i.t===`brace`&&(n=i.v,this.next()),this.isIdent(`by`)){this.next();let e=this.next();if(e.t!==`brace`)throw new gd(`Expected '{dims}' after 'by'`,e.pos);r=e.v.split(`,`).map(e=>e.trim()).filter(Boolean)}return{kind:`wql`,aggregator:e.v,metric:t.v,filters:n,groupBy:r}}if(this.isOp(`(`)){this.next();let t=[];if(this.isOp(`)`))this.next();else for(;;){t.push(this.parseArg());let e=this.next();if(e.t!==`op`||e.v!==`,`){if(e.t===`op`&&e.v===`)`)break;throw new gd(`Expected ',' or ')' in argument list`,e.pos)}}return{kind:`call`,name:e.v,args:t}}return{kind:`ref`,name:e.v}}throw new gd(`Expected expression`,e.pos)}parseArg(){let e=this.peek();return e.t===`filter`?(this.next(),{kind:`filter`,value:e.v}):this.parseExpression()}};function Sd(e){return new xd(yd(e)).parseTop()}function Cd(e){let t=yd(e),n=-1,r=-1,i=0;for(let e=0;e<t.length;e++){let a=t[e];if(a.t===`op`&&a.v===`(`)i++;else if(a.t===`op`&&a.v===`)`)i--;else if(i===0&&a.t===`op`&&a.v===`->`&&n<0)n=e;else if(i===0&&a.t===`ident`&&a.v===`when`){r=e;break}}let a=n>=0?t[n].pos:r>=0?t[r].pos:e.length,o=e.slice(0,a).trim(),s,c;if(n>=0){let i=r>=0?t[r].pos:e.length;s=e.slice(t[n].pos+2,i).trim()}return r>=0&&(c=e.slice(t[r].pos+4).trim()),{head:o,unit:s||void 0,when:c||void 0}}function wd(e){let{head:t,unit:n,when:r}=Cd(e),i=t.indexOf(`=`);if(i<0)throw new gd(`Expected '=' in calc line`,0);let a=t.slice(0,i).trim();if(!a)throw new gd(`Missing calc name`,0);let o=t.slice(i+1).trim();if(!o)throw new gd(`Missing expression`,i+1);return{name:a,expr:Sd(o),unit:n,when:r?Sd(r):void 0}}var Td=/^(segment|workout|store)\b/;function Ed(e,t){let n=[],r=[],i=t?.scope,a=t?.fences,o;for(let s of e.split(/\r?\n/)){let e=s.trim();if(!e||e.startsWith(`#`))continue;let c=Td.exec(e);if(c&&/^(on\s|when\s|:)/.test(e.slice(c[0].length).trim())){i=c[1];let t=Dd(e.slice(c[0].length).trim());a=t.fences,o=t.when;continue}n.push(Rd(e,i??t?.scope??`segment`,a,o,r))}return{defs:n,warnings:r}}function Dd(e){let t=e.replace(/^\s*:/,``).trim(),n,r=/^on\s*\[([^\]]*)\]/.exec(t);r&&(n=r[1].split(`,`).map(e=>e.trim()).filter(Boolean),t=t.slice(r[0].length).trim());let i,a=/^when\s+([\s\S]+)$/.exec(t);return a&&(i=a[1].replace(/:\s*$/,``).trim()),{fences:n,when:i}}function Od(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===` `||r===` `){n++;continue}if(r===`"`){let r=n+1;for(;r<e.length&&e[r]!==`"`;)r++;t.push({pos:n,word:e.slice(n+1,r),isStr:!0}),n=r<e.length?r+1:r;continue}let i=e.slice(n,n+2);if(i===`->`||i===`==`||i===`!=`||i===`<=`||i===`>=`){t.push({pos:n,op:i}),n+=2;continue}if(`(),[]{}|=<:`.includes(r)){t.push({pos:n,op:r}),n++;continue}if(/[0-9A-Za-z_.]/.test(r)){let r=n+1;for(;r<e.length&&/[0-9A-Za-z_.]/.test(e[r]);)r++;t.push({pos:n,word:e.slice(n,r)}),n=r;continue}n++}return t}function kd(e,t){let n=[],r=0,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===`"`){i=!i;continue}i||(o===`(`||o===`[`||o===`{`?r++:o===`)`||o===`]`||o===`}`?r--:r===0&&e.startsWith(t,a)&&(n.push(a),a+=t.length-1))}return n}function Ad(e,t){let n=Od(e),r=[],i=0;for(let e of n)e.op===`(`?i++:e.op===`)`?i--:i===0&&e.word&&t.includes(e.word)&&r.push(e.pos);return r}function jd(e){let t=kd(e,`|`),n=Ad(e,[`where`]).find(e=>!t.length||e>t[t.length-1]),r=n??e.length,i=e.slice(0,t.length?t[0]:r).trim(),a=[];for(let n=0;n<t.length;n++){let i=t[n]+1,o=n+1<t.length?t[n+1]:r;a.push(e.slice(i,o).trim())}return{primary:i,variants:a,where:n===void 0?void 0:e.slice(n+5).trim()}}var Md=[`when`,`key`,`label`,`emit`,`meta`,`estimated`];function Nd(e){let t=kd(e,`->`),n=Ad(e,Md),r=e.length;t.length&&t[0]<r&&(r=t[0]);for(let e of n)e<r&&(r=e);let i=e.slice(0,r).trim(),a=e.slice(r).trim(),o,s={};if(a.startsWith(`->`)){let e=a.slice(2).trim(),t=/(?:^|\s)(when|key|label|emit|meta|estimated)\b/.exec(e),n=t?t.index+ +(t[0][0]===` `):e.length;o=e.slice(0,n).trim()||void 0,a=e.slice(n).trim()}for(;a=a.trim(),a;){let e=/^(when|key|label|emit|meta|estimated)\b([\s\S]*)$/.exec(a);if(!e)break;let t=e[1],n=e[2].trim(),r=/^(when|key|label|emit|meta|estimated)\b/.exec(n);s[t]=(r?n.slice(0,r.index):n).trim(),a=n.slice(r?r.index:n.length)}return{expr:i,unit:o,clauses:s}}function Pd(e){let t=[],n=0,r=0,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===`"`){i=!i;continue}if(!i){if(o===`(`||o===`[`||o===`{`)r++;else if(o===`)`||o===`]`||o===`}`)r--;else if(r===0&&o===`,`){t.push(e.slice(n,a)),n=a+1;continue}r===0&&e.startsWith(`where`,a)&&!/[A-Za-z0-9_.]/.test(e[a-1]??``)&&!/[A-Za-z0-9_.]/.test(e[a+5]??``)&&(t.push(e.slice(n,a)),n=a+5,a+=4)}}return t.push(e.slice(n)),t.map(e=>e.trim()).filter(Boolean)}function Fd(e){let t=[];for(let n of Pd(e)){let e=kd(n,`->`),r=n,i;e.length&&(r=n.slice(0,e[0]).trim(),i=n.slice(e[0]+2).trim()||void 0);let a=Od(r).find(e=>e.op===`=`);if(!a)throw new gd(`Invalid where binding: ${n}`,0);t.push({name:r.slice(0,a.pos).trim(),expr:r.slice(a.pos+1).trim(),unit:i})}return t}function Id(e,t){let n=Ad(e,[`when`])[0],r=e,i;n!==void 0&&(i=e.slice(n+4).trim(),r=e.slice(0,n).trim());let a=/\bestimated\b/.test(r),o=r.replace(/\bestimated\b/g,``).trim();if(!o)return{when:i,estimated:a,expr:t};let{expr:s,unit:c}=Nd(o);return{expr:s,unit:c,when:i,estimated:a}}function Ld(e,t,n,r,i,a,o){let s={};s.value={id:`value`,kind:`expr`,expression:r,...i?{unit:i}:{}};for(let e of a)s[e.name]={id:e.name,kind:`expr`,expression:e.expr,...e.unit?{unit:e.unit}:{}};let c={id:e,priority:t,origin:n,nodes:s};return o&&(c.when=o),c}function Rd(e,t,n,r,i){let a=/\(library\)/.exec(e),o=!!a,s=o?e.slice(0,a.index)+` `+e.slice(a.index+a[0].length):e,c=Od(s).find(e=>e.op===`=`);if(!c)throw new gd(`Missing '=' in calc line: ${e}`,0);let l=s.slice(0,c.pos).trim();if(!l)throw new gd(`Missing calc name`,0);let{primary:u,variants:d,where:f}=jd(s.slice(c.pos+1).trim()),{expr:p,unit:m,clauses:h}=Nd(u),g=f?Fd(f):[];Sd(p);for(let e of g)Sd(e.expr);h.when&&Sd(h.when);let _=h.when,v=d.length>0,y=[],b=h.estimated===void 0?`analyzed`:`analyzed-estimated`,x=b===`analyzed-estimated`?10:100,S=v?_:void 0;y.push(Ld(`default`,x,b,p,m,g,S??void 0)),d.forEach((e,t)=>{let n=Id(e,p),r=n.estimated?`est-${t+1}`:`alt-${t+1}`,i=t===0?50:10;y.push(Ld(r,i,n.estimated?`analyzed-estimated`:`analyzed`,n.expr??p,n.unit??(t===0?m:void 0),g,n.when))});let C;if(!o){if(C={nodeId:`value`,...m?{unit:m}:{}},h.key){let e=zd(h.key);C.key=e.key,e.grouped&&(C.isGrouped=!0,C.groupBy=e.groupBy)}h.label&&(C.label=h.label.replace(/^"|"$/g,``)),h.emit&&(C.emitType=h.emit),h.meta&&(C.publishMetadataNodes=h.meta.split(`,`).map(e=>e.trim()).filter(Boolean))}let w=v?r:_??r,T={id:l,kind:o?`library`:`output`,scope:t,variants:y,...n&&n.length?{fences:n}:{},...w?{when:w}:{}};return C&&(T.output=C),T}function zd(e){let t=/by\s*\{([^}]*)\}/.exec(e),n=e.includes(`grouped`)||!!t,r=t?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):void 0;return{key:e.split(/\s+/).find(e=>e!==`grouped`&&!/^by$/.test(e)&&!e.startsWith(`{`)&&!e.startsWith(`by`))??e,grouped:n,groupBy:r}}function Bd(e){let t=e.output?.nodeId;return Array.isArray(t)?t[0]:t}var Vd={statement:6,tag:5,effort:4,equipment:3,note:2,category:1},Hd={parser:!0,dialect:!0,"user-plan":!0,runtime:!0,execution:!0,tracked:!0,user:!0,collected:!0};function Ud(e,t,n){let r={},i={};for(let[t,n]of Object.entries(e)){let e=t.trim();if(e.startsWith(`metrics.`)){let t=e.slice(8).trim();t&&Wd(n)&&(r[t]=n)}else if(e===`metrics`&&Gd(n))for(let[e,t]of Object.entries(n))Wd(t)&&(r[e.trim()]=t);else if(e.startsWith(`summaries.`)){let t=e.slice(10).trim();t&&(typeof n==`string`||typeof n==`number`)&&(i[t]=String(n))}else if(e===`summaries`&&Gd(n))for(let[e,t]of Object.entries(n))(typeof t==`string`||typeof t==`number`)&&(i[e.trim()]=String(t))}return{layer:t,sourceSlug:n,metrics:r,summaries:i}}function Wd(e){return typeof e==`number`?Number.isFinite(e):typeof e==`string`?e.trim().length>0:Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Gd(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Kd(e,t){if(!e||t.length===0)return[];let n=[];for(let r of t){let t=po(e,r);if(t.metrics.length===0)continue;let i={},a={},o={},s={};for(let n of t.tags){let t=e.resolve(n);if(!t)continue;let r=t.isCategory?o:i,c=t.isCategory?s:a;for(let e of t.contributions){if(e.kind!==`metric`)continue;let t=e.type.trim();if(t){if(t.startsWith(`summaries.`)){let n=t.slice(10).trim();n&&!(n in c)&&(c[n]=String(e.value))}else t in r||(r[t]=e.unit?`${String(e.value)} ${e.unit}`:e.value===null||typeof e.value==`boolean`?String(e.value):e.value)}}}(Object.keys(i).length>0||Object.keys(a).length>0)&&n.push({layer:`tag`,sourceSlug:r,metrics:i,summaries:a}),(Object.keys(o).length>0||Object.keys(s).length>0)&&n.push({layer:`category`,sourceSlug:r,metrics:o,summaries:s})}return n}var qd={note:6,tag:5,effort:4,equipment:3,category:1};function Jd(e){let t=[...e].sort((e,t)=>qd[t.layer]-qd[e.layer]),n=new Map;for(let e of t)if(e.summaries)for(let[t,r]of Object.entries(e.summaries)){let e=t.trim(),i=r.trim();!e||!i||n.has(e)||n.set(e,i)}let r=new Map;for(let e of t)if(e.metrics)for(let[t,n]of Object.entries(e.metrics)){let i=Xd(t,n,e.layer,e.sourceSlug);!i||r.has(i.key)||(i.kind===`static`?r.set(i.key,i.dim):r.set(i.key,nf(i.ast,r)))}let i=[];for(let[e,t]of n)try{let n=[...Yd(wd(`summary = ${t}`).expr)].filter(e=>!r.has(e)&&Uu[e]===void 0&&Wu[e]===void 0);for(let e of n)r.set(e,J);n.length>0&&i.push({id:e,message:`Summary ${e}: missing ${[...new Set(n)].join(`, `)}`})}catch{}let a=Object.fromEntries(r),o=[];for(let[e,t]of n){let n=t.includes(`=`)?t:`${e} = ${t}`;try{let t=Ed(n,{scope:`workout`});for(let n of t.defs)o.push({...n,customAtoms:a,output:{nodeId:n.output?.nodeId??`value`,key:n.output?.key??e,emitType:n.output?.emitType??e,unit:n.output?.unit??`auto`,...n.output?.isGrouped?{isGrouped:!0,groupBy:n.output.groupBy}:{},...n.output?.label?{label:n.output.label}:{}}})}catch{}}return{defs:o,diagnostics:i}}function Yd(e,t=new Set){if(!e)return t;switch(e.kind){case`ref`:return t.add(e.name),t;case`unary`:return Yd(e.arg,t);case`binary`:return Yd(e.left,t),Yd(e.right,t);case`call`:if(e.name===`has`)return t;if(e.name===`convert`)return e.args[0]&&Yd(e.args[0],t),t;if(e.name===`lookup`)return e.args[1]&&Yd(e.args[1],t),t;for(let n of e.args)n.kind!==`filter`&&Yd(n,t);return t;default:return t}}function Xd(e,t,n,r){let i=e.trim();if(!i)return;if(typeof t==`number`)return{kind:`static`,key:i,value:t,dim:Uu[i]?.dim??J,layer:n,sourceSlug:r};if(Array.isArray(t))return{kind:`static`,key:i,value:t,dim:J,layer:n,sourceSlug:r};let a=String(t).trim();if(!a)return;let o=Number(a);if(!Number.isNaN(o)&&/^[+-]?\d+(?:\.\d+)?$/.test(a))return{kind:`static`,key:i,value:o,dim:Uu[i]?.dim??J,layer:n,sourceSlug:r};let s=a.match(/^([+-]?\d+(?:\.\d+)?)\s*([A-Za-z%/][\w%/.-]*)$/);if(s){let e=Number(s[1]),t=s[2],a=Xu(t);if(!Number.isNaN(e)&&(a||/^(kg|lb|m|km|mi|s|min|h|ms|reps|cal|bpm|W|pts|AU|%)$/i.test(t)))return{kind:`static`,key:i,value:e,unit:t,dim:a?.dim??Uu[i]?.dim??J,layer:n,sourceSlug:r}}if(i===`effort`||i===`equipment`)return{kind:`static`,key:i,value:a,dim:J,layer:n,sourceSlug:r};try{let e=wd(`${i} = ${a}`),t=e.when,o=Yd(e.expr);return t&&Yd(t,o),o.delete(i),{kind:`equation`,key:i,expression:a,ast:e.expr,unit:e.unit,whenAst:t,dependencies:[...o],layer:n,sourceSlug:r}}catch{return{kind:`static`,key:i,value:a,dim:J,layer:n,sourceSlug:r}}}function Zd(e){return e===`reps`?q.Rep:e===`distance`?q.Distance:e===`resistance`?q.Resistance:e===`elapsed`?q.Elapsed:e===`effort`?q.Effort:e===`equipment`?q.Equipment:e}function Qd(e,t,n,r){let i=Zd(t),a=e.rawMetrics;if(t===`reps`){let e=0,t=!1;for(let n of a)if(n.type===q.Rep||n.type===`reps`){let r=$d(n);r!==void 0&&(e+=r,t=!0)}return t?nd(e,Uu.reps.dim,`reps`):td}for(let e=a.length-1;e>=0;e--){let r=a[e];if(r.type!==i&&r.type!==t&&r.name!==t)continue;let o=$d(r);if(o!==void 0){let e=ef(r)??Uu[t]?.unit;return nd(o,n.get(t)??(e&&Yu[e]?Yu[e].dim:void 0)??Uu[t]?.dim??J,e)}if(typeof r.value==`string`&&r.value.length>0)return rd(r.value)}return t===`effort`&&r?rd(r):td}function $d(e){if(typeof e.value==`number`&&!Number.isNaN(e.value))return e.value;let t=e.value;if(t&&typeof t==`object`&&`amount`in t&&typeof t.amount==`number`)return t.amount}function ef(e){let t=e.value;return t&&typeof t==`object`&&`units`in t&&typeof t.units==`string`?t.units:e.unit}function tf(e,t){let n=Zd(t);return e.rawMetrics.some(e=>(e.type===n||e.type===t||e.name===t)&&Hd[e.origin]===!0)}function nf(e,t){switch(e.kind){case`ref`:return t.get(e.name)??Uu[e.name]?.dim??Wu[e.name]??J;case`unary`:return e.op===`not`?J:nf(e.arg,t);case`binary`:return e.op===`*`?Fu(nf(e.left,t),nf(e.right,t)):e.op===`/`?Iu(nf(e.left,t),nf(e.right,t)):e.op===`+`||e.op===`-`?nf(e.left,t):J;case`call`:if(e.name===`convert`&&e.args[1]){let n=e.args[1].kind===`ref`?e.args[1].name:e.args[1].kind===`string`?e.args[1].value:void 0;return(n?Xu(n)?.dim:void 0)??nf(e.args[0],t)}return e.args[0]?nf(e.args[0],t):J;default:return J}}function rf(e,t){let n=[...t.sources].sort((e,t)=>Vd[t.layer]-Vd[e.layer]),r=new Map;for(let e of n)if(e.metrics)for(let[t,n]of Object.entries(e.metrics)){let i=Xd(t,n,e.layer,e.sourceSlug);i&&(r.has(i.key)||r.set(i.key,i))}let i=t.stage===`plan`?`compiler`:`analyzed`,a=new Map,o=[],s=[];for(let t of r.values())if(!tf(e,t.key)){if(t.kind===`static`){a.set(t.key,t.dim);let n=Zd(t.key);e.add({type:n,name:t.key,value:t.value,...t.unit?{unit:t.unit}:{},image:t.unit?`${String(t.value)} ${t.unit}`:String(t.value),origin:i,metadata:{canonicalKey:t.key,sourceLayer:t.layer,sourceSlug:t.sourceSlug}}),o.push(t.key)}else s.push(t)}let c=new Set(s),l=new Set,u=new Set,d=()=>({resolveRef:n=>Qd(e,n,a,t.lastEffortSlug),callFunction:(e,n,r)=>{if(e===`lookup`&&t.lookups)return t.lookups.callFunction(e,n,r)}}),f=!0;for(;f&&c.size>0;){f=!1;for(let t of[...c]){let n=d();if(t.dependencies.filter(e=>n.resolveRef(e).kind===`absent`).length>0)continue;if(t.whenAst&&!id(od(t.whenAst,n))){c.delete(t),l.add(t),f=!0;continue}let r=od(t.ast,n);if(r.kind!==`number`){c.delete(t),u.add(t),f=!0;continue}let s=r.dim;t.unit&&Ku[t.unit]?s=J:s.every(e=>e===0)&&(s=nf(t.ast,a)),a.set(t.key,s);let p=!t.unit||t.unit===`auto`?r.unit:t.unit,m=Zd(t.key);e.add({type:m,name:t.key,value:r.value,...p?{unit:p}:{},image:p?`${r.value} ${p}`:String(r.value),origin:i,metadata:{canonicalKey:t.key,sourceLayer:t.layer,sourceSlug:t.sourceSlug,expression:t.expression}}),c.delete(t),o.push(t.key),f=!0}}let p=[],m=[],h=d(),g=(n,r)=>{if(t.emitDiagnostics===!1)return;let i={target:n.key,expression:n.expression,sourceLayer:n.layer,sourceSlug:n.sourceSlug,missing:r};m.push(i),e.add({type:q.Diagnostic,name:`diagnostic.${n.key}`,value:`Skipped ${n.key}: ${r.length>0?`missing ${r.join(`, `)}`:`expression could not be evaluated`}`,image:`Skipped ${n.key} (${r.length>0?`missing ${r.join(`, `)}`:`expression could not be evaluated`})`,origin:`diagnostic`,metadata:{diagnostic:`skipped-dependency`,target:n.key,expression:n.expression,sourceLayer:n.layer,sourceSlug:n.sourceSlug,missing:r}})};for(let e of c){if(l.has(e))continue;let n=e.dependencies.filter(e=>h.resolveRef(e).kind===`absent`);if(n.length!==0){if(t.stage===`plan`){p.push(e.key);continue}g(e,n)}}for(let e of u){if(t.stage===`plan`){p.push(e.key);continue}g(e,[])}return{resolved:o,deferredRuntime:p,diagnostics:m,inferredDims:Object.fromEntries(a)}}var af=e=>console.log(e);function of(e,t){let{resolver:n,references:r,overwrite:i=!1,debug:a=!1,propertySources:o}=t;sf(e,n,r,i,a,o)}function sf(e,t,n,r,i,a){let o=e.blockType?.toLowerCase();if(o!==`effort`&&o!==`exercise`)return;let s=e.label;if(!s){i&&af(`[EffortEnrichment] Skipping block with no label: ${e.key}`);return}if(e.getAllMemory().find(e=>e.metrics.toArray().some(e=>e.type===`effort-data`))&&!r){i&&af(`[EffortEnrichment] Skipping block already enriched: ${s}`);return}try{let o,c=`none`,l=[],u=[];if(n){let e=n.resolve(s);o=e.effort??void 0,c=e.matched,l=e.equipment,u=e.diagnostics}else o=t.resolveEffort(s);if(!o){u.length>0&&e.pushMemory(new iu(`metric:tracked`,[{type:q.Hint,value:`reference.unresolved`,image:s,origin:`compiler`,metadata:{[ra]:{matched:`none`,source:s,diagnostics:u}}}])),i&&af(`[EffortEnrichment] Unresolved effort: ${s}`);return}let d=o.effort.hints;d&&Object.keys(d).length>0&&e.mergeHints(d),i&&af(`[EffortEnrichment] Resolved effort: ${s} → ${o.label} (MET: ${o.met})`);let f={type:Eu,image:o.label,value:o,origin:`compiler`,timestamp:new Date,...l.length>0||u.length>0?{metadata:{[ra]:{matched:c,source:s,refs:[{kind:`effort`,slug:o.slug,label:o.label},...l],...u.length>0?{diagnostics:u}:{}}}}:{}},p=e.getMetricMemoryByVisibility(`private`).find(e=>e.metrics.toArray().some(e=>e.type===Eu));if(p&&r){let e=p.metrics.toArray().filter(e=>e.type!==Eu);e.push(f),p.update(e)}else if(!p){let t=new iu(`metric:tracked`,[f]);e.pushMemory(t)}if(l.length>0&&cf(e,q.Equipment,[new ms(l.map(e=>e.slug),{refs:l,source:s,origin:`compiler`})],q.Equipment,r),a&&a.length>0){let t=e.getAllMemory().find(e=>e.tag===`metric:tracked`);t&&rf(t.metrics,{stage:`plan`,sources:a,lastEffortSlug:o.slug})}}catch(e){console.error(`[EffortEnrichment] Failed to resolve effort "${s}":`,e)}}function cf(e,t,n,r,i){let a=e.getMetricMemoryByVisibility(`private`).find(e=>e.metrics.toArray().some(e=>e.type===t));if(a&&i){let e=a.metrics.toArray().filter(e=>e.type!==r);a.update([...e,...n])}else a||e.pushMemory(new iu(`metric:tracked`,n))}var lf=class{statementIds;options;type=`compile-and-push-block`;constructor(e,t={}){this.statementIds=e,this.options=t}do(e){if(!this.statementIds||this.statementIds.length===0)return[];let t=e.script.getIds(this.statementIds);if(t.length===0)return[];try{let n=e.jit.compile(t,e);return n?(e.analyticsContext?.effortResolver&&of(n,{resolver:e.analyticsContext.effortResolver,references:e.analyticsContext.references}),[new ql(n,this.options)]):[]}catch(t){return e.options.logger?.error?.(`CompileAndPushBlockAction: Compilation failed`,t),[]}}},uf=class{durationMs;label;type=`push-rest-block`;constructor(e,t=`Rest`){this.durationMs=e,this.label=t}do(e){return[new ql(new Mf(e,{durationMs:this.durationMs,label:this.label}))]}},df=class e{config;static DEFAULT_MIN_REST_MS=1e3;childIndex=0;dispatchedOnLastNext=!1;restState=`idle`;constructor(e){this.config=e}onMount(e){this.restState=`idle`,this.dispatchedOnLastNext=!1,e.declareCapability(`childSelection`);let t=[];if(this.config.startRound!==void 0){let t=e.block.key.toString();e.pushMemory(`round`,[new yu(this.config.startRound,this.config.totalRounds,t,e.clock.currentDate)])}if(this.config.injectRest&&e.subscribe(`timer:complete`,(t,n)=>{if(this.restState!==`idle`)return[];let r=this.advanceRound(e);return this.childIndex=0,this.restState=`idle`,this.writeChildrenStatus(e),r},{scope:`active`}),this.config.skipOnMount)return this.totalChildren>0&&t.push(this.createNextPreview(e,this.config.childGroups[0])),this.writeChildrenStatus(e),t;if(this.totalChildren===0)return this.writeChildrenStatus(e),t;let n=this.dispatchNext(e);return this.writeChildrenStatus(e),[...t,...n]}onNext(e){if(this.dispatchedOnLastNext=!1,e.block.isComplete){let t=[this.createNextPreview(e)];return this.writeChildrenStatus(e),t}let t=[];if(this.config.startRound!==void 0){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t?.total!==void 0&&t.current>t.total)return e.markComplete(`rounds-exhausted`),this.writeChildrenStatus(e),[new Jl]}if(this.restState===`active`&&(this.restState=`idle`,this.config.injectRest&&(t.push(...this.advanceRound(e)),this.childIndex=0,e.emitEvent({name:`timer:reset`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}))),this.childIndex>=this.totalChildren){if(!this.shouldLoop(e))return this.writeChildrenStatus(e),e.markComplete(this.isLoopEnabled()?`rounds-exhausted`:`children-complete`),[this.createNextPreview(e)];if(this.shouldInjectRest(e)){this.restState=`pending`;let n=[new uf(this.getRemainingCountdownMs(e),`Rest`),this.createNextPreview(e,this.config.childGroups[0])];return this.restState=`active`,this.writeChildrenStatus(e),[...t,...n]}t.push(...this.advanceRound(e)),this.childIndex=0}let n=this.dispatchNext(e);return this.writeChildrenStatus(e),[...t,...n]}onUnmount(e){return[]}onDispose(e){this.restState=`idle`}get allChildrenExecuted(){return this.childIndex>=this.totalChildren}get allChildrenCompleted(){return this.allChildrenExecuted&&!this.dispatchedOnLastNext}get totalChildren(){return this.config.childGroups.length}dispatchNext(e){if(this.childIndex>=this.totalChildren)return[this.createNextPreview(e)];let t=this.config.childGroups[this.childIndex];this.childIndex++,this.dispatchedOnLastNext=!0;let n=this.config.childGroups[this.childIndex];return[new lf(t),this.createNextPreview(e,n)]}shouldLoop(e){if(e.block.isComplete||!this.isLoopEnabled())return!1;let t=this.getLoopCondition();if(t===`always`)return!0;if(t===`timer-active`){let t=e.getMemoryByTag(`time`)[0]?.metrics[0]?.value;return t?t.direction===`down`&&t.durationMs?this.getRemainingCountdownMs(e)>0:!0:!1}let n=e.getMemoryByTag(`round`)[0]?.metrics[0];return n?n.total===void 0||n.current<n.total:!1}shouldInjectRest(t){if(!this.config.injectRest)return!1;let n=t.getMemoryByTag(`time`)[0]?.metrics[0]?.value;if(!n||n.direction!==`down`||!n.durationMs)return!1;let r=this.getRemainingCountdownMs(t);return!(r<e.DEFAULT_MIN_REST_MS||r>=n.durationMs)}getRemainingCountdownMs(e){let t=e.getMemoryByTag(`time`)[0]?.metrics[0]?.value;if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=_u(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}writeChildrenStatus(e){let t={childIndex:this.childIndex,totalChildren:this.totalChildren,allExecuted:this.allChildrenExecuted,allCompleted:this.allChildrenCompleted},n=e.getMemoryByTag(`children:status`)[0];n?.metrics[0]?e.updateMemory(`children:status`,[{...n.metrics[0],value:t}]):e.pushMemory(`children:status`,[{type:`status`,image:``,origin:`runtime`,value:t}])}advanceRound(e){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(!t)return[];if(t.total!==void 0&&t.current>=t.total)return e.markComplete(`rounds-exhausted`),[];let n=e.block.key.toString(),r=t.current+1,i=t.total,a=new yu(r,i,n,e.clock.currentDate);return e.updateMemory(`round`,[a]),[]}createNextPreview(e,t){return new Tu(e.block.key.toString(),t??[])}isLoopEnabled(){return this.config.loop===void 0?!1:typeof this.config.loop!=`boolean`||this.config.loop}getLoopCondition(){return typeof this.config.loop==`object`&&this.config.loop.condition?this.config.loop.condition:`timer-active`}},ff=class{value;sourceBlockKey;timestamp;type=q.Elapsed;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return vu(this.value)}},pf=class{value;sourceBlockKey;timestamp;type=q.Total;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return vu(this.value)}},mf=class e{spans;sourceBlockKey;timestamp;type=q.Spans;origin=`tracked`;constructor(e,t,n){this.spans=e,this.sourceBlockKey=t,this.timestamp=n}get value(){return this.spans}get image(){if(this.spans.length===0)return`--:--`;if(this.spans.length===1){let t=this.spans[0];return t.started===t.ended?e.formatTimestamp(t.started):`${e.formatTimestamp(t.started)} – ${e.formatTimestamp(t.ended??Date.now())}`}return`${this.spans.length} spans`}get isOpen(){return this.spans.length!==0&&this.spans[this.spans.length-1].isOpen}static formatTimestamp(e){let t=new Date(e);return`${t.getHours().toString().padStart(2,`0`)}:${t.getMinutes().toString().padStart(2,`0`)}:${t.getSeconds().toString().padStart(2,`0`)}`}},hf=class{value;sourceBlockKey;type=q.SystemTime;origin=`tracked`;constructor(e,t){this.value=e,this.sourceBlockKey=t}get timestamp(){return this.value}get image(){return this.value.toISOString()}},gf=class{config;_now;lastEmittedRound;constructor(e={},t=El){this.config=e,this._now=t}onMount(e){if(this.config.emitSegmentOnMount??!1){let t=this.collectDisplayFragments(e),n=this.collectStateFragments(e),r=this.mergeFragments(t,n);e.emitOutput(`segment`,r.toArray(),{label:this.formatLabel(e)})}let t=e.getMemoryByTag(`round`)[0]?.metrics[0];return(this.config.emitMilestones??!!t)&&t&&(t.total===void 0||t.total>1)&&(this.lastEmittedRound=t.current,e.emitOutput(`milestone`,this.buildMilestoneFragments(e,t).toArray(),{label:this.formatRoundLabel(t)})),[]}onNext(e){let t=e.getMemoryByTag(`round`)[0]?.metrics[0];return!(this.config.emitMilestones??!!t)||!t||t.total!==void 0&&t.total<=1||t.total!==void 0&&t.current>t.total||this.lastEmittedRound!==void 0&&t.current===this.lastEmittedRound?[]:(this.lastEmittedRound=t.current,e.emitOutput(`milestone`,this.buildMilestoneFragments(e,t).toArray(),{label:this.formatRoundLabel(t)}),[])}onUnmount(e){let t=pu(e),n=e.getMemoryByTag(`round`)[0]?.metrics[0],r=this.config.computeTimeResults??!0,i=this.config.label??`Completed`;if(this.config.label||(e.block.blockType===`SessionRoot`?i=`Session Completed`:n&&n.total!==void 0&&n.total>1?i=`Completed ${n.total} Round(s)`:n&&n.current>1&&(i=`Completed ${n.current} Round(s)`)),r){let n=e.block.getMemoryByTag(`metric:display`);if(n.length>1){let r=this.computeSplitTimeResults(e,t,n.map(e=>e.metrics),i);return this.writeResultGroups(e,r),[]}}let a=r?this.computeTimeResults(e,t,i):la.from([new hf(this._now.now(),e.block.key.toString())],e.block.key.toString());return this.writeResultMemory(e,a),[]}onDispose(e){}collectDisplayFragments(e){let t=la.empty(e.block.key.toString());for(let n of e.block.getMemoryByTag(`metric:display`))t.merge(n.metrics);return t}collectStateFragments(e){let t=la.empty(e.block.key.toString());for(let n of e.block.getMemoryByTag(`round`))t.merge(n.metrics);for(let n of e.block.getMemoryByTag(`time`))t.merge(n.metrics);return t}mergeFragments(e,t){let n=new Set(e.map(e=>`${e.type}:${e.type}`)),r=t.filter(e=>!n.has(`${e.type}:${e.type}`));return e.clone().add(...r)}buildMilestoneFragments(e,t){let n=la.empty(e.block.key.toString()).add(new yu(t.current,t.total,e.block.key.toString(),e.clock.currentDate)),r=pu(e);if(r){let t=_u(r,e.clock.currentDate.getTime());n.add(new ff(t,e.block.key.toString(),e.clock.currentDate)),r.spans.length>0&&n.add(new mf([...r.spans],e.block.key.toString(),e.clock.currentDate))}return n}computeTimeResults(e,t,n){let r=e.clock.currentDate,i=r.getTime(),a=e.block.key.toString(),o=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t&&t.spans.length>0){let e=_u(t,i),s=t.spans[0].started,c=t.spans[t.spans.length-1].ended??i,l=Math.max(0,c-s),u=la.empty(a).add(new ff(e,a,r),new pf(l,a,r),new mf([...t.spans],a,r),new hf(this._now.now(),a));return o&&u.add(new yu(o.current,o.total,a,r,n)),u}let s=new Cl(i,i),c=la.empty(a).add(new ff(0,a,r),new pf(0,a,r),new mf([s],a,r),new hf(this._now.now(),a));return o&&c.add(new yu(o.current,o.total,a,r,n)),c}computeSplitTimeResults(e,t,n,r){let i=e.clock.currentDate,a=i.getTime(),o=e.block.key.toString(),s=e.getMemoryByTag(`round`)[0]?.metrics[0];if(!t||t.spans.length===0)return n.map(e=>{let t=e.clone().add(new ff(0,o,i),new pf(0,o,i),new mf([new Cl(a,a)],o,i),new hf(this._now.now(),o));return s&&t.add(new yu(s.current,s.total,o,i,r)),t});let c=_u(t,a),l=t.spans[0].started,u=(t.spans[t.spans.length-1].ended??a)-l,d=n.map(e=>{let t=e.filter(e=>e.type===q.Rep&&typeof e.value==`number`).reduce((e,t)=>e+t.value,0);return t>0?t:1}),f=d.reduce((e,t)=>e+t,0),p=0;return n.map((e,t)=>{let n=d[t]/f,a=Math.round(c*n),m=Math.round(u*n),h=l+p,g=h+m;p+=m;let _=e.clone().add(new ff(a,o,i),new pf(m,o,i),new mf([new Cl(h,g)],o,i),new hf(this._now.now(),o));return s&&_.add(new yu(s.current,s.total,o,i,r)),_})}writeResultMemory(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length>0){let r=_f(n);r.length>0&&(t=t.clone().add(...r)),e.updateMemory(`metric:result`,t.toArray());return}e.pushMemory(`metric:result`,t.toArray())}writeResultGroups(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length===0){for(let n of t)e.pushMemory(`metric:result`,n.toArray());return}let r=Math.max(n.length,t.length);for(let i=0;i<r;i++){let r=t[i]?t[i].clone():n[i].metrics.clone(),a=t[i]&&i<n.length?_f([n[i]]):[],o=r.add(...a);i<n.length?n[i].update(o):e.pushMemory(`metric:result`,o.toArray())}}formatLabel(e){return this.config.label??e.block.label}formatRoundLabel(e){return e.total===void 0?`Round ${e.current}`:`Round ${e.current} of ${e.total}`}};function _f(e){let t=[];for(let n of e)for(let e of n.metrics)e.origin===`user`&&t.push(e);return t}var vf=class{sound;trigger;type=q.Sound;origin;value;image;constructor(e,t,n={}){this.sound=e,this.trigger=t,this.origin=n.origin??`tracked`,this.value={sound:e,trigger:t,atSecond:n.atSecond},this.image=n.atSecond===void 0?e:`${e}@${n.atSecond}s`}};function yf(e){let t=e.trim();if(t.length===0)return;let n,r;t.startsWith(`-`)?(n=`end`,r=t.slice(1)):(n=`start`,r=t),r.startsWith(`:`)&&(r=r.slice(1));let i=bf(r);if(i!==void 0)return{anchor:n,offsetMs:i}}function bf(e){let t=e.trim().replace(/^:/,``);if(t.length===0)return 0;if(!/^\d+(:\d+)*$/.test(t))return;let n=t.split(`:`).map(Number).reverse(),[r=0,i=0,a=0,o=0]=n;if(!(n.length>4)&&!(i>59||a>59))return((o*24+a)*60+i)*6e4+r*1e3}function xf(e,t){return e.rules.filter(e=>{let{anchor:n,offsetMs:r}=e.trigger;return n===`start`||r===0||t!==void 0&&r<=t})}var Sf={id:`default`,name:`Default`,rules:[{trigger:{anchor:`end`,offsetMs:3e3},sound:`countdown-beep`},{trigger:{anchor:`end`,offsetMs:2e3},sound:`countdown-beep`},{trigger:{anchor:`end`,offsetMs:1e3},sound:`countdown-beep`},{trigger:{anchor:`end`,offsetMs:0},sound:`timer-complete`}]},Cf=`sound:play`,wf=class{config;rules=[];fired=new Set;durationMs;constructor(e){this.config=e}onMount(e){let t=pu(e);return this.durationMs=t?.durationMs,this.rules=xf(this.config.profile,this.durationMs),this.fireDue(e,0,this.durationMs),e.subscribe(`tick`,(e,t)=>{let n=this.elapsedMs(t);return n===void 0||this.fireDue(t,n,this.durationMs),[]},{scope:`bubble`}),[]}onNext(e){return[]}onUnmount(e){return this.fireDue(e,this.elapsedMs(e)??0,this.durationMs,!0),[]}onDispose(e){this.fired.clear()}elapsedMs(e){let t=pu(e);if(t)return _u(t,e.clock.currentDate.getTime())}fireDue(e,t,n,r=!1){let i=n===void 0?void 0:Math.max(0,n-t);this.rules.forEach((n,a)=>{if(this.fired.has(a))return;let{anchor:o,offsetMs:s}=n.trigger;(o===`start`?t>=s:s===0?r||i!==void 0&&i<=0:i!==void 0&&i<=s)&&(this.fired.add(a),this.play(e,n,o,s))})}play(e,t,n,r){let i=n===`start`?r===0?`mount`:`countdown`:r===0?`complete`:`countdown`;e.emitOutput(`system`,[new vf(t.sound,i,{atSecond:r/1e3})],{label:`Sound: ${t.sound}`}),e.emitEvent({name:Cf,timestamp:e.clock.currentDate,data:{sound:t.sound,volume:1}})}},Tf=class{config;constructor(e){this.config=e}onMount(e){let t=la.from(this.config.buttons.map(t=>({type:q.Action,image:t.label,origin:`runtime`,value:{id:t.id,label:t.label,variant:t.variant,visible:t.visible,enabled:t.enabled,eventName:t.eventName},sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate})),e.block.key.toString());return t.length>0&&e.pushMemory(`controls`,t.toArray()),[]}onNext(e){return[]}onUnmount(e){return e.updateMemory(`controls`,[]),[]}onDispose(e){}static updateButton(e,t,n){let r=e.block.getMemoryByTag(`controls`);if(r.length===0)return;let i=r[0].metrics.map(e=>{let r=e.value;return r.id===t?{...e,value:{...r,...n}}:e});e.updateMemory(`controls`,i)}},Ef=class e extends su{constructor(t){let n=new pa(`waiting-to-start`),r=new ru(t,n.toString(),`WaitingToStart`),i=e.buildBehaviors();super({runtime:t,sourceIds:[],behaviors:i,context:r,key:n,blockType:`WaitingToStart`,label:`Ready to Start`})}static buildBehaviors(){let e=[];return e.push(new gf({label:`Ready to Start`,emitSegmentOnMount:!0})),e.push(new wu({mode:`clock`,label:`Ready to Start`})),e.push(new Tf({buttons:[{id:`start`,label:`Start Workout`,variant:`primary`,visible:!0,enabled:!0,eventName:`next`}]})),e.push(new Cu({mode:`immediate`,onNext:!0})),e}mount(e,t){return super.mount(e,t)}unmount(e,t){return super.unmount(e,t)}dispose(e){super.dispose(e),this.context&&this.context.release()}},Df=class{runtime;constructor(e){this.runtime=e}onMount(e){return[new ql(new Ef(this.runtime))]}onNext(e){return[]}onUnmount(e){return[]}onDispose(e){}},Of=q.Sound;function kf(e,t){let n=Af(e);if(n){let e=jf(t?.profiles,n);if(e)return e}if(t?.noteProfileId){let e=jf(t?.profiles,t.noteProfileId);if(e)return e}return Sf}function Af(e){for(let t of e){let e=t.metrics.find(e=>e.type===Of);if(!e)continue;let n=e.value;if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function jf(e,t){if(e)return e.find(e=>e.id===t)}var Mf=class e extends su{constructor(t,n){if(n.durationMs<0)throw RangeError(`RestBlock durationMs must be >= 0, got: ${n.durationMs}`);let r=n.label??`Rest`,i=new pa(`rest`),a=new ru(t,i.toString(),`Rest`),o=e.buildBehaviors(n,t.options?.soundOptions);super({runtime:t,sourceIds:[],behaviors:o,context:a,key:i,blockType:`Rest`,label:r})}static buildBehaviors(e,t){let n=[],r=e.label??`Rest`;return n.push(new gf({label:r})),n.push(new bu({durationMs:e.durationMs,label:r,role:`primary`,mode:`complete-block`})),n.push(new Cu({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})),n.push(new wu({mode:`timer`,label:r})),n.push(new wf({profile:kf([],t)})),n}mount(e,t){return super.mount(e,t)}unmount(e,t){return super.unmount(e,t)}dispose(e){super.dispose(e),this.context&&this.context.release()}},Nf=class{runtime;behaviors=new Map;context;key;label=``;blockType=`Block`;metrics;sourceIds=[];tagComposition=[];pendingRoundConfig;declaredExitMode;constructor(e){this.runtime=e}addBehavior(e){return this.behaviors.set(e.constructor,e),this}addBehaviorIfMissing(e){return this.behaviors.has(e.constructor)||this.behaviors.set(e.constructor,e),this}removeBehavior(e){return this.behaviors.delete(e),this}moveBehaviorLast(e){let t=this.behaviors.get(e);return t?(this.behaviors.delete(e),this.behaviors.set(e,t),this):this}hasBehavior(e){return this.behaviors.has(e)}declareExit(e){return(e===`deferred`||this.declaredExitMode===void 0)&&(this.declaredExitMode=e),this}get exitMode(){return this.declaredExitMode}getBehavior(e){return this.behaviors.get(e)}setContext(e){return this.context=e,this}setKey(e){return this.key=e,this}setLabel(e){return this.label=e,this}setBlockType(e){return this.blockType=e,this}setFragments(e){return this.metrics=e.map(e=>{let t=la.from(e);return t.removeByType(q.Hint),t}),this}setSourceIds(e){return this.sourceIds=e,this}setTagComposition(e){return this.tagComposition=e,this}getLabel(){return this.label}getBlockType(){return this.blockType}getFragments(){return this.metrics}getSourceIds(){return this.sourceIds}getContext(){return this.context}getKey(){return this.key}asTimer(e){if(e.direction===`down`&&e.durationMs){let t=e.completionConfig?.completesBlock===!1?`reset-interval`:`complete-block`;this.addBehavior(new bu({durationMs:e.durationMs,label:e.label,role:e.role,mode:t,required:e.required,restBlockFactory:e.injectRest?(e,t)=>[new ql(new Mf(this.runtime,{durationMs:e,label:t}))]:void 0}))}else this.addBehavior(new hu({label:e.label,role:e.role}));return this}hasRoundConfig(){return this.pendingRoundConfig!==void 0}hasTimerBehavior(){return this.behaviors.has(bu)||this.behaviors.has(hu)||this.behaviors.has(See)}asRepeater(e){return this.pendingRoundConfig={totalRounds:e.totalRounds,startRound:e.startRound??1,addCompletion:e.addCompletion},this}asContainer(e){let t=this.pendingRoundConfig;return this.addBehavior(new df({childGroups:e.childGroups,loop:e.addLoop?{condition:e.loopConfig?.condition??`timer-active`}:!1,injectRest:e.injectRest,skipOnMount:e.skipOnMount,startRound:t?.startRound,totalRounds:t?.totalRounds})),this}build(){if(!this.context)throw Error(`BlockContext is required`);if(!this.key)throw Error(`BlockKey is required`);this.addBehaviorIfMissing(new xee),this.declaredExitMode&&(this.removeBehavior(Cu),this.addBehavior(new Cu(this.declaredExitMode===`immediate`?{mode:`immediate`,onNext:!0}:{mode:`deferred`}))),this.moveBehaviorLast(Su);let e=new su({runtime:this.runtime,sourceIds:this.sourceIds,tagComposition:this.tagComposition,behaviors:Array.from(this.behaviors.values()),context:this.context,key:this.key,blockType:this.blockType});if(this.metrics&&this.metrics.length>0)for(let t of this.metrics)e.pushMemory(new iu(`metric:display`,t));return this.label&&e.pushMemory(new iu(`metric:label`,[{type:q.Label,image:this.label,origin:`compiler`,value:this.label}])),e}};function Pf(e){return typeof e==`object`&&!!e&&`getPromotedFragments`in e&&typeof e.getPromotedFragments==`function`}var Ff=class{resolvePromotions(e,t){if(!e)return{promotedFragments:[],hasPromotions:!1};let n=e.getMetricMemoryByVisibility(`promote`).flatMap(e=>e.metrics.toArray());for(let r of e.behaviors){if(!Pf(r))continue;let i=r.getPromotedFragments(t,e);for(let e of i){let t=n.findIndex(t=>t.type===e.type);t===-1?n.push(e):n[t]=e}}return{promotedFragments:n,hasPromotions:n.length>0}}},If=class{strategies;_promotionResolver;constructor(e=[],t){this.strategies=e,this._promotionResolver=t??new Ff}registerStrategy(e){this.strategies.push(e)}compile(e,t){if(e.length===0)return;let n=e,r=t.stack?.current,i=this._promotionResolver.resolvePromotions(r,t);if(i.hasPromotions){let e=i.promotedFragments;n=n.map(t=>{let n=Object.create(Object.getPrototypeOf(t));return Object.assign(n,t),n.metrics=t.metrics.clone(t.id).add(...e),n})}let a=this.strategies.filter(e=>e.match(n,t)).sort((e,t)=>(t.priority||0)-(e.priority||0));if(a.length===0)return;let o=new Nf(t),s=[];for(let e of n)lo(e.metrics,s);o.setTagComposition(s);for(let e of a)e.apply(o,n,t);try{return o.build()}catch{return}}},Lf=class{handlersByEvent=new Map;callbacksByEvent=new Map;register(e,t,n,r={}){let{priority:i=0,scope:a=`active`}=r,o=[...this.handlersByEvent.get(e)??[],{handler:t,ownerId:n,priority:i,scope:a}];return o.sort((e,t)=>t.priority-e.priority),this.handlersByEvent.set(e,o),()=>this.unregisterById(t.id)}on(e,t,n){let r=C(),i=this.callbacksByEvent.get(e)??[];return i.push({id:r,callback:t,ownerId:n}),this.callbacksByEvent.set(e,i),()=>this.unregisterById(r)}unregisterById(e){for(let[t,n]of this.handlersByEvent.entries()){let r=n.filter(t=>t.handler.id!==e);r.length===0?this.handlersByEvent.delete(t):this.handlersByEvent.set(t,r)}for(let[t,n]of this.callbacksByEvent.entries()){let r=n.filter(t=>t.id!==e);r.length===0?this.callbacksByEvent.delete(t):this.callbacksByEvent.set(t,r)}}unregisterByOwner(e){for(let[t,n]of this.handlersByEvent.entries()){let r=n.filter(t=>t.ownerId!==e);r.length===0?this.handlersByEvent.delete(t):this.handlersByEvent.set(t,r)}for(let[t,n]of this.callbacksByEvent.entries()){let r=n.filter(t=>t.ownerId!==e);r.length===0?this.callbacksByEvent.delete(t):this.callbacksByEvent.set(t,r)}}dispatch(e,t){let n=[...this.callbacksByEvent.get(`*`)??[],...this.callbacksByEvent.get(e.name)??[]];for(let r of n)try{r.callback(e,t)}catch(t){console.error(`EventBus callback error for ${e.name}:`,t)}let r=t.stack.current?.key.toString(),i=new Set(t.stack.keys.map(e=>e.toString())),a=[...this.handlersByEvent.get(`*`)??[],...this.handlersByEvent.get(e.name)??[]].filter(e=>{switch(e.scope){case`global`:return!0;case`bubble`:return i.has(e.ownerId);default:return e.ownerId===r}}),o=[];for(let n of a)try{let r=n.handler.handler(e,t);r&&r.length>0&&o.push(...r)}catch(t){console.error(`EventBus handler error for ${e.name}:`,t)}return Wl.logEvent(e,o),o}emit(e,t){t.handle(e)}dispose(){this.handlersByEvent.clear(),this.callbacksByEvent.clear()}},Rf=class e extends su{constructor(t,n){let r=n.label??`Session`,i=new pa(`session-root`),a=new ru(t,i.toString(),`Session`),o=e.buildBehaviors(n,t);super({runtime:t,sourceIds:n.childGroups.flat(),behaviors:o,context:a,key:i,blockType:`SessionRoot`,label:r})}static buildBehaviors(e,t){let n=[],r=e.totalRounds??1,i=e.label??`Session`;return n.push(new hu({label:i,role:`auto`})),n.push(new df({childGroups:e.childGroups,loop:r>1&&{condition:`rounds-remaining`},skipOnMount:!0,startRound:1,totalRounds:r})),n.push(new Df(t)),n.push(new gf({label:i})),n.push(new wu({mode:`clock`,label:i})),n.push(new Tf({buttons:[{id:`pause`,label:`Pause`,variant:`secondary`,visible:!0,enabled:!0,eventName:`timer:pause`},{id:`next`,label:`Next`,variant:`primary`,visible:!0,enabled:!0,eventName:`next`},{id:`stop`,label:`Stop`,variant:`danger`,visible:!0,enabled:!0,eventName:`workout:stop`}]})),n}mount(e,t){return super.mount(e,t)}unmount(e,t){return super.unmount(e,t)}dispose(e){super.dispose(e),this.context&&this.context.release()}},zf=class{priority=100;id=`session-root`;match(e,t){return!1}apply(e,t,n){}build(e,t){return new Rf(e,t)}buildFromStatements(e,t,n){let r={childGroups:Hf(t),label:n?.label,totalRounds:n?.totalRounds};return this.build(e,r)}};function Bf(e){let t=e.metrics;return(!e.children||e.children.length===0)&&!t.some(e=>e.type===q.Effort)&&!t.some(e=>e.type===q.Duration)&&!t.some(e=>e.type===q.Rounds)&&!t.some(e=>e.type===q.Rep)&&t.some(e=>e.type===q.Resistance||e.type===q.Distance)}function Vf(e){return!!e.children&&e.children.length>0||e.metrics.some(e=>e.type===q.Rounds)||e.metrics.some(e=>e.type===q.Duration)}function Hf(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(Bf(r)&&n+1<e.length){let i=e[n+1];if(Vf(i)){t.push([i.id,r.id]),n+=2;continue}}t.push([r.id]),n++}return t}var Uf=class{options;type=`start-session`;constructor(e={}){this.options=e}do(e){if(e.stack.count>0)return console.warn(`[StartSessionAction] Session already started - stack is not empty`),[];let t=e.script?.statements;if(!t||t.length===0)return console.warn(`[StartSessionAction] No statements in script to start`),[];let n=new Set;for(let e of t)if(e.children)for(let t of e.children)for(let e of t)n.add(e);let r={childGroups:Hf(t.filter(e=>!n.has(e.id))),label:this.options.label,totalRounds:this.options.totalRounds};return[new ql(new zf().build(e,r),{startTime:e.clock.currentDate,...this.options.lifecycle})]}},Wf=class{realtimeProcessors=[];summaryProcessors=[];outputHistory=[];_onLiveOutput;_lastLiveProjectionSignature;setLiveOutputEmitter(e){this._onLiveOutput=e}addRealtimeProcessor(e){this.realtimeProcessors.push(e)}addSummaryProcessor(e){this.summaryProcessors.push(e)}run(e){let t=e;for(let e of this.realtimeProcessors)try{t=e.process(t)}catch(t){console.error(`[AnalyticsEngine] realtime error in '${e.id}':`,t)}if(t.outputType===`segment`&&(this.outputHistory.push(t),this._onLiveOutput)){let e=Date.now(),t=this._runSummaries(),n=this._projectionSignature(t);if(n!==this._lastLiveProjectionSignature){this._lastLiveProjectionSignature=n;let r=this._buildProjectionOutputs(t,e);this._onLiveOutput(r)}}return t}finalize(){let e=this._runSummaries(),t=this._buildProjectionOutputs(e,Date.now()),n=this._projectionSignature(e);return this._lastLiveProjectionSignature!==void 0&&this._lastLiveProjectionSignature===n?[]:t}_projectionSignature(e){return JSON.stringify(e.map(e=>({name:e.name,value:e.value,unit:e.unit,metricType:e.metricType})))}_buildProjectionOutputs(e,t){return e.map(e=>{let n=la.empty(`projection-${e.name}`).add({type:q.Label,image:e.name,value:e.name,origin:e.origin??`analyzed`,timestamp:new Date(t)},{type:e.metricType||q.Metric,image:`${e.value} ${e.unit}`,value:e.value,unit:e.unit,origin:e.origin??`analyzed`,timestamp:new Date(t),...e.metadata?{metadata:e.metadata}:{}});return new fa({outputType:`analytics`,timeSpan:{started:t,ended:t},sourceBlockKey:`analytics-summary`,stackLevel:0,metrics:n})})}_runSummaries(){let e=[];for(let t of this.summaryProcessors)try{e.push(...t.summarize(this.outputHistory))}catch(e){console.error(`[AnalyticsEngine] summary error in '${t.id}':`,e)}return e}},Gf=class{resolver;id=`two-pass-effort-resolution`;fenceTypes=[`time`,`log`];constructor(e){this.resolver=e}process(e){let t=e.getMetric(q.Effort),n=e.getMetric(q.Action),r,i=`analyzed`;if(t&&typeof t.value==`string`?(r=t.value,i=t.origin===`compiler`?`compiler`:`analyzed`):n&&typeof n.value==`string`&&(r=n.value,i=`analyzed`),!r)return e;let{resolved:a,finalOrigin:o}=this.resolve(r,i),s={type:Eu,image:a.label,value:a,origin:o,timestamp:new Date},c=e.metrics.toArray(),l=[],u=!1;for(let e of c)l.push(e),!u&&(e.type===q.Effort||e.type===q.Action)&&(l.push(s),u=!0);u||l.push(s),e.metrics.clear();for(let t of l)e.metrics.add(t);return e}resolve(e,t){let n;if(t===`compiler`&&(n=this.resolver.resolveBySlug(e)??this.resolver.resolveByAlias(e),n))return{resolved:this.resolver.resolveDefinition(n),finalOrigin:`compiler`};let r=this.resolver.resolveEffort(e);return{resolved:r,finalOrigin:r.isEstimated?`analyzed-estimated`:`analyzed`}}},Kf=class extends Error{constructor(e){super(e),this.name=`CalcRegistrationError`}};function qf(e,t){switch(e.kind){case`literal`:return J;case`period`:return J;case`string`:return J;case`filter`:return J;case`ref`:{let n=t.refDim(e.name);if(!n)throw new Kf(`Unknown symbol: ${e.name}`);return n}case`wql`:return t.wqlDim?.(e)??J;case`unary`:return e.op===`not`?J:qf(e.arg,t);case`binary`:{let{op:n}=e;if(n===`and`||n===`or`)return qf(e.left,t),qf(e.right,t),J;if(n===`*`)return Fu(qf(e.left,t),qf(e.right,t));if(n===`/`)return Iu(qf(e.left,t),qf(e.right,t));let r=Jf(e.left,t),i=Jf(e.right,t);if(r&&i&&!Lu(r,i))throw new Kf(`Dimension mismatch for '${n}': ${Bu(r)} vs ${Bu(i)}`);return n===`+`||n===`-`?r??J:J}case`call`:return Xf(e,t)}}function Jf(e,t){if(e.kind!==`literal`||e.value!==0)return qf(e,t)}function Yf(e){return e.kind===`string`?e.value:void 0}function Xf(e,t){let{name:n,args:r}=e;if(n===`has`)return J;if(n===`convert`){if(r.length!==2)throw new Kf(`convert() takes (value, targetUnit)`);let e=r[1],n=e.kind===`ref`?e.name:e.kind===`string`?e.value:void 0,i=n===void 0?void 0:Xu(n);if(!n||!i)throw new Kf(`convert() target must be a known unit name`);let a=qf(r[0],t);if(!Lu(a,i.dim))throw new Kf(`convert(x, ${n}) dimension mismatch: ${Bu(a)} is not ${Bu(i.dim)}`);return i.dim}if(n===`min`||n===`max`||n===`clamp`){let e;for(let i of r){let r=qf(i,t);if(e&&!Lu(e,r))throw new Kf(`${n}() arguments have mismatched dimensions`);e=r}if(!e)throw new Kf(`${n}() requires at least one argument`);return e}if(n===`abs`||n===`round`||n===`floor`||n===`ceil`){if(r.length<1)throw new Kf(`${n}() requires an argument`);return qf(r[0],t)}if(n===`windowMean`||n===`windowSum`||n===`windowSd`||n===`windowEwma`){if(r.length!==2)throw new Kf(`${n}() takes (series, period)`);return qf(r[0],t)}if(n===`lookup`){if(r.length!==3)throw new Kf(`lookup() takes (table, key, field)`);let e=Yf(r[0]),n=Yf(r[2]);if(!e||!n)throw new Kf(`lookup() table and field must be string literals`);qf(r[1],t);let i=t.lookupDim?.(e,n);if(!i)throw new Kf(`Unknown lookup field: ${e}.${n}`);return i}let i=r.map(e=>e.kind===`filter`?J:qf(e,t)),a=t.callDim?.(n,i);if(!a)throw new Kf(`Unknown function: ${n}`);return a}function Zf(e,t){if(!t||t===`auto`||Ku[t])return;let n=Xu(t);if(!n)throw new Kf(`Unknown output unit: ${t}`);if(!Lu(n.dim,e))throw new Kf(`Declared unit ${t} (${Bu(n.dim)}) does not match expression dimension ${Bu(e)}`)}var Qf=class{lookups;defs=new Map;libraryDims=new Map;constructor(e){this.lookups=e}byScope(e){return[...this.defs.values()].filter(t=>t.scope===e)}get(e){return this.defs.get(e)}registerAtom(e,t=J){this.libraryDims.set(e,t)}register(e){if(e.variants.length===0)throw new Kf(`Calc ${e.id}: at least one variant is required`);if(e.customAtoms)for(let[t,n]of Object.entries(e.customAtoms))this.libraryDims.set(t,n);let t=this.staticEnv();e.when&&(e.whenAst=$f(e.when,e.id,t)),e.variants=[...e.variants].sort((e,t)=>t.priority-e.priority);for(let n of e.variants)this.compileVariant(e,n,t);if(e.kind===`output`&&e.output?.unit&&e.output.unit!==`auto`)for(let t of e.variants)for(let n of np(e)){let r=t.nodeDims?.[n];r&&Zf(r,e.output.unit)}if(e.kind===`library`)for(let t of e.variants)for(let[n,r]of Object.entries(t.nodeDims??{}))this.libraryDims.set(`${e.id}.${n}`,r);this.defs.set(e.id,e)}compileVariant(e,t,n){t.when&&(t.whenAst=$f(t.when,`${e.id}:${t.id}`,n));let r={},i=new Set,a=n=>{if(r[n])return r[n];let a=t.nodes[n];if(!a)throw new Kf(`Unknown symbol: ${n}`);if(i.has(n))throw new Kf(`Calc ${e.id}:${t.id}.${n}: cyclic node reference`);i.add(n);try{let i=a.ast??Sd(ep(e,t,n,a.expression));a.ast=i;let s=qf(i,this.staticEnv(o));return a.unit&&(Zf(s,a.unit),Ku[a.unit]&&(s=J)),r[n]=s,s}catch(r){throw tp(e,t,n,r)}finally{i.delete(n)}},o=e=>{if(e in t.nodes)return a(e)};for(let e of Object.keys(t.nodes))a(e);t.nodeDims=r}staticEnv(e=()=>void 0){return{refDim:t=>e(t)??this.libraryDims.get(t)??Uu[t]?.dim??Wu[t],callDim:(e,t)=>{if(e===`count`)return J;if(Gu[e])return t[0]},lookupDim:(e,t)=>this.lookups.fieldDim(e,t)}}};function $f(e,t,n){try{let t=Sd(e);return qf(t,n),t}catch(e){throw e instanceof Error?new Kf(`Calc ${t} predicate: ${e.message}`):e}}function ep(e,t,n,r){if(!r)throw new Kf(`Calc ${e.id}:${t.id}.${n}: node needs an expression or AST`);return r}function tp(e,t,n,r){return r instanceof Error?new Kf(`Calc ${e.id}:${t.id}.${n}: ${r.message}`):r}function np(e){let t=e.output?.nodeId;return t?Array.isArray(t)?t:[t]:[]}var rp=class{registry;deps;id=`composed-calculations`;fenceTypes=[`time`,`log`];segmentCalcs;workoutCalcs;lastSegmentEffort;tagCarriedFunctions=new Map;activatedTags=new Set;runTags;summaryDiagnosticsStamped=!1;constructor(e,t){this.registry=e,this.deps=t;let n=e=>!e.fences||e.fences.includes(t.dialect);this.segmentCalcs=e.byScope(`segment`).filter(n),this.workoutCalcs=e.byScope(`workout`).filter(n);let r=new Set;for(let e of t.propertySources??[])for(let t of Object.keys(e.summaries??{}))r.add(t.trim());for(let e of t.tags?.list()??[]){let n=po(t.tags,e.slug),i=[...n.functions];for(let e of n.metrics)if(e.type.trim().startsWith(`summaries.`)){let t=e.type.trim().slice(10).trim();t&&!r.has(t)&&i.push(t)}for(let t of i){let n=this.tagCarriedFunctions.get(t);n?n.add(e.slug):this.tagCarriedFunctions.set(t,new Set([e.slug]))}}this.runTags=[...t.activeTags??[]];for(let e of this.runTags)this.activatedTags.add(e)}isActive(e,t){let n=this.tagCarriedFunctions.get(e.id);if(!n)return!0;for(let e of n)if(t.includes(e))return!0;return!1}appliedTags(e){let t=vo(e.metrics.rawMetrics);for(let e of t)this.activatedTags.add(e);return this.runTags.length===0?t:[...t,...this.runTags.filter(e=>!t.includes(e))]}process(e){if(e.outputType!==`segment`||!e.isLeaf)return e;let t=ku(e.metrics.rawMetrics);t&&(this.lastSegmentEffort=t.resolved.slug);let n=this.appliedTags(e),r=[...Kd(this.deps.tags,n),...this.deps.propertySources??[]],i=e.metrics.rawMetrics.some(e=>e.type===q.Effort&&String(e.value??e.image??``).trim().toLowerCase()!==`rest`);if(!this.summaryDiagnosticsStamped&&(this.deps.summaryDiagnostics?.length??0)>0){this.summaryDiagnosticsStamped=!0;for(let t of this.deps.summaryDiagnostics??[])e.metrics.add({type:q.Diagnostic,name:`diagnostic.${t.id}`,value:t.message,image:t.message,origin:`diagnostic`,timestamp:new Date,metadata:{diagnostic:`summary-registration`,target:t.id}})}if(r.length>0){let t=typeof e.timeSpan?.started==`number`&&typeof e.timeSpan.ended==`number`?e.timeSpan.ended-e.timeSpan.started:0,n=e.metrics.rawMetrics.map(e=>e.type===q.Elapsed&&typeof e.value==`number`?e.value:void 0).reduce((e,t)=>t??e,void 0);t>0&&(n===void 0||n===0)&&e.metrics.add({type:q.Elapsed,name:`elapsed`,value:t,unit:`ms`,image:`${t} ms`,origin:`analyzed`,timestamp:new Date}),rf(e.metrics,{stage:`log`,sources:r,lookups:this.deps.lookups,lastEffortSlug:this.lastSegmentEffort,emitDiagnostics:i})}let a=ip(e,this.lastSegmentEffort),o=cp(e).slug??this.lastSegmentEffort,s={};if(o){s.effortSlug=o;let e=this.lookupString(o,`discipline`),t=this.lookupString(o,`intensityTier`);e&&(s.effortDiscipline=e),t&&(s.effortIntensityTier=t)}let c=e.metrics.rawMetrics.find(e=>e.type===`climb-grade`)?.value;c&&typeof c==`object`&&`raw`in c&&(s.grade=String(c.raw));for(let t of this.segmentCalcs){if(!this.isActive(t,n))continue;let r=this.makeContext(a);if(!this.applicable(t.whenAst,r))continue;let i=this.selectVariant(t,r);if(!i)continue;let o=this.evaluateVariant(i,a);if(t.kind===`library`)for(let[t,n]of o)n.kind===`number`&&(this.hasFrozen(e,t)||this.appendAnnotation(e,t,n,i.origin,void 0,s));else for(let n of np(t)){let r=o.get(n);r?.kind===`number`&&(this.hasFrozen(e,t.output?.emitType??t.id)||this.appendAnnotation(e,t.output?.emitType??t.id,r,i.origin,t.output?.unit,s))}}return e}appendAnnotation(e,t,n,r,i,a){let o=!i||i===`auto`?n.unit:i;e.metrics.add({type:t,image:o?`${fp(n.value)} ${o}`:fp(n.value),value:n.value,unit:o,origin:r,timestamp:new Date,...a&&Object.keys(a).length>0?{metadata:a}:{}})}hasFrozen(e,t){return e.metrics.rawMetrics.some(e=>e.type===t&&e.origin===`analyzed-estimated`)}summarize(e){let t=[];for(let t of e)if(t.outputType===`segment`)for(let e of vo(t.metrics.rawMetrics))this.activatedTags.add(e);let n=[...this.activatedTags];for(let r of this.workoutCalcs)this.isActive(r,n)&&(r.output?.isGrouped?t.push(...this.summarizeGrouped(r,e)):t.push(...this.summarizeUngrouped(r,e)));return t}summarizeUngrouped(e,t){let n=this.buildWorkoutAtoms(t),r=this.makeContext(n);if(!this.applicable(e.whenAst,r))return[];let i=this.selectVariant(e,r);if(!i)return[];let a=this.evaluateVariant(i,n),o=this.toProjection(e,i,a,void 0);return o?[o]:[]}summarizeGrouped(e,t){let n=new Map;for(let e of t){if(e.outputType!==`segment`)continue;let t=cp(e);if(!t.slug)continue;let r=n.get(t.slug);r||(r={label:t.label,segments:[]},n.set(t.slug,r)),r.segments.push(e)}let r=[];for(let[t,i]of n){let n=this.buildWorkoutAtoms(i.segments),a=this.makeContext(n);if(!this.applicable(e.whenAst,a))continue;let o=this.selectVariant(e,a);if(!o)continue;let s=this.evaluateVariant(o,n),c=this.toProjection(e,o,s,{effortSlug:t,exerciseName:i.label,groupTags:{effort:t},effortDiscipline:this.lookupString(t,`discipline`),effortIntensityTier:this.lookupString(t,`intensityTier`)});c&&r.push(c)}return r}lookupString(e,t){let n=this.deps.lookups.lookup(`effort`,e,t);return n.kind===`string`&&n.value?n.value:void 0}toProjection(e,t,n,r){let i=np(e)[0],a=n.get(i);if(a?.kind!==`number`)return;let o={canonicalKey:e.output?.key??e.id,...r};for(let t of e.output?.publishMetadataNodes??[]){let e=n.get(t);e?.kind===`number`&&(o[t]=e.value),e?.kind===`string`&&(o[t]=e.value)}return{name:e.output?.key??e.id,value:a.value,unit:!e.output?.unit||e.output.unit===`auto`?a.unit??``:e.output.unit,metricType:e.output?.emitType,timeSpan:{started:Date.now(),ended:Date.now()},origin:t.origin,metadata:o}}applicable(e,t){return!e||id(od(e,t))}selectVariant(e,t){for(let n of e.variants)if(this.applicable(n.whenAst,t))return n}evaluateVariant(e,t){let n=new Map,r=new Set,i=i=>{let o=n.get(i);if(o)return o;let s=e.nodes[i];if(!s?.ast||r.has(i))return td;r.add(i);let c=od(s.ast,this.makeContext(t,a));return r.delete(i),c.kind===`number`&&s.unit&&Ku[s.unit]&&(c=nd(c.value,J,s.unit)),n.set(i,c),c},a=t=>t in e.nodes?i(t):void 0;for(let t of Object.keys(e.nodes))i(t);return n}makeContext(e,t){return{resolveRef:n=>t?.(n)??e.resolveRef(n),callFunction:(t,n,r)=>t===`lookup`?this.deps.lookups.callFunction(t,n,r):e.callFunction?.(t,n,r)}}buildWorkoutAtoms(e){let t=new Map,n=e=>{let n=t.get(e);return n||(n=cp(e),t.set(e,n)),n},r=(t,r)=>{let i=Uu[t],a=i?.metricType??t,o=[],s=i?.unit;for(let t of e)if(t.outputType===`segment`&&!(r&&lp(n(t).slug,r)))for(let e of t.getDisplayMetrics({types:[a]})){let t=ap(e);t!==void 0&&(o.push(t),s=op(e)??e.unit??s)}return{values:o,unit:s}},i=(e,t)=>{let n=t[0];if(n?.kind!==`ref`)return td;let i=t[1]?.kind===`filter`?t[1].value:void 0,{values:a,unit:o}=r(n.name,i);if(a.length===0)return td;let s=Uu[n.name]?.dim;switch(e){case`sum`:return nd(a.reduce((e,t)=>e+t,0),s,o);case`max`:return nd(Math.max(...a),s,o);case`min`:return nd(Math.min(...a),s,o);case`avg`:return nd(a.reduce((e,t)=>e+t,0)/a.length,s,o);case`last`:return nd(a[a.length-1],s,o);case`count`:return nd(a.length);default:return td}},a=new Map,o=(e,t)=>{let n=t.indexOf(`.`);if(n<0)return td;let r=a.get(t);if(r)return r;let i=this.registry.get(t.slice(0,n));if(!i||i.kind!==`library`)return td;let o=this.makeContext(e);if(!this.applicable(i.whenAst,o))return td;let s=this.selectVariant(i,o);if(!s)return td;let c=this.evaluateVariant(s,e);for(let[e,t]of c)a.set(`${i.id}.${e}`,t);return a.get(t)??td},s={resolveRef:t=>{if(t===`session.duration`){let t=up(e);return t===void 0?td:nd(t,Uu.elapsed.dim,`ms`)}if(t===`sessionRpe`){let t=dp(e,q.SessionRPE);return t===void 0?td:nd(t)}if(t===`profile.vo2max`){let e=this.deps.userProfile?.vo2max;return e===void 0?td:nd(e)}if(t===`effort`){for(let t=e.length-1;t>=0;t--){let n=ku(e[t].metrics.rawMetrics);if(n)return rd(n.resolved.slug)}return rd(``)}return t.includes(`.`)?o(s,t):td},callFunction:(e,t,n)=>{if([`sum`,`max`,`min`,`avg`,`count`,`last`].includes(e))return i(e,n)}};return s}};function ip(e,t){let n=e.metrics.rawMetrics,r=t=>{let n=0,r=!1;for(let i of e.getDisplayMetrics({types:[t]}))typeof i.value==`number`&&(n+=i.value,r=!0);return r?n:void 0},i=t=>{let n=e.getMetric(t);if(!n)return;let r=ap(n);if(r!==void 0)return{value:r,unit:op(n)??n.unit}},a=r(q.Rep),o=typeof e.getMetric(q.Elapsed)?.value==`number`?e.getMetric(q.Elapsed).value:void 0,s=i(q.Distance),c=i(q.Resistance),l=ku(n),u=[...n].reverse().find(e=>e.type===q.Effort&&typeof e.value==`string`),d=[...n].some(e=>e.type===`climb-send-type`),f=[...n].find(e=>e.type===`climb-grade`)?.value,p=f&&typeof f==`object`&&`raw`in f?String(f.raw):void 0;return{resolveRef:e=>{switch(e){case`reps`:return a===void 0?td:nd(a,Uu.reps.dim,`reps`);case`elapsed`:return o===void 0?td:nd(o,Uu.elapsed.dim,`ms`);case`distance`:return s===void 0?td:nd(s.value,Uu.distance.dim,s.unit??`m`);case`resistance`:return c===void 0?td:nd(c.value,Uu.resistance.dim,c.unit??`kg`);case`climbSend`:return d?nd(1,Uu.reps.dim,`count`):td;case`climbGrade`:return p?rd(p):td;case`effort`:return rd(l?.resolved.slug??t??``);case`effortLabel`:return u?rd(u.value):td;default:for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.type!==e&&r.name!==e)continue;let i=ap(r);if(i!==void 0){let t=op(r)??r.unit??Uu[e]?.unit;return nd(i,(t&&Yu[t]?Yu[t].dim:void 0)??Uu[e]?.dim??J,t)}if(typeof r.value==`string`&&r.value)return rd(r.value)}return td}}}}function ap(e){if(typeof e.value==`number`)return e.value;let t=e.value;if(t&&typeof t==`object`&&`amount`in t&&typeof t.amount==`number`)return t.amount}function op(e){let t=e.value;if(t&&typeof t==`object`&&`units`in t&&typeof t.units==`string`&&t.units)return t.units}function sp(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/(^-|-$)/g,``)}function cp(e){let t=ku(e.metrics.rawMetrics);if(t)return{slug:t.resolved.slug,label:t.resolved.label};let n=[...e.metrics.rawMetrics].reverse().find(e=>e.type===q.Effort&&typeof e.value==`string`);return n?{slug:sp(n.value),label:n.value}:{slug:``,label:``}}function lp(e,t){for(let n of t.split(`|`)){let t=n.trim();if(t){if(t.endsWith(`*`)){if(e.startsWith(t.slice(0,-1)))return!0}else if(e===t)return!0}}return!1}function up(e){let t=e.filter(e=>e.outputType===`segment`);if(t.length===0)return;let n=t.find(e=>e.stackLevel===0||e.sourceBlockKey===`root`),r=e=>{let t=e.getMetric(q.Elapsed)?.value;return typeof t==`number`?t:0};if(n&&r(n)>0)return r(n);let i=t.filter(e=>e.stackLevel>0),a=(i.length>0?i:t).reduce((e,t)=>e+r(t),0);return a>0?a:void 0}function dp(e,t){let n;for(let r of e)for(let e of r.metrics.rawMetrics){if(e.type!==t)continue;let r=ap(e);r!==void 0&&(n=r)}return n}function fp(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/\.?0+$/,``)}var pp={bundled:0,dialect:1,user:2},mp=class{tables=new Map;register(e,t=`bundled`){let n=this.tables.get(e.id);n&&pp[n.layer]>pp[t]||this.tables.set(e.id,{table:e,layer:t})}get(e){return this.tables.get(e)?.table}fieldDim(e,t){return this.tables.get(e)?.table.fields[t]?.dimension}lookup(e,t,n){let r=this.tables.get(e)?.table;return r?r.get(t,n)??td:td}callFunction=(e,t)=>{if(e!==`lookup`)return;let[n,r,i]=t;if(n?.kind!==`string`||i?.kind!==`string`)throw new ad(`lookup() table and field must be strings`);if(r.kind===`absent`||r.kind===`series`||r.kind===`period`)return td;let a=r.kind===`string`?r.value:String(r.value);return this.lookup(n.value,a,i.value)}},hp=`rest|pause|rest-*`,Y=(e,t,n)=>({id:e,kind:`expr`,expression:t,unit:n}),gp=[{id:`pace-reps`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(reps)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`reps / convert(elapsed, min)`)}}],output:{nodeId:`value`,emitType:`pace`,unit:`reps/min`}},{id:`pace-speed`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(distance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`distance / convert(elapsed, s)`)}}],output:{nodeId:`value`,emitType:`pace`,unit:`m/s`}},{id:`pace-runner`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(distance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`convert(elapsed, min) / convert(distance, km)`)}}],output:{nodeId:`value`,emitType:`pace`,unit:`min/km`}},{id:`power`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0 and has(reps) and has(resistance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`reps * resistance / convert(elapsed, s)`)}}],output:{nodeId:`value`,emitType:`power`,unit:`auto`}},{id:`segment-volume`,kind:`library`,scope:`segment`,when:`has(reps) and has(resistance)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{segmentVolume:Y(`segmentVolume`,`reps * resistance`)}}]},{id:`e1rm`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`has(reps) and has(resistance) and reps > 0 and resistance > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{repFactor:Y(`repFactor`,`reps / 30`,`ratio`),value:Y(`value`,`round(resistance * (1 + repFactor), 1)`)}}],output:{nodeId:`value`,emitType:`calc.e1rm`,key:`calc.e1rm`,unit:`auto`,label:`Estimated 1RM`}},{id:`pct1rm`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`has(reps) and has(resistance) and reps > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{repFactor:Y(`repFactor`,`reps / 30`,`ratio`),value:Y(`value`,`100 / (1 + repFactor)`)}}],output:{nodeId:`value`,emitType:`calc.pct1rm`,key:`calc.pct1rm`,unit:`%`,label:`%1RM Intensity`}},{id:`climb-sends`,kind:`output`,scope:`segment`,fences:[`time`,`log`],when:`has(climbSend)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{value:Y(`value`,`climbSend`)}}],output:{nodeId:`value`,emitType:`calc.sends`,key:`calc.sends`,unit:`count`,label:`Sends`}},{id:`effort-rpe`,kind:`library`,scope:`segment`,when:`has(effortLabel)`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{effortRpe:Y(`effortRpe`,`lookup("rpe-labels", effortLabel, "rpe")`)}}]},{id:`met-minutes-segment`,kind:`library`,scope:`segment`,fences:[`time`,`log`],when:`elapsed > 0`,variants:[{id:`resolved`,priority:100,when:`lookup("effort", effort, "resolvedFrom") != "default"`,origin:`analyzed`,nodes:{metMinutes:Y(`metMinutes`,`lookup("effort", effort, "met") * convert(elapsed, min)`)}},{id:`unresolved`,priority:10,origin:`analyzed-estimated`,nodes:{metMinutes:Y(`metMinutes`,`lookup("effort", effort, "met") * convert(elapsed, min)`),metMinutesEstimated:Y(`metMinutesEstimated`,`1`)}}]},{id:`total-reps`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(reps)) and sum(reps) > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(reps)`)}}],output:{nodeId:`total`,key:`reps`,emitType:`rep`,unit:`reps`}},{id:`total-reps-by-effort`,kind:`output`,scope:`workout`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(reps, without: ${hp})`)}}],output:{nodeId:`total`,key:`reps`,emitType:`rep`,unit:`reps`,isGrouped:!0,groupBy:[`effort`]}},{id:`total-distance`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(distance)) and sum(distance) > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(distance)`)}}],output:{nodeId:`total`,key:`distance`,emitType:`distance`,unit:`auto`}},{id:`total-volume`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(segmentVolume)) and sum(segmentVolume) > 0`,variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(segmentVolume)`)}}],output:{nodeId:`total`,key:`totalVolume`,emitType:`volume`,unit:`auto`}},{id:`total-volume-by-effort`,kind:`output`,scope:`workout`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`sum(segmentVolume)`),totalSets:Y(`totalSets`,`count(segmentVolume)`)}}],output:{nodeId:`total`,key:`totalVolume`,emitType:`volume`,unit:`auto`,isGrouped:!0,groupBy:[`effort`],publishMetadataNodes:[`totalSets`]}},{id:`met-minutes`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(metMinutes))`,variants:[{id:`estimated`,priority:100,when:`sum(metMinutesEstimated) > 0`,origin:`analyzed-estimated`,nodes:{total:Y(`total`,`round(sum(metMinutes))`)}},{id:`resolved`,priority:10,origin:`analyzed`,nodes:{total:Y(`total`,`round(sum(metMinutes))`)}}],output:{nodeId:`total`,key:`calc.metMinutes`,emitType:`work`,unit:`MET-min`}},{id:`rpeSource`,kind:`library`,scope:`workout`,variants:[{id:`captured`,priority:100,when:`has(sessionRpe)`,origin:`analyzed`,nodes:{rpe:Y(`rpe`,`sessionRpe`)}},{id:`label`,priority:50,when:`has(max(effortRpe))`,origin:`analyzed`,nodes:{rpe:Y(`rpe`,`max(effortRpe)`)}},{id:`default`,priority:10,origin:`analyzed-estimated`,nodes:{rpe:Y(`rpe`,`5`)}}]},{id:`session-load`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(session.duration)`,variants:[{id:`captured-rpe`,priority:100,when:`has(sessionRpe)`,origin:`analyzed`,nodes:_p()},{id:`label-rpe`,priority:50,when:`has(max(effortRpe))`,origin:`analyzed`,nodes:_p()},{id:`default-rpe`,priority:10,origin:`analyzed-estimated`,nodes:_p()}],output:{nodeId:`load`,key:`sessionLoad`,emitType:`load`,unit:`AU`,publishMetadataNodes:[`sRPE`,`durationMinutes`]}},{id:`sharedMet`,kind:`library`,scope:`workout`,variants:[{id:`personalized`,priority:100,when:`has(profile.vo2max)`,origin:`analyzed`,nodes:{metMax:Y(`metMax`,`profile.vo2max / 3.5`)}},{id:`population`,priority:10,origin:`analyzed`,nodes:{metMax:Y(`metMax`,`11.4`)}}]},{id:`tis`,kind:`output`,scope:`workout`,fences:[`time`,`log`],when:`has(sum(metMinutes)) and has(sum(elapsed))`,variants:[{id:`resolved`,priority:100,when:`not (sum(metMinutesEstimated) > 0)`,origin:`analyzed`,nodes:vp()},{id:`estimated`,priority:10,origin:`analyzed-estimated`,nodes:vp()}],output:{nodeId:`tis`,key:`tis`,emitType:`tis`,unit:`pts`,publishMetadataNodes:[`metScore`,`rpeScore`,`durationScore`,`disciplineFactor`,`metMax`]}}];function _p(){return{sRPE:Y(`sRPE`,`rpeSource.rpe`),durationMinutes:Y(`durationMinutes`,`convert(session.duration, min)`),load:Y(`load`,`round(rpeSource.rpe * convert(session.duration, min))`)}}function vp(){return{elapsedMin:Y(`elapsedMin`,`convert(sum(elapsed), min)`),avgMets:Y(`avgMets`,`sum(metMinutes) / elapsedMin`),metMax:Y(`metMax`,`sharedMet.metMax`),metScore:Y(`metScore`,`min(100, avgMets / metMax * 100)`),rpeScore:Y(`rpeScore`,`rpeSource.rpe * 10`),durationScore:Y(`durationScore`,`elapsedMin / 60 * metScore`,`pts`),disciplineFactor:Y(`disciplineFactor`,`lookup("effort", effort, "disciplineFactor")`),tis:Y(`tis`,`round(0.30 * metScore + 0.35 * rpeScore + 0.20 * durationScore + 0.15 * disciplineFactor, 1)`)}}var yp=()=>({id:`daily`,kind:`wql`,expression:`sum:sessionLoad{} by {day}`}),bp=[{id:`acwr`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:yp(),acute:Y(`acute`,`windowMean(daily, 7d)`),chronic:Y(`chronic`,`windowMean(daily, 28d)`),value:Y(`value`,`acute / chronic`)}}],output:{nodeId:`value`,key:`calc.acwr`,unit:`ratio`,label:`Acute:Chronic Workload Ratio`}},{id:`monotony`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:yp(),mean7:Y(`mean7`,`windowMean(daily, 7d)`),sd7:Y(`sd7`,`windowSd(daily, 7d)`),value:Y(`value`,`mean7 / sd7`)}}],output:{nodeId:`value`,key:`calc.monotony`,unit:`ratio`,label:`Training Monotony`}},{id:`strain`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:yp(),monotony:Y(`monotony`,`windowMean(daily, 7d) / windowSd(daily, 7d)`,`ratio`),weekly:Y(`weekly`,`windowSum(daily, 7d)`),value:Y(`value`,`monotony * weekly`)}}],output:{nodeId:`value`,key:`calc.strain`,unit:`AU`,label:`Training Strain`}},{id:`ctl`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:yp(),value:Y(`value`,`windowEwma(daily, 42d)`)}}],output:{nodeId:`value`,key:`calc.ctl`,unit:`AU`,label:`Chronic Training Load (CTL)`}},{id:`atl`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:yp(),value:Y(`value`,`windowEwma(daily, 7d)`)}}],output:{nodeId:`value`,key:`calc.atl`,unit:`AU`,label:`Acute Training Load (ATL)`}},{id:`tsb`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{daily:yp(),ctl:Y(`ctl`,`windowEwma(daily, 42d)`),atl:Y(`atl`,`windowEwma(daily, 7d)`),value:Y(`value`,`ctl - atl`)}}],output:{nodeId:`value`,key:`calc.tsb`,unit:`AU`,label:`Training Stress Balance (TSB)`}},{id:`soreness`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`user`,nodes:{daily:{id:`daily`,kind:`wql`,expression:`avg:soreness{} by {day}`},value:Y(`value`,`daily * (daily / daily)`)}}],output:{nodeId:`value`,key:`calc.soreness`,unit:`rating`,label:`Soreness`}},{id:`sleep`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`user`,nodes:{daily:{id:`daily`,kind:`wql`,expression:`avg:sleep{} by {day}`},value:Y(`value`,`daily * (daily / daily)`)}}],output:{nodeId:`value`,key:`calc.sleep`,unit:`pts`,label:`Sleep (h)`}},{id:`hrv`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`user`,nodes:{daily:{id:`daily`,kind:`wql`,expression:`avg:hrv{} by {day}`},value:Y(`value`,`daily * (daily / daily)`)}}],output:{nodeId:`value`,key:`calc.hrv`,unit:`pts`,label:`HRV (ms)`}},{id:`readiness`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{soreness:{id:`soreness`,kind:`wql`,expression:`avg:soreness{} by {day}`},sleep:{id:`sleep`,kind:`wql`,expression:`avg:sleep{} by {day}`},hrv:{id:`hrv`,kind:`wql`,expression:`avg:hrv{} by {day}`},value:Y(`value`,`((10 - soreness) / 10 * 40 + sleep / 8 * 30 + hrv / 90 * 30) * (soreness / soreness) * (sleep / sleep) * (hrv / hrv)`)}}],output:{nodeId:`value`,key:`calc.readiness`,unit:`pts`,label:`Readiness`}},{id:`mvcBw`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{hang:{id:`hang`,kind:`wql`,expression:`max:hang{} by {day}`},weight:{id:`weight`,kind:`wql`,expression:`avg:weight{} by {day}`},value:Y(`value`,`hang / weight * 100`)}}],output:{nodeId:`value`,key:`calc.mvcBw`,unit:`%`,label:`Max Hang %BW`}},{id:`ef`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{dist:{id:`dist`,kind:`wql`,expression:`sum:totalDistance{discipline:running} by {day}`},elapsed:{id:`elapsed`,kind:`wql`,expression:`sum:elapsed{discipline:running} by {day}`},hr:{id:`hr`,kind:`wql`,expression:`avg:hr{} by {day}`},pace:Y(`pace`,`dist / (elapsed / 1000)`,`pts`),value:Y(`value`,`pace / hr * 100000`,`pts`)}}],output:{nodeId:`value`,key:`calc.ef`,unit:`pts`,label:`Efficiency Factor`}},{id:`adherence`,kind:`output`,scope:`store`,fences:[`time`,`log`],variants:[{id:`default`,priority:10,origin:`analyzed`,nodes:{sessions:{id:`sessions`,kind:`wql`,expression:`count:sessionLoad{} by {day}`},planned:{id:`planned`,kind:`wql`,expression:`avg:planned{} by {day}`},value:Y(`value`,`sessions / planned`)}}],output:{nodeId:`value`,key:`calc.adherence`,unit:`ratio`,label:`Plan Adherence`}}],xp={easy:3,moderate:5,hard:7,"all-out":10,max:10};function Sp(e){return{id:`effort`,missPolicy:`default-row`,fields:{met:{dimension:J,type:`number`},disciplineFactor:{dimension:J,type:`number`},discipline:{dimension:J,type:`string`},intensityTier:{dimension:J,type:`string`},resolvedFrom:{dimension:J,type:`string`},isEstimated:{dimension:J,type:`number`}},get(t,n){if(!t)switch(n){case`met`:return nd(oc.defaultMet);case`disciplineFactor`:return nd(1);case`resolvedFrom`:return rd(`default`);case`isEstimated`:return nd(1);default:return}let r=e.resolveEffort(t);switch(n){case`met`:return nd(r.met);case`disciplineFactor`:return nd(r.disciplineFactor);case`discipline`:return r.discipline?rd(r.discipline):void 0;case`intensityTier`:return r.intensityTier?rd(r.intensityTier):void 0;case`resolvedFrom`:return rd(r.resolvedFrom);case`isEstimated`:return nd(+!!r.isEstimated);default:return}}}}function Cp(){return{id:`rpe-labels`,missPolicy:`absent`,fields:{rpe:{dimension:J,type:`number`}},get(e,t){if(t!==`rpe`)return;let n=xp[e.toLowerCase()];return n===void 0?void 0:nd(n)}}}function wp(e){return{id:`profile`,missPolicy:`absent`,fields:{vo2max:{dimension:J,type:`number`}},get(t,n){if(n===`vo2max`)return e?.vo2max===void 0?void 0:nd(e.vo2max)}}}function Tp(){return{id:`disciplines`,missPolicy:`default-row`,fields:{disciplineFactor:{dimension:J,type:`number`}},get(e,t){if(t===`disciplineFactor`)return nd(Bc(e)?Hc(e):1)}}}function Ep(e){let t=new mp;t.register(Sp(e.effortResolver)),t.register(Cp()),t.register(wp(e.userProfile)),t.register(Tp());let n=new Qf(t);for(let e of gp)n.register(e);for(let t of e.calcs??[])n.register(t);let r=(e.tags?.list()??[]).map(e=>e.slug),i=Kd(e.tags,r),a=[...e.propertySources??[],...i],o=[];if(a.length>0){let e=Jd(a);o.push(...e.diagnostics);for(let t of e.defs)try{n.register(t)}catch(e){let n=`Skipped summary ${t.id}: ${e instanceof Error?e.message:String(e)}`;o.push({id:t.id,message:n}),console.error(`[createCalcStack] ${n}`)}}return{lookups:t,registry:n,diagnostics:o}}function Dp(e,t){let n=Ep(t);return new rp(n.registry,{dialect:e,lookups:n.lookups,userProfile:t.userProfile,tags:t.tags,activeTags:t.activeTags,propertySources:t.propertySources,summaryDiagnostics:n.diagnostics})}var Op=new Ya([]),kp=new Ya([]),Ap=class{build(e){let t=[],n=[];if(e.analyticsContext?.effortResolver){t.push(new Gf(e.analyticsContext.effortResolver));let r=Dp(e.dialect,{effortResolver:e.analyticsContext.effortResolver,userProfile:e.userProfile,calcs:e.calcs,tags:e.tags,activeTags:e.activeTags,propertySources:e.propertySources});t.push(r),n.push(r)}return t.push(...Op.list().filter(t=>this.isApplicable(t,e))),n.push(...kp.list().filter(t=>this.isApplicable(t,e))),{realtime:t,summary:n}}isApplicable(e,t){if(e.fenceTypes&&e.fenceTypes.length>0&&!e.fenceTypes.includes(t.dialect))return!1;if(e.requiredMetrics&&e.requiredMetrics.length>0){for(let n of e.requiredMetrics)if(!t.scriptMetricTypes.has(n))return!1}return!0}};function jp(e,t){let n=e.dialect||`time`,r=new Set;if(e.statements)for(let t of e.statements)for(let e of t.metrics)r.add(e.type);let i=t?.effortResolver;if(!i){let e=new _l;e.seed(gl),i=new ml(e)}let a={effortResolver:i,...t?.references?{references:t.references}:{}},o={dialect:n,scriptMetricTypes:r,analyticsContext:a,userProfile:t?.userProfile,calcs:t?.calcs,tags:t?.tags,activeTags:t?.activeTags,propertySources:t?.propertySources},{realtime:s,summary:c}=new Ap().build(o),l=new Wf;for(let e of s)l.addRealtimeProcessor(e);for(let e of c)l.addSummaryProcessor(e);return{engine:l,analyticsContext:a}}function Mp(e,t){return!e.metrics.some(e=>e===t)}function Np(e){let t=[];return e.forEach((e,n)=>{for(let r of e.metrics)if(r.type===q.Choice){let i=r;Mp(e,i)||t.push({statementIndex:n,statementId:e.id,choice:i})}}),t}function Pp(e,t,n){let r=t[n]??t[0];r&&(e.metrics.remove(e=>e.type===r.type&&e.origin===`user-plan`),e.metrics.remove(e=>e.type===q.Choice&&e.alternatives===t),e.metrics.add({...r,origin:`user-plan`}))}function Fp(e){let t=Np(e);for(let n of t){let t=e[n.statementIndex],r=n.choice.alternatives[0]?.type;r&&t.metrics.some(e=>e.type===r&&e.origin===`user-plan`)?t.metrics.remove(e=>e===n.choice):Pp(t,n.choice.alternatives,0)}return t.length}var Ip=class{compiler;nowProvider;constructor(e,t=El){this.compiler=e,this.nowProvider=t}createRuntime(e,t){if(!e.statements||e.statements.length===0)return null;let n=new $s(e.content,e.statements);Fp(n.statements);let r={stack:new bee,clock:new Tl,eventBus:new Lf},i=new Yl(n,this.compiler,r,t,this.nowProvider),{engine:a,analyticsContext:o}=jp(e,t?.analyticsOptions);return i.analyticsContext=o,i.setAnalyticsEngine(a),i.do(new Uf),i}disposeRuntime(e){e.dispose()}},Lp=class{static build(e,t={}){let{includeMetric:n=!0,includeLogic:r=!0,includeIdentity:i=!0,includeAttributes:a=!0,defaultLabel:o=`Block`,format:s=`logic-first`}=t,c=la.from(e.flatMap(e=>la.from(e.metrics).toArray()).filter(e=>e.origin!==`runtime`&&e.type!==q.Hint));if(c.length===0)return o;let l=c.find(e=>e.type===q.Label);if(l)return l.image||l.value?.toString()||o;let u=n?this.getPrimaryMetric(c):void 0,d=r?this.getLogicKeyword(e,c):void 0,f=i?this.getIdentityText(c):void 0,p=a?this.getAttributesText(c):void 0,m=[];return s===`logic-first`?(d&&m.push(d),u&&m.push(u),f&&m.push(f),p&&m.push(p)):s===`metric-first`?(u&&m.push(u),d&&m.push(d),f&&m.push(f),p&&m.push(p)):(f&&m.push(f),u&&m.push(u),d&&m.push(d),p&&m.push(p)),m.length===0?c.filter(e=>!!e.image&&!wo.isStructural(e)).map(e=>e.image).join(` `)||o:m.join(` `).trim().replace(/\s+/g,` `)}static getPrimaryMetric(e){let t=e.find(e=>e.type===q.Rounds);if(t&&t.image)return t.image;let n=e.find(e=>e.type===q.Duration);if(n&&n.image)return n.image}static getLogicKeyword(e,t){if(e.some(e=>to(e,Xa.LABEL_AMRAP)))return`AMRAP`;if(e.some(e=>to(e,Xa.LABEL_EMOM)))return`EMOM`;if(e.some(e=>to(e,Xa.LABEL_TABATA)))return`TABATA`;if(e.some(e=>to(e,Xa.LABEL_FOR_TIME)))return`FOR TIME`;let n=[`AMRAP`,`EMOM`,`TABATA`,`FOR TIME`];for(let e of t){let t=(e.image||e.value?.toString()||``).toUpperCase();if(n.includes(t))return t}}static getIdentityText(e){let t=[`AMRAP`,`EMOM`,`TABATA`,`FOR TIME`],n=e.filter(e=>{if(e.type===q.Duration||e.type===q.Rounds||e.type===q.Resistance||e.type===q.Distance||e.type===q.Lap||e.type===q.Group)return!1;let n=(e.image||e.value?.toString()||``).toUpperCase();return!t.includes(n)});if(n.length!==0)return n.map(e=>e.image).join(` `).trim()}static getAttributesText(e){let t=e.filter(e=>e.type===q.Resistance||e.type===q.Distance);if(t.length!==0)return t.map(e=>e.image).join(` `).trim()}},Rp=class{distribute(e,t){return[e.clone()]}},zp=e=>e[0];function Bp(e,t){let{statements:n,runtime:r,blockType:i,defaultLabel:a}=t,o=(t.pickStatement??zp)(n),s=t.key??new pa,c=t.context??new ru(r,s.toString(),o.exerciseId||``),l=Lp.build(n,{defaultLabel:a});e.setContext(c).setKey(s).setBlockType(i).setLabel(l).setSourceIds(n.map(e=>e.id));let u=t.metricDistributorType??i,d=new Rp,f=t.filterMetrics,p=n.flatMap(e=>{let t=f?la.from(e.metrics.filter(f)):la.from(e.metrics);return d.distribute(t,u)}).filter(e=>e.length>0);if(e.setFragments(p),t.timer){let n=t.timer,r=n.mode===`reset-interval`?{completesBlock:!1}:void 0;e.asTimer({direction:n.direction,durationMs:n.durationMs,label:n.label,role:n.role??`primary`,addCompletion:n.mode!==`reset-interval`,completionConfig:r,injectRest:n.injectRest,required:n.required,...t.countdownTimerConfig??{}})}if(t.repeater){let n=t.repeater;e.asRepeater({totalRounds:n.totalRounds,startRound:n.startRound??1,addCompletion:n.addCompletion})}return l}var Vp=class{priority=90;id=`amrap-logic`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.hasMetric(q.Duration)),r=e.some(e=>e.hasMetric(q.Rounds)),i=e.some(e=>e.metrics.some(e=>(e.type===q.Effort||e.type===q.Action)&&typeof e.value==`string`&&(e.value.toLowerCase()===`rounds`||e.value.toLowerCase()===`amrap`)));return n&&(r||i)}apply(e,t,n){let r=(t.find(e=>e.hasMetric(q.Duration))||t[0]).metrics.find(e=>e.type===q.Duration)?.value||0,i=Bp(e,{blockType:`AMRAP`,defaultLabel:`AMRAP ${Math.round(r/6e4)} min`,statements:t,runtime:n,timer:{direction:`down`,durationMs:r,label:`AMRAP`,role:`primary`,mode:`complete-block`,injectRest:!1},repeater:{totalRounds:void 0,startRound:1,addCompletion:!1},pickStatement:e=>e.find(e=>e.hasMetric(q.Duration))||e[0]});e.addBehavior(new wu({mode:`countdown`,label:i}))}},Hp=class{priority=90;id=`interval-logic`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.metrics.some(e=>e.type===q.Duration)),r=e.some(e=>to(e,Xa.REPEATING_INTERVAL)),i=e.some(e=>e.metrics.some(e=>(e.type===q.Action||e.type===q.Effort)&&typeof e.value==`string`&&e.value.toLowerCase()===`emom`)),a=e.some(e=>to(e,Xa.LABEL_AMRAP)||e.metrics.some(e=>e.type===q.Rounds&&typeof e.value==`string`&&e.value.toLowerCase()===`amrap`)),o=e.some(e=>to(e,Xa.LABEL_TABATA)||e.metrics.some(e=>e.type===q.Effort&&typeof e.value==`string`&&e.value.toLowerCase()===`tabata`)),s=i||e.some(e=>e.metrics.some(e=>e.type===q.Rounds));return n&&(r||i)&&!a&&(!o||s)}apply(e,t,n){let r=(t.find(e=>e.metrics.some(e=>e.type===q.Duration))||t[0]).metrics.find(e=>e.type===q.Duration),i=t.flatMap(e=>la.from(e.metrics).toArray()).find(e=>e.type===q.Rounds),a=r?.value||6e4,o=typeof i?.value==`number`?i.value:10,s=Bp(e,{blockType:`EMOM`,defaultLabel:`EMOM ${o}`,statements:t,runtime:n,timer:{direction:`down`,durationMs:a,label:`Interval`,role:`primary`,mode:`reset-interval`,injectRest:!0},repeater:{totalRounds:o,startRound:1,addCompletion:!0},pickStatement:e=>e.find(e=>e.hasMetric(q.Duration))||e[0],metricDistributorType:`EMOM`});e.addBehavior(new wu({mode:`countdown`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===q.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===q.Distance)),u=[...c?[{metricType:q.Resistance,origin:`compiler`}]:[],...l?[{metricType:q.Distance,origin:`compiler`}]:[]];u.length>0&&e.addBehavior(new Su({promotions:u}))}},Up=class{priority=0;id=`effort-fallback`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`)),r=e.some(e=>e.metrics.some(e=>e.type===q.Rounds&&e.origin!==`runtime`)),i=e.some(e=>e.children&&e.children.length>0);return!n&&!r&&!i}apply(e,t,n){Bp(e,{blockType:`effort`,defaultLabel:`Effort`,statements:t,runtime:n,timer:{direction:`up`,role:`secondary`,mode:`reset-interval`},filterMetrics:e=>e.origin!==`runtime`}),e.addBehavior(new Cu({mode:`immediate`,onNext:!0}))}},Wp=class{priority=50;id=`generic-group`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.children&&e.children.length>0),r=e.some(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`)),i=e.some(e=>e.metrics.some(e=>e.type===q.Rounds&&e.origin!==`runtime`));return n&&!r&&!i}apply(e,t,n){if(e.hasTimerBehavior()||e.hasRoundConfig())return;let r=Bp(e,{blockType:`Group`,defaultLabel:`Group`,statements:t,runtime:n});e.addBehavior(new wu({mode:`clock`,label:r}));let i=t.some(e=>e.metrics.some(e=>e.type===q.Resistance)),a=t.some(e=>e.metrics.some(e=>e.type===q.Distance)),o=[...i?[{metricType:q.Resistance,origin:`compiler`}]:[],...a?[{metricType:q.Distance,origin:`compiler`}]:[]];o.length>0&&e.addBehavior(new Su({promotions:o}))}},Gp=class{priority=50;id=`generic-loop`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===q.Rounds))}apply(e,t,n){if(e.hasRoundConfig())return;let r=(t.find(e=>e.metrics.some(e=>e.type===q.Rounds))||t[0]).metrics.find(e=>e.type===q.Rounds);if(!r)return;let i=1,a;typeof r.value==`number`&&(i=r.value);let o=t.flatMap(e=>e.metrics.filter(e=>e.type===q.Rep&&typeof e.value==`number`)).map(e=>e.value);o.length>0&&(a=o,i<=1&&(i=a.length));let s=Bp(e,{blockType:`Rounds`,defaultLabel:a?a.join(`-`):`${i} Rounds`,statements:t,runtime:n,repeater:{totalRounds:i,startRound:1,addCompletion:!0},pickStatement:e=>e.find(e=>e.metrics.some(e=>e.type===q.Rounds))||e[0],filterMetrics:e=>e.type!==q.Rep});e.addBehavior(new wu({mode:`clock`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===q.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===q.Distance)),u=[...c?[{metricType:q.Resistance,origin:`compiler`}]:[],...l?[{metricType:q.Distance,origin:`compiler`}]:[]];e.addBehavior(new Su({repScheme:a,promotions:u})),e.declareExit(`immediate`)}},Kp=class{priority=50;id=`generic-timer`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`))}apply(e,t,n){if(e.hasTimerBehavior())return;let r=(t.find(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`))||t[0]).metrics.find(e=>e.type===q.Duration&&e.origin!==`runtime`),i=r?.direction||`up`,a=r?.value||void 0,o=t.some(e=>to(e,Xa.REQUIRED_TIMER)),s=t.some(e=>to(e,Xa.INJECT_REST)),c=!!(a&&i===`down`),l=Bp(e,{blockType:`Timer`,defaultLabel:i===`down`?`Countdown`:`For Time`,statements:t,runtime:n,timer:{direction:i,durationMs:a,label:a?`Countdown`:`For Time`,role:`primary`,mode:`complete-block`,injectRest:s,required:o},pickStatement:e=>e.find(e=>e.metrics.some(e=>e.type===q.Duration&&e.origin!==`runtime`))||e[0]});o&&c?e.addBehavior(new Cu({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})):e.addBehavior(new Cu({mode:`immediate`,onNext:!0})),e.addBehavior(new wu({mode:a?`countdown`:`clock`,label:l}))}},qp=class{priority=50;id=`children`;match(e,t){return e&&e.length>0&&e[0].children&&e[0].children.length>0}apply(e,t,n){let r=t[0].children.filter(e=>e.length>0),i=e.hasRoundConfig(),a=e.getBehavior(bu),o=!!a;i||(o?e.asRepeater({totalRounds:void 0,startRound:1,addCompletion:!1}):e.asRepeater({totalRounds:1,startRound:1,addCompletion:!0}));let s=o||i,c=i?`rounds-remaining`:`timer-active`,l=o&&a?.config.mode===`reset-interval`;e.asContainer({childGroups:r,addLoop:s,loopConfig:s?{condition:c}:void 0,injectRest:l}),e.declareExit(`deferred`)}},Jp=class{priority=15;id=`report-output`;match(e,t){return e&&e.length>0}apply(e,t,n){e.hasBehavior(gf)||e.addBehavior(new gf)}},Yp=class{priority=20;id=`sound`;match(e,t){return e.length>0}apply(e,t,n){if(e.hasBehavior(wf)||!e.hasTimerBehavior())return;let r=kf(t,n.options?.soundOptions);e.addBehavior(new wf({profile:r}))}},Xp=class e{now;name=`next`;timestamp;_data;static _counter=0;constructor(t,n=El){this.now=n;let r=this.now.nowMs();e._counter++,this.timestamp=new Date(r+e._counter),this._data=t}get data(){return this._data}set data(e){this._data=e}toJSON(){return{name:this.name,timestamp:this.timestamp,data:this._data}}},Zp=new Ya([new Vp,new Hp,new Kp,new Gp,new Wp,new Yp,new Jp,new qp,new Up]);Zp.list();function Qp(e){let t=new If;for(let n of e??Zp.list())t.registerStrategy(n);return t}var $p=class{id;onStackSnapshotCallback;onOutputCallback;constructor(e){this.id=e?.id??`local`,this.onStackSnapshotCallback=e?.onStackSnapshot,this.onOutputCallback=e?.onOutput}onStackSnapshot(e){this.onStackSnapshotCallback?.(e)}onOutput(e){this.onOutputCallback?.(e)}dispose(){this.onStackSnapshotCallback=void 0,this.onOutputCallback=void 0}},em=class{runtime;subscriptions=new Map;stackUnsub=null;outputUnsub=null;disposed=!1;constructor(e){this.runtime=e,this.stackUnsub=this.runtime.subscribeToStack(e=>{for(let t of this.subscriptions.values())try{t.onStackSnapshot(e)}catch(e){console.error(`[SubscriptionManager] Error in subscription '${t.id}' onStackSnapshot:`,e)}}),this.outputUnsub=this.runtime.subscribeToOutput(e=>{for(let t of this.subscriptions.values())try{t.onOutput(e)}catch(e){console.error(`[SubscriptionManager] Error in subscription '${t.id}' onOutput:`,e)}})}add(e){if(this.disposed){console.warn(`[SubscriptionManager] Cannot add subscription after dispose`);return}let t=this.subscriptions.get(e.id);t&&t.dispose(),this.subscriptions.set(e.id,e);try{e.onStackSnapshot({type:`initial`,blocks:[...this.runtime.stack.blocks],depth:this.runtime.stack.count,clockTime:this.runtime.clock.currentDate});let t=this.runtime.getOutputStatements();for(let n of t)e.onOutput(n)}catch(t){console.error(`[SubscriptionManager] Error catching up subscription '${e.id}':`,t)}}remove(e){let t=this.subscriptions.get(e);return t?(t.dispose(),this.subscriptions.delete(e),!0):!1}has(e){return this.subscriptions.has(e)}get count(){return this.subscriptions.size}dispose(){if(!this.disposed){this.disposed=!0,this.stackUnsub?.(),this.stackUnsub=null,this.outputUnsub?.(),this.outputUnsub=null;for(let e of this.subscriptions.values())try{e.dispose()}catch(t){console.error(`[SubscriptionManager] Error disposing subscription '${e.id}':`,t)}this.subscriptions.clear()}}};function tm(e){let t=e.metrics instanceof la?e.metrics.toArray():Array.isArray(e.metrics)?e.metrics:typeof e.metrics.toArray==`function`?e.metrics.toArray():[],n=eo(e);return{id:e.id,line:e.line??e.statement?.line,text:e.text??e.statement?.text,dialect:e.dialect??e.statement?.dialect,outputType:e.outputType,timeSpan:e.timeSpan?{started:e.timeSpan.started,ended:e.timeSpan.ended}:void 0,metrics:t,hints:n.length>0?n:void 0,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,parent:e.parent,sourceStatementId:e.sourceStatementId,completionReason:e.completionReason}}var nm=[`reps`,`distance`,`resistance`,`elapsed`,`power`,`pace`],rm=[`totalVolume`,`totalDistance`,`tis`,`sessionLoad`],im=[`sum`,`avg`,`min`,`max`,`count`,`last`,`delta`],am=[`domain`,`format`,`equipment`,`quality`,`intent`],om=[...am,`effort`,`discipline`,`intensity`,`grade`,`note`,`page`,`origin`,`grain`,`metric`,`block`,`result`,`tags`],sm=[`type`,`text`,`source`,`notebook`,`contributes`,`feed`,`subscribed`],cm=[`effort`,`discipline`,`intensity`,`origin`,`text`],lm=[`day`,`week`,`session`,`round`],um=[`calc.metMinutes`,`calc.acwr`,`calc.monotony`,`calc.strain`,`calc.e1rm`,`calc.ctl`,`calc.atl`,`calc.tsb`,`calc.soreness`,`calc.sleep`,`calc.hrv`,`calc.readiness`,`calc.mvcBw`,`calc.ef`,`calc.adherence`,`calc.pct1rm`,`calc.sends`],dm=[`low`,`moderate`,`high`],fm=[`summary`,`event`],pm=[`note`,`block`,`effort`,`session`,`segment`,`event`,`notebook`,`page`,`tag`,`equipment`],mm=[`journal`,`notebooks`,`guides`,`playground`,`dashboards`,`efforts`,`equipment`],hm=[`note`,`notes`,`block`,`effort`,`session`,`segment`,`event`,`journal`,`notebook`,`notebooks`,`playground`,`page`,`tag`,`equipment`,`dashboard`],gm={journal:`journal`,notebooks:`notebooks`,playground:`playground`},_m=[`notes`],vm={dashboard:`dashboard`},ym=[],bm=im,xm=[`timeseries`,`bar`,`table`,`donut`,`toplist`,`value`],Sm=[`@session`,`@today`],Cm=Sa;[...om];var wm=[`2w`,`4w`],Tm=[`kg`,`lb`],Em=[`date`,`day`,`week`,`month`,`year`,`discipline`,`origin`,`source`,`notebook`,`kind`,`type`,`tag`,`feed`],Dm={time:!0,groupby:!0,rollup:!0,unit:!0,where:!0,agg:!0},Om=om.filter(e=>e!==`metric`),km=om.filter(e=>e!==`tags`),Am=new Set([...Om.map(e=>e===`tags`?`tag`:e),`time`,`groupby`,`rollup`,`unit`,`where`,`agg`,`metric`]),jm={notebook:new Set([`text`,`notebook`,`tag`,`effort`,...am,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`]),note:new Set([`text`,`notebook`,`tag`,`effort`,...am,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`]),block:new Set([`text`,`notebook`,`tag`,`effort`,`type`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`]),effort:new Set([...cm,`groupby`]),session:new Set([`result`,`block`,`note`,`plane`,`time`,`groupby`]),segment:new Set([...km,`time`,`groupby`,`unit`]),event:new Set([...km,`time`,`groupby`,`unit`]),page:new Set([`page`,`notebook`,`text`,`note`,`time`]),tag:new Set([`tag`,`type`,`text`,`contributes`,`time`]),equipment:new Set([`equipment`,`tags`,`text`,`notebook`,`time`])},Mm=new Set,Nm=om,Pm=Object.fromEntries(Object.entries(jm).map(([e,t])=>[e,[...t].filter(e=>!Dm[e]).map(e=>e===`tag`?`tags`:e)])),Fm=[`day`,`week`,`session`,`round`,...om],Im=[`date`,`effort`,`discipline`,...nm,...rm,...um];function Lm(e,t){return t===`aggregate`?Am:jm[e]??Mm}function Rm(e,t){return t===`aggregate`?Nm:Pm[e]??[]}function zm(e,t){return t===`aggregate`?Fm:e===`segment`||e===`event`?Im:Em}function Bm(e,t,n){let r=n===`tag`?`tags`:n;return t===`aggregate`||e===`segment`||e===`event`?!sm.includes(r)&&r!==`plane`&&(t!==`find`||r!==`tags`):Rm(e,t).includes(r)}var Vm=_i.deserialize({version:14,states:"+dOVQPOOOOQO'#Cb'#CbObQPO'#C`OgQPO'#C`OlQPO'#ClOqQQO'#C_OOQO'#C_'#C_O!SQQO'#CnQOQPOOOOQO,58z,58zO!bQPO,58zOOQO,59W,59WO!gQPO'#CdOOQO,58y,58yOVQPO,58xO!rQPO'#CoO!wQPO'#CrOOQO,59Y,59YO!|QPO,59YO#UQQO'#CcOOQO1G.f1G.fOOQO'#Cg'#CgO#jQPO'#CeO#oQPO'#CeOOQO,59O,59OO#tQPO,59OO#|QPO'#C_O$XQPO1G.dO$aQPO,59ZO$iQQO,59^OOQO1G.t1G.tO$nQPO'#CuO$sQQO,58}O%XQPO,59PO%dQPO,59PO%iQPO'#CxO%qQPO1G.jOOQO1G.j1G.jOVQPO'#CyO%yQPO7+$OOOQO'#Cq'#CqOOQO1G.u1G.uO&RQPO1G.uO&ZQPO1G.xOOQO,59a,59aOOQO-E6s-E6sOOQO'#Ci'#CiO&`QPO'#CiO&tQPO'#CiO'SQPO'#ChOOQO1G.k1G.kO%XQPO1G.kOOQO,59d,59dOOQO-E6v-E6vOOQO7+$U7+$UO'_QPO'#CcOOQO,59e,59eOOQO-E6w-E6wO'mQPO'#CzO'rQPO7+$aOOQO7+$a7+$aO'zQPO7+$dO(PQPO'#CvO(UQPO,59TOOQO,59T,59TO%XQPO'#CwO(jQPO,59SOOQO7+$V7+$VO(uQPO,58}OOQO,59f,59fOOQO-E6x-E6xOOQO<<G{<<G{OOQO<<HO<<HOOOQO,59b,59bOOQO-E6t-E6tOOQO1G.o1G.oOOQO,59c,59cOOQO-E6u-E6uO)TQPO,58zO)YQPO'#C`",stateData:")_~OqOS~OTPOaSOrQO~OTXO~OrYO~OTZO~Ot[OdRXgRXoRXuRX~Od_Og`Ou^OobX~OTcO~OTeOYgOwhO~OtlO~OxmO~Og`Ooba~OsoOdVXgVXoVXtVXuVX~OrqO~OTeO~OvsOwuO~Ot[OoRXuRX~OuvOoQi~OTxOwyO~Oh{O~OT|O~OsoOdVagVaoVatVauVa~OT!PO^!OO_!QO~Or!TO~OTeOYgO~OvsOw!WO~OuvOoQq~Ov![Ow!^O~OT!_O~O^!bOr!`Os!`Ou]Xv]Xw]X~O^!bOu]Xv]Xw]X~Ou!cOv[Xw[X~OsoOoVXtVXuVX~OTxO~Ov![Ow!iO~Oy!jO~OT!kO~O^!mOr!`Os!`Ou]av]aw]a~Ou!cOv[aw[a~OsoOoVatVauVa~OT!XO~Or!pO~O",goto:"$^oPPps|P!T![!`!dP!j!q!wPP#OPp#TP#W#^PP#d#n#t#z$Q$WRWOQVOQk^R!YvQTOTj^vQROT!q^vTdY!pT]TjQi[R!UsSf[sRrgQ!SqR!e!TS!Rq!TR!n!cVUO^vRbVQzlR!g![QaVRnbQpcS}p!fR!f!XQ!a!PR!l!aQ!d!RR!o!dQtiR!VtQwkR!ZwQ!]zR!h!]",nodeNames:`⚠ Query Pipeline Stage Head Word Aggregator Metric Filters Filter Negate TagKey TagValue Value Star Quoted DatasetReference At Single GroupBy By Dimension Rollup RollupDot Int`,maxTerm:41,skippedNodes:[0],repeatNodeCount:6,tokenData:"'i~RgXY!jYZ!j]^!jpq!jqr!{rs#Qxy#oyz#tz{#y|}$O}!O$T!O!P$i!Q![%f![!]%|!b!c&R!c!}$T#R#S$T#T#U$T#U#V&W#V#o$T#o#p'Y#p#q'_#q#r'd~!oSq~XY!jYZ!j]^!jpq!j~#QOY~~#TTOr#Qrs#ds;'S#Q;'S;=`#i<%lO#Q~#iO_~~#lP;=`<%l#Q~#tOx~~#yOy~~$OO^~~$TOv~P$YTTP}!O$T!Q![$T!c!}$T#R#S$T#T#o$T~$nPs~#f#g$q~$tP#c#d$w~$zP#`#a$}~%QP#`#a%T~%WP#i#j%Z~%^P#d#e%a~%fOg~R%mThQTP}!O$T!Q![%f!c!}$T#R#S$T#T#o$T~&ROr~~&WOa~R&]VTP}!O$T!Q![$T!c!}$T#R#S$T#T#m$T#m#n&r#n#o$TR&yTdQTP}!O$T!Q![$T!c!}$T#R#S$T#T#o$T~'_Ot~~'dOu~~'iOw~",tokenizers:[0,1],topRules:{Query:[0,1]},tokenPrec:0});function Hm(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`{`)t++;else if(r===`}`)t=Math.max(0,t-1);else if(t===0&&r===`w`&&e.slice(n,n+5)===`where`&&(n===0||/\s/.test(e[n-1]))&&(n+5>=e.length||/\s/.test(e[n+5])))return{primary:e.slice(0,n).trim(),where:e.slice(n+5).trim()}}return{primary:e.trim()}}var Um=/\s*=>\s*@?([a-zA-Z0-9_-]+)\s*$/,Wm=/^@([a-zA-Z0-9_-]+)\s*(?:\||=>)\s*/,Gm=/\s+(?:in|from)\s+@([a-zA-Z0-9_-]+)\s*$/i,Km=/\s+in\s+([a-zA-Z0-9_-]+)\s*$/,qm=/\.rollup\((\d+)?([a-zA-Z]*)\)\s*$/,Jm=/\s+by\s+\{([^}]*)\}\s*$/,Ym=/\s+last\s+(\d+)([dw])\s*$/i,Xm=/\s+from\s+(\d{4}-\d{2}-\d{2})(?:\s+to\s+(\d{4}-\d{2}-\d{2}))?\s*$/i;function Zm(e){let{primary:t,where:n}=Hm(e),r=t.trim(),i,a,o,s,c,l,u,d=[],f=r.match(Wm);f&&(a=`@`+f[1],r=r.slice(f[0].length).trim());let p=r.startsWith(`find:`),m=/^rows(?=[:{]|\s|$)/.test(r),h=e=>{let t=[];for(let n=e.exec(r);n;n=e.exec(r))t.unshift(n),r=r.slice(0,n.index).trim();return t},g=(e,t)=>{t.length>1&&d.push(`Duplicate '${e}' clause: '${t[0][0].trim()}' conflicts with '${t[t.length-1][0].trim()}'`)},_=h(Um);g(`=>`,_),_.length&&(i=`@`+_[_.length-1][1]);let v=h(Xm),y=h(Ym);{let e=[...v.map(e=>({kind:`range`,start:e[1],end:e[2],raw:e[0].trim(),at:e.index})),...y.map(e=>({kind:`relative`,size:parseInt(e[1],10),unit:e[2].toLowerCase(),raw:e[0].trim(),at:e.index}))].sort((e,t)=>e.at-t.at);if(e.length>1&&d.push(`Duplicate 'window' clause: '${e[0].raw}' conflicts with '${e[e.length-1].raw}'`),e.length===1){let t=e[0];l=t.kind===`range`?{kind:`range`,start:t.start,end:t.end,raw:t.raw}:{kind:`relative`,size:t.size,unit:t.unit,raw:t.raw}}}let b=h(Km);if(g(p||m?`scope`:`display-unit`,b),b.length){let e=b[b.length-1][1];e===`kg`||e===`lb`?o=e:p||m?u=e:o=e}let x=h(qm);if(g(`.rollup`,x),x.length){let e=x[x.length-1];s={size:e[1]?parseInt(e[1],10):1,unit:e[2]||``,raw:e[1]+e[2]}}let S=h(Jm);g(`by`,S),S.length&&(c=S[S.length-1][1].split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean));let C=h(Gm);return C.length&&(a=`@`+C[C.length-1][1]),{where:n,storedAs:i,sourceRef:a,displayUnit:o,rollup:s,groupBy:c,window:l,legacyScope:u,conflicts:d.length?d:void 0,primaryText:Qm(r)}}function Qm(e){let t=e.indexOf(`{`),n=t===-1?-1:e.lastIndexOf(`}`);if(t===-1||n<=t)return e;let r=e.slice(t+1,n);if(!r.includes(`,`))return e;let i=[],a=``,o=!1;for(let e of r)e===`"`&&(o=!o),e===`,`&&!o?(i.push(a),a=``):a+=e;i.push(a);let s=[];for(let e=0;e<i.length;e++){let t=i[e];for(;e+1<i.length;){let n=i[e+1].trim();if(n&&!n.includes(`:`)&&!n.includes(`"`))t=`${t}|${n}`,e++;else break}s.push(t)}return`${e.slice(0,t+1)}${s.join(`,`)}${e.slice(n)}`}function $m(e){let t={},n=e.split(`|`).map(e=>e.trim()).filter(Boolean);for(let e of n){let n=e.toLowerCase();if(n.startsWith(`select`))t.select=e.slice(6).trim().split(`,`).map(e=>{let t=/^([\w-]+)(?:\s+in\s+([\w/%]+))?$/i.exec(e.trim());return t?{col:t[1],...t[2]?{unit:t[2]}:{}}:{col:e.trim()}});else if(n.startsWith(`order by`))t.order=e.slice(8).trim().split(`,`).map(e=>{let t=/^(\S+)(?:\s+(asc|desc))?$/i.exec(e.trim());return{col:t?.[1]??e.trim(),dir:t?.[2]?.toLowerCase()??`asc`}});else if(n.startsWith(`limit`)){let n=/^limit\s+(\d+)(?:\s+offset\s+(\d+))?$/i.exec(e);if(!n)return t.error=`Cannot parse pipe "${e}". Expected limit <n> [offset <m>]`,t;t.limit=Number(n[1]),n[2]&&(t.offset=Number(n[2]))}else if(n.startsWith(`offset`)){let n=/^offset\s+(\d+)$/i.exec(e);if(!n)return t.error=`Cannot parse pipe "${e}". Expected offset <n>`,t;t.offset=Number(n[1])}else return t.error=`Unknown pipe "${e}". Try: select, order by, limit`,t}return t}function eh(e){return e.family===`find`}function th(e){return e.family===`aggregate`}function nh(e){return e.family===`pipeline`}var rh=im;function ih(e){return`Cannot parse "${e}". Expected agg:metric{filters} by {dims} .rollup(period)`}var ah=/^(.+?)\s*(>=|<=|!=|==|>|<)\s*(-?\d+(?:\.\d+)?)\s*$/;function oh(e){return`Cannot parse join "${e}". Expected :source{filters} or find:target{filters}, or agg:metric{filters} <op> <number>`}function sh(e){let t=e.trimStart(),n=/^:?([a-zA-Z0-9_-]+)/.exec(t)?.[1]?.toLowerCase()??``;if(t.startsWith(`find:`)||t.startsWith(`:`)&&hm.includes(n)){let n=kh(e,{colon:t.startsWith(`:`)});return n.error?{error:n.error}:n.window?.kind===`range`?{error:`Range windows are not supported on join halves — use last <n>d|w`}:{find:{target:n.target,filters:n.filters,last:n.window?.kind===`relative`?{size:n.window.size,unit:n.window.unit}:void 0},advisories:n.advisories}}let r=ah.exec(e.trim());if(!r)return{error:oh(e)};let i=Dh(r[1].trim(),{colon:r[1].trimStart().startsWith(`:`)});return i.error?{error:i.error}:{metric:{agg:i.agg,metric:i.metric,filters:i.filters,operator:r[2],threshold:parseFloat(r[3])}}}function ch(e){let t=/^rows(?::(\w+))?\{([^}]*)\}/.exec(e);if(!t)return`The "rows:" query family is retired — use :session, :segment, or :event instead.`;let n=t[1]??`all`,r=t[2].trim();return n===`all`||[`note`,`block`,`effort`,`page`].includes(n)?`rows:${n}{…} is retired — use :session{${r}} instead.`:n===`segment`&&!r.includes(`result:`)&&!r.includes(`block:`)&&!r.includes(`note:`)?`rows:segment{…} is retired — use :segment{${r}} instead.`:n===`event`?`rows:event{…} is retired — use :event{${r}} instead.`:`rows:${n}{…} is retired — use :session{${r?`${r}, plane:${n}`:`plane:${n}`}} instead.`}var lh=/^\s*(?:select|order\s+by|limit|offset)\b/i;function uh(e){let t=[],n=0,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(r){o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}o===`{`?n++:o===`}`?n=Math.max(0,n-1):o===`|`&&n===0&&(t.push(e.slice(i,a)),i=a+1)}return t.push(e.slice(i)),t}function dh(e){let t=/^\s*([:@])([a-zA-Z0-9_-]+)/.exec(e);return t?{name:t[2].toLowerCase(),dataset:t[1]===`@`}:void 0}function fh(e){return`Cannot parse pipeline "${e}". Expected :source{filters} | :function{metric:key} | :chart{params} or @dataset | :function{…}`}function ph(e){return{family:`find`,raw:e,target:``,filters:[],error:`The "find:" query family is retired — use the :${(/^find:([a-zA-Z0-9_-]*)/.exec(e.trim())?.[1]??``)||`note`}{…} colon head instead.`}}function mh(e){let t=gh(e),n=dh(t.query),r;return r=n&&!n.dataset?bm.includes(n.name)?Dh(t.query,{colon:!0}):(hm.includes(n.name),kh(t.query,{colon:!0})):Dh(t.query,{colon:!1}),t.advisories.length&&(r.advisories=[...new Set([...r.advisories??[],...t.advisories])]),r.raw=e,r}function X(e){let t=e.trimStart();if(/^rows(?=[:{]|\s|$)/.test(t))return{family:`find`,raw:e,target:``,filters:[],error:ch(e.trim())};if(/^find:/.test(t))return ph(e);let n=uh(e),r=n[0];if(n.length>1&&!lh.test(r)&&n.slice(1).every(e=>lh.test(e.trim())))return mh(e);let i=dh(r);return n.length>1||i&&(i.dataset||xm.includes(i.name))?jh(e,n):mh(e)}function hh(e){return e.replace(/\bnotebook:notebook\/([a-zA-Z0-9_-]+)/g,`notebook:"notebook/$1"`)}function gh(e){let t=[],n=hh(e.trim()),{primary:r,where:i}=Hm(n);if(r.startsWith(`find:`)){let e=Zm(r);if(e.legacyScope&&!e.conflicts?.length){t.push(`Legacy 'in <scope>' syntax is deprecated; use 'source:<scope>' filter instead.`);let r=e.legacyScope,a=e.primaryText.trim();if(r!==`all`){let e=a.indexOf(`{`),t=a.lastIndexOf(`}`);if(e!==-1&&t!==-1&&t>e){let n=a.slice(0,e+1),i=a.slice(e+1,t).trim(),o=a.slice(t);a=`${n}${i?`${i},source:${r}`:`source:${r}`}${o}`}else a=`${a}{source:${r}}`}let o=[a];e.groupBy&&o.push(`by {${e.groupBy.join(`, `)}}`),e.rollup&&o.push(`.rollup(${e.rollup.raw})`),e.window&&o.push(e.window.raw),i&&o.push(`where ${i}`),n=o.join(` `)}}return{query:n,advisories:t}}function _h(e){for(let t of e)if(t.key===`source`)for(let e of t.values){let t=e.value;if(t===`page`||t===`pages`)return`source:${t} is retired — page-ness is handled by type:page or source:guides.`;if(t===`all`)return`source:all is retired — omit the source: filter to query all sources.`;if(t===`notebook`)return`source:notebook is retired — :notebook{} is the notebook plane (every notebook); narrow it with the notebook: filter, e.g. :notebook{notebook:journal}.`;if(t===`feed`||t===`feeds`||t.startsWith(`feed:`))return`source:${t} is retired — the feed corpus is the notebook plane; use feed:<feedId> or source:notebooks.`;if(t===`collection`||t===`collections`||t.startsWith(`collection:`))return`source:${t} is retired — collections are notebooks; use source:notebooks or notebook:<slug>.`;if(!(mm.includes(t)||t.startsWith(`notebook:`)||t.startsWith(`notebook/`)))return`Unknown source "${t}". Try: ${mm.join(`, `)} (or notebook:<slug>)`}}function vh(e){for(let t of e)if(t.key===`subscribed`){for(let e of t.values)if(e.value!==`true`&&e.value!==`false`)return`Invalid subscribed: value '${e.value}' — expected true or false`}}function yh(e){for(let t of e)if(t.key===`feed`){for(let e of t.values)if(!e.value&&!e.wildcard)return`Invalid feed: value — expected a non-empty feed identifier or wildcard`}}function bh(e){let t=-1,n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){a===`"`&&(r=!1);continue}if(a===`"`){r=!0;continue}if(a===`{`)n++;else if(a===`}`)n=Math.max(0,n-1);else if(a===`|`&&n===0){t=i;break}}if(t!==-1){let n=e.slice(t+1);return{text:e.slice(0,t).trimEnd(),pipes:$m(n)}}return{text:e}}function xh(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(n,r-1,i);return a.getFullYear()===n&&a.getMonth()===r-1&&a.getDate()===i}function Sh(e){if(!e)return{};if(e.kind===`relative`)return{window:{kind:`relative`,size:e.size,unit:e.unit}};for(let t of[e.start,e.end])if(t!==void 0&&!xh(t))return{error:`Invalid window date "${t}" — expected a real calendar date YYYY-MM-DD`};return{window:{kind:`range`,start:e.start,end:e.end}}}function Ch(e){if(e.some(e=>e.key===`grain`&&e.values.some(e=>e.value===`rollup`)))return`grain:rollup is retired — rollup grains are never stored; compute them with the .rollup suffix`}function wh(e,t){let n=[],r=e.getChild(8);if(!r)return n;for(let e of r.getChildren(9)){let r=e.getChild(11),i=e.getChild(12);if(!r||!i)continue;let a=[];for(let e of i.getChildren(13)){let n=t.slice(e.from,e.to),r=e.getChild(15)!==null,i=r?n.slice(1,-1):n,o=!r&&i.endsWith(`*`);o&&(i=i.slice(0,-1)),!(!i&&!o)&&a.push({value:i,wildcard:o})}a.length!==0&&n.push({key:t.slice(r.from,r.to),negate:e.getChild(10)!==null,values:a})}return n}function Th(e){return e.getChild(18)?.getChild(3)??e.getChild(3)??void 0}function Eh(e){return`Cannot parse "${e}". Expected :function{metric:<key>, filters} by {dims} .rollup(period) — e.g. :sum{metric:tis}`}function Dh(e,t){let n=Zm(e),{where:r,displayUnit:i,groupBy:a,rollup:o,window:s,primaryText:c}=n,l=Sh(s),u={family:`aggregate`,raw:e,agg:`sum`,metric:``,filters:[],groupBy:a??[],displayUnit:i,rollup:o?{size:o.size,unit:o.unit}:void 0,window:l.window};if(l.error)return u.error=l.error,u;if(n.conflicts?.length)return u.error=n.conflicts.join(`; `),u;if(o){if(o.unit!==`d`&&o.unit!==`w`)return u.error=ih(c),u;if((o.unit===`d`||o.unit===`w`)&&o.size===1)return u.error=`.rollup(1${o.unit}) is retired — use by {${o.unit===`d`?`day`:`week`}} instead.`,u}let d=Vm.parse(c),f=!1;if(d.iterate({enter(e){e.type.isError&&(f=!0)}}),f)return u.error=ih(c),u;let p=d.topNode,m=Th(p),h=m?.getChild(4),g=h?.getChild(6),_=h?.getChild(7);if(u.filters=m?wh(m,c):[],t.colon){let e=h?.getChild(5);if(!h||!e)return u.error=Eh(c),u;let n=c.slice(e.from,e.to).toLowerCase();if(!bm.includes(n))return u.error=`Unknown function ":${n}". Try: ${bm.join(`, `)}`,u;u.agg=n;let r=u.filters.filter(e=>e.key===`metric`);u.filters=u.filters.filter(e=>e.key!==`metric`);let i=r[0];if(!i){if(n!==`count`&&t.inheritedMetric===void 0)return u.error=`:${n} requires 'metric:<key>' — e.g. :${n}{metric:tis}`,u;u.metric=n===`count`?``:t.inheritedMetric}else if(i.negate||r.length>1||i.values.length!==1||i.values[0].wildcard)return u.error=`:${n} takes a single 'metric:<key>' clause — no negation, OR values, or wildcards`,u;else u.metric=i.values[0].value}else{if(!m||!h||!g||!_)return u.error=ih(c),u;let e=c.slice(g.from,g.to);if(!rh.includes(e))return u.error=`Unknown aggregator "${e}". Try: ${rh.join(`, `)}`,u;u.agg=e,u.metric=c.slice(_.from,_.to)}let v=u.filters.map(e=>e.key).filter(e=>sm.includes(e));if(v.length>0)return u.error=`Content filter key(s) ${v.map(e=>`"${e}"`).join(`, `)} cannot narrow an aggregate — facts carry effort/dimension data, not note text. Aggregate dims: ${om.join(`, `)}, plus any custom dimension.`,u;let y=Ch(u.filters);if(y)return u.error=y,u;if(r){let e=sh(r);if(e.error)return u.error=e.error,u;if(e.advisories?.length&&(u.advisories=[...u.advisories??[],...e.advisories]),!e.find)return u.error=`Cross-store join on an analytics query must be find:…, got "${r}"`,u;u.join=e.find}return u}function Oh(e){return`Cannot parse "${e}". Expected :source{key:value, !key:value}; filters are optional. Optional suffixes include by {dimension}, last <n>d or last <n>w, from YYYY-MM-DD [to YYYY-MM-DD], where <aggregator>:<metric>{filters} <operator> <number>, and | order by <column> | limit <n>. Support depends on the target.`}function kh(e,t){let{text:n,pipes:r}=bh(hh(e)),i=Zm(n),{where:a,window:o,legacyScope:s,groupBy:c,displayUnit:l,primaryText:u}=i,d=Sh(o),f=[];s&&f.push(`Legacy 'in <scope>' syntax is deprecated; use 'source:<scope>' filter instead.`);let p={family:`find`,raw:e,target:``,filters:[],window:d.window,...r?{pipes:r}:{},...c?{groupBy:c}:{},...l?{displayUnit:l}:{},...f.length?{advisories:f}:{}};if(d.error)return p.error=d.error,p;if(r?.error)return p.error=r.error,p;if(i.conflicts?.length)return p.error=i.conflicts.join(`; `),p;let m=Vm.parse(u),h=!1;if(m.iterate({enter(e){e.type.isError&&(h=!0)}}),h)return p.error=Oh(u),p;let g=Th(m.topNode),_=g?.getChild(4),v=_?.getChild(6),y=_?.getChild(7),b;if(t?.colon){let e=_?.getChild(5);if(!g||!_||!e)return p.error=Oh(u),p;b=u.slice(e.from,e.to).toLowerCase()}else{if(!g||!_||!v||!y)return p.error=Oh(u),p;let e=u.slice(v.from,v.to);if(e!==`find`)return p.error=`Expected "find:" but got "${e}:"`,p;b=u.slice(y.from,y.to)}let x=gm[b],S=vm[b];if(x||S)p.target=`note`;else if(p.target=_m.includes(b)?`note`:b,!pm.includes(p.target))return p.error=`Unknown find target "${p.target}". Try: ${pm.join(`, `)}`,p;p.filters=wh(g,u),S&&p.filters.unshift({key:`type`,negate:!1,values:[{value:S,wildcard:!1}]}),x&&p.filters.push({key:`source`,negate:!1,values:[{value:x,wildcard:!1}]});let C=t?.colon&&p.displayUnit&&p.displayUnit!==`kg`&&p.displayUnit!==`lb`?p.displayUnit:s;t?.colon&&C&&(delete p.displayUnit,f.push(`Legacy 'in <scope>' syntax is deprecated; use 'source:<scope>' filter instead.`)),C&&C!==`all`&&p.filters.push({key:`source`,negate:!1,values:[{value:C,wildcard:!1}]});let w=_h(p.filters);if(w)return p.error=w,p;let T=vh(p.filters);if(T)return p.error=T,p;let E=yh(p.filters);if(E)return p.error=E,p;let D=Ch(p.filters);if(D)return p.error=D,p;let O=p.target;if(i.rollup&&f.push(`:${O} ignores '.rollup(...)'; rollup is supported by aggregate queries.`),a){let e=sh(a);if(e.error)return p.error=e.error,p;if(!e.metric)return p.error=`Cross-store join on a find query must be agg:metric{} <op> <number>, got "${a}"`,p;p.join=e.metric}let k=Mh(p);return(f.length||k.length)&&(p.advisories=[...new Set([...f,...k])]),p}function Ah(e){return e?e.dataset?`dataset`:bm.includes(e.name)?`function`:hm.includes(e.name)?`source`:xm.includes(e.name)?`chart`:`unknown`:`unknown`}function jh(e,t){let n=[],r=t=>({family:`pipeline`,raw:e,source:{kind:`dataset`,name:``},transforms:[],error:t}),i=t.map(dh),a=i.map(Ah),o;if(!i[0]){if(lh.test(t[0]))return r(`Presentation pipes (| select / order by / limit) apply to a single source query — they cannot sit between pipeline stages.`);let e=Dh(t[0],{colon:!1});if(e.error)return r(e.error);o=e,a[0]=`function`}for(let e=0;e<t.length;e++){if(e===0&&o)continue;let n=i[e]?`:${i[e].name}`:`"${t[e].trim()}"`;if(!i[e])return r(`Empty or unparseable pipeline stage ${n} — check for doubled or trailing "|".`);if(a[e]===`unknown`)return r(`Unknown pipeline head ${n}. Sources: ${hm.join(`, `)}; functions: ${bm.join(`, `)}; charts: ${xm.join(`, `)}.`);if(e>0&&(a[e]===`source`||a[e]===`dataset`))return r(`Pipeline stage ${n} must come first — a pipeline starts at its source, transforms follow.`);if(a[e]===`chart`&&e<t.length-1)return r(`Chart head ${n} must be the final pipeline stage — nothing may follow a chart.`)}let s=t.map(e=>Zm(e).primaryText.trim()).join(` | `),c=Vm.parse(s),l=!1;c.iterate({enter(e){e.type.isError&&(l=!0)}});let u=l?void 0:c.topNode.getChild(2),d=l?void 0:c.topNode.getChild(18),f=u?u.getChildren(3):d?[d.getChild(3)].filter(e=>e!==null):[];if(!u&&t.length>1||f.length!==t.length)return r(fh(e));let p=t.length-1,m;if(a[0]===`dataset`)m={kind:`dataset`,name:`@`+i[0].name};else if(a[0]===`chart`)m={kind:`query`,query:{family:`find`,raw:`:segment{}`,target:`segment`,filters:[]}};else{let e=a[0]===`function`?Dh(t[0],{colon:t[0].trimStart().startsWith(`:`)}):kh(t[0],{colon:!0});if(e.error)return r(e.error);m={kind:`query`,query:e}}let h=[],g=m.kind===`query`&&m.query.family===`aggregate`?m.query.metric:void 0,_=a[p]===`chart`?p-1:p;for(let e=1;e<=_;e++){let n=Dh(t[e],{colon:!0,inheritedMetric:g});if(n.error)return r(n.error);h.push(n),g=n.metric||g}let v;if(a[p]===`chart`){let i=f[p],a=i.getChild(4)?.getChild(5);if(!a)return r(fh(e));let o=s.slice(a.from,a.to).toLowerCase();if(!xm.includes(o))return r(`Unknown chart head ":${o}". Try: ${xm.join(`, `)}`);let c=Zm(t[p]);(c.window||c.rollup||c.groupBy||c.displayUnit||c.where||c.legacyScope)&&n.push(`:${o} ignores query suffixes — apply windows and grouping to the source or function stages.`),v={head:o,filters:wh(i,s)}}return{family:`pipeline`,raw:e,source:m,transforms:h,...v?{sink:v}:{},...n.length?{advisories:n}:{}}}function Mh(e){let t=[],n=e.target,r=Lm(n,`find`),i=[...new Set(e.filters.filter(e=>!Bm(n,`find`,e.key)).map(e=>e.key))];if(i.length){let e=n===`segment`||n===`event`?`, custom fact dimensions`:``,r=i.find(e=>cm.includes(e)),a=r&&n!==`effort`?` To filter by ${r}, use :effort{${r}:…}.`:``;t.push(`:${n} ignores ${i.map(e=>`'${e}:'`).join(`, `)} — the filter is not applied.${a} Supported keys: ${Rm(n,`find`).join(`, `)}${e}.`)}for(let r of e.filters){if(i.includes(r.key))continue;let e=[`result`,`block`,`note`].includes(r.key),a=n===`note`?[`effort`,`text`,`type`,`domain`,`format`,`equipment`,`quality`,`intent`].includes(r.key):n===`block`?[`text`,`type`,`tags`,`effort`].includes(r.key):(n===`session`||n===`segment`||n===`event`)&&e;r.negate&&a&&t.push(`:${n} does not support '!${r.key}:' negation; this clause is not applied as a negated filter.`);let o=n===`effort`?[`effort`,`text`].includes(r.key):(n===`segment`||n===`event`)&&!e;r.values.some(e=>e.wildcard)&&!o&&t.push(`:${n} does not support '${r.key}:…*' wildcards; values are matched without wildcard expansion.`)}if(e.window&&!r.has(`time`)&&t.push(`:${n} ignores the window because its registry has no time dimension.`),e.groupBy?.length){let r=zm(n,`find`),i=e.groupBy.filter(e=>!r.some(t=>t.toLowerCase()===e.toLowerCase()));if(n!==`note`&&n!==`block`){if(n===`segment`||n===`event`){let i=e.pipes?.select?.map(e=>e.col),a=e.groupBy.filter(e=>i?!i.includes(e):!r.includes(e));a.length&&t.push(`:${n} groups only emitted table columns; ${a.join(`, `)} may be unassigned. Select each grouping column explicitly.`)}else i.length&&t.push(`:${n} cannot group by ${i.join(`, `)}; the view groups by content dimensions. Valid alternatives: ${r.join(`, `)}.`)}}return e.displayUnit&&!r.has(`unit`)&&t.push(`:${n} ignores the display unit 'in ${e.displayUnit}'.`),e.join&&!r.has(`where`)&&t.push(`:${n} ignores the 'where' join; joins are supported by :note and :block.`),e.pipes?.select&&n!==`segment`&&n!==`event`&&t.push(`:${n} ignores '| select'; the result keeps its original fields.`),e.pipes?.order&&n===`session`&&t.push(`:session ignores '| order by'; sessions remain ordered by completion time.`),[...new Set(t)]}function Nh(e){let t=e.filters[0];return e.target===`note`&&e.sourceScope===void 0&&!!t&&t.key===`type`&&!t.negate&&t.values.length===1&&!t.values[0].wildcard&&t.values[0].value===vm.dashboard}function Ph(e,t=[]){if(Nh(e)){let n=[...e.filters.slice(1),...t];return`:dashboard${n.length?`{${Vh(n)}}`:``}`}let n=[...e.filters,...t];return`:${e.target}${n.length?`{${Vh(n)}}`:``}`}function Fh(e){return e.target!==`note`||e.filters.some(e=>e.key===`source`)||Nh(e)||!e.sourceScope?.length?{clause:``,scopeFilters:[]}:{clause:``,scopeFilters:[{key:`source`,negate:!1,values:e.sourceScope.map(e=>({value:e,wildcard:!1}))}]}}function Ih(e){let t=Fh(e),n=[Ph(e,t.scopeFilters)];return e.groupBy?.length&&n.push(`by {${e.groupBy.join(`, `)}}`),e.displayUnit&&n.push(`in ${e.displayUnit}`),n.push(t.clause),n.push(Kh(e.window)),e.join&&n.push(`where ${Gh(e.join)}`),n.filter(Boolean).join(` `)}function Lh(e){let t=e.metric?[{key:`metric`,negate:!1,values:[{value:e.metric,wildcard:!1}]},...e.filters]:e.filters,n=`:${e.agg}{${Vh(t)}}`;e.groupBy.length&&(n+=` by {${e.groupBy.join(`, `)}}`),e.rollup&&(n+=`.rollup(${e.rollup.size}${e.rollup.unit})`),e.displayUnit&&(n+=` in ${e.displayUnit}`);let r=Kh(e.window);return r&&(n+=` ${r}`),e.join&&(n+=` where ${Wh(e.join.target,e.join.filters,e.join.last)}`),n}function Rh(e){return e.kind===`dataset`?e.name:e.query.family===`find`?Ih(e.query):Lh(e.query)}function zh(e){let t=[Rh(e.source),...e.transforms.map(Lh)];return e.sink&&t.push(`:${e.sink.head}${e.sink.filters.length?`{${Vh(e.sink.filters)}}`:``}`),t.join(` | `)}function Bh(e){return/^[a-zA-Z0-9_-]+((:|\.)[a-zA-Z0-9_-]+)*$/.test(e)?e:`"${e}"`}function Vh(e){return e.map(e=>`${e.negate?`!`:``}${e.key}:${e.values.map(e=>Bh(e.value)+(e.wildcard?`*`:``)).join(`|`)}`).join(`,`)}function Hh(e,t,n){return`${e}:${t}{${Vh(n)}}`}function Uh(e){return Hh(e.agg,e.metric,e.filters)}function Wh(e,t,n){let r=`find:${e}${t.length?`{${Vh(t)}}`:``}`;return n?`${r} last ${n.size}${n.unit}`:r}function Gh(e){return`${Hh(e.agg,e.metric,e.filters)} ${e.operator} ${e.threshold}`}function Kh(e){return e?e.kind===`relative`?`last ${e.size}${e.unit}`:e.end?`from ${e.start} to ${e.end}`:`from ${e.start}`:``}function qh(e){if(e.error)return e.raw;if(e.family===`aggregate`){let t=e,n=Uh(t);t.groupBy.length&&(n+=` by {${t.groupBy.join(`, `)}}`),t.rollup&&(n+=`.rollup(${t.rollup.size}${t.rollup.unit})`),t.displayUnit&&(n+=` in ${t.displayUnit}`);let r=Kh(t.window);return r&&(n+=` ${r}`),t.join&&(n+=` where ${Wh(t.join.target,t.join.filters,t.join.last)}`),n}if(e.family===`find`){let t=Fh(e),n=[Ph(e,t.scopeFilters)];e.groupBy?.length&&n.push(`by {${e.groupBy.join(`, `)}}`),e.displayUnit&&n.push(`in ${e.displayUnit}`),n.push(t.clause),n.push(Kh(e.window)),e.join&&n.push(`where ${Gh(e.join)}`);let r=n.filter(Boolean).join(` `);if(e.pipes){let t=[];e.pipes.select&&t.push(`select ${e.pipes.select.map(e=>e.col+(e.unit?` in ${e.unit}`:``)).join(`, `)}`),e.pipes.order&&t.push(`order by ${e.pipes.order.map(e=>e.dir===`desc`?`${e.col} desc`:e.col).join(`, `)}`),e.pipes.limit===void 0?e.pipes.offset!==void 0&&t.push(`offset ${e.pipes.offset}`):t.push(`limit ${e.pipes.limit}${e.pipes.offset===void 0?``:` offset ${e.pipes.offset}`}`),t.length>0&&(r+=` | ${t.join(` | `)}`)}return r}return e.family===`pipeline`?zh(e):e.raw??``}var Jh=[`bodyweight`,`cycling`,`gymnastics`,`kettlebell`,`recovery`,`rowing`,`running`,`strength`,`swimming`,`walking`],Yh=Or.define({parser:Vm.configure({props:[Si({"Aggregator/Word":H.keyword,"Metric/Word":H.variableName,"Head/Word":H.keyword,DatasetReference:H.keyword,"DatasetReference/Word":H.keyword,At:H.punctuation,TagKey:H.propertyName,"TagKey/Word":H.propertyName,TagValue:H.string,"TagValue/Value/Word":H.string,"TagValue/Word":H.string,Negate:H.operator,Star:H.operator,Dimension:H.attributeName,"Dimension/Word":H.attributeName,By:H.keyword,RollupDot:H.keyword,Int:H.number,"Rollup/Word":H.unit,braceOpen:H.bracket,braceClose:H.bracket,parenOpen:H.bracket,parenClose:H.bracket,colon:H.punctuation,comma:H.punctuation,pipe:H.punctuation,dot:H.punctuation})]}),languageData:{closeBrackets:{brackets:[`{`,`(`]}}});function Xh(e){return e.map(e=>typeof e==`string`?{label:e}:e)}function Zh(e,t){let n=0,r=!1,i=-1,a=-1,o=0;for(let s=0;s<t;s++){let t=e[s];if(r){t===`"`&&(r=!1);continue}if(t===`"`){r=!0;continue}t===`{`?(n++,a=s,o=s+1):t===`}`?(n=Math.max(0,n-1),o=s+1):t===`,`&&n>0?o=s+1:t===`|`&&n===0&&(i=s+1,o=s+1)}return{depth:n,quoted:r,pipeFrom:i,lastBrace:a,fragStart:o}}function Qh(e){let t=``,n=!1;for(let r of e)r===`"`?(n=!n,t+=` `):t+=n?` `:r;return t}function $h(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(r===`"`)t=!t;else if(r===`:`&&!t)return n}return-1}function eg(e,t,n){let r=Qh(e.slice(t+1,n)),i=new Set;for(let e of r.split(`,`)){let t=/!?\s*([A-Za-z][\w-]*)/.exec(e);t&&i.add(t[1])}return i}function tg(e){return typeof e.apply==`string`?e.apply:e.label}function ng(e){let t=tg(e);return/\s/.test(t)?{...e,apply:(e,n,r,i)=>{let a=e.state.sliceDoc(Math.max(0,r-1),r)===`"`?t:`"${t}"`;e.dispatch({changes:{from:r,to:i,insert:a},selection:{anchor:r+a.length},userEvent:`input.complete`})}}:e}function rg(e,t){let n=new Set,r=[];e.forEach((e,t)=>{let i=tg(e).toLowerCase();!i||n.has(i)||(n.add(i),r.push(ng({...e,boost:Math.max(-99,Math.min(99,80-t))})))});for(let e of t){let t=tg(e).toLowerCase();!t||n.has(t)||(n.add(t),r.push(ng(e)))}return r}function ig(e,t){let n=t.toLowerCase();if(!n)return[...e];let r=[],i=[];for(let t of e){let e=t.label.toLowerCase();e.startsWith(n)?r.push(t):e.includes(n)&&i.push(t)}return[...r,...i]}function ag(e,t,n,r){let i=ig(n,r);return i.length?{from:t,options:i.map((e,t)=>e.boost===void 0?{...e,boost:Math.max(-99,50-t)}:e),filter:!1}:null}function og(e,t){return e.map(e=>({...e,apply:(n,r,i,a)=>{let o=typeof e.apply==`string`?e.apply:e.label,s=/\W$/.test(o),c=n.state.sliceDoc(a,a+t.length)===t,l=s||c?o:o+t;n.dispatch({changes:{from:i,to:a+(s&&c?t.length:0),insert:l},selection:{anchor:i+l.length},userEvent:`input.complete`}),$r(n)}}))}var sg=[...bm.map(e=>({label:e,detail:`function head`,type:`keyword`})),...hm.map(e=>({label:e,detail:`source head`,type:`keyword`})),...xm.map(e=>({label:e,detail:`chart head`,type:`class`})),...Sm.map(e=>({label:e,detail:`page dataset`,type:`class`}))];function cg(e,t){return e.label.startsWith(`@`)?{...e,apply:e.label}:{...e,apply:`${t?``:`:`}${e.label}{`}}var lg=im.map(e=>({label:e,type:`keyword`})),ug=[`title`,`date`,`createdAt`,`type`,`sourceId`,`notebookId`],dg=[`noteTitle`,`dataType`,`position`,`createdAt`,`noteId`,`sourceId`],fg=[`slug`,`label`,`registrySource`],pg=[`duration`,`startTime`,`origin`],mg=[`date`,`effort`,`discipline`,`note`,`grade`,`intensity`,...nm,...rm],hg=new Set([`distance`,`resistance`,`totalVolume`,`totalDistance`]),gg=[{label:`asc`,detail:`sort ascending`,type:`keyword`},{label:`desc`,detail:`sort descending`,type:`keyword`}],_g=Tm.map(e=>({label:e,detail:`display unit`,type:`constant`}));function vg(e,t){return{family:`aggregate`}}function yg(e){let t=e.toLowerCase();if(bm.includes(t))return{family:`aggregate`};if(xm.includes(t))return{family:`find`};let n=e=>_m.includes(e)||gm[e]||vm[e]?`note`:e;if(hm.includes(t))return{family:`find`,target:n(t)};let r=t?hm.filter(e=>e.startsWith(t)):[],i=[...new Set(r.map(n))];return i.length===1?{family:`find`,target:i[0]}:{family:`find`}}var bg=[...new Set(pm.flatMap(e=>[...Rm(e,`find`)]))];function xg(e){return e.family===`find`?e.target?Rm(e.target,`find`):bg:Rm(``,`aggregate`)}function Sg(e){switch(e){case`note`:return ug;case`block`:return dg;case`effort`:return fg;case`session`:return pg;default:return mg}}var Cg=new Set([`note`,`block`,`effort`,`session`]);function wg(e={}){let{effortNames:t,tagTypeValues:n,catalog:r,values:i}=e,a=async e=>r?(await r.listByPrefix(e,20)).map(e=>({label:e.path,detail:[e.kind,...e.units].filter(Boolean).join(` · `),type:`variable`,apply:e.path})):[],o=async(e,t)=>r?(await r.listValues(e,t,20)).map(e=>({label:e.value,type:`constant`})):[],s=()=>{let e=t?.()??[];return[...Xh(rm).map(e=>({...e,type:`constant`})),...Xh(nm).map(e=>({...e,type:`variable`})),...Xh(e.flatMap(e=>nm.map(t=>`${e}.${t}`))).map(e=>({...e,type:`variable`})),...Xh(um).map(e=>({...e,type:`namespace`})),gr("calc.${target}",{label:`calc.`,detail:`calculated target`,type:`namespace`})]},c=e=>{switch(e){case`effort`:return Xh(t?.()??[]);case`discipline`:return Xh(Jh);case`intensity`:return Xh(dm);case`grain`:return Xh(fm);case`metric`:return s();case`source`:return Xh(mm);case`domain`:case`format`:case`equipment`:case`quality`:case`intent`:return n?Promise.resolve(n(e)).then(e=>Xh(e)):null;default:return null}},l=(e,t,n,a)=>{let s=(i,s)=>{let c=rg(i,s??[]);return c.length?ag(t,n,c,a):r?o(e,a).then(e=>ag(t,n,e,a)):ag(t,n,[],a)},l=c(e);if(!i)return l instanceof Promise?l.then(e=>s([],e)):s([],l);let u=i(e);return l instanceof Promise?Promise.all([Promise.resolve(u),l]).then(([e,t])=>s(e,t)):Promise.resolve(u).then(e=>s(e,l))},u=(e,t,n)=>r?a(n).then(r=>ag(e,t,[...s(),...r],n)):ag(e,t,s(),n),d=(e,t,n,r,i,a)=>{if(/\bby\s*$/.test(Qh(t.slice(0,n.lastBrace)))){let o=zm(a.target??``,a.family),s=eg(t,n.lastBrace,n.fragStart),c=[...o].filter(e=>!s.has(e));return c.length?ag(e,r,og(c.map(e=>({label:e,type:`atom`,detail:`grouping dimension`})),`, `),i):ag(e,r,[],i)}let o=t.slice(n.fragStart,e.pos),s=$h(o);if(s>=0){let t=o.slice(0,s).replace(/^!/,``).trim();return l(t,e,r,i)}let c=e.matchBefore(/[\w-]*/),u=o.trimStart().startsWith(`!`),d=eg(t,n.lastBrace,n.fragStart),f=og(xg(a).filter(e=>!d.has(e)).map(e=>({label:e,type:`property`,...u?{detail:`exclude ${e} values`}:{}})),`:`);return ag(e,c.from,f,i)},f=(e,t,n,r,i,a,o)=>{let s=t.slice(o,e.pos);if(/\.rollup\([^)]*$/.test(s))return a.family===`aggregate`?ag(e,r,Xh(wm).map(e=>({...e,type:`constant`})),i):ag(e,r,[],i);if(/\bby\s*\{[^}]*$/.test(s))return d(e,t,n,r,i,a);if(/\s+last\s+$/i.test(s))return ag(e,e.pos,[{label:`4w`,detail:`relative window`,type:`constant`},{label:`8w`,detail:`relative window`,type:`constant`},{label:`7d`,detail:`relative window`,type:`constant`},{label:`30d`,detail:`relative window`,type:`constant`}],``);let c=/\s+last\s+(\d+)([dw]?)$/i.exec(s);if(c)return c[2]?null:ag(e,e.pos,[{label:`d`,detail:`days`,type:`constant`},{label:`w`,detail:`weeks`,type:`constant`}],``);if(/\s+from\s+$/i.test(s))return ag(e,e.pos,[{label:`2026-01-01`,apply:`2026-01-01 `,detail:`start date (YYYY-MM-DD)`,type:`constant`}],``);if(/\s+from\s+\d{4}-\d{2}-\d{2}\s+$/i.test(s))return ag(e,e.pos,[{label:`to`,apply:`to `,detail:`end date`,type:`keyword`}],``);if(/\s+to\s+$/i.test(s))return ag(e,e.pos,[{label:`2026-03-31`,detail:`end date (YYYY-MM-DD)`,type:`constant`}],``);let l=/\bby\s*\{[^{}]*\}/.test(s),u=/\.rollup\([^()]*\)/.test(s),f=/\s+last\s+\d+[dw]\b/i.test(s)||/\s+from\s+\d{4}-\d{2}-\d{2}(?:\s+to\s+\d{4}-\d{2}-\d{2})?\b/i.test(s),p=zm(a.target??``,a.family);return ag(e,r,og([...l?[]:[{label:`by {}`,apply:`by `,detail:p.length?`group by dimensions`:`advisory: no grouping dimensions for find:${a.target}`,type:`keyword`}],...a.family===`aggregate`&&!u?[{label:`.rollup()`,apply:`.rollup(`,detail:`bucket period`,type:`keyword`}]:[],...f?[]:[{label:`last`,apply:`last `,detail:`relative window: last <n>d|w`,type:`keyword`},{label:`from`,apply:`from `,detail:`date range: from YYYY-MM-DD [to YYYY-MM-DD]`,type:`keyword`}],...a.family===`find`?[{label:`|`,apply:`| `,detail:`presentation pipes: order by / select / limit`,type:`keyword`}]:[]],` `),i)},p=(e,t,n,r,i,a)=>{let o=t.slice(n.pipeFrom,e.pos),s=/^\s*order\b/i.exec(o);if(s){let t=o.slice(s[0].length),n=/^\s*by\b/i.exec(t);if(!n)return ag(e,r,[{label:`by`,apply:`by `,type:`keyword`}],i);let c=t.slice(n[0].length).split(`,`).pop()??``,l=c.trim().split(/\s+/).filter(Boolean),u=Sg(a.target).map(e=>({label:e,type:`property`}));return l.length?/\s$/.test(c)?ag(e,e.pos,gg,``):l.length>=2?/^(asc|desc)$/i.test(l[1])?null:ag(e,r,gg,i):ag(e,r,u,c.trim()):ag(e,r,u,``)}let c=/^\s*select\b/i.exec(o);if(c){let t=o.slice(c[0].length).split(`,`).pop()??``,n=t.trim().split(/\s+/).filter(Boolean);if(!n.length)return ag(e,r,Sg(a.target).map(e=>({label:e,type:`property`})),``);if(/\s$/.test(t))return hg.has(n[0].toLowerCase())?ag(e,e.pos,_g,``):ag(e,r,[],i);if(n.length>=2){let t=n[1].toLowerCase();return t===`in`?n[2]?ag(e,r,_g,n[2]):ag(e,e.pos,_g,``):`in`.startsWith(t)?ag(e,e.pos,_g,``):null}return ag(e,r,Sg(a.target).map(e=>({label:e,type:`property`})),n[0])}if(/^\s*(limit|offset)\b/i.test(o))return null;let l=gr("limit ${10}",{label:`limit`,detail:`cap result rows`,type:`keyword`});return ag(e,r,[...og([{label:`order by`,apply:`order by `,detail:a.target===`session`?`advisory: order ignored for sessions`:`sort rows`,type:`keyword`},{label:`select`,apply:`select `,detail:Cg.has(a.target??``)?`advisory: select ignored for find:${a.target}`:`choose columns`,type:`keyword`}],` `),l],i)};function m(e,t=!1){let n=e.state.doc.toString(),r=e.pos,i=e.matchBefore(/[\w.*-]*/)??{from:r,to:r,text:``},a=i.from===i.to&&r>0&&/[{,:|(!"@]/.test(n[r-1]);if(i.from===i.to&&!e.explicit&&!a)return null;let o=Zh(n,r);if(o.quoted&&o.depth===0)return null;let s=t?``:i.text,c=/^[ \t]*:[ \t]*([A-Za-z][\w-]*)/.exec(n),l=c??/^[ \t]*([A-Za-z]+)[ \t]*:[ \t]*([A-Za-z0-9_.-]*)/.exec(n),m=c?yg(c[1]):l?vg(l[1],l[2]):{family:`aggregate`};if(o.pipeFrom>=0&&o.depth===0)return p(e,n,o,i.from,s,m);if(o.depth>0)return d(e,n,o,i.from,s,m);let h=i.from>0&&n[i.from-1]===`@`,g=h?sg.filter(e=>e.label.startsWith(`@`)):sg,_=h?`@`+s:s,v=h?i.from-1:i.from;return l?c?r<=c[0].length?ag(e,v,g.map(e=>cg(e,!0)),_):f(e,n,o,i.from,s,m,c[0].length):r<=l[0].indexOf(`:`)?ag(e,i.from,og(lg,`:`),s):r<=l[0].length?u(e,i.from,s):f(e,n,o,i.from,s,m,l[0].length):ag(e,v,g.map(e=>cg(e,!1)),_)}function h(e){let t=e.state.selection.main;if(t.empty)return m(e);let n=m(new vi(e.state,t.to,!0),!0),r=e=>e&&{...e,from:t.from,to:t.to,filter:!1,validFor:void 0};return n instanceof Promise?n.then(r):r(n)}return h}var Tg=Dr.define([{tag:H.keyword,color:`hsl(var(--primary))`},{tag:H.variableName,color:`hsl(var(--accent-foreground))`,fontWeight:`600`},{tag:H.propertyName,color:`hsl(var(--secondary-foreground))`},{tag:H.string,color:`hsl(var(--success))`},{tag:H.attributeName,color:`hsl(var(--warning))`},{tag:H.number,color:`hsl(var(--primary))`},{tag:H.unit,color:`hsl(var(--muted-foreground))`},{tag:H.operator,color:`hsl(var(--destructive))`},{tag:[H.bracket,H.punctuation],color:`hsl(var(--muted-foreground))`}]);function Eg(e,t,n){if(t===void 0||n===void 0||t===n)return e;let r=$i(t);if(!r||r!==$i(n))return e;try{return na(e,t,n)}catch{return e}}function Dg(e){return e?$i(e):void 0}function Og(e,{directive:t,preferred:n}){let r=new Set;for(let t of e){let e=t.unit??t.metricUnit;e&&r.add(e)}let i;for(let e of r){let t=$i(e);if(!t)return{error:`Unknown unit "${e}"`,convert:!1};if(i&&t!==i)return{error:`Incompatible units in one calculation (${[...r].join(`, `)})`,convert:!1};i=t}if(t){let e=$i(t);return e?i&&e!==i?{error:`Output unit "${t}" is not compatible with this result's dimension`,convert:!1}:i?{unit:t,convert:!0}:{unit:t,convert:!1}:{error:`Unknown unit "${t}"`,convert:!1}}if(i){let e=ta(i);return{unit:e,convert:e!==void 0}}return{unit:void 0,convert:!1}}function kg(e=Date.now(),t=Ag()){return{instant:e,timeZone:t}}function Ag(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`}catch{return`UTC`}}var jg=/^(\d{4})-(\d{2})-(\d{2})$/;function Mg(e){let t=jg.exec(e);if(!t)throw Error(`Invalid civil date: ${e}`);return{y:Number(t[1]),m:Number(t[2]),d:Number(t[3])}}var Ng=new Map;function Pg(e,t){let n=`${e}|${JSON.stringify(t)}`,r=Ng.get(n);return r||(r=new Intl.DateTimeFormat(`en-CA`,{timeZone:e,...t}),Ng.set(n,r)),r}function Fg(e,t){let n=Pg(t,{year:`numeric`,month:`2-digit`,day:`2-digit`}).formatToParts(e),r=e=>n.find(t=>t.type===e)?.value??``;return`${r(`year`)}-${r(`month`)}-${r(`day`)}`}function Ig(e,t){let{y:n,m:r,d:i}=Mg(e),a=new Date(Date.UTC(n,r-1,i+t)),o=e=>String(e).padStart(2,`0`);return`${a.getUTCFullYear()}-${o(a.getUTCMonth()+1)}-${o(a.getUTCDate())}`}function Lg(e,t){let n=Mg(e),r=Mg(t);return Math.round((Date.UTC(r.y,r.m-1,r.d)-Date.UTC(n.y,n.m-1,n.d))/864e5)}function Rg(e){let{y:t,m:n,d:r}=Mg(e);return Ig(e,-((new Date(Date.UTC(t,n-1,r)).getUTCDay()+6)%7))}function zg(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hour12:!1,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}).formatToParts(e),r=e=>Number(n.find(t=>t.type===e)?.value??`0`);return Date.UTC(r(`year`),r(`month`)-1,r(`day`),r(`hour`)%24,r(`minute`),r(`second`))-e}function Bg(e,t){let{y:n,m:r,d:i}=Mg(e),a=Date.UTC(n,r-1,i);return a-zg(a-zg(a,t),t)}function Vg(e,t){return Bg(e,t)+432e5}function Hg(e,t){if(!e)return;if(e.kind===`relative`){let n=Fg(t.instant,t.timeZone);return{start:Bg(e.unit===`d`?Ig(n,-(e.size-1)):Ig(Rg(n),-7*(e.size-1)),t.timeZone),end:t.instant+1,endExclusive:!0}}let n=Bg(e.start,t.timeZone);return e.end===void 0?{start:n,end:2**53-1,endExclusive:!1}:{start:n,end:Bg(Ig(e.end,1),t.timeZone),endExclusive:!0}}function Ug(e,t){return t?e<t.start?!1:t.endExclusive?e<t.end:e<=t.end:!0}var Wg=/^[\w\s.+\-*/(),]+$/;function Gg(e,t){let n=[];for(let r of e.matchAll(/[A-Za-z_][\w-]*/g)){let e=r[0];t.has(e)&&!n.includes(e)&&n.push(e)}return n}function Kg(e){let t=[],n=e.split(`
20
20
  `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`//`)),r={},i=!1,a=[],o,s=!1,c=new Set;for(let e of n){if(e.startsWith(`defaults `)){i=!0;let t=e.slice(9).trim(),n=/by\s*\{([^}]*)\}/.exec(t);n&&(r.groupBy=n[1].split(`,`).map(e=>e.trim()).filter(Boolean));let a=/last\s+(\d+)\s*(d|w)/.exec(t);a&&(r.window={kind:`relative`,size:Number(a[1]),unit:a[2]});let o=/from\s+(\d{4}-\d{2}-\d{2})(?:\s+to\s+(\d{4}-\d{2}-\d{2}))?/.exec(t);o&&(r.window={kind:`range`,start:o[1],end:o[2]});continue}if(e.startsWith(`show `)){o=e.slice(5).split(`,`).map(e=>e.trim()).filter(Boolean);continue}let n=/^([A-Za-z_][\w-]*)\s*=\s*(.+)$/.exec(e);if(n){let r=n[1],i=n[2].trim();c.add(r);let o=/->\s*([\w/%.]+)\s*$/.exec(i),s=/\(normalize\s+([^)]+)\)/.exec(i),l=i.replace(/->\s*[\w/%.]+\s*$/,``).replace(/\(normalize\s+[^)]+\)/,``).trim();if(/^(sum|avg|min|max|count|last|delta|find|rows)\b|^[:@|]/.test(l)){let n=X(l);n.error?t.push(`Assignment "${r}" is not a valid query`):a.push({name:r,kind:`query`,queryText:l,parsed:n,raw:e});continue}if(!Wg.test(l)){t.push(`Assignment "${r}" has characters a formula cannot parse`);continue}let u={expression:l,references:[],...s?{normalize:s[1].trim()}:{},...o?{unit:o[1]}:{}};a.push({name:r,kind:`formula`,formula:u,raw:e});continue}s=!0}if(!i&&o===void 0&&!s&&a.length===1&&a[0].kind,!i&&o===void 0&&a.length===0){let e=X(n.join(` `));e.error?t.push(`Body is neither a valid query nor a valid document`):(c.add(`query`),a.push({name:`query`,kind:`query`,queryText:n.join(` `),parsed:e,raw:n.join(` `)}),o=[`query`],s=!0)}for(let e of a)if(!(e.kind!==`formula`||!e.formula)){e.formula.references=Gg(e.formula.expression,c);for(let n of e.formula.expression.matchAll(/[A-Za-z_][\w-]*/g)){let r=n[0];c.has(r)||t.push(`Formula "${e.name}" references unknown name "${r}"`)}e.formula.references.length===0&&t.push(`Formula "${e.name}" references no named query or formula`)}let l=qg(a);if(l&&t.push(`Reference cycle detected: ${l.join(` -> `)}`),o===void 0)o=a.filter(e=>e.kind===`query`).map(e=>e.name),a.length>0&&o.length===0&&(o=[a[0].name]);else for(let e of o)c.has(e)||t.push(`show references unknown name "${e}"`);return{doc:{...Object.keys(r).length>0?{defaults:r}:{},assignments:a,show:o,degenerate:s},diagnostics:t}}function qg(e){let t=new Map(e.filter(e=>e.kind===`formula`).map(e=>[e.name,e.formula.references])),n=new Map,r=[],i=e=>{let a=n.get(e);if(a!==2){if(a===1){let t=r.indexOf(e);return[...r.slice(t===-1?0:t),e]}n.set(e,1),r.push(e);for(let n of t.get(e)??[]){let e=i(n);if(e)return e}r.pop(),n.set(e,2)}};for(let e of t.keys()){let t=i(e);if(t)return t}}function Jg(){let e=(t,n,r)=>{let i=t.trim();if(i.startsWith(`(`)&&i.endsWith(`)`))return e(i.slice(1,-1),n,r);let a=e=>{let t=0;for(let n=i.length-1;n>=0;n--){let r=i[n];if(r===`)`)t++;else if(r===`(`)t--;else if(t===0&&e.includes(r)&&n>0){let e=r,t=i.slice(0,n),a=i.slice(n+1);if(t.trim()&&a.trim())return{op:e,left:t,right:a}}}},o=a([`+`]);if(o&&o.op===`+`){let t=e(o.left,n,r),i=e(o.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:{value:t.value+i.value,missingDerived:t.missingDerived||i.missingDerived}}let s=a([`-`]);if(s&&s.op===`-`){let t=e(s.left,n,r),i=e(s.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:{value:t.value-i.value,missingDerived:t.missingDerived||i.missingDerived}}let c=a([`*`]);if(c&&c.op===`*`){let t=e(c.left,n,r),i=e(c.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:{value:t.value*i.value,missingDerived:t.missingDerived||i.missingDerived}}let l=a([`/`]);if(l&&l.op===`/`){let t=e(l.left,n,r),i=e(l.right,n,r);return t.error||i.error?{value:0,missingDerived:!0,error:t.error??i.error}:i.value===0?{value:0,missingDerived:!1,error:`Division by zero`}:{value:t.value/i.value,missingDerived:t.missingDerived||i.missingDerived}}if(/^-?\d+(\.\d+)?$/.test(i))return{value:Number(i),missingDerived:!1};let u=n[i];if(u){let e=u(r);return e===void 0?{value:0,missingDerived:!0}:e}return{value:0,missingDerived:!0,error:`Unknown reference "${i}"`}};return{evaluate(t,n,r){try{return e(t,n,r)}catch(e){return{value:0,missingDerived:!0,error:e instanceof Error?e.message:String(e)}}}}}function Yg(e,t,n){let r=e;return n&&n.length>0&&!/by\s*\{/.test(r)&&(r+=` by {${n.join(`, `)}}`),t.kind===`relative`&&!/\blast\b/.test(r)?r+=` last ${t.size}${t.unit}`:t.kind===`range`&&!/\bfrom\b/.test(r)&&(r+=` from ${t.start}${t.end?` to ${t.end}`:``}`),r}var Xg=class{runAggregate;evaluator;constructor(e,t={}){this.runAggregate=e,this.options=t,this.evaluator=t.formulaEvaluator??Jg()}options;async run(e){let t=Kg(e),n=[...t.diagnostics],r=t.doc,i=[],a=new Map,o=async e=>{if(e.kind===`query`){let t=this.mergeDefaults(e,r),n=e.parsed?.family;if(n===`find`){let n=t.window?Yg(t.queryText,t.window,t.groupBy):t.queryText,r=await this.options?.runFind?.(n)??{error:`find queries are not supported by this host`};i.push({name:e.name,kind:`find`,...r.notes?{notes:r.notes}:{},...r.blocks?{blocks:r.blocks}:{},...r.efforts?{efforts:r.efforts}:{},...r.containers?{containers:r.containers}:{},...r.placements?{placements:r.placements}:{},...r.runs?{runs:r.runs}:{},...r.table?{table:r.table}:{},...r.unit?{unit:r.unit}:{},...r.error?{error:r.error}:{}});return}if(n===`pipeline`){let n=t.window?Yg(t.queryText,t.window,t.groupBy):t.queryText,r=await this.options?.runPipeline?.(n)??{error:`pipeline queries are not supported by this host`},o=new Map;for(let e of r.series??[])for(let t of e.points)t.missing||o.set(t.ts,{value:t.value,missingDerived:!1});o.size>0&&a.set(e.name,{byPosition:o,unit:r.unit,groupKeys:(r.series??[]).map(e=>e.key)}),i.push({name:e.name,kind:`pipeline`,...r.series?{series:r.series}:{},...r.table?{table:r.table}:{},...r.notes?{notes:r.notes}:{},...r.blocks?{blocks:r.blocks}:{},...r.efforts?{efforts:r.efforts}:{},...r.containers?{containers:r.containers}:{},...r.placements?{placements:r.placements}:{},...r.runs?{runs:r.runs}:{},...r.unit?{unit:r.unit}:{},...r.chart?{chart:r.chart}:{},...r.error?{error:r.error}:{}});return}let o=await this.runAggregate(t.queryText,{groupBy:t.groupBy,window:t.window}),s=o.series??[],c=new Map;for(let e of s)for(let t of e.points)t.missing||c.set(t.ts,{value:t.value,missingDerived:!1});a.set(e.name,{byPosition:c,unit:o.unit,groupKeys:s.map(e=>e.key)}),i.push({name:e.name,kind:`aggregate`,unit:o.unit,...r.defaults?.groupBy?{groupBy:r.defaults.groupBy}:{},...t.window?{window:t.window}:{},series:s,...o.error?{error:o.error}:{}});return}let t=e.formula,o={},s=new Set;for(let r of t.references){let t=a.get(r);if(!t){n.push(`Formula "${e.name}" references unavailable input "${r}"`);return}for(let e of t.byPosition.keys())s.add(e);o[r]=e=>t.byPosition.get(e)}let c=new Map,l,u;if(t.expression.startsWith(`corr(`)&&t.expression.endsWith(`)`)){let[r,o]=t.expression.slice(5,-1).split(`,`).map(e=>e.trim()),s=a.get(r)?.byPosition,l=a.get(o)?.byPosition;if(!s||!l){n.push(`corr("${r}", "${o}") references unavailable inputs`);return}let d=[];for(let[e,t]of s){let n=l.get(e);n&&!t.missingDerived&&!n.missingDerived&&d.push([t.value,n.value])}if(u=d.length,d.length<2){i.push({name:e.name,kind:`formula`,pairs:u,error:`corr needs at least two paired positions`}),a.set(e.name,{byPosition:new Map,groupKeys:[]});return}let f=e=>e.reduce((e,t)=>e+t,0)/e.length,p=f(d.map(([e])=>e)),m=f(d.map(([,e])=>e)),h=0,g=0,_=0;for(let[e,t]of d)h+=(e-p)*(t-m),g+=(e-p)**2,_+=(t-m)**2;if(g===0||_===0){i.push({name:e.name,kind:`formula`,pairs:u,error:`corr is undefined for zero-variance inputs`}),a.set(e.name,{byPosition:new Map,groupKeys:[]});return}let v=h/Math.sqrt(g*_);c.set(0,{value:v,missingDerived:!1}),i.push({name:e.name,kind:`formula`,pairs:u,series:[{key:`corr`,label:`corr`,points:[{ts:0,value:v}]}]}),a.set(e.name,{byPosition:c,groupKeys:[`corr`]});return}for(let e of[...s].sort((e,t)=>e-t)){let n=this.evaluator.evaluate(t.expression,o,e);if(n.error){l=n.error;continue}c.set(e,{value:n.value,missingDerived:n.missingDerived})}let d=[{key:e.name,label:e.name,points:[...c.entries()].map(([e,t])=>({ts:e,value:t.value,...t.missingDerived?{missingDerived:!0}:{}}))}];a.set(e.name,{byPosition:c,unit:t.unit,groupKeys:[e.name]}),i.push({name:e.name,kind:`formula`,...t.unit?{unit:t.unit}:{},series:d,...l?{error:l}:{}})},s=[...r.assignments],c=!0,l=new Set;for(;s.length>0&&c;){c=!1;for(let e=s.length-1;e>=0;e--){let t=s[e];(t.formula?.references??[]).every(e=>l.has(e))&&(await o(t),l.add(t.name),s.splice(e,1),c=!0)}}let u=new Set(r.show);return{outputs:i.filter(e=>u.has(e.name)),diagnostics:n}}mergeDefaults(e,t){let n=e.parsed,r=n?.family===`aggregate`?n.groupBy:void 0,i=r?.length?r:t.defaults?.groupBy,a=(n&&n.family!==`pipeline`?n.window:void 0)??t.defaults?.window;return{queryText:e.queryText??``,...i?{groupBy:i}:{},...a?{window:a}:{}}}},Zg=class extends Map{getDataset(e){return this.get(e)}},Qg=[`calc.acwr`,`calc.monotony`,`calc.strain`],$g=class{host;initialOptions;constructor(e,t={}){this.host=e,this.initialOptions=t}async run(e,t={}){let n={...this.initialOptions,...t,tokens:{...this.initialOptions.tokens,...t.tokens},context:t.context??this.initialOptions.context??kg()},r=e_(e,n.tokens??{});return Kg(r).doc.assignments.some(e=>t_(e.parsed))&&await this.host.rollupEnsure?.(),new Xg(async(e,t)=>(t.window&&(e=Yg(e,t.window,t.groupBy)),this.host.runAggregate(e,{context:n.context,window:t.window})),{formulaEvaluator:n.formulaEvaluator??this.host.formulaEvaluator,runFind:async e=>await this.host.runFind?.(e,n.context)??{error:`find queries are not supported by this host`},runPipeline:async e=>await this.host.runPipeline?.(e,n.context)??{error:`pipeline queries are not supported by this host`}}).run(r)}};function e_(e,t){return e.replace(/\$([A-Za-z_][\w-]*)/g,(e,n)=>{let r=t[n];return r===void 0?e:r})}function t_(e){return e?e.family===`aggregate`?Qg.includes(e.metric):e.family===`pipeline`?e.source.kind===`query`&&e.source.query.family===`aggregate`&&Qg.includes(e.source.query.metric)?!0:e.transforms.some(e=>Qg.includes(e.metric)):!1:!1}function n_(e){return e.trim().split(/[^a-zA-Z0-9]+/).filter(Boolean).map((e,t)=>t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function r_(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}function i_(e){let t=e?.fieldRef;if(!t||typeof t!=`object`)return;let{path:n,kind:r,dimension:i}=t;if(typeof n==`string`&&n.length!==0&&typeof r==`string`)return{path:n,kind:r,...typeof i==`string`?{dimension:i}:{}}}function a_(e){let t=e?.groupTags;if(!t||typeof t!=`object`)return;let n=Object.entries(t).filter(e=>typeof e[1]==`string`&&e[1].length>0).sort(([e],[t])=>e<t?-1:1);return n.length>0?Object.fromEntries(n):void 0}function o_(e){let t=new Map;for(let n of e){if(n.outputType!==`analytics`)continue;let e=n.metrics.find(e=>e.type===q.Label),r=n.metrics.find(e=>e.type!==q.Label&&typeof e.value==`number`);if(!e||!r)continue;let i=String(e.value??e.image??``);if(!i)continue;let a=i_(r.metadata),o=r_(r.metadata,`canonicalKey`)??a?.path??n_(i),s=r_(r.metadata,`effortSlug`),c=r_(r.metadata,`effortDiscipline`),l=r_(r.metadata,`effortIntensityTier`),u=r_(r.metadata,`grade`),d=a_(r.metadata)??(s?{effort:s}:void 0),f=a?`${Ji(a)}${d?`:`+Object.entries(d).map(([e,t])=>`${e}=${t}`).join(`:`):``}`:d?`${o}:${Object.entries(d).map(([e,t])=>`${e}=${t}`).join(`:`)}`:o;t.set(f,{projectionName:i,metricKey:o,value:r.value,unit:r.unit,effortSlug:s,discipline:c,intensityTier:l,grade:u,groupTags:d,rowKey:f,...a?{fieldRef:a}:{},started:n.timeSpan?.started})}return t}function s_(e){let t=e;for(let e of t){let t=r_(e.metadata,`effortSlug`);if(t)return t;if((e.type===`effort`||e.type===q.Effort)&&typeof e.value==`string`&&e.value)return e.value}}function c_(e,t){return e.map((e,n)=>({id:`${t.resultId}:${n}`,resultId:t.resultId,noteId:t.noteId,blockContentId:t.blockContentId,pageId:t.pageId,origin:t.origin,timestamp:e.timeSpan?.started??t.workoutTimestamp??Date.now(),grain:`event`,outputType:e.outputType??`segment`,effortSlug:s_(e.metrics),metrics:e.metrics,timeSpan:e.timeSpan?.started===void 0?void 0:{started:e.timeSpan.started,ended:e.timeSpan.ended},metricTemporal:e.timeSpan?.started===void 0?void 0:e.metrics.map(()=>({temporalKind:`instant`,instant:e.timeSpan.started})),sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,line:e.line,sourceStatementId:e.sourceStatementId,text:e.text,dialect:e.dialect,completionReason:e.completionReason,blockId:t.blockId,blockVersion:t.blockVersion}))}function l_(e,t){let n=Date.now();return Array.from(o_(e).values(),e=>({id:`${t.resultId}:summary:${e.rowKey}`,resultId:t.resultId,noteId:t.noteId,blockContentId:t.blockContentId,pageId:t.pageId,origin:t.origin,timestamp:t.workoutTimestamp??e.started??n,grain:`summary`,outputType:`analytics`,representationKind:`calculated`,summaryCoverage:{scope:e.effortSlug?`effort`:e.groupTags?`partition`:`workout`,...e.effortSlug?{effortSlug:e.effortSlug}:{},...e.groupTags?{groupTags:e.groupTags}:{}},effortSlug:e.effortSlug,metrics:[{type:e.metricKey,value:e.value,...e.unit?{unit:e.unit}:{},metadata:{canonicalKey:e.metricKey,...e.fieldRef?{fieldRef:e.fieldRef,originalKey:e.projectionName}:{},...e.effortSlug?{effortSlug:e.effortSlug}:{},...e.discipline?{effortDiscipline:e.discipline}:{},...e.intensityTier?{effortIntensityTier:e.intensityTier}:{},...e.groupTags?{groupTags:e.groupTags}:{},...e.grade?{grade:e.grade}:{}}}],blockId:t.blockId,blockVersion:t.blockVersion}))}function u_(e){let t=Vi(e.metrics).visible();if(e.grain===`summary`){let n=t[0];if(!n||typeof n.value!=`number`)return[];let r=i_(n.metadata),i=r_(n.metadata,`canonicalKey`)??r?.path??n.type??``,a=e.metricTemporal?.[0],o=a_(n.metadata);return[{id:`${e.id}:0`,noteId:e.noteId,blockContentId:e.blockContentId,origin:e.origin,pageId:e.pageId,grain:`summary`,blockId:e.blockId??``,blockVersion:e.blockVersion??0,resultId:e.resultId,type:i,value:n.value,unit:n.unit,label:i,metricKey:i,metricLabel:i,metricUnit:n.unit,...r?{fieldRef:r}:{},...a?.temporalKind===`civil-date`&&a.civilDate?{metricDate:a.civilDate,temporalKind:`civil-date`}:{},representationKind:e.representationKind??(e.outputType===`wellness`?`direct`:void 0),...e.summaryCoverage?{summaryCoverage:e.summaryCoverage}:{},...e.reducerStats?{reducerStats:e.reducerStats}:{},effortSlug:r_(n.metadata,`effortSlug`)??e.effortSlug,discipline:r_(n.metadata,`effortDiscipline`),intensityTier:r_(n.metadata,`effortIntensityTier`),grade:r_(n.metadata,`grade`),...o?{dimensions:o}:{},timestamp:e.timestamp,createdAt:e.timestamp}]}let n=t.find(e=>e.type===q.Label),r=n?String(n.value??n.image??``):``,i=t.find(e=>e.type===q.Effort||e.type===`effort`),a=r_(t[0]?.metadata,`effortSlug`)??e.effortSlug??(i&&typeof i.value==`string`?i.value:void 0),o=t.find(e=>e.type===q.Grade||e.type===`grade`),s=r_(t[0]?.metadata,`grade`)??(o&&typeof o.value==`string`?o.value:void 0),c=[],l={};for(let e of t){if(e.type===q.Label||e.type===`label`||e.type===q.Hint||e.type===`hint`)continue;let t=qi(e.value);if(t!==`string`&&t!==`boolean`)continue;let n=i_(e.metadata)?.path??Ki(e.type??``);n&&(l[n]=String(e.value))}let u=Object.keys(l).length>0?l:void 0;return t.forEach(t=>{if(t.type===q.Label||t.type===`label`||typeof t.value!=`number`)return;let n=i_(t.metadata),i=t.type===q.Rep||t.type===`rep`?`reps`:t.type??`metric`;if(!n&&i===`custom`)return;let o=r_(t.metadata,`canonicalKey`)??n?.path??(r?n_(r):i),l=c.length,d=e.metricTemporal?.[l],f=d?.temporalKind===`instant`&&d.instant!==void 0?d.instant:e.timestamp;c.push({id:`${e.id}:${l}`,noteId:e.noteId,blockContentId:e.blockContentId,origin:e.origin,pageId:e.pageId,grain:`event`,blockId:e.blockId??``,blockVersion:e.blockVersion??0,resultId:e.resultId,type:o,value:t.value,unit:t.unit,label:r||o,metricKey:o,metricLabel:r||o,metricUnit:t.unit,...n?{fieldRef:n}:{},...d?.temporalKind===`civil-date`&&d.civilDate?{metricDate:d.civilDate,temporalKind:`civil-date`}:{},effortSlug:r_(t.metadata,`effortSlug`)??a,discipline:r_(t.metadata,`effortDiscipline`),intensityTier:r_(t.metadata,`effortIntensityTier`),grade:r_(t.metadata,`grade`)??s,...u?{dimensions:u}:{},timestamp:f,createdAt:e.timestamp})}),c}function d_(e){return[...e].sort((e,t)=>e.timestamp===t.timestamp?e.id.localeCompare(t.id):e.timestamp-t.timestamp).map((e,t)=>({id:t,outputType:e.outputType,timeSpan:e.timeSpan??{started:e.timestamp},metrics:e.metrics,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,line:e.line,sourceStatementId:e.sourceStatementId,text:e.text,dialect:e.dialect,completionReason:e.completionReason}))}function f_(e,t){let n=e?.groupTags?Object.entries(e.groupTags).sort(([e],[t])=>e<t?-1:1).map(([e,t])=>`${e}=${t}`).join(`,`):``;return`${e?.effortSlug??t??``}|${n}`}function p_(e,t){if(!e)return t===`sum`||t===`min`||t===`max`||t===`last`||t===`delta`;switch(t){case`sum`:case`min`:case`max`:case`last`:return!0;case`avg`:case`count`:return typeof e.observedCount==`number`;case`delta`:return!0}}function m_(e,t){let n={detailPopulations:0,selectedSummaries:[],ignoredDuplicates:[],insufficientScopes:[]},r=[],i=new Map;for(let t of e){let e=`${t.resultId}\u0000${t.metricKey??t.type}`,n=i.get(e);n?n.push(t):i.set(e,[t])}for(let[e,a]of i){let[i,o]=e.split(`\0`),s=a.filter(e=>e.grain!==`summary`||e.representationKind===`direct`),c=a.filter(e=>e.grain===`summary`);if(s.length>0){n.detailPopulations+=1,r.push(...s);let e=new Set(s.map(e=>f_(void 0,e.effortSlug)));for(let a of c){let s=f_(a.summaryCoverage,a.effortSlug);s!==`|`&&a.summaryCoverage!==void 0&&!e.has(s)&&p_(a.reducerStats,t)?(n.selectedSummaries.push({resultId:i,metricKey:o,coverage:a.summaryCoverage}),r.push(a)):n.ignoredDuplicates.push({resultId:i,metricKey:o,id:a.id})}continue}let l=!1;for(let e of c)p_(e.reducerStats,t)&&(n.selectedSummaries.push({resultId:i,metricKey:o,coverage:e.summaryCoverage}),r.push(e),l=!0);l||n.insufficientScopes.push({resultId:i,metricKey:o,reason:t===`avg`||t===`count`||t===`delta`?`summary lacks the retained observation count this operation requires`:`no detail rows and no sufficient summary for this population`})}return{selected:r,report:n}}function h_(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}var g_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function __(e){if(!e?.startsWith(`notebook:`))return;let t=e.slice(9);if(!(!t||t===`_root`))return t.split(`/`)[0]}function v_(e){if(e.notebookId&&e.notebookId.trim())return Ta(e.notebookId);if(e.tags){for(let t of e.tags)if(t.startsWith(`notebook:`)||t.startsWith(`notebook/`)){let e=wa(t);if(e)return Ta(e)}}let t=/^markdown\/(notebooks|canvas|efforts|dashboards|equipment)\/(.+)$/.exec(e.sourcePath??``);if(t){let[,e,n]=t;if(e===`canvas`)return`notebook/guides`;if(e!==`notebooks`)return Ta(e);let r=n.split(`/`);if(r.length>1)return Ta(r[0])}if(D_(e,`playground`))return`notebook/playground`;if(D_(e,`guides`))return`notebook/guides`;if(e.sourceId===`efforts`)return`notebook/efforts`;if(e.sourceId===`equipment`)return`notebook/equipment`;if(e.sourceId===`dashboards`||e.type===`dashboard`)return`notebook/dashboards`;let n=__(e.sourceId);if(n)return Ta(n);if(C_(e))return`notebook/journal`}function y_(e){let t=v_(e);if(t)return e.notebookId?.trim()||e.tags?.some(e=>e.startsWith(`notebook:`)||e.startsWith(`notebook/`))?`user`:t===`notebook/journal`||t===`notebook/playground`?`default`:`feed`}function b_(e){let t=y_(e);return t===`user`?`local`:e.feedSourceId?e.feedSourceId:t==="default"?`local`:`core`}function x_(e){if(e.seedChunkId)return e.seedChunkId;let t=v_(e);if(t)return`notebook.${t.replace(/^notebook\//,``)}`}function S_(e,t){let n=e.origin??y_(e);if(n===`user`||n==="default"||!t)return!0;let r=b_(e),i=x_(e);return!i||t(r,i)}function C_(e){let t=e.sourceId;return e.type===`playground`||e.id?.startsWith(`playground/`)||e.noteId?.startsWith(`playground/`)||t&&t!==`journal`&&!g_.test(t)&&!/^journal\/\d{4}-\d{2}-\d{2}$/.test(t)?!1:e.type!==`dashboard`&&e.type!==`effort`&&e.type!==`equipment`&&e.seedOrigin!==`seed`&&e.feedOrigin!==`feed`&&e.seedChunkId===void 0&&!(e.sourcePath&&e.sourcePath.startsWith(`markdown/`))}var w_={notebooks:{prefixes:[`notebook:`]},pages:{exact:[`page`],prefixes:[`page:`,`guides:`]},guides:{prefixes:[`guides:`]},playground:{exact:[`playground`],legacyType:`playground`},efforts:{exact:[`efforts`]},equipment:{exact:[`equipment`]},dashboards:{exact:[`dashboards`]}},T_={page:`pages`,guide:`guides`};function E_(e){return w_[T_[e]??e]}function D_(e,t){let n=e.sourceId;if(t===`all`)return!n||mm.some(t=>D_(e,t));if(t===`journal`)return v_(e)===`notebook/journal`;let r=E_(t);if(r)return!!n&&(r.exact?.includes(n)||r.prefixes?.some(e=>n.startsWith(e))===!0)||!!r.legacyType&&e.type===r.legacyType;if(t.startsWith(`notebook:`)||t.startsWith(`notebook/`)){let r=wa(t),i=n?.startsWith(`notebook:`)?n.slice(9):void 0;return i?i===r||i.startsWith(`${r}/`):v_(e)===Ta(t)}return n===t}function O_(e,t){for(let n of t){if(n.key!==`source`)continue;let t=n.values.map(e=>e.value);e=e.filter(e=>{let r=t.some(t=>D_(e,t));return n.negate?!r:r})}return e}function k_(e,t){for(let n of t){if(n.key!==`notebook`)continue;let t=new Set(n.values.map(e=>Ta(e.value)));e=e.filter(e=>{let r=v_(e);if(!r)return n.negate;let i=t.has(r);return n.negate?!i:i})}return e}var A_={notebooks:!0,page:!0,pages:!0,guide:!0,guides:!0,playground:!0};function j_(e,t,n){let r=[],i=[],a=!1;for(let n of e){let e=!n.negate&&n.values.every(e=>!e.wildcard),o=e?n.values.map(e=>e.value):[];if(n.key===`source`&&e&&n.values.every(e=>A_[e.value]===!0)){r.push({field:`source`,values:o});continue}if(n.key===`type`&&e){i.push({field:`type`,values:o});continue}if(n.key===`page`){a=!0;continue}if(t===`note`&&am.includes(n.key)&&e){i.push({field:`typedTag`,tagType:n.key,values:o});continue}if(n.key===`text`&&e){i.push({field:`text`,value:o.join(` `)});continue}if(n.key===`note`&&e){i.push({field:t===`block`?`noteId`:`id`,values:o});continue}a=!0}return t===`note`&&n?.length&&r.push({field:`source`,values:n}),t===`block`&&r.push({field:`sourceFence`}),{selection:r,filters:i,residual:a}}function M_(e,t){let n=O_(e,t.filters);if(t.sourceScope?.length){let e=t.sourceScope;n=n.filter(t=>e.some(e=>D_(t,e)))}return n}function N_(e,t,n){let r=e.pipes,i=r?.limit!==void 0||(r?.offset??0)>0;return n||e.join||e.window||t.range||r?.order||!i?{order:[{field:`id`,direction:`asc`}],paged:!1}:{order:[{field:`id`,direction:`asc`}],...r?.offset?{offset:r.offset}:{},...r?.limit===void 0?{}:{limit:r.limit},paged:!0}}function P_(e){return e.context?e.context:kg(e.anchorNow)}function F_(e,t,n,r){return Ug(e,t?Hg(t,r):n)}function I_(e){let t=e.find(e=>e.outputType===`completion`);return t?.timestamp?t.timestamp:e[0]?.timestamp??0}function L_(e,t,n){if(e.window)return Hg(e.window,n);if(t.rangeStart!==void 0||t.rangeEnd!==void 0)return{start:t.rangeStart??0,end:t.rangeEnd??2**53-1,endExclusive:!1}}var R_={getEventsByTimeRange:async()=>[],getEventsByResult:async()=>[],getEventsForNote:async()=>[],getEventsByContent:async()=>[],scanAll:async()=>[],appendEvents:async()=>{},finalizeSummaries:async()=>{},deleteEvents:async()=>{}},z_={getAllNotes:async()=>[],getNoteIdsForTag:async()=>new Set,getNoteTagLabels:async()=>[]},B_={getAllBlocks:async()=>[]},V_={getAllEfforts:async()=>[]};function H_(e,t,n){let r=[],i=e;for(;i<t;){let e=Fg(i,n);r[r.length-1]!==e&&r.push(e);let t=Bg(Ig(e,1),n);if(t<=i)break;i=t}return r}function U_(e,t,n){switch(t){case`effort`:return e.effortSlug;case`discipline`:return e.discipline;case`intensity`:return e.intensityTier;case`grade`:return e.grade;case`note`:return e.noteId;case`page`:return e.pageId;case`origin`:return e.origin;case`grain`:return e.grain;case`metric`:return e.metricKey;case`block`:return e.blockContentId;case`result`:return e.resultId;case`tags`:return n.get(e.noteId)??[];default:{let n=e.dimensions;return n?n[t]??n[Gi(t)]:void 0}}}function W_(e,t,n){let r=new Map;for(let e of t){let t=`${e.negate?`!`:``}${e.key}`,n=r.get(t);n?n.push(e):r.set(t,[e])}return[...r.values()].every(t=>{let r=t[0].key,i=t[0].negate,a=U_(e,r,n),o=(Array.isArray(a)?a:a===void 0?[]:[a]).some(e=>t.some(t=>t.values.some(t=>t.wildcard?e.startsWith(t.value):e===t.value)));return i?!o:o})}function Cee(e,t,n,r){if(t===`day`)return e.metricDate??Fg(e.timestamp,r.timeZone);if(t===`week`)return Rg(e.metricDate??Fg(e.timestamp,r.timeZone));if(t===`session`)return e.resultId;let i=U_(e,t,n);return i===void 0?G_:typeof i==`string`?i:i.length?i.join(`,`):G_}var G_=`\0unassigned`;function K_(e,t,n){if(t===`count`)return{state:`observed`,value:n.length};if(e.length===0)return{state:`absent`,value:0};switch(t){case`sum`:return{state:`observed`,value:e.reduce((e,t)=>e+t,0)};case`avg`:return{state:`observed`,value:e.reduce((e,t)=>e+t,0)/e.length};case`min`:return{state:`observed`,value:Math.min(...e)};case`max`:return{state:`observed`,value:Math.max(...e)};case`last`:{let t=0;for(let e=0;e<n.length;e++)n[e].timestamp>n[t].timestamp&&(t=e);return{state:`observed`,value:e[t]}}case`delta`:{if(n.length<2)return{state:`absent`,value:0};let t=n.map((t,n)=>({point:t,value:e[n]})).sort((e,t)=>e.point.timestamp-t.point.timestamp),r=t[0],i=t[t.length-1],a=t.filter(e=>e.point.timestamp===r.point.timestamp),o=t.filter(e=>e.point.timestamp===i.point.timestamp),s=new Set(a.map(e=>e.point.value)),c=new Set(o.map(e=>e.point.value));return s.size>1||c.size>1?{state:`error`,message:`Ambiguous delta order: tied endpoint observations differ in value without recorded order`}:{state:`observed`,value:i.value-r.value}}}}function wee(e,t,n){switch(t){case`>`:return e>n;case`>=`:return e>=n;case`<`:return e<n;case`<=`:return e<=n;case`==`:return e===n;case`!=`:return e!==n}}function q_(e,t,n,r){let i={selected:0,buckets:0,aggregated:0,groups:0},a=[t.join&&`where <content> join`,t.filters.length>0&&`tag filters`,t.groupBy.length>0&&`by {…} grouping`,t.rollup&&`.rollup(…)`].filter(Boolean);if(a.length>0)return{parsed:t,series:[],stages:{...i},matched:[],error:`:${t.agg}{…} on a carried stage cannot apply ${a.join(`, `)} — carried values carry no fact dimensions; author them in the source stage.`};if(e.error)return e;let o=L_(t,n,r),s=[],c=[],l=0;for(let t of e.series)for(let e of t.points)e.missing||o&&!Ug(e.ts,o)||(s.push(e.value),c.push({timestamp:e.ts,value:e.value,noteId:``,resultId:``}),e.ts>l&&(l=e.ts));if(t.metric&&!(e.parsed.metric&&((e,t)=>e===t||e===`rep`&&t===`reps`||e===`reps`&&t===`rep`)(t.metric,e.parsed.metric)))return{parsed:t,series:[],stages:{...i},matched:[],error:`:${t.agg}{metric:${t.metric}} on a carried stage reduces the preceding "${e.parsed.metric||`metricless`}" values — metric:${t.metric} does not exist on them.`};let u=t.agg===`count`?`count`:e.unit;if(t.displayUnit){if(!u||u===`count`)return{parsed:t,series:[],stages:{...i},matched:[],error:`Cannot apply in ${t.displayUnit} — the preceding stage carries no convertible unit.`};try{for(let e=0;e<s.length;e++){let n=na(s[e],u,t.displayUnit);s[e]=n,c[e]={...c[e],value:n}}u=t.displayUnit}catch(e){return{parsed:t,series:[],stages:{...i},matched:[],error:e instanceof Error?e.message:String(e)}}}let d=K_(s,t.agg,c);return d.state===`error`?{parsed:t,series:[],stages:{...i},matched:[],error:d.message}:{parsed:t,series:[{key:t.agg,label:t.agg,points:[{ts:l||r.instant,value:d.value,...d.state===`absent`?{missing:!0}:{}}],unit:u}],stages:{selected:s.length,buckets:1,aggregated:1,groups:1},matched:[],...u?{unit:u}:{}}}var J_=class{store;noteStore;blockStore;effortStore;pageStore;relationStore;datasetStore;isNotebookSubscribed;blockEffortsStore={getAllFromIndex:async()=>[]};tagsStore={getAllFromIndex:async()=>[]};noteTagsStore={getAllFromIndex:async()=>[]};constructor(e,t,n,r){if(e&&typeof e==`object`&&(`eventStore`in e||`noteStore`in e||`blockStore`in e||`effortStore`in e||`pageStore`in e||`relationStore`in e||`datasetStore`in e)){let t=e;this.store=t.eventStore??R_,this.noteStore=t.noteStore??z_,this.blockStore=t.blockStore??B_,this.effortStore=t.effortStore??V_,this.pageStore=t.pageStore,this.relationStore=t.relationStore,this.datasetStore=t.datasetStore,t.blockEffortsStore&&(this.blockEffortsStore=t.blockEffortsStore),t.tagsStore&&(this.tagsStore=t.tagsStore),t.noteTagsStore&&(this.noteTagsStore=t.noteTagsStore),t.isNotebookSubscribed&&(this.isNotebookSubscribed=t.isNotebookSubscribed)}else this.store=e??R_,this.noteStore=t??z_,this.blockStore=n??B_,this.effortStore=r??V_}async getFactsByTimeRange(e,t){return(await this.store.getEventsByTimeRange(e,t)).flatMap(u_)}async runQuery(e,t={}){let n=X(e);return nh(n)?this.pipelineResultToQueryResult(await this.runPipelineParsed(n,t)):this.run(n,t)}async runRows(e,t={}){let n=e.filters.some(e=>[`result`,`block`,`note`].includes(e.key)),r=e.outputType??(e.target===`all`?void 0:e.target),i,a=e.filters;r?r===`segment`&&!n?i=`segment`:(i=`session`,a=[...e.filters,{key:`plane`,negate:!1,values:[{value:r,wildcard:!1}]}]):i=`session`;let o={family:`find`,raw:e.raw,target:i,filters:a,...e.window?{window:e.window}:{},...e.pipes?{pipes:e.pipes}:{},...e.error?{error:e.error}:{}},s=await this.runFind(o,t);return{parsed:e,runs:s.runs??[],...s.table?{table:s.table}:{}}}async runFindSession(e,t={}){let n=P_(t),r=t=>e.filters.filter(e=>e.key===t).flatMap(e=>e.values.map(e=>e.value)),i=r(`result`),a=r(`block`),o=r(`note`),s=new Map,c=new Set,l=e=>{for(let t of e){if(c.has(t.id))continue;c.add(t.id);let e=s.get(t.resultId);e?e.push(t):s.set(t.resultId,[t])}};if(i.length+a.length+o.length===0){let r=e.window?Hg(e.window,n):t.range?t.range:void 0;l(r?await this.store.getEventsByTimeRange(r.start,r.end):await this.store.scanAll())}else{for(let e of i)l(await this.store.getEventsByResult(e));for(let e of a)l(await this.store.getEventsByContent(e));for(let e of o)l(await this.store.getEventsForNote(e))}let u=[...s.entries()].filter(([,e])=>e.length>0);(e.window||t.range)&&(u=u.filter(([,r])=>F_(I_(r),e.window,t.range,n))),u.sort((e,t)=>I_(t[1])-I_(e[1]));let d=e.filters.filter(e=>e.key===`plane`),f=u.map(([e,t])=>{let n=t;return d.length>0&&(n=n.filter(e=>d.every(t=>{let n=t.values.some(t=>t.value===e.outputType);return t.negate?!n:n}))),{resultId:e,noteId:t[0].noteId,timestamp:I_(t),events:n}}).filter(e=>e.events.length>0),p=f,m=e.pipes;if(m&&(m.limit!==void 0||(m.offset??0)>0)){let e=m.offset??0;f=m.limit===void 0?f.slice(e):f.slice(e,e+m.limit)}return{parsed:e,notes:[],blocks:[],runs:f,events:p.flatMap(e=>e.events),stages:{selected:u.length,matched:f.length}}}async runFindTable(e,t={}){let n=P_(t),r=t=>e.filters.filter(e=>e.key===t).flatMap(e=>e.values.map(e=>e.value)),i=r(`result`),a=r(`block`),o=r(`note`),s=[];if(i.length+a.length+o.length===0){let r=e.window?Hg(e.window,n):t.range?t.range:void 0,i=r&&r.start>0&&r.end<2**53-1?r:void 0;if(i){if(s=await this.store.getEventsByTimeRange(i.start,i.end),this.store.getEventsByMetricDates){let e=H_(i.start,i.end,n.timeZone);if(e.length>0){let t=await this.store.getEventsByMetricDates(e);if(t.length>0){let e=new Set(s.map(e=>e.id));s=[...s,...t.filter(t=>!e.has(t.id))]}}}}else s=await this.store.scanAll()}else{let e=new Set,t=t=>{for(let n of t)e.has(n.id)||(e.add(n.id),s.push(n))};for(let e of i)t(await this.store.getEventsByResult(e));for(let e of a)t(await this.store.getEventsByContent(e));for(let e of o)t(await this.store.getEventsForNote(e))}let c=new Set,l=[];for(let t of s)t.grain===`event`&&(e.target!==`segment`||t.outputType===`segment`)&&(c.has(t.id)||(c.add(t.id),l.push(t)));let u=new Map,d=e=>{let t=e.metricTemporal?.[0];if(t?.temporalKind===`civil-date`&&t.civilDate)return t.civilDate;let r=u.get(e.timestamp);if(r)return r;let i=Fg(e.timestamp,n.timeZone);return u.set(e.timestamp,i),i},f=e=>{let t=e.metricTemporal?.[0];return t?.temporalKind===`civil-date`&&t.civilDate?Vg(t.civilDate,n.timeZone):e.timestamp},p=new Map,m=e.filters.filter(e=>![`result`,`block`,`note`,`plane`].includes(e.key)),h=!!(e.window||t.range),g=l.filter(r=>!h||F_(f(r),e.window,t.range,n)).filter(e=>{if(m.length===0)return!0;let t=u_(e);return t.length!==0&&t.some(e=>W_(e,m,p))}),_=g.length,v=new Map,y=new Set;for(let e of g)for(let t of e.metrics)if(t.type&&t.type!==`label`&&typeof t.value==`number`){y.add(t.type);let e=typeof t.metadata?.canonicalKey==`string`?t.metadata.canonicalKey:void 0;t.unit&&(v.set(t.type,t.unit),e&&v.set(e,t.unit))}let b=e.pipes,x=b?.select?.map(e=>e.col)??[`date`,`effort`,`discipline`,...y],S=t=>b?.select?.find(e=>e.col===t)?.unit??(e.displayUnit?e.displayUnit:v.get(t)),C=x.map(e=>e===`date`?{name:`date`,type:`date`}:e===`effort`||e===`discipline`||e===`note`||e===`grade`||e===`intensity`?{name:e,type:`string`}:{name:e,type:`number`,...S(e)?{unit:S(e)}:{}}),w=new Map(C.map(e=>[e.name,e.type])),T=g.map(t=>{let n={};for(let r of x)if(w.get(r)===`date`)n.date=d(t);else if(r===`effort`)n.effort=t.effortSlug;else if(r===`discipline`)n.discipline=t.metrics.find(e=>e.metadata?.effortDiscipline)?.metadata?.effortDiscipline;else{let i=t.metrics.find(e=>e.type===r||e.metadata?.canonicalKey===r);if(i&&typeof i.value==`number`){let t=i.value;if(e.displayUnit&&i.unit&&i.unit!==e.displayUnit)try{t=na(t,i.unit,e.displayUnit)}catch{}n[r]=t}else n[r]=i?i.value:void 0}return n.__id=t.id,n.__resultId=t.resultId,n});for(let e of[...b?.order??[]].reverse()){let t=e.dir===`desc`?-1:1;T=[...T].sort((n,r)=>{let i=n[e.col]??n.__id,a=r[e.col]??r.__id;return i===a?0:(i>a?1:-1)*t})}let E;if(e.groupBy&&e.groupBy.length>0){let t=new Map;for(let n of T){let r=e.groupBy.map(e=>String(n[e]??`unassigned`)).join(` · `),i=t.get(r);i?i.push(n):t.set(r,[n])}E=[...t.entries()].map(([e,t])=>({key:e,label:e,rows:t}))}let D=b?.offset??0,O=b?.limit;return{parsed:e,notes:[],blocks:[],runs:[],events:g,table:{columns:C,rows:O===void 0?T.slice(D):T.slice(D,D+O),...E?{groups:E}:{},totalCount:_,...O===void 0?{}:{limit:O},...D>0?{offset:D}:{}},stages:{selected:g.length,matched:_}}}async runFind(e,t={}){if(e.error)return{parsed:e,notes:[],blocks:[],stages:{selected:0,matched:0}};let n=Mh(e);if(n.length){let t=[...new Set([...e.advisories??[],...n])];t.length!==(e.advisories?.length??0)&&(e={...e,advisories:t})}if(e.target===`block`)return this.runFindBlock(e,t);if(e.target===`effort`)return this.runFindEffort(e);if(e.target===`session`)return this.runFindSession(e,t);if(e.target===`segment`||e.target===`event`)return this.runFindTable(e,t);if(e.target===`notebook`)return this.runFindNotebook(e,t);if(e.target===`page`)return this.runFindPage(e,t);if(e.target===`tag`)return this.runFindTag(e,t);if(e.target===`equipment`)return this.runFindEquipment(e,t);let r=j_(e.filters,`note`,e.sourceScope),i=N_(e,t,r.residual),a=(r.filters.length>0||r.selection.length>0||i.paged)&&this.noteStore.queryDomain?await this.noteStore.queryDomain({plan:`notes`,selection:r.selection,...r.filters.length?{filters:r.filters}:{},...i.order?{order:i.order}:{},...i.offset===void 0?{}:{offset:i.offset},...i.limit===void 0?{}:{limit:i.limit}}):void 0,o=a&&a.plan===`notes`?a:void 0,s=o?o.rows:await this.noteStore.getAllNotes(),c=o?o.selectedCount:void 0,l=!!o&&i.paged;s=M_(s,e);let u=c??s.length,d=P_(t);for(let t of e.filters)if(X_(t.key)&&!t.negate){let e=new Set;for(let n of t.values)(await this.noteStore.getNoteIdsForTag(n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.id))}else if(X_(t.key)&&t.negate)for(let e of t.values){let t=await this.noteStore.getNoteIdsForTag(e.value);s=s.filter(e=>!t.has(e.id))}else if(t.key===`effort`&&!t.negate){let e=new Set;for(let n of t.values)(await this.getNoteIdsForEffort(n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.id))}else if(am.includes(t.key)&&!t.negate){let e=new Set;for(let n of t.values)(await this.getNoteIdsForTypedTag(t.key,n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.id))}for(let t of e.filters)if(t.key===`text`){let e=t.values.map(e=>e.value).join(` `).toLowerCase();s=s.filter(n=>{let r=n.title.toLowerCase().includes(e)||n.rawContent.toLowerCase().includes(e);return t.negate?!r:r})}for(let t of e.filters)if(t.key===`type`&&!t.negate){let e=new Set(t.values.map(e=>e.value));s=s.filter(t=>t.type&&e.has(t.type))}for(let t of e.filters)if(t.key===`page`){let e=t.values.some(e=>e.value===`true`||e.value===`1`),n=t.negate?!e:e;s=s.filter(e=>n?e.type===`page`:e.type!==`page`)}s=k_(s,e.filters);let f=t.isNotebookSubscribed??this.isNotebookSubscribed??(()=>!0);for(let t of e.filters)if(t.key===`feed`){let e=new Set(t.values.map(e=>e.value)),n=t.values.some(e=>e.wildcard);s=s.filter(r=>{let i=b_(r),a=n?i!==`local`:e.has(i);return t.negate?!a:a})}let p=e.filters.find(e=>e.key===`subscribed`);if(p){let e=new Set(p.values.map(e=>e.value)),t=e.has(`true`),n=e.has(`false`);s=s.filter(e=>{let r=S_(e,f),i=!1;return t&&n?i=!0:t?i=r:n&&(i=!r),p.negate?!i:i})}else(e.target===`notebook`||e.raw.startsWith(`:notebook`))&&(s=s.filter(e=>S_(e,f)));for(let t of e.filters)if(t.key===`note`){let e=new Set(t.values.map(e=>e.value));s=s.filter(n=>t.negate?!e.has(n.id):e.has(n.id))}if((e.window||t.range)&&(s=s.filter(n=>F_(n.date??n.createdAt,e.window,t.range,d))),e.join&&(s=(await this.applyMetricJoin(e,s,[])).notes),e.pipes?.order)for(let t of[...e.pipes.order].reverse()){let e=t.dir===`desc`?-1:1;s=[...s].sort((n,r)=>{let i=n[t.col]??``,a=r[t.col]??``;return i===a?0:(i>a?1:-1)*e})}let m=e.pipes;if(!l&&m&&(m.limit!==void 0||(m.offset??0)>0)){let e=m.offset??0;s=m.limit===void 0?s.slice(e):s.slice(e,e+m.limit)}let h=s.length&&(this.pageStore||this.relationStore)?await this.containersAndPlacements(s):void 0;return{parsed:e,notes:s,blocks:[],...h?{containers:h.containers,placements:h.placements}:{},stages:{selected:u,matched:s.length}}}async containersAndPlacements(e){let t={},n={},r=this.relationStore?await this.relationStore.getBatches([...new Set(e.map(e=>e.id))]):void 0,i=new Map;for(let a of e){let e,o;if(r)e=r.get(a.id),o=ba(e?.links??[],e?.pages??[]),e&&e.tags.length>0&&(!a.tags||a.tags.length===0)&&(a.tags=e.tags.map(e=>e.label));else{let e=await this.pageStore.getNotePages(a.id),t=[];for(let n of e){i.has(n.pageId)||i.set(n.pageId,await this.pageStore.getPage(n.pageId));let e=i.get(n.pageId);e&&t.push(e)}o=ba(e,t)}n[a.id]=o;let s=o[0];t[a.id]=s?{kind:`page`,id:s.pageId,...s.slug?{slug:s.slug}:{},...s.date?{date:s.date}:{}}:{kind:`note`,id:a.id}}return{containers:t,placements:n}}async hydrateBlocks(e){let t=[...new Set(e.map(e=>e.noteId))];if(t.length===0)return[];let n=this.noteStore.getNotesByIds?await this.noteStore.getNotesByIds(t):await this.noteStore.getAllNotes(),r=new Map;for(let e of n)if(!(!Number.isSafeInteger(e.sourceRevision)||e.sourceRevision<1))try{Fa(e.rawContent,e.blocks,e.sourceRevision),r.set(e.id,e)}catch{}return e.flatMap(e=>{let t=r.get(e.noteId),n=t?.blocks[e.blockId];return!t||!n||e.id!==`${t.id}:${n.id}`||n.id!==e.blockId||n.kind!==e.dataType||n.version!==e.blockVersion||n.sourceRevision!==e.sourceRevision||t.sourceRevision!==e.sourceRevision||n.from!==e.from||n.to!==e.to?[]:[{...e,rawContent:t.rawContent.slice(n.from,n.to)}]})}async runFindBlock(e,t={}){let n=j_(e.filters,`block`),r=N_(e,t,n.residual),i=(n.filters.length>0||n.selection.length>1||r.paged)&&this.blockStore.queryDomain?await this.blockStore.queryDomain({plan:`blocks`,selection:n.selection,...n.filters.length?{filters:n.filters}:{},...r.order?{order:r.order}:{},...r.offset===void 0?{}:{offset:r.offset},...r.limit===void 0?{}:{limit:r.limit}}):void 0,a=i&&i.plan===`blocks`?i:void 0,o=a?a.rows:await this.blockStore.getAllBlocks(),s=await this.hydrateBlocks(o),c=s.length!==o.length,l=a&&!c?a.selectedCount:void 0,u=!!a&&r.paged&&!c;a&&c&&(s=await this.hydrateBlocks(await this.blockStore.getAllBlocks())),s=O_(s,e.filters),s=s.filter(e=>!e.sourceId||mm.some(t=>D_(e,t)));let d=l??s.length,f=P_(t);for(let t of e.filters)if(t.key===`text`){let e=t.values.map(e=>e.value).join(` `).toLowerCase();s=s.filter(n=>t.negate!==n.rawContent.toLowerCase().includes(e))}for(let t of e.filters)if(t.key===`type`&&!t.negate){let e=new Set(t.values.map(e=>e.value));s=s.filter(t=>e.has(t.dataType))}s=k_(s,e.filters);let p=t.isNotebookSubscribed??this.isNotebookSubscribed??(()=>!0);for(let t of e.filters)if(t.key===`feed`){let e=new Set(t.values.map(e=>e.value)),n=t.values.some(e=>e.wildcard);s=s.filter(r=>{let i=b_(r),a=n?i!==`local`:e.has(i);return t.negate?!a:a})}let m=e.filters.find(e=>e.key===`subscribed`);if(m){let e=new Set(m.values.map(e=>e.value)),t=e.has(`true`),n=e.has(`false`);s=s.filter(e=>{let r=S_(e,p),i=!1;return t&&n?i=!0:t?i=r:n&&(i=!r),m.negate?!i:i})}for(let t of e.filters)if(X_(t.key)&&!t.negate){let e=new Set;for(let n of t.values)(await this.noteStore.getNoteIdsForTag(n.value)).forEach(t=>e.add(t));s=s.filter(t=>e.has(t.noteId))}else if(t.key===`effort`&&!t.negate){let e=new Set;for(let n of t.values){let t=await this.blockEffortsStore.getAllFromIndex(`by-effort`,n.value);for(let n of t)e.add(`${n.noteId}:${n.blockId}`)}s=s.filter(t=>e.has(`${t.noteId}:${t.blockId}`))}for(let t of e.filters)if(t.key===`note`){let e=new Set(t.values.map(e=>e.value));s=s.filter(n=>t.negate?!e.has(n.noteId):e.has(n.noteId))}if(e.window||t.range){let n=await this.noteStore.getAllNotes(),r=new Map(n.map(e=>[e.id,e.date??e.createdAt]));s=s.filter(n=>F_(r.get(n.noteId)??n.createdAt,e.window,t.range,f))}if(e.join&&(s=(await this.applyMetricJoin(e,[],s)).blocks),e.pipes?.order)for(let t of[...e.pipes.order].reverse()){let e=t.dir===`desc`?-1:1;s=[...s].sort((n,r)=>{let i=n[t.col]??``,a=r[t.col]??``;return i===a?0:(i>a?1:-1)*e})}let h=e.pipes;if(!u&&h&&(h.limit!==void 0||(h.offset??0)>0)){let e=h.offset??0;s=h.limit===void 0?s.slice(e):s.slice(e,e+h.limit)}return{parsed:e,notes:[],blocks:s,stages:{selected:d,matched:s.length}}}async runFindEffort(e){let t=await this.effortStore.getAllEfforts(),n=t.length,r=(e,t,n,r)=>{let i=n.toLowerCase();switch(t){case`effort`:return r?e.slug.includes(i)||e.label.toLowerCase().includes(i)||e.aliases.some(e=>e.toLowerCase().includes(i)):e.slug===n||e.label.toLowerCase()===i||e.aliases.some(e=>e.toLowerCase()===i);case`discipline`:return e.baseAttributes.discipline===n;case`intensity`:return e.baseAttributes.intensityTier===n;case`origin`:return e.registrySource===n;case`text`:return e.label.toLowerCase().includes(i)||e.slug.includes(i)||e.aliases.some(e=>e.toLowerCase().includes(i));default:return!0}},i=t;for(let t of e.filters)[`effort`,`discipline`,`intensity`,`origin`,`text`].includes(t.key)&&(i=i.filter(e=>{let n=t.values.some(n=>r(e,t.key,n.value,n.wildcard));return t.negate?!n:n}));if(e.pipes?.order)for(let t of[...e.pipes.order].reverse()){let e=t.dir===`desc`?-1:1;i=[...i].sort((n,r)=>{let i=n[t.col]??``,a=r[t.col]??``;return i===a?0:(i>a?1:-1)*e})}let a=e.pipes;if(a&&(a.limit!==void 0||(a.offset??0)>0)){let e=a.offset??0;i=a.limit===void 0?i.slice(e):i.slice(e,e+a.limit)}let o=[...new Set(i.map(e=>e.ownerNoteId).filter(e=>typeof e==`string`&&e.length>0))],s=[];if(o.length>0){let e=this.noteStore.getNotesByIds?await this.noteStore.getNotesByIds(o):(await this.noteStore.getAllNotes()).filter(e=>o.includes(e.id)),t=new Map(e.map(e=>[e.id,e]));s=o.flatMap(e=>{let n=t.get(e);return n?[n]:[]})}return{parsed:e,notes:s,blocks:[],efforts:i,stages:{selected:n,matched:i.length}}}async run(e,t={}){if(nh(e))throw Error(`Pipeline queries do not aggregate directly — execute them with runPipeline().`);if(eh(e))return{parsed:{family:`aggregate`,raw:e.raw,agg:`count`,metric:e.target,filters:[],groupBy:[]},series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[],...e.error?{error:e.error}:{}};let n={parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[]};if(e.error)return n;if(e.join)return this.runJoined(e,t);let r=P_(t),i=L_(e,t,r),a=i?{start:i.start,end:i.end}:void 0,o=a&&a.start>0&&a.end<2**53-1?a:void 0,s=o?await this.store.getEventsByTimeRange(o.start,o.end):await this.store.scanAll();if(o&&this.store.getEventsByMetricDates){let e=H_(o.start,o.end,r.timeZone);if(e.length>0){let t=await this.store.getEventsByMetricDates(e);if(t.length>0){let e=new Set(s.map(e=>e.id));s=[...s,...t.filter(t=>!e.has(t.id))]}}}return this.aggregateEventRows(e,s,t,i)}async runAggregateEvents(e,t,n={}){let r={parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[]};if(e.error)return r;if(e.join)return{...r,error:`where <content> joins re-read the store and cannot run on carried pipeline data — author the join in the source stage.`};let i=L_(e,n,P_(n));return this.aggregateEventRows(e,t,n,i)}async runPipeline(e,t={}){return this.runPipelineParsed(X(e),t)}async runPipelineParsed(e,t={}){if(!nh(e)){let t=e.error??`Not a pipeline: "${e.raw}". Pipelines look like :source{filters} | :sum{metric:x} | :table.`;return{parsed:{family:`pipeline`,raw:e.raw,source:{kind:`dataset`,name:``},transforms:[],error:t},error:t}}let n=t=>({parsed:e,error:t});if(e.error)return n(e.error);let r,i,a,o=[];if(e.source.kind===`dataset`){let r=e.source.name,i=t.pageSources?.get(r)??this.datasetStore?.getDataset(r);if(!i)return n(`Unknown dataset "${r}" — the host must register it before the query runs.`);a=i.events,o=i.notes}else if(eh(e.source.query)){let i=e.source.query;if(r=await this.runFind(i,{context:t.context,...t.rangeStart!==void 0||t.rangeEnd!==void 0?{range:{start:t.rangeStart??0,end:t.rangeEnd??2**53-1,endExclusive:!1}}:{}}),i.error)return n(i.error)}else if(i=await this.run(e.source.query,t),e.source.query.error)return n(e.source.query.error);if(e.transforms.length===0)return r?{parsed:e,...r.notes.length?{notes:r.notes}:{},...r.blocks.length?{blocks:r.blocks}:{},...r.efforts?.length?{efforts:r.efforts}:{},...r.runs?.length?{runs:r.runs}:{},...r.table?{table:r.table}:{},...r.containers?{containers:r.containers}:{},...r.placements?{placements:r.placements}:{},...e.sink?{chart:e.sink}:{}}:e.source.kind===`dataset`?{parsed:e,notes:o,...e.sink?{chart:e.sink}:{}}:{parsed:e,...i?{series:i.series,...i.unit?{unit:i.unit}:{},...i.error?{error:i.error}:{}}:{},...e.sink?{chart:e.sink}:{}};if(i)for(let n of e.transforms){if(i.error)break;i=q_(i,n,t,P_(t))}else{!a&&r&&(a=await this.sourceEventsFromFind(r)),i=await this.runAggregateEvents(e.transforms[0],a??[],t);for(let n of e.transforms.slice(1)){if(i.error)break;i=q_(i,n,t,P_(t))}}return{parsed:e,series:i.series,...i.unit?{unit:i.unit}:{},...i.error?{error:i.error}:{},...e.sink?{chart:e.sink}:{}}}async sourceEventsFromFind(e){if(e.events)return e.events;let t=[];for(let n of e.notes)t.push(...await this.store.getEventsForNote(n.id));for(let n of e.blocks)n.dataType===`wod`&&n.blockContentId&&t.push(...await this.store.getEventsByContent(n.blockContentId));return t}pipelineResultToQueryResult(e){let t={family:`aggregate`,raw:e.parsed.raw,agg:`count`,metric:``,filters:[],groupBy:[]};if(e.series){let n=e.series.reduce((e,t)=>e+t.points.length,0);return{parsed:t,series:e.series,stages:{selected:0,buckets:e.series[0]?.points.length??0,aggregated:n,groups:e.series.length},matched:[],...e.unit?{unit:e.unit}:{},...e.error?{error:e.error}:{}}}return{parsed:t,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[],...e.error?{error:e.error}:{}}}async aggregateEventRows(e,t,n,r){let i=P_(n);if(!e.metric&&e.agg!==`count`)return{parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[],error:`Aggregate "${e.agg}" requires a metric — use ${e.agg}{metric:<key>}`};let a=(e,t)=>!t||e===t||t===`rep`&&e===`reps`||t===`reps`&&e===`rep`,o=e=>e.metricDate?Vg(e.metricDate,i.timeZone):e.timestamp,s=t.flatMap(u_).filter(t=>a(t.metricKey,e.metric)).filter(e=>!r||Ug(o(e),r)),c=e.filters.some(e=>e.key===`tags`)||e.groupBy.includes(`tags`),l=await this.loadNoteTags(s,c),{selected:u,report:d}=m_(s.filter(t=>W_(t,e.filters,l)),e.agg);return this.buildResult(u,e,n,l,r,d)}buildResult(e,t,n,r,i,a){let o=P_(n),s=t.groupBy.find(e=>e===`day`||e===`week`),c=t.groupBy.filter(e=>e!==`day`&&e!==`week`),l=t.rollup,u=e=>e.metricDate??Fg(e.timestamp,o.timeZone),d=e=>{if(s===`day`)return`d:${u(e)}`;if(s===`week`)return`w:${Rg(u(e))}`;if(l){let t=u(e);if(l.unit===`w`){let e=Rg(t),n=Math.floor(Lg(`1970-01-05`,e)/7);return`w:${Ig(`1970-01-05`,Math.floor(n/l.size)*l.size*7)}`}if(l.unit===`d`){let e=Lg(`1970-01-01`,t);return`d:${Ig(`1970-01-01`,Math.floor(e/l.size)*l.size)}`}}return``},f=e=>e.startsWith(`d:`)||e.startsWith(`w:`)?Vg(e.slice(2),o.timeZone):2**53-1,p=e=>e.startsWith(`d:`)||e.startsWith(`w:`)?e.slice(2):e,m=e=>{let t=s??(l?.unit===`w`?`week`:l?.unit===`d`?`day`:void 0);if(!t||e.length===0)return e;let n=i&&i.end!==2**53-1?{startIso:Fg(i.start,o.timeZone),endIso:i.endExclusive?Fg(i.end-1,o.timeZone):Fg(i.end,o.timeZone)}:{startIso:p(e[0]),endIso:p(e[e.length-1])},r=t===`week`?Rg(n.startIso):n.startIso,a=t===`week`?Rg(n.endIso):n.endIso,c=t===`week`?7*(l?.size??1):l?.size??1,u=Lg(r,a);if(u<0||u/c>1e4)return e;let d=[];for(let e=r;d.push(t===`week`?`w:${e}`:`d:${e}`),!(e>=a);e=Ig(e,c));return d},h=Og(e,{directive:t.displayUnit,preferred:n.preferredUnit}),g=h.unit,_=h.convert===!0,v=h.error,y=new Map;for(let n of e){let e=c.map(e=>Cee(n,e,r,o)),i=c.length?JSON.stringify(e):t.metric,a=c.length?e.map(e=>e===`\0unassigned`?`unassigned`:e).join(` · `):t.metric,s=y.get(i);s?s.rows.push(n):y.set(i,{label:a,rows:[n]})}let b=[...y.entries()].map(([e,n])=>{let r=n.rows;if(v)return{key:e,label:n.label,points:[],unit:void 0,error:v};let i=new Map;for(let e of r){let t=d(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=[...i.keys()].sort(),o=s?m(a):a,c,u=o.map(e=>{let n=i.get(e);if(!n)return{ts:f(e),value:0,missing:!0};let r;try{r=n.map(e=>_&&g&&(e.unit??e.metricUnit)!==void 0?na(e.value,e.unit??e.metricUnit,g):e.value)}catch(t){return c=t instanceof Error?t.message:String(t),{ts:f(e),value:0,missing:!0}}let a=K_(r,t.agg,n);return a.state===`error`?(c=a.message,{ts:f(e),value:0,missing:!0}):{ts:s||l?f(e):Math.min(...n.map(e=>e.timestamp)),value:a.value,...a.state===`absent`?{missing:!0}:{}}}),p=t.agg===`count`?`count`:g;return{key:e,label:n.label,points:u,unit:p,...c?{error:c}:{}}}),x=b.reduce((e,t)=>e+t.points.length,0),S=b.length===1&&b[0].points.length===1?b[0].points[0].value:void 0,C=b.length>0?b[0].unit:void 0,w=s||l?b[0]?.points.length??0:+!!e.length,T=a?.insufficientScopes??[],E=b.find(e=>e.error)?.error??(T.length>0?`Insufficient evidence: ${T.map(e=>`${e.resultId}/${e.metricKey} (${e.reason})`).join(`; `)}`:void 0);return{parsed:t,series:b,stages:{selected:e.length,buckets:w,aggregated:x,groups:b.length},matched:e,scalar:S,unit:C,...E?{error:E}:{},...a?{coverage:a}:{}}}async runJoined(e,t){let n={parsed:e,series:[],stages:{selected:0,buckets:0,aggregated:0,groups:0},matched:[]},r=e.join,i=await this.runFind({family:`find`,raw:``,target:r.target,filters:r.filters,window:r.last?{kind:`relative`,size:r.last.size,unit:r.last.unit}:void 0}),a=await this.contentIdsFromFindResult(i);if(a.size===0)return n;let o=h_(await this.deriveMetricFacts(a,e.metric)),s=L_(e,t,P_(t));s&&(o=o.filter(e=>Ug(e.timestamp,s)));let c=e.filters.some(e=>e.key===`tags`)||e.groupBy.includes(`tags`),l=await this.loadNoteTags(o,c),{selected:u,report:d}=m_(o.filter(t=>W_(t,e.filters,l)),e.agg);return this.buildResult(u,e,t,l,s,d)}async applyMetricJoin(e,t,n){let r=e.join,i=await this.noteContentMap(new Set(t.map(e=>e.id))),a=new Set;for(let e of i.values())for(let t of e)a.add(t);for(let e of n)e.dataType===`wod`&&e.blockContentId&&a.add(e.blockContentId);let o=await this.contentIdsSatisfying(a,r);return n=n.filter(e=>e.dataType===`wod`&&!!e.blockContentId&&o.has(e.blockContentId)),t=t.filter(e=>{let t=i.get(e.id);return!!t&&[...t].some(e=>o.has(e))}),{notes:t,blocks:n}}async contentIdsSatisfying(e,t){let n=h_(await this.deriveMetricFacts(e,t.metric)),r=await this.loadNoteTags(n,t.filters.some(e=>e.key===`tags`)),i=m_(n.filter(e=>W_(e,t.filters,r)),t.agg).selected,a=new Map;for(let e of i){let t=e.blockContentId??``,n=a.get(t);n?n.push(e):a.set(t,[e])}let o=new Set;for(let[e,n]of a){let r=K_(n.map(e=>e.value),t.agg,n);r.state===`observed`&&wee(r.value,t.operator,t.threshold)&&o.add(e)}return o}async deriveMetricFacts(e,t){let n=[...new Set(e)];return(await Promise.all(n.map(e=>this.store.getEventsByContent(e)))).flat().flatMap(u_).filter(e=>e.metricKey===t)}async allContentBlocks(){return this.hydrateBlocks(await this.blockStore.getAllBlocks())}async noteContentMap(e){let t=new Map;if(!e.size)return t;let n=await this.allContentBlocks();for(let r of n){if(r.dataType!==`wod`||!r.blockContentId||!e.has(r.noteId))continue;let n=t.get(r.noteId);n||(n=new Set,t.set(r.noteId,n)),n.add(r.blockContentId)}return t}async contentIdsFromFindResult(e){let t=new Set;for(let n of e.blocks)n.dataType===`wod`&&n.blockContentId&&t.add(n.blockContentId);if(e.notes.length){let n=new Set(e.notes.map(e=>e.id)),r=await this.noteContentMap(n);for(let e of r.values())for(let n of e)t.add(n)}return t}async loadNoteTags(e,t){let n=new Map;if(!t)return n;let r=[...new Set(e.map(e=>e.noteId))];if(this.relationStore){let e=await this.relationStore.getBatches(r);for(let t of r)n.set(t,(e.get(t)?.tags??[]).map(e=>e.label));return n}return await Promise.all(r.map(async e=>n.set(e,await this.noteStore.getNoteTagLabels(e)))),n}async getNoteIdsForEffort(e){let t=await this.blockEffortsStore.getAllFromIndex(`by-effort`,e);return new Set(t.map(e=>e.noteId))}async getNoteIdsForTypedTag(e,t){let n=(await this.tagsStore.getAllFromIndex(`by-label`,t)).find(t=>t.type===e);if(!n)return new Set;let r=await this.noteTagsStore.getAllFromIndex(`by-tag`,n.id);return new Set(r.map(e=>e.noteId))}async runFindNotebook(e,t={}){return this.runFind({...e,target:`note`},t)}async runFindPage(e,t={}){let n={parsed:e,notes:[],blocks:[],stages:{selected:0,matched:0}};if(!this.pageStore?.getAllPages||!this.pageStore?.getAllLinks)return n;let r=P_(t),[i,a]=await Promise.all([this.pageStore.getAllPages(),this.pageStore.getAllLinks()]),o=ba(a,i),s=new Set(o.map(e=>e.noteId)).size;for(let t of e.filters){if(t.key!==`page`)continue;let e=new Set(t.values.map(e=>e.value));o=o.filter(n=>{let r=e.has(n.pageId)||n.slug!==void 0&&e.has(n.slug)||n.date!==void 0&&e.has(n.date);return t.negate?!r:r})}let c=[...new Set(o.map(e=>e.noteId))],l=this.noteStore.getNotesByIds?await this.noteStore.getNotesByIds(c):(await this.noteStore.getAllNotes()).filter(e=>c.includes(e.id));for(let t of e.filters)if(t.key===`note`){let e=new Set(t.values.map(e=>e.value));l=l.filter(n=>t.negate?!e.has(n.id):e.has(n.id))}for(let t of e.filters)if(t.key===`text`){let e=t.values.map(e=>e.value).join(` `).toLowerCase();l=l.filter(n=>{let r=n.title.toLowerCase().includes(e)||n.rawContent.toLowerCase().includes(e);return t.negate?!r:r})}l=k_(l,e.filters),(e.window||t.range)&&(l=l.filter(n=>F_(n.date??n.createdAt,e.window,t.range,r))),l=Y_(l,e);let u=new Set(l.map(e=>e.id)),d=new Map;for(let e of o){if(!u.has(e.noteId))continue;let t=d.get(e.noteId);t?t.push(e):d.set(e.noteId,[e])}let f={};for(let e of l){let t=d.get(e.id)?.[0];f[e.id]=t?{kind:`page`,id:t.pageId,...t.slug?{slug:t.slug}:{},...t.date?{date:t.date}:{}}:{kind:`note`,id:e.id}}return{parsed:e,notes:l,blocks:[],containers:f,placements:Object.fromEntries(d),stages:{selected:s,matched:l.length}}}async runFindTag(e,t={}){let n=P_(t),r=this.tagsStore.getAll?await this.tagsStore.getAll():[],i=r.length,a=r;for(let t of e.filters)if(X_(t.key)){let e=new Set(t.values.map(e=>e.value.toLowerCase()));a=a.filter(n=>{let r=typeof n.label==`string`&&e.has(n.label.toLowerCase());return t.negate?!r:r})}else if(t.key===`type`){let e=new Set(t.values.map(e=>e.value));a=a.filter(n=>{let r=n.type!==void 0&&e.has(n.type);return t.negate?!r:r})}else if(t.key===`contributes`)a=a.filter(e=>{let n=(e.contributions??[]).some(e=>t.values.some(t=>Tee(e,t.value)));return t.negate?!n:n});else if(t.key===`text`){let e=t.values.map(e=>e.value).join(` `).toLowerCase();a=a.filter(n=>t.negate!==`${n.label??``} ${Z_(n)}`.toLowerCase().includes(e))}let o=a.map(e=>({id:`tag/${typeof e.type==`string`&&e.type?e.type:`general`}/${e.label}`,title:e.label,type:`tag`,tagType:typeof e.type==`string`?e.type:void 0,contributions:e.contributions??[],createdAt:typeof e.createdAt==`number`?e.createdAt:0,content:Z_(e),rawContent:Z_(e),sourceRevision:1,blocks:{}}));return(e.window||t.range)&&(o=o.filter(r=>F_(r.createdAt,e.window,t.range,n))),o=Y_(o,e),{parsed:e,notes:o,blocks:[],stages:{selected:i,matched:o.length}}}async runFindEquipment(e,t={}){let n=await this.noteStore.getAllNotes(),r=P_(t),i=n.filter(e=>v_(e)===`notebook/equipment`||e.type===`equipment`||D_(e,`equipment`)),a=i.length;for(let t of e.filters)if(t.key===`equipment`){let e=new Set;for(let n of t.values)(await this.getNoteIdsForTypedTag(`equipment`,n.value)).forEach(t=>e.add(t));i=i.filter(n=>t.negate?!e.has(n.id):e.has(n.id))}else if(X_(t.key)&&!t.negate){let e=new Set;for(let n of t.values)(await this.noteStore.getNoteIdsForTag(n.value)).forEach(t=>e.add(t));i=i.filter(t=>e.has(t.id))}else if(X_(t.key)&&t.negate)for(let e of t.values){let t=await this.noteStore.getNoteIdsForTag(e.value);i=i.filter(e=>!t.has(e.id))}for(let t of e.filters)if(t.key===`text`){let e=t.values.map(e=>e.value).join(` `).toLowerCase();i=i.filter(n=>{let r=n.title.toLowerCase().includes(e)||n.rawContent.toLowerCase().includes(e);return t.negate?!r:r})}return i=k_(i,e.filters),(e.window||t.range)&&(i=i.filter(n=>F_(n.date??n.createdAt,e.window,t.range,r))),i=Y_(i,e),{parsed:e,notes:i,blocks:[],stages:{selected:a,matched:i.length}}}};function Y_(e,t){let n=e;if(t.pipes?.order)for(let e of[...t.pipes.order].reverse()){let t=e.dir===`desc`?-1:1;n=[...n].sort((n,r)=>{let i=n[e.col]??``,a=r[e.col]??``;return i===a?0:(i>a?1:-1)*t})}let r=t.pipes;if(r&&(r.limit!==void 0||(r.offset??0)>0)){let e=r.offset??0;n=r.limit===void 0?n.slice(e):n.slice(e,e+r.limit)}return n}function X_(e){return e===`tags`||e===`tag`}function Tee(e,t){let n=t.indexOf(`:`),r=n===-1?t:t.slice(0,n),i=n===-1?``:t.slice(n+1);return e.kind===r?i?e.kind===`metric`?e.type===i:e.kind===`tag`?e.slug===i:e.name===i:!0:!1}function Z_(e){let t=(e.contributions??[]).map(e=>e.kind===`metric`?`metric ${e.type}`:e.kind===`tag`?`tag ${e.slug}`:`function ${e.name}`);return t.length?`contributes ${t.join(`, `)}`:``}function Q_(e){return e.startsWith(`collection.`)?`notebook.${e.slice(11)}`:e.startsWith(`feed.`)?`notebook.${e.slice(5)}`:e}function Eee(e){return e.startsWith(`markdown/collections/`)?`markdown/notebooks/${e.slice(21)}`:e.startsWith(`markdown/feeds/`)?`markdown/notebooks/${e.slice(15)}`:e}function Dee(e){return e.startsWith(`page:collection:`)?`page:${e.slice(16)}`:e.startsWith(`collection:`)?`notebook:${e.slice(11)}`:e.startsWith(`feed:`)?`notebook:${e.slice(5).replace(/^feeds\//,``)}`:e}function Oee(e){return e.startsWith(`feeds/`)?e.slice(6):e}function kee(e){let t=e,n=e=>{t={...t,...e}},r=e.sourceId;if(typeof r==`string`){let e=Dee(r);e!==r&&n({sourceId:e})}let i=e.sourcePath;if(typeof i==`string`){let e=Eee(i);e!==i&&n({sourcePath:e})}let a=e.seedChunkId;if(typeof a==`string`){let e=Q_(a);e!==a&&n({seedChunkId:e})}let o=e.routeId;if(typeof o==`string`){let e=Oee(o);e!==o&&n({routeId:e})}return`catalog`in t&&(t={...t},delete t.catalog),t.type===`feed`&&n({type:`note`}),t}function Aee(e){let t=e.sourceId;if(typeof t==`string`&&(/^(collection|feed):/.test(t)||t.startsWith(`page:collection:`)))return!0;let n=e.sourcePath;if(typeof n==`string`&&(n.startsWith(`markdown/collections/`)||n.startsWith(`markdown/feeds/`)))return!0;let r=e.seedChunkId;if(typeof r==`string`&&/^(collection|feed)\./.test(r))return!0;let i=e.routeId;return!!(typeof i==`string`&&i.startsWith(`feeds/`)||`catalog`in e||e.type===`feed`)}var $_=[`table`,`list`,`value`,`timeseries`,`bar`,`donut`,`toplist`,`stacked-bar`,`goal-rings`,`zone-distribution`];function ev(e){return $_.includes(e)}function tv(e){return e==null||e===``?`table`:e}function nv(e){return`unknown widget type "${e}"`}function rv(e){return`unknown token${e.length>1?`s`:``}: ${e.map(e=>`$${e}`).join(`, `)}`}var iv=[];new Set(um);function av(e){if(e===``)return{type:``,attributes:{},attributeOrder:[],error:`missing widget type after "query:"`};let t={},n=[],r=e.trim(),i=r.search(/\s/),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i),s=/([a-zA-Z][a-zA-Z0-9_-]*)=("([^"]*)"|\S+)/g,c=0;for(let e of o.matchAll(s)){c+=e[0].length;let r=e[1].toLowerCase(),i=e[3]===void 0?e[2]:e[3];if(r in t)return{type:a,attributes:t,attributeOrder:n,error:`duplicate attribute "${r}"`};t[r]=i,n.push(r)}let l=o.replace(s,``).trim();if(l!==``)return{type:a,attributes:t,attributeOrder:n,error:`malformed attribute "${l.split(/\s+/)[0]}"`};let u=a.toLowerCase(),d,f;if(u.endsWith(`-full`))f=!0,u=u.slice(0,-5);else{let e=u.match(/-(\d+)$/);e&&(d=Number(e[1]),u=u.slice(0,-e[0].length))}return u===``||!/^[a-z][a-z0-9-]*$/.test(u)?{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n,error:`malformed widget type "${e}"`}:/-(\d+|full)$/.test(u)?{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n,error:`malformed widget suffix "${e}"`}:d!=null&&(d<1||d>4)?{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n,error:`span ${d} outside 1..4`}:{type:u,spanCols:d,spanFull:f,attributes:t,attributeOrder:n}}var ov=`dashboard.`;function jee(e){return e.dashboard===`true`||e.dashboard===!0}function Mee(e){let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith(ov)||n===ov)continue;let e=n.slice(10);e!==``&&(Array.isArray(r)?r.length>0&&t.push({name:e,values:r.map(String),isList:!0}):t.push({name:e,values:[String(r)],isList:!1}))}return t}function sv(e){let t={};for(let n of e)t[n.name]=n.values[0];return t}function Nee(e,t,n){let r=`${ov}${t}`,i=e[r],a={...e};if(Array.isArray(i)){if(!i.includes(n))return e;a[r]=[n,...i.filter(e=>e!==n)]}else a[r]=i==null?n:typeof i==`number`&&!isNaN(Number(n))?Number(n):n;return a}var Pee=/\$([A-Za-z][\w-]*)/g;function cv(e,t){let n=new Set;return{query:e.replace(Pee,(e,r)=>t[r]??(n.add(r),e)),missing:[...n]}}function lv(e){let t=e.split(`
21
21
  `,1)[0].replace(/^#{1,6}\s*/,``).trim();return t===``?void 0:t}function Fee(e){let t=e.replace(/\s*\n\s*/g,` `).trim();return t===``?void 0:t}function uv(e,t){let n=[];e.forEach((t,r)=>{if(t.type!==`query`)return;let i=t.content.split(`
@@ -72,7 +72,7 @@ sum:$metric{} by {week}
72
72
  `)?e:e+`
73
73
  `,r=Qr.create({doc:n,extensions:[Rc]}),i=Mr(r),a=[];return i.iterate({enter(e){if(e.type.isError){let n=t+e.from,r=t+Math.max(e.to,e.from+1);a.push({from:n,to:Math.min(r,n+50),severity:`error`,message:`Syntax error in Whiteboard Script`})}}}),a}function RT(e){let{sections:t}=e.state.field(NT,!1)??{sections:[]},n=[];for(let r of t){if(r.type!==`time`&&r.type!==`log`||r.contentFrom===void 0||r.contentTo===void 0)continue;let t=LT(e.state.doc.sliceString(r.contentFrom,r.contentTo),r.contentFrom);n.push(...t)}return n}var zT=fi(RT,{delay:500}),BT=[{label:"```time",detail:`Whiteboard Script (timer)`,type:`keyword`,apply:ei("```time\n${}\n```"),boost:90},{label:"```log",detail:`Whiteboard Script (log/completed)`,type:`keyword`,apply:ei("```log\n${}\n```"),boost:85},{label:"```query",detail:`WQL Analytics Query`,type:`keyword`,apply:ei("```query\n${}\n```"),boost:80},{label:"```widget",detail:`Custom React Widget`,type:`keyword`,apply:ei("```widget:${name}\n${}\n```"),boost:75}];function VT(e){let t=e.state.doc.lineAt(e.pos);if(!t.text.slice(0,e.pos-t.from).match(/^`{1,3}(\w*)$/))return null;let n=IT(e.state);return n&&n.type!==`markdown`?null:{from:t.from,options:BT,validFor:/^`{1,3}\w*$/}}function HT(e){if(e.state.readOnly)return!1;let t=IT(e.state);if(t&&t.type!==`markdown`)return!1;let{from:n,to:r}=e.state.selection.main,i=e.state.doc.sliceString(n,r);return i?e.dispatch({changes:{from:n,to:r,insert:`\`\`\`time\n${i}\n\`\`\``}}):e.dispatch({changes:{from:n,insert:"```time\n\n```"},selection:{anchor:n+8}}),!0}function UT(e,t){if(t.state.readOnly||e.data!=="`")return!1;let n=IT(t.state);if(n&&n.type!==`markdown`)return!1;let{from:r,to:i}=t.state.selection.main;if(r===i)return!1;let a=t.state.doc.sliceString(r,i);return t.dispatch({changes:{from:r,to:i,insert:`\`\`\`time\n${a}\n\`\`\``}}),!0}var WT=Sr.domEventHandlers({beforeinput:UT}),GT=hr.of([{key:`Mod-Alt-w`,run:HT}]),KT=Ur.define({combine:e=>e}),qT=Ur.define({combine:e=>e[e.length-1]}),JT,YT=new WeakMap;function XT(e){if(!e)return JT??=wg({});let t=YT.get(e);return t||(t=wg(e),YT.set(e,t)),t}var ZT,QT=new WeakMap;function $T(e,t){let n;e?(n=QT.get(e)??new Map,QT.set(e,n)):n=ZT??=new Map;let r=t??``,i=n.get(r);return i||(i=Lc({...e??{},...t?{sport:t}:{}}),n.set(r,i)),i}function eE(e,t){return/^`{3,}wql\b/i.test(e.doc.lineAt(t).text.trim())}function tE(e){let t=FT(e.state,e.pos),{contentFrom:n,contentTo:r}=t??{};if(!t||n===void 0||r===void 0)return null;let i=t.type===`time`||t.type===`log`,a=t.type===`query`||eE(e.state,t.from);if(!i&&!a||e.pos<n||e.pos>r)return null;let{state:o}=e,s=o.selection.main,c=Math.min(Math.max(s.from,n),r),l=Math.min(Math.max(s.to,n),r),u=Qr.create({doc:o.doc.sliceString(n,r),selection:di.range(c-n,l-n),extensions:i?Rc:[Yh]}),d=(i?$T(o.facet(qT)?.whiteboardScript,t.sport):XT(o.facet(qT)?.wql))(new vi(u,e.pos-n,e.explicit)),f=e=>e&&{...e,from:n+e.from,...e.to===void 0?{}:{to:n+e.to}};return d instanceof Promise?d.then(f):f(d)}async function nE(e){for(let t of e.state.facet(KT)){let n=await t(e);if(n)return n}return VT(e)??tE(e)}var rE=Wr({interactionDelay:0,activateOnCompletion:e=>e.type===`property`&&typeof e.apply==`string`&&e.apply.endsWith(`:
74
74
  - `),override:[nE]}),iE=class{view;rects=[];docVersion=0;listeners=new Set;pendingNotify=null;constructor(e){this.view=e,this.measure()}update(e){e.docChanged&&this.docVersion++,(e.docChanged||e.geometryChanged)&&this.measure()}addListener(e){return this.listeners.add(e),e(this.rects,this.docVersion),()=>{this.listeners.delete(e)}}measure(){try{let e=this.view.state.field(NT,!1)?.sections??[],t=this.view.state.doc.length;this.rects=e.map(e=>{let n=Math.max(0,Math.min(e.from,t)),r=Math.max(0,Math.min(e.to,t)),i=0,a=20,o;try{let e=this.view.lineBlockAt(n),t=this.view.lineBlockAt(r);i=e.top,o=e.height,a=t.top+t.height}catch{}let s=Math.max(a-i,20);return{sectionId:e.id,top:i,height:s,firstLineHeight:o,type:e.type,subtype:e.subtype,widgetName:e.widgetName}}),this.notify()}catch{}}notify(){if(typeof requestAnimationFrame==`function`){if(this.pendingNotify!==null)return;this.pendingNotify=requestAnimationFrame(()=>{this.pendingNotify=null;for(let e of this.listeners)e(this.rects,this.docVersion)})}else for(let e of this.listeners)e(this.rects,this.docVersion)}destroy(){this.pendingNotify!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(this.pendingNotify),this.listeners.clear()}},aE=Lr.fromClass(iE),oE=class extends xr{eq(e){return!0}toDOM(){let e=document.createElement(`div`);return e.className=`cm-wod-block-footer`,e}get estimatedHeight(){return 28}get block(){return!0}},sE=class extends xr{eq(e){return!0}toDOM(){let e=document.createElement(`div`);return e.className=`cm-wod-insert-spacer`,e}get estimatedHeight(){return 28}get block(){return!0}},cE=new oE,lE=new sE,uE=Ir.line({attributes:{class:`cm-wod-fence cm-wod-fence-open`}}),dE=Ir.line({attributes:{class:`cm-wod-fence cm-wod-fence-close`}}),fE=Ir.line({attributes:{class:`cm-wod-inner`}});function pE(e){let t=new pi,{sections:n}=e.field(NT),r=e.selection.main.head,i=e.doc.lineAt(r).number;for(let r of n){if(r.type!==`time`&&r.type!==`log`)continue;let n=i>r.startLine&&i<r.endLine,a=e.doc.line(r.startLine),o=e.doc.line(r.endLine);if(r.endLine<=r.startLine){t.add(a.from,a.from,uE);continue}t.add(a.from,a.from,uE);for(let a=r.startLine+1;a<r.endLine;a++){let r=e.doc.line(a);t.add(r.from,r.from,fE),n&&a===i&&t.add(r.to,r.to,Ir.widget({widget:lE,block:!0,side:1}))}n||t.add(o.from,o.from,Ir.widget({widget:cE,block:!0,side:-1})),t.add(o.from,o.from,dE)}return t.finish()}var mE=[ni.define({create(e){return pE(e)},update(e,t){return t.docChanged||t.selection?pE(t.state):e},provide:e=>Sr.decorations.from(e)}),Sr.baseTheme({".cm-wod-fence":{opacity:`0.5`,fontSize:`0.85em`,color:`hsl(var(--metric-time))`,paddingLeft:`8px`,paddingRight:`8px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`},".cm-wod-fence-open":{borderTop:`1px solid hsl(var(--border) / 0.5)`,borderRadius:`6px 6px 0 0`,paddingTop:`26px`,backgroundColor:`transparent`,backgroundImage:`linear-gradient(to bottom, transparent 27px, rgba(128, 128, 128, 0.05) 27px)`},".cm-wod-fence-close":{borderBottom:`1px solid hsl(var(--border) / 0.5)`,borderRadius:`0 0 6px 6px`},".cm-wod-inner":{paddingLeft:`8px`,paddingRight:`8px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`},".cm-wod-block-footer":{height:`28px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`,pointerEvents:`none`},".cm-wod-insert-spacer":{height:`28px`,backgroundColor:`rgba(128, 128, 128, 0.05)`,borderLeft:`1px solid hsl(var(--border) / 0.5)`,borderRight:`1px solid hsl(var(--border) / 0.5)`,boxSizing:`border-box`,pointerEvents:`none`}})],hE=class extends xr{height;constructor(e){super(),this.height=e}eq(e){return e.height===this.height}toDOM(){let e=document.createElement(`div`);return e.className=`cm-embed-spacer`,e.style.height=`${this.height}px`,e.style.pointerEvents=`none`,e}get estimatedHeight(){return this.height}get block(){return!0}};function gE(e){let t=new pi,{sections:n}=e.field(NT);for(let r of n)if(r.type===`embed`&&r.embed?.height){let n=e.doc.line(r.startLine);t.add(n.from,n.from,Ir.widget({widget:new hE(r.embed.height),side:1}))}return t.finish()}var _E=[ni.define({create(e){return gE(e)},update(e,t){return t.docChanged?gE(t.state):e},provide:e=>Sr.decorations.from(e)})];function vE(e,t,n,r,i=8){let a=Math.min(Math.max(e.width,192),320),o=Math.min(Math.max(n,0),256),s={top:e.bottom+i,bottom:e.bottom+i+o},c={top:e.top-i-o,bottom:e.top-i},l=s.bottom<=t.height,u=c.top>=0,d=(r&&s.bottom>r.top&&s.top<r.bottom||!l)&&u?`above`:`below`,f=d===`below`?s:c;return{left:Math.min(Math.max(i,e.left),Math.max(i,t.width-a-i)),top:Math.min(Math.max(i,f.top),Math.max(i,t.height-o-i)),width:a,placement:d}}var yE=0,bE=class{element;inputElement;onPick;avoid;listId;currentChoices=[];currentIndex=-1;isOpen=!1;constructor(e,t){this.inputElement=e,this.onPick=t.onPick,this.avoid=t.avoid,this.listId=`frontmatter-suggestions-${++yE}`;let n=document.createElement(`div`);n.id=this.listId,n.setAttribute(`role`,`listbox`),n.setAttribute(`aria-label`,t.label),n.tabIndex=-1,n.className=`fixed z-[60] max-h-64 overflow-auto rounded-md border border-border bg-popover text-popover-foreground shadow-md text-xs`,n.hidden=!0,this.element=n,document.body.appendChild(n),e.setAttribute(`role`,`combobox`),e.setAttribute(`aria-haspopup`,`listbox`),e.setAttribute(`aria-autocomplete`,`list`),e.setAttribute(`aria-controls`,this.listId),e.setAttribute(`aria-expanded`,`false`)}get choices(){return this.currentChoices}get activeIndex(){return this.currentIndex}setChoices(e){this.currentChoices=e,this.currentIndex=-1,this.inputElement.removeAttribute(`aria-activedescendant`),this.element.replaceChildren(),e.forEach((e,t)=>{let n=document.createElement(`div`);n.id=`${this.listId}-${t}`,n.setAttribute(`role`,`option`),n.setAttribute(`aria-selected`,`false`),n.className=`cursor-pointer px-2 py-1.5 hover:bg-muted`,n.textContent=e.label,n.addEventListener(`mousedown`,e=>e.preventDefault()),n.addEventListener(`click`,()=>this.pick(e)),this.element.appendChild(n)})}open(){this.isOpen||(this.isOpen=!0,this.element.hidden=!1,this.position(),this.inputElement.setAttribute(`aria-expanded`,`true`),window.addEventListener(`scroll`,this.handleViewportChange,!0),window.addEventListener(`resize`,this.handleViewportChange))}close(){this.isOpen&&(this.isOpen=!1,this.element.hidden=!0,this.currentIndex=-1,this.inputElement.setAttribute(`aria-expanded`,`false`),this.inputElement.removeAttribute(`aria-activedescendant`),window.removeEventListener(`scroll`,this.handleViewportChange,!0),window.removeEventListener(`resize`,this.handleViewportChange))}destroy(){this.close(),this.element.remove()}activate(e){this.currentIndex=e,Array.from(this.element.children).forEach((t,n)=>{t.setAttribute(`aria-selected`,String(n===e)),t.classList.toggle(`bg-muted`,n===e)});let t=this.element.children[e];t&&(this.inputElement.setAttribute(`aria-activedescendant`,t.id),t instanceof HTMLElement&&t.scrollIntoView?.({block:`nearest`}))}moveActive(e){if(this.currentChoices.length===0)return;let t=this.currentIndex<0?e>0?0:this.currentChoices.length-1:(this.currentIndex+e+this.currentChoices.length)%this.currentChoices.length;this.activate(t)}pickActive(){let e=this.currentChoices[this.currentIndex];e&&this.pick(e)}pick(e){this.inputElement.value=e.value,this.close(),this.onPick(e)}handleViewportChange=()=>{this.isOpen&&this.position()};position(){let e=this.inputElement.getBoundingClientRect(),t=(this.avoid?.()??null)?.getBoundingClientRect(),n=Math.min(this.element.scrollHeight,256),r=vE({top:e.top,bottom:e.bottom,left:e.left,width:e.width},{width:window.innerWidth,height:window.innerHeight},n,t?{top:t.top,bottom:t.bottom,left:t.left,right:t.right}:void 0);this.element.style.width=`${r.width}px`,this.element.style.maxHeight=`${n}px`,this.element.style.left=`${r.left}px`,this.element.style.top=`${r.top}px`,this.element.dataset.placement=r.placement}},xE=Ur.define({combine:e=>e[0]??null}),SE=Ur.define({combine:e=>e[0]??null}),CE=Kr.define(),wE=Ur.define({combine:e=>e[0]??!0}),TE=Kr.define(),EE=ni.define({create:()=>!1,update(e,t){for(let e of t.effects)if(e.is(TE))return e.value;return e}}),DE=Kr.define(),OE=ni.define({create:()=>!1,update(e,t){let n=e;for(let e of t.effects)e.is(DE)&&(n=e.value);if(n&&t.selection){let e=t.state.field(NT).sections.find(e=>e.type===`frontmatter`);(!e||!t.state.selection.ranges.some(t=>t.from<=e.to&&t.to>=e.from))&&(n=!1)}return n}}),kE=new WeakMap,AE=new WeakMap,jE=0,ME={tag:!0,tags:!0,category:!0,domain:!0,format:!0,equipment:!0,effort:!0,quality:!0,intent:!0,discipline:!0,intensity:!0,intensitytier:!0,sound:!0};function NE(e){return[`tag`,`tags`,`category`].includes(e.trim().toLowerCase())}function PE(e,t){let n=document.createElement(`span`);return n.id=`frontmatter-hint-${++jE}`,n.className=`sr-only`,n.textContent=t,e.appendChild(n),n}function FE(){let e=document.createElement(`div`);e.className=`flex items-center border-b border-border text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`;let t=document.createElement(`div`);t.dataset.frontmatterColumn=`key`,t.className=`px-3 py-1.5 w-36 shrink-0 border-r border-border max-[479px]:w-auto max-[479px]:border-r-0 max-[479px]:border-b`,t.textContent=`Key`;let n=document.createElement(`div`);n.dataset.frontmatterColumn=`value`,n.className=`px-3 py-1.5 flex-1 min-w-0`,n.textContent=`Value`;let r=document.createElement(`div`);return r.className=`w-9 shrink-0`,e.append(t,n,r),e}function IE(e,t){e.querySelector(`[data-frontmatter-column]`)||e.insertBefore(FE(),t)}function LE(e,t,n,r,i,a,o,s=`tags`){let c=t.state.facet(xE);if(!c||!e.parentElement)return;let l=new bE(e,{label:r===`key`?`Suggested properties`:RE(s),onPick:()=>o(),avoid:()=>n.querySelector(`[data-frontmatter-actions]`)}),u=0,d=()=>{u++,l.close()},f=async(t=!1)=>{d();let n=++u,o=t?``:e.value.trim().toLowerCase();try{let t=await c();if(n!==u||!e.isConnected||document.activeElement!==e)return;let d;d=r===`key`?t.types.map(e=>({value:e,label:e,haystack:e})):s===`effort`||s===`equipment`?(s===`effort`?t.efforts??[]:t.equipment??[]).map(e=>({value:e.slug,label:`${e.label} (${e.slug})`,haystack:[e.label,e.slug,...e.aliases].join(` `).toLowerCase()})):t.tags.filter(e=>NE(i)||e.type?.toLowerCase()===i.trim().toLowerCase()).map(e=>({value:e.label,label:e.label,haystack:e.label.toLowerCase()}));let f=new Set(a.map(e=>e.toLowerCase())),p=d.filter(e=>(o===``||e.haystack.includes(o))&&!f.has(e.value.toLowerCase())).map(e=>({value:e.value,label:e.label}));l.setChoices(p),p.length>0&&l.open()}catch{n===u&&d()}};e.addEventListener(`focus`,()=>void f(!0)),e.addEventListener(`input`,()=>void f(!1)),e.addEventListener(`blur`,d),e.addEventListener(`keydown`,e=>{if(e.ctrlKey&&(e.code===`Space`||e.key===` `))e.preventDefault(),f(!0);else if(e.key===`Escape`)e.preventDefault(),d();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(l.choices.length===0)return;e.preventDefault(),l.moveActive(e.key===`ArrowDown`?1:-1)}else if(e.key===`Enter`||e.key===`Tab`){if(l.activeIndex<0)return;e.preventDefault(),l.pickActive()}}),AE.get(n)?.push(()=>l.destroy())}function RE(e){return e===`effort`?`Suggested efforts`:e===`equipment`?`Suggested equipment`:`Suggested tags`}function zE(e){if(Array.isArray(e))return e.map(String).map(e=>e.trim()).filter(Boolean);if(typeof e==`string`&&e.trim()){let t=e.trim();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^['"]|['"]$/g,``)).filter(Boolean):[t.replace(/^['"]|['"]$/g,``)]}return[]}function BE(e,t,n,r,i=!1){if(e.state.readOnly)return;let a=e.state.doc.toString(),o=Ja(a,n,r);if(o===a){i&&e.dispatch({effects:TE.of(!0)});return}e.dispatch({changes:{from:0,to:a.length,insert:o},...i?{effects:TE.of(!0)}:{}})}function VE(e,t,n,r,i){if(e.state.readOnly)return;let a=e.state.doc.toString(),o=Ja(Ja(a,[r],i),[n],null);o!==a&&e.dispatch({changes:{from:0,to:a.length,insert:o}})}function HE(e){let t=typeof e.type==`string`?e.type.trim().toLowerCase():``;return t===`effort`?`effort`:t===`equipment`?`equipment`:e.registrySource!==void 0||e.baseAttributes!==void 0?`effort`:null}function UE(e,t={}){let n={};t[`metrics.met`]!==void 0&&!Array.isArray(t[`metrics.met`])&&(n.met=String(t[`metrics.met`])),t.discipline!==void 0&&!Array.isArray(t.discipline)&&(n.discipline=String(t.discipline)),t.intensityTier!==void 0&&!Array.isArray(t.intensityTier)&&(n.intensityTier=String(t.intensityTier));let r=!1;for(let t of e.split(/\r?\n/)){if(/^baseAttributes:\s*(#.*)?$/.test(t)){r=!0,n.hasBaseBlock=!0;continue}if(!r)continue;if(/^\S/.test(t))break;let e=t.match(/^\s+([\w-]+):\s*(.*)$/);e&&(e[1]===`met`||e[1]===`discipline`||e[1]===`intensityTier`)&&(n[e[1]]=WE(e[2].trim()))}return n}function WE(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1).replace(/\\(["\\])/g,`$1`):e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1).replace(/\\'/g,`'`):e}function GE(e,t){let n=e.trim().toLowerCase();return n===`metrics.effort`?`effort`:n===`metrics.equipment`||n===`equipment`||n===`aliases`&&t===`equipment`?`equipment`:n===`aliases`&&t===`effort`?`effort`:`tags`}function KE(e,t){let n=e.trim().toLowerCase();return n===`metrics.effort`||n===`metrics.equipment`||n===`equipment`&&t===`effort`}function qE(e,t,n,r){let i=document.createElement(`div`);i.className=`flex items-center min-h-[34px] border-b border-dashed border-border last:border-b-0 group hover:bg-muted/10 transition-colors max-[479px]:flex-col max-[479px]:items-stretch`,i.setAttribute(`data-frontmatter-tag-draft`,`true`),i.dataset.frontmatterRow=n;let a=document.createElement(`div`);a.className=`flex items-center gap-2 px-3 py-1.5 w-36 shrink-0 border-r border-dashed border-border text-muted-foreground max-[479px]:w-auto max-[479px]:border-r-0 max-[479px]:border-b`,a.appendChild($E());let o=document.createElement(`span`);o.className=`truncate font-medium text-foreground/90`,o.textContent=n,a.appendChild(o),i.appendChild(a);let s=document.createElement(`div`);s.className=`flex items-center flex-wrap gap-1.5 px-3 py-1.5 flex-1 min-w-0`;let c=document.createElement(`input`);c.className=`flex-none w-44 max-w-full rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring`,c.placeholder=`Add tag…`,c.setAttribute(`aria-label`,`Value for ${n}`),c.dataset.frontmatterField=`value`,c.dataset.frontmatterProperty=n,c.setAttribute(`aria-describedby`,PE(s,`Press Enter to add the value.`).id),s.appendChild(c),i.appendChild(s);let l=!1,u=t=>{if(!l){if(l=!0,t){let e=c.value.trim().replace(/^,|,$/g,``);e&&r(e)}i.remove(),e.requestMeasure()}},d=()=>u(!0),f=()=>u(!1);return LE(c,e,t,`value`,n,[],d),c.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),f();return}e.defaultPrevented||(e.key===`Enter`||e.key===`,`)&&(e.preventDefault(),d())}),c.addEventListener(`blur`,()=>queueMicrotask(()=>{c.isConnected&&(c.value.trim()?d():f())})),i}function JE(e,t){let n=e.split(/\r?\n/);for(let e=0;e<n.length;e++)if(RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}:\\s*$`).test(n[e]))return e+1<n.length&&/^\s+\S/.test(n[e+1]);return!1}function YE(e,t,n){let r=t.trim();if(!r||e.resolveEffort(r))return null;let i=e.resolve(r).diagnostics,a=document.createElement(`div`);a.setAttribute(`data-testid`,`editor-ref-unknown`),a.className=`w-full basis-full flex flex-wrap items-center gap-2 text-[10px] text-destructive`;let o=document.createElement(`span`);o.textContent=i[0]?.message||`Unknown effort: ${r}`,a.appendChild(o);for(let e of i[0]?.candidates??[]){let t=document.createElement(`button`);t.type=`button`,t.textContent=`Use ${e}`,t.className=`underline hover:text-foreground cursor-pointer`,t.addEventListener(`click`,t=>{t.preventDefault(),n(e)}),a.appendChild(t)}let s=document.createElement(`a`);return s.href=e.createHref(`effort`),s.textContent=`Create page`,s.className=`underline hover:text-foreground`,a.appendChild(s),a}var XE={effort:{label:`Effort`,path:`metrics.effort`,kind:`effort`},equipment:{label:`Equipment`,path:`metrics.equipment`,kind:`equipment`},rpe:{label:`RPE`,path:`metrics.rpe`,kind:`number`},custom:{label:`Custom / Equation`,path:`metrics.`,kind:`custom`}};function ZE(e,t,n,r){let i=document.createElement(`div`);i.className=`flex items-center min-h-[34px] border-b border-dashed border-border last:border-b-0 group hover:bg-muted/10 transition-colors max-[479px]:flex-col max-[479px]:items-stretch`,i.setAttribute(`data-frontmatter-metric-draft`,`true`),i.dataset.frontmatterRow=`metric`;let a=document.createElement(`select`);a.setAttribute(`aria-label`,`Metric kind`),a.className=`mx-3 my-1.5 h-7 w-28 shrink-0 rounded-md border border-input bg-background px-1.5 text-[11px] text-muted-foreground outline-none`;for(let[e,t]of Object.entries(XE)){let n=document.createElement(`option`);n.value=e,n.textContent=t.label,a.appendChild(n)}i.appendChild(a);let o=document.createElement(`div`);o.className=`flex items-center flex-wrap gap-1.5 px-3 py-1.5 flex-1 min-w-0`;let s=null,c=document.createElement(`input`);c.className=`flex-none w-44 max-w-full rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring`,c.placeholder=`Value…`,c.setAttribute(`aria-label`,`Metric value`),c.dataset.frontmatterField=`value`,c.setAttribute(`aria-describedby`,PE(o,`Press Enter to apply the metric value.`).id),o.appendChild(c),i.appendChild(o);let l=!1,u=t=>{if(l)return;l=!0;let n=XE[a.value],o=c.value.trim();if(t&&n&&o){if(n.kind===`equipment`)r([n.path],[o]);else if(n.kind===`number`){let e=Number(o);Number.isNaN(e)||r([n.path],e)}else if(n.kind===`custom`){let e=(s?.value.trim()||`custom`).replace(/^metrics\./i,``),t=Number(o);r([`metrics.${e}`],!Number.isNaN(t)&&o!==``?t:o)}else r([n.path],o)}i.remove(),e.requestMeasure()},d=()=>{let r=XE[a.value];r?.kind===`custom`?(s||(s=document.createElement(`input`),s.className=`flex-none w-32 max-w-full rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring`,s.placeholder=`Metric key…`,s.setAttribute(`aria-label`,`Metric key`),s.dataset.frontmatterField=`key`,s.addEventListener(`keydown`,e=>{e.key===`Escape`?(e.preventDefault(),u(!1)):e.key===`Enter`&&(e.preventDefault(),c.value.trim()?u(!0):c.focus())}),o.insertBefore(s,c)),c.placeholder=`Value or equation…`):s&&(s.remove(),s=null,c.placeholder=`Value…`),r&&(r.kind===`effort`||r.kind===`equipment`)&&n&&LE(c,e,t,`value`,r.path,[],()=>u(!0),r.kind)};return d(),a.addEventListener(`change`,d),c.addEventListener(`keydown`,e=>{if(!(e.defaultPrevented&&e.key!==`Escape`)){if(e.key===`Escape`){e.preventDefault(),u(!1);return}e.key===`Enter`&&(e.preventDefault(),u(!0))}}),c.addEventListener(`blur`,()=>queueMicrotask(()=>{c.isConnected&&(i.contains(document.activeElement)||u(c.value.trim().length>0))})),a.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),u(!1))}),i}function QE(e,t){let n=document.createElement(`div`);n.className=`flex items-center min-h-[34px] border-b border-dashed border-border last:border-b-0 group hover:bg-muted/10 transition-colors max-[479px]:flex-col max-[479px]:items-stretch`,n.setAttribute(`data-frontmatter-summary-draft`,`true`),n.dataset.frontmatterRow=`summary`;let r=document.createElement(`div`);r.className=`flex items-center gap-2 px-3 py-1.5 w-36 shrink-0 border-r border-dashed border-border text-muted-foreground max-[479px]:w-auto max-[479px]:border-r-0 max-[479px]:border-b`,r.appendChild(eD());let i=document.createElement(`input`);i.className=`w-full rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring`,i.placeholder=`Summary key…`,i.setAttribute(`aria-label`,`Summary key`),i.dataset.frontmatterField=`key`,i.setAttribute(`aria-describedby`,PE(r,`Summary metric name. Press Enter to move to the equation.`).id),r.appendChild(i),n.appendChild(r);let a=document.createElement(`div`);a.className=`flex items-center flex-wrap gap-1.5 px-3 py-1.5 flex-1 min-w-0`;let o=document.createElement(`input`);o.className=`flex-1 min-w-[160px] rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring`,o.placeholder=`Equation (e.g. sum(work))…`,o.setAttribute(`aria-label`,`Summary equation`),o.dataset.frontmatterField=`value`,o.setAttribute(`aria-describedby`,PE(a,`Summary equation. Press Enter to apply.`).id),a.appendChild(o),n.appendChild(a);let s=!1,c=r=>{if(s)return;s=!0;let a=(i.value.trim()||`summary`).replace(/^summaries\./i,``),c=o.value.trim();r&&c&&t([`summaries.${a}`],c),n.remove(),e.requestMeasure()};i.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),c(!1);return}e.key===`Enter`&&(e.preventDefault(),o.value.trim()?c(!0):o.focus())}),o.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),c(!1);return}e.key===`Enter`&&(e.preventDefault(),c(!0))});let l=()=>queueMicrotask(()=>{n.isConnected&&(n.contains(document.activeElement)||c(o.value.trim().length>0))});return i.addEventListener(`blur`,l),o.addEventListener(`blur`,l),n}function $E(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`shrink-0 h-3.5 w-3.5 text-muted-foreground/70`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,`M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);return n.setAttribute(`cx`,`7`),n.setAttribute(`cy`,`7`),n.setAttribute(`r`,`.5`),n.setAttribute(`fill`,`currentColor`),e.appendChild(n),e}function eD(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`shrink-0 h-3.5 w-3.5 text-muted-foreground/70`);for(let t of[`6`,`12`,`18`]){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`4`),n.setAttribute(`x2`,`20`),n.setAttribute(`y1`,t),n.setAttribute(`y2`,t),e.appendChild(n)}return e}function tD(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`shrink-0 h-3 w-3`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);t.setAttribute(`x1`,`12`),t.setAttribute(`x2`,`12`),t.setAttribute(`y1`,`5`),t.setAttribute(`y2`,`19`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);return n.setAttribute(`x1`,`5`),n.setAttribute(`x2`,`19`),n.setAttribute(`y1`,`12`),n.setAttribute(`y2`,`12`),e.appendChild(n),e}function nD(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`h-3 w-3`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,`M15 3h6v6`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`10`),n.setAttribute(`x2`,`21`),n.setAttribute(`y1`,`14`),n.setAttribute(`y2`,`3`),e.appendChild(n);let r=document.createElementNS(`http://www.w3.org/2000/svg`,`polyline`);return r.setAttribute(`points`,`21 14 21 3 10 3`),e.appendChild(r),e}function rD(e=`md`){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,e===`sm`?`2.5`:`2`),t.setAttribute(`stroke-linecap`,`round`),t.setAttribute(`stroke-linejoin`,`round`),t.setAttribute(`class`,e===`sm`?`h-2.5 w-2.5`:`h-3.5 w-3.5`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`18`),n.setAttribute(`x2`,`6`),n.setAttribute(`y1`,`6`),n.setAttribute(`y2`,`18`),t.appendChild(n);let r=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);return r.setAttribute(`x1`,`6`),r.setAttribute(`x2`,`18`),r.setAttribute(`y1`,`6`),r.setAttribute(`y2`,`18`),t.appendChild(r),t}function iD(e){return[`alias`,`aliases`].includes(e.trim().toLowerCase())}function aD(e,t){let n=document.createElement(`span`);n.className=`inline-flex max-w-full items-center rounded-md border border-border/60 bg-muted/40 px-2 py-0.5 text-xs text-foreground`;let r=document.createElement(`span`);return r.className=`truncate`,r.textContent=t?`#${e}`:e,n.appendChild(r),n}function oD(e,t){let n=document.createElement(`div`);n.dataset.frontmatterSummary=`true`,n.className=`divide-y divide-border/60`;let r=[{label:`Tags`,entries:e.filter(([e])=>ME[e.trim().toLowerCase()]===!0),hash:!0},{label:`Aliases`,entries:e.filter(([e])=>iD(e)),hash:!1}];for(let e of r){let t=e.entries.flatMap(([,e])=>zE(e));if(t.length===0)continue;let r=document.createElement(`div`);r.className=`flex flex-wrap items-center gap-1.5 px-3 py-2`;let i=document.createElement(`span`);i.className=`mr-1 w-14 shrink-0 text-[11px] font-medium text-muted-foreground`,i.textContent=e.label,r.appendChild(i);for(let n of t)r.appendChild(aD(n,e.hash));n.appendChild(r)}let i=e.filter(([e])=>ME[e.trim().toLowerCase()]!==!0&&!iD(e)),a=i.filter(([e])=>{let t=e.trim().toLowerCase();return t.startsWith(`metrics.`)||t===`metrics`}).length,o=i.filter(([e])=>{let t=e.trim().toLowerCase();return t.startsWith(`summaries.`)||t===`summaries`}).length,s=document.createElement(`button`);s.type=`button`,s.setAttribute(`aria-label`,`Show property details`),s.setAttribute(`aria-expanded`,`false`),s.className=`flex w-full flex-wrap items-center gap-x-2 gap-y-1 px-3 py-2 text-left text-[11px] text-muted-foreground transition-colors hover:bg-muted/20 hover:text-foreground cursor-pointer`;let c=document.createElement(`span`);if(c.textContent=`${i.length} more ${i.length===1?`property`:`properties`}`,s.appendChild(c),a>0){let e=document.createElement(`span`);e.textContent=`· ${a} custom ${a===1?`metric`:`metrics`}`,s.appendChild(e)}if(o>0){let e=document.createElement(`span`);e.textContent=`· ${o} ${o===1?`summary`:`summaries`}`,s.appendChild(e)}let l=document.createElement(`span`);return l.className=`ml-auto`,l.setAttribute(`aria-hidden`,`true`),l.textContent=`▾`,s.appendChild(l),s.addEventListener(`click`,t),n.appendChild(s),n}var sD=class extends xr{sectionId;rawContent;readOnly;detailed;constructor(e,t,n=!1,r=!1){super(),this.sectionId=e,this.rawContent=t??``,this.readOnly=n,this.detailed=r}eq(e){return this.sectionId===e.sectionId&&this.rawContent===e.rawContent&&this.readOnly===e.readOnly&&this.detailed===e.detailed}ignoreEvent(){return!0}toDOM(e){let t=document.createElement(`div`);AE.set(t,[]),t.className=`cm-frontmatter-preview py-2 font-sans select-none`;let n=document.createElement(`div`);n.className=`mb-1.5 flex items-center px-0.5 text-xs font-medium text-muted-foreground`;let r=document.createElement(`span`);if(r.textContent=`Properties`,n.appendChild(r),this.detailed){let t=document.createElement(`button`);t.type=`button`,t.setAttribute(`aria-label`,`Show property summary`),t.setAttribute(`aria-expanded`,`true`),t.className=`ml-auto px-1 py-0.5 text-[11px] font-normal hover:text-foreground cursor-pointer`,t.textContent=`Hide details ▴`,t.addEventListener(`click`,()=>{e.dispatch({effects:TE.of(!1)})}),n.appendChild(t)}t.appendChild(n);let i=document.createElement(`div`);i.dataset.frontmatterProperties=`true`,i.className=`rounded-lg border border-border/80 bg-background/50 text-xs shadow-xs`,t.appendChild(i);let a=this.rawContent.replace(/^---\r?\n?/,``).replace(/\r?\n?---\r?$/,``),o=mv(a),s=Object.entries(o),c=HE(o),l=e.state.facet(SE)?.()??null,u=c===`effort`?UE(a,o):{};if(!this.detailed)i.appendChild(oD(s,()=>{e.dispatch({effects:TE.of(!0)})}));else{if(i.appendChild(FE()),s.length===0){let e=document.createElement(`div`);e.className=`px-3 py-2 text-xs text-muted-foreground/60 italic`,e.textContent=`No properties`,i.appendChild(e)}for(let[n,r]of s){let u=NE(n),d=GE(n,c),f=(KE(n,c)||n===`aliases`)&&Array.isArray(r),p=r===``&&JE(a,n),m=document.createElement(`div`);m.className=`flex items-center min-h-[34px] border-b border-dashed border-border last:border-b-0 group hover:bg-muted/10 transition-colors max-[479px]:flex-col max-[479px]:items-stretch`,m.dataset.frontmatterRow=n,i.appendChild(m);let h=document.createElement(`div`);if(h.className=`flex items-center gap-2 px-3 py-1.5 w-36 shrink-0 border-r border-dashed border-border text-muted-foreground max-[479px]:w-auto max-[479px]:border-r-0 max-[479px]:border-b`,m.appendChild(h),h.appendChild(u||f?$E():eD()),this.readOnly||p){let e=document.createElement(`span`);e.className=`truncate font-medium text-foreground/90`,e.textContent=n,h.appendChild(e)}else{let i=document.createElement(`input`);i.className=`w-full bg-transparent text-xs text-foreground/90 font-medium outline-none truncate hover:bg-muted/30 focus:bg-background focus:ring-1 focus:ring-ring rounded px-1 -mx-1`,i.value=n,i.spellcheck=!1,i.setAttribute(`aria-label`,`Property key: ${n}`),i.dataset.frontmatterField=`key`,i.dataset.frontmatterProperty=n,i.setAttribute(`aria-describedby`,PE(h,`Property name. Press Enter to apply. Arrow keys browse suggested property names.`).id);let a=n,c=()=>{let t=i.value.trim();if(!t||t===a){i.value=a;return}if(!/^[A-Za-z_][\w.-]*$/.test(t)||t in o){i.value=a;return}VE(e,this.sectionId,a,t,r),delete o[a],o[t]=r,a=t},l=()=>queueMicrotask(()=>{i.isConnected&&c()});i.addEventListener(`change`,l),h.appendChild(i),LE(i,e,t,`key`,n,s.map(([e])=>e),c),i.addEventListener(`blur`,l),i.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Enter`&&(e.preventDefault(),i.blur())});let u=kE.get(e);u?.kind===`key`&&u.key===n&&(setTimeout(()=>{i.isConnected&&(i.focus(),i.select())},0),kE.delete(e))}let g=document.createElement(`div`);g.className=`flex items-center flex-wrap gap-1.5 px-3 py-1.5 flex-1 min-w-0`,m.appendChild(g);let _=t=>{o[n]=t,BE(e,this.sectionId,[n],t.length>0?t:``)},v=e=>l?d===`effort`?l.resolveEffort(e):d===`equipment`?l.resolveEquipment(e):null:null;if(u||f){let i=zE(r),a=d!==`tags`,o=iD(n);for(let e=0;e<i.length;e++){let t=i[e],n=a?v(t):null,r=document.createElement(`span`);r.className=n?`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-muted/60 text-foreground border border-border/60`:a?`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-destructive/10 text-destructive border border-destructive/30`:`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-amber-500/10 text-amber-800 dark:text-amber-300 border border-amber-500/20 dark:border-amber-500/30`;let s=document.createElement(`span`);if(s.textContent=o?t:n?n.label:t,r.appendChild(s),n&&l){let e=document.createElement(`a`);e.href=l.openHref(d,n.slug),e.title=`Open ${n.label} page`,e.setAttribute(`aria-label`,`Open ${n.label} page`),e.className=`inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground cursor-pointer`,e.appendChild(nD()),r.appendChild(e)}if(!this.readOnly){let n=document.createElement(`button`);n.type=`button`,n.setAttribute(`aria-label`,u?`Remove tag ${t}`:`Remove ${t}`),n.className=`inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground dark:hover:text-foreground cursor-pointer`,n.appendChild(rD(`sm`)),n.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),_(i.filter((t,n)=>n!==e))}),r.appendChild(n)}g.appendChild(r)}if(!this.readOnly){let r=document.createElement(`input`);r.className=`flex-none w-44 max-w-full rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring`,r.placeholder=i.length===0?f?`Add ${d===`effort`?`effort`:`equipment`}…`:`Add tags…`:u?`Add tag…`:`Add…`,r.setAttribute(`aria-label`,`Value for ${n}`),r.dataset.frontmatterField=`value`,r.dataset.frontmatterProperty=n,r.setAttribute(`aria-describedby`,PE(g,`Press Enter or comma to add a value. Arrow keys browse the suggestions.`).id);let o=()=>{let t=r.value.trim().replace(/^,|,$/g,``);t&&!i.some(e=>e.toLowerCase()===t.toLowerCase())&&(r.value=``,kE.set(e,{kind:`tag`,key:n}),_([...i,t]))};g.appendChild(r),LE(r,e,t,`value`,n,i,o,d),r.addEventListener(`keydown`,t=>{t.defaultPrevented||(t.key===`Enter`||t.key===`,`?(t.preventDefault(),o()):t.key===`Backspace`&&!r.value&&i.length>0&&(t.preventDefault(),kE.set(e,{kind:`tag`,key:n}),_(i.slice(0,-1))))}),r.addEventListener(`blur`,()=>queueMicrotask(()=>{r.isConnected&&r.value.trim()&&o()}));let s=kE.get(e);if(s?.kind===`tag`&&s.key===n&&(setTimeout(()=>{r.isConnected&&r.focus()},0),kE.delete(e)),a&&l){let e=i.filter(e=>!v(e));if(e.length>0){let t=document.createElement(`div`);t.setAttribute(`data-testid`,`editor-ref-unknown`),t.className=`w-full basis-full flex flex-wrap items-center gap-2 text-[10px] text-destructive`;let n=document.createElement(`span`);n.textContent=`Unknown ${d===`effort`?`effort`:`equipment`}: ${e.join(`, `)}`,t.appendChild(n);let i=document.createElement(`button`);i.type=`button`,i.textContent=`Select existing`,i.className=`underline hover:text-foreground cursor-pointer`,i.addEventListener(`click`,e=>{e.preventDefault(),r.focus()}),t.appendChild(i);let a=document.createElement(`a`);a.href=l.createHref(d),a.textContent=`Create page`,a.className=`underline hover:text-foreground`,t.appendChild(a),g.appendChild(t)}}}}else if(p){let e=document.createElement(`span`);e.className=`text-xs text-muted-foreground/60 italic py-0.5 truncate`,e.textContent=`Nested block — edit in YAML`,g.appendChild(e)}else{let i=Array.isArray(r)?r.join(`, `):String(r??``);if(this.readOnly){let e=document.createElement(`span`);e.className=`text-xs text-foreground py-0.5 truncate`,e.textContent=i,g.appendChild(e)}else{let r=document.createElement(`input`);r.className=`w-full rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring transition-colors`,r.value=i,r.spellcheck=!1,r.setAttribute(`aria-label`,`Value for ${n}`),r.dataset.frontmatterField=`value`,r.dataset.frontmatterProperty=n,r.setAttribute(`aria-describedby`,PE(g,`Property value. Press Enter to apply.`).id);let a=i,s=()=>{let t=r.value.trim();if(t!==a){a=t;let r=Number(t),i=t!==``&&!isNaN(r)?r:t;o[n]=i,BE(e,this.sectionId,[n],i)}},c=()=>queueMicrotask(()=>{r.isConnected&&s()});if(r.addEventListener(`change`,c),g.appendChild(r),LE(r,e,t,`value`,n,[i],s,n.trim().toLowerCase()===`metrics.effort`?`effort`:`tags`),r.addEventListener(`blur`,c),r.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Enter`&&(e.preventDefault(),r.blur())}),n.trim().toLowerCase()===`metrics.effort`&&l){let t=l.resolveEffort(i);if(t){let e=document.createElement(`span`);e.className=`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs font-medium bg-muted/60 text-foreground border border-border/60 shrink-0`;let n=document.createElement(`span`);n.textContent=t.label,e.appendChild(n);let i=document.createElement(`a`);i.href=l.openHref(`effort`,t.slug),i.title=`Open ${t.label} page`,i.setAttribute(`aria-label`,`Open ${t.label} page`),i.className=`inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground cursor-pointer`,i.appendChild(nD()),e.appendChild(i),g.insertBefore(e,r),r.className=`flex-1 min-w-[70px] rounded-md border border-field-border bg-background/60 px-2 py-1 text-xs text-foreground outline-none placeholder:text-field-placeholder focus:border-ring focus:ring-1 focus:ring-ring transition-colors`}let a=YE(l,i,t=>{o[n]=t,BE(e,this.sectionId,[n],t)});a&&g.appendChild(a)}}if(/^https?:\/\/\S+$/i.test(i)){let e=document.createElement(`a`);e.href=i,e.target=`_blank`,e.rel=`noopener noreferrer`,e.title=i,e.setAttribute(`aria-label`,`Open ${n} in new tab`),e.className=`shrink-0 inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground transition-colors cursor-pointer`,e.appendChild(nD()),g.appendChild(e)}}if(!this.readOnly&&!p){let t=document.createElement(`div`);t.className=`flex items-center pr-2`;let r=document.createElement(`button`);r.type=`button`,r.setAttribute(`aria-label`,`Remove property ${n}`),r.className=`opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-muted-foreground/70 hover:text-destructive p-1 rounded transition-opacity cursor-pointer`,r.appendChild(rD(`md`)),r.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),delete o[n],BE(e,this.sectionId,[n],null)}),t.appendChild(r),m.appendChild(t)}}c===`effort`&&!this.readOnly&&i.appendChild(this.buildDefinitionRows(e,u))}if(!this.readOnly){let n=s.find(([e])=>e.trim().toLowerCase()===`tags`)?.[0]??s.find(([e])=>NE(e))?.[0],r=document.createElement(`div`);r.className=`mt-2 flex flex-wrap items-center gap-x-3 gap-y-1`,r.dataset.frontmatterActions=`true`;let a=document.createElement(`button`);a.type=`button`,a.setAttribute(`aria-label`,`Add property`),a.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,a.appendChild(tD());let c=document.createElement(`span`);c.textContent=`Add property`,a.appendChild(c),a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation();let n=`property`,r=1;for(;n in o;)r++,n=`property_${r}`;kE.set(e,{kind:`key`,key:n}),BE(e,this.sectionId,[n],``,!this.detailed);let i=e.dom.querySelector(`[data-frontmatter-row="${n}"] [data-frontmatter-field="key"]`);i?.focus(),i?.select()}),r.appendChild(a);{let n=document.createElement(`button`);n.type=`button`,n.setAttribute(`aria-label`,`Add metric`),n.setAttribute(`data-testid`,`editor-add-metric-note`),n.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,n.appendChild(tD());let a=document.createElement(`span`);a.textContent=`Add metric`,n.appendChild(a),n.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),this.detailed||e.dispatch({effects:TE.of(!0)});let r=e.dom.querySelector(`.cm-frontmatter-preview`)??t,a=r.querySelector(`[data-frontmatter-properties]`)??i,o=r.querySelector(`[data-frontmatter-metric-draft] input`);if(o){o.focus();return}let s=ZE(e,r,l,(t,n)=>{BE(e,this.sectionId,t,n)});a.appendChild(s),s.querySelector(`input`)?.focus(),e.requestMeasure()}),r.appendChild(n)}{let n=document.createElement(`button`);n.type=`button`,n.setAttribute(`aria-label`,`Add summary`),n.setAttribute(`data-testid`,`editor-add-summary-note`),n.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,n.appendChild(tD());let a=document.createElement(`span`);a.textContent=`Add summary`,n.appendChild(a),n.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),this.detailed||e.dispatch({effects:TE.of(!0)});let r=e.dom.querySelector(`.cm-frontmatter-preview`)??t,a=r.querySelector(`[data-frontmatter-properties]`)??i,o=r.querySelector(`[data-frontmatter-summary-draft] input`);if(o){o.focus();return}let s=QE(e,(t,n)=>{BE(e,this.sectionId,t,n)});a.appendChild(s),s.querySelector(`input`)?.focus(),e.requestMeasure()}),r.appendChild(n)}{let a=document.createElement(`button`);a.type=`button`,a.setAttribute(`aria-label`,`Add tag`),a.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,a.appendChild(tD());let o=document.createElement(`span`);o.textContent=`Add tag`,a.appendChild(o),a.addEventListener(`click`,r=>{r.preventDefault(),r.stopPropagation(),this.detailed||e.dispatch({effects:TE.of(!0)});let a=e.dom.querySelector(`.cm-frontmatter-preview`)??t,o=a.querySelector(`[data-frontmatter-properties]`)??i;if(n){Array.from(a.querySelectorAll(`[data-frontmatter-field="value"]`)).find(e=>e.dataset.frontmatterProperty===n)?.focus();return}let s=a.querySelector(`[data-frontmatter-tag-draft] input`);if(s){s.focus();return}let c=qE(e,a,`category`,t=>{kE.set(e,{kind:`tag`,key:`category`}),BE(e,this.sectionId,[`category`],[t])});o.appendChild(c),c.querySelector(`input`)?.focus(),e.requestMeasure()}),r.appendChild(a)}{let t=document.createElement(`button`);t.type=`button`,t.setAttribute(`aria-label`,`Edit YAML`),t.setAttribute(`data-testid`,`editor-property-edit-yaml`),t.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`;let n=document.createElement(`span`);n.textContent=`Edit YAML`,t.appendChild(n),t.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation();let{sections:n}=e.state.field(NT),r=n.find(e=>e.id===this.sectionId&&e.type===`frontmatter`)||n.find(e=>e.type===`frontmatter`);r&&(e.dispatch({selection:{anchor:r.from},effects:DE.of(!0),scrollIntoView:!0}),e.focus())}),r.appendChild(t)}t.appendChild(r)}return t}buildDefinitionRows(e,t){let n=document.createElement(`div`);n.setAttribute(`data-frontmatter-definition`,`true`),n.className=`border-t border-dashed border-border/60`;let r=document.createElement(`div`);r.className=`px-3 pt-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground`,r.textContent=`Definition`,n.appendChild(r);let i=(n,r)=>{if(n===`met`){let n=Number(r),i=t.hasBaseBlock?[`baseAttributes`,`met`]:[`metrics.met`];BE(e,this.sectionId,i,r!==``&&!Number.isNaN(n)?n:null);return}let i=t.hasBaseBlock?[`baseAttributes`,n]:[n];BE(e,this.sectionId,i,r===``?null:r)},a=(e,t)=>{let r=document.createElement(`label`);r.className=`flex items-center gap-2 px-3 py-1.5 min-h-[34px] border-b border-dashed border-border/60 last:border-b-0 max-[479px]:flex-col max-[479px]:items-stretch`;let i=document.createElement(`span`);i.className=`w-28 shrink-0 text-muted-foreground`,i.textContent=e,r.appendChild(i),t.className=`flex-1 min-w-0 bg-transparent text-xs text-foreground outline-none py-0.5`,r.appendChild(t),n.appendChild(r)},o=document.createElement(`input`);o.type=`number`,o.step=`0.1`,o.inputMode=`decimal`,o.value=t.met??``,o.setAttribute(`aria-label`,`MET value`),o.addEventListener(`change`,()=>queueMicrotask(()=>{o.isConnected&&i(`met`,o.value.trim())})),a(`MET`,o);let s=document.createElement(`select`);s.setAttribute(`aria-label`,`Discipline`),s.className=`flex-1 min-w-0 rounded-md border border-input bg-background px-1.5 text-[11px] text-muted-foreground outline-none`;let c=document.createElement(`option`);c.value=``,c.textContent=`Unset`,s.appendChild(c);for(let e of zc){let t=document.createElement(`option`);t.value=e,t.textContent=e,s.appendChild(t)}s.value=t.discipline??``,s.addEventListener(`change`,()=>i(`discipline`,s.value)),a(`Discipline`,s);let l=document.createElement(`select`);l.setAttribute(`aria-label`,`Intensity tier`),l.className=`flex-1 min-w-0 rounded-md border border-input bg-background px-1.5 text-[11px] text-muted-foreground outline-none`;let u=document.createElement(`option`);u.value=``,u.textContent=`Unset`,l.appendChild(u);for(let e of[`low`,`moderate`,`high`]){let t=document.createElement(`option`);t.value=e,t.textContent=e,l.appendChild(t)}return l.value=t.intensityTier??``,l.addEventListener(`change`,()=>i(`intensityTier`,l.value)),a(`Intensity tier`,l),n}destroy(e){AE.get(e)?.forEach(e=>e()),AE.delete(e)}},cD=class extends xr{detailed;constructor(e=!1){super(),this.detailed=e}eq(e){return this.detailed===e.detailed}ignoreEvent(){return!0}toDOM(e){let t=document.createElement(`div`);t.className=`cm-frontmatter-preview py-2 font-sans select-none`;let n=document.createElement(`div`);n.className=`text-xs font-medium text-muted-foreground mb-1.5 px-0.5`,n.textContent=`Properties`,t.appendChild(n);let r=document.createElement(`div`);r.className=`flex flex-wrap items-center gap-x-3 gap-y-1`,r.dataset.frontmatterActions=`true`;let i=document.createElement(`button`);i.type=`button`,i.setAttribute(`aria-label`,`Add property`),i.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,i.appendChild(tD());let a=document.createElement(`span`);a.textContent=`Add property`,i.appendChild(a),i.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),kE.set(e,{kind:`key`,key:`property`}),BE(e,`new`,[`property`],``,!0);let n=e.dom.querySelector(`[data-frontmatter-row="property"] [data-frontmatter-field="key"]`);n?.focus(),n?.select()}),r.appendChild(i);let o=document.createElement(`button`);o.type=`button`,o.setAttribute(`aria-label`,`Add metric`),o.setAttribute(`data-testid`,`editor-add-metric-note`),o.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,o.appendChild(tD());let s=document.createElement(`span`);s.textContent=`Add metric`,o.appendChild(s),o.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),this.detailed||e.dispatch({effects:TE.of(!0)});let r=e.dom.querySelector(`.cm-frontmatter-preview`)??t,i=r.querySelector(`[data-frontmatter-metric-draft] input`);if(i){i.focus();return}let a=ZE(e,r,e.state.facet(SE)?.()??null,(t,n)=>{BE(e,`new`,t,n,!0)});r.appendChild(a),IE(r,a),a.querySelector(`input`)?.focus(),e.requestMeasure()}),r.appendChild(o);let c=document.createElement(`button`);c.type=`button`,c.setAttribute(`aria-label`,`Add summary`),c.setAttribute(`data-testid`,`editor-add-summary-note`),c.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,c.appendChild(tD());let l=document.createElement(`span`);l.textContent=`Add summary`,c.appendChild(l),c.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),this.detailed||e.dispatch({effects:TE.of(!0)});let r=e.dom.querySelector(`.cm-frontmatter-preview`)??t,i=r.querySelector(`[data-frontmatter-summary-draft] input`);if(i){i.focus();return}let a=QE(e,(t,n)=>{BE(e,`new`,t,n,!0)});r.appendChild(a),IE(r,a),a.querySelector(`input`)?.focus(),e.requestMeasure()}),r.appendChild(c);let u=document.createElement(`button`);u.type=`button`,u.setAttribute(`aria-label`,`Add tag`),u.className=`inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground px-1 py-1 cursor-pointer transition-colors select-none`,u.appendChild(tD());let d=document.createElement(`span`);return d.textContent=`Add tag`,u.appendChild(d),u.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),this.detailed||e.dispatch({effects:TE.of(!0)});let r=e.dom.querySelector(`.cm-frontmatter-preview`)??t,i=r.querySelector(`[data-frontmatter-tag-draft] input`);if(i){i.focus();return}let a=qE(e,r,`category`,t=>{kE.set(e,{kind:`tag`,key:`category`}),BE(e,`new`,[`category`],[t],!0)});r.appendChild(a),IE(r,a),a.querySelector(`input`)?.focus(),e.requestMeasure()}),r.appendChild(u),t.appendChild(r),t}};function lD(e){let t=new pi,{sections:n}=e.field(NT),r=e.facet(wE),i=!1;for(let a of n){if(a.type!==`frontmatter`)continue;if(i=!0,!r){let n=a.to<e.doc.length?a.to+1:a.to;t.add(a.from,n,Ir.replace({block:!0}));continue}if(!e.readOnly&&(e.field(OE)||e.selection.ranges.some(e=>e.from<a.to&&e.to>a.from)))continue;let n=e.doc.sliceString(a.from,a.to);t.add(a.from,a.to,Ir.replace({widget:new sD(a.id,n,e.readOnly,e.field(EE)),block:!0}))}return r&&!i&&!e.readOnly&&t.add(0,0,Ir.widget({widget:new cD(e.field(EE)),side:-1,block:!0})),t.finish()}var uD=[EE,OE,ni.define({create(e){return lD(e)},update(e,t){return t.docChanged||t.reconfigured||t.selection||t.effects.some(e=>e.is(CE)||e.is(TE)||e.is(DE))?lD(t.state):e},provide:e=>[Sr.decorations.from(e),Sr.atomicRanges.of(t=>t.state.facet(wE)?Ir.none:t.state.field(e))]})],dD=/^(#{1,6}) /,fD=/\*\*([^*\n]+)\*\*/g,pD=/(?<!\*)\*([^*\n]+)\*(?!\*)/g,mD=[1,2,3,4,5,6].map(e=>Ir.line({attributes:{class:`cm-md-heading cm-md-heading-${e}`}})),hD=Ir.replace({}),gD=Ir.mark({class:`cm-md-bold font-bold`}),_D=Ir.mark({class:`cm-md-italic italic`});function vD(e){let t=new pi,{sections:n}=e.field(NT),r=e.selection.main.head;for(let i of n)if(i.type===`markdown`)for(let n=i.startLine;n<=i.endLine;n++){let i=e.doc.line(n),a=r>=i.from&&r<=i.to,o=i.text.match(dD);if(o){let e=o[1].length;t.add(i.from,i.from,mD[e-1]),a||t.add(i.from,i.from+o[0].length,hD)}if(!a){let e;for(fD.lastIndex=0;(e=fD.exec(i.text))!==null;){let n=i.from+e.index,r=n+e[0].length;t.add(n,n+2,hD),t.add(n+2,r-2,gD),t.add(r-2,r,hD)}for(pD.lastIndex=0;(e=pD.exec(i.text))!==null;){let n=i.from+e.index,r=n+e[0].length;t.add(n,n+1,hD),t.add(n+1,r-1,_D),t.add(r-1,r,hD)}}}return t.finish()}var yD=ni.define({create(e){return vD(e)},update(e,t){return t.docChanged||t.selection?vD(t.state):e},provide:e=>Sr.decorations.from(e)}),bD=Sr.baseTheme({".cm-md-heading-1":{fontSize:`1.3em`,fontWeight:`bold`},".cm-md-heading-2":{fontSize:`1.2em`,fontWeight:`bold`},".cm-md-heading-3":{fontSize:`1.1em`,fontWeight:`bold`}});function xD(){return[yD,bD]}function SD(e){return/^\|[\s:]*-+[\s:]*(\|[\s:]*-+[\s:]*)*\|$/.test(e.trim())}function CD(e){let t=e.trim();return(t.startsWith(`|`)&&t.endsWith(`|`)?t.slice(1,-1):t).split(`|`).map(e=>e.trim())}var wD=class extends xr{head;rows;constructor(e,t){super(),this.head=e,this.rows=t}eq(e){return this.head.length!==e.head.length||this.rows.length!==e.rows.length?!1:this.head.every((t,n)=>t===e.head[n])}toDOM(){let e=document.createElement(`div`);e.className=`cm-table-preview my-2 overflow-auto border border-border/80 rounded-lg`;let t=document.createElement(`table`);t.className=`w-full text-xs font-mono border-collapse`;let n=document.createElement(`thead`),r=document.createElement(`tr`);r.className=`border-b border-border bg-muted/40 text-muted-foreground text-left`;for(let e of this.head){let t=document.createElement(`th`);t.className=`py-1.5 px-3 font-semibold`,t.textContent=e,r.appendChild(t)}n.appendChild(r),t.appendChild(n);let i=document.createElement(`tbody`);for(let e of this.rows){let t=document.createElement(`tr`);t.className=`border-b border-border/40 hover:bg-muted/20`;for(let n of e){let e=document.createElement(`td`);e.className=`py-1.5 px-3 text-foreground`,e.textContent=n,t.appendChild(e)}i.appendChild(t)}return t.appendChild(i),e.appendChild(t),e}};function TD(e,t){let n=[];for(let r=t.startLine;r<=t.endLine;r++){if(!e.doc.line(r).text.trim().startsWith(`|`))continue;let t=n[n.length-1];t&&t.toLine===r-1?t.toLine=r:n.push({fromLine:r,toLine:r})}for(let t of n){let n=[];for(let r=t.fromLine;r<=t.toLine;r++)n.push(e.doc.line(r).text);if(!(n.length<2||!SD(n[1].trim())))return{head:CD(n[0]),rows:n.slice(2).map(CD),fromLine:t.fromLine,toLine:t.toLine}}return null}function ED(e){let t=new pi,{sections:n}=e.field(NT),r=e.selection.main.head;for(let i of n){if(i.type!==`markdown`)continue;let n=TD(e,i);if(!n)continue;let a=e.doc.line(n.fromLine).from,o=e.doc.line(n.toLine).to;r>=a&&r<=o||t.add(a,o,Ir.replace({widget:new wD(n.head,n.rows),block:!0}))}return t.finish()}var DD=[ni.define({create(e){return ED(e)},update(e,t){return t.docChanged||t.selection?ED(t.state):e},provide:e=>Sr.decorations.from(e)})],OD=/\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g,kD=/https?:\/\/\S+/g,AD=/`[^`\n]*`/g,jD=/[.,;:!?)\]}>'"]$/;function MD(e){let t=e.match(/[?&]v=([a-zA-Z0-9_-]{11})/);if(t)return t[1];let n=e.match(/youtu\.be\/([a-zA-Z0-9_-]+)/);if(n)return n[1];let r=e.match(/youtube\.com\/embed\/([a-zA-Z0-9_-]{11})/);return r?r[1]:null}function ND(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2`),e.setAttribute(`stroke-linecap`,`round`),e.setAttribute(`stroke-linejoin`,`round`),e.setAttribute(`class`,`h-3 w-3`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,`M15 3h6v6`),e.appendChild(t);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);n.setAttribute(`x1`,`10`),n.setAttribute(`x2`,`21`),n.setAttribute(`y1`,`14`),n.setAttribute(`y2`,`3`),e.appendChild(n);let r=document.createElementNS(`http://www.w3.org/2000/svg`,`polyline`);return r.setAttribute(`points`,`21 14 21 3 10 3`),e.appendChild(r),e}var PD=class extends xr{label;url;constructor(e,t){super(),this.label=e,this.url=t}eq(e){return this.label===e.label&&this.url===e.url}toDOM(){let e=document.createElement(`span`);e.className=`cm-link-pill`;let t=document.createElement(`span`);t.className=`cm-link-pill-label`,t.textContent=this.label||this.url,e.appendChild(t);let n=document.createElement(`a`);return n.className=`cm-link-pill-open`,n.href=this.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.title=this.url,n.setAttribute(`aria-label`,`Open ${this.label||this.url} in new tab`),n.appendChild(ND()),e.appendChild(n),e}},FD=class extends xr{videoId;title;constructor(e,t){super(),this.videoId=e,this.title=t}eq(e){return this.videoId===e.videoId&&this.title===e.title}toDOM(){let e=document.createElement(`div`);e.className=`cm-youtube-player`;let t=document.createElement(`iframe`);return t.className=`cm-youtube-player-frame`,t.src=`https://www.youtube-nocookie.com/embed/${encodeURIComponent(this.videoId)}`,t.title=this.title||`YouTube video`,t.setAttribute(`allow`,`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`),t.setAttribute(`allowfullscreen`,``),t.setAttribute(`loading`,`lazy`),e.appendChild(t),e}get block(){return!0}};function ID(e){let t=[],n=[],r;for(AD.lastIndex=0;(r=AD.exec(e.text))!==null;)n.push([r.index,r.index+r[0].length]);let i=e=>n.some(([t,n])=>e>=t&&e<n);for(OD.lastIndex=0;(r=OD.exec(e.text))!==null;)i(r.index)||t.push({from:e.from+r.index,to:e.from+r.index+r[0].length,label:r[1],url:r[2]});for(kD.lastIndex=0;(r=kD.exec(e.text))!==null;){if(i(r.index))continue;let n=r;if(t.some(t=>n.index>=t.from-e.from&&n.index<t.to-e.from))continue;let a=n[0];for(;jD.test(a);)a=a.slice(0,-1);a&&t.push({from:e.from+n.index,to:e.from+n.index+a.length,label:a,url:a})}return t.sort((e,t)=>e.from-t.from)}function LD(e){let t=new pi,{sections:n}=e.field(NT),r=e.selection.main.head,i=e.readOnly;for(let a of n)if((a.type===`markdown`||a.type===`embed`)&&(a.type!==`markdown`||a.subtype!==`table`))for(let n=a.startLine;n<=a.endLine;n++){let a=e.doc.line(n);if(a.text.trim().startsWith(`|`)||!i&&r>=a.from&&r<=a.to)continue;let o=ID(a),s=a.text.trimStart(),c=a.text.length-s.length,l=a.text.length-a.text.trimEnd().length,u=c+(s.match(/^[-*+]\s+/)?.[0].length??0);for(let e of o){let n=o.length===1&&e.from===a.from+u&&e.to===a.to-l?MD(e.url):null;n?t.add(a.from,a.to,Ir.replace({widget:new FD(n,e.label),block:!0})):t.add(e.from,e.to,Ir.replace({widget:new PD(e.label,e.url)}))}}return t.finish()}var RD=[ni.define({create(e){return LD(e)},update(e,t){return t.docChanged||t.selection?LD(t.state):e},provide:e=>Sr.decorations.from(e)}),Sr.baseTheme({".cm-link-pill":{display:`inline-flex`,alignItems:`center`,gap:`4px`,padding:`0 5px`,border:`1px solid hsl(var(--border))`,borderRadius:`6px`,backgroundColor:`hsl(var(--muted) / 0.35)`,maxWidth:`100%`},".cm-link-pill-label":{color:`hsl(var(--primary))`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},".cm-link-pill-open":{display:`inline-flex`,alignItems:`center`,flexShrink:`0`,color:`hsl(var(--muted-foreground))`,textDecoration:`none`,cursor:`pointer`},".cm-link-pill-open:hover":{color:`hsl(var(--primary))`},".cm-youtube-player":{width:`100%`,aspectRatio:`16 / 9`,margin:`8px 0`,backgroundColor:`#000`,borderRadius:`6px`,overflow:`hidden`},".cm-youtube-player-frame":{display:`block`,width:`100%`,height:`100%`,border:`none`}})],zD=Kr.define(),BD=ni.define({create(){return new Set},update(e,t){for(let e of t.effects)if(e.is(zD))return e.value;return e}}),VD={runtime:`cm-gutter-runtime`,error:`cm-gutter-error`,warning:`cm-gutter-warning`,info:`cm-gutter-info`},HD=class extends Fr{kind;constructor(e){super(),this.kind=e}toDOM(){let e=document.createElement(`div`);return e.className=`cm-unified-gutter-marker ${VD[this.kind]}`,e}},UD=new Map([[`runtime`,new HD(`runtime`)],[`error`,new HD(`error`)],[`warning`,new HD(`warning`)],[`info`,new HD(`info`)]]),WD=[BD,wr({class:`cm-unified-gutter`,markers(e){let t=new pi,n=e.state.field(BD),r=new Map;for(let t of n)t>=1&&t<=e.state.doc.lines&&r.set(t,`runtime`);Hr(e.state,t=>{let n=e.state.doc.lineAt(t.from).number;if(r.get(n)===`runtime`)return;let i=r.get(n);(!i||t.severity===`error`&&i!==`error`)&&r.set(n,t.severity)});let i=Array.from(r.keys()).sort((e,t)=>e-t);for(let n of i){let i=e.state.doc.line(n),a=UD.get(r.get(n));a&&t.add(i.from,i.from,a)}return t.finish()},initialSpacer:()=>new HD(`info`)})];function GD(e,t){e.dispatch({effects:zD.of(new Set(t))})}var KD=Kr.define(),qD=Kr.define(),JD=Kr.define(),YD=class extends xr{height;constructor(e){super(),this.height=e}eq(e){return e.height===this.height}toDOM(){let e=document.createElement(`div`);return e.className=`cm-runtime-panel-spacer`,e.style.height=`${this.height}px`,e.style.pointerEvents=`none`,e}get block(){return!0}};function XD(e){let t=new pi,n=Array.from(e.values()).sort((e,t)=>e.afterPos-t.afterPos);for(let e of n){let n=e.expanded?600:500;t.add(e.afterPos,e.afterPos,Ir.widget({widget:new YD(n),block:!0,side:1}))}return t.finish()}ni.define({create(){return new Map},update(e,t){let n=e;for(let e of t.effects)if(e.is(KD))n=new Map(n),n.set(e.value.sectionId,e.value);else if(e.is(qD))n.has(e.value.sectionId)&&(n=new Map(n),n.delete(e.value.sectionId));else if(e.is(JD)){let t=n.get(e.value.sectionId);t&&(n=new Map(n),n.set(e.value.sectionId,{...t,expanded:e.value.expanded}))}return n},provide:e=>Sr.decorations.compute([e],t=>XD(t.field(e)))});function ZD(e){return`:session{result:${e}}`}function QD(e,t,n){let r=e.field(NT).sections.find(e=>e.id===t);return!r||r.type!==`time`&&r.type!==`log`?null:{from:r.to,insert:`\n\n\`\`\`query:table\n${ZD(n)}\n\`\`\``}}function $D(e){let t=e.split(`:`);if(t.length<1||t.length>4)return null;let n=t.map(e=>parseInt(e,10));if(n.some(e=>isNaN(e)))return null;for(;n.length<4;)n.unshift(0);return n}function eO(e,t,n,r){let i=[];return e>0?i.push(e,t,n,r):t>0?i.push(t,n,r):n>0?i.push(n,r):i.push(r),i.map((e,t)=>t===0?String(e):String(e).padStart(2,`0`)).join(`:`)}function tO(e,t,n,r,i,a){let o=e*86400+t*3600+n*60+r,s=[86400,3600,60,1][i]??1;o=Math.max(0,o+a*s);let c=Math.floor(o/86400);o%=86400;let l=Math.floor(o/3600);return o%=3600,[c,l,Math.floor(o/60),o%60]}function nO(e,t){let n=/\b(\d{1,2}(?::\d{2}){1,3})\b/g,r;for(;(r=n.exec(e))!==null;){let e=r.index,n=e+r[0].length;if(t>=e&&t<=n){let i=r[0],a=Math.min(t-e,i.length-1),o=(i.slice(0,a).match(/:/g)||[]).length;return{timeStr:i,startCol:e,endCol:n,digitIndex:4-((i.match(/:/g)||[]).length+1)+o}}}return null}function rO(e,t){let n=e.state.selection.main,r=e.state.doc.lineAt(n.head),i=n.head-r.from,a=nO(r.text,i);if(!a)return!1;let o=$D(a.timeStr);if(!o)return!1;let[s,c,l,u]=tO(o[0],o[1],o[2],o[3],a.digitIndex,t),d=eO(s,c,l,u);return e.dispatch({changes:{from:r.from+a.startCol,to:r.from+a.endCol,insert:d}}),!0}var iO=hr.of([{key:`Alt-ArrowUp`,run:e=>rO(e,1)},{key:`Alt-ArrowDown`,run:e=>rO(e,-1)}]),aO=[],oO={duration:`cm-metric-duration`,rep:`cm-metric-rep`,rounds:`cm-metric-rounds`,distance:`cm-metric-distance`,resistance:`cm-metric-resistance`,action:`cm-metric-action`,pace:`cm-metric-pace`,heart_rate:`cm-metric-heart_rate`,power:`cm-metric-power`,calories:`cm-metric-calories`};function sO(e,t){if(e.type!==`time`&&e.type!==`log`||e.contentFrom===void 0||e.contentTo===void 0)return null;let n=t.doc.sliceString(e.contentFrom,e.contentTo);try{return _c().read(n,e.sport).statements}catch{return null}}function cO(e){let t=new pi,{sections:n}=e.field(NT),r=e.selection.main.head,i=e.doc.lineAt(r),a=null;for(let o of n){if(o.type!==`time`&&o.type!==`log`)continue;let n=sO(o,e);if(!n)continue;let s=r>=o.from&&r<=o.to;for(let r=0;r<n.length;r++){let c=n[r],l=o.startLine+1+r;if(l>=o.endLine)break;let u=e.doc.line(l),d=s&&i.number===l;for(let e=0;e<c.metrics.length;e++){let i=c.metrics[e],s=oO[i.type]||`cm-metric-generic`;t.add(u.from,u.to,Ir.mark({class:`cm-metric-mark ${s}`})),d&&!a&&(a={sectionId:o.id,section:o,lineFrom:u.from,docLine:l,statementIndex:r,statement:c,focusedMetric:i,focusedMetricIndex:e,allStatements:n})}}}return{focus:a,decos:t.finish()}}ni.define({create(e){return cO(e)},update(e,t){return cO(t.state)},provide:e=>Sr.decorations.from(e,e=>e.decos)});var lO=class extends xr{queryText;sectionId;widgetType;widgetError;options;root=null;constructor(e,t,n,r,i){super(),this.queryText=e,this.sectionId=t,this.widgetType=n,this.widgetError=r,this.options=i}eq(e){return this.queryText===e.queryText&&this.sectionId===e.sectionId&&this.widgetType===e.widgetType&&this.widgetError===e.widgetError&&this.options?.readOnly===e.options?.readOnly&&this.options?.executor===e.options?.executor&&this.options?.onOpenNote===e.options?.onOpenNote&&this.options?.noteHref===e.options?.noteHref}toDOM(e){let t=document.createElement(`div`);t.className=`cm-query-block-preview my-2`;let n=(0,Ci.createRoot)(t);return this.root=n,n.render((0,W.jsx)(uT,{query:this.queryText,widgetType:this.widgetType,widgetError:this.widgetError,readOnly:this.options?.readOnly,executor:this.options?.executor,onResultSaved:this.options?.onResultSaved,onSaveQuery:t=>{if(this.options?.onSaveQuery)return this.options.onSaveQuery(this.sectionId,t);let n=dO(e,this.sectionId,t);if(!n.ok)throw Error(n.message)},onOpenNote:this.options?.onOpenNote,noteHref:this.options?.noteHref})),t}updateDOM(e,t){return this.root?(this.root.render((0,W.jsx)(uT,{query:this.queryText,widgetType:this.widgetType,widgetError:this.widgetError,readOnly:this.options?.readOnly,executor:this.options?.executor,onResultSaved:this.options?.onResultSaved,onOpenNote:this.options?.onOpenNote,noteHref:this.options?.noteHref,onSaveQuery:e=>{if(this.options?.onSaveQuery)return this.options.onSaveQuery(this.sectionId,e);let n=dO(t,this.sectionId,e);if(!n.ok)throw Error(n.message)}})),!0):!1}destroy(){this.root&&setTimeout(()=>{try{this.root?.unmount()}catch{}},0)}get block(){return!0}};function uO(e,t){let n=new pi,{sections:r}=e.field(NT),i=e.selection.main.head;for(let a of r){if(a.type!==`query`||i>=a.from&&i<=a.to||a.contentFrom===void 0||a.contentTo===void 0)continue;let r=e.doc.sliceString(a.contentFrom,a.contentTo);n.add(a.from,a.to,Ir.replace({widget:new lO(r,a.id,a.queryType,a.queryError,t),block:!0}))}return n.finish()}function dO(e,t,n,r=0){if(e.state.readOnly)return{ok:!1,message:`Cannot modify query source in read-only mode.`};let i=fO(e,t);if(!i||i.contentFrom===void 0||i.contentTo===void 0)return{ok:!1,message:`Query block section not found`};let a=zC(e.state.doc.sliceString(i.contentFrom,i.contentTo),n,r);return e.dispatch({changes:{from:i.contentFrom,to:i.contentTo,insert:a}}),{ok:!0,patchedContent:a}}function fO(e,t){let{sections:n}=e.state.field(NT);return n.find(e=>e.id===t)??null}function pO(e){return[ni.define({create(t){return uO(t,e)},update(t,n){return n.docChanged||n.selection?uO(n.state,e):t},provide:e=>Sr.decorations.from(e)})]}var mO={view:`Edit widget`,editing:`Save widget`,error:`Undo changes`};function hO(e,t,n,r){return e===`editing`?n:e===`error`?r:t}function gO(e){return e?`opacity-100 scale-100 rotate-0`:`pointer-events-none opacity-0 scale-75 -rotate-12`}var _O=U.forwardRef(({mode:e,enterEditMode:t,onSave:n,onUndo:r,className:i,type:a=`button`,...o},s)=>{let c=mO[e],l=hO(e,t,n,r);return(0,W.jsx)(`button`,{...o,ref:s,type:a,"aria-label":c,title:c,"data-mode":e,onClick:l,className:gS(`absolute right-2 top-2 inline-flex h-8 w-8 items-center justify-center rounded-full border border-border/80 bg-background/90 shadow-sm backdrop-blur-sm transition-all duration-200 ease-out hover:bg-muted/80 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer`,e===`view`&&`text-muted-foreground hover:text-foreground`,e===`editing`&&`text-signal-positive hover:text-signal-positive/80`,e===`error`&&`text-signal-caution hover:text-signal-caution/80`,i),children:(0,W.jsxs)(`span`,{className:`relative h-4 w-4`,"aria-hidden":`true`,children:[(0,W.jsx)(en,{"data-icon-state":`view`,className:gS(`absolute inset-0 h-4 w-4 transition-all duration-200 ease-out`,gO(e===`view`))}),(0,W.jsx)(I,{"data-icon-state":`editing`,className:gS(`absolute inset-0 h-4 w-4 transition-all duration-200 ease-out`,gO(e===`editing`))}),(0,W.jsx)(Oe,{"data-icon-state":`error`,className:gS(`absolute inset-0 h-4 w-4 transition-all duration-200 ease-out`,gO(e===`error`))})]})})});_O.displayName=`WidgetEditButton`;var vO=U.forwardRef(({className:e,hasError:t=!1,spellCheck:n=!1,...r},i)=>(0,W.jsx)(`textarea`,{...r,ref:i,spellCheck:n,className:gS(`min-h-[160px] w-full rounded-xl border bg-background px-4 py-3 font-mono text-sm leading-6 text-foreground shadow-sm outline-none transition-colors duration-200 ease-out placeholder:text-muted-foreground/70`,`focus:border-ring focus:ring-2 focus:ring-ring/20`,t?`border-destructive/70 focus:border-destructive focus:ring-destructive/20`:`border-border/70`,e)}));vO.displayName=`EditableMarkdown`;var yO=Kr.define(),bO=ni.define({create:()=>new Set,update(e,t){let n=e;for(let e of t.effects)e.is(yO)&&(n=new Set(n),e.value.editing?n.add(e.value.sectionId):n.delete(e.value.sectionId));return n}});function xO(e){return e.endsWith(`
75
- `)?e.slice(0,-1):e}function SO(e){return`${e.replace(/\n+$/,``)}\n`}function CO(e){let t=e.trim();if(t.length===0)return{ok:!0,config:{}};try{let e=JSON.parse(t);return!e||Array.isArray(e)||typeof e!=`object`?{ok:!1,config:{},message:`Widget config must be a JSON object.`}:{ok:!0,config:e}}catch(e){return{ok:!1,config:{},message:e instanceof Error?e.message:`Invalid JSON.`}}}function wO(e,t){let{sections:n}=e.state.field(NT);return n.find(e=>e.type===`widget`&&e.id===t)??null}function TO(e,t,n){if(e.state.readOnly)return{ok:!1,config:{},message:`Cannot modify widget source in read-only mode.`};let r=CO(n);if(!r.ok)return r;let i=wO(e,t);return!i||i.contentFrom==null||i.contentTo==null?{ok:!1,config:{},message:`Unable to locate widget source in the editor.`}:(e.dispatch({changes:{from:i.contentFrom,to:i.contentTo,insert:SO(n)}}),r)}function EO(e){return(0,W.jsxs)(`div`,{className:`rounded-xl border border-dashed border-border/70 bg-muted/30 px-4 py-5 text-sm text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,e]}),(0,W.jsx)(`span`,{className:`ml-2 opacity-70`,children:`is not registered`})]})}function DO(e,t){return(0,W.jsxs)(`div`,{className:`rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-5 text-sm text-destructive shadow-sm`,children:[(0,W.jsx)(`p`,{className:`font-medium`,children:`Widget config error`}),(0,W.jsxs)(`p`,{className:`mt-1 font-mono text-xs leading-5 text-destructive/90`,children:[`widget:`,e]}),(0,W.jsx)(`p`,{className:`mt-2 font-mono text-xs leading-5 text-destructive/90`,children:t})]})}function OO({widgetName:e,rawContent:t,sectionId:n,registry:r,view:i}){let a=U.useRef(null),o=U.useRef(null),s=U.useRef(null),c=U.useMemo(()=>xO(t),[t]),[l,u]=U.useState(()=>({isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c,hasFocus:!1}));U.useEffect(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c}))},[c]),U.useEffect(()=>{if(!l.isEditing)return;let e=window.requestAnimationFrame(()=>{o.current?.focus();let e=o.current?.value.length??0;o.current?.setSelectionRange(e,e)});return()=>window.cancelAnimationFrame(e)},[l.isEditing]);let d=r.get(e),f=U.useMemo(()=>CO(l.originalMarkdown),[l.originalMarkdown]),p=U.useCallback(e=>{u(t=>t.hasFocus===e?t:{...t,hasFocus:e})},[]),m=U.useCallback(()=>{u(e=>({...e,isEditing:!0,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),h=U.useCallback(e=>{let t=TO(i,n,e);if(!t?.ok)return u(e=>({...e,error:t?.message??`Invalid JSON.`})),!1;let r=xO(SO(e));return u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1}),!0},[i,n]),g=U.useCallback(()=>{h(o.current?.value??l.currentMarkdown)},[h,l.currentMarkdown]),_=U.useCallback(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),v=U.useCallback(e=>{let t=e.target.value;u(e=>{let n=e.error?CO(t):null;return{...e,currentMarkdown:t,isDirty:t!==e.originalMarkdown,error:n?.ok===!1?n.message:n?.ok?null:e.error}})},[]),y=U.useCallback(()=>{p(!1);let e=o.current?.value;if(e===void 0)return;let t=TO(i,n,e);if(!t?.ok){u(n=>({...n,isDirty:e!==n.originalMarkdown,error:t?.message??`Unable to save widget source.`}));return}let r=xO(SO(e));u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1})},[n,i,p]),b=U.useCallback(e=>{let t=e.relatedTarget;t instanceof Node&&a.current?.contains(t)||p(!1)},[p]),x=U.useCallback(e=>{e.key===`Enter`&&!l.isEditing&&(e.preventDefault(),m())},[m,l.isEditing]);U.useEffect(()=>{let e=s.current;if(e)return e.addEventListener(`keydown`,x),()=>e.removeEventListener(`keydown`,x)},[x]);let S=U.useCallback(e=>{e.key===`Escape`?(e.preventDefault(),_()):e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),g())},[g,_]),C=l.error?`error`:l.isEditing?`editing`:`view`,w=l.hasFocus||l.isEditing||l.error!==null,T;return T=d?f.ok?U.createElement(d,{config:f.config,rawContent:l.originalMarkdown,sectionId:n}):DO(e,f.message):EO(e),(0,W.jsxs)(`div`,{ref:a,"data-widget-section-id":n,"data-widget-mode":C,className:gS(`group relative rounded-2xl border border-transparent bg-background/95 p-3 transition-colors duration-200 ease-out hover:border-border`,l.isEditing&&l.error===null&&`border-signal-positive/40 ring-1 ring-signal-positive/15`,l.error!==null&&`border-destructive/40 ring-1 ring-destructive/15`),onMouseDownCapture:e=>{l.isEditing||e.preventDefault()},onFocusCapture:()=>p(!0),onBlurCapture:b,onKeyDownCapture:x,children:[(0,W.jsx)(_O,{mode:C,enterEditMode:m,onSave:g,onUndo:_,className:gS(`z-10 focus-visible:opacity-100 focus-visible:scale-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-focus-within:scale-100`,w?`pointer-events-auto opacity-100 scale-100`:`pointer-events-none opacity-0 scale-95 group-hover:pointer-events-auto group-hover:opacity-100 group-hover:scale-100`)}),l.isEditing?(0,W.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[l.error!==null&&(0,W.jsxs)(`div`,{"data-testid":`widget-error-inlay`,className:`rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive`,children:[`Invalid JSON: `,l.error]}),(0,W.jsx)(vO,{ref:o,"data-testid":`widget-markdown-editor`,value:l.currentMarkdown,onChange:v,onBlur:y,onKeyDown:S,hasError:l.error!==null})]}):(0,W.jsx)(`div`,{ref:s,"data-testid":`widget-preview-surface`,tabIndex:0,onKeyDown:x,children:T})]})}var kO=class extends xr{sectionId;constructor(e){super(),this.sectionId=e}eq(e){return this.sectionId===e.sectionId}toDOM(e){let t=document.createElement(`div`);return t.className=`relative h-0 w-full`,(0,Ci.createRoot)(t).render((0,W.jsx)(`div`,{className:`absolute right-0 top-1 z-50`,children:(0,W.jsx)(_O,{mode:`editing`,enterEditMode:()=>{},onSave:()=>{e.dispatch({effects:yO.of({sectionId:this.sectionId,editing:!1})})},onUndo:()=>{e.dispatch({effects:yO.of({sectionId:this.sectionId,editing:!1})})}})})),t}ignoreEvent(){return!1}},AO=class extends xr{widgetName;rawContent;sectionId;registry;root=null;constructor(e,t,n,r){super(),this.widgetName=e,this.rawContent=t,this.sectionId=n,this.registry=r}eq(e){return this.widgetName===e.widgetName&&this.rawContent===e.rawContent&&this.sectionId===e.sectionId}toDOM(e){let t=document.createElement(`div`);return t.className=`cm-widget-block-preview`,t.style.cssText=`display:block; width:100%; min-height:1.5em; outline:none;`,this.root=(0,Ci.createRoot)(t),this.root.render(U.createElement(OO,{widgetName:this.widgetName,rawContent:this.rawContent,sectionId:this.sectionId,registry:this.registry,view:e})),t}destroy(){if(this.root){let e=this.root;this.root=null,queueMicrotask(()=>{try{e.unmount()}catch{}})}}ignoreEvent(){return!1}get estimatedHeight(){return 200}};function jO(e,t){let n;try{n=e.field(NT)}catch{return Ir.none}let{sections:r}=n,i=e.field(bO),a=[],o=e.selection.main.head;for(let n of r){if(n.type!==`widget`||!n.widgetName)continue;let r=e.doc;if(n.startLine>r.lines||n.endLine>r.lines)continue;if(i.has(n.id)){a.push(Ir.widget({widget:new kO(n.id),side:1,block:!1}).range(n.from));continue}if(o>=n.from&&o<=n.to)continue;let s=n.contentFrom!=null&&n.contentTo!=null?r.sliceString(n.contentFrom,n.contentTo):``;a.push(Ir.replace({widget:new AO(n.widgetName,s,n.id,t),block:!0}).range(n.from,n.to))}return a.sort((e,t)=>e.from-t.from),Ir.set(a)}function MO(e,t){return e.find(e=>e.type===`widget`&&t.from>=e.from&&t.from<=e.to)??null}function NO(e,t){let{head:n}=e.state.selection.main,r=e.state.doc.lineAt(n),i=Math.max(0,n-r.from),a=Math.min(i,t.length),o=t.from+a;e.dispatch({selection:{anchor:o,head:o},scrollIntoView:!0})}function PO(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(NT),i=e.state.field(bO),a=MO(r,n);if(a&&!i.has(a.id))return!1;let o=n.number+1;if(o>e.state.doc.lines)return!1;let s=MO(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(NO(e,e.state.doc.line(s.startLine)),!0)}function FO(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(NT),i=e.state.field(bO),a=MO(r,n);if(a&&!i.has(a.id))return!1;let o=n.number-1;if(o<1)return!1;let s=MO(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(NO(e,e.state.doc.line(s.endLine)),!0)}var IO=si.high(hr.of([{key:`ArrowDown`,run:PO},{key:`ArrowUp`,run:FO}]));function LO(e){return[ni.define({create(t){return jO(t,e)},update(t,n){let r=n.effects.some(e=>e.is(yO)),i=!n.startState.selection.eq(n.newSelection);return n.docChanged||r||i?jO(n.state,e):t},provide:e=>Sr.decorations.from(e)}),bO,IO]}function RO(e){let t=e?.split(`:`,1)[0]?.toLowerCase();return t===`time`||t===`log`||t===`wod`||t===`whiteboard`?Rc:t===`wql`||t===`query`?Yh:null}var zO=new class{_db;constructor(e){this._db=e}get db(){return this._db??Z}async load(){return this.db.getAllEfforts()}async save(e){await this.db.saveEffort(e)}async delete(e){await this.db.deleteEffort(e)}};function BO(){return new bl({storage:zO})}async function VO(e){let t=await Z.getAllEfforts();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),WO()}var HO=new Set;function UO(e){return HO.add(e),()=>HO.delete(e)}function WO(){for(let e of HO)e()}var GO=null;function KO(){return GO||=BO(),GO}function qO(e){let t=e.split(/\r?\n\s*\r?\n/).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```")&&!e.startsWith(`|`)&&!e.startsWith(`- `)&&!e.startsWith(`* `));if(t)return t.replace(/^>\s?/,``).replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`).replace(/[`*_~]/g,``).replace(/\s+/g,` `).trim()||void 0}function JO(e){let{meta:t,body:n}=Qy(e),r=ib(t,`description`),i=ib(t,`image`),a;if(typeof i==`string`&&i.trim()){let e=i.trim();(/^https?:\/\//.test(e)||e.startsWith(`/`))&&(a=e)}let o=typeof r==`string`&&r.trim()?r.trim():qO(n);return{...o?{description:o}:{},...a?{image:a}:{}}}function YO(e){return e.split(/[-_\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var XO={and:!0,or:!0,of:!0,for:!0,to:!0,in:!0,on:!0,at:!0,by:!0,with:!0,the:!0,a:!0,an:!0};function ZO(e){let t=e.replace(/\.md$/,``);if(t.toUpperCase()===`README`)return`Overview`;let n=t.replace(/^day-\d+-/,``).split(/[-_]/),r=[];for(let e=0;e<n.length;e++){let t=n[e],i=n[e+1],a=n[e+2],o=n[e-1];if(/^\d{1,2}$/.test(t)&&/^\d{1,2}$/.test(i??``)&&!/^\d+$/.test(o??``)&&!/^\d+$/.test(a??``)){r.push(`${t}.${i}`),e++;continue}if(r.length>0&&XO[t.toLowerCase()]){r.push(t.toLowerCase());continue}r.push(t.charAt(0).toUpperCase()+t.slice(1))}return r.join(` `)}function QO(e,t){if(e!==`notebooks`)return[];let n=new Map,r=e=>{let t=n.get(e);return t||(t={id:e,name:YO(e),categories:[],items:[]},n.set(e,t)),t};for(let[e,n]of Object.entries(t)){let t=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/README\.md$/i);if(t){let e=r(t[1]);e.readme=n,e.categories=ob(n),Object.assign(e,JO(n));continue}let i=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/(\d{4}-\d{2}-\d{2})\/([^/]+\.md)$/);if(i){let[,t,a,o]=i;r(t).items.push({id:o.replace(/\.md$/,``),name:ZO(o),content:n,path:e,...a?{date:a}:{}});continue}let a=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/([^/]+\.md)$/);if(!a)continue;let[,o,s]=a;s.toLowerCase()!==`readme.md`&&r(o).items.push({id:s.replace(/\.md$/,``),name:ZO(s),content:n,path:e})}for(let e of n.values())e.items.sort((e,t)=>e.date&&t.date&&e.date!==t.date?t.date.localeCompare(e.date):e.date&&!t.date?-1:!e.date&&t.date?1:e.id.localeCompare(t.id));return Array.from(n.values()).filter(({items:e,readme:t})=>e.length>0||t!==void 0).sort((e,t)=>e.name.localeCompare(t.name))}function $O(e){return QO(`notebooks`,e)}var ek=null,tk=[];async function nk(){let e=await gk();return ek!==e&&(ek=e,tk=$O(e)),tk}function rk(e,t,n){return e?.items.find(e=>(e.date??``)===t&&e.id===n)}var ik=null,ak=null;function ok(){return ik||=Z.getAllBlockIndex().then(e=>e.filter(e=>e.isStatic===!0)).catch(e=>{throw ik=null,e}),ik}function sk(){ik=null,ak=null}function ck(e){let t=new Map;for(let n of e)for(let e of Ma(n.rawContent).filter(e=>e.type===`frontmatter`).flatMap(e=>sb(e.displayContent))){let r=t.get(e);r?r.add(n.id):t.set(e,new Set([n.id]))}return t}function lk(){return ak||=Z.getAllNotes().then(async e=>{let t=ck(e.filter(e=>e.seedOrigin===`seed`));try{let e=await nk();for(let n of e)for(let e of n.categories){let r=t.get(e);r?r.add(n.id):t.set(e,new Set([n.id]))}}catch{}return t}),ak}async function uk(){let e=KO();return e.isInitialized()||await e.loadBundled(),e.list()}ww(`discipline`,{load:async()=>{try{return _w((await uk()).map(e=>e.baseAttributes?.discipline).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),gw(zc))}catch{return gw(zc)}},cache:{ttlMs:6e4},open:!1,emptyText:`No disciplines available`}),ww(`effort`,{load:async()=>{try{return _w((await uk()).filter(e=>e.slug).map(e=>({value:e.slug,label:e.label||e.slug})),[]).sort((e,t)=>e.value.localeCompare(t.value))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No efforts indexed yet — type one to filter`}),ww(`intensity`,{load:async()=>{try{return _w((await uk()).map(e=>e.baseAttributes?.intensityTier).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),gw(ac))}catch{return gw(ac)}},cache:{ttlMs:6e4},open:!1,emptyText:`No intensity tiers indexed yet`}),ww(`type`,{load:async()=>{try{return _w(pw(await ok()).map(e=>({value:e,label:e})),gw(hw))}catch{return gw(hw)}},cache:{ttlMs:3e5},open:!1,emptyText:`No indexed block types yet`}),ww(`notebook`,{load:async()=>fw(await ok()).map(e=>({value:e,label:e})),cache:`static`,open:!1,emptyText:`No notebooks in the static corpus`}),ww(`tag`,{load:async()=>{let e=await lk(),t=Array.from(e.keys()),n=[];try{n=(await Z.getAllTags()).map(e=>e.label)}catch{}return mw(n,t).map(e=>({value:e,label:e}))},cache:{ttlMs:3e4},open:!0,emptyText:`No tags yet — type one to filter by it`});for(let e of[`domain`,`format`,`equipment`,`quality`,`intent`])ww(e,{load:async()=>{try{return(await Z.getTags(e)).map(e=>({value:e.label,label:e.label}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No ${e}s indexed yet`});ww(`origin`,{load:async()=>{try{let e=await Z.getAllEfforts(),t=new Set;for(let n of e)n.registrySource&&t.add(n.registrySource);return Array.from(t).sort().map(e=>({value:e,label:e}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No effort origins indexed yet — type one to filter`}),(async()=>{try{let e=await Z.getAllTagTypes();for(let t of e)Tw(t.name)||ww(t.name,{load:async()=>{try{return(await Z.getTags(t.name)).map(e=>({value:e.label,label:e.label}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No ${t.label}s indexed yet`})}catch{}})();var dk=null,fk=null,pk=new Set;function mk(){for(let e of pk)e()}async function hk(){let e=await Z.getSeedContent(),t={};for(let{path:n,raw:r}of e)t[n]=r;return t}function gk(){return fk||=hk().then(e=>(Object.keys(e).length>0&&hS(`corpusReady`),dk=e,mk(),e)).catch(e=>{throw fk=null,e}),fk}function _k(){dk=null,fk=null,sk(),gk()}function vk(e){return pk.add(e),()=>pk.delete(e)}function yk(){return dk}function bk(){let e=(0,U.useSyncExternalStore)(vk,yk);return(0,U.useEffect)(()=>{gk()},[]),e}var xk=!1;function Sk(){if(xk||typeof BroadcastChannel>`u`)return;xk=!0;let e=new BroadcastChannel(Gv);e.onmessage=()=>_k()}var Ck=200,wk=1e6,Tk=500,Ek=50,Dk=6e4,Ok=3e4,kk=750,Ak=`wodwiki-sync`,jk={attachments:`data`};function Mk(e,t){let n=e instanceof Error?e.message:String(e);return t&&(n=n.split(t).join(`••••••`)),n||`Sync failed`}function Nk(e){let t=0;for(let n of e.ops){if(t+=32,n.op!==`put`)continue;let e=jk[n.store],r=n.value,i=e&&typeof r==`object`&&r&&!Array.isArray(r)?Reflect.get(r,e):void 0;t+=typeof i==`string`?i.length:i instanceof ArrayBuffer?Math.ceil(i.byteLength/3)*4+64:JSON.stringify(n.value)?.length??0}return t}var Pk=class{local;settings;connect;db;stopped=!1;chain=Promise.resolve();timers=[];reconciled=!1;halted=!1;retryAt=0;debounceTimer;unsubscribeOutbox;onOnline;onVisible;constructor(e,t,n){this.local=e,this.settings=t,this.connect=n}syncNow(){let e=this.chain.then(()=>this.cycle(!0));return this.chain=e.then(()=>void 0,()=>void 0),e}restoreNow(){let e=this.chain.then(async()=>{if(this.stopped)throw Error(`Restore engine is stopped`);if((await this.local.snapshotAllRows()).some(e=>e.rows.length>0)||(await this.local.readOutbox(0,1)).length>0)throw Error(`Restore requires an empty isolated local database`);let e=await this.remote(),t=await Ub(e);if(t===`empty`||t.kind!==`current`||t.schemaVersion!==32)throw Error(`Restore requires a provisioned v32 backup. Migrate older backups with the CLI first.`);let n=0;for(;n<t.rev;){let r=await Jb(e,n,Tk);if(r.length===0)break;if(r[r.length-1].rev>t.rev)throw Error(`Backup changed during restore. Freeze its writers and retry with a fresh local database.`);n=r[r.length-1].rev,await this.local.applySyncMutations(r.map(e=>e.mutation),n,this.cursorKey())}await this.local.validateSyncState();let r=await Ub(e);if(r===`empty`||r.kind!==`current`||r.schemaVersion!==t.schemaVersion||r.rev!==t.rev||n!==t.rev)throw Error(`Backup changed during restore. Freeze its writers and retry with a fresh local database.`);await this.local.setSyncState(this.bootstrappedKey(),{done:!0}),this.reconciled=!0});return this.chain=e.then(()=>void 0,()=>void 0),e}start(){let e=e=>{this.enqueue(()=>this.cycle(!1,e))};return this.onOnline=()=>{e(`full`)},this.onVisible=()=>{typeof document<`u`&&!document.hidden&&e(`full`)},typeof window<`u`&&(window.addEventListener(`online`,this.onOnline),typeof document<`u`&&document.addEventListener(`visibilitychange`,this.onVisible)),this.timers.push(setInterval(()=>{e(`full`)},Dk)),this.unsubscribeOutbox=sx(()=>{this.scheduleUpload()}),e(`full`),()=>{this.stop()}}async stop(){this.stopped=!0;for(let e of this.timers)clearInterval(e);this.timers=[],clearTimeout(this.debounceTimer),this.debounceTimer=void 0,typeof window<`u`&&this.onOnline&&window.removeEventListener(`online`,this.onOnline),typeof document<`u`&&this.onVisible&&document.removeEventListener(`visibilitychange`,this.onVisible),this.onOnline=void 0,this.onVisible=void 0,this.unsubscribeOutbox?.(),this.unsubscribeOutbox=void 0,await this.chain.catch(()=>void 0),await this.db?.close().catch(()=>void 0),this.db=void 0}scheduleUpload(){this.stopped||this.debounceTimer!==void 0||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.stopped||this.enqueue(()=>this.cycle(!1,`upload`))},kk))}enqueue(e){this.chain=this.chain.then(e,e),this.chain.catch(()=>{})}async cycle(e=!1,t=`full`){if(this.stopped||this.halted||!e&&Date.now()<this.retryAt)return;let n=globalThis.navigator?.locks;try{n?await n.request(Ak,()=>this.cycleInner(e,t)):await this.cycleInner(e,t)}catch(e){this.retryAt=Date.now()+Ok,Qx(Mk(e,this.settings.authToken))}}async cycleInner(e,t){let n=[];if(t===`full`){try{await this.ensureReconciled()}catch(e){n.push(e)}try{await this.pullOnce()}catch(e){n.push(e)}}try{await this.uploadOnce()}catch(e){n.push(e)}if(n.length>0)throw n[0]}async remote(){return this.db||=this.connect?.()??nS(Fe({url:this.settings.url,authToken:this.settings.authToken})),this.db}cursorKey(){return`cursor:${this.settings.url}`}watermarkKey(){return`watermark:${this.settings.url}`}bootstrappedKey(){return`bootstrapped:${this.settings.url}`}bootstrapRunKey(){return`bootstrap-run:${this.settings.url}`}async ensureReconciled(){if(this.reconciled)return;let e=await this.remote(),t=await Ub(e);if(t!==`empty`&&t.kind===`unknown`){let e=`Backup database contains unrelated tables and no WOD Wiki schema; refusing to adopt it. Point the backup setting at a fresh database.`;throw this.halted=!0,dS(e),Error(e)}let n=t===`empty`?0:t.schemaVersion;if(n>32){let e=`Backup database schema is newer than this app supports (v${n} > v32). Update the app to sync.`;throw this.halted=!0,dS(e),Error(e)}if(t===`empty`)await Wb(e,32);else if(t.kind===`legacy`||n<32){let e=`Backup schema v${n} requires an explicit CLI migration into a fresh v32 target. The old database was left untouched.`;throw this.halted=!0,dS(e),Error(e)}this.reconciled=!0}async bootstrapSnapshot(){let e=await this.remote(),t=await this.local.captureSyncBootstrap(this.bootstrapRunKey());for(let n of t)await qb(e,[n],{expectSchema:32});await this.local.setSyncState(this.bootstrappedKey(),{done:!0}),await(await this.local.open()).delete(`sync_state`,this.bootstrapRunKey())}async uploadOnce(){if(!this.reconciled||this.stopped||this.halted||!await this.local.getSyncState(this.bootstrappedKey()))return;let e=this.watermarkKey();if((await this.local.readOutbox((await this.local.getSyncState(e))?.seq??0,1)).length===0)return;let t=Yx(`upload`,`Uploading changes to backup`);try{let t=await this.remote(),n=(await this.local.getSyncState(e))?.seq??0,r=0;for(;;){let i=await this.local.readOutbox(n,Ek);if(i.length===0)break;let a=0;for(;a<i.length;){let o=[],s=0,c=0,l=n;for(;a<i.length&&s<Ck&&c<wk;){let e=i[a],t=Nk(e);if(o.length>0&&(s+e.ops.length>Ck||c+t>wk))break;o.push({id:e.id,at:e.at,ops:e.ops}),s+=e.ops.length,c+=t,l=e.seq,a+=1}await qb(t,o,{expectSchema:32}),r+=o.flatMap(e=>e.ops).filter(e=>e.op===`put`&&(e.store===`notes`||e.store===`efforts`)).length,n=l,await this.local.setSyncState(e,{seq:n}),await this.local.ackOutbox(n)}if(i.length<Ek)break}r>0&&Xx({source:`turso backup`,added:r,updated:0})}finally{t()}}async pullOnce(){if(!this.reconciled||this.stopped||this.halted)return;let e=this.cursorKey(),t=(await this.local.getSyncState(e))?.rev??0,n=Yx(`download`,`Syncing from backup`);try{let n=await this.remote(),r=t,i=0,a=0;for(;;){let t=await Jb(n,r,Tk);if(t.length===0){if(!await this.local.getSyncState(this.bootstrappedKey())){await this.bootstrapSnapshot();continue}break}let o=t[t.length-1].rev,s=await this.local.applySyncMutations(t.map(e=>e.mutation),o,e);i+=s.added,a+=s.updated,r=o}if(i+a>0){Xx({source:`turso backup`,added:i,updated:a}),_k();let e=KO();e.isInitialized()&&await VO(e)}}finally{n()}}},Fk=`wodwiki.dataSettings.v1`;function Ik(){let e=Uk();return e.state!==`invalid`&&e.localDbName?e.localDbName:Yb}function Lk(e,t){let n=e=>{let t=e.trim();try{let e=new URL(t);return`${e.hostname===`[::1]`?`::1`:e.hostname}${e.port?`:${e.port}`:``}${e.pathname.replace(/\/+$/,``)}`}catch{return t}};return n(e)===n(t)}function Rk(e){return typeof e==`string`&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(e)}var zk={"libsql:":!0,"https:":!0,"wss:":!0};function Bk(e,t){let n;try{n=new URL(e.trim())}catch{return`That is not a valid URL.`}if(n.protocol===`http:`||n.protocol===`ws:`){if(n.hostname!==`localhost`&&n.hostname!==`127.0.0.1`&&n.hostname!==`[::1]`&&n.hostname!==`::1`)return`Plain http:// is only allowed for a local smoke server (localhost / 127.0.0.1).`}else if(!zk[n.protocol])return`Unsupported protocol "${n.protocol}" — use libsql:// or https://.`;if(n.username||n.password)return`The URL must not embed credentials — put the token in the token field.`;if(n.search)return`The URL must not contain a query string.`;if(n.hash)return`The URL must not contain a fragment.`;if(!t||!t.trim())return`A database token is required.`}function Vk(e,...t){let n=e instanceof Error?e.message:String(e);for(let e of t)e&&(n=n.split(e).join(`••••••`));return Error(n)}function Hk(){try{return localStorage.getItem(Fk)}catch{return null}}function Uk(){let e=Hk();if(e===null)return{state:`indexed-db`};let t;try{t=JSON.parse(e)}catch{return{state:`invalid`,raw:e,error:`Saved data settings are not valid JSON.`}}if(!t||typeof t!=`object`||Array.isArray(t))return{state:`invalid`,raw:e,error:`Saved data settings have an unexpected shape.`};if(!(`kind`in t))return{state:`invalid`,raw:e,error:`Saved data settings have no kind.`};let n=t.kind,r=`localDbName`in t?t.localDbName:void 0;if(r!==void 0&&!Rk(r))return{state:`invalid`,raw:e,error:`Saved data settings have an invalid localDbName.`};let i=r===void 0?{}:{localDbName:r};if(n===`indexed-db`)return{state:`indexed-db`,...i};if(n!==`turso`)return{state:`invalid`,raw:e,error:`Saved data settings have an unknown kind "${String(n)}".`};if(!(`url`in t)||!(`authToken`in t))return{state:`invalid`,raw:e,error:`Saved Turso settings are missing the URL or token.`};let a=t.url,o=t.authToken;if(typeof a!=`string`||typeof o!=`string`)return{state:`invalid`,raw:e,error:`Saved Turso settings are missing the URL or token.`};let s=Bk(a,o);return s?{state:`invalid`,raw:e,error:s}:{state:`turso`,url:a,authToken:o,...i}}async function Wk(e){let t=nS(Fe({url:e.url.trim(),authToken:e.authToken}));try{await t.query(`SELECT 1`);let e=Error(`verifyTursoTarget: deliberate rollback`);try{await t.transaction(async t=>{throw await t.exec(`CREATE TABLE IF NOT EXISTS "_wodwiki_write_check" ("v" TEXT)`),await t.exec(`INSERT INTO "_wodwiki_write_check" ("v") VALUES (?)`,[crypto.randomUUID()]),e})}catch(t){if(t!==e)throw t}}finally{await t.close().catch(()=>void 0)}}var Gk;async function Kk(e){if(Gk)throw Error(`A connect is already running — wait for it to finish.`);let t=Bk(e.url,e.authToken);if(t)throw Error(t);Gk=(async()=>{try{await Wk(e)}catch(t){throw Vk(t,e.authToken)}let t=Uk(),n=t.state!==`invalid`&&t.localDbName?{localDbName:t.localDbName}:{};localStorage.setItem(Fk,JSON.stringify({kind:`turso`,url:e.url.trim(),authToken:e.authToken,...n}))})();try{await Gk}finally{Gk=void 0}}async function qk(e){let t=Bk(e.url,e.authToken);if(t)throw Error(t);try{await Wk(e)}catch(t){throw Vk(t,e.authToken)}}function Jk(e){if(!Rk(e))throw Error(`A valid local database name is required.`);localStorage.setItem(Fk,JSON.stringify({kind:`indexed-db`,localDbName:e}))}function Yk(){let e=Uk(),t=e.state!==`invalid`&&e.localDbName?{localDbName:e.localDbName}:{};localStorage.setItem(Fk,JSON.stringify({kind:`indexed-db`,...t}))}var Xk=Hk();typeof window<`u`&&window.addEventListener(`storage`,e=>{(e.key===`wodwiki.dataSettings.v1`||e.key===null)&&e.newValue!==Xk&&window.location.reload()});var Zk=t({DATA_SETTINGS_KEY:()=>Fk,IndexedDBStorage:()=>gx,StorageService:()=>Ox,getActiveLocalDbName:()=>Ik,profileService:()=>$k,readAllLocalRows:()=>fA,readDataSettings:()=>Uk,readUnsentEdits:()=>dA,startBackgroundStorageSync:()=>lA,stopBackgroundStorageSync:()=>uA,storage:()=>nA,storageBackend:()=>Qk,storageService:()=>Z,whenStorageReady:()=>aA}),Qk=`indexed-db`,$k=Lx(`indexed-db`);function eA(){return new gx({dbName:Ik(),getUserId:()=>$k.currentSync()?.id,onUpgradeStart:e=>uS(e,32)})}var tA=eA(),nA={readonly(e){return tA.readonly(e)},readwrite(e){return tA.readwrite(e)},transaction(e,t,n){return tA.transaction(e,t,n)},async queryDomain(e){return tA.queryDomain?.(e)},wipe(){return tA.wipe()},close(){return tA.close()}},Z=new Ox(nA),rA;async function iA(){try{await Z.ensureDefaultTagTypes()}catch{}}function aA(){return rA||(rA=(async()=>{try{let e=globalThis.indexedDB;if(e&&typeof e.databases==`function`){let t=Ik(),n=(await e.databases().catch(()=>[])).find(e=>e.name===t);if(n&&typeof n.version==`number`){if(n.version>32){let e=`local database schema v${n.version} is newer than this app supports (v32); refusing to downgrade`;throw dS(e),Error(e)}n.version<32&&lS(`Checking local database schema v${n.version}…`)}}await tA.open(),cS(32),await iA()}catch(e){throw rA=void 0,oS().phase!==`error`&&dS(e instanceof Error?e.message:String(e)),e}})(),rA)}var oA,sA,cA;function lA(){if(!oA){if(!(tA instanceof gx))oA={stop:()=>{oA=void 0}};else{let e=Uk();if(e.state===`invalid`){let t=`Saved backup settings are invalid: ${e.error}`;Qx(t),dS(t),oA={stop:()=>{oA=void 0}}}else if(e.state===`turso`){let t=new Pk(tA,e);cA=t;let n=t.start();oA={stop:()=>{n(),cA===t&&(cA=void 0),oA=void 0}}}else oA={stop:()=>{oA=void 0}}}sA=()=>{oA?.stop(),sA=void 0}}return sA}async function uA(){if(!oA)return!1;let e=cA;return oA.stop(),e&&await e.stop(),e!==void 0}async function dA(){return tA instanceof gx?tA.readOutbox(0,2**53-1):[]}async function fA(){return tA instanceof gx?tA.snapshotAllRows():[]}var pA={registeredWidgets:Oa},mA=[`notes`,`block_revisions`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`];function hA(e){let t=ba(e.links,e.pages),n=xa(t);return{id:e.note.id,title:e.note.title,slug:n.pageSlug,pageId:n.pageId,journalDate:n.journalDate,placements:t,createdAt:e.note.createdAt,updatedAt:e.note.createdAt,targetDate:e.note.date??e.note.createdAt,rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision,tags:e.tags.map(e=>e.label),type:e.note.type??`note`,sourceId:e.note.sourceId,notebookId:e.note.notebookId,seedOrigin:e.note.seedOrigin,schemaVersion:1}}function gA(e){if(e?.dateRange)return e.dateRange;if(e?.daysBack!=null){let t=Date.now();return{start:t-e.daysBack*864e5,end:t}}}var _A=class e{db;constructor(e=Z){this.db=e}get persistenceStorage(){return this.db}mode=`history`;capabilities={canWrite:!0,canDelete:!0,canFilter:!0,canMultiSelect:!0,supportsHistory:!0};async getRecords(e){let t=gA(e),n=[];t&&n.push({field:`date`,start:t.start,end:t.end});for(let t of e?.tags??[])n.push({field:`tags`,values:[t]});let r=await this.db.queryDomain(n.length?{plan:`detail`,selection:n}:{plan:`detail`}),i;if(r?.plan===`detail`)i=r.rows.map(hA);else{let e=t?await this.db.getNotesByDateRange(t.start,t.end):await this.db.getAllNotes();i=[...(await this.db.getDetailBatches(e.map(e=>e.id))).values()].map(hA)}return i=i.filter(n=>(!t||n.targetDate>=t.start&&n.targetDate<=t.end)&&(e?.tags??[]).every(e=>n.tags.includes(e))),i.sort((e,t)=>t.targetDate-e.targetDate)}async getRecord(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.db.getNote(e)??(t===e?void 0:await this.db.getNote(t))??await this.db.getNoteBySlug(e)??(t===e?void 0:await this.db.getNoteBySlug(t));if(!n)return null;let r=(await this.db.getDetailBatches([n.id])).get(n.id);if(!r)return null;let i=hA(r),a=(await this.db.getSessionsForNote(n.id)).sort((e,t)=>t.createdAt-e.createdAt)[0],o=Ma(n.rawContent,pA).map(e=>{let t=Object.values(n.blocks).find(t=>t.from===e.from&&t.to===e.to);return t?{...e,id:t.id,version:t.version,scriptBlock:e.scriptBlock?{...e.scriptBlock,id:t.id,version:t.version}:void 0}:e});return{...i,sections:o,results:a?vb(a,await this.db.getEventsByResult(a.id)):void 0}}async cloneRecord(e,t){let n=await this.getRecord(e);if(!n)throw Error(`Source entry not found: ${e}`);let r=t??Date.now();return this.saveRecord({title:n.title,rawContent:n.rawContent,tags:n.tags,targetDate:r,journalDate:Yy(new Date(r)),type:`journal`,sourceId:n.id})}async saveRecord(t){let n=Date.now(),r=t.id??(t.type===`playground`?mb(n):ze());if(!t.id&&t.type===`playground`){let e=r;for(let t=1;await this.db.getNote(r);t++){if(t>100)throw Error(`Unable to allocate unique playground timestamp ID`);r=`${e}-${t}`}}await this.db.withTransaction([...mA],async n=>{let i=await n.getNote(r),a=i?t.sourceRevision:0;if(a===void 0)throw new yb(`STALE_SOURCE`,`An expected source revision is required for ${r}`);let o=await new e(n).changedManualTags(r,t.tags),s=t.blocks??(i?.rawContent===t.rawContent?i.blocks:Pa(t.rawContent,{...pA,sourceRevision:a||1}));await n.saveNoteSource({noteId:r,rawContent:t.rawContent,blocks:s,expectedSourceRevision:a,createdAt:t.createdAt,metadata:{title:t.title,type:t.type,tags:o,targetDate:t.targetDate,sourceId:t.sourceId}});let c=new e(n);await c.updateRelationships(r,{journalDate:t.journalDate,slug:t.slug}),await c.updateTags(r,t.rawContent,o)});let i=await this.getRecord(r);if(!i)throw Error(`Saved note disappeared: ${r}`);return i}async updateRecord(t,n){let r=t.startsWith(`playground/`)?t.slice(11):t,i=await this.db.getNote(t)??(r===t?void 0:await this.db.getNote(r))??await this.db.getNoteBySlug(t)??(r===t?void 0:await this.db.getNoteBySlug(r));if(!i)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${t}`);await this.db.withTransaction([...mA],async t=>{let r=await t.getNote(i.id);if(!r)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${i.id}`);let a=n.rawContent??r.rawContent;if(n.rawContent!==void 0&&n.expectedSourceRevision===void 0)throw new yb(`STALE_SOURCE`,`An expected source revision is required for ${r.id}`);let o=n.expectedSourceRevision??r.sourceRevision,s=n.tags===void 0?void 0:await new e(t).changedManualTags(r.id,n.tags),c=n.blocks??(a===r.rawContent?r.blocks:Pa(a,{...pA,sourceRevision:o}));await t.saveNoteSource({noteId:r.id,rawContent:a,blocks:c,expectedSourceRevision:o,metadata:{title:n.title,type:n.type,tags:s,targetDate:n.targetDate,sourceId:n.sourceId}});let l=new e(t);if(await l.updateRelationships(r.id,n),(n.tags!==void 0||a!==r.rawContent)&&await l.updateTags(r.id,a,s),n.results){if(!n.blockId||!n.blockVersion)throw Error(`Recording a result requires its frozen block pin`);let e=await t.getBlockRevision(r.id,n.blockId,n.blockVersion);if(!e||e.kind!==`wod`)throw new yb(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision not found`);let i=n.resultId?await t.getSessionById(n.resultId):void 0;if(i&&(i.noteId!==r.id||i.blockId!==n.blockId||i.blockVersion!==n.blockVersion))throw new yb(`RESULT_NOTE_MISMATCH`,`Cannot replace a Session pin`);let a=n.results,o={...i,id:n.resultId??ze(),noteId:r.id,blockId:n.blockId,blockVersion:n.blockVersion,blockContentId:n.blockContentId,origin:n.origin??i?.origin,startTime:a.startTime,endTime:a.endTime,duration:a.duration??0,completed:a.completed,roundsCompleted:a.roundsCompleted,totalRounds:a.totalRounds,repsCompleted:a.repsCompleted,status:`completed`,createdAt:i?.createdAt??a.endTime??Date.now()};if(await t.saveSession(o),a.logs?.length){let e={noteId:o.noteId,resultId:o.id,blockId:o.blockId,blockVersion:o.blockVersion,blockContentId:o.blockContentId,origin:o.origin,pageId:o.pageId,workoutTimestamp:o.endTime};await t.appendEvents(c_(a.logs,e)),await t.finalizeSummaries(o.id,l_(a.logs,e))}}});let a=await this.getRecord(i.id);if(!a)throw Error(`Saved note disappeared: ${i.id}`);return a}async updateRelationships(e,t){for(let n of[`journalDate`,`slug`]){let r=t[n];if(r===void 0)continue;if(!r){for(let t of await this.db.getNotePages(e)){let r=await this.db.getPage(t.pageId);(n===`journalDate`?r?.date:r?.slug&&!r.date)&&await this.db.removeNoteFromPage(e,t.pageId)}continue}let i=await this.resolvePage(e,n,r);await this.db.addNoteToPage(e,i.id)}}async resolvePage(e,t,n){if(t===`journalDate`)return this.db.getOrCreatePageForDate(n);let r=await this.db.getPageBySlug(n);if(r)return r;let i={id:ze(),slug:n,title:(await this.db.getNote(e))?.title,createdAt:Date.now()};return await this.db.savePage(i),i}async resolveTargetPage(e,t){if(t.date)return this.db.getOrCreatePageForDate(t.date);if(t.slug)return this.resolvePage(e,`slug`,t.slug);throw Error(`A placement target needs a date or a slug`)}async addRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e),r=await this.resolveTargetPage(n,t);await this.db.addNoteToPage(n,r.id);let i=await this.getRecord(n);if(!i)throw Error(`Saved note disappeared: ${n}`);return i}async removeRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e);await this.db.removeNoteFromPage(n,t);let r=await this.getRecord(n);if(!r)throw Error(`Saved note disappeared: ${n}`);return r}async moveRecordPlacement(e,t,n){let r=await this.resolvePlacementNoteId(e),i=await this.resolveTargetPage(r,n);await this.db.moveNoteBetweenPages(r,t,i.id);let a=await this.getRecord(r);if(!a)throw Error(`Saved note disappeared: ${r}`);return a}async getPageRecords(e){let t=await this.db.getPageBySlug(e);if(!t)return[];let n=await this.db.getPagePlacements(t.id);if(n.length===0)return[];let r=await this.db.getDetailBatches(n.map(e=>e.noteId));return n.map(e=>r.get(e.noteId)).filter(e=>e!==void 0).map(hA)}async resolvePlacementNoteId(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.db.getNote(e)??(t===e?void 0:await this.db.getNote(t));if(!n)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${e}`);return n.id}async resolveNoteId(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.db.getNote(e)??(t===e?void 0:await this.db.getNote(t))??await this.db.getNoteBySlug(e)??(t===e?void 0:await this.db.getNoteBySlug(t));if(!n)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${e}`);return n.id}async changedManualTags(e,t){let n=(await this.db.getTagsForNote(e)).map(e=>e.label).sort(),r=[...new Set(t.map(e=>e.trim()).filter(Boolean))].sort();return n.length===r.length&&n.every((e,t)=>e===r[t])?void 0:r}async updateTags(e,t,n){let r=(await this.db.getAllTagTypes()).map(e=>e.name),i=Ma(t,pA).filter(e=>e.type===`frontmatter`).flatMap(e=>cb(e.displayContent,r)),a=n??(await this.db.getNote(e))?.tags??[];await this.db.setNoteTags(e,[...a,...i.map(e=>e.type?e:e.label)])}async deleteRecord(e){await this.db.deleteNote(e)}async getAttachments(e){return this.db.getAttachmentsForNote(e)}async saveAttachment(e,t){let n={...t,id:t.id??ze(),noteId:e,createdAt:Date.now()};return await this.db.saveAttachment(n),n}async deleteAttachment(e){await this.db.deleteAttachment(e)}},vA={beep:{notes:[{freq:880,type:`sine`,duration:.1}]},tick:{notes:[{freq:880,type:`sine`,duration:.1}]},click:{notes:[{freq:1400,type:`sine`,duration:.1}]},buzzer:{notes:[{freq:150,type:`sawtooth`,duration:.5}]},chime:{notes:[{freq:523.25,type:`sine`,duration:.5,offset:0},{freq:659.25,type:`sine`,duration:.5,offset:.1},{freq:783.99,type:`sine`,duration:.5,offset:.2}]},complete:{notes:[{freq:523.25,type:`sine`,duration:.5,offset:0},{freq:659.25,type:`sine`,duration:.5,offset:.1},{freq:783.99,type:`sine`,duration:.5,offset:.2}]},select:{notes:[{freq:880,type:`sine`,duration:.08,offset:0},{freq:1200,type:`sine`,duration:.12,offset:.08}]},start:{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"countdown-beep":{notes:[{freq:880,type:`sine`,duration:.1}]},"timer-complete":{notes:[{freq:523.25,type:`sine`,duration:.4,offset:0},{freq:659.25,type:`sine`,duration:.4,offset:.1},{freq:783.99,type:`sine`,duration:.6,offset:.2}]},"start-beep":{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"interval-start":{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"interval-complete":{notes:[{freq:523.25,type:`sine`,duration:.4,offset:0},{freq:659.25,type:`sine`,duration:.4,offset:.1},{freq:783.99,type:`sine`,duration:.6,offset:.2}]},"rest-over":{notes:[{freq:783.99,type:`sine`,duration:.3,offset:0},{freq:1046.5,type:`sine`,duration:.5,offset:.15}]}};function yA(e){return vA[e]}var bA=Object.freeze(Object.keys(vA)),xA=class{context=null;masterGain=null;init(){if(this.context)return;let e=window;if(typeof window>`u`)return;let t=window.AudioContext??e.webkitAudioContext;t&&(this.context=new t,this.masterGain=this.context.createGain(),this.masterGain.connect(this.context.destination))}async playNotes(e,t){if(this.context||this.init(),!this.context||!this.masterGain||(this.context.state===`suspended`&&await this.context.resume().catch(()=>{}),this.context.state!==`running`))return;let n=this.context.currentTime;for(let r of e)this.playNote(n+(r.offset??0),r.freq,r.type,r.duration,t)}playNote(e,t,n,r,i){if(!this.context||!this.masterGain)return;let a=this.context.createOscillator(),o=this.context.createGain();a.connect(o),o.connect(this.masterGain),a.type=n,a.frequency.setValueAtTime(t,e),o.gain.setValueAtTime(i*.5,e),o.gain.exponentialRampToValueAtTime(.01,e+r),a.start(e),a.stop(e+r)}},SA=class extends Error{sound;constructor(e){super(`Unknown sound "${e}" — it has no entry in the sound table`),this.sound=e,this.name=`UnknownSoundError`}},CA=new class{enabled;sink;constructor(e,t){if(this.sink=e??new xA,t!==void 0)this.enabled=t;else if(typeof window<`u`)try{let e=localStorage.getItem(`wod-wiki-audio-enabled`);this.enabled=e===null||e===`true`}catch{this.enabled=!0}else this.enabled=!0}setEnabled(e){if(this.enabled=e,typeof window<`u`)try{localStorage.setItem(`wod-wiki-audio-enabled`,String(e))}catch{}}isEnabled(){return this.enabled}async playSound(e,t=1){if(!this.enabled)return;let n=yA(e);if(!n)throw new SA(e);`init`in this.sink&&typeof this.sink.init==`function`&&this.sink.init(),await this.sink.playNotes(n.notes,t)}},wA=class{listeners=new Set;emit(e){this.listeners.forEach(t=>{try{t(e)}catch(e){console.error(`[SimpleEventBus] Error in listener:`,e)}})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get size(){return this.listeners.size}};new class{bus=new wA;emitScrollToBlock(e,t=`unknown`){this.bus.emit({type:`workbench:scroll-to-block`,payload:{blockId:e,source:t}})}emitHighlightBlock(e,t=`unknown`){this.bus.emit({type:`workbench:highlight-block`,payload:{blockId:e,source:t}})}emitStartWorkout(e){this.bus.emit({type:`workbench:start-workout`,payload:{block:e}})}emitNavigateTo(e,t){this.bus.emit({type:`workbench:navigate-to`,payload:{entryId:e,view:t}})}onScrollToBlock(e){return this.bus.subscribe(t=>{t.type===`workbench:scroll-to-block`&&e(t.payload)})}onHighlightBlock(e){return this.bus.subscribe(t=>{t.type===`workbench:highlight-block`&&e(t.payload)})}onStartWorkout(e){return this.bus.subscribe(t=>{t.type===`workbench:start-workout`&&e(t.payload)})}onNavigateTo(e){return this.bus.subscribe(t=>{t.type===`workbench:navigate-to`&&e(t.payload)})}},new wA;function TA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`notebook`}var EA=`wodwiki.seedSources`,DA=`wodwiki.seedSources.hidden`;function OA(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!==`https:`&&n.protocol!==`http:`||n.username||n.password||n.search||n.hash?null:(n.pathname.endsWith(`/`)||(n.pathname+=`/`),n.toString())}function kA(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!==`https:`||n.username||n.password||n.search||n.hash?null:n.toString()}var AA=`/seed/core/`;function jA(e,t){if(/^https?:\/\//i.test(e))return e;let n=t??(typeof document<`u`?document.baseURI:void 0);if(!n)return e;try{return new URL(e,n).href}catch{return e}}function MA(){try{let e=localStorage.getItem(EA);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.label!=`string`||typeof e.url!=`string`)return[];let{repositoryUrl:t}=e,n=typeof t==`string`?kA(t):null,r={id:e.id,label:e.label,url:e.url};return[n?{...r,repositoryUrl:n}:r]}):[]}catch{return[]}}function NA(){return MA()}function PA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`source`}function FA(e,t,n){let r=OA(t);if(!r)throw Error(`Enter an absolute http(s) URL of a feed directory.`);let i=MA();if(i.some(e=>OA(e.url)===r)||GA().includes(r))throw Error(`This source is already registered.`);let a=n?.repositoryUrl?.trim(),o;if(a&&(o=kA(a)??void 0,!o))throw Error(`Enter an absolute https repository URL without credentials.`);let s=e.trim()||(()=>{try{return new URL(r).hostname}catch{return`Source`}})(),c={...nj};for(let e of i)c[e.id]=!0;let l=PA(s);for(let e=2;c[l];e++)l=`${PA(s)}-${e}`;let u={id:l,label:s,url:r,...o?{repositoryUrl:o}:{}};return localStorage.setItem(EA,JSON.stringify([...i,u])),u}function IA(e){localStorage.setItem(EA,JSON.stringify(MA().filter(t=>t.id!==e)))}function LA(){return WA.map(e=>e.id)}function RA(){try{let e=JSON.parse(localStorage.getItem(DA)??`null`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function zA(e){let t=tj(e),n=RA();LA().includes(t)&&!n.includes(t)&&localStorage.setItem(DA,JSON.stringify([...n,t]))}function BA(){return[...new Set(RA().map(tj))]}var VA={id:`core`,label:`Core`,url:AA,description:`The app's own corpus — guides, the page template, and the reference chunks.`,tier:`core`},HA=`https://bitcobblers.github.io`;function UA(e,t,n,r,i=!1){return{id:e,label:t,url:`${HA}/${n}/`,repositoryUrl:`https://github.com/bitcobblers/${n}`,description:r,tier:`community`,...i?{autoImport:!0}:{}}}var WA=[UA(`sport-crossfit`,`CrossFit`,`wod-wiki-sport-crossfit`,`CrossFit benchmark collections (Games, Girls, Heroes) and weekly programming.`),UA(`sport-hyrox`,`HYROX`,`wod-wiki-sport-hyrox`,`HYROX race preparation and simulation workouts.`),UA(`legends-of-kettlebell`,`Kettlebell Coaches`,`wod-wiki-legends-of-kettlebell`,`Kettlebell coach collections and the Dan John 40-Day Program feed.`),UA(`sport-swimming`,`Swimming`,`wod-wiki-sport-swimming`,`Swimming programs from pre-highschool through college, masters, Olympic, and triathlete.`),UA(`sport-track`,`Track & Field`,`wod-wiki-sport-track`,`High-school track programs — 400m (Raffensperger) and sprints (Arrowhead).`),UA(`wayback-zombie-fit`,`ZombieFit`,`wod-wiki-wayback-zombie-fit`,`The ZombieFit parkour archive — daily WODs since 2009.`),UA(`sport-golos-method`,`Golos Method`,`wod-wiki-feed-golos-method`,`Daily minimalist strength and conditioning.`),UA(`yt-dan-john`,`Dan John`,`wod-wiki-youtube-dan-john`,`Dan John kettlebell workouts.`),UA(`yt-mark-wildman`,`Mark Wildman`,`wod-wiki-youtube-mark-wildman`,`Mark Wildman athletic kettlebell and club training.`),UA(`yt-strongfirst`,`StrongFirst`,`wod-wiki-youtube-strongfirst`,`StrongFirst hardstyle kettlebell workouts.`),UA(`yt-the-stone-circle`,`The Stone Circle`,`wod-wiki-youtube-the-stone-circle`,`Sandbag power-endurance and density training.`),UA(`samples-movement`,`Movement Examples`,`wod-wiki-samples-movement`,`Unconventional and parkour-style training examples.`),UA(`sport-yoga`,`Yoga Examples`,`wod-wiki-sport-yoga`,`Yoga session examples.`),UA(`r-workoutroutines`,`r/WorkoutRoutines`,`wod-wiki-r-workoutroutines`,`Community feed from the r/WorkoutRoutines subreddit.`)];function GA(){return[AA,...WA.map(e=>e.url)]}function KA(e){return XA().find(t=>t.id===e)}function qA(e){let t=KA(e);if(!t)throw Error(`unknown feed source: ${e}`);return t}function JA(e,t,n,r,i,a){return qA(e),{id:`community-${t}`,feedId:e,chunkId:n,label:r,category:i,description:a}}var YA=[JA(`sport-crossfit`,`crossfit-games`,`notebook.crossfit-games`,`CrossFit Games`,`workouts`,`CrossFit Games workouts — Open, Regionals, and Games programming, formatted for Wod Wiki.`),JA(`sport-crossfit`,`crossfit-girls`,`notebook.crossfit-girls`,`CrossFit Girls`,`workouts`,`Classic benchmark workouts — Fran, Helen, Grace, Diane, and more, formatted for Wod Wiki.`),JA(`sport-crossfit`,`crossfit-heroes`,`notebook.crossfit-heroes`,`CrossFit Heroes`,`workouts`,`Hero benchmark workouts honoring service members — Murph, DT, Badger, and more.`),JA(`sport-crossfit`,`crossfit-programming`,`notebook.crossfit-programming`,`CrossFit Programming`,`programs`,`Weekly CrossFit programming — daily strength, conditioning, and skill sessions on a rotation with a weekly benchmark.`),JA(`sport-hyrox`,`hyrox`,`notebook.hyrox`,`HYROX`,`workouts`,`HYROX race preparation — running, sled work, ergs, and functional stations in race format.`),JA(`legends-of-kettlebell`,`geoff-neupert`,`notebook.geoff-neupert`,`Geoff Neupert`,`workouts`,`Geoff Neupert kettlebell workouts — strength and conditioning from a Master SFG coach.`),JA(`legends-of-kettlebell`,`girevoy-sport`,`notebook.girevoy-sport`,`Girevoy Sport`,`workouts`,`Competitive kettlebell sport — jerk, snatch, and long-cycle programming.`),JA(`legends-of-kettlebell`,`joe-daniels`,`notebook.joe-daniels`,`Joe Daniels (Swing This)`,`workouts`,`Joe Daniels kettlebell workouts — kettlebell sport and hardstyle fusion.`),JA(`legends-of-kettlebell`,`keith-weber`,`notebook.keith-weber`,`Keith Weber`,`workouts`,`Keith Weber kettlebell workouts — high-intensity kettlebell cardio.`),JA(`legends-of-kettlebell`,`steve-cotter`,`notebook.steve-cotter`,`Steve Cotter`,`workouts`,`Steve Cotter kettlebell workouts — comprehensive kettlebell education.`),JA(`legends-of-kettlebell`,`dan-john-40-day`,`notebook.dan-john-40-day`,`Dan John 40-Day Program`,`programs`,`Dan John's 40-day barbell program — five lifts, five sets of five, five days a week for 40 sessions.`),JA(`yt-dan-john`,`dan-john`,`notebook.dan-john`,`Dan John Kettlebell`,`workouts`,`Dan John kettlebell workouts — simple, effective programming with clear objectives.`),JA(`yt-mark-wildman`,`mark-wildman`,`notebook.mark-wildman`,`Mark Wildman`,`workouts`,`Mark Wildman workouts — athletic kettlebell and club training.`),JA(`yt-strongfirst`,`strongfirst`,`notebook.strongfirst`,`StrongFirst`,`workouts`,`StrongFirst workouts — hardstyle kettlebell strength and skill.`),JA(`yt-the-stone-circle`,`the-stone-circle`,`notebook.the-stone-circle`,`The Stone Circle`,`workouts`,`Sandbag power endurance and density training — progressive EMOM protocols.`),JA(`sport-swimming`,`swimming-college`,`notebook.swimming-college`,`Swimming: College`,`workouts`,`College swimming training sessions.`),JA(`sport-swimming`,`swimming-highschool`,`notebook.swimming-highschool`,`Swimming: High School`,`workouts`,`High-school swimming training sessions.`),JA(`sport-swimming`,`swimming-masters`,`notebook.swimming-masters`,`Swimming: Masters`,`workouts`,`Masters swimming training sessions.`),JA(`sport-swimming`,`swimming-olympic`,`notebook.swimming-olympic`,`Swimming: Olympic`,`workouts`,`Olympic-caliber swimming training sessions.`),JA(`sport-swimming`,`swimming-post-college`,`notebook.swimming-post-college`,`Swimming: Post-College`,`workouts`,`Post-college swimming training sessions.`),JA(`sport-swimming`,`swimming-pre-highschool`,`notebook.swimming-pre-highschool`,`Swimming: Pre-Highschool`,`workouts`,`Pre-highschool swimming training sessions.`),JA(`sport-swimming`,`swimming-triathlete`,`notebook.swimming-triathlete`,`Swimming: Triathlete`,`workouts`,`Triathlete swim training sessions.`),JA(`sport-track`,`hs-track-400m`,`notebook.hs-track-400m`,`HS Track 400m`,`workouts`,`High-school 400m program after Raffensperger — speed, tempo, and strength phases.`),JA(`sport-track`,`hs-track-sprints`,`notebook.hs-track-sprints`,`HS Track Sprints`,`workouts`,`High-school sprints program after Arrowhead — acceleration, maximum velocity, and speed endurance.`),JA(`wayback-zombie-fit`,`zombiefit`,`notebook.zombiefit`,`ZombieFit`,`workouts`,`The ZombieFit archive — parkour-inspired fitness WODs, 2009–2013.`),JA(`sport-golos-method`,`the-golos-method`,`notebook.the-golos-method`,`The Golos Method`,`workouts`,`Daily minimalist strength and conditioning — dense, repeatable sessions.`),JA(`samples-movement`,`unconventional`,`notebook.unconventional`,`Unconventional`,`workouts`,`Unconventional training — maces, clubs, sandbags, and parkour movement.`),JA(`sport-yoga`,`yoga`,`notebook.yoga`,`Yoga`,`workouts`,`Yoga sessions for mobility and recovery.`),JA(`r-workoutroutines`,`workoutroutines-reddit`,`notebook.workoutroutines-reddit`,`r/WorkoutRoutines`,`programs`,`Community workouts from the r/WorkoutRoutines subreddit.`)];function XA(){return[VA,...WA,...NA().map(e=>({id:e.id,label:e.label,url:e.url,description:`Custom feed synced from ${e.url}`,tier:`imported`,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{}}))]}function ZA(){return XA().filter(e=>e.id!==VA.id)}function QA(){return[...YA,...NA().map(e=>({id:e.id,feedId:e.id,chunkId:e.id,label:e.label,category:`custom`,description:`Custom feed synced from ${e.url}`}))]}function $A(e){return QA().filter(t=>t.feedId===e)}var ej={"seed-crossfit":`sport-crossfit`,"seed-hyrox":`sport-hyrox`,"seed-kettlebell":`legends-of-kettlebell`,"seed-swimming":`sport-swimming`,"seed-track":`sport-track`,"seed-zombie-fit":`wayback-zombie-fit`,"seed-golos-method":`sport-golos-method`,"example-movement":`samples-movement`,"example-yoga":`sport-yoga`};function tj(e){return ej[e]||(YA.find(t=>t.id===e)?.feedId??e)}var nj=Object.fromEntries([[`core`,!0],[`community`,!0],[`common`,!0],[`seed-core`,!0],[`seed-crossfit`,!0],[`seed-hyrox`,!0],[`seed-kettlebell`,!0],[`seed-swimming`,!0],[`seed-track`,!0],[`seed-zombie-fit`,!0],[`seed-golos-method`,!0],[`example-movement`,!0],[`example-yoga`,!0],...WA.map(e=>[e.id,!0]),...YA.map(e=>[e.id,!0])]),rj=`notebook/defaults`,ij=new Set(Da.map(e=>e.slug)),aj=class{store;constructor(e=Z){this.store=e}tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}getFeedNotebooks(){let e=[];for(let t of QA()){if(t.category===`dashboards`)continue;let n=t.chunkId.replace(/^notebook\./,``);e.push({id:Ta(n),slug:n,notebookId:Ta(n),name:t.label,description:t.description,icon:t.category===`feeds`?`📡`:`📚`,origin:`feed`,feedEntryId:t.feedId,seedChunkId:t.chunkId,createdAt:0})}return e}getDefaultNotebooks(){return Da.map(e=>({id:e.notebookId,slug:e.slug,notebookId:e.notebookId,name:e.name,description:e.description,icon:e.icon,origin:`default`,...e.feedEntryId?{feedEntryId:e.feedEntryId}:{},...e.seedChunkId?{seedChunkId:e.seedChunkId}:{},createdAt:0}))}async getAllNotebooks(){let e=new Map;for(let t of[...this.getDefaultNotebooks(),...this.getFeedNotebooks(),...await this.getAll()])e.set(t.notebookId,t);return[...e.values()]}async getAll(){return(await this.store.getAllNotes()).filter(oj).sort((e,t)=>e.createdAt-t.createdAt).map(uj)}async getById(e){let t=Ta(e),n=await this.store.getNote(t);return n&&oj(n)?uj(n):null}create(e,t=``,n=`📓`){return this.enqueue(()=>this.createNow(e,t,n))}async createNow(e,t,n){let r=await this.getAll(),i=TA(e),a=new Set([...ij,...r.map(e=>e.slug)]),o=i;for(let e=2;a.has(o);e++)o=`${i}-${e}`;let s=Ta(o);return uj(await this.saveLanding(s,e,t,n))}async saveLanding(e,t,n,r,i){let a=cj(t,n,r),o={...await this.store.saveNoteSource({noteId:e,rawContent:a,blocks:Pa(a,{sourceRevision:i||1}),expectedSourceRevision:i??0,metadata:{title:t}}),notebookId:e,type:`note`};return i===void 0&&(o.createdAt=Date.now()),await this.store.saveNote(o),o}update(e,t){return this.enqueue(async()=>{let n=Ta(e);sj(n);let r=await this.store.getNote(n);if(!r||!oj(r))throw Error(`Notebook not found: ${e}`);let i=lj(r);return uj(await this.saveLanding(r.id,t.name??r.title,t.description??i.description,t.icon??i.icon,r.sourceRevision))})}delete(e){return this.enqueue(async()=>{let t=Ta(e);sj(t);let n=await this.listNotes(t);for(let e of n){let{notebookId:t,...n}=e;await this.store.saveNote(n)}await this.store.deleteNote(t)})}async listNotes(e){let t=Ta(e);return(await this.store.getAllNotes()).filter(e=>e.notebookId===t&&!oj(e))}moveNote(e,t){return this.enqueue(async()=>{let n=await this.store.getNote(e);if(!n)throw Error(`Note not found: ${e}`);if(t===null){let{notebookId:e,...t}=n;await this.store.saveNote(t);return}let r=Ta(t);if(this.getFeedNotebooks().some(e=>e.notebookId===r))throw Error(`Notebook ${r} is feed-delivered and read-only.`);await this.store.saveNote({...n,notebookId:r})})}cloneNote(e,t,n){return this.enqueue(async()=>{let r=await this.store.getNote(e);if(!r)throw Error(`Note not found: ${e}`);let i=r.rawContent,a={...await this.store.saveNoteSource({noteId:ze(),rawContent:i,blocks:Pa(i,{sourceRevision:1}),expectedSourceRevision:0,createdAt:Date.now(),metadata:{title:n??r.title,type:`note`,sourceId:r.id,...r.tags?.length?{tags:[...r.tags]}:{}}}),notebookId:Ta(t),seedOrigin:`user`};return await this.store.saveNote(a),a})}ensureNotebooks(){return this.enqueue(async()=>{let e=await this.store.getAllNotes();e.some(e=>oj(e)&&e.id===`notebook/defaults`)||await this.saveLanding(rj,`Defaults`,`Starter notes — clone any of them into your own notebooks.`,`📝`);for(let t of e)t.type===`template`&&await this.store.saveNote({...t,type:`note`,notebookId:t.notebookId??`notebook/defaults`});if((await this.listNotes(`notebook/defaults`)).length===0){let e="# My Workout\n\n```time\n10 Push-ups\n```\n",t=await this.store.saveNoteSource({noteId:ze(),rawContent:e,blocks:Pa(e,{sourceRevision:1}),expectedSourceRevision:0,createdAt:Date.now(),metadata:{title:`My Workout`,type:`note`}});await this.store.saveNote({...t,notebookId:rj,seedOrigin:`user`})}})}};function oj(e){return e.id.startsWith(`notebook/`)&&e.notebookId===e.id}function sj(e){if(ij.has(wa(e)))throw Error(`Notebook ${e} is always present and cannot be changed.`)}function cj(e,t,n){return`---\ndescription: ${t?JSON.stringify(t.replace(/\n/g,` `)):``}\nicon: ${n?JSON.stringify(n.replace(/\n/g,` `)):``}\n---\n\n# ${e}\n`}function lj(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e.rawContent),n=``,r=`📓`,i=e=>{if(e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`))try{return JSON.parse(e)}catch{return e}return e};if(t)for(let e of t[1].split(/\r?\n/)){let t=e.match(/^(description|icon):\s*(.*)$/);t&&(t[1]===`description`?n=i(t[2].trim()):r=i(t[2].trim())||r)}return{description:n,icon:r}}function uj(e){let{description:t,icon:n}=lj(e);return{id:e.id,slug:e.id.slice(9),notebookId:Ta(e.id),name:e.title,description:t,icon:n,origin:`user`,createdAt:e.createdAt}}var dj=new aj,fj=null,pj=new Set;function mj(e){fj!==e&&(fj=e,pj.forEach(e=>e(fj)))}function hj(){return fj}function gj(e){return pj.add(e),()=>{pj.delete(e)}}var _j=(0,U.createContext)({transport:null});function vj(){let e=(0,U.useContext)(_j),[t,n]=U.useState(()=>hj());return U.useEffect(()=>gj(n),[]),e.transport??t}var yj=({children:e,transport:t})=>{let n=(0,U.useMemo)(()=>({transport:t}),[t]);return(0,W.jsx)(_j.Provider,{value:n,children:e})},bj=(0,U.createContext)(void 0);function xj({children:e}){let[t,n]=(0,U.useState)(CA.isEnabled()),r=vj();(0,U.useEffect)(()=>{CA.setEnabled(t)},[t]);let i=(0,U.useCallback)((e,n=1)=>{if(t){if(r?.connected){console.log(`[AudioContext] Routing sound '${e}' to cast receiver`);try{r.send({type:`rpc-audio`,name:e,volume:n})}catch(t){console.error(`[AudioContext] Failed to send rpc-audio`,t),CA.playSound(e,n).catch(Sj)}}else CA.playSound(e,n).catch(Sj)}},[t,r]),a=(0,U.useCallback)(()=>{let e=!t;n(e),e&&(CA.setEnabled(!0),CA.playSound(`beep`).catch(Sj))},[t]),o=(0,U.useCallback)(()=>{i(`chime`)},[i]),s=(0,U.useCallback)(()=>{i(`click`,.5)},[i]),c=(0,U.useMemo)(()=>({isEnabled:t,toggleAudio:a,playTestSound:o,playSound:i,playClick:s}),[t,a,o,i,s]);return(0,W.jsx)(bj.Provider,{value:c,children:e})}function Sj(e){console.error(`[AudioContext] Sound playback failed`,e)}function Cj(){let e=(0,U.useContext)(bj);if(e===void 0)throw Error(`useAudio must be used within an AudioProvider`);return e}var wj=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},Tj=class{baseUrl;fetchImpl;constructor(e,t=fetch.bind(globalThis)){this.baseUrl=e,this.fetchImpl=t}async fetchManifest(){let e=await this.fetchImpl(`${this.baseUrl}manifest.json`,{cache:`no-cache`});if(!e.ok)throw new wj(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return Cy(await e.json())}async fetchChunk(e){let t=await this.fetchImpl(`${this.baseUrl}${e}`);if(!t.ok)throw new wj(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}},Ej=class{storageInstance;constructor(e){this.storageInstance=e}async getSeedMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async getNoteCommits(e){let t=await this.storageInstance.readonly(`notes`).getMany(e),n=new Map;for(let r=0;r<e.length;r++){let i=t[r];n.set(e[r],i?.seedCommit)}return n}async putSeedMeta(e,t){await this.storageInstance.transaction([`meta`],`readwrite`,async n=>{let r=n.readwrite(`meta`),i=await r.get(e.key);if(t!==void 0&&JSON.stringify(i??null)!==JSON.stringify(t))throw Error(`Seed checkpoint changed during claim`);await r.put(e)})}applyChunk(e){return Ny(this.storageInstance,e)}backfillFeedProvenance(){return Fy(this.storageInstance)}migrateNotebookVocabulary(){return Iy(this.storageInstance)}async removeSourceContent(e){return await this.storageInstance.transaction([`notes`,`attachments`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`efforts`,`equipment`,`meta`],`readwrite`,async t=>{let n=new Set,r=[];for(let[t,i]of Object.entries(e.chunks))if(i.noteIds?.length)for(let e of i.noteIds)n.add(e);else r.push(t);if(r.length)for(let e of await t.readwrite(`notes`).getAll())e.seedOrigin===`seed`&&e.seedChunkId&&r.includes(e.seedChunkId)&&n.add(e.id);let i=t.readwrite(`meta`),a=[];for(let t of await i.getAll()){let n=t;if(!n||typeof n.key!=`string`||!n.key.startsWith(`seed:`)||n.key===e.key)continue;let r=new Set;for(let e of Object.values(n.chunks??{}))for(let t of e.noteIds??[])r.add(t);a.push({key:n.key,sourceId:n.key.slice(5),rank:Wv(n.key,n.tier),meta:n,noteIds:r})}a.sort((e,t)=>t.rank-e.rank);let o=e=>a.some(t=>t.noteIds.has(e)),s=e.key.startsWith(`seed:`)?e.key.slice(5):e.key,c=t.readwrite(`notes`),l=0,u=new Set;for(let r of n){if(o(r))continue;let n=await c.get(r);if(!n||n.seedOrigin!==`seed`||n.seedChunkId&&!e.chunks[n.seedChunkId])continue;n.sourcePath&&u.add(n.sourcePath),await c.delete(r);let i=t.readwrite(`attachments`);for(let e of await i.getAllFromIndex(`by-note`,r))await i.delete(e.id);let a=t.readwrite(`note_tags`);for(let e of await a.getAllFromIndex(`by-note`,r))await a.delete(e.id);let s=t.readwrite(`block_index`);for(let e of await s.getAllFromIndex(`by-note`,r))await s.delete(e.id);let d=t.readwrite(`block_efforts`);for(let e of await d.getAllFromIndex(`by-note`,r))await d.delete(e.id);let f=t.readwrite(`block_equipment`);for(let e of await f.getAllFromIndex(`by-note`,r))await f.delete(e.id);let p=t.readwrite(`page_notes`);for(let e of await p.getAllFromIndex(`by-note`,r))await p.delete(e.id);l++}let d=[{storeName:`efforts`,familyPathPrefix:`markdown/efforts/`,parse:nl},{storeName:`equipment`,familyPathPrefix:`markdown/equipment/`,parse:rl}];for(let{storeName:e,familyPathPrefix:r,parse:i}of d){let o=t.readwrite(e);for(let t of await o.getAll()){if(t.registrySource!==`bundled`||!(t.sourceId===s||t.ownerNoteId!==void 0&&n.has(t.ownerNoteId)&&(!t.sourceId||t.sourceId===e)||t.sourcePath!==void 0&&t.sourcePath.startsWith(r)&&u.has(t.sourcePath)))continue;let l=!1;for(let n of a){let r=n.meta.chunks?.[e]?.noteIds??[];for(let e of r){let r=await c.get(e);if(!r||r.seedOrigin!==`seed`)continue;let a=i(r.rawContent);if(a&&a.slug===t.slug){await o.put({...a,registrySource:`bundled`,ownerNoteId:r.id,sourceId:n.sourceId,feedSourceId:n.sourceId,sourcePath:r.sourcePath??``}),l=!0;break}}if(l)break}l||await o.delete(t.slug)}}return await i.delete(e.key),l})}};function Dj(){return new Ej(nA)}var Oj={core:1};function kj(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function Aj(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}var jj=`wodwiki.seedSubscriptions`,Mj=`wodwiki.seedAutoSync`,Nj=null,Pj=null,Fj=new Set;function Ij(e){let t={};try{let n=localStorage.getItem(e),r=n?JSON.parse(n):{};if(r&&typeof r==`object`&&!Array.isArray(r))for(let[e,n]of Object.entries(r))typeof n==`boolean`&&(t[e]=n)}catch{t={}}return t}function Lj(){return Nj||(Nj=Ij(jj),Nj)}function Rj(e,t){let n=!0;try{localStorage.setItem(e,JSON.stringify(t))}catch{n=!1}return n}function zj(e){Nj=e;let t=Rj(jj,e);for(let e of Fj)e();return t}function Bj(e){let t=tj(e);if(t===`core`)return`full`;let n=Lj();if(n[t]===!0||n[e]===!0)return`full`;let r=`${t}#`,i=`${e}#`;return Object.entries(n).some(([e,t])=>t===!0&&(e.startsWith(r)||e.startsWith(i)))?`partial`:`unsubscribed`}function Vj(e){return e===`core`||Bj(e)!==`unsubscribed`}function Hj(e,t){if(e===`core`)return!0;let n={},r=`${e}#`;for(let[t,i]of Object.entries(Lj()))t.startsWith(r)||YA.some(n=>n.feedId===e&&n.id===t)||(n[t]=i);return n[e]=t,zj(n)}function Uj(e,t){let n=tj(e);if(n===`core`)return!0;let r=Lj(),i=`${n}#${t}`;if(i in r)return r[i]===!0;let a=`${e}#${t}`;return a in r?r[a]===!0:r[n]===!0||r[e]===!0}function Wj(e,t,n,r){if(e===`core`)return!0;let i={...Lj()},a=`${e}#${t}`,o=`${e}#`,s=r??YA.filter(t=>t.feedId===e).map(e=>e.chunkId);if(i[e]===!0&&!n){i[e]=!1;for(let n of s)n!==t&&(i[`${e}#${n}`]=!0);return i[a]=!1,zj(i)}if(i[a]=n,n&&s.length>0&&s.every(n=>n===t||i[`${e}#${n}`]===!0)){i[e]=!0;for(let e of Object.keys(i))e.startsWith(o)&&delete i[e]}else!n&&s.length>0&&s.every(t=>i[`${e}#${t}`]===!1)&&(i[e]=!1);return zj(i)}function Gj(e){let t=tj(e),n=Bj(t);if(n===`full`)return null;if(n===`unsubscribed`)return[];let r=Lj(),i=`${t}#`,a=`${e}#`;return Object.entries(r).filter(([e,t])=>t===!0&&(e.startsWith(i)||e.startsWith(a))).map(([e])=>e.startsWith(i)?e.slice(i.length):e.slice(a.length))}function Kj(e){return Fj.add(e),()=>{Fj.delete(e)}}function qj(){return Pj||(Pj=Ij(Mj),Pj)}function Jj(e){let t=qj();return e in t?t[e]===!0:e===`core`}function Yj(e,t){let n={...qj(),[e]:t},r=Rj(Mj,n);Pj=n;for(let e of Fj)e();return r}async function Lee(e,t=Dj()){let n={...Lj()},r=[],i=!1;for(let[e,t]of Object.entries(ej))e in n&&(t in n||(n[t]=n[e],n[e]&&r.push(t)),delete n[e],i=!0);for(let e of YA){let t=e.chunkId.replace(/^notebook\./,``),r=`${e.feedId}#${e.chunkId}`,a=[e.feedId];for(let[t,n]of Object.entries(ej))n===e.feedId&&a.push(t);for(let o of a)for(let a of[`collection.${t}`,`feed.${t}`,e.chunkId]){let e=`${o}#${a}`;e===r||!(e in n)||(r in n||(n[r]=n[e]),delete n[e],i=!0)}}for(let e of YA)e.id in n&&(e.feedId in n||(n[e.feedId]=n[e.id],n[e.id]&&r.push(e.feedId)),delete n[e.id]);for(let{id:i}of e)if(!(i===`core`||i in n))try{let e=await t.getSeedMeta(qv(i));e&&e.seedVersion>0&&(n[i]=!0,r.push(i))}catch{}return(r.length||i)&&zj(n),r}var Ree=`sound-`;function zee(e){if(!e.startsWith(`sound-`))return;let t=e.slice(6);return t.length>0?t:void 0}function Bee(e){let t=zee(e);return t?[{kind:`metric`,type:`sound`,value:t}]:[]}function Vee(e){let t=[],n=new Set(eM().map(e=>e.slug));for(let t of e){let e=t.label.trim();e.length>0&&n.add(e)}for(let r of e){let e=r.label.trim();if(e.length===0)continue;let i=r.contributions?.length?[...r.contributions]:[...Bee(e)],a=r.type?.trim();a&&a!==e&&a!==`category`&&n.has(a)&&!i.some(e=>e.kind===`tag`&&e.slug===a)&&i.push({kind:`tag`,slug:a}),t.push({slug:e,...a===`category`?{isCategory:!0}:{},contributions:i})}return t}function Xj(e){let t=eM(),n=new Set(t.map(e=>e.slug)),r=e.filter(e=>!n.has(e.slug)||e.contributions.length>0),i=new Set(r.map(e=>e.slug));return ma([...t.filter(e=>!i.has(e.slug)),...r])}function Hee(e){return e.filter(e=>e.name.trim().length>0).map(e=>({slug:e.name.trim(),isCategory:!0,contributions:e.contributions??[]}))}async function Zj(){let[e,t]=await Promise.all([Uee.loadTags(),Z.getAllTagTypes().catch(()=>[])]);return[...Hee(t),...e]}var Uee=new class{async loadTags(){return Vee(await Z.getAllTags())}},Qj=ma(eM()),$j=new Set;function eM(){return[{slug:`tonnage`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]},{slug:`metabolic`,contributions:[{kind:`metric`,type:`met`,value:8},{kind:`metric`,type:`metMinutes`,value:`met * convert(elapsed, min)`},{kind:`metric`,type:`summaries.totalMetMinutes`,value:`sum(metMinutes)`}]},{slug:`kettlebell-24kg`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]}]}function tM(){return Qj}var nM=null;function rM(){return nM||=Zj().then(e=>{Qj=Xj(e);for(let e of $j)e();return Qj}).finally(()=>{nM=null}),nM}async function iM(){Qj=Xj(await Zj());for(let e of $j)e();return Qj}function aM(e){return $j.add(e),()=>$j.delete(e)}var Wee=new class{_db;constructor(e){this._db=e}get db(){return this._db??Z}async load(){return this.db.getAllEquipment()}async save(e){await this.db.saveEquipment(e)}async delete(e){await this.db.deleteEquipment(e)}};async function oM(e){let t=await Z.getAllEquipment();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),Kee()}var sM=new Set;function Gee(e){return sM.add(e),()=>sM.delete(e)}function Kee(){for(let e of sM)e()}var cM=null;function lM(){return cM||=new yl({storage:Wee}),cM}var qee=class{storage;source;sourceId;now;constructor(e,t,n,r=Date.now){this.storage=e,this.source=t,this.sourceId=n,this.now=r}async applyAll(e={}){let t=Cy(e.manifest??await this.source.fetchManifest()),n=qv(this.sourceId),r=e.stored===void 0?await this.storage.getSeedMeta(n):e.stored,i=r?.schema===9?r:void 0,a=i??Yv(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=t.chunks.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))),s=!!(t.notebooks&&t.notebooks.length>0),c=o.filter(n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),i=a.chunks[n.id];if(e.forceAll||!i)return!0;if(r){if((r.version??0)>(i.version??0))return!0}else if(!s&&(t.version!==a.seedVersion||t.builtAt!==a.builtAt))return!0;return i.sha256!==n.sha256});c.sort((e,t)=>Number(t.id===Kv)-Number(e.id===Kv));let l=Object.keys(a.chunks).filter(e=>!t.chunks.some(t=>t.id===e)),u={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,addedNotes:0,updatedNotes:0};if(!c.length&&!l.length&&t.version===a.seedVersion&&t.builtAt===a.builtAt)return u;u.status=`imported`;let d=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:u.appliedChunks,totalChunks:c.length,totalNotes:u.totalNotes,totalEfforts:u.totalEfforts,totalEquipment:u.totalEquipment,totalBlocks:u.totalBlocks,skippedUserOwned:u.skippedUserOwned,deleted:u.deleted,addedNotes:u.addedNotes,updatedNotes:u.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}});for(let n=0;n<c.length;){let r=c.slice(n,n+(c[n]?.id===`canvas`?1:4));for(let n of r){let r,o=t.notebooks?.find(e=>e.notebookId===n.id),s=n.records,c=!!(a.chunks[n.id]&&e.granularRecords&&(o?.indexPath||n.records));if(c||e.granularRecords&&n.records&&n.records.length>0){if(c&&o?.indexPath&&(s=wy(await this.source.fetchChunk(o.indexPath)).records),s&&s.length>0){let t=!e.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(s.map(e=>e.uuid)):void 0,i=t?s.filter(e=>t.get(e.uuid)!==e.commit):s;if(c&&i.length>s.length/2){if(d(`fetching`,n.id),r=Ty(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`)}else{let e=[],t=0;for(let r of i){d(`fetching`,n.id,r.uuid,t,i.length);let a=await this.source.fetchChunk(r.recordPath),o=Array.isArray(a)?Ty(a):[Ey(a)];e.push(...o),t++}r=e}}else if(d(`fetching`,n.id),r=Ty(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`)}else if(d(`fetching`,n.id),r=Ty(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`);let l=s&&s.length>0?s.map(e=>e.uuid):await Promise.all(r.map(e=>Dy(e.path))),f={...a,seedVersion:t.version,builtAt:t.builtAt,chunks:{...a.chunks,[n.id]:{sha256:n.sha256,version:o?.version,builtAt:o?.builtAt??t.builtAt,importedAt:this.now(),noteIds:l}},importedAt:this.now()};d(`applying`,n.id);let p=await this.storage.applyChunk({chunkId:n.id,rows:r,manifest:t,expectedMeta:i,meta:f});u.totalNotes+=p.totalNotes,u.totalEfforts+=p.totalEfforts,u.totalEquipment+=p.totalEquipment,u.totalBlocks+=p.totalBlocks,u.skippedUserOwned+=p.skippedUserOwned,u.deleted+=p.deleted,u.addedNotes+=p.addedNotes,u.updatedNotes+=p.updatedNotes,u.appliedChunks++,a=f,i=f,d(`committed`,n.id),n.id===`canvas`&&e.onFirstPaintApplied?.()}n+=r.length}for(let e of l){let n={...a.chunks};delete n[e];let r={...a,chunks:n,importedAt:this.now()},o=await this.storage.applyChunk({chunkId:e,rows:[],manifest:t,expectedMeta:i,meta:r});u.deleted+=o.deleted,a=r,i=r}let f={...a,schema:9,seedVersion:t.version,builtAt:t.builtAt,importedAt:this.now()};return await this.storage.applyChunk({chunkId:null,rows:[],manifest:t,expectedMeta:i,meta:f}),d(`finalizing`,null),u}},Jee=45e3;function Yee(e){return(e instanceof Error?e.message:String(e)).replace(/(authToken["'=:\s]+)[^&\s,"']+/gi,`$1…`).replace(/(Bearer\s+)[\w.-]+/gi,`$1…`).replace(/https?:\/\/[^\s]+/gi,e=>{try{let t=new URL(e);return`${t.protocol}//${t.host}/…`}catch{return`…`}}).slice(0,300)}function Xee(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function Zee(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=qv(e.id),s={outcome:`current`,error:null,manifestChecked:!1,hadCheckpoint:!1};try{let c=await r.getSeedMeta(o);if(s.hadCheckpoint=(c?.seedVersion??0)>0,!t.force&&!t.probeManifests&&Aj(c,e.embeddedVersion))return s.outcome=`current`,s;if(Xee(c,i,a()))return s.outcome=`busy`,s;let l=Cy(await e.source.fetchManifest());s.manifestChecked=!0;let u=t.force?`import`:kj(c?.seedVersion,l.version);if(u===`server-stale`)return s.outcome=`server-stale`,s;if(c&&c.schema!==9)throw Error(`Incompatible seed checkpoint; recreate storage`);if(t.background&&!e.autoSyncOn)return s.outcome=l.chunks.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))).some(e=>{let t=l.notebooks?.find(t=>t.notebookId===e.id),n=c?.chunks[e.id];return!n||t&&(t.version??0)>(n.version??0)?!0:n.sha256!==e.sha256})?`update-pending`:`current`,s;if(!t.force&&u===`current`&&c?.schema===9&&c.builtAt===l.builtAt)return s.outcome=`current`,s;let d={...c??Yv(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(d,c??null);try{let i=await new qee(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:e.granularRecords,manifest:l,stored:d});s.outcome=`imported`,i.status===`imported`&&(s.applied=!0,s.importedVersion=l.version,s.added=i.addedNotes,s.updated=i.updatedNotes)}finally{let e=await r.getSeedMeta(o);e?.claim?.owner===i&&await r.putSeedMeta({...e,claim:null},e)}return s}catch(t){return console.warn(`[feedSync] ${e.id} seed sync failed`,t),s.outcome=`error`,s.error=Yee(t),s}}function uM(){try{return typeof localStorage<`u`&&localStorage.getItem(`wodwiki.seedImport.enabled`)!==`0`}catch{return!1}}function dM(){let e=new Set(BA()),t=jA(AA);return[{id:`core`,label:`Core`,source:new Tj(t),url:t,embeddedVersion:Oj.core??0},...WA.map(e=>({id:e.id,label:e.label,source:new Tj(e.url),url:e.url,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{},embeddedVersion:0,autoImport:e.autoImport??!1,tier:e.tier,...e.description?{description:e.description}:{}})),...NA().map(e=>({id:e.id,label:e.label,source:new Tj(e.url),url:e.url,repositoryUrl:e.repositoryUrl,embeddedVersion:Oj[e.id]??0,autoImport:!1}))].filter(t=>!e.has(t.id))}function fM(e){try{if(typeof BroadcastChannel<`u`){let t=new BroadcastChannel(Gv);t.postMessage(e),t.close()}}catch{}}async function pM(){_k(),await iM().catch(()=>{});let e=KO();e.isInitialized()&&await VO(e);let t=lM();t.isInitialized()&&await oM(t)}function mM(e){return e.includes(`error`)?`error`:e.includes(`imported`)?`imported`:e.includes(`update-pending`)?`update-pending`:e.includes(`server-stale`)?`server-stale`:e.includes(`busy`)?`busy`:`current`}function hM(e,t,n,r){let i=n.now??Date.now,a=n.broadcast??fM,o=n.reportActivity!==!1;if(t.manifestChecked&&CM(e.id,i()),t.outcome===`error`){let i=t.error??`feed sync failed`;n.mode===`background`&&r?.set(e.id,{sourceId:e.id,label:e.label,state:`error`}),o&&Qx(i);return}t.outcome===`imported`&&t.applied&&(a({kind:`seed-imported`,source:e.id,version:t.importedVersion}),pM(),o&&Xx({source:e.label,added:t.added??0,updated:t.updated??0}),r&&t.hadCheckpoint&&r.set(e.id,{sourceId:e.id,label:e.label,state:`updated`})),r&&t.outcome===`update-pending`&&r.set(e.id,{sourceId:e.id,label:e.label,state:`pending`})}function Qee(){return typeof Worker<`u`&&!0}async function $ee(e,t,n){return await new Promise(r=>{let i;try{i=new Worker(new URL(`/assets/feedSync.worker-6iecnGGU.js`,``+import.meta.url),{type:`module`})}catch(e){console.warn(`[feedSync] seed worker unavailable; running on main thread`,e),r(null);return}let a=t.mode===`background`?new Map:void 0,o=[],s=e.length,c=!1,l=e=>{Zx(null),i.terminate(),r(e)};i.onerror=e=>{console.warn(`[feedSync] feed worker failed`,e.message??`unknown error`),l(c?mM(o):null)},i.onmessage=n=>{c=!0;let r=n.data;if(r.type===`progress`){let n=e.find(e=>e.id===r.sourceId);Zx({sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,chunkId:r.progress.chunkId,recordId:r.progress.recordId,completedRecords:r.progress.completedRecords,totalRecords:r.progress.totalRecords,completedChunks:r.progress.completedChunks,totalChunks:r.progress.totalChunks,phase:r.progress.phase}),t.onProgress?.({...r.progress,sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,sourceIndex:e.indexOf(n)+1,totalSources:s});return}if(r.type===`first-paint`){pM(),t.onFirstPaint?.();return}if(r.type===`source-result`){let n=e.findIndex(e=>e.id===r.sourceId),i=e[n];if(!i)return;o.push(r.result.outcome),hM(i,r.result,t,a),t.onProgress?.({phase:`finished`,outcome:r.result.outcome,error:r.result.error,sourceId:i.id,sourceLabel:i.label,sourceIndex:n+1,totalSources:s});return}a&&yM([...a.values()]),l(mM(r.outcomes.length?r.outcomes:o))},i.postMessage({type:`run`,dbName:Ik(),userId:$k.currentSync()?.id??null,owner:n,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`,sources:e.map(e=>({id:e.id,label:e.label,url:jA(e.url),...e.tier?{tier:e.tier}:{},embeddedVersion:e.embeddedVersion,autoSyncOn:Jj(e.id),notebookIds:t.notebookIds===void 0?Bj(e.id)===`partial`?Gj(e.id)??void 0:t.mode===`background`&&Bj(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0}))})})}var gM=null,ete=0,_M=new Set;function tte(){return gM}function vM(e){return _M.add(e),()=>{_M.delete(e)}}function yM(e){gM=e.length?{id:++ete,updates:e}:null;for(let e of _M)e()}function bM(e){gM?.updates.some(t=>t.sourceId===e)&&yM(gM.updates.filter(t=>t.sourceId!==e))}var xM=`wodwiki.seedChecks`;function SM(){try{let e=JSON.parse(localStorage.getItem(xM)??`null`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`number`))}catch{return{}}}function CM(e,t){try{localStorage.setItem(xM,JSON.stringify({...SM(),[e]:t}))}catch{}}function nte(e){return SM()[e]??null}async function wM(e={}){let t=[],n=e.storage??Dj(),r=e.mode===`background`?new Map:void 0;if(!(e.isEnabled??uM)())return`disabled`;let i=e.owner??`seed-${(e.now??Date.now)()}-${Math.random().toString(36).slice(2,8)}`,a=e.sources??dM();if(!e.storage&&!e.now&&Qee()){let t=await $ee(a,e,i);if(t)return t}for(let[o,s]of a.entries()){let c=await rte(s,e,n,i,o+1,a.length,r);console.debug(`[feedSync] ${s.id} outcome: ${c}`),t.push(c)}return r&&yM([...r.values()]),mM(t)}async function TM(e={}){let t=e.sources??dM(),n=e.storage??Dj();await LM({storage:n}).catch(e=>console.warn(`[feedSync] core registry migration failed`,e));let r;try{r=await n.getSeedMeta(qv(`core`))}catch(e){return console.warn(`[feedSync] boot provider probe failed`,e),`error`}if(!r||r.seedVersion<=0)return wM({...e,sources:t.filter(e=>e.autoImport!==!1)});let i=t.filter(e=>e.id===`core`||Bj(e.id)!==`unsubscribed`);return wM({...e,sources:i,probeManifests:!0,mode:`background`,reportActivity:!1})}async function rte(e,t,n,r,i,a,o){let s=t.now??Date.now,c=t.onProgress,l=t.reportActivity!==!1,u=(t,n=null)=>c?.({phase:`finished`,outcome:t,error:n,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a});c?.({phase:`checking`,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a});let d=l?Yx(`download`,e.label):()=>{};try{let l=await Zee({id:e.id,label:e.label,source:e.source,embeddedVersion:e.embeddedVersion,autoSyncOn:Jj(e.id),...e.tier?{tier:e.tier}:{},notebookIds:t.notebookIds===void 0?Bj(e.id)===`partial`?Gj(e.id)??void 0:t.mode===`background`&&Bj(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0},{storage:n,owner:r,now:s,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`},{onProgress:t=>{Zx({sourceId:e.id,sourceLabel:e.label,chunkId:t.chunkId,recordId:t.recordId,completedRecords:t.completedRecords,totalRecords:t.totalRecords,completedChunks:t.completedChunks,totalChunks:t.totalChunks,phase:t.phase}),c?.({...t,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a})},onFirstPaint:()=>{_k(),t.onFirstPaint?.()}});return hM(e,l,t,o),u(l.outcome,l.error),l.outcome}finally{Zx(null),d()}}async function EM(e,t={}){let n=(t.sources??dM()).find(t=>t.id===e);if(!n)return console.warn(`[feedSync] unknown feed source: ${e}`),`error`;let r=await wM({...t,sources:[n]});return(r===`imported`||r===`current`)&&(t.subscribe===!1?Vj(e)||Hj(e,!1):!t.preserveSubscriptionState&&!t.notebookIds&&Hj(e,!0),bM(e)),r}async function DM(e,t,n={}){return EM(e,{...n,notebookIds:[t],preserveSubscriptionState:!0,force:!0})}async function OM(e,t,n,r={}){if(n)return Wj(e,t,!0),{outcome:await DM(e,t,r)};{Wj(e,t,!1);let n=r.storage??Dj(),i=await n.getSeedMeta(qv(e));if(!i||!i.chunks[t])return{deleted:0};let a={...i.chunks};if(delete a[t],Object.keys(a).length===0){let t=await n.removeSourceContent(i);_k();let r=KO();r.isInitialized()&&await VO(r);let a=lM();return a.isInitialized()&&await oM(a),fM({kind:`seed-removed`,source:e}),{deleted:t}}let o={...i,chunks:a,importedAt:Date.now()},s={schema:9,version:i.seedVersion,builtAt:i.builtAt,chunks:[]},c=await n.applyChunk({chunkId:t,rows:[],manifest:s,expectedMeta:i,meta:o});_k();let l=KO();l.isInitialized()&&await VO(l);let u=lM();return u.isInitialized()&&await oM(u),fM({kind:`seed-removed`,source:e}),{deleted:c.deleted}}}async function kM(e,t={}){if(e===`core`)return{deleted:0};let n=t.storage??Dj(),r=await n.getSeedMeta(qv(e)),i=r?await n.removeSourceContent(r):0;Hj(e,!1),Yj(e,!1),bM(e),_k();let a=KO();a.isInitialized()&&await VO(a);let o=lM();return o.isInitialized()&&await oM(o),fM({kind:`seed-removed`,source:e}),{deleted:i}}async function AM(e,t={}){if(e===`core`)return{deleted:0};let n=await kM(e,t);return NA().some(t=>t.id===e)?IA(e):zA(e),n}async function jM(e={}){let t=e.storage??Dj(),n=!1,r=!1;return await Promise.all((e.sources??dM()).map(async e=>{try{let i=await t.getSeedMeta(qv(e.id));if(!i||i.seedVersion<=0)return;e.autoImport===!1?r=!0:n=!0}catch{}})),{coreImported:n,libraryImported:r}}async function MM(e={}){let t=e.storage??Dj();return{sources:await Promise.all((e.sources??dM()).map(async n=>{let r=await t.getSeedMeta(qv(n.id)),i=null,a=null,o=null,s=n.repositoryUrl;try{o=Cy(await n.source.fetchManifest()),i={version:o.version,schema:o.schema,builtAt:o.builtAt},s??=kA(o.repositoryUrl??``)??void 0,CM(n.id,(e.now??Date.now)())}catch(e){a=e instanceof Error?e.message:String(e)}let c=NM(n.id,o,r);return{id:n.id,label:n.label,url:n.url,...s?{repositoryUrl:s}:{},...n.description?{description:n.description}:{},autoImport:n.autoImport!==!1,notebooks:c,stored:r?{version:r.seedVersion,schema:r.schema,builtAt:r.builtAt,importedAt:r.importedAt}:null,remote:i,remoteError:a,upToDate:r!=null&&i!=null&&r.schema===9&&r.seedVersion===i.version,count:c.reduce((e,t)=>e+t.count,0),bytes:c.reduce((e,t)=>e+t.bytes,0),checkedAt:nte(n.id),subscribed:Vj(n.id),autoSync:Jj(n.id)}}))}}function NM(e,t,n){let r={};for(let t of $A(e))r[t.chunkId]=t;let i=(t?.chunks??[]).map(t=>({id:r[t.id]?.id??t.id,label:r[t.id]?.label??t.id,chunkId:t.id,count:t.count,bytes:t.bytes,imported:!!n?.chunks[t.id],subscribed:Uj(e,t.id)}));return i.length>0?i:$A(e).map(t=>({id:t.id,label:t.label,chunkId:t.chunkId,count:0,bytes:0,imported:!!n?.chunks[t.chunkId],subscribed:Uj(e,t.chunkId)}))}async function PM(e={}){let t=e.storage??Dj(),n=0;for(let e of WA){let r=qv(e.id);try{let i=await t.getSeedMeta(r);if(i&&i.seedVersion>0)continue;let a=[];for(let n of $A(e.id)){if(n.id===e.id)continue;let r=await t.getSeedMeta(qv(n.id));r&&r.seedVersion>0&&a.push(r)}if(a.length===0)continue;let o=a.reduce((e,t)=>t.seedVersion>e.seedVersion?t:e),s=a.find(e=>e.tier)?.tier,c={key:r,schema:o.schema,seedVersion:o.seedVersion,builtAt:o.builtAt,importedAt:Math.max(...a.map(e=>e.importedAt)),chunks:Object.assign({},...a.map(e=>e.chunks)),...s?{tier:s}:{},claim:null};await t.putSeedMeta(c,i??null);for(let e of a)await t.putSeedMeta({...e,seedVersion:0,chunks:{},claim:null},e);n+=1}catch(t){console.warn(`[feedSync] legacy checkpoint adoption failed for ${e.id}`,t)}}return n}async function FM(e={}){return await(e.storage??Dj()).backfillFeedProvenance()}async function IM(e={}){return await(e.storage??Dj()).migrateNotebookVocabulary()}async function LM(e={}){let t=e.storage??Dj(),n=qv(`seed-core`),r=await t.getSeedMeta(n),i=r?.chunks??{};if(!r||r.seedVersion<=0&&Object.keys(i).length===0&&!r.claim)return!1;let a=qv(`core`),o=await t.getSeedMeta(a),s={...o?.chunks};for(let[e,t]of Object.entries(i)){let n=s[e];s[e]=n?{sha256:n.sha256,noteIds:[...new Set([...n.noteIds??[],...t.noteIds??[]])]}:{...t,noteIds:t.noteIds??[]}}let c=o?{...o,builtAt:``,claim:null,chunks:s}:{...Yv(a),chunks:s};return await t.putSeedMeta(c,o??null),await t.putSeedMeta(Yv(n),r),!0}var RM=(0,U.createContext)(null);function zM({children:e}){let[{isReady:t,error:n,revision:r},i]=(0,U.useState)({isReady:!1,error:null,revision:0}),a=KO(),o=(0,U.useCallback)(async()=>{try{await VO(a),i(e=>({isReady:!0,error:null,revision:e.revision+1}))}catch(e){i(t=>({...t,isReady:!1,error:e instanceof Error?e:Error(String(e))}))}},[a]),s=(0,U.useCallback)(async()=>{await o()},[o]);return(0,U.useEffect)(()=>{o()},[o]),(0,U.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(Gv);return e.onmessage=()=>{s()},()=>e.close()},[s]),(0,W.jsx)(RM.Provider,{value:{registry:a,isReady:t,error:n,revision:r,refresh:s},children:e})}function BM(){let e=(0,U.useContext)(RM);if(!e)throw Error(`useEffortRegistry must be within EffortRegistryProvider`);return e}var VM=(0,U.createContext)(null);function HM({children:e}){let[t,n]=(0,U.useState)(!1),[r,i]=(0,U.useState)(null),a=lM(),o=(0,U.useCallback)(async()=>{try{await oM(a),n(!0),i(null)}catch(e){i(e instanceof Error?e:Error(String(e))),n(!1)}},[a]),s=(0,U.useCallback)(async()=>{n(!1),await o()},[o]);return(0,U.useEffect)(()=>{o()},[o]),(0,U.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(Gv);return e.onmessage=()=>{s()},()=>e.close()},[s]),(0,W.jsx)(VM.Provider,{value:{registry:a,isReady:t,error:r,refresh:s},children:e})}function UM(){let e=(0,U.useContext)(VM);if(!e)throw Error(`useEquipmentRegistry must be within EquipmentRegistryProvider`);return e}var WM=yt,GM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(p,{ref:n,className:G(`pointer-events-none fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]`,e),...t}));GM.displayName=p.displayName;var KM=ye(`group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full`,{variants:{variant:{default:`border bg-background text-foreground`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),qM=U.forwardRef(({className:e,variant:t,...n},r)=>(0,W.jsx)(rr,{ref:r,className:G(KM({variant:t}),e),...n}));qM.displayName=rr.displayName;var JM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(ut,{ref:n,className:G(`inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive`,e),...t}));JM.displayName=ut.displayName;var YM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(Xn,{ref:n,className:G(`absolute right-2 top-2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-destructive-foreground group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-background`,e),"toast-close":``,"aria-label":`Dismiss notification`,...t,children:(0,W.jsx)(ge,{className:`h-4 w-4`})}));YM.displayName=Xn.displayName;var XM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(Me,{ref:n,className:G(`text-sm font-semibold`,e),...t}));XM.displayName=Me.displayName;var ZM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(sr,{ref:n,className:G(`text-sm opacity-90`,e),...t}));ZM.displayName=sr.displayName;var QM=3,$M=1e6,eN=0;function tN(){return eN=(eN+1)%(2**53-1),eN.toString()}var nN=new Map,rN=e=>{if(nN.has(e))return;let t=setTimeout(()=>{nN.delete(e),sN({type:`REMOVE_TOAST`,toastId:e})},$M);nN.set(e,t)},iN=(e,t)=>{switch(t.type){case`ADD_TOAST`:return{...e,toasts:[t.toast,...e.toasts].slice(0,QM)};case`UPDATE_TOAST`:return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case`DISMISS_TOAST`:{let{toastId:n}=t;return n?rN(n):e.toasts.forEach(e=>rN(e.id)),{...e,toasts:e.toasts.map(e=>!n||e.id===n?{...e,open:!1}:e)}}case`REMOVE_TOAST`:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},aN=[],oN={toasts:[]};function sN(e){oN=iN(oN,e),aN.forEach(e=>e(oN))}function Q(e){let t=tN(),n=()=>sN({type:`DISMISS_TOAST`,toastId:t}),r=e=>sN({type:`UPDATE_TOAST`,toast:{...e,id:t}});return sN({type:`ADD_TOAST`,toast:{...e,id:t,open:!0,onOpenChange:e=>{e||n()}}}),{id:t,dismiss:n,update:r}}function cN(){let[e,t]=U.useState(oN);return U.useEffect(()=>(aN.push(t),()=>{let e=aN.indexOf(t);e>-1&&aN.splice(e,1)}),[e]),{...e,toast:Q,dismiss:e=>sN({type:`DISMISS_TOAST`,toastId:e})}}function lN(){let{toasts:e}=cN();return(0,W.jsxs)(WM,{children:[e.map(function({id:e,title:t,description:n,action:r,...i}){return(0,W.jsxs)(qM,{...i,children:[(0,W.jsxs)(`div`,{className:`grid gap-1`,children:[t&&(0,W.jsx)(XM,{children:t}),n&&(0,W.jsx)(ZM,{children:n})]}),r,(0,W.jsx)(YM,{})]},e)}),(0,W.jsx)(GM,{})]})}var uN={activeL1Id:null,activeL2Id:null,activeL3Id:null,leftDrawerOpen:!1,rightDrawerOpen:!1,expandedIds:new Set,journalFilter:{selectedDate:null,selectedTags:[]},searchFilter:{scope:`all`}};function dN(e,t){switch(t.type){case`SET_ACTIVE_L1`:return e.activeL1Id===t.id?e:{...e,activeL1Id:t.id};case`SET_ACTIVE_L2`:return e.activeL2Id===t.id?e:{...e,activeL2Id:t.id};case`SET_ACTIVE_L3`:return e.activeL3Id===t.id?e:{...e,activeL3Id:t.id};case`SET_LEFT_DRAWER`:return e.leftDrawerOpen===t.open?e:{...e,leftDrawerOpen:t.open};case`SET_RIGHT_DRAWER`:return e.rightDrawerOpen===t.open?e:{...e,rightDrawerOpen:t.open};case`TOGGLE_EXPANDED`:{let n=new Set(e.expandedIds);return n.has(t.id)?n.delete(t.id):n.add(t.id),{...e,expandedIds:n}}case`SET_JOURNAL_DATE`:return{...e,journalFilter:{...e.journalFilter,selectedDate:t.date}};case`SET_JOURNAL_TAGS`:return{...e,journalFilter:{...e.journalFilter,selectedTags:t.tags}};case`SET_SEARCH_SCOPE`:return{...e,searchFilter:{scope:t.scope}};default:return e}}var fN=e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-80;window.scrollTo({top:e,behavior:`smooth`})}},pN=(0,U.createContext)({tree:[],navState:uN,dispatch:()=>{},l3Items:[],setL3Items:()=>{},secondarySpec:void 0,setSecondarySpec:()=>{},contextNav:void 0,setContextNav:()=>{},streamControls:null,setStreamControls:()=>{},scrollToSection:fN,registerScrollFn:()=>{},openCreateJournal:()=>{},registerCreateJournal:()=>{}});function mN(){return(0,U.useContext)(pN)}function hN(e){let{tree:t,dispatch:n}=mN();(0,U.useEffect)(()=>{e&&t.some(t=>t.id===e)&&n({type:`SET_ACTIVE_L1`,id:e})},[e,t,n])}function gN({tree:e,children:t}){let[n,r]=(0,U.useReducer)(dN,uN),[i,a]=(0,U.useState)([]),[o,s]=(0,U.useState)(void 0),[c,l]=(0,U.useState)(void 0),[u,d]=(0,U.useState)(null),f=ht(),p=(0,U.useRef)(fN),m=(0,U.useRef)(null);(0,U.useEffect)(()=>{let t=e.find(e=>e.isActive?e.isActive(f,n):e.action.type===`route`?e.action.to===`/`?f.pathname===`/`||f.pathname===``:f.pathname.startsWith(e.action.to):!1);r({type:`SET_ACTIVE_L1`,id:t?.id??null})},[f.pathname]),(0,U.useEffect)(()=>{r({type:`SET_LEFT_DRAWER`,open:!1})},[f.pathname]);let h=(0,U.useCallback)(e=>{a(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n]?.id&&t.label===e[n]?.label&&t.secondaryAction?.id===e[n]?.secondaryAction?.id&&t.secondaryRunIcon===e[n]?.secondaryRunIcon)?t:e)},[]),g=(0,U.useCallback)(e=>{r({type:`SET_ACTIVE_L3`,id:e}),p.current(e)},[]),_=(0,U.useCallback)(e=>{p.current=e},[]),v=(0,U.useCallback)(e=>{m.current?.(e)},[]),y=(0,U.useCallback)(e=>{m.current=e},[]),b=(0,U.useMemo)(()=>({tree:e,navState:n,dispatch:r,l3Items:i,setL3Items:h,secondarySpec:o,setSecondarySpec:s,contextNav:c,setContextNav:l,streamControls:u,setStreamControls:d,scrollToSection:g,registerScrollFn:_,openCreateJournal:v,registerCreateJournal:y}),[e,n,i,h,o,c,l,u,g,_,v,y]);return(0,W.jsx)(pN.Provider,{value:b,children:t})}function _N(e){if(!e)return null;let t=X(e);return t.error?`Couldn't parse "${e}" — ${t.error}`:null}var vN=1e3;function yN(e){let t=(0,U.useRef)(e);t.current=e;let[n,r]=Ct(),i=n.get(`q`)??``,[a,o]=(0,U.useState)(()=>{let{defaultQuery:e,legacy:r}=t.current;return i?X(i).error?r?.salvageQ?.(i,n)??e:i:r?.toQuery(n)??e}),[s,c]=(0,U.useState)(()=>!i||!X(i).error||t.current.legacy?.salvageQ?.(i,n)?null:_N(i)),l=(0,U.useRef)(a);l.current=a;let u=(0,U.useRef)(n);u.current=n;let d=(0,U.useRef)(!1);(0,U.useEffect)(()=>{if(d.current)return;d.current=!0;let{legacy:e}=t.current,n=u.current,i=n.get(`q`)??``,a=null;if(i?X(i).error&&(a=e?.salvageQ?.(i,n)??null):a=e?.toQuery(n)??null,!a)return;let o=new URLSearchParams(n);for(let t of e?.keys??[])o.delete(t);o.set(`q`,a),r(o,{replace:!0})},[r]);let f=(0,U.useRef)(!0),p=(0,U.useRef)(null),m=(0,U.useRef)(i);(0,U.useEffect)(()=>{if(i===m.current)return;m.current=i,f.current=!0,clearTimeout(p.current),p.current=null,c(_N(i));let e=i&&!X(i).error?i:t.current.defaultQuery;o(t=>t===e?t:e)},[i]);let h=(0,U.useRef)(t.current.defaultQuery);return(0,U.useEffect)(()=>{let e=t.current.defaultQuery;e!==h.current&&(h.current=e,!i&&o(t=>t===e?t:e))},[i,t.current.defaultQuery]),(0,U.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`q`)??``;e!==m.current&&(m.current=e,f.current=!0,clearTimeout(p.current),p.current=null,c(_N(e)),o(e&&!X(e).error?e:t.current.defaultQuery))};return window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e),clearTimeout(p.current)}},[]),{query:a,setQuery:(0,U.useCallback)(e=>{if(o(e),!X(e).error&&e!==l.current){let t=new URLSearchParams(u.current);t.set(`q`,e),m.current=e,r(t,{replace:!f.current}),f.current=!1,clearTimeout(p.current),p.current=setTimeout(()=>{f.current=!0,p.current=null},vN)}},[r]),urlQueryError:s}}var bN=[`origin`,`discipline`];function xN(e){return/\s/.test(e)?`text:"${e}"`:`text:${e}`}function SN(e){let t=e.filter(Boolean);return`:effort${t.length?`{${t.join(`,`)}}`:``}`}function CN(e,t){let n=e.trim();if(!n||n.startsWith(`:`)||n.includes(`{`)||n.includes(`}`))return null;let r=t.get(`origin`),i=t.get(`discipline`)?.trim();return SN([xN(n),...r&&r!==`all`?[`origin:${r}`]:[],...i?[`discipline:${i}`]:[]])}function wN(e){if(!bN.some(t=>e.get(t)))return null;let t=e.get(`origin`),n=e.get(`discipline`)?.trim();return SN([...t&&t!==`all`?[`origin:${t}`]:[],...n?[`discipline:${n}`]:[]])}var TN={keys:bN,toQuery:wN,salvageQ:CN};function EN(e){return e.endsWith(`/`)&&e.length>1?e.slice(0,-1):e}function DN(e){let t=[`note`,`session`,`post`,`text`,`timePreset`,`rangeStart`,`rangeEnd`,`s`,`tags`,`mode`];return{keys:t,toQuery(n){if(!t.some(e=>n.has(e)))return null;let r=null;if(n.has(`note`)||n.has(`session`)||n.has(`post`)){let e=[];(n.get(`note`)??`include`)!==`hide`&&e.push(`journal`),(n.get(`session`)??`include`)!==`hide`&&e.push(`notebooks`),e.length===1&&(r=`source:${e[0]}`)}else e&&(r=`source:${e}`);let i=n.get(`timePreset`)??`2w`,a=i===`all`||i===`custom`?null:`last ${i}`,o=n.get(`text`)?.trim(),s=n.get(`tags`)?.trim(),c=o?/\s/.test(o)?`text:"${o}"`:`text:${o}`:null,l=s?`tags:${s}`:null,u=`:note`,d=[c,l].filter(Boolean);r===`source:journal`?u=`:journal`:r===`source:notebooks`?u=`:notebooks`:r===`source:playground`?u=`:playground`:r&&d.unshift(r);let f=d.length?`{${d.join(`,`)}}`:``;return[`${u}${f}`,a].filter(Boolean).join(` `)}}}var ON={route:`/journal`,title:`Journal`,defaultWql:`:note{notebook:journal} by {date} last 4w`,level:`note`,target:`note`,scopeOptions:[`journal`],legacy:DN(`journal`)},kN={route:`/notebooks`,title:`Notebooks`,defaultWql:`:notebook{} by {feed}`,level:`session`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,feedNotice:!0,legacy:DN(`notebooks`)},AN={route:`/notes`,title:`Notes`,defaultWql:`:note{}`,level:`note`,target:`note`,scopeOptions:[`journal`,`notebooks`],emptyMessage:`No note entries match your search.`,legacy:DN(`notebooks`)},jN={route:`/feeds`,title:`Feeds`,defaultWql:`:notebook{source:notebooks}`,level:`session`,target:`notebook`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,emptyMessage:`No feeds match your search.`,feedNotice:!0,legacy:DN(`notebooks`)},MN={route:`/pages`,title:`Pages`,defaultWql:`:page{}`,level:`note`,target:`page`,scopeOptions:[],emptyMessage:`No pages match your search.`},NN={route:`/efforts`,title:`Efforts`,defaultWql:`:effort`,level:`effort`,target:`effort`,scopeOptions:[],emptyMessage:`No efforts match your search.`,legacy:TN},PN={route:`/equipment`,title:`Equipment`,defaultWql:`:equipment{}`,level:`note`,target:`equipment`,scopeOptions:[`equipment`],emptyMessage:`No equipment matches your search.`},FN={route:`/tags`,title:`Tags`,defaultWql:`:tag{}`,level:`note`,target:`tag`,scopeOptions:[],emptyMessage:`No tags match your search.`},IN={route:`/sessions`,title:`Sessions`,defaultWql:`:session{} last 1d`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No completed session results recorded in this period.`},LN={route:`/playgrounds`,title:`Playgrounds`,defaultWql:`:playground{} by {date} last 1w`,level:`note`,target:`note`,scopeOptions:[`playground`],shelfVisible:!0,legacy:DN(`playground`)};function RN(e){return{route:`/session/${e}`,defaultWql:`:session{} from ${e} to ${e}`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No session results recorded on ${e}.`}}function zN(e){return{route:`/results/${e}`,defaultWql:`:session{result:${e}, plane:segment}`,level:`segment`,target:`session`,scopeOptions:[],emptyMessage:`No segment records found for result ${e}.`}}function BN(e){return{route:`/notebook/${e}`,title:YO(e),defaultWql:`:note{notebook:${e}} by {date}`,level:`session`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,notebookSlug:e,legacy:DN(`notebooks`)}}var VN={"/journal":ON,"/notebooks":kN,"/notes":AN,"/feeds":jN,"/pages":MN,"/efforts":NN,"/equipment":PN,"/tags":FN,"/sessions":IN,"/playgrounds":LN};function HN(e){let t=EN(e),n=VN[t];if(n)return n;if(t.startsWith(`/results/`)){let e=t.slice(9);if(e)return zN(e)}if(t.startsWith(`/session/`)){let e=t.slice(9);if(e)return RN(e)}if(t.startsWith(`/notebook/`)){let e=t.slice(10);if(e&&!e.includes(`/`))return BN(e)}}function UN(e){return HN(e)??ON}function WN(e){let t=VN[EN(e)]?.title;if(t)return t;if(EN(e).startsWith(`/notebook/`)){let t=EN(e).slice(10);if(t&&!t.includes(`/`))return YO(t)}}function GN(e){let t=EN(e);if(VN[t])return!0;if(t.startsWith(`/results/`)||t.startsWith(`/session/`))return t.slice(9)!==``;if(t.startsWith(`/notebook/`)){let e=t.slice(10);return!!(e&&!e.includes(`/`))}return!1}var $={home:`/`,playgroundRoot:`/playground`,playground:`/playground/:id`,note:`/note/:noteId`,notes:`/notes`,journal:`/journal`,day:`/day/:date`,plan:`/plan`,aiFirst:`/ai-first`,feeds:`/feeds`,feed:`/feed/:slug`,notebooks:`/notebooks`,notebook:`/notebook/:slug`,notebookTarget:`/notebook/:slug/:target`,notebookItem:`/notebook/:slug/:itemDate/:item`,subscribe:`/subscribe`,pages:`/pages`,page:`/page/:slug`,tags:`/tags`,tagCategory:`/t/:type`,tag:`/t/:type/:tag`,sessions:`/sessions`,sessionDetail:`/results/:sessionId`,sessionDate:`/session/:date`,playgrounds:`/playgrounds`,tracker:`/tracker/:runtimeId`,run:`/run/:runtimeId`,load:`/load`,loadJournal:`/load/journal`,loadJournalDate:`/load/journal/:date`,efforts:`/efforts`,effort:`/effort/:slug`,equipment:`/equipment`,equipmentSlug:`/equipment/:slug`,dashboards:`/dashboards`,dashboardView:`/dashboard/:slug`,settings:`/settings`,settingsAppearance:`/settings/appearance`,settingsProfile:`/settings/profile`,settingsStorage:`/settings/storage`,settingsSync:`/settings/sync`,settingsSystem:`/settings/system`,settingsTags:`/settings/tags`,settingsSoundProfiles:`/settings/sound-profiles`,settingsData:`/settings/data`,settingsDatabase:`/settings/database`,settingsQueries:`/settings/queries`};function KN(e){return`/playground/${encodeURIComponent(e)}`}function qN(e){return`/day/${encodeURIComponent(e)}`}function JN(e,t){return`/day/${encodeURIComponent(e)}?autoStart=${encodeURIComponent(t)}`}function YN(e){return`/note/${encodeURIComponent(e)}`}function XN(e){return`/notebook/${encodeURIComponent(e)}`}function ZN(e,t){return`/notebook/${encodeURIComponent(e)}/${t.split(`/`).map(encodeURIComponent).join(`/`)}`}function QN(e){return`/run/${encodeURIComponent(e)}`}function $N({zip:e}){return`/load?zip=${encodeURIComponent(e)}`}function eP(e){return`/results/${encodeURIComponent(e)}`}function tP(e){return`/page/${encodeURIComponent(e)}`}function nP(){return`/playgrounds`}function rP(){return`/efforts`}function iP(e){return`/equipment/${encodeURIComponent(e)}`}function aP(e,t){return`/t/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function oP(e){let t=new URLSearchParams;e?.q&&t.set(`q`,e.q),e?.weeks&&t.set(`weeks`,String(e.weeks));let n=t.toString();return`/dashboards${n?`?${n}`:``}`}function sP(){return`/dashboards`}function cP(e){return`/dashboard/${encodeURIComponent(e)}`}function lP(e,t,n){let r=new URLSearchParams;if(t)for(let[e,n]of Object.entries(t))r.set(e,n);n?.mode&&r.set(`mode`,n.mode),n?.tab&&r.set(`tab`,n.tab);let i=r.toString();return i?`/effort/${encodeURIComponent(e)}?${i}`:`/effort/${encodeURIComponent(e)}`}function uP(e){return{mode:e.get(`mode`)??void 0,tab:e.get(`tab`)??void 0,q:e.get(`q`)??void 0,origin:e.get(`origin`)??void 0}}function dP(e){return e.startsWith(`/playground/`)}function fP(e){return e===`/efforts`||e.startsWith(`/effort/`)||e===`/t/effort`||e.startsWith(`/t/effort/`)}function pP(e){return e===`/equipment`||e.startsWith(`/equipment/`)||e===`/t/equipment`||e.startsWith(`/t/equipment/`)}function mP(e){let t=e.match(/^\/notebook\/([^/]+)\/([^/]+)\/([^/]+)$/);return t?[t[1],t[2],t[3]]:null}function hP(e){let t=e.match(/^\/feed\/([^/]+)$/);return t?t[1]:null}function gP(e){if(!e)return``;let t=e.split(`-`);return t.length>1?t[t.length-1]:e}function _P(e){return typeof File<`u`&&e instanceof File?!1:`file`in e&&e.file!==void 0||`data`in e&&e.data!==void 0}async function vP(e){let t=Date.now();if(!_P(e))return{label:e.name,mimeType:e.type,data:await e.arrayBuffer(),timeSpan:{start:t,end:t}};let n=`file`in e?e.file:void 0,r=`data`in e?e.data:void 0,i;if(r!==void 0)i=r;else{if(!n)throw Error(`Attachment input requires either file or data, but neither was provided`);i=await n.arrayBuffer()}return{id:e.id,label:e.label??n?.name??`Attachment`,mimeType:e.mimeType??n?.type??`application/octet-stream`,data:i,timeSpan:e.timeSpan??{start:t,end:t}}}function yP(e){return{id:e.id,outputType:e.outputType,timeSpan:{started:e.timeSpan.started,ended:e.timeSpan.ended},metrics:e.metrics.toArray(),hints:(()=>{let t=eo(e);return t.length?t:void 0})(),sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,parent:e.parent,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,completionReason:e.completionReason}}function bP(e){return new fa({outputType:e.outputType,timeSpan:e.timeSpan,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,metrics:e.metrics,parent:e.parent,completionReason:e.completionReason})}function xP(e){return{...e,metrics:e.metrics.filter(e=>e.origin!==`analyzed`)}}function SP(e,t){let{engine:n}=jp(t.block,{effortResolver:t.effortResolver,userProfile:t.userProfile,calcs:t.calcs,tags:t.tags,activeTags:t.activeTags,propertySources:t.propertySources}),r=[];for(let t of e){if(t.outputType===`analytics`)continue;if(t.outputType!==`segment`){r.push(t);continue}let e=xP(t),i=n.run(bP(e)),a=t.metrics.filter(e=>e.origin===`analyzed`&&!i.metrics.some(t=>t.origin===`analyzed`&&t.type===e.type));r.push(yP(a.length?new fa({...i,metrics:[...i.metrics,...a]}):i))}return[...r,...n.finalize().map(yP)]}function CP(e,t,n){return SP(d_(t),{block:e,...n})}var wP={soreness:{unit:`rating`,label:`Soreness`,min:1,max:10},sleep:{unit:`h`,label:`Sleep`},hrv:{unit:`ms`,label:`HRV`},weight:{unit:`kg`,label:`Bodyweight`},hang:{unit:`kg`,label:`Max Hang Weight`},hr:{unit:`bpm`,label:`Avg Heart Rate`},planned:{unit:`count`,label:`Planned Sessions`}};function TP(e){let t=/^(-?\d+(?:\.\d+)?)\s*([a-z%]*)$/i.exec(e.trim());if(t)return{value:parseFloat(t[1]),unit:t[2]||void 0}}function EP(e){let t=new Map;for(let n of e.split(`
75
+ `)?e.slice(0,-1):e}function SO(e){return`${e.replace(/\n+$/,``)}\n`}function CO(e){let t=e.trim();if(t.length===0)return{ok:!0,config:{}};try{let e=JSON.parse(t);return!e||Array.isArray(e)||typeof e!=`object`?{ok:!1,config:{},message:`Widget config must be a JSON object.`}:{ok:!0,config:e}}catch(e){return{ok:!1,config:{},message:e instanceof Error?e.message:`Invalid JSON.`}}}function wO(e,t){let{sections:n}=e.state.field(NT);return n.find(e=>e.type===`widget`&&e.id===t)??null}function TO(e,t,n){if(e.state.readOnly)return{ok:!1,config:{},message:`Cannot modify widget source in read-only mode.`};let r=CO(n);if(!r.ok)return r;let i=wO(e,t);return!i||i.contentFrom==null||i.contentTo==null?{ok:!1,config:{},message:`Unable to locate widget source in the editor.`}:(e.dispatch({changes:{from:i.contentFrom,to:i.contentTo,insert:SO(n)}}),r)}function EO(e){return(0,W.jsxs)(`div`,{className:`rounded-xl border border-dashed border-border/70 bg-muted/30 px-4 py-5 text-sm text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,e]}),(0,W.jsx)(`span`,{className:`ml-2 opacity-70`,children:`is not registered`})]})}function DO(e,t){return(0,W.jsxs)(`div`,{className:`rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-5 text-sm text-destructive shadow-sm`,children:[(0,W.jsx)(`p`,{className:`font-medium`,children:`Widget config error`}),(0,W.jsxs)(`p`,{className:`mt-1 font-mono text-xs leading-5 text-destructive/90`,children:[`widget:`,e]}),(0,W.jsx)(`p`,{className:`mt-2 font-mono text-xs leading-5 text-destructive/90`,children:t})]})}function OO({widgetName:e,rawContent:t,sectionId:n,registry:r,view:i}){let a=U.useRef(null),o=U.useRef(null),s=U.useRef(null),c=U.useMemo(()=>xO(t),[t]),[l,u]=U.useState(()=>({isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c,hasFocus:!1}));U.useEffect(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,originalMarkdown:c,currentMarkdown:c}))},[c]),U.useEffect(()=>{if(!l.isEditing)return;let e=window.requestAnimationFrame(()=>{o.current?.focus();let e=o.current?.value.length??0;o.current?.setSelectionRange(e,e)});return()=>window.cancelAnimationFrame(e)},[l.isEditing]);let d=r.get(e),f=U.useMemo(()=>CO(l.originalMarkdown),[l.originalMarkdown]),p=U.useCallback(e=>{u(t=>t.hasFocus===e?t:{...t,hasFocus:e})},[]),m=U.useCallback(()=>{u(e=>({...e,isEditing:!0,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),h=U.useCallback(e=>{let t=TO(i,n,e);if(!t?.ok)return u(e=>({...e,error:t?.message??`Invalid JSON.`})),!1;let r=xO(SO(e));return u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1}),!0},[i,n]),g=U.useCallback(()=>{h(o.current?.value??l.currentMarkdown)},[h,l.currentMarkdown]),_=U.useCallback(()=>{u(e=>({...e,isEditing:!1,isDirty:!1,error:null,currentMarkdown:e.originalMarkdown}))},[]),v=U.useCallback(e=>{let t=e.target.value;u(e=>{let n=e.error?CO(t):null;return{...e,currentMarkdown:t,isDirty:t!==e.originalMarkdown,error:n?.ok===!1?n.message:n?.ok?null:e.error}})},[]),y=U.useCallback(()=>{p(!1);let e=o.current?.value;if(e===void 0)return;let t=TO(i,n,e);if(!t?.ok){u(n=>({...n,isDirty:e!==n.originalMarkdown,error:t?.message??`Unable to save widget source.`}));return}let r=xO(SO(e));u({isEditing:!1,isDirty:!1,error:null,originalMarkdown:r,currentMarkdown:r,hasFocus:!1})},[n,i,p]),b=U.useCallback(e=>{let t=e.relatedTarget;t instanceof Node&&a.current?.contains(t)||p(!1)},[p]),x=U.useCallback(e=>{e.key===`Enter`&&!l.isEditing&&(e.preventDefault(),m())},[m,l.isEditing]);U.useEffect(()=>{let e=s.current;if(e)return e.addEventListener(`keydown`,x),()=>e.removeEventListener(`keydown`,x)},[x]);let S=U.useCallback(e=>{e.key===`Escape`?(e.preventDefault(),_()):e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),g())},[g,_]),C=l.error?`error`:l.isEditing?`editing`:`view`,w=l.hasFocus||l.isEditing||l.error!==null,T;return T=d?f.ok?U.createElement(d,{config:f.config,rawContent:l.originalMarkdown,sectionId:n}):DO(e,f.message):EO(e),(0,W.jsxs)(`div`,{ref:a,"data-widget-section-id":n,"data-widget-mode":C,className:gS(`group relative rounded-2xl border border-transparent bg-background/95 p-3 transition-colors duration-200 ease-out hover:border-border`,l.isEditing&&l.error===null&&`border-signal-positive/40 ring-1 ring-signal-positive/15`,l.error!==null&&`border-destructive/40 ring-1 ring-destructive/15`),onMouseDownCapture:e=>{l.isEditing||e.preventDefault()},onFocusCapture:()=>p(!0),onBlurCapture:b,onKeyDownCapture:x,children:[(0,W.jsx)(_O,{mode:C,enterEditMode:m,onSave:g,onUndo:_,className:gS(`z-10 focus-visible:opacity-100 focus-visible:scale-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-focus-within:scale-100`,w?`pointer-events-auto opacity-100 scale-100`:`pointer-events-none opacity-0 scale-95 group-hover:pointer-events-auto group-hover:opacity-100 group-hover:scale-100`)}),l.isEditing?(0,W.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[l.error!==null&&(0,W.jsxs)(`div`,{"data-testid":`widget-error-inlay`,className:`rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive`,children:[`Invalid JSON: `,l.error]}),(0,W.jsx)(vO,{ref:o,"data-testid":`widget-markdown-editor`,value:l.currentMarkdown,onChange:v,onBlur:y,onKeyDown:S,hasError:l.error!==null})]}):(0,W.jsx)(`div`,{ref:s,"data-testid":`widget-preview-surface`,tabIndex:0,onKeyDown:x,children:T})]})}var kO=class extends xr{sectionId;constructor(e){super(),this.sectionId=e}eq(e){return this.sectionId===e.sectionId}toDOM(e){let t=document.createElement(`div`);return t.className=`relative h-0 w-full`,(0,Ci.createRoot)(t).render((0,W.jsx)(`div`,{className:`absolute right-0 top-1 z-50`,children:(0,W.jsx)(_O,{mode:`editing`,enterEditMode:()=>{},onSave:()=>{e.dispatch({effects:yO.of({sectionId:this.sectionId,editing:!1})})},onUndo:()=>{e.dispatch({effects:yO.of({sectionId:this.sectionId,editing:!1})})}})})),t}ignoreEvent(){return!1}},AO=class extends xr{widgetName;rawContent;sectionId;registry;root=null;constructor(e,t,n,r){super(),this.widgetName=e,this.rawContent=t,this.sectionId=n,this.registry=r}eq(e){return this.widgetName===e.widgetName&&this.rawContent===e.rawContent&&this.sectionId===e.sectionId}toDOM(e){let t=document.createElement(`div`);return t.className=`cm-widget-block-preview`,t.style.cssText=`display:block; width:100%; min-height:1.5em; outline:none;`,this.root=(0,Ci.createRoot)(t),this.root.render(U.createElement(OO,{widgetName:this.widgetName,rawContent:this.rawContent,sectionId:this.sectionId,registry:this.registry,view:e})),t}destroy(){if(this.root){let e=this.root;this.root=null,queueMicrotask(()=>{try{e.unmount()}catch{}})}}ignoreEvent(){return!1}get estimatedHeight(){return 200}};function jO(e,t){let n;try{n=e.field(NT)}catch{return Ir.none}let{sections:r}=n,i=e.field(bO),a=[],o=e.selection.main.head;for(let n of r){if(n.type!==`widget`||!n.widgetName)continue;let r=e.doc;if(n.startLine>r.lines||n.endLine>r.lines)continue;if(i.has(n.id)){a.push(Ir.widget({widget:new kO(n.id),side:1,block:!1}).range(n.from));continue}if(o>=n.from&&o<=n.to)continue;let s=n.contentFrom!=null&&n.contentTo!=null?r.sliceString(n.contentFrom,n.contentTo):``;a.push(Ir.replace({widget:new AO(n.widgetName,s,n.id,t),block:!0}).range(n.from,n.to))}return a.sort((e,t)=>e.from-t.from),Ir.set(a)}function MO(e,t){return e.find(e=>e.type===`widget`&&t.from>=e.from&&t.from<=e.to)??null}function NO(e,t){let{head:n}=e.state.selection.main,r=e.state.doc.lineAt(n),i=Math.max(0,n-r.from),a=Math.min(i,t.length),o=t.from+a;e.dispatch({selection:{anchor:o,head:o},scrollIntoView:!0})}function PO(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(NT),i=e.state.field(bO),a=MO(r,n);if(a&&!i.has(a.id))return!1;let o=n.number+1;if(o>e.state.doc.lines)return!1;let s=MO(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(NO(e,e.state.doc.line(s.startLine)),!0)}function FO(e){let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t),{sections:r}=e.state.field(NT),i=e.state.field(bO),a=MO(r,n);if(a&&!i.has(a.id))return!1;let o=n.number-1;if(o<1)return!1;let s=MO(r,e.state.doc.line(o));return!s||i.has(s.id)?!1:(NO(e,e.state.doc.line(s.endLine)),!0)}var IO=si.high(hr.of([{key:`ArrowDown`,run:PO},{key:`ArrowUp`,run:FO}]));function LO(e){return[ni.define({create(t){return jO(t,e)},update(t,n){let r=n.effects.some(e=>e.is(yO)),i=!n.startState.selection.eq(n.newSelection);return n.docChanged||r||i?jO(n.state,e):t},provide:e=>Sr.decorations.from(e)}),bO,IO]}function RO(e){let t=e?.split(`:`,1)[0]?.toLowerCase();return t===`time`||t===`log`||t===`wod`||t===`whiteboard`?Rc:t===`wql`||t===`query`?Yh:null}var zO=new class{_db;constructor(e){this._db=e}get db(){return this._db??Z}async load(){return this.db.getAllEfforts()}async save(e){await this.db.saveEffort(e)}async delete(e){await this.db.deleteEffort(e)}};function BO(){return new bl({storage:zO})}async function VO(e){let t=await Z.getAllEfforts();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),WO()}var HO=new Set;function UO(e){return HO.add(e),()=>HO.delete(e)}function WO(){for(let e of HO)e()}var GO=null;function KO(){return GO||=BO(),GO}function qO(e){let t=e.split(/\r?\n\s*\r?\n/).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```")&&!e.startsWith(`|`)&&!e.startsWith(`- `)&&!e.startsWith(`* `));if(t)return t.replace(/^>\s?/,``).replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`).replace(/[`*_~]/g,``).replace(/\s+/g,` `).trim()||void 0}function JO(e){let{meta:t,body:n}=Qy(e),r=ib(t,`description`),i=ib(t,`image`),a;if(typeof i==`string`&&i.trim()){let e=i.trim();(/^https?:\/\//.test(e)||e.startsWith(`/`))&&(a=e)}let o=typeof r==`string`&&r.trim()?r.trim():qO(n);return{...o?{description:o}:{},...a?{image:a}:{}}}function YO(e){return e.split(/[-_\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var XO={and:!0,or:!0,of:!0,for:!0,to:!0,in:!0,on:!0,at:!0,by:!0,with:!0,the:!0,a:!0,an:!0};function ZO(e){let t=e.replace(/\.md$/,``);if(t.toUpperCase()===`README`)return`Overview`;let n=t.replace(/^day-\d+-/,``).split(/[-_]/),r=[];for(let e=0;e<n.length;e++){let t=n[e],i=n[e+1],a=n[e+2],o=n[e-1];if(/^\d{1,2}$/.test(t)&&/^\d{1,2}$/.test(i??``)&&!/^\d+$/.test(o??``)&&!/^\d+$/.test(a??``)){r.push(`${t}.${i}`),e++;continue}if(r.length>0&&XO[t.toLowerCase()]){r.push(t.toLowerCase());continue}r.push(t.charAt(0).toUpperCase()+t.slice(1))}return r.join(` `)}function QO(e,t){if(e!==`notebooks`)return[];let n=new Map,r=e=>{let t=n.get(e);return t||(t={id:e,name:YO(e),categories:[],items:[]},n.set(e,t)),t};for(let[e,n]of Object.entries(t)){let t=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/README\.md$/i);if(t){let e=r(t[1]);e.readme=n,e.categories=ob(n),Object.assign(e,JO(n));continue}let i=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/(\d{4}-\d{2}-\d{2})\/([^/]+\.md)$/);if(i){let[,t,a,o]=i;r(t).items.push({id:o.replace(/\.md$/,``),name:ZO(o),content:n,path:e,...a?{date:a}:{}});continue}let a=e.match(/(?:^|\/)markdown\/notebooks\/([^/]+)\/([^/]+\.md)$/);if(!a)continue;let[,o,s]=a;s.toLowerCase()!==`readme.md`&&r(o).items.push({id:s.replace(/\.md$/,``),name:ZO(s),content:n,path:e})}for(let e of n.values())e.items.sort((e,t)=>e.date&&t.date&&e.date!==t.date?t.date.localeCompare(e.date):e.date&&!t.date?-1:!e.date&&t.date?1:e.id.localeCompare(t.id));return Array.from(n.values()).filter(({items:e,readme:t})=>e.length>0||t!==void 0).sort((e,t)=>e.name.localeCompare(t.name))}function $O(e){return QO(`notebooks`,e)}var ek=null,tk=[];async function nk(){let e=await gk();return ek!==e&&(ek=e,tk=$O(e)),tk}function rk(e,t,n){return e?.items.find(e=>(e.date??``)===t&&e.id===n)}var ik=null,ak=null;function ok(){return ik||=Z.getAllBlockIndex().then(e=>e.filter(e=>e.isStatic===!0)).catch(e=>{throw ik=null,e}),ik}function sk(){ik=null,ak=null}function ck(e){let t=new Map;for(let n of e)for(let e of Ma(n.rawContent).filter(e=>e.type===`frontmatter`).flatMap(e=>sb(e.displayContent))){let r=t.get(e);r?r.add(n.id):t.set(e,new Set([n.id]))}return t}function lk(){return ak||=Z.getAllNotes().then(async e=>{let t=ck(e.filter(e=>e.seedOrigin===`seed`));try{let e=await nk();for(let n of e)for(let e of n.categories){let r=t.get(e);r?r.add(n.id):t.set(e,new Set([n.id]))}}catch{}return t}),ak}async function uk(){let e=KO();return e.isInitialized()||await e.loadBundled(),e.list()}ww(`discipline`,{load:async()=>{try{return _w((await uk()).map(e=>e.baseAttributes?.discipline).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),gw(zc))}catch{return gw(zc)}},cache:{ttlMs:6e4},open:!1,emptyText:`No disciplines available`}),ww(`effort`,{load:async()=>{try{return _w((await uk()).filter(e=>e.slug).map(e=>({value:e.slug,label:e.label||e.slug})),[]).sort((e,t)=>e.value.localeCompare(t.value))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No efforts indexed yet — type one to filter`}),ww(`intensity`,{load:async()=>{try{return _w((await uk()).map(e=>e.baseAttributes?.intensityTier).filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>({value:e.trim(),label:e.trim()})),gw(ac))}catch{return gw(ac)}},cache:{ttlMs:6e4},open:!1,emptyText:`No intensity tiers indexed yet`}),ww(`type`,{load:async()=>{try{return _w(pw(await ok()).map(e=>({value:e,label:e})),gw(hw))}catch{return gw(hw)}},cache:{ttlMs:3e5},open:!1,emptyText:`No indexed block types yet`}),ww(`notebook`,{load:async()=>fw(await ok()).map(e=>({value:e,label:e})),cache:`static`,open:!1,emptyText:`No notebooks in the static corpus`}),ww(`tag`,{load:async()=>{let e=await lk(),t=Array.from(e.keys()),n=[];try{n=(await Z.getAllTags()).map(e=>e.label)}catch{}return mw(n,t).map(e=>({value:e,label:e}))},cache:{ttlMs:3e4},open:!0,emptyText:`No tags yet — type one to filter by it`});for(let e of[`domain`,`format`,`equipment`,`quality`,`intent`])ww(e,{load:async()=>{try{return(await Z.getTags(e)).map(e=>({value:e.label,label:e.label}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No ${e}s indexed yet`});ww(`origin`,{load:async()=>{try{let e=await Z.getAllEfforts(),t=new Set;for(let n of e)n.registrySource&&t.add(n.registrySource);return Array.from(t).sort().map(e=>({value:e,label:e}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No effort origins indexed yet — type one to filter`}),(async()=>{try{let e=await Z.getAllTagTypes();for(let t of e)Tw(t.name)||ww(t.name,{load:async()=>{try{return(await Z.getTags(t.name)).map(e=>({value:e.label,label:e.label}))}catch{return[]}},cache:{ttlMs:6e4},open:!0,emptyText:`No ${t.label}s indexed yet`})}catch{}})();var dk=null,fk=null,pk=new Set;function mk(){for(let e of pk)e()}async function hk(){let e=await Z.getSeedContent(),t={};for(let{path:n,raw:r}of e)t[n]=r;return t}function gk(){return fk||=hk().then(e=>(Object.keys(e).length>0&&hS(`corpusReady`),dk=e,mk(),e)).catch(e=>{throw fk=null,e}),fk}function _k(){dk=null,fk=null,sk(),gk()}function vk(e){return pk.add(e),()=>pk.delete(e)}function yk(){return dk}function bk(){let e=(0,U.useSyncExternalStore)(vk,yk);return(0,U.useEffect)(()=>{gk()},[]),e}var xk=!1;function Sk(){if(xk||typeof BroadcastChannel>`u`)return;xk=!0;let e=new BroadcastChannel(Gv);e.onmessage=()=>_k()}var Ck=200,wk=1e6,Tk=500,Ek=50,Dk=6e4,Ok=3e4,kk=750,Ak=`wodwiki-sync`,jk={attachments:`data`};function Mk(e,t){let n=e instanceof Error?e.message:String(e);return t&&(n=n.split(t).join(`••••••`)),n||`Sync failed`}function Nk(e){let t=0;for(let n of e.ops){if(t+=32,n.op!==`put`)continue;let e=jk[n.store],r=n.value,i=e&&typeof r==`object`&&r&&!Array.isArray(r)?Reflect.get(r,e):void 0;t+=typeof i==`string`?i.length:i instanceof ArrayBuffer?Math.ceil(i.byteLength/3)*4+64:JSON.stringify(n.value)?.length??0}return t}var Pk=class{local;settings;connect;db;stopped=!1;chain=Promise.resolve();timers=[];reconciled=!1;halted=!1;retryAt=0;debounceTimer;unsubscribeOutbox;onOnline;onVisible;constructor(e,t,n){this.local=e,this.settings=t,this.connect=n}syncNow(){let e=this.chain.then(()=>this.cycle(!0));return this.chain=e.then(()=>void 0,()=>void 0),e}restoreNow(){let e=this.chain.then(async()=>{if(this.stopped)throw Error(`Restore engine is stopped`);if((await this.local.snapshotAllRows()).some(e=>e.rows.length>0)||(await this.local.readOutbox(0,1)).length>0)throw Error(`Restore requires an empty isolated local database`);let e=await this.remote(),t=await Ub(e);if(t===`empty`||t.kind!==`current`||t.schemaVersion!==32)throw Error(`Restore requires a provisioned v32 backup. Migrate older backups with the CLI first.`);let n=0;for(;n<t.rev;){let r=await Jb(e,n,Tk);if(r.length===0)break;if(r[r.length-1].rev>t.rev)throw Error(`Backup changed during restore. Freeze its writers and retry with a fresh local database.`);n=r[r.length-1].rev,await this.local.applySyncMutations(r.map(e=>e.mutation),n,this.cursorKey())}await this.local.validateSyncState();let r=await Ub(e);if(r===`empty`||r.kind!==`current`||r.schemaVersion!==t.schemaVersion||r.rev!==t.rev||n!==t.rev)throw Error(`Backup changed during restore. Freeze its writers and retry with a fresh local database.`);await this.local.setSyncState(this.bootstrappedKey(),{done:!0}),this.reconciled=!0});return this.chain=e.then(()=>void 0,()=>void 0),e}start(){let e=e=>{this.enqueue(()=>this.cycle(!1,e))};return this.onOnline=()=>{e(`full`)},this.onVisible=()=>{typeof document<`u`&&!document.hidden&&e(`full`)},typeof window<`u`&&(window.addEventListener(`online`,this.onOnline),typeof document<`u`&&document.addEventListener(`visibilitychange`,this.onVisible)),this.timers.push(setInterval(()=>{e(`full`)},Dk)),this.unsubscribeOutbox=sx(()=>{this.scheduleUpload()}),e(`full`),()=>{this.stop()}}async stop(){this.stopped=!0;for(let e of this.timers)clearInterval(e);this.timers=[],clearTimeout(this.debounceTimer),this.debounceTimer=void 0,typeof window<`u`&&this.onOnline&&window.removeEventListener(`online`,this.onOnline),typeof document<`u`&&this.onVisible&&document.removeEventListener(`visibilitychange`,this.onVisible),this.onOnline=void 0,this.onVisible=void 0,this.unsubscribeOutbox?.(),this.unsubscribeOutbox=void 0,await this.chain.catch(()=>void 0),await this.db?.close().catch(()=>void 0),this.db=void 0}scheduleUpload(){this.stopped||this.debounceTimer!==void 0||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.stopped||this.enqueue(()=>this.cycle(!1,`upload`))},kk))}enqueue(e){this.chain=this.chain.then(e,e),this.chain.catch(()=>{})}async cycle(e=!1,t=`full`){if(this.stopped||this.halted||!e&&Date.now()<this.retryAt)return;let n=globalThis.navigator?.locks;try{n?await n.request(Ak,()=>this.cycleInner(e,t)):await this.cycleInner(e,t)}catch(e){this.retryAt=Date.now()+Ok,Qx(Mk(e,this.settings.authToken))}}async cycleInner(e,t){let n=[];if(t===`full`){try{await this.ensureReconciled()}catch(e){n.push(e)}try{await this.pullOnce()}catch(e){n.push(e)}}try{await this.uploadOnce()}catch(e){n.push(e)}if(n.length>0)throw n[0]}async remote(){return this.db||=this.connect?.()??nS(Fe({url:this.settings.url,authToken:this.settings.authToken})),this.db}cursorKey(){return`cursor:${this.settings.url}`}watermarkKey(){return`watermark:${this.settings.url}`}bootstrappedKey(){return`bootstrapped:${this.settings.url}`}bootstrapRunKey(){return`bootstrap-run:${this.settings.url}`}async ensureReconciled(){if(this.reconciled)return;let e=await this.remote(),t=await Ub(e);if(t!==`empty`&&t.kind===`unknown`){let e=`Backup database contains unrelated tables and no WOD Wiki schema; refusing to adopt it. Point the backup setting at a fresh database.`;throw this.halted=!0,dS(e),Error(e)}let n=t===`empty`?0:t.schemaVersion;if(n>32){let e=`Backup database schema is newer than this app supports (v${n} > v32). Update the app to sync.`;throw this.halted=!0,dS(e),Error(e)}if(t===`empty`)await Wb(e,32);else if(t.kind===`legacy`||n<32){let e=`Backup schema v${n} requires an explicit CLI migration into a fresh v32 target. The old database was left untouched.`;throw this.halted=!0,dS(e),Error(e)}this.reconciled=!0}async bootstrapSnapshot(){let e=await this.remote(),t=await this.local.captureSyncBootstrap(this.bootstrapRunKey());for(let n of t)await qb(e,[n],{expectSchema:32});await this.local.setSyncState(this.bootstrappedKey(),{done:!0}),await(await this.local.open()).delete(`sync_state`,this.bootstrapRunKey())}async uploadOnce(){if(!this.reconciled||this.stopped||this.halted||!await this.local.getSyncState(this.bootstrappedKey()))return;let e=this.watermarkKey();if((await this.local.readOutbox((await this.local.getSyncState(e))?.seq??0,1)).length===0)return;let t=Yx(`upload`,`Uploading changes to backup`);try{let t=await this.remote(),n=(await this.local.getSyncState(e))?.seq??0,r=0;for(;;){let i=await this.local.readOutbox(n,Ek);if(i.length===0)break;let a=0;for(;a<i.length;){let o=[],s=0,c=0,l=n;for(;a<i.length&&s<Ck&&c<wk;){let e=i[a],t=Nk(e);if(o.length>0&&(s+e.ops.length>Ck||c+t>wk))break;o.push({id:e.id,at:e.at,ops:e.ops}),s+=e.ops.length,c+=t,l=e.seq,a+=1}await qb(t,o,{expectSchema:32}),r+=o.flatMap(e=>e.ops).filter(e=>e.op===`put`&&(e.store===`notes`||e.store===`efforts`)).length,n=l,await this.local.setSyncState(e,{seq:n}),await this.local.ackOutbox(n)}if(i.length<Ek)break}r>0&&Xx({source:`turso backup`,added:r,updated:0})}finally{t()}}async pullOnce(){if(!this.reconciled||this.stopped||this.halted)return;let e=this.cursorKey(),t=(await this.local.getSyncState(e))?.rev??0,n=Yx(`download`,`Syncing from backup`);try{let n=await this.remote(),r=t,i=0,a=0;for(;;){let t=await Jb(n,r,Tk);if(t.length===0){if(!await this.local.getSyncState(this.bootstrappedKey())){await this.bootstrapSnapshot();continue}break}let o=t[t.length-1].rev,s=await this.local.applySyncMutations(t.map(e=>e.mutation),o,e);i+=s.added,a+=s.updated,r=o}if(i+a>0){Xx({source:`turso backup`,added:i,updated:a}),_k();let e=KO();e.isInitialized()&&await VO(e)}}finally{n()}}},Fk=`wodwiki.dataSettings.v1`;function Ik(){let e=Uk();return e.state!==`invalid`&&e.localDbName?e.localDbName:Yb}function Lk(e,t){let n=e=>{let t=e.trim();try{let e=new URL(t);return`${e.hostname===`[::1]`?`::1`:e.hostname}${e.port?`:${e.port}`:``}${e.pathname.replace(/\/+$/,``)}`}catch{return t}};return n(e)===n(t)}function Rk(e){return typeof e==`string`&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(e)}var zk={"libsql:":!0,"https:":!0,"wss:":!0};function Bk(e,t){let n;try{n=new URL(e.trim())}catch{return`That is not a valid URL.`}if(n.protocol===`http:`||n.protocol===`ws:`){if(n.hostname!==`localhost`&&n.hostname!==`127.0.0.1`&&n.hostname!==`[::1]`&&n.hostname!==`::1`)return`Plain http:// is only allowed for a local smoke server (localhost / 127.0.0.1).`}else if(!zk[n.protocol])return`Unsupported protocol "${n.protocol}" — use libsql:// or https://.`;if(n.username||n.password)return`The URL must not embed credentials — put the token in the token field.`;if(n.search)return`The URL must not contain a query string.`;if(n.hash)return`The URL must not contain a fragment.`;if(!t||!t.trim())return`A database token is required.`}function Vk(e,...t){let n=e instanceof Error?e.message:String(e);for(let e of t)e&&(n=n.split(e).join(`••••••`));return Error(n)}function Hk(){try{return localStorage.getItem(Fk)}catch{return null}}function Uk(){let e=Hk();if(e===null)return{state:`indexed-db`};let t;try{t=JSON.parse(e)}catch{return{state:`invalid`,raw:e,error:`Saved data settings are not valid JSON.`}}if(!t||typeof t!=`object`||Array.isArray(t))return{state:`invalid`,raw:e,error:`Saved data settings have an unexpected shape.`};if(!(`kind`in t))return{state:`invalid`,raw:e,error:`Saved data settings have no kind.`};let n=t.kind,r=`localDbName`in t?t.localDbName:void 0;if(r!==void 0&&!Rk(r))return{state:`invalid`,raw:e,error:`Saved data settings have an invalid localDbName.`};let i=r===void 0?{}:{localDbName:r};if(n===`indexed-db`)return{state:`indexed-db`,...i};if(n!==`turso`)return{state:`invalid`,raw:e,error:`Saved data settings have an unknown kind "${String(n)}".`};if(!(`url`in t)||!(`authToken`in t))return{state:`invalid`,raw:e,error:`Saved Turso settings are missing the URL or token.`};let a=t.url,o=t.authToken;if(typeof a!=`string`||typeof o!=`string`)return{state:`invalid`,raw:e,error:`Saved Turso settings are missing the URL or token.`};let s=Bk(a,o);return s?{state:`invalid`,raw:e,error:s}:{state:`turso`,url:a,authToken:o,...i}}async function Wk(e){let t=nS(Fe({url:e.url.trim(),authToken:e.authToken}));try{await t.query(`SELECT 1`);let e=Error(`verifyTursoTarget: deliberate rollback`);try{await t.transaction(async t=>{throw await t.exec(`CREATE TABLE IF NOT EXISTS "_wodwiki_write_check" ("v" TEXT)`),await t.exec(`INSERT INTO "_wodwiki_write_check" ("v") VALUES (?)`,[crypto.randomUUID()]),e})}catch(t){if(t!==e)throw t}}finally{await t.close().catch(()=>void 0)}}var Gk;async function Kk(e){if(Gk)throw Error(`A connect is already running — wait for it to finish.`);let t=Bk(e.url,e.authToken);if(t)throw Error(t);Gk=(async()=>{try{await Wk(e)}catch(t){throw Vk(t,e.authToken)}let t=Uk(),n=t.state!==`invalid`&&t.localDbName?{localDbName:t.localDbName}:{};localStorage.setItem(Fk,JSON.stringify({kind:`turso`,url:e.url.trim(),authToken:e.authToken,...n}))})();try{await Gk}finally{Gk=void 0}}async function qk(e){let t=Bk(e.url,e.authToken);if(t)throw Error(t);try{await Wk(e)}catch(t){throw Vk(t,e.authToken)}}function Jk(e){if(!Rk(e))throw Error(`A valid local database name is required.`);localStorage.setItem(Fk,JSON.stringify({kind:`indexed-db`,localDbName:e}))}function Yk(){let e=Uk(),t=e.state!==`invalid`&&e.localDbName?{localDbName:e.localDbName}:{};localStorage.setItem(Fk,JSON.stringify({kind:`indexed-db`,...t}))}var Xk=Hk();typeof window<`u`&&window.addEventListener(`storage`,e=>{(e.key===`wodwiki.dataSettings.v1`||e.key===null)&&e.newValue!==Xk&&window.location.reload()});var Zk=t({DATA_SETTINGS_KEY:()=>Fk,IndexedDBStorage:()=>gx,StorageService:()=>Ox,getActiveLocalDbName:()=>Ik,profileService:()=>$k,readAllLocalRows:()=>fA,readDataSettings:()=>Uk,readUnsentEdits:()=>dA,startBackgroundStorageSync:()=>lA,stopBackgroundStorageSync:()=>uA,storage:()=>nA,storageBackend:()=>Qk,storageService:()=>Z,whenStorageReady:()=>aA}),Qk=`indexed-db`,$k=Lx(`indexed-db`);function eA(){return new gx({dbName:Ik(),getUserId:()=>$k.currentSync()?.id,onUpgradeStart:e=>uS(e,32)})}var tA=eA(),nA={readonly(e){return tA.readonly(e)},readwrite(e){return tA.readwrite(e)},transaction(e,t,n){return tA.transaction(e,t,n)},async queryDomain(e){return tA.queryDomain?.(e)},wipe(){return tA.wipe()},close(){return tA.close()}},Z=new Ox(nA),rA;async function iA(){try{await Z.ensureDefaultTagTypes()}catch{}}function aA(){return rA||(rA=(async()=>{try{let e=globalThis.indexedDB;if(e&&typeof e.databases==`function`){let t=Ik(),n=(await e.databases().catch(()=>[])).find(e=>e.name===t);if(n&&typeof n.version==`number`){if(n.version>32){let e=`local database schema v${n.version} is newer than this app supports (v32); refusing to downgrade`;throw dS(e),Error(e)}n.version<32&&lS(`Checking local database schema v${n.version}…`)}}await tA.open(),cS(32),await iA()}catch(e){throw rA=void 0,oS().phase!==`error`&&dS(e instanceof Error?e.message:String(e)),e}})(),rA)}var oA,sA,cA;function lA(){if(!oA){if(!(tA instanceof gx))oA={stop:()=>{oA=void 0}};else{let e=Uk();if(e.state===`invalid`){let t=`Saved backup settings are invalid: ${e.error}`;Qx(t),dS(t),oA={stop:()=>{oA=void 0}}}else if(e.state===`turso`){let t=new Pk(tA,e);cA=t;let n=t.start();oA={stop:()=>{n(),cA===t&&(cA=void 0),oA=void 0}}}else oA={stop:()=>{oA=void 0}}}sA=()=>{oA?.stop(),sA=void 0}}return sA}async function uA(){if(!oA)return!1;let e=cA;return oA.stop(),e&&await e.stop(),e!==void 0}async function dA(){return tA instanceof gx?tA.readOutbox(0,2**53-1):[]}async function fA(){return tA instanceof gx?tA.snapshotAllRows():[]}var pA={registeredWidgets:Oa},mA=[`notes`,`block_revisions`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`sessions`,`events`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`];function hA(e){let t=ba(e.links,e.pages),n=xa(t);return{id:e.note.id,title:e.note.title,slug:n.pageSlug,pageId:n.pageId,journalDate:n.journalDate,placements:t,createdAt:e.note.createdAt,updatedAt:e.note.createdAt,targetDate:e.note.date??e.note.createdAt,rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision,tags:e.tags.map(e=>e.label),type:e.note.type??`note`,sourceId:e.note.sourceId,notebookId:e.note.notebookId,seedOrigin:e.note.seedOrigin,schemaVersion:1}}function gA(e){if(e?.dateRange)return e.dateRange;if(e?.daysBack!=null){let t=Date.now();return{start:t-e.daysBack*864e5,end:t}}}var _A=class e{db;constructor(e=Z){this.db=e}get persistenceStorage(){return this.db}mode=`history`;capabilities={canWrite:!0,canDelete:!0,canFilter:!0,canMultiSelect:!0,supportsHistory:!0};async getRecords(e){let t=gA(e),n=[];t&&n.push({field:`date`,start:t.start,end:t.end});for(let t of e?.tags??[])n.push({field:`tags`,values:[t]});let r=await this.db.queryDomain(n.length?{plan:`detail`,selection:n}:{plan:`detail`}),i;if(r?.plan===`detail`)i=r.rows.map(hA);else{let e=t?await this.db.getNotesByDateRange(t.start,t.end):await this.db.getAllNotes();i=[...(await this.db.getDetailBatches(e.map(e=>e.id))).values()].map(hA)}return i=i.filter(n=>(!t||n.targetDate>=t.start&&n.targetDate<=t.end)&&(e?.tags??[]).every(e=>n.tags.includes(e))),i.sort((e,t)=>t.targetDate-e.targetDate)}async getRecord(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.db.getNote(e)??(t===e?void 0:await this.db.getNote(t))??await this.db.getNoteBySlug(e)??(t===e?void 0:await this.db.getNoteBySlug(t));if(!n)return null;let r=(await this.db.getDetailBatches([n.id])).get(n.id);if(!r)return null;let i=hA(r),a=(await this.db.getSessionsForNote(n.id)).sort((e,t)=>t.createdAt-e.createdAt)[0],o=Ma(n.rawContent,pA).map(e=>{let t=Object.values(n.blocks).find(t=>t.from===e.from&&t.to===e.to);return t?{...e,id:t.id,version:t.version,scriptBlock:e.scriptBlock?{...e.scriptBlock,id:t.id,version:t.version}:void 0}:e});return{...i,sections:o,results:a?vb(a,await this.db.getEventsByResult(a.id)):void 0}}async cloneRecord(e,t){let n=await this.getRecord(e);if(!n)throw Error(`Source entry not found: ${e}`);let r=t??Date.now();return this.saveRecord({title:n.title,rawContent:n.rawContent,tags:n.tags,targetDate:r,journalDate:Yy(new Date(r)),type:`journal`,sourceId:n.id})}async saveRecord(t){let n=Date.now(),r=t.id??(t.type===`playground`?mb(n):ze());if(!t.id&&t.type===`playground`){let e=r;for(let t=1;await this.db.getNote(r);t++){if(t>100)throw Error(`Unable to allocate unique playground timestamp ID`);r=`${e}-${t}`}}await this.db.withTransaction([...mA],async n=>{let i=await n.getNote(r),a=i?t.sourceRevision:0;if(a===void 0)throw new yb(`STALE_SOURCE`,`An expected source revision is required for ${r}`);let o=await new e(n).changedManualTags(r,t.tags),s=t.blocks??(i?.rawContent===t.rawContent?i.blocks:Pa(t.rawContent,{...pA,sourceRevision:a||1}));await n.saveNoteSource({noteId:r,rawContent:t.rawContent,blocks:s,expectedSourceRevision:a,createdAt:t.createdAt,metadata:{title:t.title,type:t.type,tags:o,targetDate:t.targetDate,sourceId:t.sourceId}});let c=new e(n);await c.updateRelationships(r,{journalDate:t.journalDate,slug:t.slug}),await c.updateTags(r,t.rawContent,o)});let i=await this.getRecord(r);if(!i)throw Error(`Saved note disappeared: ${r}`);return i}async updateRecord(t,n){let r=t.startsWith(`playground/`)?t.slice(11):t,i=await this.db.getNote(t)??(r===t?void 0:await this.db.getNote(r))??await this.db.getNoteBySlug(t)??(r===t?void 0:await this.db.getNoteBySlug(r));if(!i)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${t}`);await this.db.withTransaction([...mA],async t=>{let r=await t.getNote(i.id);if(!r)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${i.id}`);let a=n.rawContent??r.rawContent;if(n.rawContent!==void 0&&n.expectedSourceRevision===void 0)throw new yb(`STALE_SOURCE`,`An expected source revision is required for ${r.id}`);let o=n.expectedSourceRevision??r.sourceRevision,s=n.tags===void 0?void 0:await new e(t).changedManualTags(r.id,n.tags),c=n.blocks??(a===r.rawContent?r.blocks:Pa(a,{...pA,sourceRevision:o}));await t.saveNoteSource({noteId:r.id,rawContent:a,blocks:c,expectedSourceRevision:o,metadata:{title:n.title,type:n.type,tags:s,targetDate:n.targetDate,sourceId:n.sourceId}});let l=new e(t);if(await l.updateRelationships(r.id,n),(n.tags!==void 0||a!==r.rawContent)&&await l.updateTags(r.id,a,s),n.results){if(!n.blockId||!n.blockVersion)throw Error(`Recording a result requires its frozen block pin`);let e=await t.getBlockRevision(r.id,n.blockId,n.blockVersion);if(!e||e.kind!==`wod`)throw new yb(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision not found`);let i=n.resultId?await t.getSessionById(n.resultId):void 0;if(i&&(i.noteId!==r.id||i.blockId!==n.blockId||i.blockVersion!==n.blockVersion))throw new yb(`RESULT_NOTE_MISMATCH`,`Cannot replace a Session pin`);let a=n.results,o={...i,id:n.resultId??ze(),noteId:r.id,blockId:n.blockId,blockVersion:n.blockVersion,blockContentId:n.blockContentId,origin:n.origin??i?.origin,startTime:a.startTime,endTime:a.endTime,duration:a.duration??0,completed:a.completed,roundsCompleted:a.roundsCompleted,totalRounds:a.totalRounds,repsCompleted:a.repsCompleted,status:`completed`,createdAt:i?.createdAt??a.endTime??Date.now()};if(await t.saveSession(o),a.logs?.length){let e={noteId:o.noteId,resultId:o.id,blockId:o.blockId,blockVersion:o.blockVersion,blockContentId:o.blockContentId,origin:o.origin,pageId:o.pageId,workoutTimestamp:o.endTime};await t.appendEvents(c_(a.logs,e)),await t.finalizeSummaries(o.id,l_(a.logs,e))}}});let a=await this.getRecord(i.id);if(!a)throw Error(`Saved note disappeared: ${i.id}`);return a}async updateRelationships(e,t){for(let n of[`journalDate`,`slug`]){let r=t[n];if(r===void 0)continue;if(!r){for(let t of await this.db.getNotePages(e)){let r=await this.db.getPage(t.pageId);(n===`journalDate`?r?.date:r?.slug&&!r.date)&&await this.db.removeNoteFromPage(e,t.pageId)}continue}let i=await this.resolvePage(e,n,r);await this.db.addNoteToPage(e,i.id)}}async resolvePage(e,t,n){if(t===`journalDate`)return this.db.getOrCreatePageForDate(n);let r=await this.db.getPageBySlug(n);if(r)return r;let i={id:ze(),slug:n,title:(await this.db.getNote(e))?.title,createdAt:Date.now()};return await this.db.savePage(i),i}async resolveTargetPage(e,t){if(t.date)return this.db.getOrCreatePageForDate(t.date);if(t.slug)return this.resolvePage(e,`slug`,t.slug);throw Error(`A placement target needs a date or a slug`)}async addRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e),r=await this.resolveTargetPage(n,t);await this.db.addNoteToPage(n,r.id);let i=await this.getRecord(n);if(!i)throw Error(`Saved note disappeared: ${n}`);return i}async removeRecordPlacement(e,t){let n=await this.resolvePlacementNoteId(e);await this.db.removeNoteFromPage(n,t);let r=await this.getRecord(n);if(!r)throw Error(`Saved note disappeared: ${n}`);return r}async moveRecordPlacement(e,t,n){let r=await this.resolvePlacementNoteId(e),i=await this.resolveTargetPage(r,n);await this.db.moveNoteBetweenPages(r,t,i.id);let a=await this.getRecord(r);if(!a)throw Error(`Saved note disappeared: ${r}`);return a}async getPageRecords(e){let t=await this.db.getPageBySlug(e);if(!t)return[];let n=await this.db.getPagePlacements(t.id);if(n.length===0)return[];let r=await this.db.getDetailBatches(n.map(e=>e.noteId));return n.map(e=>r.get(e.noteId)).filter(e=>e!==void 0).map(hA)}async resolvePlacementNoteId(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.db.getNote(e)??(t===e?void 0:await this.db.getNote(t));if(!n)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${e}`);return n.id}async resolveNoteId(e){let t=e.startsWith(`playground/`)?e.slice(11):e,n=await this.db.getNote(e)??(t===e?void 0:await this.db.getNote(t))??await this.db.getNoteBySlug(e)??(t===e?void 0:await this.db.getNoteBySlug(t));if(!n)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${e}`);return n.id}async changedManualTags(e,t){let n=(await this.db.getTagsForNote(e)).map(e=>e.label).sort(),r=[...new Set(t.map(e=>e.trim()).filter(Boolean))].sort();return n.length===r.length&&n.every((e,t)=>e===r[t])?void 0:r}async updateTags(e,t,n){let r=(await this.db.getAllTagTypes()).map(e=>e.name),i=Ma(t,pA).filter(e=>e.type===`frontmatter`).flatMap(e=>cb(e.displayContent,r)),a=n??(await this.db.getNote(e))?.tags??[];await this.db.setNoteTags(e,[...a,...i.map(e=>e.type?e:e.label)])}async deleteRecord(e){await this.db.deleteNote(e)}async getAttachments(e){return this.db.getAttachmentsForNote(e)}async saveAttachment(e,t){let n={...t,id:t.id??ze(),noteId:e,createdAt:Date.now()};return await this.db.saveAttachment(n),n}async deleteAttachment(e){await this.db.deleteAttachment(e)}},vA={beep:{notes:[{freq:880,type:`sine`,duration:.1}]},tick:{notes:[{freq:880,type:`sine`,duration:.1}]},click:{notes:[{freq:1400,type:`sine`,duration:.1}]},buzzer:{notes:[{freq:150,type:`sawtooth`,duration:.5}]},chime:{notes:[{freq:523.25,type:`sine`,duration:.5,offset:0},{freq:659.25,type:`sine`,duration:.5,offset:.1},{freq:783.99,type:`sine`,duration:.5,offset:.2}]},complete:{notes:[{freq:523.25,type:`sine`,duration:.5,offset:0},{freq:659.25,type:`sine`,duration:.5,offset:.1},{freq:783.99,type:`sine`,duration:.5,offset:.2}]},select:{notes:[{freq:880,type:`sine`,duration:.08,offset:0},{freq:1200,type:`sine`,duration:.12,offset:.08}]},start:{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"countdown-beep":{notes:[{freq:880,type:`sine`,duration:.1}]},"timer-complete":{notes:[{freq:523.25,type:`sine`,duration:.4,offset:0},{freq:659.25,type:`sine`,duration:.4,offset:.1},{freq:783.99,type:`sine`,duration:.6,offset:.2}]},"start-beep":{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"interval-start":{notes:[{freq:440,type:`square`,duration:.1,offset:0},{freq:880,type:`square`,duration:.3,offset:.15}]},"interval-complete":{notes:[{freq:523.25,type:`sine`,duration:.4,offset:0},{freq:659.25,type:`sine`,duration:.4,offset:.1},{freq:783.99,type:`sine`,duration:.6,offset:.2}]},"rest-over":{notes:[{freq:783.99,type:`sine`,duration:.3,offset:0},{freq:1046.5,type:`sine`,duration:.5,offset:.15}]}};function yA(e){return vA[e]}var bA=Object.freeze(Object.keys(vA)),xA=class{context=null;masterGain=null;init(){if(this.context)return;let e=window;if(typeof window>`u`)return;let t=window.AudioContext??e.webkitAudioContext;t&&(this.context=new t,this.masterGain=this.context.createGain(),this.masterGain.connect(this.context.destination))}async playNotes(e,t){if(this.context||this.init(),!this.context||!this.masterGain||(this.context.state===`suspended`&&await this.context.resume().catch(()=>{}),this.context.state!==`running`))return;let n=this.context.currentTime;for(let r of e)this.playNote(n+(r.offset??0),r.freq,r.type,r.duration,t)}playNote(e,t,n,r,i){if(!this.context||!this.masterGain)return;let a=this.context.createOscillator(),o=this.context.createGain();a.connect(o),o.connect(this.masterGain),a.type=n,a.frequency.setValueAtTime(t,e),o.gain.setValueAtTime(i*.5,e),o.gain.exponentialRampToValueAtTime(.01,e+r),a.start(e),a.stop(e+r)}},SA=class extends Error{sound;constructor(e){super(`Unknown sound "${e}" — it has no entry in the sound table`),this.sound=e,this.name=`UnknownSoundError`}},CA=new class{enabled;sink;constructor(e,t){if(this.sink=e??new xA,t!==void 0)this.enabled=t;else if(typeof window<`u`)try{let e=localStorage.getItem(`wod-wiki-audio-enabled`);this.enabled=e===null||e===`true`}catch{this.enabled=!0}else this.enabled=!0}setEnabled(e){if(this.enabled=e,typeof window<`u`)try{localStorage.setItem(`wod-wiki-audio-enabled`,String(e))}catch{}}isEnabled(){return this.enabled}async playSound(e,t=1){if(!this.enabled)return;let n=yA(e);if(!n)throw new SA(e);`init`in this.sink&&typeof this.sink.init==`function`&&this.sink.init(),await this.sink.playNotes(n.notes,t)}},wA=class{listeners=new Set;emit(e){this.listeners.forEach(t=>{try{t(e)}catch(e){console.error(`[SimpleEventBus] Error in listener:`,e)}})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get size(){return this.listeners.size}};new class{bus=new wA;emitScrollToBlock(e,t=`unknown`){this.bus.emit({type:`workbench:scroll-to-block`,payload:{blockId:e,source:t}})}emitHighlightBlock(e,t=`unknown`){this.bus.emit({type:`workbench:highlight-block`,payload:{blockId:e,source:t}})}emitStartWorkout(e){this.bus.emit({type:`workbench:start-workout`,payload:{block:e}})}emitNavigateTo(e,t){this.bus.emit({type:`workbench:navigate-to`,payload:{entryId:e,view:t}})}onScrollToBlock(e){return this.bus.subscribe(t=>{t.type===`workbench:scroll-to-block`&&e(t.payload)})}onHighlightBlock(e){return this.bus.subscribe(t=>{t.type===`workbench:highlight-block`&&e(t.payload)})}onStartWorkout(e){return this.bus.subscribe(t=>{t.type===`workbench:start-workout`&&e(t.payload)})}onNavigateTo(e){return this.bus.subscribe(t=>{t.type===`workbench:navigate-to`&&e(t.payload)})}},new wA;function TA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`notebook`}var EA=`wodwiki.seedSources`,DA=`wodwiki.seedSources.hidden`;function OA(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!==`https:`&&n.protocol!==`http:`||n.username||n.password||n.search||n.hash?null:(n.pathname.endsWith(`/`)||(n.pathname+=`/`),n.toString())}function kA(e){let t=e.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!==`https:`||n.username||n.password||n.search||n.hash?null:n.toString()}var AA=`/seed/core/`;function jA(e,t){if(/^https?:\/\//i.test(e))return e;let n=t??(typeof document<`u`?document.baseURI:void 0);if(!n)return e;try{return new URL(e,n).href}catch{return e}}function MA(){try{let e=localStorage.getItem(EA);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.label!=`string`||typeof e.url!=`string`)return[];let{repositoryUrl:t}=e,n=typeof t==`string`?kA(t):null,r={id:e.id,label:e.label,url:e.url};return[n?{...r,repositoryUrl:n}:r]}):[]}catch{return[]}}function NA(){return MA()}function PA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`source`}function FA(e,t,n){let r=OA(t);if(!r)throw Error(`Enter an absolute http(s) URL of a feed directory.`);let i=MA();if(i.some(e=>OA(e.url)===r)||GA().includes(r))throw Error(`This source is already registered.`);let a=n?.repositoryUrl?.trim(),o;if(a&&(o=kA(a)??void 0,!o))throw Error(`Enter an absolute https repository URL without credentials.`);let s=e.trim()||(()=>{try{return new URL(r).hostname}catch{return`Source`}})(),c={...nj};for(let e of i)c[e.id]=!0;let l=PA(s);for(let e=2;c[l];e++)l=`${PA(s)}-${e}`;let u={id:l,label:s,url:r,...o?{repositoryUrl:o}:{}};return localStorage.setItem(EA,JSON.stringify([...i,u])),u}function IA(e){localStorage.setItem(EA,JSON.stringify(MA().filter(t=>t.id!==e)))}function LA(){return WA.map(e=>e.id)}function RA(){try{let e=JSON.parse(localStorage.getItem(DA)??`null`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function zA(e){let t=tj(e),n=RA();LA().includes(t)&&!n.includes(t)&&localStorage.setItem(DA,JSON.stringify([...n,t]))}function BA(){return[...new Set(RA().map(tj))]}var VA={id:`core`,label:`Core`,url:AA,description:`The app's own corpus — guides, the page template, and the reference chunks.`,tier:`core`},HA=`https://bitcobblers.github.io`;function UA(e,t,n,r,i=!1){return{id:e,label:t,url:`${HA}/${n}/`,repositoryUrl:`https://github.com/bitcobblers/${n}`,description:r,tier:`community`,...i?{autoImport:!0}:{}}}var WA=[UA(`sport-crossfit`,`CrossFit`,`wod-wiki-sport-crossfit`,`CrossFit benchmark collections (Games, Girls, Heroes) and weekly programming.`),UA(`sport-hyrox`,`HYROX`,`wod-wiki-sport-hyrox`,`HYROX race preparation and simulation workouts.`),UA(`legends-of-kettlebell`,`Kettlebell Coaches`,`wod-wiki-legends-of-kettlebell`,`Kettlebell coach collections and the Dan John 40-Day Program feed.`),UA(`sport-swimming`,`Swimming`,`wod-wiki-sport-swimming`,`Swimming programs from pre-highschool through college, masters, Olympic, and triathlete.`),UA(`sport-track`,`Track & Field`,`wod-wiki-sport-track`,`High-school track programs — 400m (Raffensperger) and sprints (Arrowhead).`),UA(`wayback-zombie-fit`,`ZombieFit`,`wod-wiki-wayback-zombie-fit`,`The ZombieFit parkour archive — daily WODs since 2009.`),UA(`sport-golos-method`,`Golos Method`,`wod-wiki-feed-golos-method`,`Daily minimalist strength and conditioning.`),UA(`yt-dan-john`,`Dan John`,`wod-wiki-youtube-dan-john`,`Dan John kettlebell workouts.`),UA(`yt-mark-wildman`,`Mark Wildman`,`wod-wiki-youtube-mark-wildman`,`Mark Wildman athletic kettlebell and club training.`),UA(`yt-strongfirst`,`StrongFirst`,`wod-wiki-youtube-strongfirst`,`StrongFirst hardstyle kettlebell workouts.`),UA(`yt-the-stone-circle`,`The Stone Circle`,`wod-wiki-youtube-the-stone-circle`,`Sandbag power-endurance and density training.`),UA(`samples-movement`,`Movement Examples`,`wod-wiki-samples-movement`,`Unconventional and parkour-style training examples.`),UA(`sport-yoga`,`Yoga Examples`,`wod-wiki-sport-yoga`,`Yoga session examples.`),UA(`r-workoutroutines`,`r/WorkoutRoutines`,`wod-wiki-r-workoutroutines`,`Community feed from the r/WorkoutRoutines subreddit.`)];function GA(){return[AA,...WA.map(e=>e.url)]}function KA(e){return XA().find(t=>t.id===e)}function qA(e){let t=KA(e);if(!t)throw Error(`unknown feed source: ${e}`);return t}function JA(e,t,n,r,i,a){return qA(e),{id:`community-${t}`,feedId:e,chunkId:n,label:r,category:i,description:a}}var YA=[JA(`sport-crossfit`,`crossfit-games`,`notebook.crossfit-games`,`CrossFit Games`,`workouts`,`CrossFit Games workouts — Open, Regionals, and Games programming, formatted for Wod Wiki.`),JA(`sport-crossfit`,`crossfit-girls`,`notebook.crossfit-girls`,`CrossFit Girls`,`workouts`,`Classic benchmark workouts — Fran, Helen, Grace, Diane, and more, formatted for Wod Wiki.`),JA(`sport-crossfit`,`crossfit-heroes`,`notebook.crossfit-heroes`,`CrossFit Heroes`,`workouts`,`Hero benchmark workouts honoring service members — Murph, DT, Badger, and more.`),JA(`sport-crossfit`,`crossfit-programming`,`notebook.crossfit-programming`,`CrossFit Programming`,`programs`,`Weekly CrossFit programming — daily strength, conditioning, and skill sessions on a rotation with a weekly benchmark.`),JA(`sport-hyrox`,`hyrox`,`notebook.hyrox`,`HYROX`,`workouts`,`HYROX race preparation — running, sled work, ergs, and functional stations in race format.`),JA(`legends-of-kettlebell`,`geoff-neupert`,`notebook.geoff-neupert`,`Geoff Neupert`,`workouts`,`Geoff Neupert kettlebell workouts — strength and conditioning from a Master SFG coach.`),JA(`legends-of-kettlebell`,`girevoy-sport`,`notebook.girevoy-sport`,`Girevoy Sport`,`workouts`,`Competitive kettlebell sport — jerk, snatch, and long-cycle programming.`),JA(`legends-of-kettlebell`,`joe-daniels`,`notebook.joe-daniels`,`Joe Daniels (Swing This)`,`workouts`,`Joe Daniels kettlebell workouts — kettlebell sport and hardstyle fusion.`),JA(`legends-of-kettlebell`,`keith-weber`,`notebook.keith-weber`,`Keith Weber`,`workouts`,`Keith Weber kettlebell workouts — high-intensity kettlebell cardio.`),JA(`legends-of-kettlebell`,`steve-cotter`,`notebook.steve-cotter`,`Steve Cotter`,`workouts`,`Steve Cotter kettlebell workouts — comprehensive kettlebell education.`),JA(`legends-of-kettlebell`,`dan-john-40-day`,`notebook.dan-john-40-day`,`Dan John 40-Day Program`,`programs`,`Dan John's 40-day barbell program — five lifts, five sets of five, five days a week for 40 sessions.`),JA(`yt-dan-john`,`dan-john`,`notebook.dan-john`,`Dan John Kettlebell`,`workouts`,`Dan John kettlebell workouts — simple, effective programming with clear objectives.`),JA(`yt-mark-wildman`,`mark-wildman`,`notebook.mark-wildman`,`Mark Wildman`,`workouts`,`Mark Wildman workouts — athletic kettlebell and club training.`),JA(`yt-strongfirst`,`strongfirst`,`notebook.strongfirst`,`StrongFirst`,`workouts`,`StrongFirst workouts — hardstyle kettlebell strength and skill.`),JA(`yt-the-stone-circle`,`the-stone-circle`,`notebook.the-stone-circle`,`The Stone Circle`,`workouts`,`Sandbag power endurance and density training — progressive EMOM protocols.`),JA(`sport-swimming`,`swimming-college`,`notebook.swimming-college`,`Swimming: College`,`workouts`,`College swimming training sessions.`),JA(`sport-swimming`,`swimming-highschool`,`notebook.swimming-highschool`,`Swimming: High School`,`workouts`,`High-school swimming training sessions.`),JA(`sport-swimming`,`swimming-masters`,`notebook.swimming-masters`,`Swimming: Masters`,`workouts`,`Masters swimming training sessions.`),JA(`sport-swimming`,`swimming-olympic`,`notebook.swimming-olympic`,`Swimming: Olympic`,`workouts`,`Olympic-caliber swimming training sessions.`),JA(`sport-swimming`,`swimming-post-college`,`notebook.swimming-post-college`,`Swimming: Post-College`,`workouts`,`Post-college swimming training sessions.`),JA(`sport-swimming`,`swimming-pre-highschool`,`notebook.swimming-pre-highschool`,`Swimming: Pre-Highschool`,`workouts`,`Pre-highschool swimming training sessions.`),JA(`sport-swimming`,`swimming-triathlete`,`notebook.swimming-triathlete`,`Swimming: Triathlete`,`workouts`,`Triathlete swim training sessions.`),JA(`sport-track`,`hs-track-400m`,`notebook.hs-track-400m`,`HS Track 400m`,`workouts`,`High-school 400m program after Raffensperger — speed, tempo, and strength phases.`),JA(`sport-track`,`hs-track-sprints`,`notebook.hs-track-sprints`,`HS Track Sprints`,`workouts`,`High-school sprints program after Arrowhead — acceleration, maximum velocity, and speed endurance.`),JA(`wayback-zombie-fit`,`zombiefit`,`notebook.zombiefit`,`ZombieFit`,`workouts`,`The ZombieFit archive — parkour-inspired fitness WODs, 2009–2013.`),JA(`sport-golos-method`,`the-golos-method`,`notebook.the-golos-method`,`The Golos Method`,`workouts`,`Daily minimalist strength and conditioning — dense, repeatable sessions.`),JA(`samples-movement`,`unconventional`,`notebook.unconventional`,`Unconventional`,`workouts`,`Unconventional training — maces, clubs, sandbags, and parkour movement.`),JA(`sport-yoga`,`yoga`,`notebook.yoga`,`Yoga`,`workouts`,`Yoga sessions for mobility and recovery.`),JA(`r-workoutroutines`,`workoutroutines-reddit`,`notebook.workoutroutines-reddit`,`r/WorkoutRoutines`,`programs`,`Community workouts from the r/WorkoutRoutines subreddit.`)];function XA(){return[VA,...WA,...NA().map(e=>({id:e.id,label:e.label,url:e.url,description:`Custom feed synced from ${e.url}`,tier:`imported`,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{}}))]}function ZA(){return XA().filter(e=>e.id!==VA.id)}function QA(){return[...YA,...NA().map(e=>({id:e.id,feedId:e.id,chunkId:e.id,label:e.label,category:`custom`,description:`Custom feed synced from ${e.url}`}))]}function $A(e){return QA().filter(t=>t.feedId===e)}var ej={"seed-crossfit":`sport-crossfit`,"seed-hyrox":`sport-hyrox`,"seed-kettlebell":`legends-of-kettlebell`,"seed-swimming":`sport-swimming`,"seed-track":`sport-track`,"seed-zombie-fit":`wayback-zombie-fit`,"seed-golos-method":`sport-golos-method`,"example-movement":`samples-movement`,"example-yoga":`sport-yoga`};function tj(e){return ej[e]||(YA.find(t=>t.id===e)?.feedId??e)}var nj=Object.fromEntries([[`core`,!0],[`community`,!0],[`common`,!0],[`seed-core`,!0],[`seed-crossfit`,!0],[`seed-hyrox`,!0],[`seed-kettlebell`,!0],[`seed-swimming`,!0],[`seed-track`,!0],[`seed-zombie-fit`,!0],[`seed-golos-method`,!0],[`example-movement`,!0],[`example-yoga`,!0],...WA.map(e=>[e.id,!0]),...YA.map(e=>[e.id,!0])]),rj=`notebook/defaults`,ij=new Set(Da.map(e=>e.slug)),aj=class{store;constructor(e=Z){this.store=e}tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}getFeedNotebooks(){let e=[];for(let t of QA()){if(t.category===`dashboards`)continue;let n=t.chunkId.replace(/^notebook\./,``);e.push({id:Ta(n),slug:n,notebookId:Ta(n),name:t.label,description:t.description,icon:t.category===`feeds`?`📡`:`📚`,origin:`feed`,feedEntryId:t.feedId,seedChunkId:t.chunkId,createdAt:0})}return e}getDefaultNotebooks(){return Da.map(e=>({id:e.notebookId,slug:e.slug,notebookId:e.notebookId,name:e.name,description:e.description,icon:e.icon,origin:`default`,...e.feedEntryId?{feedEntryId:e.feedEntryId}:{},...e.seedChunkId?{seedChunkId:e.seedChunkId}:{},createdAt:0}))}async getAllNotebooks(){let e=new Map;for(let t of[...this.getDefaultNotebooks(),...this.getFeedNotebooks(),...await this.getAll()])e.set(t.notebookId,t);return[...e.values()]}async getAll(){return(await this.store.getAllNotes()).filter(oj).sort((e,t)=>e.createdAt-t.createdAt).map(uj)}async getById(e){let t=Ta(e),n=await this.store.getNote(t);return n&&oj(n)?uj(n):null}create(e,t=``,n=`📓`){return this.enqueue(()=>this.createNow(e,t,n))}async createNow(e,t,n){let r=await this.getAll(),i=TA(e),a=new Set([...ij,...r.map(e=>e.slug)]),o=i;for(let e=2;a.has(o);e++)o=`${i}-${e}`;let s=Ta(o);return uj(await this.saveLanding(s,e,t,n))}async saveLanding(e,t,n,r,i){let a=cj(t,n,r),o={...await this.store.saveNoteSource({noteId:e,rawContent:a,blocks:Pa(a,{sourceRevision:i||1}),expectedSourceRevision:i??0,metadata:{title:t}}),notebookId:e,type:`note`};return i===void 0&&(o.createdAt=Date.now()),await this.store.saveNote(o),o}update(e,t){return this.enqueue(async()=>{let n=Ta(e);sj(n);let r=await this.store.getNote(n);if(!r||!oj(r))throw Error(`Notebook not found: ${e}`);let i=lj(r);return uj(await this.saveLanding(r.id,t.name??r.title,t.description??i.description,t.icon??i.icon,r.sourceRevision))})}delete(e){return this.enqueue(async()=>{let t=Ta(e);sj(t);let n=await this.listNotes(t);for(let e of n){let{notebookId:t,...n}=e;await this.store.saveNote(n)}await this.store.deleteNote(t)})}async listNotes(e){let t=Ta(e);return(await this.store.getAllNotes()).filter(e=>e.notebookId===t&&!oj(e))}moveNote(e,t){return this.enqueue(async()=>{let n=await this.store.getNote(e);if(!n)throw Error(`Note not found: ${e}`);if(t===null){let{notebookId:e,...t}=n;await this.store.saveNote(t);return}let r=Ta(t);if(this.getFeedNotebooks().some(e=>e.notebookId===r))throw Error(`Notebook ${r} is feed-delivered and read-only.`);await this.store.saveNote({...n,notebookId:r})})}cloneNote(e,t,n){return this.enqueue(async()=>{let r=await this.store.getNote(e);if(!r)throw Error(`Note not found: ${e}`);let i=r.rawContent,a={...await this.store.saveNoteSource({noteId:ze(),rawContent:i,blocks:Pa(i,{sourceRevision:1}),expectedSourceRevision:0,createdAt:Date.now(),metadata:{title:n??r.title,type:`note`,sourceId:r.id,...r.tags?.length?{tags:[...r.tags]}:{}}}),notebookId:Ta(t),seedOrigin:`user`};return await this.store.saveNote(a),a})}ensureNotebooks(){return this.enqueue(async()=>{let e=await this.store.getAllNotes();e.some(e=>oj(e)&&e.id===`notebook/defaults`)||await this.saveLanding(rj,`Defaults`,`Starter notes — clone any of them into your own notebooks.`,`📝`);for(let t of e)t.type===`template`&&await this.store.saveNote({...t,type:`note`,notebookId:t.notebookId??`notebook/defaults`});if((await this.listNotes(`notebook/defaults`)).length===0){let e="# My Workout\n\n```time\n10 Push-ups\n```\n",t=await this.store.saveNoteSource({noteId:ze(),rawContent:e,blocks:Pa(e,{sourceRevision:1}),expectedSourceRevision:0,createdAt:Date.now(),metadata:{title:`My Workout`,type:`note`}});await this.store.saveNote({...t,notebookId:rj,seedOrigin:`user`})}})}};function oj(e){return e.id.startsWith(`notebook/`)&&e.notebookId===e.id}function sj(e){if(ij.has(wa(e)))throw Error(`Notebook ${e} is always present and cannot be changed.`)}function cj(e,t,n){return`---\ndescription: ${t?JSON.stringify(t.replace(/\n/g,` `)):``}\nicon: ${n?JSON.stringify(n.replace(/\n/g,` `)):``}\n---\n\n# ${e}\n`}function lj(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e.rawContent),n=``,r=`📓`,i=e=>{if(e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`))try{return JSON.parse(e)}catch{return e}return e};if(t)for(let e of t[1].split(/\r?\n/)){let t=e.match(/^(description|icon):\s*(.*)$/);t&&(t[1]===`description`?n=i(t[2].trim()):r=i(t[2].trim())||r)}return{description:n,icon:r}}function uj(e){let{description:t,icon:n}=lj(e);return{id:e.id,slug:e.id.slice(9),notebookId:Ta(e.id),name:e.title,description:t,icon:n,origin:`user`,createdAt:e.createdAt}}var dj=new aj,fj=null,pj=new Set;function mj(e){fj!==e&&(fj=e,pj.forEach(e=>e(fj)))}function hj(){return fj}function gj(e){return pj.add(e),()=>{pj.delete(e)}}var _j=(0,U.createContext)({transport:null});function vj(){let e=(0,U.useContext)(_j),[t,n]=U.useState(()=>hj());return U.useEffect(()=>gj(n),[]),e.transport??t}var yj=({children:e,transport:t})=>{let n=(0,U.useMemo)(()=>({transport:t}),[t]);return(0,W.jsx)(_j.Provider,{value:n,children:e})},bj=(0,U.createContext)(void 0);function xj({children:e}){let[t,n]=(0,U.useState)(CA.isEnabled()),r=vj();(0,U.useEffect)(()=>{CA.setEnabled(t)},[t]);let i=(0,U.useCallback)((e,n=1)=>{if(t){if(r?.connected){console.log(`[AudioContext] Routing sound '${e}' to cast receiver`);try{r.send({type:`rpc-audio`,name:e,volume:n})}catch(t){console.error(`[AudioContext] Failed to send rpc-audio`,t),CA.playSound(e,n).catch(Sj)}}else CA.playSound(e,n).catch(Sj)}},[t,r]),a=(0,U.useCallback)(()=>{let e=!t;n(e),e&&(CA.setEnabled(!0),CA.playSound(`beep`).catch(Sj))},[t]),o=(0,U.useCallback)(()=>{i(`chime`)},[i]),s=(0,U.useCallback)(()=>{i(`click`,.5)},[i]),c=(0,U.useMemo)(()=>({isEnabled:t,toggleAudio:a,playTestSound:o,playSound:i,playClick:s}),[t,a,o,i,s]);return(0,W.jsx)(bj.Provider,{value:c,children:e})}function Sj(e){console.error(`[AudioContext] Sound playback failed`,e)}function Cj(){let e=(0,U.useContext)(bj);if(e===void 0)throw Error(`useAudio must be used within an AudioProvider`);return e}var wj=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},Tj=class{baseUrl;fetchImpl;constructor(e,t=fetch.bind(globalThis)){this.baseUrl=e,this.fetchImpl=t}async fetchManifest(){let e=await this.fetchImpl(`${this.baseUrl}manifest.json`,{cache:`no-cache`});if(!e.ok)throw new wj(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return Cy(await e.json())}async fetchChunk(e){let t=await this.fetchImpl(`${this.baseUrl}${e}`);if(!t.ok)throw new wj(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}},Ej=class{storageInstance;constructor(e){this.storageInstance=e}async getSeedMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async getNoteCommits(e){let t=await this.storageInstance.readonly(`notes`).getMany(e),n=new Map;for(let r=0;r<e.length;r++){let i=t[r];n.set(e[r],i?.seedCommit)}return n}async putSeedMeta(e,t){await this.storageInstance.transaction([`meta`],`readwrite`,async n=>{let r=n.readwrite(`meta`),i=await r.get(e.key);if(t!==void 0&&JSON.stringify(i??null)!==JSON.stringify(t))throw Error(`Seed checkpoint changed during claim`);await r.put(e)})}applyChunk(e){return Ny(this.storageInstance,e)}backfillFeedProvenance(){return Fy(this.storageInstance)}migrateNotebookVocabulary(){return Iy(this.storageInstance)}async removeSourceContent(e){return await this.storageInstance.transaction([`notes`,`attachments`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`efforts`,`equipment`,`meta`],`readwrite`,async t=>{let n=new Set,r=[];for(let[t,i]of Object.entries(e.chunks))if(i.noteIds?.length)for(let e of i.noteIds)n.add(e);else r.push(t);if(r.length)for(let e of await t.readwrite(`notes`).getAll())e.seedOrigin===`seed`&&e.seedChunkId&&r.includes(e.seedChunkId)&&n.add(e.id);let i=t.readwrite(`meta`),a=[];for(let t of await i.getAll()){let n=t;if(!n||typeof n.key!=`string`||!n.key.startsWith(`seed:`)||n.key===e.key)continue;let r=new Set;for(let e of Object.values(n.chunks??{}))for(let t of e.noteIds??[])r.add(t);a.push({key:n.key,sourceId:n.key.slice(5),rank:Wv(n.key,n.tier),meta:n,noteIds:r})}a.sort((e,t)=>t.rank-e.rank);let o=e=>a.some(t=>t.noteIds.has(e)),s=e.key.startsWith(`seed:`)?e.key.slice(5):e.key,c=t.readwrite(`notes`),l=0,u=new Set;for(let r of n){if(o(r))continue;let n=await c.get(r);if(!n||n.seedOrigin!==`seed`||n.seedChunkId&&!e.chunks[n.seedChunkId])continue;n.sourcePath&&u.add(n.sourcePath),await c.delete(r);let i=t.readwrite(`attachments`);for(let e of await i.getAllFromIndex(`by-note`,r))await i.delete(e.id);let a=t.readwrite(`note_tags`);for(let e of await a.getAllFromIndex(`by-note`,r))await a.delete(e.id);let s=t.readwrite(`block_index`);for(let e of await s.getAllFromIndex(`by-note`,r))await s.delete(e.id);let d=t.readwrite(`block_efforts`);for(let e of await d.getAllFromIndex(`by-note`,r))await d.delete(e.id);let f=t.readwrite(`block_equipment`);for(let e of await f.getAllFromIndex(`by-note`,r))await f.delete(e.id);let p=t.readwrite(`page_notes`);for(let e of await p.getAllFromIndex(`by-note`,r))await p.delete(e.id);l++}let d=[{storeName:`efforts`,familyPathPrefix:`markdown/efforts/`,parse:nl},{storeName:`equipment`,familyPathPrefix:`markdown/equipment/`,parse:rl}];for(let{storeName:e,familyPathPrefix:r,parse:i}of d){let o=t.readwrite(e);for(let t of await o.getAll()){if(t.registrySource!==`bundled`||!(t.sourceId===s||t.ownerNoteId!==void 0&&n.has(t.ownerNoteId)&&(!t.sourceId||t.sourceId===e)||t.sourcePath!==void 0&&t.sourcePath.startsWith(r)&&u.has(t.sourcePath)))continue;let l=!1;for(let n of a){let r=n.meta.chunks?.[e]?.noteIds??[];for(let e of r){let r=await c.get(e);if(!r||r.seedOrigin!==`seed`)continue;let a=i(r.rawContent);if(a&&a.slug===t.slug){await o.put({...a,registrySource:`bundled`,ownerNoteId:r.id,sourceId:n.sourceId,feedSourceId:n.sourceId,sourcePath:r.sourcePath??``}),l=!0;break}}if(l)break}l||await o.delete(t.slug)}}return await i.delete(e.key),l})}};function Dj(){return new Ej(nA)}var Oj={core:1};function kj(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function Aj(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}var jj=`wodwiki.seedSubscriptions`,Mj=`wodwiki.seedAutoSync`,Nj=null,Pj=null,Fj=new Set;function Ij(e){let t={};try{let n=localStorage.getItem(e),r=n?JSON.parse(n):{};if(r&&typeof r==`object`&&!Array.isArray(r))for(let[e,n]of Object.entries(r))typeof n==`boolean`&&(t[e]=n)}catch{t={}}return t}function Lj(){return Nj||(Nj=Ij(jj),Nj)}function Rj(e,t){let n=!0;try{localStorage.setItem(e,JSON.stringify(t))}catch{n=!1}return n}function zj(e){Nj=e;let t=Rj(jj,e);for(let e of Fj)e();return t}function Bj(e){let t=tj(e);if(t===`core`)return`full`;let n=Lj();if(n[t]===!0||n[e]===!0)return`full`;let r=`${t}#`,i=`${e}#`;return Object.entries(n).some(([e,t])=>t===!0&&(e.startsWith(r)||e.startsWith(i)))?`partial`:`unsubscribed`}function Vj(e){return e===`core`||Bj(e)!==`unsubscribed`}function Hj(e,t){if(e===`core`)return!0;let n={},r=`${e}#`;for(let[t,i]of Object.entries(Lj()))t.startsWith(r)||YA.some(n=>n.feedId===e&&n.id===t)||(n[t]=i);return n[e]=t,zj(n)}function Uj(e,t){let n=tj(e);if(n===`core`)return!0;let r=Lj(),i=`${n}#${t}`;if(i in r)return r[i]===!0;let a=`${e}#${t}`;return a in r?r[a]===!0:r[n]===!0||r[e]===!0}function Wj(e,t,n,r){if(e===`core`)return!0;let i={...Lj()},a=`${e}#${t}`,o=`${e}#`,s=r??YA.filter(t=>t.feedId===e).map(e=>e.chunkId);if(i[e]===!0&&!n){i[e]=!1;for(let n of s)n!==t&&(i[`${e}#${n}`]=!0);return i[a]=!1,zj(i)}if(i[a]=n,n&&s.length>0&&s.every(n=>n===t||i[`${e}#${n}`]===!0)){i[e]=!0;for(let e of Object.keys(i))e.startsWith(o)&&delete i[e]}else!n&&s.length>0&&s.every(t=>i[`${e}#${t}`]===!1)&&(i[e]=!1);return zj(i)}function Gj(e){let t=tj(e),n=Bj(t);if(n===`full`)return null;if(n===`unsubscribed`)return[];let r=Lj(),i=`${t}#`,a=`${e}#`;return Object.entries(r).filter(([e,t])=>t===!0&&(e.startsWith(i)||e.startsWith(a))).map(([e])=>e.startsWith(i)?e.slice(i.length):e.slice(a.length))}function Kj(e){return Fj.add(e),()=>{Fj.delete(e)}}function qj(){return Pj||(Pj=Ij(Mj),Pj)}function Jj(e){let t=qj();return e in t?t[e]===!0:e===`core`}function Yj(e,t){let n={...qj(),[e]:t},r=Rj(Mj,n);Pj=n;for(let e of Fj)e();return r}async function Lee(e,t=Dj()){let n={...Lj()},r=[],i=!1;for(let[e,t]of Object.entries(ej))e in n&&(t in n||(n[t]=n[e],n[e]&&r.push(t)),delete n[e],i=!0);for(let e of YA){let t=e.chunkId.replace(/^notebook\./,``),r=`${e.feedId}#${e.chunkId}`,a=[e.feedId];for(let[t,n]of Object.entries(ej))n===e.feedId&&a.push(t);for(let o of a)for(let a of[`collection.${t}`,`feed.${t}`,e.chunkId]){let e=`${o}#${a}`;e===r||!(e in n)||(r in n||(n[r]=n[e]),delete n[e],i=!0)}}for(let e of YA)e.id in n&&(e.feedId in n||(n[e.feedId]=n[e.id],n[e.id]&&r.push(e.feedId)),delete n[e.id]);for(let{id:i}of e)if(!(i===`core`||i in n))try{let e=await t.getSeedMeta(qv(i));e&&e.seedVersion>0&&(n[i]=!0,r.push(i))}catch{}return(r.length||i)&&zj(n),r}var Ree=`sound-`;function zee(e){if(!e.startsWith(`sound-`))return;let t=e.slice(6);return t.length>0?t:void 0}function Bee(e){let t=zee(e);return t?[{kind:`metric`,type:`sound`,value:t}]:[]}function Vee(e,t=[]){let n=[],r=new Set([...eM().map(e=>e.slug),...t.map(e=>e.name.trim())]);for(let t of e){let e=t.label.trim();e.length>0&&r.add(e)}for(let t of e){let e=t.label.trim();if(e.length===0)continue;let i=t.contributions?.length?[...t.contributions]:[...Bee(e)],a=t.type?.trim();a&&a!==e&&a!==`category`&&r.has(a)&&!i.some(e=>e.kind===`tag`&&e.slug===a)&&i.push({kind:`tag`,slug:a}),n.push({slug:e,...a===`category`?{isCategory:!0}:{},contributions:i})}return n}function Xj(e){let t=eM(),n=new Set(t.map(e=>e.slug)),r=e.filter(e=>!n.has(e.slug)||e.contributions.length>0),i=new Set(r.map(e=>e.slug));return ma([...t.filter(e=>!i.has(e.slug)),...r])}function Hee(e){return e.filter(e=>e.name.trim().length>0).map(e=>({slug:e.name.trim(),isCategory:!0,contributions:e.contributions??[]}))}async function Zj(){return Uee.loadTags()}var Uee=new class{async loadTags(){let[e,t]=await Promise.all([Z.getAllTags(),Z.getAllTagTypes().catch(()=>[])]);return[...Hee(t),...Vee(e,t)]}},Qj=ma(eM()),$j=new Set;function eM(){return[{slug:`tonnage`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]},{slug:`metabolic`,contributions:[{kind:`metric`,type:`met`,value:8},{kind:`metric`,type:`metMinutes`,value:`met * convert(elapsed, min)`},{kind:`metric`,type:`summaries.totalMetMinutes`,value:`sum(metMinutes)`}]},{slug:`kettlebell-24kg`,contributions:[{kind:`metric`,type:`resistance`,value:24,unit:`kg`},{kind:`metric`,type:`work`,value:`reps * resistance`},{kind:`metric`,type:`summaries.totalWork`,value:`sum(work)`}]}]}function tM(){return Qj}var nM=null;function rM(){return nM||=Zj().then(e=>{Qj=Xj(e);for(let e of $j)e();return Qj}).finally(()=>{nM=null}),nM}async function iM(){Qj=Xj(await Zj());for(let e of $j)e();return Qj}function aM(e){return $j.add(e),()=>$j.delete(e)}var Wee=new class{_db;constructor(e){this._db=e}get db(){return this._db??Z}async load(){return this.db.getAllEquipment()}async save(e){await this.db.saveEquipment(e)}async delete(e){await this.db.deleteEquipment(e)}};async function oM(e){let t=await Z.getAllEquipment();await e.loadBundled(t.filter(e=>e.registrySource===`bundled`)),Kee()}var sM=new Set;function Gee(e){return sM.add(e),()=>sM.delete(e)}function Kee(){for(let e of sM)e()}var cM=null;function lM(){return cM||=new yl({storage:Wee}),cM}var qee=class{storage;source;sourceId;now;constructor(e,t,n,r=Date.now){this.storage=e,this.source=t,this.sourceId=n,this.now=r}async applyAll(e={}){let t=Cy(e.manifest??await this.source.fetchManifest()),n=qv(this.sourceId),r=e.stored===void 0?await this.storage.getSeedMeta(n):e.stored,i=r?.schema===9?r:void 0,a=i??Yv(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=t.chunks.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))),s=!!(t.notebooks&&t.notebooks.length>0),c=o.filter(n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),i=a.chunks[n.id];if(e.forceAll||!i)return!0;if(r){if((r.version??0)>(i.version??0))return!0}else if(!s&&(t.version!==a.seedVersion||t.builtAt!==a.builtAt))return!0;return i.sha256!==n.sha256});c.sort((e,t)=>Number(t.id===Kv)-Number(e.id===Kv));let l=Object.keys(a.chunks).filter(e=>!t.chunks.some(t=>t.id===e)),u={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,addedNotes:0,updatedNotes:0};if(!c.length&&!l.length&&t.version===a.seedVersion&&t.builtAt===a.builtAt)return u;u.status=`imported`;let d=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:u.appliedChunks,totalChunks:c.length,totalNotes:u.totalNotes,totalEfforts:u.totalEfforts,totalEquipment:u.totalEquipment,totalBlocks:u.totalBlocks,skippedUserOwned:u.skippedUserOwned,deleted:u.deleted,addedNotes:u.addedNotes,updatedNotes:u.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}});for(let n=0;n<c.length;){let r=c.slice(n,n+(c[n]?.id===`canvas`?1:4));for(let n of r){let r,o=t.notebooks?.find(e=>e.notebookId===n.id),s=n.records,c=!!(a.chunks[n.id]&&e.granularRecords&&(o?.indexPath||n.records));if(c||e.granularRecords&&n.records&&n.records.length>0){if(c&&o?.indexPath&&(s=wy(await this.source.fetchChunk(o.indexPath)).records),s&&s.length>0){let t=!e.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(s.map(e=>e.uuid)):void 0,i=t?s.filter(e=>t.get(e.uuid)!==e.commit):s;if(c&&i.length>s.length/2){if(d(`fetching`,n.id),r=Ty(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`)}else{let e=[],t=0;for(let r of i){d(`fetching`,n.id,r.uuid,t,i.length);let a=await this.source.fetchChunk(r.recordPath),o=Array.isArray(a)?Ty(a):[Ey(a)];e.push(...o),t++}r=e}}else if(d(`fetching`,n.id),r=Ty(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`)}else if(d(`fetching`,n.id),r=Ty(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`);let l=s&&s.length>0?s.map(e=>e.uuid):await Promise.all(r.map(e=>Dy(e.path))),f={...a,seedVersion:t.version,builtAt:t.builtAt,chunks:{...a.chunks,[n.id]:{sha256:n.sha256,version:o?.version,builtAt:o?.builtAt??t.builtAt,importedAt:this.now(),noteIds:l}},importedAt:this.now()};d(`applying`,n.id);let p=await this.storage.applyChunk({chunkId:n.id,rows:r,manifest:t,expectedMeta:i,meta:f});u.totalNotes+=p.totalNotes,u.totalEfforts+=p.totalEfforts,u.totalEquipment+=p.totalEquipment,u.totalBlocks+=p.totalBlocks,u.skippedUserOwned+=p.skippedUserOwned,u.deleted+=p.deleted,u.addedNotes+=p.addedNotes,u.updatedNotes+=p.updatedNotes,u.appliedChunks++,a=f,i=f,d(`committed`,n.id),n.id===`canvas`&&e.onFirstPaintApplied?.()}n+=r.length}for(let e of l){let n={...a.chunks};delete n[e];let r={...a,chunks:n,importedAt:this.now()},o=await this.storage.applyChunk({chunkId:e,rows:[],manifest:t,expectedMeta:i,meta:r});u.deleted+=o.deleted,a=r,i=r}let f={...a,schema:9,seedVersion:t.version,builtAt:t.builtAt,importedAt:this.now()};return await this.storage.applyChunk({chunkId:null,rows:[],manifest:t,expectedMeta:i,meta:f}),d(`finalizing`,null),u}},Jee=45e3;function Yee(e){return(e instanceof Error?e.message:String(e)).replace(/(authToken["'=:\s]+)[^&\s,"']+/gi,`$1…`).replace(/(Bearer\s+)[\w.-]+/gi,`$1…`).replace(/https?:\/\/[^\s]+/gi,e=>{try{let t=new URL(e);return`${t.protocol}//${t.host}/…`}catch{return`…`}}).slice(0,300)}function Xee(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function Zee(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=qv(e.id),s={outcome:`current`,error:null,manifestChecked:!1,hadCheckpoint:!1};try{let c=await r.getSeedMeta(o);if(s.hadCheckpoint=(c?.seedVersion??0)>0,!t.force&&!t.probeManifests&&Aj(c,e.embeddedVersion))return s.outcome=`current`,s;if(Xee(c,i,a()))return s.outcome=`busy`,s;let l=Cy(await e.source.fetchManifest());s.manifestChecked=!0;let u=t.force?`import`:kj(c?.seedVersion,l.version);if(u===`server-stale`)return s.outcome=`server-stale`,s;if(c&&c.schema!==9)throw Error(`Incompatible seed checkpoint; recreate storage`);if(t.background&&!e.autoSyncOn)return s.outcome=l.chunks.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))).some(e=>{let t=l.notebooks?.find(t=>t.notebookId===e.id),n=c?.chunks[e.id];return!n||t&&(t.version??0)>(n.version??0)?!0:n.sha256!==e.sha256})?`update-pending`:`current`,s;if(!t.force&&u===`current`&&c?.schema===9&&c.builtAt===l.builtAt)return s.outcome=`current`,s;let d={...c??Yv(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(d,c??null);try{let i=await new qee(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:e.granularRecords,manifest:l,stored:d});s.outcome=`imported`,i.status===`imported`&&(s.applied=!0,s.importedVersion=l.version,s.added=i.addedNotes,s.updated=i.updatedNotes)}finally{let e=await r.getSeedMeta(o);e?.claim?.owner===i&&await r.putSeedMeta({...e,claim:null},e)}return s}catch(t){return console.warn(`[feedSync] ${e.id} seed sync failed`,t),s.outcome=`error`,s.error=Yee(t),s}}function uM(){try{return typeof localStorage<`u`&&localStorage.getItem(`wodwiki.seedImport.enabled`)!==`0`}catch{return!1}}function dM(){let e=new Set(BA()),t=jA(AA);return[{id:`core`,label:`Core`,source:new Tj(t),url:t,embeddedVersion:Oj.core??0},...WA.map(e=>({id:e.id,label:e.label,source:new Tj(e.url),url:e.url,...e.repositoryUrl?{repositoryUrl:e.repositoryUrl}:{},embeddedVersion:0,autoImport:e.autoImport??!1,tier:e.tier,...e.description?{description:e.description}:{}})),...NA().map(e=>({id:e.id,label:e.label,source:new Tj(e.url),url:e.url,repositoryUrl:e.repositoryUrl,embeddedVersion:Oj[e.id]??0,autoImport:!1}))].filter(t=>!e.has(t.id))}function fM(e){try{if(typeof BroadcastChannel<`u`){let t=new BroadcastChannel(Gv);t.postMessage(e),t.close()}}catch{}}async function pM(){_k(),await iM().catch(()=>{});let e=KO();e.isInitialized()&&await VO(e);let t=lM();t.isInitialized()&&await oM(t)}function mM(e){return e.includes(`error`)?`error`:e.includes(`imported`)?`imported`:e.includes(`update-pending`)?`update-pending`:e.includes(`server-stale`)?`server-stale`:e.includes(`busy`)?`busy`:`current`}function hM(e,t,n,r){let i=n.now??Date.now,a=n.broadcast??fM,o=n.reportActivity!==!1;if(t.manifestChecked&&CM(e.id,i()),t.outcome===`error`){let i=t.error??`feed sync failed`;n.mode===`background`&&r?.set(e.id,{sourceId:e.id,label:e.label,state:`error`}),o&&Qx(i);return}t.outcome===`imported`&&t.applied&&(a({kind:`seed-imported`,source:e.id,version:t.importedVersion}),pM(),o&&Xx({source:e.label,added:t.added??0,updated:t.updated??0}),r&&t.hadCheckpoint&&r.set(e.id,{sourceId:e.id,label:e.label,state:`updated`})),r&&t.outcome===`update-pending`&&r.set(e.id,{sourceId:e.id,label:e.label,state:`pending`})}function Qee(){return typeof Worker<`u`&&!0}async function $ee(e,t,n){return await new Promise(r=>{let i;try{i=new Worker(new URL(`/assets/feedSync.worker-6iecnGGU.js`,``+import.meta.url),{type:`module`})}catch(e){console.warn(`[feedSync] seed worker unavailable; running on main thread`,e),r(null);return}let a=t.mode===`background`?new Map:void 0,o=[],s=e.length,c=!1,l=e=>{Zx(null),i.terminate(),r(e)};i.onerror=e=>{console.warn(`[feedSync] feed worker failed`,e.message??`unknown error`),l(c?mM(o):null)},i.onmessage=n=>{c=!0;let r=n.data;if(r.type===`progress`){let n=e.find(e=>e.id===r.sourceId);Zx({sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,chunkId:r.progress.chunkId,recordId:r.progress.recordId,completedRecords:r.progress.completedRecords,totalRecords:r.progress.totalRecords,completedChunks:r.progress.completedChunks,totalChunks:r.progress.totalChunks,phase:r.progress.phase}),t.onProgress?.({...r.progress,sourceId:r.sourceId,sourceLabel:n?.label??r.sourceId,sourceIndex:e.indexOf(n)+1,totalSources:s});return}if(r.type===`first-paint`){pM(),t.onFirstPaint?.();return}if(r.type===`source-result`){let n=e.findIndex(e=>e.id===r.sourceId),i=e[n];if(!i)return;o.push(r.result.outcome),hM(i,r.result,t,a),t.onProgress?.({phase:`finished`,outcome:r.result.outcome,error:r.result.error,sourceId:i.id,sourceLabel:i.label,sourceIndex:n+1,totalSources:s});return}a&&yM([...a.values()]),l(mM(r.outcomes.length?r.outcomes:o))},i.postMessage({type:`run`,dbName:Ik(),userId:$k.currentSync()?.id??null,owner:n,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`,sources:e.map(e=>({id:e.id,label:e.label,url:jA(e.url),...e.tier?{tier:e.tier}:{},embeddedVersion:e.embeddedVersion,autoSyncOn:Jj(e.id),notebookIds:t.notebookIds===void 0?Bj(e.id)===`partial`?Gj(e.id)??void 0:t.mode===`background`&&Bj(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0}))})})}var gM=null,ete=0,_M=new Set;function tte(){return gM}function vM(e){return _M.add(e),()=>{_M.delete(e)}}function yM(e){gM=e.length?{id:++ete,updates:e}:null;for(let e of _M)e()}function bM(e){gM?.updates.some(t=>t.sourceId===e)&&yM(gM.updates.filter(t=>t.sourceId!==e))}var xM=`wodwiki.seedChecks`;function SM(){try{let e=JSON.parse(localStorage.getItem(xM)??`null`);return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`number`))}catch{return{}}}function CM(e,t){try{localStorage.setItem(xM,JSON.stringify({...SM(),[e]:t}))}catch{}}function nte(e){return SM()[e]??null}async function wM(e={}){let t=[],n=e.storage??Dj(),r=e.mode===`background`?new Map:void 0;if(!(e.isEnabled??uM)())return`disabled`;let i=e.owner??`seed-${(e.now??Date.now)()}-${Math.random().toString(36).slice(2,8)}`,a=e.sources??dM();if(!e.storage&&!e.now&&Qee()){let t=await $ee(a,e,i);if(t)return t}for(let[o,s]of a.entries()){let c=await rte(s,e,n,i,o+1,a.length,r);console.debug(`[feedSync] ${s.id} outcome: ${c}`),t.push(c)}return r&&yM([...r.values()]),mM(t)}async function TM(e={}){let t=e.sources??dM(),n=e.storage??Dj();await LM({storage:n}).catch(e=>console.warn(`[feedSync] core registry migration failed`,e));let r;try{r=await n.getSeedMeta(qv(`core`))}catch(e){return console.warn(`[feedSync] boot provider probe failed`,e),`error`}if(!r||r.seedVersion<=0)return wM({...e,sources:t.filter(e=>e.autoImport!==!1)});let i=t.filter(e=>e.id===`core`||Bj(e.id)!==`unsubscribed`);return wM({...e,sources:i,probeManifests:!0,mode:`background`,reportActivity:!1})}async function rte(e,t,n,r,i,a,o){let s=t.now??Date.now,c=t.onProgress,l=t.reportActivity!==!1,u=(t,n=null)=>c?.({phase:`finished`,outcome:t,error:n,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a});c?.({phase:`checking`,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a});let d=l?Yx(`download`,e.label):()=>{};try{let l=await Zee({id:e.id,label:e.label,source:e.source,embeddedVersion:e.embeddedVersion,autoSyncOn:Jj(e.id),...e.tier?{tier:e.tier}:{},notebookIds:t.notebookIds===void 0?Bj(e.id)===`partial`?Gj(e.id)??void 0:t.mode===`background`&&Bj(e.id)===`unsubscribed`?[]:void 0:t.notebookIds??void 0,granularRecords:!0},{storage:n,owner:r,now:s,force:t.force,probeManifests:t.probeManifests,background:t.mode===`background`},{onProgress:t=>{Zx({sourceId:e.id,sourceLabel:e.label,chunkId:t.chunkId,recordId:t.recordId,completedRecords:t.completedRecords,totalRecords:t.totalRecords,completedChunks:t.completedChunks,totalChunks:t.totalChunks,phase:t.phase}),c?.({...t,sourceId:e.id,sourceLabel:e.label,sourceIndex:i,totalSources:a})},onFirstPaint:()=>{_k(),t.onFirstPaint?.()}});return hM(e,l,t,o),u(l.outcome,l.error),l.outcome}finally{Zx(null),d()}}async function EM(e,t={}){let n=(t.sources??dM()).find(t=>t.id===e);if(!n)return console.warn(`[feedSync] unknown feed source: ${e}`),`error`;let r=await wM({...t,sources:[n]});return(r===`imported`||r===`current`)&&(t.subscribe===!1?Vj(e)||Hj(e,!1):!t.preserveSubscriptionState&&!t.notebookIds&&Hj(e,!0),bM(e)),r}async function DM(e,t,n={}){return EM(e,{...n,notebookIds:[t],preserveSubscriptionState:!0,force:!0})}async function OM(e,t,n,r={}){if(n)return Wj(e,t,!0),{outcome:await DM(e,t,r)};{Wj(e,t,!1);let n=r.storage??Dj(),i=await n.getSeedMeta(qv(e));if(!i||!i.chunks[t])return{deleted:0};let a={...i.chunks};if(delete a[t],Object.keys(a).length===0){let t=await n.removeSourceContent(i);_k();let r=KO();r.isInitialized()&&await VO(r);let a=lM();return a.isInitialized()&&await oM(a),fM({kind:`seed-removed`,source:e}),{deleted:t}}let o={...i,chunks:a,importedAt:Date.now()},s={schema:9,version:i.seedVersion,builtAt:i.builtAt,chunks:[]},c=await n.applyChunk({chunkId:t,rows:[],manifest:s,expectedMeta:i,meta:o});_k();let l=KO();l.isInitialized()&&await VO(l);let u=lM();return u.isInitialized()&&await oM(u),fM({kind:`seed-removed`,source:e}),{deleted:c.deleted}}}async function kM(e,t={}){if(e===`core`)return{deleted:0};let n=t.storage??Dj(),r=await n.getSeedMeta(qv(e)),i=r?await n.removeSourceContent(r):0;Hj(e,!1),Yj(e,!1),bM(e),_k();let a=KO();a.isInitialized()&&await VO(a);let o=lM();return o.isInitialized()&&await oM(o),fM({kind:`seed-removed`,source:e}),{deleted:i}}async function AM(e,t={}){if(e===`core`)return{deleted:0};let n=await kM(e,t);return NA().some(t=>t.id===e)?IA(e):zA(e),n}async function jM(e={}){let t=e.storage??Dj(),n=!1,r=!1;return await Promise.all((e.sources??dM()).map(async e=>{try{let i=await t.getSeedMeta(qv(e.id));if(!i||i.seedVersion<=0)return;e.autoImport===!1?r=!0:n=!0}catch{}})),{coreImported:n,libraryImported:r}}async function MM(e={}){let t=e.storage??Dj();return{sources:await Promise.all((e.sources??dM()).map(async n=>{let r=await t.getSeedMeta(qv(n.id)),i=null,a=null,o=null,s=n.repositoryUrl;try{o=Cy(await n.source.fetchManifest()),i={version:o.version,schema:o.schema,builtAt:o.builtAt},s??=kA(o.repositoryUrl??``)??void 0,CM(n.id,(e.now??Date.now)())}catch(e){a=e instanceof Error?e.message:String(e)}let c=NM(n.id,o,r);return{id:n.id,label:n.label,url:n.url,...s?{repositoryUrl:s}:{},...n.description?{description:n.description}:{},autoImport:n.autoImport!==!1,notebooks:c,stored:r?{version:r.seedVersion,schema:r.schema,builtAt:r.builtAt,importedAt:r.importedAt}:null,remote:i,remoteError:a,upToDate:r!=null&&i!=null&&r.schema===9&&r.seedVersion===i.version,count:c.reduce((e,t)=>e+t.count,0),bytes:c.reduce((e,t)=>e+t.bytes,0),checkedAt:nte(n.id),subscribed:Vj(n.id),autoSync:Jj(n.id)}}))}}function NM(e,t,n){let r={};for(let t of $A(e))r[t.chunkId]=t;let i=(t?.chunks??[]).map(t=>({id:r[t.id]?.id??t.id,label:r[t.id]?.label??t.id,chunkId:t.id,count:t.count,bytes:t.bytes,imported:!!n?.chunks[t.id],subscribed:Uj(e,t.id)}));return i.length>0?i:$A(e).map(t=>({id:t.id,label:t.label,chunkId:t.chunkId,count:0,bytes:0,imported:!!n?.chunks[t.chunkId],subscribed:Uj(e,t.chunkId)}))}async function PM(e={}){let t=e.storage??Dj(),n=0;for(let e of WA){let r=qv(e.id);try{let i=await t.getSeedMeta(r);if(i&&i.seedVersion>0)continue;let a=[];for(let n of $A(e.id)){if(n.id===e.id)continue;let r=await t.getSeedMeta(qv(n.id));r&&r.seedVersion>0&&a.push(r)}if(a.length===0)continue;let o=a.reduce((e,t)=>t.seedVersion>e.seedVersion?t:e),s=a.find(e=>e.tier)?.tier,c={key:r,schema:o.schema,seedVersion:o.seedVersion,builtAt:o.builtAt,importedAt:Math.max(...a.map(e=>e.importedAt)),chunks:Object.assign({},...a.map(e=>e.chunks)),...s?{tier:s}:{},claim:null};await t.putSeedMeta(c,i??null);for(let e of a)await t.putSeedMeta({...e,seedVersion:0,chunks:{},claim:null},e);n+=1}catch(t){console.warn(`[feedSync] legacy checkpoint adoption failed for ${e.id}`,t)}}return n}async function FM(e={}){return await(e.storage??Dj()).backfillFeedProvenance()}async function IM(e={}){return await(e.storage??Dj()).migrateNotebookVocabulary()}async function LM(e={}){let t=e.storage??Dj(),n=qv(`seed-core`),r=await t.getSeedMeta(n),i=r?.chunks??{};if(!r||r.seedVersion<=0&&Object.keys(i).length===0&&!r.claim)return!1;let a=qv(`core`),o=await t.getSeedMeta(a),s={...o?.chunks};for(let[e,t]of Object.entries(i)){let n=s[e];s[e]=n?{sha256:n.sha256,noteIds:[...new Set([...n.noteIds??[],...t.noteIds??[]])]}:{...t,noteIds:t.noteIds??[]}}let c=o?{...o,builtAt:``,claim:null,chunks:s}:{...Yv(a),chunks:s};return await t.putSeedMeta(c,o??null),await t.putSeedMeta(Yv(n),r),!0}var RM=(0,U.createContext)(null);function zM({children:e}){let[{isReady:t,error:n,revision:r},i]=(0,U.useState)({isReady:!1,error:null,revision:0}),a=KO(),o=(0,U.useCallback)(async()=>{try{await VO(a),i(e=>({isReady:!0,error:null,revision:e.revision+1}))}catch(e){i(t=>({...t,isReady:!1,error:e instanceof Error?e:Error(String(e))}))}},[a]),s=(0,U.useCallback)(async()=>{await o()},[o]);return(0,U.useEffect)(()=>{o()},[o]),(0,U.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(Gv);return e.onmessage=()=>{s()},()=>e.close()},[s]),(0,W.jsx)(RM.Provider,{value:{registry:a,isReady:t,error:n,revision:r,refresh:s},children:e})}function BM(){let e=(0,U.useContext)(RM);if(!e)throw Error(`useEffortRegistry must be within EffortRegistryProvider`);return e}var VM=(0,U.createContext)(null);function HM({children:e}){let[t,n]=(0,U.useState)(!1),[r,i]=(0,U.useState)(null),a=lM(),o=(0,U.useCallback)(async()=>{try{await oM(a),n(!0),i(null)}catch(e){i(e instanceof Error?e:Error(String(e))),n(!1)}},[a]),s=(0,U.useCallback)(async()=>{n(!1),await o()},[o]);return(0,U.useEffect)(()=>{o()},[o]),(0,U.useEffect)(()=>{if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(Gv);return e.onmessage=()=>{s()},()=>e.close()},[s]),(0,W.jsx)(VM.Provider,{value:{registry:a,isReady:t,error:r,refresh:s},children:e})}function UM(){let e=(0,U.useContext)(VM);if(!e)throw Error(`useEquipmentRegistry must be within EquipmentRegistryProvider`);return e}var WM=yt,GM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(p,{ref:n,className:G(`pointer-events-none fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]`,e),...t}));GM.displayName=p.displayName;var KM=ye(`group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full`,{variants:{variant:{default:`border bg-background text-foreground`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),qM=U.forwardRef(({className:e,variant:t,...n},r)=>(0,W.jsx)(rr,{ref:r,className:G(KM({variant:t}),e),...n}));qM.displayName=rr.displayName;var JM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(ut,{ref:n,className:G(`inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive`,e),...t}));JM.displayName=ut.displayName;var YM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(Xn,{ref:n,className:G(`absolute right-2 top-2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-destructive-foreground group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-background`,e),"toast-close":``,"aria-label":`Dismiss notification`,...t,children:(0,W.jsx)(ge,{className:`h-4 w-4`})}));YM.displayName=Xn.displayName;var XM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(Me,{ref:n,className:G(`text-sm font-semibold`,e),...t}));XM.displayName=Me.displayName;var ZM=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(sr,{ref:n,className:G(`text-sm opacity-90`,e),...t}));ZM.displayName=sr.displayName;var QM=3,$M=1e6,eN=0;function tN(){return eN=(eN+1)%(2**53-1),eN.toString()}var nN=new Map,rN=e=>{if(nN.has(e))return;let t=setTimeout(()=>{nN.delete(e),sN({type:`REMOVE_TOAST`,toastId:e})},$M);nN.set(e,t)},iN=(e,t)=>{switch(t.type){case`ADD_TOAST`:return{...e,toasts:[t.toast,...e.toasts].slice(0,QM)};case`UPDATE_TOAST`:return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case`DISMISS_TOAST`:{let{toastId:n}=t;return n?rN(n):e.toasts.forEach(e=>rN(e.id)),{...e,toasts:e.toasts.map(e=>!n||e.id===n?{...e,open:!1}:e)}}case`REMOVE_TOAST`:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},aN=[],oN={toasts:[]};function sN(e){oN=iN(oN,e),aN.forEach(e=>e(oN))}function Q(e){let t=tN(),n=()=>sN({type:`DISMISS_TOAST`,toastId:t}),r=e=>sN({type:`UPDATE_TOAST`,toast:{...e,id:t}});return sN({type:`ADD_TOAST`,toast:{...e,id:t,open:!0,onOpenChange:e=>{e||n()}}}),{id:t,dismiss:n,update:r}}function cN(){let[e,t]=U.useState(oN);return U.useEffect(()=>(aN.push(t),()=>{let e=aN.indexOf(t);e>-1&&aN.splice(e,1)}),[e]),{...e,toast:Q,dismiss:e=>sN({type:`DISMISS_TOAST`,toastId:e})}}function lN(){let{toasts:e}=cN();return(0,W.jsxs)(WM,{children:[e.map(function({id:e,title:t,description:n,action:r,...i}){return(0,W.jsxs)(qM,{...i,children:[(0,W.jsxs)(`div`,{className:`grid gap-1`,children:[t&&(0,W.jsx)(XM,{children:t}),n&&(0,W.jsx)(ZM,{children:n})]}),r,(0,W.jsx)(YM,{})]},e)}),(0,W.jsx)(GM,{})]})}var uN={activeL1Id:null,activeL2Id:null,activeL3Id:null,leftDrawerOpen:!1,rightDrawerOpen:!1,expandedIds:new Set,journalFilter:{selectedDate:null,selectedTags:[]},searchFilter:{scope:`all`}};function dN(e,t){switch(t.type){case`SET_ACTIVE_L1`:return e.activeL1Id===t.id?e:{...e,activeL1Id:t.id};case`SET_ACTIVE_L2`:return e.activeL2Id===t.id?e:{...e,activeL2Id:t.id};case`SET_ACTIVE_L3`:return e.activeL3Id===t.id?e:{...e,activeL3Id:t.id};case`SET_LEFT_DRAWER`:return e.leftDrawerOpen===t.open?e:{...e,leftDrawerOpen:t.open};case`SET_RIGHT_DRAWER`:return e.rightDrawerOpen===t.open?e:{...e,rightDrawerOpen:t.open};case`TOGGLE_EXPANDED`:{let n=new Set(e.expandedIds);return n.has(t.id)?n.delete(t.id):n.add(t.id),{...e,expandedIds:n}}case`SET_JOURNAL_DATE`:return{...e,journalFilter:{...e.journalFilter,selectedDate:t.date}};case`SET_JOURNAL_TAGS`:return{...e,journalFilter:{...e.journalFilter,selectedTags:t.tags}};case`SET_SEARCH_SCOPE`:return{...e,searchFilter:{scope:t.scope}};default:return e}}var fN=e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-80;window.scrollTo({top:e,behavior:`smooth`})}},pN=(0,U.createContext)({tree:[],navState:uN,dispatch:()=>{},l3Items:[],setL3Items:()=>{},secondarySpec:void 0,setSecondarySpec:()=>{},contextNav:void 0,setContextNav:()=>{},streamControls:null,setStreamControls:()=>{},scrollToSection:fN,registerScrollFn:()=>{},openCreateJournal:()=>{},registerCreateJournal:()=>{}});function mN(){return(0,U.useContext)(pN)}function hN(e){let{tree:t,dispatch:n}=mN();(0,U.useEffect)(()=>{e&&t.some(t=>t.id===e)&&n({type:`SET_ACTIVE_L1`,id:e})},[e,t,n])}function gN({tree:e,children:t}){let[n,r]=(0,U.useReducer)(dN,uN),[i,a]=(0,U.useState)([]),[o,s]=(0,U.useState)(void 0),[c,l]=(0,U.useState)(void 0),[u,d]=(0,U.useState)(null),f=ht(),p=(0,U.useRef)(fN),m=(0,U.useRef)(null);(0,U.useEffect)(()=>{let t=e.find(e=>e.isActive?e.isActive(f,n):e.action.type===`route`?e.action.to===`/`?f.pathname===`/`||f.pathname===``:f.pathname.startsWith(e.action.to):!1);r({type:`SET_ACTIVE_L1`,id:t?.id??null})},[f.pathname]),(0,U.useEffect)(()=>{r({type:`SET_LEFT_DRAWER`,open:!1})},[f.pathname]);let h=(0,U.useCallback)(e=>{a(t=>t.length===e.length&&t.every((t,n)=>t.id===e[n]?.id&&t.label===e[n]?.label&&t.secondaryAction?.id===e[n]?.secondaryAction?.id&&t.secondaryRunIcon===e[n]?.secondaryRunIcon)?t:e)},[]),g=(0,U.useCallback)(e=>{r({type:`SET_ACTIVE_L3`,id:e}),p.current(e)},[]),_=(0,U.useCallback)(e=>{p.current=e},[]),v=(0,U.useCallback)(e=>{m.current?.(e)},[]),y=(0,U.useCallback)(e=>{m.current=e},[]),b=(0,U.useMemo)(()=>({tree:e,navState:n,dispatch:r,l3Items:i,setL3Items:h,secondarySpec:o,setSecondarySpec:s,contextNav:c,setContextNav:l,streamControls:u,setStreamControls:d,scrollToSection:g,registerScrollFn:_,openCreateJournal:v,registerCreateJournal:y}),[e,n,i,h,o,c,l,u,g,_,v,y]);return(0,W.jsx)(pN.Provider,{value:b,children:t})}function _N(e){if(!e)return null;let t=X(e);return t.error?`Couldn't parse "${e}" — ${t.error}`:null}var vN=1e3;function yN(e){let t=(0,U.useRef)(e);t.current=e;let[n,r]=Ct(),i=n.get(`q`)??``,[a,o]=(0,U.useState)(()=>{let{defaultQuery:e,legacy:r}=t.current;return i?X(i).error?r?.salvageQ?.(i,n)??e:i:r?.toQuery(n)??e}),[s,c]=(0,U.useState)(()=>!i||!X(i).error||t.current.legacy?.salvageQ?.(i,n)?null:_N(i)),l=(0,U.useRef)(a);l.current=a;let u=(0,U.useRef)(n);u.current=n;let d=(0,U.useRef)(!1);(0,U.useEffect)(()=>{if(d.current)return;d.current=!0;let{legacy:e}=t.current,n=u.current,i=n.get(`q`)??``,a=null;if(i?X(i).error&&(a=e?.salvageQ?.(i,n)??null):a=e?.toQuery(n)??null,!a)return;let o=new URLSearchParams(n);for(let t of e?.keys??[])o.delete(t);o.set(`q`,a),r(o,{replace:!0})},[r]);let f=(0,U.useRef)(!0),p=(0,U.useRef)(null),m=(0,U.useRef)(i);(0,U.useEffect)(()=>{if(i===m.current)return;m.current=i,f.current=!0,clearTimeout(p.current),p.current=null,c(_N(i));let e=i&&!X(i).error?i:t.current.defaultQuery;o(t=>t===e?t:e)},[i]);let h=(0,U.useRef)(t.current.defaultQuery);return(0,U.useEffect)(()=>{let e=t.current.defaultQuery;e!==h.current&&(h.current=e,!i&&o(t=>t===e?t:e))},[i,t.current.defaultQuery]),(0,U.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`q`)??``;e!==m.current&&(m.current=e,f.current=!0,clearTimeout(p.current),p.current=null,c(_N(e)),o(e&&!X(e).error?e:t.current.defaultQuery))};return window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`popstate`,e),clearTimeout(p.current)}},[]),{query:a,setQuery:(0,U.useCallback)(e=>{if(o(e),!X(e).error&&e!==l.current){let t=new URLSearchParams(u.current);t.set(`q`,e),m.current=e,r(t,{replace:!f.current}),f.current=!1,clearTimeout(p.current),p.current=setTimeout(()=>{f.current=!0,p.current=null},vN)}},[r]),urlQueryError:s}}var bN=[`origin`,`discipline`];function xN(e){return/\s/.test(e)?`text:"${e}"`:`text:${e}`}function SN(e){let t=e.filter(Boolean);return`:effort${t.length?`{${t.join(`,`)}}`:``}`}function CN(e,t){let n=e.trim();if(!n||n.startsWith(`:`)||n.includes(`{`)||n.includes(`}`))return null;let r=t.get(`origin`),i=t.get(`discipline`)?.trim();return SN([xN(n),...r&&r!==`all`?[`origin:${r}`]:[],...i?[`discipline:${i}`]:[]])}function wN(e){if(!bN.some(t=>e.get(t)))return null;let t=e.get(`origin`),n=e.get(`discipline`)?.trim();return SN([...t&&t!==`all`?[`origin:${t}`]:[],...n?[`discipline:${n}`]:[]])}var TN={keys:bN,toQuery:wN,salvageQ:CN};function EN(e){return e.endsWith(`/`)&&e.length>1?e.slice(0,-1):e}function DN(e){let t=[`note`,`session`,`post`,`text`,`timePreset`,`rangeStart`,`rangeEnd`,`s`,`tags`,`mode`];return{keys:t,toQuery(n){if(!t.some(e=>n.has(e)))return null;let r=null;if(n.has(`note`)||n.has(`session`)||n.has(`post`)){let e=[];(n.get(`note`)??`include`)!==`hide`&&e.push(`journal`),(n.get(`session`)??`include`)!==`hide`&&e.push(`notebooks`),e.length===1&&(r=`source:${e[0]}`)}else e&&(r=`source:${e}`);let i=n.get(`timePreset`)??`2w`,a=i===`all`||i===`custom`?null:`last ${i}`,o=n.get(`text`)?.trim(),s=n.get(`tags`)?.trim(),c=o?/\s/.test(o)?`text:"${o}"`:`text:${o}`:null,l=s?`tags:${s}`:null,u=`:note`,d=[c,l].filter(Boolean);r===`source:journal`?u=`:journal`:r===`source:notebooks`?u=`:notebooks`:r===`source:playground`?u=`:playground`:r&&d.unshift(r);let f=d.length?`{${d.join(`,`)}}`:``;return[`${u}${f}`,a].filter(Boolean).join(` `)}}}var ON={route:`/journal`,title:`Journal`,defaultWql:`:note{notebook:journal} by {date} last 4w`,level:`note`,target:`note`,scopeOptions:[`journal`],legacy:DN(`journal`)},kN={route:`/notebooks`,title:`Notebooks`,defaultWql:`:notebook{} by {feed}`,level:`session`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,feedNotice:!0,legacy:DN(`notebooks`)},AN={route:`/notes`,title:`Notes`,defaultWql:`:note{}`,level:`note`,target:`note`,scopeOptions:[`journal`,`notebooks`],emptyMessage:`No note entries match your search.`,legacy:DN(`notebooks`)},jN={route:`/feeds`,title:`Feeds`,defaultWql:`:notebook{source:notebooks}`,level:`session`,target:`notebook`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,emptyMessage:`No feeds match your search.`,feedNotice:!0,legacy:DN(`notebooks`)},MN={route:`/pages`,title:`Pages`,defaultWql:`:page{}`,level:`note`,target:`page`,scopeOptions:[],emptyMessage:`No pages match your search.`},NN={route:`/efforts`,title:`Efforts`,defaultWql:`:effort`,level:`effort`,target:`effort`,scopeOptions:[],emptyMessage:`No efforts match your search.`,legacy:TN},PN={route:`/equipment`,title:`Equipment`,defaultWql:`:equipment{}`,level:`note`,target:`equipment`,scopeOptions:[`equipment`],emptyMessage:`No equipment matches your search.`},FN={route:`/tags`,title:`Tags`,defaultWql:`:tag{}`,level:`note`,target:`tag`,scopeOptions:[],emptyMessage:`No tags match your search.`},IN={route:`/sessions`,title:`Sessions`,defaultWql:`:session{} last 1d`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No completed session results recorded in this period.`},LN={route:`/playgrounds`,title:`Playgrounds`,defaultWql:`:playground{} by {date} last 1w`,level:`note`,target:`note`,scopeOptions:[`playground`],shelfVisible:!0,legacy:DN(`playground`)};function RN(e){return{route:`/session/${e}`,defaultWql:`:session{} from ${e} to ${e}`,level:`result`,target:`session`,scopeOptions:[],emptyMessage:`No session results recorded on ${e}.`}}function zN(e){return{route:`/results/${e}`,defaultWql:`:session{result:${e}, plane:segment}`,level:`segment`,target:`session`,scopeOptions:[],emptyMessage:`No segment records found for result ${e}.`}}function BN(e){return{route:`/notebook/${e}`,title:YO(e),defaultWql:`:note{notebook:${e}} by {date}`,level:`session`,target:`note`,scopeOptions:[`notebooks`],shelfVisible:!1,defaultLayout:`cards`,notebookSlug:e,legacy:DN(`notebooks`)}}var VN={"/journal":ON,"/notebooks":kN,"/notes":AN,"/feeds":jN,"/pages":MN,"/efforts":NN,"/equipment":PN,"/tags":FN,"/sessions":IN,"/playgrounds":LN};function HN(e){let t=EN(e),n=VN[t];if(n)return n;if(t.startsWith(`/results/`)){let e=t.slice(9);if(e)return zN(e)}if(t.startsWith(`/session/`)){let e=t.slice(9);if(e)return RN(e)}if(t.startsWith(`/notebook/`)){let e=t.slice(10);if(e&&!e.includes(`/`))return BN(e)}}function UN(e){return HN(e)??ON}function WN(e){let t=VN[EN(e)]?.title;if(t)return t;if(EN(e).startsWith(`/notebook/`)){let t=EN(e).slice(10);if(t&&!t.includes(`/`))return YO(t)}}function GN(e){let t=EN(e);if(VN[t])return!0;if(t.startsWith(`/results/`)||t.startsWith(`/session/`))return t.slice(9)!==``;if(t.startsWith(`/notebook/`)){let e=t.slice(10);return!!(e&&!e.includes(`/`))}return!1}var $={home:`/`,playgroundRoot:`/playground`,playground:`/playground/:id`,note:`/note/:noteId`,notes:`/notes`,journal:`/journal`,day:`/day/:date`,plan:`/plan`,aiFirst:`/ai-first`,feeds:`/feeds`,feed:`/feed/:slug`,notebooks:`/notebooks`,notebook:`/notebook/:slug`,notebookTarget:`/notebook/:slug/:target`,notebookItem:`/notebook/:slug/:itemDate/:item`,subscribe:`/subscribe`,pages:`/pages`,page:`/page/:slug`,tags:`/tags`,tagCategory:`/t/:type`,tag:`/t/:type/:tag`,sessions:`/sessions`,sessionDetail:`/results/:sessionId`,sessionDate:`/session/:date`,playgrounds:`/playgrounds`,tracker:`/tracker/:runtimeId`,run:`/run/:runtimeId`,load:`/load`,loadJournal:`/load/journal`,loadJournalDate:`/load/journal/:date`,efforts:`/efforts`,effort:`/effort/:slug`,equipment:`/equipment`,equipmentSlug:`/equipment/:slug`,dashboards:`/dashboards`,dashboardView:`/dashboard/:slug`,settings:`/settings`,settingsAppearance:`/settings/appearance`,settingsProfile:`/settings/profile`,settingsStorage:`/settings/storage`,settingsSync:`/settings/sync`,settingsSystem:`/settings/system`,settingsTags:`/settings/tags`,settingsSoundProfiles:`/settings/sound-profiles`,settingsData:`/settings/data`,settingsDatabase:`/settings/database`,settingsQueries:`/settings/queries`};function KN(e){return`/playground/${encodeURIComponent(e)}`}function qN(e){return`/day/${encodeURIComponent(e)}`}function JN(e,t){return`/day/${encodeURIComponent(e)}?autoStart=${encodeURIComponent(t)}`}function YN(e){return`/note/${encodeURIComponent(e)}`}function XN(e){return`/notebook/${encodeURIComponent(e)}`}function ZN(e,t){return`/notebook/${encodeURIComponent(e)}/${t.split(`/`).map(encodeURIComponent).join(`/`)}`}function QN(e){return`/run/${encodeURIComponent(e)}`}function $N({zip:e}){return`/load?zip=${encodeURIComponent(e)}`}function eP(e){return`/results/${encodeURIComponent(e)}`}function tP(e){return`/page/${encodeURIComponent(e)}`}function nP(){return`/playgrounds`}function rP(){return`/efforts`}function iP(e){return`/equipment/${encodeURIComponent(e)}`}function aP(e,t){return`/t/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function oP(e){let t=new URLSearchParams;e?.q&&t.set(`q`,e.q),e?.weeks&&t.set(`weeks`,String(e.weeks));let n=t.toString();return`/dashboards${n?`?${n}`:``}`}function sP(){return`/dashboards`}function cP(e){return`/dashboard/${encodeURIComponent(e)}`}function lP(e,t,n){let r=new URLSearchParams;if(t)for(let[e,n]of Object.entries(t))r.set(e,n);n?.mode&&r.set(`mode`,n.mode),n?.tab&&r.set(`tab`,n.tab);let i=r.toString();return i?`/effort/${encodeURIComponent(e)}?${i}`:`/effort/${encodeURIComponent(e)}`}function uP(e){return{mode:e.get(`mode`)??void 0,tab:e.get(`tab`)??void 0,q:e.get(`q`)??void 0,origin:e.get(`origin`)??void 0}}function dP(e){return e.startsWith(`/playground/`)}function fP(e){return e===`/efforts`||e.startsWith(`/effort/`)||e===`/t/effort`||e.startsWith(`/t/effort/`)}function pP(e){return e===`/equipment`||e.startsWith(`/equipment/`)||e===`/t/equipment`||e.startsWith(`/t/equipment/`)}function mP(e){let t=e.match(/^\/notebook\/([^/]+)\/([^/]+)\/([^/]+)$/);return t?[t[1],t[2],t[3]]:null}function hP(e){let t=e.match(/^\/feed\/([^/]+)$/);return t?t[1]:null}function gP(e){if(!e)return``;let t=e.split(`-`);return t.length>1?t[t.length-1]:e}function _P(e){return typeof File<`u`&&e instanceof File?!1:`file`in e&&e.file!==void 0||`data`in e&&e.data!==void 0}async function vP(e){let t=Date.now();if(!_P(e))return{label:e.name,mimeType:e.type,data:await e.arrayBuffer(),timeSpan:{start:t,end:t}};let n=`file`in e?e.file:void 0,r=`data`in e?e.data:void 0,i;if(r!==void 0)i=r;else{if(!n)throw Error(`Attachment input requires either file or data, but neither was provided`);i=await n.arrayBuffer()}return{id:e.id,label:e.label??n?.name??`Attachment`,mimeType:e.mimeType??n?.type??`application/octet-stream`,data:i,timeSpan:e.timeSpan??{start:t,end:t}}}function yP(e){return{id:e.id,outputType:e.outputType,timeSpan:{started:e.timeSpan.started,ended:e.timeSpan.ended},metrics:e.metrics.toArray(),hints:(()=>{let t=eo(e);return t.length?t:void 0})(),sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,parent:e.parent,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,completionReason:e.completionReason}}function bP(e){return new fa({outputType:e.outputType,timeSpan:e.timeSpan,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,metrics:e.metrics,parent:e.parent,completionReason:e.completionReason})}function xP(e){return{...e,metrics:e.metrics.filter(e=>e.origin!==`analyzed`)}}function SP(e,t){let{engine:n}=jp(t.block,{effortResolver:t.effortResolver,userProfile:t.userProfile,calcs:t.calcs,tags:t.tags,activeTags:t.activeTags,propertySources:t.propertySources}),r=[];for(let t of e){if(t.outputType===`analytics`)continue;if(t.outputType!==`segment`){r.push(t);continue}let e=xP(t),i=n.run(bP(e)),a=t.metrics.filter(e=>e.origin===`analyzed`&&!i.metrics.some(t=>t.origin===`analyzed`&&t.type===e.type));r.push(yP(a.length?new fa({...i,metrics:[...i.metrics,...a]}):i))}return[...r,...n.finalize().map(yP)]}function CP(e,t,n){return SP(d_(t),{block:e,...n})}var wP={soreness:{unit:`rating`,label:`Soreness`,min:1,max:10},sleep:{unit:`h`,label:`Sleep`},hrv:{unit:`ms`,label:`HRV`},weight:{unit:`kg`,label:`Bodyweight`},hang:{unit:`kg`,label:`Max Hang Weight`},hr:{unit:`bpm`,label:`Avg Heart Rate`},planned:{unit:`count`,label:`Planned Sessions`}};function TP(e){let t=/^(-?\d+(?:\.\d+)?)\s*([a-z%]*)$/i.exec(e.trim());if(t)return{value:parseFloat(t[1]),unit:t[2]||void 0}}function EP(e){let t=new Map;for(let n of e.split(`
76
76
  `)){let e=/^([a-z][a-z0-9]*)\s*[:=]\s*(.+)$/i.exec(n.trim());if(!e)continue;let r=e[1].toLowerCase(),i=wP[r];if(!i)continue;let a=TP(e[2]);a&&(i.min!==void 0&&a.value<i.min||i.max!==void 0&&a.value>i.max||t.set(r,{key:r,value:a.value,unit:a.unit??i.unit,label:i.label}))}return[...t.values()]}function DP(e){let t=new Map,n=/```wellness[^\S\n]*\n([\s\S]*?)```/g,r;for(;(r=n.exec(e))!==null;)for(let e of EP(r[1]))t.set(e.key,e);return[...t.values()]}function OP(e,t,n={}){let r=DP(t);if(r.length===0)return[];let i=n.targetDate??n.now??Date.now(),a=new Date(i),o=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,`0`)}-${String(a.getDate()).padStart(2,`0`)}`,s=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime();return r.map(t=>({id:kP(e,t.key),resultId:`wellness:${e}`,noteId:e,timestamp:s,grain:`summary`,origin:`user`,outputType:`wellness`,representationKind:`direct`,metrics:[{type:t.key,value:t.value,unit:t.unit,origin:`user`,metadata:{canonicalKey:t.key}}],metricTemporal:[{temporalKind:`civil-date`,civilDate:o}]}))}function kP(e,t){return`wellness:${e}:${t}`}async function AP(e,t,n,r={}){let i=OP(e,t,r),a=new Set(i.map(e=>e.id)),o=(await n.getEventsForNote(e)).filter(t=>t.id.startsWith(`wellness:${e}:`)),s=i.filter(e=>{let t=o.find(t=>t.id===e.id);return!t||t.metrics[0]?.value!==e.metrics[0]?.value||t.timestamp!==e.timestamp}),c=o.filter(e=>!a.has(e.id)).map(e=>e.id);return s.length>0&&await n.appendEvents(s),c.length>0&&await n.deleteEvents(c),{written:s.length,deleted:c.length}}function jP(e){return[...e].sort((e,t)=>t.createdAt-e.createdAt)}function MP(e,t){return t==null?e:e.slice(0,t)}var NP=class e{storage;contentProvider;constructor(e=Z,t=new _A(e)){this.storage=e,this.contentProvider=t}async createNote(e){if(await this.contentProvider.persistenceReady,await this.storage.getNote(e.id))throw Error(`Note already exists: ${e.id}`);return this.contentProvider.saveRecord({id:e.id,title:e.title,rawContent:e.rawContent,tags:e.tags??[],targetDate:e.targetDate,journalDate:e.journalDate,type:e.type??`note`,slug:e.slug,sourceId:e.sourceId})}async getNote(e,t={}){await this.contentProvider.persistenceReady;let n=await this.resolveNote(e);if(!n)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);let r=t.projection??`workbench`,i=t.includeSections??r!==`summary`,a=t.includeAttachments??!1,o=await this.contentProvider.getRecord(n.id);if(!o)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);let s=r===`summary`?{}:await this.selectResults(n,t.resultSelection),c=a?await this.storage.getAttachmentsForNote(n.id):void 0;return{...o,...s,sections:i?o.sections:void 0,attachments:c}}async listNotes(e={}){if(e.ids&&e.ids.length>0){let t=e.projection??`summary`;return Promise.all(e.ids.map(e=>this.getNote(e,{projection:t,...t===`history-detail`&&{resultSelection:{mode:`all-for-note`}}})))}let t=await this.contentProvider.getRecords(e);if(e.journalDate&&(t=t.filter(t=>t.placements&&t.placements.length>0?t.placements.some(t=>t.date===e.journalDate):t.journalDate===e.journalDate)),e.kind&&(t=t.filter(t=>t.type===e.kind)),e.search){let n=e.search.toLowerCase();t=t.filter(e=>e.title.toLowerCase().includes(n)||e.rawContent.toLowerCase().includes(n))}return e.projection===`history-detail`&&(t=await Promise.all(t.map(e=>this.getNote(e.id,{projection:`history-detail`,resultSelection:{mode:`all-for-note`}})))),(e.offset||e.limit)&&(t=t.slice(e.offset??0,(e.offset??0)+(e.limit??t.length))),t}async mutateNote(e,t){await this.contentProvider.persistenceReady;let n=await this.resolveNote(e);if(!n)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);if(t.expectedSourceRevision!==void 0&&t.expectedSourceRevision!==n.sourceRevision)throw new yb(`STALE_SOURCE`,`Note ${n.id} changed since it was loaded`);let r=t.attachments?.add?await Promise.all(t.attachments.add.map(e=>vP(e))):[];return await this.storage.withTransaction([`notes`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`,`block_revisions`,`sessions`,`events`,`attachments`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`],async e=>{let i=new _A(e);if(await i.updateRecord(n.id,{...t.metadata,rawContent:t.rawContent,blocks:t.blocks,expectedSourceRevision:t.expectedSourceRevision,results:t.workoutResult?.data,blockId:t.workoutResult?.blockId,blockVersion:t.workoutResult?.blockVersion,blockContentId:t.workoutResult?.blockContentId,origin:t.workoutResult?.origin,resultId:t.workoutResult?.id}),t.rawContent!==void 0&&t.rawContent!==n.rawContent){let r=await i.getRecord(n.id);await AP(n.id,t.rawContent,e,{targetDate:r?.targetDate})}for(let i of r)await e.saveAttachment({...i,id:i.id??ze(),noteId:n.id,resultId:t.workoutResult?.id,createdAt:Date.now()});for(let n of t.attachments?.remove??[])await e.deleteAttachment(n)}),this.getNote(n.id,{includeAttachments:!!t.attachments})}async saveNote(e){if(await this.contentProvider.persistenceReady,await this.storage.getNote(e.noteId))return this.mutateNote(e.noteId,{rawContent:e.rawContent,blocks:e.blocks,expectedSourceRevision:e.expectedSourceRevision,metadata:e.metadata});if(e.expectedSourceRevision!==0)throw new yb(`STALE_SOURCE`,`Note ${e.noteId} no longer exists`);return this.contentProvider.saveRecord({id:e.noteId,rawContent:e.rawContent,blocks:e.blocks,sourceRevision:0,title:e.metadata?.title??`Workout Note`,tags:e.metadata?.tags??[],targetDate:e.metadata?.targetDate??Date.now(),journalDate:e.metadata?.journalDate,slug:e.metadata?.slug??void 0,type:e.metadata?.type??e.noteType,sourceId:e.metadata?.sourceId??void 0,createdAt:e.createdAt})}async startSession(t,n){if(await this.contentProvider.persistenceReady,n.noteId!==t.noteId)throw new yb(`RESULT_NOTE_MISMATCH`,`Session belongs to another Note`);return this.storage.withTransaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`sessions`,`events`,`page`,`page_notes`,`tags`,`note_tags`,`tag_types`],async r=>{await new e(r,new _A(r)).saveNote(t);let i=await r.getNote(t.noteId),a=i?.blocks[n.blockId];if(!i||!a||a.kind!==`wod`)throw new yb(`BLOCK_REVISION_NOT_FOUND`,`Selected workout is not in the saved Note`);let o=await r.getBlockRevision(i.id,a.id,a.version);if(!o)throw new yb(`BLOCK_REVISION_NOT_FOUND`,`Selected workout revision is missing`);if(await r.getSessionById(n.id))throw Error(`Session already exists: ${n.id}`);let s=Ma(o.rawContent,{registeredWidgets:Oa}).find(e=>e.scriptBlock),c={...n,blockId:a.id,blockVersion:o.version,blockContentId:s?.scriptBlock?.contentId,status:`in-progress`};return await r.saveSession(c),{note:i,revision:o,session:c}})}async finishSession(e,t,n){return await this.contentProvider.persistenceReady,this.storage.withTransaction([`sessions`,`block_revisions`,`events`],async r=>{let i=await r.getSessionById(e);if(!i)throw new yb(`RESULT_NOT_FOUND`,`Session not found: ${e}`);if(!await r.getBlockRevision(i.noteId,i.blockId,i.blockVersion))throw new yb(`BLOCK_REVISION_NOT_FOUND`,`Pinned workout revision is missing`);let a={...i,startTime:t.startTime,endTime:t.endTime,duration:t.duration??0,roundsCompleted:t.roundsCompleted,totalRounds:t.totalRounds,repsCompleted:t.repsCompleted,completed:t.completed,status:`completed`,createdAt:n??i.createdAt};if(await r.saveSession(a),t.logs?.length){let e={noteId:a.noteId,resultId:a.id,blockId:a.blockId,blockVersion:a.blockVersion,blockContentId:a.blockContentId,origin:a.origin,pageId:a.pageId,workoutTimestamp:a.endTime};await r.appendEvents(c_(t.logs,e)),await r.finalizeSummaries(a.id,l_(t.logs,e))}return a})}async getBlockRevision(e,t,n){return await this.contentProvider.persistenceReady,this.storage.getBlockRevision(e,t,n)}async getBlockHistory(e,t){return await this.contentProvider.persistenceReady,this.storage.getBlockHistory(e,t)}async getNoteBlockHistory(e){return await this.contentProvider.persistenceReady,this.storage.getNoteBlockHistory(e)}async deleteNote(e){await this.contentProvider.persistenceReady;let t=await this.resolveNote(e);if(!t)throw new yb(`NOTE_NOT_FOUND`,`Note not found: ${this.describeLocator(e)}`);await this.contentProvider.deleteRecord(t.id)}async getSessionById(e){return await this.contentProvider.persistenceReady,this.storage.getSessionById(e)}async rederiveResultAnalytics(e){await this.contentProvider.persistenceReady;let t=await this.storage.getSessionById(e);if(!t)throw new yb(`RESULT_NOT_FOUND`,`Result not found: ${e}`);let n=await this.storage.getBlockRevision(t.noteId,t.blockId,t.blockVersion),r=n&&Ma(n.rawContent).find(e=>e.scriptBlock)?.scriptBlock;if(!r||n?.kind!==`wod`)throw new yb(`BLOCK_REVISION_NOT_FOUND`,`Cannot re-derive result ${e}: pinned workout revision is missing`);let i={...r,id:t.blockId,version:t.blockVersion,dialect:n.dialect,sport:n.sport,statements:_c().read(r.content,n.sport).statements},a=this.storage.getEventsByResult?await this.storage.getEventsByResult(e):[],o=CP(i,a);if(this.storage.appendEvents&&this.storage.finalizeSummaries){let e={noteId:t.noteId,resultId:t.id,blockId:t.blockId,blockVersion:t.blockVersion,blockContentId:t.blockContentId,origin:t.origin,pageId:t.pageId,workoutTimestamp:t.createdAt};await this.storage.withTransaction([`events`],async n=>{a.length>0&&await n.deleteEvents(a.map(e=>e.id)),await n.appendEvents(c_(o,e)),await n.finalizeSummaries(t.id,l_(o,e))})}return t}async resolveNote(e){if(typeof e==`string`)return this.resolveByAnyId(e);if(e.id)return this.resolveByAnyId(e.id);if(e.slug)return this.resolveByAnyId(e.slug);let t=await this.storage.getAllNotes();if(e.shortId)return t.find(t=>gP(t.id)===e.shortId);let n=e.title;if(n)return t.find(e=>e.title.toLowerCase()===n.toLowerCase())}async resolveByAnyId(e){return await this.storage.getNote(e)||await this.storage.getNoteBySlug?.(e)||(await this.storage.getAllNotes()).find(t=>gP(t.id)===e||t.title.toLowerCase()===e.toLowerCase())}describeLocator(e){return typeof e==`string`?e:e.id??e.slug??e.shortId??e.title??`<empty locator>`}async getSimilarSessions(e,t={}){let n=await this.storage.getSessionsByContentId(e);return t.excludeNoteId&&(n=n.filter(e=>e.noteId!==t.excludeNoteId)),t.includePlayground||(n=n.filter(e=>e.origin!==`playground`)),MP(jP(n),t.limit)}async selectResults(e,t={mode:`latest`}){let n=async e=>!e||!this.storage.getEventsByResult?[]:this.storage.getEventsByResult(e.id);if(t.mode===`by-result-id`){let r=await this.storage.getSessionById(t.resultId);if(!r)throw new yb(`RESULT_NOT_FOUND`,`Result not found: ${t.resultId}`);if(r.noteId!==e.id)throw new yb(`RESULT_NOTE_MISMATCH`,`Result ${t.resultId} does not belong to note ${e.id}`);return{results:vb(r,await n(r))}}if(t.mode===`latest-for-section`||t.mode===`all-for-section`){let n=jP(await this.storage.getSessionsForSection(e.id,t.blockId));if(t.mode===`all-for-section`){let e=MP(n,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(n[0])}}let r=jP(await this.storage.getSessionsForNote(e.id));if(t.mode===`all-for-note`){let e=MP(r,t.limit);return{results:await this.payloadOf(e[0]),extendedResults:e}}return{results:await this.payloadOf(r[0])}}async payloadOf(e){return e?vb(e,this.storage.getEventsByResult?await this.storage.getEventsByResult(e.id):[]):void 0}},PP=new NP;function FP(e){return Object.entries(e).filter(([e])=>e.startsWith(`markdown/dashboards/`)).map(([e,t])=>{let{meta:n}=Qy(t),r=e.split(`/`).pop().replace(/\.md$/,``);return{slug:typeof n.slug==`string`&&n.slug?n.slug:r,title:typeof n.title==`string`&&n.title?n.title:r,rawContent:t}}).sort((e,t)=>e.title.localeCompare(t.title))}function IP(e){return e.map(e=>{let{meta:t}=Qy(e.rawContent);if(t.dashboard!==`true`)return null;let n=typeof t.slug==`string`&&t.slug?t.slug:null,r=typeof t.title==`string`&&t.title?t.title:n??e.id;return n?{noteId:e.id,slug:n,title:r,rawContent:e.rawContent}:null}).filter(e=>e!==null)}function LP(e,t){let n=bk(),r=(0,U.useMemo)(()=>n?FP(n):[],[n]),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(!0);return(0,U.useEffect)(()=>{if(!e){a(null),s(!1);return}let t=!1;return s(!0),PP.listNotes({kind:`dashboard`}).then(n=>{if(t)return;let i=IP(n).find(t=>t.slug===e);if(i)a({slug:e,title:i.title,rawContent:i.rawContent,editable:!0,noteId:i.noteId});else{let t=r.find(t=>t.slug===e);a(t?{slug:t.slug,title:t.title,rawContent:t.rawContent,editable:!1}:null)}}).catch(()=>{t||a(null)}).finally(()=>{t||s(!1)}),()=>{t=!0}},[e,t,r]),{source:i,loading:o}}function RP(){let e=bk(),t=(0,U.useMemo)(()=>e?FP(e):[],[e]),[n,r]=(0,U.useState)([]),[i,a]=(0,U.useState)(!0);return(0,U.useEffect)(()=>{let e=!1;return PP.listNotes({kind:`dashboard`}).then(n=>{if(e)return;let i=IP(n),a=new Set(i.map(e=>e.slug)),o=[...i.map(e=>({slug:e.slug,title:e.title,editable:!0})),...t.filter(e=>!a.has(e.slug)).map(e=>({slug:e.slug,title:e.title,editable:!1}))];e||r(o)}).catch(()=>{e||r(t.map(e=>({slug:e.slug,title:e.title,editable:!1})))}).finally(()=>{e||a(!1)}),()=>{e=!0}},[t]),{items:n,loading:i}}var zP=/^#{1,6}\s+/;function BP(e){return(e??``).replace(zP,``).trim()}function VP(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function HP(){return VP(new Date)}function UP(e){return e<HP()}function WP(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;let n=Number(t[1]),r=Number(t[2])-1,i=Number(t[3]),a=new Date(n,r,i),o=VP(a);return o===e?{dateKey:o,date:a}:null}function GP(e){let t=WP(e);if(!t)throw Error(`Invalid journal date: ${e}`);return t.date.getTime()}function KP({persistence:e,moveRecordPlacement:t,addRecordPlacement:n,uuid:r=ze}){let i=new Map;return{async create(t){let n=t.journalDate?GP(t.journalDate):Date.now();return e.createNote({id:r(),title:BP(t.title),rawContent:t.rawContent,tags:t.tags??[],targetDate:n,journalDate:t.journalDate||void 0,type:t.type??`journal`,slug:t.slug,sourceId:t.sourceId})},getById(t){return e.getNote({id:t},{projection:`workbench`,resultSelection:{mode:`all-for-note`},includeSections:!0,includeAttachments:!0})},resolve(t){return e.getNote(t,{projection:`workbench`,resultSelection:{mode:`all-for-note`},includeSections:!0,includeAttachments:!0})},async listByDate(t){return GP(t),(await e.listNotes({journalDate:t,kind:`journal`,projection:`summary`})).sort((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id))},update(t,n,r){let a=t.id,o=BP(n.match(/^#\s+(.+)$/m)?.[1]?.trim()),s=t.sourceRevision;if(s===void 0)return Promise.reject(Error(`Loaded Note source revision is required`));let c=0;for(;c<t.rawContent.length&&c<n.length&&t.rawContent[c]===n[c];)c++;let l=t.rawContent.length,u=n.length;for(;l>c&&u>c&&t.rawContent[l-1]===n[u-1];)l--,u--;let d=Ia(t.blocks??{},r?.changes??[{from:c,to:l,insert:n.slice(c,u)}]);for(let e of r?.retainedBlocks??[]){let n=Object.values(t.blocks??{}).find(t=>t.from===e.from&&t.to===e.to);n&&(d[n.id]={...n,from:e.nextFrom,to:e.nextTo})}let f=Pa(n,{sourceRevision:s,registeredWidgets:Oa,blocks:d}),p=async()=>e.mutateNote({id:a},{rawContent:n,blocks:f,expectedSourceRevision:s,metadata:o?{title:o}:void 0}),m=(i.get(a)??Promise.resolve()).then(p,p);i.set(a,m);let h=()=>{i.get(a)===m&&i.delete(a)};return m.then(h,h),m},async moveToDate(r,i){let a=GP(i);if(t&&n){let a=(await e.getNote({id:r},{projection:`summary`})).placements?.find(e=>e.date);return a?t(r,a.pageId,{date:i}):n(r,{date:i})}return e.mutateNote({id:r},{metadata:{journalDate:i,targetDate:a}})},delete(t){return e.deleteNote({id:t})}}}var qP=new _A,JP=KP({persistence:PP,moveRecordPlacement:(e,t,n)=>qP.moveRecordPlacement(e,t,n),addRecordPlacement:(e,t)=>qP.addRecordPlacement(e,t)});function YP({persistence:e,journal:t}){async function n(n){let r=await e.listNotes({kind:`dashboard`});for(let e of r){if(n&&e.id===n)continue;let{meta:r,body:i}=Qy(e.rawContent);if(r.dashboard!==`true`||r[`dashboard.active`]!==`true`)continue;let a={...r};delete a[`dashboard.active`],await t.update(e,`---\n${nb(a)}\n---\n${i}`)}}return{async createDashboard(e=gv){return await n(),t.create({title:e,rawContent:vv(e),type:`dashboard`,sourceId:`dashboards`})},async cloneDashboard(e,r,i){await n();let{meta:a,body:o}=Qy(r),s={...a,slug:e};i&&(s.title=i);let c=`---\n${nb(s)}\n---\n${o}`;return t.create({title:typeof s.title==`string`?s.title:e,rawContent:c,type:`dashboard`,sourceId:`dashboards`})}}}var XP=YP({persistence:PP,journal:JP}),ZP=[{query:`sum:totalVolume{discipline:strength} by {week}`,label:`Weekly strength volume`,question:`Is strength volume rising?`},{query:`avg:tis{effort:thruster} by {week}`,label:`Thruster time-in-motion`,question:`Is time-in-motion improving?`},{query:`sum:totalReps{discipline:strength} by {effort}`,label:`Reps by lift`,question:`Where do the reps go?`},{query:`last:sessionLoad{note:benchmark} by {session}`,label:`Benchmark loads`,question:`Is session load dropping?`},{query:`sum:sessionLoad{} by {intensity, week}`,label:`Polarized weekly load`,question:`Is my intensity 80/20?`},{query:`avg:calc.acwr{} by {day}`,label:`Injury risk (ACWR)`,question:`Am I spiking my workload?`},{query:`count:totalReps{tags:mobility} by {week}`,label:`Mobility habit`,question:`Did I do mobility work?`},{query:`avg:tis{} by {round}`,label:`TIS by round`,question:`Where does the pace fall apart?`},{query:`sum:totalVolume{} by {effort}`,label:`Volume by lift`,question:`Where does the volume go?`},{query:`:note{tags:pr,source:journal}`,label:`Find PR notes`,question:`Which notes are tagged PR?`},{query:`:note{type:wod,source:journal} last 8w`,label:`Recent workouts`,question:`What workouts did I do recently?`},{query:`:note{source:feeds}`,label:`Notebook workouts`,question:`What workouts are in the library?`},{query:`:block{text:fran}`,label:`Find Fran everywhere`,question:`Which blocks mention Fran?`}],QP=(0,U.createContext)(()=>{});function $P({close:e,children:t}){return(0,W.jsx)(QP.Provider,{value:e,children:t})}function eF(){return(0,U.useContext)(QP)}function tF(e,t){if(!e)return!1;if(e===t)return!0;let n=X(e),r=X(t);return!n.error&&!r.error&&qh(n)===qh(r)}function nF(e){let t=ht(),n=yn(),r=eF(),{items:i,loading:a}=RP(),[o,s]=(0,U.useState)(!1),c=async()=>{s(!0);try{let e=await XP.createDashboard(),{meta:t}=Qy(e.rawContent),i=typeof t.slug==`string`&&t.slug?t.slug:e.id;n(cP(i)),r()}finally{s(!1)}},l=t.pathname===`/dashboards`,u=l?new URLSearchParams(t.search).get(`q`):null;return(0,W.jsxs)(`div`,{className:`flex flex-col gap-1 px-2 py-3`,"data-testid":`dashboards-nav-panel`,children:[(0,W.jsx)(rF,{label:`Explorer`,active:l,onClick:()=>{n(sP()),r()}}),l?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`mt-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 px-3`,children:`Examples`}),ZP.map(e=>(0,W.jsx)(rF,{label:e.label,title:e.question,active:tF(u,e.query),onClick:()=>{n(oP({q:e.query})),r()}},e.query))]}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`mt-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground/60 px-3`,children:`Dashboards`}),a?(0,W.jsx)(`div`,{className:`px-3 py-2 text-xs text-muted-foreground/60`,children:`Loading…`}):i.length===0?(0,W.jsx)(`div`,{className:`px-3 py-2 text-xs text-muted-foreground/60`,children:`No dashboards yet.`}):i.map(e=>(0,W.jsx)(rF,{label:e.title,badge:e.editable?void 0:`prebuilt`,active:t.pathname===`/dashboard/${e.slug}`,onClick:()=>{n(cP(e.slug)),r()}},e.slug)),(0,W.jsxs)(`button`,{type:`button`,onClick:c,disabled:o,"data-testid":`dashboards-nav-new`,className:`mt-2 flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-muted hover:text-foreground transition-colors disabled:opacity-50`,children:[(0,W.jsx)(Rt,{className:`size-3.5`}),`New dashboard`]})]})]})}function rF({label:e,active:t,onClick:n,badge:r,title:i}){return(0,W.jsxs)(`button`,{type:`button`,onClick:n,title:i,className:G(`flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-left transition-colors`,t?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:[(0,W.jsx)(`span`,{className:G(`size-2 rounded-full shrink-0`,t?`bg-primary`:`bg-border`)}),(0,W.jsx)(`span`,{className:`truncate`,children:e}),r&&(0,W.jsx)(`span`,{className:`ml-auto text-[9px] font-bold uppercase tracking-wide text-muted-foreground/50 shrink-0`,children:r})]})}function iF({children:e}){return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`absolute left-1/2 top-1/2 size-[max(100%,2.75rem)] -translate-x-1/2 -translate-y-1/2 pointer-events-auto`,"aria-hidden":`true`}),e]})}var aF=(0,U.forwardRef)(function(e,t){return(0,W.jsx)(ne,{children:(0,W.jsx)(Vn,{...e,to:e.href,ref:t})})});function oF({className:e,...t}){return(0,W.jsx)(`nav`,{...t,className:ct(e,`flex h-full min-h-0 flex-col`)})}function sF({className:e,...t}){return(0,W.jsx)(`div`,{...t,className:ct(e,`flex flex-col border-b border-zinc-950/5 p-4 dark:border-white/5 [&>[data-slot=section]+[data-slot=section]]:mt-2.5`)})}function cF({className:e,...t}){return(0,W.jsx)(`div`,{...t,className:ct(e,`flex flex-1 flex-col overflow-y-auto p-4 [&>[data-slot=section]+[data-slot=section]]:mt-8`)})}function lF({className:e,...t}){let n=(0,U.useId)();return(0,W.jsx)(nee,{id:n,children:(0,W.jsx)(`div`,{...t,"data-slot":`section`,className:ct(e,`flex flex-col gap-0.5`)})})}var uF=(0,U.forwardRef)(function({current:e,className:t,children:n,...r},i){let a=ct(`group flex w-full items-center gap-3 rounded-xl px-2 py-2.5 text-left text-base/6 font-medium text-foreground sm:py-2 sm:text-sm/5 transition-all duration-200`,`[&>[data-slot=icon]]:size-6 [&>[data-slot=icon]]:shrink-0 [&>[data-slot=icon]]:text-muted-foreground sm:[&>[data-slot=icon]]:size-5 [&>[data-slot=icon]]:transition-colors`,`[&>[data-slot=icon]:last-child]:ml-auto [&>[data-slot=icon]:last-child]:size-5 sm:[&>[data-slot=icon]:last-child]:size-4`,`[&>[data-slot=avatar]]:-m-0.5 [&>[data-slot=avatar]]:size-7 sm:[&>[data-slot=avatar]]:size-6`,`data-[hover]:bg-primary/10 data-[hover]:text-primary data-[hover]:[&>[data-slot=icon]]:text-primary`,`data-[active]:bg-primary/15 data-[active]:scale-[0.98]`,`data-[current]:bg-primary/10 data-[current]:text-primary data-[current]:[&>[data-slot=icon]]:text-primary font-bold`);return(0,W.jsxs)(`span`,{className:ct(t,`relative`),children:[e&&(0,W.jsx)(Ht.span,{layoutId:`current-indicator`,className:`absolute inset-y-2 -left-4 w-1 rounded-full bg-primary shadow-[0_0_8px_rgba(129,140,248,0.5)]`}),typeof r.href==`string`?(0,W.jsx)(it,{as:aF,...r,className:a,"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:(0,W.jsx)(iF,{children:n})}):(0,W.jsx)(et,{...r,className:ct(`cursor-default`,a),"data-current":e?`true`:void 0,"aria-current":e?`page`:void 0,ref:i,children:(0,W.jsx)(iF,{children:n})})]})});function dF({className:e,...t}){return(0,W.jsx)(`span`,{...t,className:ct(e,`truncate`)})}var fF=Qk===`api`,pF=[`wodwiki.routeWql.v1`,`wodwiki.routeWqlShortcuts.v1`,`wodwiki.soundProfiles.v1`],mF=[],hF=new Map,gF={getItem:e=>hF.get(e)??null,setItem:(e,t)=>hF.set(e,t),removeItem:e=>hF.delete(e)};async function _F(){let e=await Promise.all(pF.map(e=>nA.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`)))),t=await Promise.all(mF.map(e=>nA.readonly(`meta`).get(e)));for(let t of e)for(let e of t)hF.set(e.key,e.value);for(let e of t)e&&hF.set(e.key,e.value)}async function vF(e,t){t===null?(await nA.readwrite(`meta`).delete(e),hF.delete(e)):(await nA.readwrite(`meta`).put({key:e,value:t}),hF.set(e,t))}async function yF(e){if(e.length===1)return vF(e[0],null);await nA.transaction([`meta`],`readwrite`,async t=>{for(let n of e)await t.readwrite(`meta`).delete(n)});for(let t of e)hF.delete(t)}async function bF(e){return await nA.readonly(`meta`).getAll(IDBKeyRange.bound(e,`${e}\uffff`))}async function xF(e,t){await nA.readwrite(`meta`).put({key:e,value:t})}async function SF(e){await nA.readwrite(`meta`).delete(e)}function CF(e){return e.replace(/(^|[{,\s!])catalog:("[^"]*"|[\w][\w/-]*)/g,`$1notebook:$2`)}var wF=[{id:`date`,label:`Date`},{id:`week`,label:`Week`},{id:`month`,label:`Month`},{id:`year`,label:`Year`},{id:`tag`,label:`Tags`},{id:`type`,label:`Type`},{id:`discipline`,label:`Discipline`},{id:`source`,label:`Source`},{id:`origin`,label:`Origin`}],TF=wF.map(e=>e.id),EF=Object.fromEntries(wF.map(e=>[e.id,e.label]));function DF(e){return EF[e]??e}function OF(e,t,n){let r=n?.sink,i=n?.priority??[],a=e=>{let t=i.indexOf(e);return t===-1?1/0:t};return[...e].sort((e,n)=>{if(t===`chronological-desc`)return n[0].localeCompare(e[0]);if(t===`priority-then-alpha`){let t=a(e[0]),r=a(n[0]);return t===r?e[0].localeCompare(n[0]):t-r}if(r){if(e[0]===r)return 1;if(n[0]===r)return-1}return e[0].localeCompare(n[0])})}function kF(e,t){let n=new Set(e);if(!t||t.length===0)return wF.filter(e=>n.has(e.id));let r=t.filter(e=>n.has(e)),i=new Set(r);return[...r.map(e=>({id:e,label:DF(e)})),...wF.filter(e=>n.has(e.id)&&!i.has(e.id))]}function AF(e,t,n){if(!e)return n;let r=new Set(t);return e.find(e=>r.has(e))??n}function jF(e){if(!e)return{options:[],invalid:[]};let t=[],n=[],r=new Set;for(let i of e){if(!TF.includes(i)){n.includes(i)||n.push(i);continue}r.has(i)||(r.add(i),t.push(i))}return{options:t,invalid:n}}var MF=`/palette`,NF=new Ax(`wodwiki.routeWql.v1`,fF?gF:void 0),PF=[...pm,...mm],FF={notes:`note`,blocks:`block`,efforts:`effort`,collections:`notebooks`,feeds:`notebooks`};function IF(e){let t=e.startsWith(`/`)?e:`/${e}`;return VF[t]??t}function LF(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim())}function RF(e,t,n){let r=[],i=[],a=new Set;for(let o of e){let e=n[o]??o;if(!t.includes(e)){i.includes(o)||i.push(o);continue}a.has(e)||(a.add(e),r.push(e))}return{options:r,invalid:i}}var zF={"/notebooks":`/catalogs`,"/notes":`/feeds`,"/sessions":`/results`,"/dashboards":`/dashboard`},BF={"/notes":`/collections`},VF={"/feeds":`/feeds@2`};function HF(e){return CF(e).replace(/^:(collections?|feeds?)(?![\w:])/,e=>e===`:collections`||e===`:feeds`?`:notebooks`:`:notebook`).replace(/(^|[{,\s])source:(collections|feeds)(?![\w:])/g,`$1source:notebooks`).replace(/(^|[{,\s])source:collection:/g,`$1source:notebook:`).replace(/(^|[{,\s])type:(feed|collection)(?![\w:])/g,`$1type:note`)}function UF(e,t=NF){let n=IF(e),r=zF[n],i=t.get(n,{alias:r});if(i==null&&r&&(i=t.get(r,{alias:BF[n]})),!i)return{};let a=LF(i.typeOptions),o=LF(i.groupByOptions),s=a&&RF(a,PF,FF),c=o?jF(o):void 0;return{defaultWql:typeof i.defaultWql==`string`&&i.defaultWql.trim().length>0?HF(i.defaultWql.trim()):void 0,typeOptions:s?.options,groupByOptions:c?.options,...s?.invalid.length?{invalidTypeOptions:s.invalid}:{},...c?.invalid.length?{invalidGroupByOptions:c.invalid}:{}}}async function WF(e,t,n=NF){let r=IF(e),i={defaultWql:t.defaultWql?.trim()||void 0,typeOptions:LF(t.typeOptions),groupByOptions:LF(t.groupByOptions)};if(fF){try{await vF(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlConfig] server write failed:`,e),!1}return XF(),!0}return n.set(r,i),XF(),!0}async function GF(e,t=NF){let n=IF(e),r=zF[n];if(fF){try{await yF(r?[t.qualify(n),t.qualify(r)]:[t.qualify(n)])}catch(e){return console.error(`[routeWqlConfig] server delete failed:`,e),!1}return XF(),!0}return t.remove(n,r),XF(),!0}var KF=0,qF=new Set;function JF(e){return qF.add(e),()=>{qF.delete(e)}}function YF(){return KF}function XF(){KF+=1;for(let e of qF)e()}function ZF(e){let t=(0,U.useSyncExternalStore)(JF,YF,YF);return(0,U.useMemo)(()=>UF(e),[e,t])}function QF(e,t){let n=t??UF(e.route);return!n.defaultWql&&!n.typeOptions&&!n.groupByOptions?e:{...e,defaultWql:n.defaultWql??e.defaultWql,scopeOptions:n.typeOptions?n.typeOptions.filter(e=>mm.includes(e)):e.scopeOptions,groupByOptions:n.groupByOptions}}function $F(e){let t=ZF(e?.route??``);return(0,U.useMemo)(()=>e?QF(e,t):void 0,[e,t])}var eI={bookmark:ft,calendar:Tn,"clipboard-list":r,clock:Te,dumbbell:k,flame:fr,folder:L,"flask-conical":ke,heart:xe,library:x,plus:Rt,rss:on,star:re,tag:Ze,activity:S,wrench:Ce},tI=new Ax(`wodwiki.routeWqlShortcuts.v1`,fF?gF:void 0);function nI(e,t){return{id:`all`,label:e,icon:t,wql:``}}var rI={"/journal":`All entries`,"/notebooks":`All notebooks`,"/notes":`All notes`,"/feeds":`All feeds`,"/pages":`All pages`,"/playgrounds":`All playgrounds`,"/efforts":`All Efforts`,"/equipment":`All Equipment`,"/sessions":`All Sessions`},iI={"/journal":`calendar`,"/notebooks":`library`,"/notes":`rss`,"/feeds":`rss`,"/pages":`clipboard-list`,"/playgrounds":`flask-conical`,"/efforts":`dumbbell`,"/equipment":`wrench`,"/sessions":`clipboard-list`};function aI(e){let t=oI(e);return t===`/notebooks`?[nI(`All notebooks`,`library`),{id:`all-configured`,label:`All configured`,icon:`bookmark`,wql:`:notebook{subscribed:true,false}`},{id:`available`,label:`Available to subscribe`,icon:`plus`,wql:`:notebook{subscribed:false}`}]:[nI(rI[t]??`Landing link`,iI[t]??`bookmark`)]}function oI(e){return e.startsWith(`/`)?e:`/${e}`}var sI={"/notebooks":`/catalogs`,"/notes":`/feeds`},cI={"/feeds":`/feeds@2`};function lI(e){let t=oI(e);return cI[t]??t}function uI(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(typeof r!=`object`||!r||Array.isArray(r))continue;let e=r;typeof e.id!=`string`||!e.id.trim()||n.has(e.id)||typeof e.label!=`string`||!e.label.trim()||typeof e.icon!=`string`||!eI[e.icon]||typeof e.wql==`string`&&(e.to!==void 0&&(typeof e.to!=`string`||!/^\/(?!\/)/.test(e.to))||(n.add(e.id.trim()),t.push({id:e.id.trim(),label:e.label.trim(),icon:e.icon,wql:HF(e.wql.trim()),...typeof e.to==`string`?{to:e.to}:{}})))}return t}function dI(e,t=tI){let n=lI(e);return uI(t.get(n,{alias:sI[n]}))}function fI(e,t=tI){let n=lI(e),r=sI[n];if(t.getRaw(n)!=null||r!=null&&t.getRaw(r)!=null){let n=dI(e,t);return n.some(e=>e.id===`all`)?n:[aI(e)[0],...n]}return aI(e)}async function pI(e,t,n=tI){let r=lI(e),i=uI(t);if(fF){try{await vF(n.qualify(r),JSON.stringify(i))}catch(e){return console.error(`[routeWqlShortcuts] server write failed:`,e),!1}return vI(),!0}return n.set(r,i),n.getRaw(r)===JSON.stringify(i)&&(vI(),!0)}var mI=0,hI=new Set;function gI(e){return hI.add(e),()=>{hI.delete(e)}}function _I(){return mI}function vI(){mI++;for(let e of hI)e()}function yI(e,t=tI){return(0,U.useSyncExternalStore)(gI,_I),fI(e,t)}function bI(e){return eh(e)?qh({...e,filters:(e.filters??[]).map(e=>({...e,values:[...e.values??[]].sort((e,t)=>e.value.localeCompare(t.value))})).sort((e,t)=>e.key.localeCompare(t.key)||Number(e.negate)-Number(t.negate)||e.values.map(e=>e.value).join(`|`).localeCompare(t.values.map(e=>e.value).join(`|`))),groupBy:[...e.groupBy??[]].sort((e,t)=>e.localeCompare(t))}):qh(e)}function xI(e,t){return e.to?t.pathname===e.to||t.pathname.startsWith(`${e.to}/`):SI(e.wql,t.query)}function SI(e,t){if(!e.trim())return t.trim()===``;if(t.trim()===``)return!1;if(t===e)return!0;let n=X(t),r=X(e);return!n.error&&!r.error&&bI(n)===bI(r)}var CI=`w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary/40`;function wI({open:e,onOpenChange:t,route:n,editing:r=null,initialQuery:i=``}){let[a,o]=(0,U.useState)(r?.label??``),[s,c]=(0,U.useState)(r?.icon??`bookmark`),[l,u]=(0,U.useState)(r?r.wql:i),[d,f]=(0,U.useState)(null);(0,U.useEffect)(()=>{e&&(o(r?.label??``),c(r?.icon??`bookmark`),u(r?r.wql:i),f(null))},[e,r,i]);let p=r!==null&&!!r.to,m=r?.id!==`all`,h=a.trim(),g=l.trim(),_=g?Qw(g).error??null:null,v=h?null:`Label is required.`,y=!!h&&!p&&(!m||!!g)&&!_;return(0,W.jsx)(WC,{open:e,onClose:()=>t(!1),title:r?`Edit shortcut`:`Save search shortcut`,description:`Saved shortcuts appear in this route's navigation panel. Stored ${fF?`on the server.`:`in this browser only.`}`,footer:(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(K,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>t(!1),children:`Cancel`}),(0,W.jsx)(K,{type:`submit`,form:`save-wql-shortcut-form`,size:`sm`,disabled:!y,"data-testid":`shortcut-save`,children:`Save`})]}),children:(0,W.jsxs)(`form`,{id:`save-wql-shortcut-form`,onSubmit:async e=>{if(e.preventDefault(),!y)return;let i={id:r?.id??crypto.randomUUID(),label:h,icon:s,wql:p?r.wql:g,...r?.to===void 0?{}:{to:r.to}};if(!await pI(n,[...fI(n).filter(e=>e.id!==i.id),i])){f(`Couldn’t save — storage is unavailable. Your input is kept.`);return}t(!1)},className:`flex flex-col gap-4`,noValidate:!0,children:[(0,W.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`shortcut-label`,className:`text-xs font-semibold text-muted-foreground`,children:`Label`}),(0,W.jsx)(`input`,{id:`shortcut-label`,value:a,onChange:e=>o(e.target.value),placeholder:`e.g. Strength this month`,"data-testid":`shortcut-label-input`,"aria-invalid":v?!0:void 0,className:CI}),v&&(0,W.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`shortcut-label-error`,children:v})]}),p?(0,W.jsxs)(`p`,{className:`rounded-md border border-border/60 bg-muted/30 px-3 py-2 text-xs text-muted-foreground`,children:[`Route action — always opens `,r?.to,`. Label and icon are editable.`]}):(0,W.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,W.jsx)(`label`,{htmlFor:`shortcut-query`,className:`text-xs font-semibold text-muted-foreground`,children:`Query (WQL)`}),(0,W.jsx)(`textarea`,{id:`shortcut-query`,rows:2,value:l,onChange:e=>u(e.target.value),placeholder:m?`find …`:`Empty — the plain route landing`,"data-testid":`shortcut-query-input`,"aria-invalid":_?!0:void 0,className:`${CI} font-mono text-xs`}),_?(0,W.jsxs)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`shortcut-query-error`,children:[`Couldn't parse — `,_]}):!g&&(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:m?`A shortcut needs a query.`:`Empty — opens the plain route landing.`})]}),(0,W.jsxs)(`fieldset`,{className:`space-y-1.5`,children:[(0,W.jsx)(`legend`,{className:`text-xs font-semibold text-muted-foreground`,children:`Icon`}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Object.entries(eI).map(([e,t])=>(0,W.jsxs)(`label`,{title:e,className:s===e?`cursor-pointer rounded-md border border-primary bg-primary/10 p-1.5 text-primary`:`cursor-pointer rounded-md border border-border p-1.5 text-muted-foreground hover:text-foreground`,children:[(0,W.jsx)(`input`,{type:`radio`,name:`shortcut-icon`,value:e,checked:s===e,onChange:()=>c(e),"aria-label":`Icon ${e}`,"data-testid":`shortcut-icon-${e}`,className:`sr-only`}),(0,W.jsx)(t,{className:`size-4`,"aria-hidden":`true`})]},e))})]}),d&&(0,W.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,"data-testid":`shortcut-storage-error`,children:d})]})})}function TI(e,t){if(e)switch(e.type){case`route`:t.navigate(e.to,{replace:!(e.pushHistory??!0)});break;case`query`:t.setQueryParam(e.params,!(e.pushHistory??!1));break;case`scroll`:t.scrollToSection?.(e.sectionId);break;case`view-source`:t.swapSource?.(e.source);break;case`view-state`:t.setPanelState?.(e.state,e.open);break;case`pipeline`:{let n=e.steps.filter(e=>e.type===`scroll`),r=e.steps.filter(e=>e.type!==`scroll`);r.forEach(e=>TI(e,t)),n.length>0&&(r.length>0?setTimeout(()=>{n.forEach(e=>TI(e,t))},0):n.forEach(e=>TI(e,t)));break}case`call`:e.handler();break;case`external`:window.open(e.href,`_blank`,`noopener,noreferrer`)}}function EI(e,t=`dialog`){if(e.action===`set-source`)return{type:`view-source`,source:e.value};if(e.action===`navigate`)return/^https?:\/\//.test(e.value)?{type:`external`,href:e.value}:{type:`route`,to:e.value};if(e.action===`set-state`){if(e.value===`note`)return{type:`view-state`,state:`note`};if(e.value===`review`)return{type:`view-state`,state:`review`};if(e.value===`track`)return{type:`view-state`,state:`track`,open:t}}return{type:`none`}}function DI(e,t){let n=e.pipeline.map(t=>EI(t,e.open));return{id:`btn-${t}`,label:e.label,action:n.length===1?n[0]:{type:`pipeline`,steps:n}}}function OI(e){let{action:t}=e;return t.type===`view-state`?t.state===`track`:t.type===`pipeline`&&t.steps.some(e=>e.type===`view-state`&&e.state===`track`)}var kI=`sticky top-0 z-10 bg-card`;function AI({title:e,defaultOpen:t=!1,collapsible:n=!0,children:r,count:i,className:a,sticky:o,trailing:s,bodyClassName:c,buttonClassName:l}){if(!n)return(0,W.jsxs)(`div`,{className:a,children:[(0,W.jsxs)(`div`,{className:ct(`group flex w-full items-center gap-1 px-2 py-3 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground/80`,o&&kI),children:[(0,W.jsx)(`div`,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{children:e}),i!==void 0&&(0,W.jsx)(`span`,{className:`ml-auto flex size-5 items-center justify-center rounded-full bg-border/50 text-[9px] font-black tabular-nums text-muted-foreground`,children:i})]}),(0,W.jsx)(`div`,{className:ct(`flex flex-col gap-0.5`),children:r})]});let u=(0,W.jsxs)(d,{className:ct(`group flex items-center gap-1 px-2 py-3 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground/80 hover:text-primary transition-colors`,s?`min-w-0 flex-1`:`w-full`,l,o&&!s&&kI),children:[(0,W.jsx)(w,{className:`size-4 shrink-0 fill-muted-foreground/50 transition-transform duration-300 group-data-[open]:rotate-90 group-hover:fill-primary`}),(0,W.jsx)(`span`,{children:e}),i!==void 0&&(0,W.jsx)(`span`,{className:`ml-auto flex size-5 items-center justify-center rounded-full bg-border/50 text-[9px] font-black tabular-nums text-muted-foreground group-hover:bg-primary/10 group-hover:text-primary transition-colors`,children:i})]});return(0,W.jsxs)(pr,{as:`div`,defaultOpen:t,className:a,children:[s?(0,W.jsxs)(`div`,{className:ct(`flex w-full items-center bg-card`,o&&kI),children:[u,s]}):u,(0,W.jsx)(Ae,{className:ct(`flex flex-col gap-0.5`,c),transition:!0,children:r})]})}var jI=null,MI=new Set;function NI(e){jI=e;for(let e of MI)e()}function PI(e){return MI.add(e),()=>{MI.delete(e)}}function FI(){return jI}function II(){return(0,U.useSyncExternalStore)(PI,FI)}var LI={tags:`tag`},RI={source:!0},zI={text:!0};function BI(e){return LI[e]??e}function VI(e){return!!zI[e]}function HI(e){switch(e){case`note`:return`note`;case`effort`:return`effort`;default:return null}}function UI(e){return e.wildcard?`${e.value}*`:e.value}function WI(e,t){return e.filters.map((e,t)=>({filter:e,filterIndex:t})).filter(({filter:e})=>e.key===t).map(({filter:e,filterIndex:n})=>({filterIndex:n,key:t,negate:e.negate,values:e.values.map(e=>({value:e.value,wildcard:e.wildcard}))}))}function GI(e,t,n){let r=[];for(let i of WI(e,t))i.values.forEach((e,t)=>{let a=UI(e);r.push({display:a,negate:i.negate,label:n?.get(i.negate?a:e.value),occurrence:i,valueIndex:t})});return r}function KI(e,t,n){if(t===`source`)return $I(e,n);let r=X(e);if(r.error||!eh(r))return e;let i=WI(r,t).filter(e=>!e.negate);if(i.length>0&&!RI[t]){let r=i[i.length-1];return nL(e,t,r,[...r.values.map(UI),n].join(`|`))}if(i.length>0)return nL(e,t,i[i.length-1],n);let a=Xw(e,rL(t,BI(t),``),n);return a.valid?a.wql:e}function qI(e,t,n){let r=n.occurrence.values.filter((e,t)=>t!==n.valueIndex).map(UI).join(`|`);return nL(e,t,n.occurrence,r||null)}function JI(e,t,n){let r=X(e);if(r.error||!eh(r))return`off`;if(t===`source`&&tL(r)===n)return`include`;let i=WI(r,t);return i.some(e=>!e.negate&&e.values.some(e=>UI(e)===n))?`include`:i.some(e=>e.negate&&e.values.some(e=>UI(e)===n))?`exclude`:`off`}function YI(e,t,n,r){return JI(e,t,n)===r?e:r===`off`?XI(e,t,n,`both`):r===`include`?KI(XI(e,t,n,`negative`),t,n):ZI(XI(e,t,n,`positive`),t,n)}function XI(e,t,n,r){let i=e;for(;;){let e=X(i);if(e.error||!eh(e))return i;if(t===`source`&&r!==`negative`&&tL(e)===n){let e=$I(i,null);if(e===i)return i;i=e;continue}let a=WI(e,t).find(e=>(r===`both`||r===(e.negate?`negative`:`positive`))&&e.values.some(e=>UI(e)===n));if(!a)return i;let o=a.values.findIndex(e=>UI(e)===n),s=qI(i,t,{display:n,negate:a.negate,occurrence:a,valueIndex:o});if(s===i)return i;i=s}}function ZI(e,t,n){let r=X(e);if(r.error||!eh(r))return e;let i=WI(r,t).filter(e=>e.negate);if(i.length>0){let r=i[i.length-1];return r.values.some(e=>UI(e)===n)?e:nL(e,t,r,[...r.values.map(UI),n].join(`|`))}let a=Xw(e,{...rL(t,BI(t),``),negate:!0},n);return a.valid?a.wql:e}function QI(e,t){let n=t.trim(),r=e,i=!1;for(;;){let e=X(r);if(e.error||!eh(e))return r;let t=WI(e,`text`).filter(e=>!e.negate);if(t.length===0){if(!n||i)return r;let e=Xw(r,rL(`text`,BI(`text`),``),n);return e.valid?e.wql:r}if(!n){let e=nL(r,`text`,t[0],null);if(e===r)return r;r=e;continue}if(!i){let e=nL(r,`text`,t[0],n);if(e===r)return r;r=e,i=!0;continue}if(t.length===1)return r;let a=nL(r,`text`,t[1],null);if(a===r)return r;r=a}}function $I(e,t){let n=X(e);if(n.error||!eh(n))return e;let r=new Set,i=n.filters.filter(e=>{if(e.key!==`source`||e.negate)return!0;let t=e.values.map(e=>`${e.value}${e.wildcard?`*`:``}`).join(`|`);return!r.has(t)&&(r.add(t),!0)}),a=hm.filter(t=>e.startsWith(`:${t}`)).sort((e,t)=>t.length-e.length)[0],o=a?gm[a]:void 0;if(!t){if(!o)return qh({...n,sourceScope:void 0,filters:i});let e=!1,t=i.filter(t=>e||t.key!==`source`||t.negate?!0:t.values.length===1&&!t.values[0].wildcard&&t.values[0].value===o?(e=!0,!1):!0);return qh({...n,sourceScope:void 0,filters:t})}let s=t===`journal`?`:journal`:t===`notebooks`?`:notebooks`:t===`playground`?`:playground`:`:note{source:${t}}`,c=X(s.startsWith(`:note`)?s:`${s}{}`);if(c.error||!eh(c)||!c.filters.length)return e;let l=i.findIndex(e=>e.key===`source`&&!e.negate),u=l>=0?i.map((e,t)=>t===l?c.filters[0]:e):[...i,c.filters[0]];return qh({...n,sourceScope:void 0,filters:u})}function eL(e,t,n){let r=X(e);if(r.error||!eh(r))return e;let i=r.groupBy??[];if(n===i.some(e=>e.toLowerCase()===t.toLowerCase()))return e;let a=n?[...i,t.toLowerCase()]:i.filter(e=>e.toLowerCase()!==t.toLowerCase());return qh({...r,groupBy:a.length>0?a:void 0})}function tL(e){return e.filters.find(e=>e.key===`source`&&!e.negate)?null:e.sourceScope?.length===1?e.sourceScope[0]:null}function nL(e,t,n,r){let i=Xw(e,{...rL(t,BI(t),n.values.map(UI).join(`|`)),filterIndex:n.filterIndex,negate:n.negate},r);return i.valid?i.wql:e}function rL(e,t,n){return{id:`nav-${e}`,type:t,...ow(t),value:n}}function iL(e,t,n){let r=new Map,i=(e,t)=>{let n=r.get(e);n?(n.count+=1,!n.label&&t&&(n.label=t)):r.set(e,{value:e,label:t,count:1})},a=am.includes(t)?t:t===`tags`?`tags`:null;if(a&&!n.tagMembership)return[];let o=(e===`note`||e===`block`)&&t===`effort`;if(o&&!n.effortMembership)return[];let s=e=>{r.has(e)||r.set(e,{value:e,count:0})};for(let r of n.entries)switch(`${e}:${t}`){case`note:notebook`:case`block:notebook`:(r.notebookId||r.sourceNotebook)&&i(r.notebookId??r.sourceNotebook);break;case`note:type`:r.noteType&&i(r.noteType);break;case`block:type`:r.block?.dataType&&i(r.block.dataType);break;case`note:page`:i(r.noteType===`page`?`true`:`false`,r.noteType===`page`?`Pages`:`Non-pages`);break;case`effort:discipline`:r.effort?.discipline&&i(r.effort.discipline);break;case`effort:intensity`:r.effort?.intensityTier&&i(r.effort.intensityTier);break;case`effort:origin`:r.effort?.registrySource&&i(r.effort.registrySource);break;case`effort:effort`:r.effort?.slug&&i(r.effort.slug,r.effort.label);break;case`session:result`:r.execution?.resultId&&i(r.execution.resultId,r.title);break;case`session:block`:{let e=new Set;for(let t of r.execution?.events??[])t.blockContentId&&e.add(t.blockContentId);for(let t of e)i(t,r.title);break}case`session:note`:{let e=new Set;for(let t of r.execution?.events??[])t.noteId&&e.add(t.noteId);for(let t of e)i(t,r.title);break}case`session:plane`:for(let e of r.execution?.events??[])i(e.outputType);break;default:if(a){let e=n.tagMembership.get(r.sourceNotebook??r.id)??n.tagMembership.get(r.id)??[];for(let t of e)(a===`tags`||t.type===a)&&i(t.label)}else if(o){let e=n.effortMembership.get(r.sourceNotebook??r.id)??n.effortMembership.get(r.id)??[];for(let t of e)i(t)}}if(e===`note`&&t===`source`)return mm.map(e=>({value:e,count:n.entries.filter(t=>D_({id:t.id,sourceId:t.sourceId,type:t.noteType},e)).length})).filter(e=>e.count>0);if(e===`block`&&t===`source`)return mm.map(e=>({value:e,count:n.entries.filter(t=>D_({id:t.id,sourceId:t.sourceId,type:void 0},e)).length})).filter(e=>e.count>0);if((e===`note`||e===`block`)&&t===`note`)for(let e of n.entries)i(e.id,e.title);if(a)for(let e of n.tagMembership.values())for(let t of e)(a===`tags`||t.type===a)&&s(t.label);if(o)for(let e of n.effortMembership.values())for(let t of e)s(t);return[...r.values()].sort((e,t)=>t.count-e.count||(e.label??e.value).localeCompare(t.label??t.value))}var aL=e=>e.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1)})),oL={source:{enabled:!1,expectedValues:aL(mm)},page:{enabled:!1,expectedValues:[{value:`true`,label:`Pages`},{value:`false`,label:`Non-pages`}]},intensity:{expectedValues:aL(dm)},discipline:{expectedValues:aL(Jh)}};function sL(e){return oL[e]??{}}var cL=[],lL=e=>new URLSearchParams(e.search).get(`q`)??``;async function uL(){let[e,t]=await Promise.all([Z.getNoteTagLabelsBatch(),Z.getAllNotes()]);for(let n of t){let t=e.get(n.id),r=__(n.sourceId);if(!r||!t?.length)continue;let i=e.get(r);if(i)for(let e of t)i.some(t=>t.label===e.label)||i.push(e);else e.set(r,t.map(({label:e,type:t})=>({label:e,type:t})))}return e}function dL(e,t,n){let r=new URLSearchParams(e.search);r.set(`q`,n),t(`${e.pathname}?${r.toString()}`)}function fL({profile:e}){let t=ht(),n=yn(),r=II(),i=lL(t),a=$F(e),o=i&&!X(i).error?i:a.defaultWql,s=(0,U.useMemo)(()=>X(o),[o]),c=(0,U.useMemo)(()=>!s.error&&eh(s)?s:null,[s]),l=r&&r.pathname===t.pathname&&r.query===o?r.entries:null,[u,d]=(0,U.useState)(null);(0,U.useEffect)(()=>{r&&r.pathname===t.pathname&&d(r)},[r,t.pathname]);let f=l===null&&u!==null&&u.pathname===t.pathname,p=l??(f?u.entries:cL),m=c?HI(c.target):null,h=!!c&&!!m&&WI(c,m).length>0,g=(0,U.useMemo)(()=>c?Rm(c.target,`find`).filter(e=>e!==m||h):[],[c,m,h]),_=g.some(e=>e===`tags`||am.includes(e)),v=g.includes(`effort`),[y,b]=(0,U.useState)({tags:null,efforts:null});(0,U.useEffect)(()=>{if(!_&&!v||p.length===0)return;let e=!1;return Promise.all([_?uL():null,v?Z.getEffortSlugsByNoteBatch():null]).then(([t,n])=>{e||b({tags:t,efforts:n})}).catch(()=>{e||b({tags:null,efforts:null})}),()=>{e=!0}},[_,v,p]);let x=(0,U.useMemo)(()=>({entries:p,tagMembership:y.tags,effortMembership:y.efforts}),[p,y]),S=(0,U.useRef)(new Map),C=S.current.get(t.pathname);C||(C=new Map,S.current.set(t.pathname,C));let w=l!==null||u!==null,T=e=>dL(t,n,e),E=c?tL(c):null,D=(0,U.useMemo)(()=>g.filter(e=>sL(e).enabled!==!1).sort((e,t)=>(sL(e).order??0)-(sL(t).order??0)),[g]);return c?(0,W.jsx)(`div`,{className:`flex flex-col`,"aria-busy":f||void 0,children:D.map(e=>(0,W.jsx)(`div`,{"data-testid":`conditions-section-${e}`,children:(0,W.jsx)(_L,{query:o,parsed:c,entryKey:e,facetContext:x,labels:pL(c.target,e,p),headScope:e===`source`?E:null,pending:f,hasEverPublished:w,routeKnownOptions:C,onApply:T})},e))}):null}function pL(e,t,n){let r=new Map,i=(e,t)=>{e&&!r.has(e)&&r.set(e,t)};if((e===`note`||e===`block`)&&t===`note`)for(let e of n)i(e.id,e.title);if(e===`session`)for(let e of n){t===`result`&&i(e.execution?.resultId,e.title);for(let n of e.execution?.events??[])t===`block`&&i(n.blockContentId,e.title),t===`note`&&i(n.noteId,e.title)}return r}var mL=[`off`,`include`,`exclude`],hL={off:`Off`,include:`Include`,exclude:`Exclude`},gL={off:at,include:De,exclude:lt};function _L({query:e,parsed:t,entryKey:n,facetContext:r,labels:i,headScope:a,pending:o,hasEverPublished:s,routeKnownOptions:c,onApply:l}){let u=ht(),d=sL(n);if(d.enabled===!1)return null;let f=ow(BI(n)),p=VI(n)||yL[n]!==void 0,m=GI(t,n,i),h=n===`text`?WI(t,`text`).filter(e=>!e.negate).map(e=>e.values.map(e=>e.value).join(`|`)).join(`|`):null,g=iL(t.target,n,r),_=c.get(n);_||(_=new Map,c.set(n,_));for(let e of g)_.has(e.value)||_.set(e.value,{value:e.value,label:e.label,count:0});let v=new Map(m.map(e=>[e.display,e])),y=new Map(g.map(e=>[e.value,e])),b=d.expectedValues,x=[],S=new Set,C=(t,r,i)=>{S.has(t)||(S.add(t),x.push({value:t,label:i??r?.label??v.get(t)?.label??t,count:r?r.count:null,state:JI(e,n,t)}))};if(s){for(let e of b??[]){let t=y.get(e.value);C(e.value,t,e.label)}if(!b){for(let e of g)C(e.value,e);for(let e of _.values())C(e.value,y.get(e.value),e.label)}}for(let e of m)C(e.display,y.get(e.display));n===`source`&&a&&C(a,y.get(a));let w=new Map((b??[]).map((e,t)=>[e.value,t]));x.sort((e,t)=>(w.get(e.value)??2**53-1)-(w.get(t.value)??2**53-1)||e.label.localeCompare(t.label));let T=u.pathname.startsWith(`/journal`)||u.pathname.startsWith(`/day`),E=d.hideZero||n===`effort`||T&&(n===`tags`||am.includes(n))?x.filter(e=>e.count!==null&&e.count>0||e.state!==`off`):x;return E.length===0&&!p?null:(0,W.jsxs)(AI,{title:d.label??f.label,count:E.length,defaultOpen:x.some(e=>e.state!==`off`)||p,sticky:!0,buttonClassName:`gap-1.5 py-1.5 text-[11px] font-semibold normal-case tracking-normal [&>span:last-child]:h-auto [&>span:last-child]:w-auto [&>span:last-child]:min-w-0 [&>span:last-child]:rounded-sm [&>span:last-child]:px-1 [&>span:last-child]:bg-transparent [&>span:last-child]:text-[10px] [&>span:last-child]:font-semibold [&>span:last-child]:text-muted-foreground`,bodyClassName:`px-6`,children:[(0,W.jsx)(`ul`,{className:`flex flex-col`,children:E.map(t=>(0,W.jsx)(vL,{query:e,entryKey:n,row:t,pending:o,onApply:l},t.value))}),p&&(0,W.jsx)(bL,{entryKey:n,placeholder:f.placeholder,pending:o,currentText:h??void 0,onTextChange:t=>l(QI(e,t)),onApply:t=>l(YI(e,n,t,`include`))})]})}function vL({query:e,entryKey:t,row:n,pending:r,onApply:i}){let a=mL[(mL.indexOf(n.state)+1)%mL.length],o=gL[n.state],s=`${hL[a]} “${n.label}” (currently ${hL[n.state]})`,c=n.count===0&&n.state===`off`;return(0,W.jsx)(`li`,{"data-testid":`conditions-row-${t}:${n.value}`,className:ct(`px-1 py-0.5`,r&&`opacity-60`,c&&`opacity-40`),children:(0,W.jsxs)(`div`,{className:`flex h-11 items-center gap-1.5`,children:[(0,W.jsx)(`span`,{className:ct(`min-w-0 flex-1 truncate text-xs leading-4`,c?`text-muted-foreground`:`text-foreground`),children:n.label}),n.count!==null&&(0,W.jsx)(`span`,{className:`text-[10px] leading-4 tabular-nums text-muted-foreground`,children:n.count}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`conditions-state-${t}:${n.value}`,"data-state":n.state,onClick:()=>i(YI(e,t,n.value,a)),disabled:r,"aria-label":s,title:s,className:ct(`flex size-11 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent transition-colors hover:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:cursor-default`,n.state===`include`&&`bg-primary/10 text-primary`,n.state===`exclude`&&`bg-destructive/10 text-destructive`,n.state===`off`&&`text-muted-foreground`),children:(0,W.jsx)(o,{"aria-hidden":`true`,className:`size-4`})})]})})}var yL={note:!0,block:!0,result:!0};function bL({entryKey:e,placeholder:t,pending:n,currentText:r,onTextChange:i,onApply:a}){let[o,s]=(0,U.useState)(``),c=eF();return e===`text`?(0,W.jsxs)(`div`,{className:`px-1 py-1.5`,children:[(0,W.jsx)(`input`,{value:r??``,onChange:e=>i?.(e.target.value),placeholder:t,"aria-label":t,"data-testid":`conditions-input-text`,className:`h-8 w-full min-w-0 rounded-md border border-border/60 bg-background px-2 text-xs text-foreground placeholder:text-muted-foreground/60 focus:outline-none focus:ring-1 focus:ring-primary/40`}),(0,W.jsxs)(`button`,{type:`button`,"data-testid":`conditions-jump-wql-text`,onClick:()=>{c(),document.querySelector(`[data-testid="stream-query-bar"]`)?.click()},className:`mt-1 inline-flex items-center gap-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground`,children:[(0,W.jsx)(tt,{"aria-hidden":`true`,className:`size-3`}),`Edit in WQL bar`]})]}):(0,W.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=o.trim();t&&(a(t),s(``))},className:`flex items-center gap-1 px-1 py-1.5`,children:[(0,W.jsx)(`input`,{value:o,onChange:e=>s(e.target.value),placeholder:t,"aria-label":t,"data-testid":`conditions-input-${e}`,disabled:n,className:`h-8 min-w-0 flex-1 rounded-md border border-border/60 bg-background px-2 text-xs text-foreground placeholder:text-muted-foreground/60 focus:outline-none focus:ring-1 focus:ring-primary/40`}),(0,W.jsx)(`button`,{type:`submit`,"aria-label":`Add ${t}`,"data-testid":`conditions-add-${e}`,disabled:n||!o.trim(),className:`flex size-8 shrink-0 items-center justify-center rounded-md border border-border/60 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50`,children:(0,W.jsx)(Rt,{"aria-hidden":`true`,className:`size-3.5`})})]})}var xL=e=>new URLSearchParams(e.search).get(`q`)??``;function SL(e){return function(t){let n=ht(),r=yn(),{openCreateJournal:i}=mN(),a=$F(e.profile),o=xL(n),s=o&&!X(o).error?o:a.defaultWql,c=e=>dL(n,r,e),l=eF(),u=yI(e.route),d={pathname:n.pathname,query:xL(n)},f=u.find(e=>e.id===`all`)??null,p=u.filter(e=>e.to===void 0&&e.id!==`all`),m=f?.wql??``,h=f?.label??e.landingLabel,g=f?eI[f.icon]:e.icon,_=d.query&&!X(d.query).error&&!u.some(e=>xI(e,d))?s:null,[v,y]=(0,U.useState)(!1);return(0,W.jsxs)(`div`,{className:`-mx-4 flex flex-col gap-1 py-3`,"data-testid":`conditions-nav-panel`,children:[(0,W.jsxs)(lF,{className:`px-6`,children:[e.createAction&&(()=>{let t=e.createAction.icon??Rt;return(0,W.jsx)(`div`,{className:`mb-2`,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":e.createAction.testId??`conditions-nav-create`,onClick:()=>{e.createAction.onClick({navigate:r,openCreateJournal:e=>i?.(e)}),l()},className:`flex w-full items-center justify-center gap-2 rounded-lg bg-primary/10 px-3 py-2 text-xs font-semibold text-primary transition-all hover:bg-primary hover:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-sm`,children:[(0,W.jsx)(t,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{children:e.createAction.label})]})})})(),_?(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,"data-testid":`conditions-nav-custom`,children:[(0,W.jsxs)(uF,{current:!0,className:`min-w-0 flex-1`,title:_,"aria-label":`Custom query: ${_}`,onClick:()=>{c(_),l()},children:[g&&(0,W.jsx)(g,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:`Custom`})]}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>y(!0),"aria-label":`Save shortcut`,title:`Save shortcut`,"data-testid":`conditions-nav-custom-save`,className:`grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,W.jsx)(Qn,{className:`size-4`,"aria-hidden":`true`})}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>{m?c(m):r(e.route),l()},"aria-label":`Clear query`,title:`Clear to all entries`,"data-testid":`conditions-nav-custom-clear`,className:`grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:(0,W.jsx)(ge,{className:`size-4`,"aria-hidden":`true`})})]}):(0,W.jsxs)(uF,{onClick:()=>{m?c(m):r(e.route),l()},current:m&&f?xI(f,d):e.familyActive(n)&&xL(n).trim()===``,children:[g&&(0,W.jsx)(g,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:h})]}),p.map(t=>{let n=eI[t.icon];return(0,W.jsxs)(uF,{onClick:()=>{t.wql?c(t.wql):r(e.route),l()},current:xI(t,d),"data-testid":`nav-shortcut-${t.id}`,children:[(0,W.jsx)(n,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:t.label})]},`shortcut-${t.id}`)}),(e.extraChildren??[]).map(e=>{let t=e.action.type===`route`?e.action.to:null,i=t?u.find(e=>e.to===t):null,a=i?eI[i.icon]:null;return(0,W.jsxs)(uF,{onClick:()=>{e.action&&(TI(e.action,{navigate:r,setQueryParam:()=>{}}),l())},current:e.isActive?.(n)??!1,"data-testid":i?`nav-shortcut-${i.id}`:void 0,children:[a?(0,W.jsx)(a,{"data-slot":`icon`}):e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:i?.label??e.label})]},e.id)})]}),(0,W.jsx)(fL,{profile:e.profile}),(0,W.jsx)(wI,{open:v,onOpenChange:y,route:e.route,initialQuery:s})]})}}var CL=e=>RL(e.pathname,`/journal`,`/day`),wL=e=>RL(e.pathname,`/playgrounds`,`/playground`),TL={id:`journal-all-notes`,label:`All`,level:2,icon:tn,action:{type:`route`,to:`/journal?q=%3Anote%7B!source%3Aplayground%7D`},isActive:e=>e.pathname===$.journal&&new URLSearchParams(e.search).get(`q`)===`:note{!source:playground}`},EL=[{id:`notebooks-view-journal`,label:`Journal`,level:2,icon:Tn,action:{type:`route`,to:$.journal},isActive:CL},{id:`notebooks-view-playgrounds`,label:`Playgrounds`,level:2,icon:ke,action:{type:`route`,to:$.playgrounds},isActive:wL}],DL=SL({landingLabel:`All notebooks`,icon:x,route:$.notebooks,profile:kN,extraChildren:EL,familyActive:e=>RL(e.pathname,`/notebooks`,`/notebook`,`/journal`,`/day`,`/playgrounds`,`/playground`)}),OL=SL({landingLabel:`All entries`,icon:Tn,route:$.journal,profile:ON,extraChildren:[...EL,TL],familyActive:CL,createAction:{label:`New journal entry`,icon:dn,testId:`journal-create-entry`,onClick:({openCreateJournal:e,navigate:t})=>{e?e({mode:`blank`}):t(`/journal?create=1`)}}}),kL=SL({landingLabel:`All playgrounds`,icon:ke,route:$.playgrounds,profile:LN,extraChildren:EL,familyActive:wL,createAction:{label:`New playground`,testId:`playgrounds-create-playground`,onClick:({navigate:e})=>{e(`/playground`)}}});function AL(e){let t=ht();return CL(t)?(0,W.jsx)(OL,{...e}):wL(t)?(0,W.jsx)(kL,{...e}):(0,W.jsx)(DL,{...e})}var jL=`https://www.buymeacoffee.com/sergeigolos`,ML=({className:e,...t})=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 884 1279`,fill:`currentColor`,className:e,"aria-hidden":`true`,...t,children:[(0,W.jsx)(`path`,{d:`M791.109 297.518L790.231 297.002L788.201 296.383C789.018 297.072 790.04 297.472 791.109 297.518V297.518Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M803.896 388.891L802.916 389.166L803.896 388.891Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M791.484 297.377C791.359 297.361 791.237 297.332 791.118 297.29C791.111 297.371 791.111 297.453 791.118 297.534C791.252 297.516 791.379 297.462 791.484 297.377V297.377Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M791.113 297.529H791.244V297.447L791.113 297.529Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M803.111 388.726L804.591 387.883L805.142 387.573L805.641 387.04C804.702 387.444 803.846 388.016 803.111 388.726V388.726Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M793.669 299.515L792.223 298.138L791.243 297.605C791.77 298.535 792.641 299.221 793.669 299.515V299.515Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M430.019 1186.18C428.864 1186.68 427.852 1187.46 427.076 1188.45L427.988 1187.87C428.608 1187.3 429.485 1186.63 430.019 1186.18Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M641.187 1144.63C641.187 1143.33 640.551 1143.57 640.705 1148.21C640.705 1147.84 640.86 1147.46 640.929 1147.1C641.015 1146.27 641.084 1145.46 641.187 1144.63Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M619.284 1186.18C618.129 1186.68 617.118 1187.46 616.342 1188.45L617.254 1187.87C617.873 1187.3 618.751 1186.63 619.284 1186.18Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M281.304 1196.06C280.427 1195.3 279.354 1194.8 278.207 1194.61C279.136 1195.06 280.065 1195.51 280.684 1195.85L281.304 1196.06Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M247.841 1164.01C247.704 1162.66 247.288 1161.35 246.619 1160.16C247.093 1161.39 247.489 1162.66 247.806 1163.94L247.841 1164.01Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M472.623 590.836C426.682 610.503 374.546 632.802 306.976 632.802C278.71 632.746 250.58 628.868 223.353 621.274L270.086 1101.08C271.74 1121.13 280.876 1139.83 295.679 1153.46C310.482 1167.09 329.87 1174.65 349.992 1174.65C349.992 1174.65 416.254 1178.09 438.365 1178.09C462.161 1178.09 533.516 1174.65 533.516 1174.65C553.636 1174.65 573.019 1167.08 587.819 1153.45C602.619 1139.82 611.752 1121.13 613.406 1101.08L663.459 570.876C641.091 563.237 618.516 558.161 593.068 558.161C549.054 558.144 513.591 573.303 472.623 590.836Z`,fill:`#FFDD00`}),(0,W.jsx)(`path`,{d:`M78.6885 386.132L79.4799 386.872L79.9962 387.182C79.5987 386.787 79.1603 386.435 78.6885 386.132V386.132Z`,fill:`#0D0C22`}),(0,W.jsx)(`path`,{d:`M879.567 341.849L872.53 306.352C866.215 274.503 851.882 244.409 819.19 232.898C808.711 229.215 796.821 227.633 788.786 220.01C780.751 212.388 778.376 200.55 776.518 189.572C773.076 169.423 769.842 149.257 766.314 129.143C763.269 111.85 760.86 92.4243 752.928 76.56C742.604 55.2584 721.182 42.8009 699.88 34.559C688.965 30.4844 677.826 27.0375 666.517 24.2352C613.297 10.1947 557.342 5.03277 502.591 2.09047C436.875 -1.53577 370.983 -0.443234 305.422 5.35968C256.625 9.79894 205.229 15.1674 158.858 32.0469C141.91 38.224 124.445 45.6399 111.558 58.7341C95.7448 74.8221 90.5829 99.7026 102.128 119.765C110.336 134.012 124.239 144.078 138.985 150.737C158.192 159.317 178.251 165.846 198.829 170.215C256.126 182.879 315.471 187.851 374.007 189.968C438.887 192.586 503.87 190.464 568.44 183.618C584.408 181.863 600.347 179.758 616.257 177.304C634.995 174.43 647.022 149.928 641.499 132.859C634.891 112.453 617.134 104.538 597.055 107.618C594.095 108.082 591.153 108.512 588.193 108.942L586.06 109.252C579.257 110.113 572.455 110.915 565.653 111.661C551.601 113.175 537.515 114.414 523.394 115.378C491.768 117.58 460.057 118.595 428.363 118.647C397.219 118.647 366.058 117.769 334.983 115.722C320.805 114.793 306.661 113.611 292.552 112.177C286.134 111.506 279.733 110.801 273.333 110.009L267.241 109.235L265.917 109.046L259.602 108.134C246.697 106.189 233.792 103.953 221.025 101.251C219.737 100.965 218.584 100.249 217.758 99.2193C216.932 98.1901 216.482 96.9099 216.482 95.5903C216.482 94.2706 216.932 92.9904 217.758 91.9612C218.584 90.9319 219.737 90.2152 221.025 89.9293H221.266C232.33 87.5721 243.479 85.5589 254.663 83.8038C258.392 83.2188 262.131 82.6453 265.882 82.0832H265.985C272.988 81.6186 280.026 80.3625 286.994 79.5366C347.624 73.2302 408.614 71.0801 469.538 73.1014C499.115 73.9618 528.676 75.6996 558.116 78.6935C564.448 79.3474 570.746 80.0357 577.043 80.8099C579.452 81.1025 581.878 81.4465 584.305 81.7391L589.191 82.4445C603.438 84.5667 617.61 87.1419 631.708 90.1703C652.597 94.7128 679.422 96.1925 688.713 119.077C691.673 126.338 693.015 134.408 694.649 142.03L696.731 151.752C696.786 151.926 696.826 152.105 696.852 152.285C701.773 175.227 706.7 198.169 711.632 221.111C711.994 222.806 712.002 224.557 711.657 226.255C711.312 227.954 710.621 229.562 709.626 230.982C708.632 232.401 707.355 233.6 705.877 234.504C704.398 235.408 702.75 235.997 701.033 236.236H700.895L697.884 236.649L694.908 237.044C685.478 238.272 676.038 239.419 666.586 240.486C647.968 242.608 629.322 244.443 610.648 245.992C573.539 249.077 536.356 251.102 499.098 252.066C480.114 252.57 461.135 252.806 442.162 252.771C366.643 252.712 291.189 248.322 216.173 239.625C208.051 238.662 199.93 237.629 191.808 236.58C198.106 237.389 187.231 235.96 185.029 235.651C179.867 234.928 174.705 234.177 169.543 233.397C152.216 230.798 134.993 227.598 117.7 224.793C96.7944 221.352 76.8005 223.073 57.8906 233.397C42.3685 241.891 29.8055 254.916 21.8776 270.735C13.7217 287.597 11.2956 305.956 7.64786 324.075C4.00009 342.193 -1.67805 361.688 0.472751 380.288C5.10128 420.431 33.165 453.054 73.5313 460.35C111.506 467.232 149.687 472.807 187.971 477.556C338.361 495.975 490.294 498.178 641.155 484.129C653.44 482.982 665.708 481.732 677.959 480.378C681.786 479.958 685.658 480.398 689.292 481.668C692.926 482.938 696.23 485.005 698.962 487.717C701.694 490.429 703.784 493.718 705.08 497.342C706.377 500.967 706.846 504.836 706.453 508.665L702.633 545.797C694.936 620.828 687.239 695.854 679.542 770.874C671.513 849.657 663.431 928.434 655.298 1007.2C653.004 1029.39 650.71 1051.57 648.416 1073.74C646.213 1095.58 645.904 1118.1 641.757 1139.68C635.218 1173.61 612.248 1194.45 578.73 1202.07C548.022 1209.06 516.652 1212.73 485.161 1213.01C450.249 1213.2 415.355 1211.65 380.443 1211.84C343.173 1212.05 297.525 1208.61 268.756 1180.87C243.479 1156.51 239.986 1118.36 236.545 1085.37C231.957 1041.7 227.409 998.039 222.9 954.381L197.607 711.615L181.244 554.538C180.968 551.94 180.693 549.376 180.435 546.76C178.473 528.023 165.207 509.681 144.301 510.627C126.407 511.418 106.069 526.629 108.168 546.76L120.298 663.214L145.385 904.104C152.532 972.528 159.661 1040.96 166.773 1109.41C168.15 1122.52 169.44 1135.67 170.885 1148.78C178.749 1220.43 233.465 1259.04 301.224 1269.91C340.799 1276.28 381.337 1277.59 421.497 1278.24C472.979 1279.07 524.977 1281.05 575.615 1271.72C650.653 1257.95 706.952 1207.85 714.987 1130.13C717.282 1107.69 719.576 1085.25 721.87 1062.8C729.498 988.559 737.115 914.313 744.72 840.061L769.601 597.451L781.009 486.263C781.577 480.749 783.905 475.565 787.649 471.478C791.392 467.391 796.352 464.617 801.794 463.567C823.25 459.386 843.761 452.245 859.023 435.916C883.318 409.918 888.153 376.021 879.567 341.849ZM72.4301 365.835C72.757 365.68 72.1548 368.484 71.8967 369.792C71.8451 367.813 71.9483 366.058 72.4301 365.835ZM74.5121 381.94C74.6842 381.819 75.2003 382.508 75.7337 383.334C74.925 382.576 74.4089 382.009 74.4949 381.94H74.5121ZM76.5597 384.641C77.2996 385.897 77.6953 386.689 76.5597 384.641V384.641ZM80.672 387.979H80.7752C80.7752 388.1 80.9645 388.22 81.0333 388.341C80.9192 388.208 80.7925 388.087 80.6548 387.979H80.672ZM800.796 382.989C793.088 390.319 781.473 393.726 769.996 395.43C641.292 414.529 510.713 424.199 380.597 419.932C287.476 416.749 195.336 406.407 103.144 393.382C94.1102 392.109 84.3197 390.457 78.1082 383.798C66.4078 371.237 72.1548 345.944 75.2003 330.768C77.9878 316.865 83.3218 298.334 99.8572 296.355C125.667 293.327 155.64 304.218 181.175 308.09C211.917 312.781 242.774 316.538 273.745 319.36C405.925 331.405 540.325 329.529 671.92 311.91C695.905 308.686 719.805 304.941 743.619 300.674C764.835 296.871 788.356 289.731 801.175 311.703C809.967 326.673 811.137 346.701 809.778 363.615C809.359 370.984 806.139 377.915 800.779 382.989H800.796Z`,fill:`#0D0C22`})]}),NL={"/page/guide-start":0,"/page/guide-protocols":1,"/page/guide-structure":2,"/page/guide-metrics":3,"/page/guide-clock":4,"/page/guide-wql":5,"/page/guide-dashboards":6,"/page/guide-sessions":7,"/page/guide-metrics-summaries":8};function PL(e){return e.filter(e=>!e.route.startsWith(`/notebook`)).filter(e=>e.page.frontmatter?.type===`guide`).sort((e,t)=>(NL[e.route]??99)-(NL[t.route]??99)).map(e=>({id:`guide-${e.route}`,label:e.page.sections[0]?.heading??`Untitled`,level:2,icon:be,action:{type:`route`,to:e.route},isActive:t=>t.pathname===e.route}))}function FL(e){return[{id:`home-new-journal`,label:`New journal entry`,level:2,icon:dn,variant:`notable`,action:{type:`route`,to:`/journal?create=1`},isActive:()=>!1},...PL(e)]}var IL=e=>e.replace(/^\//,``).replace(/\/$/,``),LL=e=>{let t=IL(e);return t.charAt(0).toUpperCase()+t.slice(1)},RL=(e,...t)=>t.some(t=>e===t||e.startsWith(`${t}/`));function zL(e){return{id:IL(e.route),label:LL(e.route),level:1,icon:e.icon,action:{type:`route`,to:e.route},isActive:t=>e.familyActive(t),applyFooter:!0,panel:SL({landingLabel:e.landingLabel,icon:e.icon,route:e.route,profile:e.profile,extraChildren:e.extraChildren,familyActive:e.familyActive,createAction:e.createAction})}}var BL=[{landingLabel:`All notes`,icon:on,route:$.notes,profile:AN,familyActive:e=>e.pathname===`/notes`||e.pathname.startsWith(`/note/`)&&!e.pathname.startsWith(`/notebook`),createAction:{label:`New note`,testId:`notes-create-note`,onClick:({openCreateJournal:e,navigate:t})=>{e?e({mode:`source`}):t(`/notes?create=1&mode=source`)}}},{landingLabel:`All feeds`,icon:on,route:$.feeds,profile:jN,familyActive:e=>RL(e.pathname,`/feeds`,`/feed`)},{landingLabel:`All pages`,icon:u,route:$.pages,profile:MN,familyActive:e=>RL(e.pathname,`/pages`,`/page`),createAction:{label:`New page`,testId:`pages-create-page`,onClick:({navigate:e})=>{e(`/page/new?mode=create`)}}}];function VL(e,t=[]){let n=FL(t);return[{id:`home`,label:`Home`,level:1,icon:Zt,action:{type:`route`,to:$.home},isActive:e=>e.pathname===`/`||e.pathname===``||e.pathname.startsWith(`/page/guide-`)||e.pathname.startsWith(`/canvas`)||e.pathname===$.home||e.pathname===$.aiFirst||e.pathname.startsWith(`/ai-first/`),children:n},{id:IL($.notebooks),label:LL($.notebooks),level:1,icon:x,action:{type:`route`,to:$.notebooks},isActive:e=>RL(e.pathname,`/notebooks`,`/notebook`,`/journal`,`/day`,`/playgrounds`,`/playground`),applyFooter:!0,panel:AL},...BL.map(zL),{id:IL($.dashboards),label:LL($.dashboards),level:1,icon:Jn,action:{type:`route`,to:$.dashboards},isActive:e=>e.pathname===$.dashboards||e.pathname.startsWith(`/dashboard/`),panel:nF},{id:IL($.efforts),label:LL($.efforts),level:1,icon:k,action:{type:`route`,to:$.efforts},isActive:e=>fP(e.pathname),applyFooter:!0,panel:SL({landingLabel:`All Efforts`,icon:k,route:$.efforts,profile:NN,familyActive:e=>fP(e.pathname),createAction:{label:`New effort`,testId:`efforts-create-effort`,onClick:({navigate:e})=>{e(`/effort/new?mode=create`)}}})},{id:IL($.equipment),label:LL($.equipment),level:1,icon:Ce,action:{type:`route`,to:$.equipment},isActive:e=>pP(e.pathname),applyFooter:!0,panel:SL({landingLabel:`All Equipment`,icon:Ce,route:$.equipment,profile:PN,familyActive:e=>pP(e.pathname),createAction:{label:`New equipment`,testId:`equipment-create-equipment`,onClick:({navigate:e})=>{e(`/equipment/new?mode=create`)}}})},{id:IL($.sessions),label:LL($.sessions),level:1,icon:r,action:{type:`route`,to:$.sessions},isActive:e=>e.pathname.startsWith(`/sessions`)||e.pathname.startsWith(`/session/`)||e.pathname.startsWith(`/results`),applyFooter:!0,panel:SL({landingLabel:`All Sessions`,icon:r,route:$.sessions,profile:IN,familyActive:e=>e.pathname.startsWith(`/sessions`)||e.pathname.startsWith(`/session/`)||e.pathname.startsWith(`/results`)})},{id:IL($.tags),label:LL($.tags),level:1,icon:Ze,action:{type:`route`,to:$.tags},isActive:e=>e.pathname.startsWith(`/tags`)||e.pathname.startsWith(`/t/`),applyFooter:!0,panel:SL({landingLabel:`All Tags`,icon:Ze,route:$.tags,profile:FN,familyActive:e=>e.pathname.startsWith(`/tags`)||e.pathname.startsWith(`/t/`)})},{id:`settings`,label:`Settings`,level:1,icon:Jt,action:{type:`route`,to:$.settingsAppearance},isActive:e=>e.pathname.startsWith(`/settings`),children:[{id:`settings-profile`,label:`Profile`,level:2,icon:V,action:{type:`route`,to:$.settingsProfile},isActive:e=>e.pathname===$.settingsProfile},{id:`settings-appearance`,label:`Appearance`,level:2,icon:eee,action:{type:`route`,to:$.settingsAppearance},isActive:e=>e.pathname===$.settings||e.pathname===$.settingsAppearance},{id:`settings-tags`,label:`Tag Types`,level:2,icon:Ze,action:{type:`route`,to:$.settingsTags},isActive:e=>e.pathname===$.settingsTags},{id:`settings-sound-profiles`,label:`Sound Profiles`,level:2,icon:ee,action:{type:`route`,to:$.settingsSoundProfiles},isActive:e=>e.pathname===$.settingsSoundProfiles},{id:`settings-sync`,label:`Sync`,level:2,icon:st,action:{type:`route`,to:$.settingsSync},isActive:e=>e.pathname===$.settingsSync},{id:`settings-storage`,label:`Storage`,level:2,icon:On,action:{type:`route`,to:$.settingsStorage},isActive:e=>e.pathname===$.settingsStorage},{id:`settings-system`,label:`System`,level:2,icon:Nt,action:{type:`route`,to:$.settingsSystem},isActive:e=>e.pathname===$.settingsSystem}]},{id:`buy-me-a-coffee`,label:`Buy Me a Coffee`,level:1,icon:ML,action:{type:`external`,href:jL}}]}VL(()=>{});var HL={slate:{panel:`border-slate-500/35 shadow-slate-500/12`,accent:`from-slate-500/70 via-slate-400/25 to-transparent`,progress:`from-slate-500 to-slate-400`},amber:{panel:`border-amber-500/35 shadow-amber-500/12`,accent:`from-amber-500/75 via-amber-400/25 to-transparent`,progress:`from-amber-500 to-orange-400`},emerald:{panel:`border-emerald-500/35 shadow-emerald-500/12`,accent:`from-emerald-500/75 via-emerald-400/25 to-transparent`,progress:`from-emerald-500 to-teal-400`},sky:{panel:`border-sky-500/35 shadow-sky-500/12`,accent:`from-sky-500/75 via-sky-400/25 to-transparent`,progress:`from-sky-500 to-cyan-400`},violet:{panel:`border-violet-500/35 shadow-violet-500/12`,accent:`from-violet-500/75 via-fuchsia-400/25 to-transparent`,progress:`from-violet-500 to-fuchsia-400`},rose:{panel:`border-rose-500/35 shadow-rose-500/12`,accent:`from-rose-500/75 via-pink-400/25 to-transparent`,progress:`from-rose-500 to-pink-400`}};function UL(e){return e.proseChunks.filter(e=>e.kind===`prose`).map(e=>e.text).join(``)}function WL(e){let t=new Map;for(let n of e.sections)for(let e of n.proseChunks)e.kind===`challenge`&&t.set(e.id,n.id);return t}function GL(e){return e.toLowerCase().replace(/[^\w\s-]/g,``).replace(/\s+/g,`-`).replace(/^-+|-+$/g,``)}function KL(e){let t=e.match(/^(#{1,6}) (.+)$/);if(!t)return null;let n=t[1].length,r=t[2],i=r.match(/\{([^}]+)\}$/),a=i?i[1].trim().split(/\s+/).filter(Boolean):[];return{level:n,text:i?r.slice(0,i.index).trim():r.trim(),attrs:a}}function qL(e){let t={};for(let n of e){let e=n.match(/^([a-zA-Z][\w-]*):\s*(.+)$/);e&&(t[e[1]]=e[2].trim())}return t}function JL(e){let t=[];for(let n of e){let e=n.match(/^\s*-\s+([\w-]+):\s+(.+)$/);e&&t.push({action:e[1],value:e[2].trim()})}return t}function YL(e){let t=e.split(`
77
77
  `),n=qL(t),r=[];for(let e of t){let t=e.match(/^button:\s*(.+)$/);if(!t)continue;let n=t[1].split(`|`).map(e=>e.trim()),i=n[0]??`Run`,a,o=[];for(let e of n.slice(1)){let t=e.match(/^open:\s*(view|dialog|route)$/);if(t){a=t[1];continue}o.push(`- ${e}`)}r.push({label:i,open:a,pipeline:JL(o)})}return{name:n.name??`view`,state:n.state??`note`,source:n.source??``,runtime:n.runtime,launch:n.launch,align:n.align??`right`,width:n.width??`50%`,buttons:r}}function XL(e){let t=e.split(`
78
78
  `),n=``,r;for(let e of t){let t=e.match(/^target:\s*(.+)$/);if(t){n=t[1].trim();continue}let i=e.match(/^open:\s*(view|dialog|route)$/);if(i){r=i[1];continue}}return{target:n,open:r,pipeline:JL(t)}}function ZL(e){let t=e.split(`
@@ -99,7 +99,7 @@ sum:$metric{} by {week}
99
99
  `)?e:e+`
100
100
  `;return{statements:Ys(Qr.create({doc:n,extensions:[Rc]}),t),errors:[],success:!0}}catch(e){return{statements:[],errors:[{message:e instanceof Error?e.message:`Unknown parse error`,severity:`error`}],success:!1}}}function qR(e,...t){console.warn(`[${e}]`,...t)}function JR(e,...t){console.error(`[${e}]`,...t)}function YR(e,t={}){let n=t.sourceRevision??1,r=Pa(e,{...t,blocks:t.noteBlocks,sourceRevision:n}),i=Ma(e,t),a=[];for(let e of i){if(!Na(e))continue;let t=Object.values(r).find(t=>t.from===e.from&&t.to===e.to);t&&(e.id=t.id,e.version=t.version,e.scriptBlock&&(e.scriptBlock=XR({...e.scriptBlock,id:t.id,version:t.version}),a.push(e.scriptBlock)))}return{sections:i,blocks:a,noteBlocks:r,rawContent:e,sourceRevision:n}}function XR(e){try{let t=KR(e.content,e.sport);return{...e,statements:t.statements,errors:t.errors,state:t.success?`parsed`:`error`}}catch(t){return JR(`WorkbenchDocumentModel`,`Block parse error:`,t),e}}function ZR(e){if(e.kind!==`wod`||!e.dialect)throw Error(`The saved revision is not a workout.`);let t=Ma(e.rawContent).find(t=>t.type===e.dialect);if(!t?.scriptBlock)throw Error(`The saved workout fence cannot be read.`);let n=t.scriptBlock.content;return{id:e.blockId,content:n,dialect:e.dialect,sport:e.sport,statements:_c().read(n,e.sport).statements,startLine:0,endLine:e.rawContent.split(`
101
101
  `).length-1,version:e.version,state:`idle`,widgetIds:{},createdAt:e.savedAt}}async function QR(e,t,n,r,i=PP){let a=Date.now(),o=await i.startSession(e,{id:n,noteId:e.noteId,blockId:t.id,blockContentId:t.contentId,origin:r??`journal`,startTime:a,endTime:a,duration:0,completed:!1,status:`in-progress`,createdAt:a});return{...o,block:ZR(o.revision)}}async function $R(e,t,n,r){let i=await Z.getNote(e);if(!i)throw Error(`The note is unavailable. Save the note before starting a workout.`);return QR({noteId:i.id,rawContent:i.rawContent,blocks:i.blocks,expectedSourceRevision:i.sourceRevision},t,n,r)}var ez={content:``,sections:null,noteBlocks:{},sourceRevision:0,capturedRun:null,saveError:null,blocks:[],activeBlockId:null,saveState:`idle`,lastSavedContent:``,loadedRouteId:null,results:[],currentEntry:null,historyEntries:[],panelLayouts:{},attachments:[],runtime:null,execution:{status:`idle`,elapsedTime:0,stepCount:0,startTime:null,start:()=>{},pause:()=>{},stop:()=>{},reset:()=>{},step:()=>{}},handles:{handleStart:()=>{},handlePause:()=>{},handleStop:()=>{},handleNext:()=>{},handleStartWorkoutAction:()=>{}},activeSegmentIds:new Set,activeStatementIds:new Set,analyticsSegments:[],analyticsGroups:[],selectedAnalyticsIds:new Set,lastSelectedAnalyticsId:null,outputStatementList:[],logOutputList:[],userOutputOverrides:new Map,gridViewPreset:`default`,hoveredBlockKey:null,documentItems:[],selectedBlock:null,selectedBlockId:null,cursorLine:1,highlightedLine:null,subscriptionManager:null,viewMode:`plan`},tz=5e3;function nz(e={}){let t=e.listeners??[],n=e.nowProvider??El,r=e.notePersistence,i=e.setTimeout??((e,t)=>window.setTimeout(e,t)),a=e.clearTimeout??(e=>{typeof e==`number`&&window.clearTimeout(e)}),o=null,s=[],c=Cn()((t,n)=>{let c=Promise.resolve(),l=async i=>{let a=n(),o=a.currentEntry?.id??a.loadedRouteId;if(!(!o||!r||!e.provider?.capabilities.canWrite)&&(i.rawContent!==a.lastSavedContent||JSON.stringify(Object.values(i.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(a.currentEntry?.blocks??{}).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport])))){t({saveState:`saving`,saveError:null});try{let e=await r.saveNote({noteId:o,rawContent:i.rawContent,blocks:i.blocks,expectedSourceRevision:a.sourceRevision,metadata:{title:i.rawContent.match(/^#\s+(.+)$/m)?.[1]?.trim()??`Untitled Session`},noteType:`playground`}),s=n();t({currentEntry:e,...s.content===i.rawContent&&JSON.stringify(Object.values(s.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(i.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))?{noteBlocks:e.blocks}:{},sourceRevision:e.sourceRevision??a.sourceRevision,lastSavedContent:i.rawContent,saveState:`saved`})}catch(e){throw t({saveState:`error`,saveError:e instanceof Error?e.message:String(e)}),e}}},u=()=>{o=null;let e=n(),t={rawContent:e.content,blocks:e.noteBlocks,sourceRevision:e.sourceRevision},r=c.catch(()=>{}).then(()=>l(t));return c=r,r};return{...ez,setContent:r=>{let s=YR(r,{noteBlocks:n().noteBlocks,sourceRevision:Math.max(1,n().sourceRevision)}),c=n(),l={content:r,sections:s.sections,blocks:s.blocks,noteBlocks:s.noteBlocks};r!==c.lastSavedContent&&(c.saveState===`idle`&&(l.saveState=`changed`),o!==null&&a(o),e.provider&&e.provider.capabilities.canWrite&&(o=i(()=>{u().catch(()=>{})},tz))),t(l)},setBlocks:e=>t({blocks:e}),setEditorIdentity:r=>{let s=JSON.stringify(Object.values(n().noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))!==JSON.stringify(Object.values(r.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]));t({content:r.rawContent,noteBlocks:r.blocks}),s&&e.provider?.capabilities.canWrite&&(o!==null&&a(o),o=i(()=>{u().catch(()=>{})},tz))},acceptSaved:e=>t(t=>({...t.content===e.rawContent&&JSON.stringify(Object.values(t.noteBlocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))===JSON.stringify(Object.values(e.blocks).map(e=>[e.id,e.from,e.to,e.kind,e.dialect,e.sport]))?{noteBlocks:e.blocks}:{},sourceRevision:e.sourceRevision,lastSavedContent:e.rawContent})),restoreBlock:async e=>{if(!r)throw Error(`Note persistence is unavailable.`);await u();let i=n(),a=OR({rawContent:i.content,blocks:i.noteBlocks,sourceRevision:i.sourceRevision},e),o=await r.saveNote({noteId:e.noteId,rawContent:a.rawContent,blocks:a.blocks,expectedSourceRevision:i.sourceRevision}),s=YR(o.rawContent,{noteBlocks:o.blocks,sourceRevision:o.sourceRevision});t({content:o.rawContent,noteBlocks:o.blocks,sourceRevision:o.sourceRevision,lastSavedContent:o.rawContent,currentEntry:o,sections:s.sections,blocks:s.blocks})},startPinnedRun:async e=>{await c.catch(()=>{});let i=n(),a=i.currentEntry?.id??i.loadedRouteId;if(!a||!r)throw Error(`Save the note before starting a workout.`);try{let n=await QR({noteId:a,rawContent:i.content,blocks:i.noteBlocks,expectedSourceRevision:i.sourceRevision},e,ze(),void 0,r);return t({capturedRun:n,noteBlocks:n.note.blocks,sourceRevision:n.note.sourceRevision,currentEntry:{...i.currentEntry,...n.note,updatedAt:Date.now(),targetDate:i.currentEntry?.targetDate??Date.now(),schemaVersion:1},lastSavedContent:n.note.rawContent,saveError:null}),n.block}catch(e){throw t({saveState:`error`,saveError:e instanceof Error?e.message:String(e)}),e}},setActiveBlockId:e=>t({activeBlockId:e}),setSaveState:e=>t({saveState:e}),flushSave:async()=>{o!==null&&a(o),o=null,await u()},markSaved:e=>t({lastSavedContent:e,saveState:`saved`}),setResults:e=>t({results:e}),resetResults:()=>t({results:[]}),setCurrentEntry:e=>{if(e&&e.id!==n().currentEntry?.id){let n=YR(e.rawContent,{noteBlocks:e.blocks,sourceRevision:Math.max(1,e.sourceRevision??0)});t({currentEntry:e,content:e.rawContent,noteBlocks:n.noteBlocks,sections:n.sections,blocks:n.blocks,sourceRevision:e.sourceRevision??0,lastSavedContent:e.rawContent})}else t({currentEntry:e})},setHistoryEntries:e=>t({historyEntries:e}),setPanelLayouts:e=>t({panelLayouts:e}),expandPanel:(e,n)=>t(t=>{let r=t.panelLayouts[e]??{viewId:e,panelSpans:{},expandedPanelId:null},i=r.expandedPanelId?r.panelSpans:{...r.panelSpans};return{panelLayouts:{...t.panelLayouts,[e]:{...r,panelSpans:{...i,[n]:3},expandedPanelId:n}}}}),collapsePanel:e=>t(t=>{let n=t.panelLayouts[e];return n?{panelLayouts:{...t.panelLayouts,[e]:{...n,expandedPanelId:null}}}:t}),setAttachments:e=>t({attachments:e}),addAttachment:async r=>{let i=e.notePersistence,a=e.provider,o=n().currentEntry?.id;if(!o||!a?.capabilities.canWrite||!i)return;console.log(`[WorkbenchSession] Processing attachment: ${r.name}`);let s=await Uy.process(r),{v7:c}=await an(async()=>{let{v7:e}=await import(`./vendor-D0x8W9No.js`).then(e=>e.wt);return{v7:e}},__vite__mapDeps([0,1,2]));console.log(`[WorkbenchSession] Saving attachment to entry ${o}`),await i.mutateNote(o,{attachments:{add:[{id:c(),label:s.label,mimeType:s.mimeType,data:s.data,timeSpan:s.timeSpan??{start:Date.now(),end:Date.now()}}]}}),t({attachments:(await i.getNote(o,{projection:`workbench`,includeAttachments:!0})).attachments??[]}),console.log(`[WorkbenchSession] Attachment saved successfully`)},deleteAttachment:async r=>{let i=e.notePersistence,a=n().currentEntry?.id;!a||!i||(await i.mutateNote(a,{attachments:{remove:[r]}}),t({attachments:(await i.getNote(a,{projection:`workbench`,includeAttachments:!0})).attachments??[]}))},patchCurrentEntryResults:e=>t(t=>t.currentEntry?{currentEntry:{...t.currentEntry,results:e}}:t),completeWorkout:async(e,i)=>{let a=n().capturedRun,o=i??a?.session.id;if(!o||!r?.finishSession)throw Error(`The saved run pin is unavailable.`);let s=await r.finishSession(o,e,e.endTime);return t(t=>({results:[...t.results,e]})),s.id},loadEntry:async r=>{let i=e.notePersistence,a=e.provider;if(!i||!a)return null;let{routeId:o,routeView:s,routeSectionId:c,routeResultId:l,resultFromLocationState:u,initialActiveEntryId:d,propInitialContent:f}=r;if(n().setContent(``),n().setBlocks([]),t({currentEntry:null,loadedRouteId:o??null}),o){if(a.mode===`history`||a.mode===`static`)try{let e=l?{mode:`by-result-id`,resultId:l}:c&&s===`review`?{mode:`latest-for-section`,blockId:c}:{mode:`latest`},d=await i.getNote(o,{projection:s===`review`?`review`:`workbench`,includeAttachments:!0,includeSections:!0,resultSelection:e}).catch(async t=>(console.warn(`[WorkbenchSession] Note persistence projection failed, falling back to provider entry:`,{routeId:o,projection:s===`review`?`review`:`workbench`,resultSelectionMode:e.mode,err:t}),a.getRecord(o)));if(d){let e=YR(d.rawContent,{noteBlocks:d.blocks,sourceRevision:Math.max(1,d.sourceRevision??0)});return t({currentEntry:d,content:d.rawContent,sections:e.sections,blocks:e.blocks,noteBlocks:e.noteBlocks,sourceRevision:d.sourceRevision??0,lastSavedContent:d.rawContent,saveState:`saved`}),s===`review`&&u&&t(e=>e.currentEntry?{currentEntry:{...e.currentEntry,results:u}}:e),r.onLoaded?.(d),d}if(a.mode===`static`){let e=await jR(o);if(e)return n().setContent(e),null}}catch(e){console.error(`[WorkbenchSession] Failed to load entry for ID:`,o,e)}}else d&&e.navigate?.({type:`goToPlan`,noteId:d});return n().setContent(f??``),null},setActiveSegmentIds:e=>t({activeSegmentIds:e}),setActiveStatementIds:e=>t({activeStatementIds:e}),setAnalytics:(e,n)=>t({analyticsSegments:e,analyticsGroups:n}),appendOutputStatement:e=>t(t=>{let n=[...t.outputStatementList,e],{segments:r,groups:i}=ER(t.runtime);return t.runtime?{outputStatementList:n,analyticsSegments:r,analyticsGroups:i}:{outputStatementList:n}}),clearOutputStatementList:()=>t({outputStatementList:[]}),feedLogOutputs:(e,n)=>{let{segments:r,groups:i}=DR(e,n);t({logOutputList:e,analyticsSegments:r,analyticsGroups:i})},toggleAnalyticsSegment:(e,n,r)=>t(t=>{let i=new Set(t.selectedAnalyticsIds);if(n?.shiftKey&&t.lastSelectedAnalyticsId!==null&&r){let n=r.indexOf(t.lastSelectedAnalyticsId),a=r.indexOf(e);if(n!==-1&&a!==-1){let e=Math.min(n,a),t=Math.max(n,a);r.slice(e,t+1).forEach(e=>i.add(e))}}else n?.ctrlKey?i.has(e)?i.delete(e):i.add(e):(i.clear(),i.add(e));return{selectedAnalyticsIds:i,lastSelectedAnalyticsId:e}}),setUserOverride:(e,n)=>t(t=>{let r=new Map(t.userOutputOverrides);return r.set(e,la.from(n,e)),{userOutputOverrides:r}}),clearUserOverride:e=>t(t=>{let n=new Map(t.userOutputOverrides);return n.delete(e),{userOutputOverrides:n}}),setGridViewPreset:e=>t({gridViewPreset:e}),setHoveredBlockKey:e=>t({hoveredBlockKey:e}),setDocumentItems:e=>t({documentItems:e}),setSelectedBlock:e=>t({selectedBlock:e,selectedBlockId:e?.id??null}),setSelectedBlockId:e=>t({selectedBlockId:e}),setCursorLine:e=>t({cursorLine:e}),setHighlightedLine:e=>t({highlightedLine:e}),setSubscriptionManager:e=>{t({subscriptionManager:e}),WR.setSubscriptionRegistry(e)},setViewMode:e=>t({viewMode:e}),setRuntime:e=>{for(let e of s)e();if(s=[],e){let r=ER(e);t({runtime:e,outputStatementList:[],analyticsSegments:r.segments,analyticsGroups:r.groups}),s.push(e.subscribeToOutput(()=>{n().appendOutputStatement({})})),s.push(e.subscribeToStack(e=>{let n=e.blocks[0],r=new Set;for(let t of e.blocks)r.add(Di(t.key.toString()));let i=new Set;if(n&&Array.isArray(n.sourceIds))for(let e of n.sourceIds)i.add(e);t({activeSegmentIds:r,activeStatementIds:i})}));let i=hj();if(i?.connected){let t=new zR(i);s.push(e.subscribeToStack(e=>t.onStackSnapshot(e)),e.subscribeToOutput(e=>t.onOutput(e)),()=>t.dispose());try{t.onStackSnapshot(e.getStackSnapshot())}catch{}}}else t({runtime:null,outputStatementList:[]})},setExecution:e=>t({execution:e}),setHandles:e=>t({handles:e}),getNote:async(e,t)=>{if(!r)throw Error(`[WorkbenchSession] getNote called without a notePersistence port`);return r.getNote(e,t)},resetStore:()=>{o!==null&&(a(o),o=null);for(let e of s)e();s=[],t({...ez})}}});return t.length>0&&c.subscribe(e=>{for(let n of t)n(e)}),Object.assign(c,{__nowProvider:n})}var rz=nz();function iz(e){let t=rz;return rz=e,t}function az(){return rz}var oz=e=>It(rz,e),sz=({nowProvider:e,notePersistence:t,provider:n,navigate:r,children:i})=>{let a=(0,U.useMemo)(()=>nz({nowProvider:e,notePersistence:t,provider:n,navigate:r}),[e,t,n,r]);return(0,U.useEffect)(()=>{let e=iz(a);return()=>{iz(e),a.getState().resetStore()}},[a]),U.createElement(U.Fragment,null,i)},cz={getEventsByTimeRange:(e,t)=>Z.getEventsByTimeRange(e,t),getEventsByMetricDates:e=>Z.getEventsByMetricDates(e),getEventsByResult:e=>Z.getEventsByResult(e),getEventsForNote:e=>Z.getEventsForNote(e),getEventsByContent:e=>Z.getEventsByContent(e),scanAll:()=>Z.scanAll(),appendEvents:e=>Z.appendEvents(e),finalizeSummaries:(e,t)=>Z.finalizeSummaries(e,t),deleteEvents:e=>Z.deleteEvents(e)},lz={getAllNotes:()=>Z.getAllNotes(),getNotesByIds:async e=>[...(await Z.getDetailBatches(e)).values()].map(e=>e.note),getNoteIdsForTag:async e=>new Set((await Z.getNotesForTag(e)).map(e=>e.id)),getNoteTagLabels:async e=>(await Z.getTagsForNote(e)).map(e=>e.label),queryDomain:async e=>{if(!Z.queryDomain)return;let t=await Z.queryDomain({...e,plan:`notes`});return t&&t.plan===`notes`?t:void 0}},uz={getAllBlocks:()=>Z.getAllBlockIndex(),queryDomain:async e=>{if(!Z.queryDomain)return;let t=await Z.queryDomain({...e,plan:`blocks`});return t&&t.plan===`blocks`?t:void 0}},dz=class{async getAllEfforts(){let e=KO();return e.isInitialized()||await VO(e),[...e.list()]}},fz=new Zg,pz={events:[],notes:[]},mz={events:[],notes:[]};fz.set(`@session`,pz),fz.set(`@today`,mz);function hz(){let e=az().getState(),t=e.runtime?.getOutputStatements()??[],n=e.currentEntry;return pz.notes=n?[{id:n.id,title:n.title,createdAt:n.createdAt,date:n.targetDate,rawContent:n.rawContent,sourceRevision:n.sourceRevision??1,blocks:n.blocks??{}}]:[],t.length===0?(pz.events=[],pz):(pz.events=c_(t.map(tm),{noteId:n?.id??``,resultId:`live:${n?.id??`session`}`,origin:`playground`,workoutTimestamp:n?.targetDate}),pz)}function gz(e,t,n,r){let i=[...t].sort((e,t)=>(e.position??1/0)-(t.position??1/0)||e.createdAt-t.createdAt);for(let e of i){let t=n.get(e.pageId)?.date;if(t)return t}return Fg(e.date??e.createdAt,r)}async function _z(e,t){let n=Fg(e.instant,e.timeZone),r=Bg(n,e.timeZone),i=Bg(Ig(n,1),e.timeZone),[a,o,s,c]=await Promise.all([Z.getEventsByTimeRange(r,i),Z.getAllNotes(),Z.getAllPageNotes(),Z.getAllPages()]),l=a.filter(e=>e.timestamp>=r&&e.timestamp<i),u=new Map(c.map(e=>[e.id,e])),d=new Map;for(let e of s){let t=d.get(e.noteId);t?t.push(e):d.set(e.noteId,[e])}let f=[];for(let t of o)gz(t,d.get(t.id)??[],u,e.timeZone)===n&&f.push(t);t===bz&&(mz.events=l,mz.notes=f,hz())}var vz=null,yz=null,bz=0,xz=!1,Sz=new Set;function Cz(){for(let e of Sz)e()}function wz(e,t){yz=t;let n=++bz;return vz=_z(e,n),vz.then(()=>{n===bz&&Tz()},()=>{n===bz&&Tz()}),vz}function Tz(){xz=!0,Cz()}function Ez(){let e=kg(),t=Fg(e.instant,e.timeZone);return!vz||yz!==t?wz(e,t):vz}function Dz(){xz=!1;let e=kg();return wz(e,Fg(e.instant,e.timeZone))}function Oz(){return xz}function kz(e){return Sz.add(e),()=>{Sz.delete(e)}}var Az=class extends J_{async runQuery(e,t){return await Ez(),super.runQuery(e,t)}async runPipeline(e,t){return await Ez(),super.runPipeline(e,t)}async runFind(e,t){return await Ez(),super.runFind(e,t)}async runRows(e,t){return await Ez(),super.runRows(e,t)}async run(e,t){return await Ez(),super.run(e,t)}};function jz(){return new Az({eventStore:cz,noteStore:lz,blockStore:uz,effortStore:new dz,blockEffortsStore:{getAllFromIndex:(e,t)=>Z.getAllFromIndex(`block_efforts`,e,t)},tagsStore:{getAllFromIndex:(e,t)=>Z.getAllFromIndex(`tags`,e,t),getAll:()=>Z.getAllTags()},noteTagsStore:{getAllFromIndex:(e,t)=>Z.getAllFromIndex(`note_tags`,e,t)},pageStore:{getNotePages:e=>Z.getNotePages(e),getPage:e=>Z.getPage(e),getAllPages:()=>Z.getAllPages(),getAllLinks:()=>Z.getAllPageNotes()},relationStore:{getBatches:e=>Z.getDetailBatches(e)},datasetStore:{getDataset:e=>e===`@session`?hz():fz.getDataset(e)}})}var Mz=jz();function Nz(e){let t=e.split(`/`),n=t[0]??e,r=t[1]??``;return n===`journal`?{kind:`journal`,id:r,raw:e}:n===`playground`?{kind:`playground`,id:r,raw:e}:t.length<2?{kind:`workout`,id:n,raw:e}:{kind:`workout`,category:n,id:r,raw:e}}var Pz=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fz(e){return typeof e==`string`&&e&&!Pz.test(e)?e:void 0}function Iz(e){return!!e.sourceId?.startsWith(`notebook:`)||e.sourcePath?.startsWith(`markdown/notebooks/`)===!0}function Lz(e){return e.type===`dashboard`||e.sourceId===`dashboards`||e.sourcePath?.startsWith(`markdown/dashboards/`)===!0}function Rz(e){return e.sourceId===`efforts`||e.sourcePath?.startsWith(`markdown/efforts/`)===!0}function zz(e){return e.sourceId===`equipment`||e.sourcePath?.startsWith(`markdown/equipment/`)===!0}function Bz(e){return e.type===`tag`&&e.id.startsWith(`tag/`)}function Vz(e){let t=/^tag\/([^/]+)\/(.+)$/.exec(e.id);return t?{type:t[1],label:t[2]}:void 0}function Hz(e,t){let n=e.sourcePath?.replace(/^markdown\/[^/]+\//,``).replace(/\.md$/,``);if(!n)return;let r=n.split(`/`);return r.length===t?r[t-1]:void 0}function Uz(e){let t=e.sourceId;if(t?.startsWith(`notebook:`)){let e=t.slice(9);if(e&&e!==`_root`){let t=e.indexOf(`/`);return t===-1?{slug:e,item:``}:{slug:e.slice(0,t),item:e.slice(t+1)}}}let n=/^markdown\/notebooks\/([^/]+)\/(.+)\.md$/.exec(e.sourcePath??``);if(n)return{slug:n[1],item:n[2].toLowerCase()===`readme`?``:n[2]};let r=e.id;if(Pz.test(r))return{slug:``,item:``};let[i,...a]=r.split(`/`);return{slug:i,item:a.join(`/`)}}function Wz(e){return e.sourceId===`playground`||e.type===`playground`||e.id.startsWith(`playground/`)}function Gz(e){return e.id.startsWith(`playground/`)?e.id.slice(11):e.id}function Kz(e){return{...qz(e),noteType:e.type,notebookId:v_(e),feedId:e.feedSourceId??(y_(e)===`user`?`local`:`core`),editable:Ea(e,y_(e))}}function qz(e){let t=e.id,n=e.title,r=e.tags&&e.tags.length>0?e.tags:void 0;if(Wz(e))return{id:t,kind:`note`,sourceNotebook:`playground`,sourceNote:Gz(e),sourceId:e.sourceId,title:n,date:null,createdAt:e.createdAt,...r?{tags:r}:{}};if(Iz(e)){let{slug:i,item:a}=Uz(e),o=!a,s=a.split(`/`),c=s.length>1&&/^\d{4}-\d{2}-\d{2}$/.test(s[0])?s[0]:null;return{id:t,kind:`note`,sourceNotebook:i,sourceNote:o?``:a,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:c??(e.date?VP(new Date(e.date)):null),createdAt:e.createdAt,subtitle:i,...r?{tags:r}:{}}}if(Lz(e))return{id:t,kind:`dashboard`,sourceNotebook:`dashboards`,sourceNote:Hz(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:`dashboards`,...r?{tags:r}:{}};if(Rz(e)){let i=Hz(e,2)??t,a=e.sourcePath?.match(/^markdown\/efforts\/([^/]+)\//)?.[1];return{id:t,kind:`effort`,sourceNotebook:`efforts`,sourceNote:i,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:a,effort:{slug:i},...r?{tags:r}:{}}}if(zz(e))return{id:t,kind:`equipment`,sourceNotebook:`equipment`,sourceNote:Hz(e,1)??t,sourceId:e.sourceId,sourcePath:e.sourcePath,title:n,date:null,createdAt:e.createdAt,subtitle:`equipment`,...r?{tags:r}:{}};if(Bz(e)){let i=Vz(e);return{id:t,kind:`tag`,sourceNotebook:`tags`,sourceNote:i?.label??n,title:n||i?.label||t,date:null,createdAt:e.createdAt,subtitle:(`tagType`in e&&typeof e.tagType==`string`?e.tagType:void 0)??i?.type,detail:e.rawContent||void 0,...r?{tags:r}:{}}}if(e.sourceId?.startsWith(`guides:`)){let i=e.sourceId.slice(7)||t;return{id:t,kind:`note`,sourceNotebook:`guides`,sourceNote:i,sourceId:e.sourceId,sourcePath:e.sourcePath,pageSlug:Fz(i.replace(/^\//,``).replace(/^page\//,``)),title:n,date:null,createdAt:e.createdAt,...r?{tags:r}:{}}}let i=null;return`journalDate`in e&&typeof e.journalDate==`string`?i=e.journalDate:`date`in e&&typeof e.date==`string`?i=e.date:`targetDate`in e&&e.targetDate&&(typeof e.targetDate==`number`||typeof e.targetDate==`string`)?i=VP(new Date(e.targetDate)):e.createdAt&&(i=VP(new Date(e.createdAt))),{id:t,kind:`note`,sourceNotebook:`journal`,sourceNote:t,sourceId:e.sourceId,sourcePath:e.sourcePath,pageId:`pageId`in e&&typeof e.pageId==`string`?e.pageId:void 0,pageSlug:`slug`in e?Fz(e.slug):void 0,title:n,date:i,createdAt:e.createdAt,...r?{tags:r}:{}}}function Jz(e){return{id:e.noteId,title:e.noteTitle,createdAt:e.createdAt,type:`note`,sourceId:e.sourceId,sourcePath:e.sourcePath,rawContent:``,sourceRevision:1,blocks:{}}}var Yz=3,Xz=120;function Zz(e){return e.split(`
102
- `).map(e=>e.trim()).filter(Boolean).slice(0,Yz).map(e=>e.length>Xz?`${e.slice(0,119)}…`:e)}function Qz(e){let t=Kz(Jz(e));return{...t,blockContentId:e.blockContentId??t.blockContentId,block:{blockId:e.blockId,dataType:e.dataType,preview:Zz(e.rawContent)}}}function $z(e){return e?e.split(`-`).map(e=>{let t=e.toLowerCase();return t===`c2b`?`C2B`:t===`t2b`?`T2B`:t===`ghd`?`GHD`:t===`hspu`?`HSPU`:e.charAt(0).toUpperCase()+e.slice(1)}).join(` `):``}function eB(e){if(!Number.isFinite(e)||e<=0)return`00:00`;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;if(n>=60){let e=Math.floor(n/60),t=n%60;return`${e}:${String(t).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function tB(e){if(!e)return`Workout Session`;let t=Nz(e);return t.kind===`journal`?t.id?`Journal: ${t.id}`:`Journal Entry`:t.kind===`workout`?$z(t.id)||t.id:t.id?$z(t.id):e}function nB(e){let t=[e.baseAttributes?.discipline,e.baseAttributes?.met==null?void 0:`MET ${e.baseAttributes.met.toFixed(1)}`,e.baseAttributes?.intensityTier].filter(Boolean);return{id:e.slug,kind:`effort`,sourceNotebook:e.registrySource??`effort`,sourceNote:e.slug,title:e.label,date:null,subtitle:t.join(` • `),detail:e.aliases&&e.aliases.length>0?`Aliases: ${e.aliases.join(`, `)}`:void 0,effort:{slug:e.slug,label:e.label,discipline:e.baseAttributes?.discipline,met:e.baseAttributes?.met,intensityTier:e.baseAttributes?.intensityTier,aliases:e.aliases,registrySource:e.registrySource}}}function rB(e){let t=(e.type??``).toLowerCase(),n=(`name`in e&&typeof e.name==`string`?e.name:``).toLowerCase(),r=typeof e.value==`number`?e.value:Number(e.value);return Number.isFinite(r)?t===`rep`||n===`reps`||n===`rep`?{kind:`rep`,val:r}:t===`weight`||t===`load`||n===`load`||n===`weight`||n===`volume`?{kind:`load`,val:r}:t===`distance`||n===`distance`?{kind:`distance`,val:r}:t===`tis`||n===`tis`?{kind:`tis`,val:r}:t===`duration`||n===`duration`?{kind:`duration`,val:r}:null:null}function iB(e){let t=1/0,n=-1/0,r=0,i=0,a=0,o=0,s=new Set;for(let c of e.events)if(c.outputType===`segment`&&o++,c.effortSlug&&s.add(c.effortSlug),c.timeSpan?.started!=null&&(c.timeSpan.started<t&&(t=c.timeSpan.started),c.timeSpan.ended!=null&&c.timeSpan.ended>n&&(n=c.timeSpan.ended)),Array.isArray(c.metrics))for(let e of c.metrics){let t=rB(e);t&&(t.kind===`rep`?r+=t.val:t.kind===`load`?i+=t.val:t.kind===`tis`&&t.val>a&&(a=t.val))}return{elapsedMs:Number.isFinite(t)&&Number.isFinite(n)&&n>t?n-t:void 0,reps:r>0?r:void 0,loadLbs:i>0?i:void 0,tis:a>0?a:void 0,segmentCount:o>0?o:void 0,effortSlugs:Array.from(s)}}function aB(e,t){let n=iB(e),r=[];n.elapsedMs!=null&&r.push(eB(n.elapsedMs)),n.tis!=null&&r.push(`TIS ${n.tis.toFixed(1)}`),n.loadLbs!=null&&r.push(`Volume: ${n.loadLbs.toLocaleString()} lbs`),n.reps!=null&&r.push(`${n.reps} reps`),n.segmentCount!=null&&r.push(`${n.segmentCount} splits`);let i=n.effortSlugs.map($z),a=VP(new Date(e.timestamp)),o=e.events.find(e=>!!e.blockContentId)?.blockContentId;return{id:e.resultId,kind:`result`,sourceNotebook:`results`,sourceNote:e.resultId,title:t?.noteTitle??tB(e.noteId),date:a,blockContentId:o,subtitle:r.join(` • `),detail:i.length>0?i.join(`, `):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:`all`,elapsedMs:n.elapsedMs,reps:n.reps,loadLbs:n.loadLbs,tis:n.tis,segmentCount:n.segmentCount,events:e.events}}}function oB(e,t){let n;e.timeSpan?.started!=null&&e.timeSpan?.ended!=null&&(n=e.timeSpan.ended-e.timeSpan.started);let r,i,a,o;if(Array.isArray(e.metrics))for(let t of e.metrics){let e=rB(t);e&&(e.kind===`rep`?r=e.val:e.kind===`load`?i=e.val:e.kind===`distance`?a=e.val:e.kind===`tis`?o=e.val:e.kind===`duration`&&!n&&(n=e.val))}let s=e.outputType===`segment`?`segment`:`event`,c=t?.index??0,l=e.effortSlug?$z(e.effortSlug):e.outputType===`segment`?`Round ${c+1}`:`${e.outputType.charAt(0).toUpperCase()+e.outputType.slice(1)} ${c+1}`,u=[];n!=null&&u.push(eB(n)),r!=null&&i!=null?u.push(`${r} reps @ ${i} lbs`):r==null?i!=null&&u.push(`${i} lbs`):u.push(`${r} reps`),a!=null&&u.push(`${a}m`),o!=null&&u.push(`TIS ${o.toFixed(1)}`);let d=VP(new Date(e.timestamp));return{id:e.id,kind:s,sourceNotebook:`results`,sourceNote:e.id,title:l,date:d,blockContentId:e.blockContentId,subtitle:u.join(` • `),detail:e.effortSlug?$z(e.effortSlug):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:e.outputType,effortSlug:e.effortSlug,elapsedMs:n,reps:r,loadLbs:i,distanceMeters:a,tis:o,metrics:e.metrics}}}function sB(e,t){if(!e||e.error||!e.runs)return[];let n=e.parsed?.filters?.find(e=>e.key===`plane`&&!e.negate),r=e.parsed?.outputType??n?.values[0]?.value;if(r===`segment`){let t=[];for(let n of e.runs){let e=0;for(let r of n.events)r.outputType===`segment`&&t.push(oB(r,{index:e++}))}return t}if(r&&r!==`all`){let t=[];for(let n of e.runs){let e=0;for(let i of n.events)i.outputType===r&&t.push(oB(i,{index:e++}))}return t}return e.runs.map(e=>aB(e,{noteTitle:t?.noteTitles?.get(e.noteId)}))}function cB(e,t,n){let r=typeof e.__id==`string`&&e.__id?e.__id:void 0,i=typeof e.__resultId==`string`&&e.__resultId?e.__resultId:void 0,a=typeof e.effort==`string`&&e.effort?e.effort:void 0,o=[];for(let[t,n]of Object.entries(e))t.startsWith(`__`)||t===`date`||t===`effort`||(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&o.push(`${t}: ${n}`);return{id:r??i??`${t}:${n}`,kind:t,sourceNotebook:`results`,sourceNote:i??r??`${t}:${n}`,title:a?$z(a):`${t===`segment`?`Segment`:`Event`} ${n+1}`,date:typeof e.date==`string`?e.date:null,subtitle:o.length>0?o.join(` • `):void 0}}function lB(e){let t=e.parsed.family===`aggregate`?e.parsed.metric:`metric`;return e.series.map(e=>{let n=e.points.map(t=>`${t.value}${e.unit?` ${e.unit}`:``}`).join(` • `);return{id:`aggregate:${t}:${e.key}`,kind:`result`,sourceNotebook:`results`,sourceNote:e.label,title:`${t}: ${n}`,subtitle:e.label,date:null}})}function uB(e,t,n){e&&e({selected:Math.max(t?.selected??0,n.length),matched:n.length})}function dB(e){return typeof e==`object`&&!!e&&`runFind`in e}var fB=new class e{customService;noteTitleResolver;noteTagsResolver;noteBlockInfo;constructor(e){dB(e)?this.customService=e:(this.customService=e?.service,this.noteTitleResolver=e?.noteTitleResolver,this.noteBlockInfo=e?.noteBlockInfo??!1,this.noteTagsResolver=e?.noteTagsResolver)}get service(){return this.customService??Mz}withNoteBlockInfo(){let t=new e({service:this.service,noteTitleResolver:this.noteTitleResolver,noteTagsResolver:this.noteTagsResolver,noteBlockInfo:!0});return Object.prototype.hasOwnProperty.call(this,`query`)&&(t.query=this.query),t}async hydrateEntries(e,t){let n=new Set;for(let r of e)r.sourceNotebook===`journal`&&n.add(r.id),t&&(!r.title||!r.tags||r.tags.length===0)&&n.add(r.id);if(n.size===0)return;let r=await Z.getDetailBatches([...n]);for(let t of e){if(t.sourceNotebook!==`journal`)continue;let e=r.get(t.id),n=ba(e?.links??[],e?.pages??[]);t.placements=n;let i=xa(n);t.pageId??=i.pageId,i.pageSlug&&(t.pageSlug=i.pageSlug)}if(t)for(let t of e){let e=r.get(t.id);!t.title&&e?.note.title&&(t.title=e.note.title),e&&e.tags.length>0&&((!t.tags||t.tags.length===0)&&(t.tags=e.tags.map(e=>e.label)),t.typedTags=e.tags.map(e=>({label:e.label,type:e.type})))}}async query(e,t){let n=typeof e==`string`?X(e):e;if(!n||n.error)return[];if(eh(n)){if(n.target===`effort`){let e=this.service.runFindEffort?await this.service.runFindEffort(n):await this.service.runFind(n),r=new Map(e.notes.map(e=>[e.id,e])),i=(e.efforts??[]).map(e=>e.ownerNoteId&&r.has(e.ownerNoteId)?Kz(r.get(e.ownerNoteId)):nB(e));return uB(t,e.stages,i),i}if(n.target===`block`){let e=await this.service.runFind(n),r=e.blocks.map(Qz);return await this.hydrateEntries(r,!0),uB(t,e.stages,r),r}if(n.target===`session`){let e=await this.service.runFind(n);t?.(e.stages);let r;if(this.noteTitleResolver&&e.runs){r=new Map;for(let t of e.runs)if(!r.has(t.noteId)){let e=await this.noteTitleResolver(t.noteId);e&&r.set(t.noteId,e)}}let i=sB(e,{noteTitles:r});return uB(t,e.stages,i),i}if(n.target===`segment`||n.target===`event`){let e=n.target,r=await this.service.runFind(n),i=(r.table?.rows??[]).map((t,n)=>cB(t,e,n));return uB(t,r.stages,i),i}let e=await this.service.runFind(n),r=e.notes.map(Kz);if(this.noteTagsResolver?(await this.hydrateEntries(r,!1),await Promise.all(r.map(async e=>{if(!e.tags||e.tags.length===0){let t=await this.noteTagsResolver(e.id);t&&t.length>0&&(e.tags=t)}}))):await this.hydrateEntries(r,!0),uB(t,e.stages,r),this.noteBlockInfo)for(let t=0;t<r.length;t++){let n=r[t],i=e.notes[t];n.excerpt=Zz(i.rawContent);try{Fa(i.rawContent,i.blocks,i.sourceRevision)}catch{continue}let a=Object.values(i.blocks).sort((e,t)=>e.from-t.from).find(e=>e.kind===`wod`),o=a&&Ma(i.rawContent).find(e=>e.from===a.from&&e.scriptBlock);if(a&&o?.scriptBlock){let e=o.scriptBlock.content,t=_a(e);n.wodBlock={blockId:a.id,blockVersion:a.version,blockContentId:t,content:e},n.blockContentId=t}}return r}if(n.family===`aggregate`){if(!this.service.runQuery)return[];let e=await this.service.runQuery(n.raw),r=lB(e);return t?.({selected:e.stages?.selected??r.length,matched:r.length}),r}return[]}};async function pB(e,t=fB,n){return t.query(e,n)}function mB(e){return e?e.map(e=>e.kind===`wql`?`${e.id}|${e.query}|${e.limit??``}`:`s:${e.id}`).join(`;`):``}async function hB(e){try{let t=(await pB(e.query)).filter(t=>!e.filterEntry||e.filterEntry(t)).slice(0,e.limit??6).map(t=>({kind:`link`,id:`${e.id}:${t.id}`,label:e.labelFromEntry?e.labelFromEntry(t):t.title,to:e.toEntry?e.toEntry(t):void 0,muted:!0}));return{kind:`section`,id:e.id,label:e.label,entries:t}}catch{return{kind:`section`,id:e.id,label:e.label,entries:[]}}}function gB(e){let t=mB(e),n=(0,U.useRef)(e);n.current=e;let[r,i]=(0,U.useState)(()=>e&&!e.some(e=>e.kind===`wql`)?e:[]);return(0,U.useEffect)(()=>{let e=n.current;if(!e){i([]);return}if(!e.some(e=>e.kind===`wql`)){i(e);return}let t=!1;return Promise.all(e.map(e=>e.kind===`wql`?hB(e):Promise.resolve(e))).then(e=>{t||i(e)}),()=>{t=!0}},[t]),r}function _B(){let[e]=ln(`s`,{shallow:!0}),{navState:t}=mN(),n=t.activeL3Id??``;return e||n||``}function vB({entry:e,active:t,onActivate:n}){let r=e.onRun;return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:G(`group flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors`,e.muted?`text-[11.5px]`:`text-[13px]`,t?`bg-primary/10 font-semibold text-primary`:G(`hover:bg-muted/60 hover:text-foreground`,e.muted?`text-muted-foreground/70`:`text-muted-foreground`)),children:[e.icon&&(0,W.jsx)(e.icon,{className:`size-4 shrink-0`}),e.timestamp&&(0,W.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/60`,children:e.timestamp}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 line-clamp-2 break-words`,title:e.label,children:e.label}),e.badge&&(0,W.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground/50`,children:e.badge}),r&&(0,W.jsx)(`span`,{role:`button`,tabIndex:-1,title:e.runIcon===`link`?`View workout`:e.runIcon===`stop`?`Stop workout`:e.runIcon===`edit`?`Edit note`:`Start workout`,onClick:t=>{t.stopPropagation(),e.onRun?.()},className:`flex size-5 shrink-0 items-center justify-center rounded text-primary opacity-0 transition-all group-hover:opacity-100 hover:bg-primary/10`,children:e.runIcon===`link`?(0,W.jsx)(dr,{className:`size-3.5`}):e.runIcon===`stop`?(0,W.jsx)(Ie,{className:`size-3.5`}):e.runIcon===`edit`?(0,W.jsx)(en,{className:`size-3.5`}):(0,W.jsx)(_e,{className:`size-3.5`})})]})}function yB({entries:e,activeId:t,onSection:n}){let r=yn(),{scrollToSection:i}=mN(),a=e=>{if(n)return n(e);if(e.onRun)return e.onRun();if(e.to)return r(e.to);if(e.sectionId)return i(e.sectionId)};return(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>e.kind===`section`?e.entries.length===0?null:(0,W.jsxs)(`div`,{className:`mt-1 flex flex-col gap-0.5 first:mt-0`,children:[(0,W.jsx)(`div`,{className:`px-2 pb-1 pt-3 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,W.jsx)(yB,{entries:e.entries,activeId:t,onSection:n})]},e.id):e.kind===`wql`?null:(0,W.jsx)(vB,{entry:e,active:t!=null&&e.sectionId===t,onActivate:a},e.id))})}function bB(){let e=yn(),{scrollToSection:t}=mN();return{navigate:(t,n)=>e(t,{replace:n?.replace}),setQueryParam:(e,t)=>{},scrollToSection:t}}function xB(){let e=bB(),{openCreateJournal:t}=mN();return n=>{if(n.id===`home-new-journal`){t({mode:`blank`});return}TI(n.action,e)}}function SB(e,t,n){return e.isActive?e.isActive(n,t):e.action.type===`route`?e.action.to===`/`?n.pathname===`/`||n.pathname===``:n.pathname===e.action.to:e.action.type===`scroll`?t.activeL3Id===e.action.sectionId:e.action.type===`query`&&t.activeL3Id===e.id}function CB({items:e}){let{navState:t}=mN(),n=ht(),r=xB();return(0,W.jsx)(lF,{children:e.map(e=>{if(e.variant===`notable`)return(0,W.jsx)(`div`,{className:`mb-2`,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`nav-item-${e.id}`,onClick:()=>r(e),className:`flex w-full items-center justify-center gap-2 rounded-lg bg-primary/10 px-3 py-2 text-xs font-semibold text-primary transition-all hover:bg-primary hover:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-sm`,children:[(0,W.jsx)(Rt,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{children:e.label})]})},e.id);let i=SB(e,t,n);return e.children&&e.children.length>0?(0,W.jsx)(AI,{title:e.label,count:e.children.length,defaultOpen:e.children.some(e=>SB(e,t,n)),collapsible:e.id!==`syntax-group`,children:e.children.map(e=>{let i=SB(e,t,n);return(0,W.jsxs)(uF,{onClick:()=>r(e),current:i,children:[e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:e.label})]},e.id)})},e.id):(0,W.jsxs)(uF,{onClick:e.disabled?void 0:()=>r(e),current:i,disabled:e.disabled,"aria-label":e.disabled?`${e.label} (coming soon)`:void 0,className:e.disabled?`opacity-60`:void 0,children:[e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:e.disabled?`+`:e.label})]},e.id)})})}function wB({navSpec:e}){let{tree:t,navState:n,dispatch:r,contextNav:i}=mN(),a=ht(),o=gB(e),s=(t??[]).find(e=>e?.id===n.activeL1Id)??null,c=i?.pathname===a.pathname?i:null;return(0,W.jsxs)(oF,{children:[(0,W.jsx)(sF,{children:(0,W.jsx)(`div`,{className:`px-2 pt-3 pb-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:s?.label??`Wod Wiki`})}),(0,W.jsxs)(cF,{children:[(()=>{if(c||!s)return null;if(s.panel){let e=s.panel;return(0,W.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,W.jsx)(e,{item:s,navState:n,dispatch:r})})}return s.children&&s.children.length>0?(0,W.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,W.jsx)(CB,{items:s.children})}):null})(),c?(0,W.jsx)(`div`,{className:`pt-1`,children:(0,W.jsx)(yB,{entries:c.spec})}):o.length>0&&(0,W.jsx)(`div`,{className:`pt-1`,children:(0,W.jsx)(yB,{entries:o})})]})]})}var TB=`0.48.2172`,EB=`https://github.com/bitcobblers/wod-wiki/releases`;function DB(e){return/-pr\.\d+$/.test(e)?EB:`${EB}/tag/v${e}`}function OB({onSearch:e,onCreate:t}){let{tree:n,navState:r,dispatch:i}=mN(),a=yn(),s=ht(),c=eF(),l={navigate:(e,t)=>a(e,{replace:t?.replace}),setQueryParam:()=>{},scrollToSection:()=>{}},u=(n??[]).filter(e=>e!=null&&e.icon!=null&&e.id!==`settings`&&e.id!==`buy-me-a-coffee`),d=s.pathname.startsWith(`/settings`),f=s.pathname===`/`||s.pathname===``,p=`pointer-events-none absolute left-full top-1/2 -translate-y-1/2 z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`;return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>a(`/`),title:`Home`,"aria-label":`Wod Wiki home`,"aria-current":f?`page`:void 0,className:`group relative mb-3 grid size-8 shrink-0 place-items-center rounded-xl bg-primary text-primary-foreground shadow-md shadow-primary/20 rotate-3`,children:[(0,W.jsx)(k,{size:17}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Home`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Home`})]}),(0,W.jsx)(`nav`,{"aria-label":`Primary`,className:`flex flex-col items-center gap-1.5`,children:u.map(e=>{let t=e.icon,n=SB(e,r,s);return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{i({type:`SET_ACTIVE_L1`,id:e.id}),TI(e.action,l)},title:e.label,"aria-label":e.label,"aria-current":n?`page`:void 0,className:G(`group relative grid size-9 place-items-center rounded-lg transition-colors`,n?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[n&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(t,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:e.label}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:e.label})]},e.id)})}),(0,W.jsx)(`div`,{className:`flex-1`}),(0,W.jsxs)(`button`,{type:`button`,onClick:e,title:`Search (⌘/)`,"aria-label":`Search`,className:`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,W.jsx)(o,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Search`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Search (⌘/)`})]}),(0,W.jsxs)(`a`,{href:jL,target:`_blank`,rel:`noopener noreferrer`,title:`Buy Me a Coffee`,"aria-label":`Buy Me a Coffee`,className:`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,W.jsx)(ML,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Buy Me a Coffee`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Buy Me a Coffee`})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{c(),a(`/settings/profile`)},title:`Profile`,"aria-label":`Profile`,"aria-current":s.pathname.startsWith(`/settings/profile`)?`page`:void 0,"data-testid":`nav-profile`,className:G(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,s.pathname.startsWith(`/settings/profile`)?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[s.pathname.startsWith(`/settings/profile`)&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(V,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Profile`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Profile`})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{c(),a(`/settings/appearance`)},title:`Settings`,"aria-label":`Settings`,"aria-current":d?`page`:void 0,"data-testid":`nav-settings`,className:G(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,d?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[d&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(Jt,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Settings`}),(0,W.jsxs)(`span`,{role:`tooltip`,className:`pointer-events-none absolute bottom-0 left-full z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[`Settings (v`,TB,`)`]})]})]})}function kB({activations:e,activeSection:t,variant:n,deps:r,className:i}){return(0,W.jsx)(`nav`,{className:G(`lg:sticky z-20 flex items-center gap-1 px-4 py-2 bg-background/95 backdrop-blur-sm border-b border-border/50 overflow-x-auto`,n===`top-fixed`?`lg:top-0`:`lg:top-[104px]`,i),children:e.map(e=>(0,W.jsx)(`button`,{onClick:()=>TI(e.action,r),className:G(`px-3 py-1.5 rounded-full text-[10px] font-black uppercase tracking-[0.12em] whitespace-nowrap transition-all ring-1`,t===e.id?`bg-primary text-primary-foreground ring-primary/30 shadow-md`:`bg-muted/50 text-muted-foreground ring-transparent hover:bg-muted hover:ring-border`),children:e.label},e.id))})}var AB=class e{now;name=`tick`;timestamp;data;static _counter=0;constructor(t,n=El){this.now=n;let r=this.now.nowMs();e._counter++,this.timestamp=new Date(r+e._counter),this.data=t}},jB=20,MB=e=>{let[t,n]=(0,U.useState)(`idle`),[r,i]=(0,U.useState)(0),[a,o]=(0,U.useState)(0),[s,c]=(0,U.useState)(null),l=(0,U.useRef)(null),u=(0,U.useRef)(null),d=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),n(`idle`)},[]),f=(0,U.useCallback)(()=>{if(e)try{let t=new AB(void 0,e.nowProvider);e.handle(t),o(e=>e+1)}catch{d(),n(`error`)}},[e,d]);(0,U.useEffect)(()=>{if(e)return e.subscribeToStack(e=>{e.blocks.length===0&&t!==`completed`&&(l.current&&=(clearInterval(l.current),null),n(`completed`))})},[e,t]),(0,U.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]);let p=(0,U.useCallback)(()=>{if(!e){console.warn(`useRuntimeExecution: Cannot start execution without a runtime`);return}if(t===`running`){console.warn(`useRuntimeExecution: Runtime is already running`);return}t===`paused`&&e.handle({name:`timer:resume`,timestamp:new Date,data:{}}),n(`running`);let i=e?.nowProvider?.nowMs()??El.nowMs();u.current=i-r,r===0&&c(i),l.current=setInterval(f,jB)},[e,t,r,f]),m=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),e&&e.handle({name:`timer:pause`,timestamp:new Date,data:{}}),n(`paused`)},[e]),h=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),i(0),o(0),n(`idle`),c(null),u.current=null},[e]),g=(0,U.useCallback)(()=>{!e||t===`running`||(n(`paused`),f())},[e,t,f]);return(0,U.useEffect)(()=>{if(t!==`running`||!u.current)return;let n=setInterval(()=>{i((e?.nowProvider?.nowMs()??El.nowMs())-u.current)},100);return()=>clearInterval(n)},[t,e?.nowProvider]),(0,U.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]),(0,U.useEffect)(()=>{h()},[e,h]),(0,U.useMemo)(()=>({status:t,elapsedTime:r,stepCount:a,startTime:s,start:p,pause:m,stop:d,reset:h,step:g}),[t,r,a,s,p,m,d,h,g])},NB=(e,t)=>!e||!Array.isArray(e)?0:e.reduce((e,n)=>{if(`started`in n){let r=n.started,i=n.ended??t;return e+Math.max(0,i-r)}let r=n.start instanceof Date?n.start.getTime():n.start||0,i=n.stop?n.stop instanceof Date?n.stop.getTime():n.stop:t;return e+Math.max(0,i-r)},0);function PB(e,t){let n=t,r=()=>{let t=e?.getMemoryByTag(n)[0];if(t)return n===`round`?t.metrics[0]:t.metrics[0]?.value},[i,a]=(0,U.useState)(r);return(0,U.useEffect)(()=>{if(!e){a(void 0);return}a(r());let t=e.getMemoryByTag(n)[0];if(t)return t.subscribe(e=>{a(n===`round`?e[0]:e[0]?.value)})},[e,t]),i}function FB(e){return PB(e,`round`)}function IB(e){return PB(e,`display`)}function LB(e){let t=FB(e),n=IB(e);return(0,U.useMemo)(()=>{if(!t)return null;let e=n?.roundDisplay??(t.total===void 0?`Round ${t.current}`:`Round ${t.current} of ${t.total}`),r=t.total===void 0?void 0:Math.min(1,(t.current-1)/t.total);return{current:t.current,total:t.total,label:e,progress:r}},[t,n?.roundDisplay])}var RB=(0,U.createContext)(void 0),zB=({runtime:e,children:t})=>(0,W.jsx)(RB.Provider,{value:e,children:t});function BB(){let e=(0,U.useContext)(RB);if(!e)throw Error(`useScriptRuntime must be used within ScriptRuntimeProvider`);return e}function VB(e){let t=BB(),n=e===void 0?t:e,[r,i]=(0,U.useState)(()=>n?.getOutputStatements?.()??[]);return(0,U.useEffect)(()=>{if(!n){i([]);return}return i(n.getOutputStatements()),n.subscribeToOutput?.(()=>{i(n.getOutputStatements())})},[n]),(0,U.useMemo)(()=>{let e=new Map,t=new Map,n=[],i=[];for(let a of r){e.set(a.id,a);let r=t.get(a.sourceBlockKey)??[];switch(r.push(a),t.set(a.sourceBlockKey,r),a.outputType){case`segment`:n.push(a);break;case`metric`:i.push(a)}}let a=n.filter(e=>e.completionReason!==void 0);return{outputs:r,byId:e,byBlockKey:t,segments:n,completions:a,metrics:i}},[r])}function HB(e){let t=BB(),n=e===void 0?t:e,[r,i]=(0,U.useState)(()=>n?.getLiveAnalytics?.()??[]);return(0,U.useEffect)(()=>{if(!n){i([]);return}return i(n.getLiveAnalytics?.()??[]),n.subscribeToOutput?.(()=>{i(n.getLiveAnalytics?.()??[])})},[n]),r}function UB(){let e=BB(),[t,n]=(0,U.useState)({type:`initial`,blocks:e.stack.blocks,depth:e.stack.count,clockTime:e.clock.currentDate});return(0,U.useEffect)(()=>e.subscribeToStack(e=>{n(e)}),[e]),t}function WB(){return UB().blocks}function GB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`metric:next`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{for(let t of e){let e=t.getMemoryByTag(`metric:next`);if(e.length===0)continue;let n=la.empty(t.key.toString());for(let t of e)n.merge(t.metrics);if(n.length>0)return{metrics:n,block:t}}return null},[e,t])}function KB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`time`)[0];if(e){let r=e.subscribe(()=>{n(e=>e+1)});t.push(r)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{let t=[];for(let n of e){let e=n.getMemoryByTag(`time`)[0];if(!e)continue;let r=e.metrics[0]?.value;r&&t.push({block:n,timer:r,isPinned:r.role===`primary`})}return t},[e,t])}function qB(){let e=KB();return(0,U.useMemo)(()=>{if(e.length===0)return;let t=e[0];return t.block.blockType===`Rest`?t:[...e].reverse().find(e=>e.isPinned)||t},[e])}function JB(){let e=KB(),t=qB();return(0,U.useMemo)(()=>t?e.filter(e=>e.block!==t.block):[],[e,t])}function YB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`controls`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{let t=[],n=[];for(let r=0;r<e.length;r++){let i=e[r].getMemoryByTag(`controls`);if(i.length===0)continue;let a=i[0].metrics.map(e=>e.value).filter(Boolean),o=r===e.length-1;for(let e of a)e.isPinned?t.push(e):o&&n.push(e)}let r=new Set,i=[];for(let e of t)r.has(e.id)||(r.add(e.id),i.push(e));for(let e of n)r.has(e.id)||(r.add(e.id),i.push(e));return i},[e,t])}function XB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`metric:display`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{if(e.length===0)return;let t=[],n=[...e].reverse();return n.forEach((e,r)=>{if(e.blockType===`Root`&&!e.label)return;let i=e.getMemoryByTag(`metric:display`),a=i.map(e=>e.metrics);if(a.length===0&&!e.label)return;let o=r===n.length-1,s=i.length>1?i.map(e=>e.metrics):void 0;t.push({block:e,displayRows:a,label:e.label,depth:r,isLeaf:o,metricGroups:s})}),t.length>0?t:void 0},[e,t])}function ZB(e){let t=BB(),n=(0,U.useMemo)(()=>t.stack.blocks.find(t=>t.key.toString()===e),[t,e]),[r,i]=(0,U.useState)(()=>n?.getMemoryByTag(`time`)[0]?.metrics[0]?.value);(0,U.useEffect)(()=>t.stack.subscribe(()=>{let n=t.stack.blocks.find(t=>t.key.toString()===e);if(n){let e=n.getMemoryByTag(`time`)[0];i(e?.metrics[0]?.value)}else i(void 0)}),[t,e]),(0,U.useEffect)(()=>{if(!n){i(void 0);return}let e=n.getMemoryByTag(`time`)[0];if(i(e?.metrics[0]?.value),e)return e.subscribe(e=>{i(e[0]?.value)})},[n]);let a=(0,U.useMemo)(()=>r?.spans??[],[r]),o=a.length>0&&a[a.length-1].ended===void 0,[s,c]=(0,U.useState)(cu()),l=(0,U.useMemo)(()=>a.length===0?0:NB(a,s),[a,s]);return(0,U.useEffect)(()=>{if(!o)return;let e,t=()=>{c(cu()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[o]),{elapsed:l,isRunning:o,timeSpans:a}}var QB=(0,U.createContext)(void 0),$B=(0,U.createContext)(null),eV={getState:()=>az().getState(),setState:(e,t)=>{let n=az();typeof e==`function`?n.setState(e(n.getState()),t):n.setState(e,t)},subscribe:e=>az().subscribe(e)},tV=({factory:e,children:t})=>{let[n,r]=(0,U.useState)(null),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(!1),[c,l]=(0,U.useState)(null),u=(0,U.useRef)(e);u.current=e;let d=(0,U.useRef)(null),f=(0,U.useRef)(null),p=(0,U.useRef)(!1),m=(0,U.useCallback)(()=>{f.current&&=(f.current.dispose(),null),a(null),eV.getState().setSubscriptionManager(null);let e=d.current;if(d.current=null,e)try{u.current.disposeRuntime(e)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime:`,e)}r(null),l(null)},[]),h=(0,U.useCallback)((e,t)=>{if(!p.current){p.current=!0,s(!0),l(null);try{f.current&&=(f.current.dispose(),null);let n=d.current;if(d.current=null,n)try{u.current.disposeRuntime(n)}catch(e){console.error(`[RuntimeProvider] Error disposing existing runtime:`,e)}let i=u.current.createRuntime(e,t);if(d.current=i,r(i),i){let e=new em(i);e.add(new $p({id:`local`})),f.current=e,a(e),eV.getState().setSubscriptionManager(e)}else f.current=null,a(null),eV.getState().setSubscriptionManager(null)}catch(e){console.error(`[RuntimeProvider] Error creating runtime:`,e),l(e instanceof Error?e:Error(String(e))),d.current=null}finally{p.current=!1,s(!1)}}},[]);(0,U.useEffect)(()=>()=>{if(f.current&&f.current.dispose(),d.current)try{u.current.disposeRuntime(d.current)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime on unmount:`,e)}},[]);let g={runtime:n,isInitializing:o,error:c,initializeRuntime:h,disposeRuntime:m};return(0,W.jsx)(QB.Provider,{value:g,children:(0,W.jsx)($B.Provider,{value:i,children:t})})};function nV({factory:e,children:t}){return(0,W.jsx)(tV,{factory:e,children:t})}var rV=`bg-background ring-1 ring-zinc-950/5 shadow-sm lg:shadow-[-18px_0_36px_-28px_rgba(15,23,42,0.16),18px_0_36px_-28px_rgba(15,23,42,0.16)] dark:shadow-none dark:ring-white/10`,iV=`flex flex-col flex-1 min-w-0 xl:max-w-[984px] 2xl:max-w-none min-h-screen lg:rounded-[2.5rem]`;function aV({id:e,title:t,subtitle:n,titleAccessory:r,actions:i,queryBar:a,subheader:o,titleTestId:s,className:c}){return(0,W.jsxs)(`div`,{id:e,"data-page-sticky-boundary":`true`,className:G(`max-lg:hidden lg:sticky lg:top-0 z-30 bg-background/80 backdrop-blur-md transition-colors`,c),children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-3 px-4 sm:px-6 lg:px-8 py-2 sm:py-2.5`,children:[t&&(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5 sm:gap-3 min-w-0`,children:[(0,W.jsx)(`div`,{className:`h-5 w-1.5 shrink-0 rounded-full bg-primary`}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[(0,W.jsxs)(`div`,{className:`min-w-0`,children:[(0,W.jsx)(`h1`,{"data-testid":s,className:`text-base sm:text-lg font-black tracking-tight text-foreground leading-none truncate`,children:t}),n&&(0,W.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground truncate`,children:n})]}),r]})]}),a&&(0,W.jsx)(`div`,{className:`min-w-0 flex-1`,children:a}),i&&(0,W.jsx)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 shrink-0 ml-auto`,children:i})]}),o&&(0,W.jsx)(`div`,{className:`bg-background/40`,children:o})]})}function oV({ids:e,enabled:t=!0,rootMargin:n=`-10% 0px -40% 0px`,threshold:r=[0,.3,1],onChange:i,shouldAcceptChange:a,scrollDirection:o=`ratio`,dataAttribute:s,debounceMs:c=0}){let l=(0,U.useRef)(``),u=(0,U.useRef)(i),d=(0,U.useRef)(a),f=(0,U.useRef)(null),p=(0,U.useRef)(1);(0,U.useEffect)(()=>{u.current=i},[i]),(0,U.useEffect)(()=>{d.current=a},[a]);let m=e.filter(Boolean).join(`\0`),h=r.join(`,`),g=(0,U.useMemo)(()=>m?m.split(`\0`):[],[m]),_=(0,U.useMemo)(()=>h.split(`,`).map(Number),[h]),v=(0,U.useCallback)(()=>{f.current&&=(clearTimeout(f.current),null)},[]);(0,U.useEffect)(()=>{if(!t||g.length===0||typeof IntersectionObserver>`u`)return;let e=new Map,r=e=>s?e.getAttribute(s):e.id||null,i;if(o===`topmost-when-up`){let e=window.scrollY,t=()=>{let t=window.scrollY;t!==e&&(p.current=t>e?1:-1),e=t};window.addEventListener(`scroll`,t,{passive:!0}),i=()=>window.removeEventListener(`scroll`,t)}let a=new IntersectionObserver(t=>{if(t.forEach(t=>{let n=r(t.target);n&&(t.isIntersecting?e.set(n,t.intersectionRatio):e.delete(n))}),e.size===0)return;let n=``;if(o===`topmost-when-up`&&p.current===-1){let t=1/0;e.forEach((e,r)=>{let i=g.indexOf(r);i>=0&&i<t&&(t=i,n=r)})}else{let t=-1;e.forEach((e,r)=>{e>t&&(t=e,n=r)})}!n||n===l.current||d.current&&!d.current(n)||(l.current=n,c>0?(v(),f.current=setTimeout(()=>{u.current(n),f.current=null},c)):u.current(n))},{rootMargin:n,threshold:_});return g.forEach(e=>{let t=s?document.querySelector(`[${s}="${e}"]`):document.getElementById(e);t&&a.observe(t)}),()=>{a.disconnect(),v(),i?.()}},[t,g,_,n,o,s,c,v])}function sV({title:e,titleAccessory:t,actions:n,subheader:r,children:i,index:a=[],activeSectionId:o,hero:s,sections:c,className:l}){let u=!!(c&&c.length>0)&&!e,[,d]=ln(`s`,{defaultValue:o??a[0]?.id??``,shallow:!0,history:`replace`}),[f,p]=(0,U.useState)(c?.[0]?.id??``);if(oV({ids:a.map(e=>e.id),enabled:!u&&a.length>0,rootMargin:`-10% 0px -40% 0px`,threshold:[0,.3,1],onChange:e=>{d(e)},shouldAcceptChange:()=>!0}),oV({ids:c?.map(e=>e.id)??[],enabled:u,rootMargin:`-20% 0px -50% 0px`,threshold:[0,.25,.5,.75],onChange:p}),u){let e=c.map(e=>({id:e.id,label:e.label,action:{type:`scroll`,sectionId:e.id}}));return(0,W.jsxs)(`div`,{className:G(`flex flex-col min-h-screen bg-background`,l),children:[s,(0,W.jsx)(kB,{activations:e,activeSection:f,variant:`top-fixed`,deps:{navigate:()=>{},setQueryParam:()=>{},scrollToSection:e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-64;window.scrollTo({top:e,behavior:`smooth`})}}}}),(0,W.jsx)(`div`,{className:`flex-1`,children:c.map(e=>{let t=(0,W.jsx)(`div`,{id:e.id,"data-section-id":e.id,className:`py-12 lg:py-16 px-6 lg:px-10 border-b border-border/30`,children:e.content},e.id);return e.runtimeFactory?(0,W.jsx)(nV,{factory:e.runtimeFactory,children:t},e.id):t})})]})}return(0,W.jsx)(`div`,{className:G(`relative flex w-full min-h-screen justify-start items-start`,l),children:(0,W.jsxs)(`div`,{className:G(iV,rV),children:[(0,W.jsx)(aV,{title:e,titleAccessory:t,actions:n,subheader:r}),(0,W.jsx)(`div`,{className:`flex-1`,children:i})]})})}var cV=`[data-page-sticky-boundary="true"]`,lV=0;function uV(e,t=lV){if(typeof document>`u`)return e;let n=Array.from(document.querySelectorAll(cV)).reduce((e,t)=>{let n=t.getBoundingClientRect();return n.height<=0||n.bottom<=0?e:Math.max(e,n.bottom)},0);return n>0?n+t:e}function dV(e,t=lV){let[n,r]=(0,U.useState)(e);return(0,U.useEffect)(()=>{let n=0,i=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(()=>r(uV(e,t)))};return i(),window.addEventListener(`scroll`,i,{passive:!0}),window.addEventListener(`resize`,i),()=>{cancelAnimationFrame(n),window.removeEventListener(`scroll`,i),window.removeEventListener(`resize`,i)}},[e,t]),n}function fV({top:e,label:t,icon:n,badge:r,meta:i,testId:a,className:o}){return(0,W.jsxs)(`div`,{"data-testid":a,className:G(`sticky z-10 flex items-center gap-2 border-y border-border/60 bg-card/95 px-6 py-2 shadow-[0_1px_2px_rgba(0,0,0,0.03)] backdrop-blur`,o),style:{top:`${e}px`},children:[n,(0,W.jsx)(`span`,{className:`min-w-0 truncate text-xs font-bold text-foreground`,children:t}),r,i&&(0,W.jsx)(`span`,{className:`ml-auto shrink-0 pl-2 font-mono text-[10px] text-muted-foreground`,children:i})]})}var pV=(0,U.createContext)(null),mV=(0,U.createContext)(null);function hV({children:e}){let[t,n]=(0,U.useState)(null);return(0,W.jsx)(mV.Provider,{value:n,children:(0,W.jsx)(pV.Provider,{value:t,children:e})})}function gV({className:e}){let t=(0,U.useContext)(mV);return(0,W.jsx)(`div`,{ref:t,className:e,"data-testid":`mobile-query-slot`})}function _V(){return(0,U.useContext)(pV)}function vV({editor:e,title:t,subtitle:n,titleTestId:r,actions:i,timerOverlay:a,reviewOverlay:o,isTimerOpen:s=!1,isReviewOpen:c=!1,onCloseTimer:l,onCloseReview:u,className:d}){return(0,W.jsxs)(`div`,{className:G(`relative flex w-full min-h-screen justify-start items-start`,d),children:[(0,W.jsxs)(`div`,{className:G(iV,rV),children:[(0,W.jsx)(aV,{title:t,subtitle:n,titleTestId:r,actions:i}),(0,W.jsx)(`main`,{className:`flex-1 min-w-0 max-w-full`,children:e})]}),s&&a&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,W.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,W.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,W.jsx)(`button`,{onClick:l,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:a})]})}),c&&o&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,W.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,W.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,W.jsx)(`button`,{onClick:u,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:o})]})})]})}function yV(e){return e.map(e=>{let t=e.action,n=e.secondaryAction?.action,r={kind:`link`,id:e.id,label:e.label};return n&&n.type===`call`&&(r.onRun=n.handler,r.runIcon=e.secondaryRunIcon??`play`),t.type===`route`?{...r,to:t.to}:t.type===`scroll`?{...r,sectionId:t.sectionId}:t.type===`call`?{...r,onRun:t.handler}:r})}var bV=U.createContext(null);function xV(){let e=U.useContext(bV);if(!e)throw Error(`DropdownMenu components must be used inside a DropdownMenu`);return e}function SV(){let e=U.useContext(bV);return U.useCallback(()=>{e?.setIsOpen(!1)},[e])}var CV=({children:e,open:t,onOpenChange:n})=>{let r=U.useContext(bV),i=U.useId(),a=r?`${r.portalChain}/${i}`:i,[o,s]=U.useState(t??!1),c=U.useRef(null),[l,u]=U.useState(-1),d=U.useRef(new Map),[,f]=U.useReducer(e=>e+1,0);U.useEffect(()=>{t!==void 0&&s(t)},[t]);let p=U.useCallback(e=>{s(e),u(-1),n?.(e)},[n]),m=U.useCallback((e,t)=>{d.current.set(e,t),f()},[]),h=U.useCallback(e=>{d.current.delete(e),f()},[]),g=U.useCallback(e=>Array.from(d.current.keys()).indexOf(e),[]),_=d.current.size,v=U.useMemo(()=>({isOpen:o,setIsOpen:p,triggerRef:c,registerItem:m,unregisterItem:h,getItemIndex:g,activeIndex:l,setActiveIndex:u,itemCount:_,menuId:i,portalChain:a}),[o,p,m,h,g,l,_,i,a]);return(0,W.jsx)(bV.Provider,{value:v,children:(0,W.jsx)(`div`,{ref:c,className:`relative inline-block`,children:e})})},wV=U.forwardRef(({className:e,children:t,asChild:n,...r},i)=>{let{isOpen:a,setIsOpen:o}=xV(),s=e=>{e.stopPropagation(),o(!a)};return n&&U.isValidElement(t)?U.cloneElement(t,{...r,onClick:s}):(0,W.jsx)(`button`,{ref:i,className:e,onClick:s,...r,children:t})});wV.displayName=`DropdownMenuTrigger`;var TV=U.forwardRef(({className:e,children:t,align:n=`center`,side:r=`bottom`,...i},a)=>{let{isOpen:o,setIsOpen:s,triggerRef:c,setActiveIndex:l,itemCount:u,menuId:d,portalChain:f}=xV(),p=U.useRef(null),m=a||p,[h,g]=U.useState({top:0,bottom:0,left:0,width:0}),_=r===`bottom`,[v,y]=U.useState(!1);U.useEffect(()=>{if(!o||!c.current)return;let e=c.current.getBoundingClientRect();g({top:e.bottom+8,bottom:window.innerHeight-e.top+8,left:e.left,width:e.width}),y(!1)},[o,c]),U.useLayoutEffect(()=>{if(!o||!_||!m.current)return;let e=m.current.getBoundingClientRect();y(h.top+e.height>window.innerHeight)},[o,_,h.top]),U.useEffect(()=>{if(!o||u===0)return;let e=setTimeout(()=>{l(0)},0);return()=>clearTimeout(e)},[o,u,l]),U.useEffect(()=>{if(!o)return;let e=e=>{let t=e.target;if(m.current&&m.current.contains(t)||c.current&&c.current.contains(t))return;let n=t.closest?.(`[data-dropdown-chain]`)?.getAttribute(`data-dropdown-chain`);n&&n.split(`/`).includes(d)||s(!1)},t=setTimeout(()=>{document.addEventListener(`mousedown`,e)},0);return()=>{clearTimeout(t),document.removeEventListener(`mousedown`,e)}},[o,s,m,c,d]);let b=e=>{if(u!==0)switch(e.key){case`ArrowDown`:e.preventDefault(),l(e=>e<u-1?e+1:0);break;case`ArrowUp`:e.preventDefault(),l(e=>e>0?e-1:u-1);break;case`Home`:e.preventDefault(),l(0);break;case`End`:e.preventDefault(),l(u-1);break;case`Escape`:e.preventDefault(),s(!1),c.current?.querySelector(`button`)?.focus();break;case`Tab`:s(!1)}};if(!o)return null;let x={position:`fixed`,zIndex:9999};return r===`top`||v?x.bottom=h.bottom:x.top=h.top,n===`end`?x.right=window.innerWidth-h.left-h.width:n===`start`?x.left=h.left:(x.left=h.left+h.width/2,x.transform=`translateX(-50%)`),BC.createPortal((0,W.jsx)(`div`,{ref:m,role:`menu`,"data-dropdown-chain":f,className:G(`min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95`,e),style:x,onKeyDown:b,...i,children:t}),document.body)});TV.displayName=`DropdownMenuContent`;var EV=U.forwardRef(({className:e,disabled:t,inset:n,onClick:r,onKeyDown:i,...a},o)=>{let{setIsOpen:s,registerItem:c,unregisterItem:l,getItemIndex:u,activeIndex:d}=xV(),f=U.useId(),p=U.useRef(null),m=U.useCallback(e=>{p.current=e,typeof o==`function`?o(e):o&&(o.current=e)},[o]);U.useEffect(()=>(c(f,p),()=>l(f)),[f,c,l]);let h=u(f)===d;return U.useEffect(()=>{h&&p.current?.focus()},[h]),(0,W.jsx)(`div`,{ref:m,role:`menuitem`,tabIndex:t?-1:h?0:-1,"aria-disabled":t,"data-active":h?`true`:void 0,className:G(`relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors`,`focus:bg-accent focus:text-accent-foreground`,`data-[active]:bg-accent data-[active]:text-accent-foreground`,n&&`pl-8`,t&&`pointer-events-none opacity-50`,e),onClick:e=>{t||(r?.(e),s(!1))},onKeyDown:e=>{t||(i?.(e),(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r?.(e),s(!1)))},...a})});EV.displayName=`DropdownMenuItem`;var DV=U.forwardRef(({className:e,inset:t,...n},r)=>(0,W.jsx)(`div`,{ref:r,className:G(`px-2 py-1.5 text-sm font-semibold`,t&&`pl-8`,e),...n}));DV.displayName=`DropdownMenuLabel`;var OV=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`div`,{ref:n,className:G(`-mx-1 my-1 h-px bg-muted`,e),...t}));OV.displayName=`DropdownMenuSeparator`;function kV({className:e,children:t,...n}){return(0,W.jsx)(`div`,{className:G(`px-2 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,e),...n,children:t})}var AV=[{label:`Past 1 week`,value:`last 1w`},{label:`Past 2 weeks`,value:`last 2w`},{label:`Past 4 weeks`,value:`last 4w`},{label:`Past 8 weeks`,value:`last 8w`},{label:`Past 12 weeks`,value:`last 12w`},{label:`Past 1 year`,value:`last 52w`},{label:`All time`,value:`all`}],jV=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function MV(e,t){return new Date(e,t+1,0).getDate()}function NV(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function PV(e,t){let n=X(e);if(n.error)return e;if(!t||t===`all`)return qh({...n,window:void 0});let r=X(`:note ${t}`);return r.error||r.family!==`find`||!r.window?e:qh({...n,window:r.window})}function FV(e){let t=X(e);return t.error||t.family===`pipeline`?null:`window`in t?t.window??null:null}function IV({query:e,onQueryChange:t,highlightDates:n=new Set,className:r}){let i=(0,U.useMemo)(()=>FV(e),[e]),[a,o]=(0,U.useState)(null),[s,c]=(0,U.useState)(()=>new Date),l=s.getFullYear(),u=s.getMonth(),d=(0,U.useMemo)(()=>i?i.kind===`relative`?`last ${i.size}${i.unit}`:i.end?`from ${i.start} to ${i.end}`:`from ${i.start}`:`All time`,[i]),f=(0,U.useMemo)(()=>{if(!i)return null;if(i.kind===`range`)return{start:i.start,end:i.end??i.start};let e=new Date,t=new Date;return i.unit===`d`?t.setDate(e.getDate()-i.size):t.setDate(e.getDate()-i.size*7),{start:VP(t),end:VP(e)}},[i]),p=(0,U.useMemo)(()=>{let e=MV(l,u),t=NV(l,u),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[l,u]),m=n=>{if(!a)o(n),t(PV(e,`from ${n} to ${n}`));else{let[r,i]=a<=n?[a,n]:[n,a];o(null),t(PV(e,`from ${r} to ${i}`))}},h=e=>{e.stopPropagation(),c(new Date(l,u-1,1))},g=e=>{e.stopPropagation(),c(new Date(l,u+1,1))},_=s.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),v=VP(new Date);return(0,W.jsxs)(`div`,{className:G(`relative inline-flex items-center`,r),children:[(0,W.jsxs)(CV,{children:[(0,W.jsx)(wV,{asChild:!0,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`wql-window-picker-trigger`,className:`flex h-9 items-center gap-1.5 rounded-lg border border-border bg-background px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,W.jsx)(Tn,{className:`size-3.5 text-muted-foreground`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{className:`font-mono text-xs`,children:d}),(0,W.jsx)(Rn,{className:`size-3 text-muted-foreground`,"aria-hidden":`true`})]})}),(0,W.jsxs)(TV,{align:`end`,className:`w-72 p-3`,children:[(0,W.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-1 border-b border-border/60 pb-2`,children:AV.map(n=>{let r=n.value===`all`?!i:i?.kind===`relative`&&`last ${i.size}${i.unit}`===n.value;return(0,W.jsx)(`button`,{type:`button`,"data-testid":`wql-window-preset-${n.value}`,onClick:()=>{o(null),t(PV(e,n.value))},className:G(`rounded-md px-2 py-1 text-[11px] font-medium transition-colors`,r?`bg-primary text-primary-foreground`:`bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground`),children:n.label},n.value)})}),(0,W.jsxs)(`div`,{className:`mb-2 flex items-center justify-between`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:h,"data-testid":`wql-calendar-prev-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Previous month`,children:(0,W.jsx)(xn,{className:`size-4`})}),(0,W.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:_}),(0,W.jsx)(`button`,{type:`button`,onClick:g,"data-testid":`wql-calendar-next-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Next month`,children:(0,W.jsx)(_t,{className:`size-4`})})]}),(0,W.jsx)(`div`,{className:`mb-1 grid grid-cols-7 gap-1`,children:jV.map(e=>(0,W.jsx)(`div`,{className:`text-center text-[10px] font-medium text-muted-foreground`,children:e},e))}),(0,W.jsx)(`div`,{className:`grid grid-cols-7 gap-1`,"data-testid":`wql-calendar-grid`,children:p.map((e,t)=>{if(e===null)return(0,W.jsx)(`div`,{className:`size-8`},`empty-${t}`);let r=`${l}-${String(u+1).padStart(2,`0`)}-${String(e).padStart(2,`0`)}`,i=f&&r>=f.start&&r<=f.end,o=f&&r===f.start||a===r,s=f&&r===f.end,c=r===v,d=n.has(r);return(0,W.jsxs)(`button`,{type:`button`,"data-testid":`wql-calendar-day-${r}`,onClick:()=>m(r),className:G(`relative flex size-8 items-center justify-center rounded-md text-xs transition-colors`,o||s?`bg-primary font-bold text-primary-foreground`:i?`bg-primary/15 font-semibold text-primary`:c?`border border-primary font-semibold text-primary`:`text-foreground hover:bg-muted`),children:[(0,W.jsx)(`span`,{children:e}),d&&!o&&!s&&(0,W.jsx)(`span`,{className:`absolute bottom-0.5 size-1 rounded-full bg-primary`})]},r)})}),a&&(0,W.jsxs)(`div`,{className:`mt-2 text-center text-[10px] text-muted-foreground`,children:[`Select second date to complete range (starting from `,a,`)`]})]})]}),i&&(0,W.jsx)(`button`,{type:`button`,"data-testid":`wql-window-picker-clear`,onClick:()=>{o(null),t(PV(e,null))},title:`Clear time window`,"aria-label":`Clear time window`,className:`ml-1 grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,W.jsx)(ge,{className:`size-3.5`})})]})}function LV({onOpen:e}){let t=SV();return(0,W.jsxs)(K,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{t(),e()},"data-testid":`query-settings-trigger`,className:`w-full justify-start gap-2 rounded-lg text-xs`,children:[(0,W.jsx)(Hn,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{className:`truncate`,children:`Query settings`})]})}function RV(e){switch(e.kind){case`note`:return`note`;case`result`:return`result`;case`segment`:case`event`:return`segment`;case`effort`:return`effort`;default:return`note`}}var zV=[{id:`title`,label:`Title`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`tags`,label:`Tags`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.tags??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)},{id:`excerpt`,label:`Text Excerpt`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.preview?.join(` `)||e.detail||``,formatValue:e=>String(e??``)},{id:`sourceNotebook`,label:`Notebook`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.sourceNotebook,formatValue:e=>String(e??``)},{id:`date`,label:`Date`,level:`note`,defaultVisible:!0,align:`right`,getValue:e=>e.date,formatValue:e=>String(e??``)}],BV={note:zV,session:[{id:`title`,label:`Title`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`protocol`,label:`Protocol`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.dataType||e.subtitle||``,formatValue:e=>String(e??``)},{id:`movements`,label:`Movements`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.detail||``,formatValue:e=>String(e??``)},{id:`targetDuration`,label:`Target Duration`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:eB(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`sessionLoad`,label:`Session Load`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``}],result:[{id:`title`,label:`Title`,level:`result`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`elapsedTime`,label:`Elapsed Time`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:eB(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`totalTonnage`,label:`Total Tonnage`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`tis`,label:`TIS Score`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.tis,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`prBadges`,label:`PR Badges`,level:`result`,defaultVisible:!0,align:`center`,getValue:e=>e.detail&&/\bPR\b/.test(e.detail)?`PR`:``,formatValue:e=>String(e??``)}],segment:[{id:`splitDuration`,label:`Split Duration`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:eB(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`roundIndex`,label:`Round/Lap Index`,level:`segment`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`reps`,label:`Reps`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.reps,formatValue:e=>e==null?``:String(e)},{id:`load`,label:`Load`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`pacingTier`,label:`Pacing / HR Tier`,level:`segment`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier||e.execution?.effortSlug||``,formatValue:e=>String(e??``)}],effort:[{id:`label`,label:`Label`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.label||e.title,formatValue:e=>String(e??``)},{id:`canonicalSlug`,label:`Canonical Slug`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.slug||e.id,formatValue:e=>String(e??``)},{id:`discipline`,label:`Discipline`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.discipline??``,formatValue:e=>String(e??``)},{id:`met`,label:`MET Score`,level:`effort`,defaultVisible:!0,align:`right`,getValue:e=>e.effort?.met,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`intensityTier`,label:`Intensity Tier`,level:`effort`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier??``,formatValue:e=>String(e??``)},{id:`aliases`,label:`Aliases`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.aliases??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)}]};function VV(e){return BV[e]??zV}function HV(e){return VV(e).filter(e=>e.defaultVisible).map(e=>e.id)}var UV=[{id:`cards`,label:`Cards`,icon:v},{id:`rows`,label:`Rows`,icon:j},{id:`feed`,label:`Feed`,icon:on}];function WV({streamControls:e}){return(0,W.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":`l3-stream-controls`,children:[e.onOpenQuerySettings&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`This page`}),(0,W.jsx)(LV,{onOpen:e.onOpenQuerySettings})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Date window`}),(0,W.jsx)(IV,{query:e.query,onQueryChange:e.onQueryChange,className:`w-full justify-between`})]}),e.availableGroupDims.length>0&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Group by`}),(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-groupby-options`,children:e.availableGroupDims.map(t=>{let n=e.groupDims.some(e=>e.toLowerCase()===t.id.toLowerCase());return(0,W.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-groupby-${t.id}`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleGroupDim(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,W.jsx)(`span`,{children:t.label})]},t.id)})})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Layout`}),(0,W.jsx)(`div`,{className:`grid grid-cols-3 gap-1`,"data-testid":`l3-layout-options`,children:UV.map(t=>{let n=t.icon,r=e.settings.layout===t.id;return(0,W.jsxs)(`button`,{type:`button`,"aria-pressed":r,onClick:()=>e.onLayoutChange(t.id),"data-testid":`l3-layout-${t.id}`,className:`flex min-h-8 items-center justify-center gap-1 rounded-md border px-1.5 py-1 text-[11px] font-medium transition-colors ${r?`border-border/80 bg-card text-foreground shadow-sm`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[(0,W.jsx)(n,{"aria-hidden":!0,className:`size-3`}),t.label]},t.id)})})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Fields`}),(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-field-options`,children:VV(e.level).map(t=>{let n=e.settings.visibleFields.includes(t.id);return(0,W.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-field-${t.id}`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleField(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,W.jsx)(`span`,{children:t.label})]},t.id)})})]})]})}function GV({spec:e,pageAction:t}){let{l3Items:n,streamControls:r}=mN(),i=gB(e),a=(0,U.useMemo)(()=>yV(n),[n]),o=_B();return i.length===0&&a.length===0&&!r&&!t?null:(0,W.jsxs)(`div`,{className:`flex flex-col px-3 py-4 gap-4`,children:[r&&(0,W.jsx)(`div`,{className:`pb-3 border-b border-border/50`,children:(0,W.jsx)(WV,{streamControls:r})}),i.length>0&&(0,W.jsx)(yB,{entries:i,activeId:o}),a.length>0&&(0,W.jsxs)(`div`,{className:`flex flex-col`,children:[(0,W.jsx)(`div`,{className:`px-2 pb-1 pt-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`On this page`}),(0,W.jsx)(yB,{entries:a,activeId:o})]}),t&&(0,W.jsx)(`div`,{className:`pt-2 border-t border-border/50`,children:t})]})}var KV=1023;function qV(e){return e===`/`?`canvas:home`:`canvas:${e.replace(/^\//,``)}`}function JV(e,t){if(e===`query:new`)return``;let n=e=>{let n=`/${e}`;for(let r of Object.keys(t))if(r===e||r.endsWith(n))return r;return null},r=e=>{let r=n(e);if(r===null)return null;let i=t[r],{meta:a,body:o}=fv(i),s=new Set([`search`,`template`,`route`,`type`,`title`,`description`,`subtitle`,`section`,`order`]);return Object.keys(a).some(e=>!s.has(e.trim().toLowerCase()))?i:o};if(e.startsWith(`markdown/`)){let t=r(e);if(t!==null)return t}let i=e;if(e.startsWith(`wods/examples/`))i=`markdown/canvas/`+e.replace(/^wods\/examples\//,``);else if(e.startsWith(`wods/`))i=`markdown/canvas/`+e.replace(/^wods\//,``);else if(e.startsWith(`canvas/`))i=`markdown/canvas/`+e.replace(/^canvas\//,``);else{let t=r(`markdown/canvas/`+e);if(t!==null)return t;i=`markdown/`+e}return r(i)??`# Source not found\n\nPath: \`${e}\`\nResolved: \`${i}\``}function YV(e){return(e.examples??[]).length>0||e.commands.some(e=>e.pipeline.length>0)}function XV(e){let t=new Map,n=null;for(let r of e)YV(r)&&(n=r),t.set(r.id,n);return t}function ZV(){let[e,t]=(0,U.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: ${KV}px)`).matches);return(0,U.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: ${KV}px)`),n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var QV=`wodwiki:fabAlignment`,$V=[{id:`left`,label:`Bottom left`,description:`Left-handed — search and page actions float near your left thumb`},{id:`right`,label:`Bottom right`,description:`Right-handed — search and page actions float near your right thumb`}];function eH(){try{return tH(localStorage.getItem(QV))}catch{return}}function tH(e){return e===`right`||e===`left`?e:void 0}var nH=typeof window>`u`?void 0:eH();typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===QV&&(nH=tH(e.newValue))});function rH(e){nH=e;try{e===`right`?localStorage.removeItem(QV):localStorage.setItem(QV,e)}catch{}window.dispatchEvent(new StorageEvent(`storage`,{key:QV,newValue:e}))}function iH(){let[e,t]=(0,U.useState)(()=>nH??`right`);return(0,U.useEffect)(()=>{let e=e=>{e.key===QV&&t(tH(e.newValue)??`right`)};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),[e,rH]}function aH({onOpen:e}){return(0,W.jsxs)(`button`,{type:`button`,onClick:e,"aria-label":`Search`,title:`Search`,"data-testid":`search-fab`,className:G(`size-14 rounded-full flex items-center justify-center`,`bg-primary text-primary-foreground shadow-lg`,`hover:bg-primary/90 active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:[(0,W.jsx)(o,{className:`size-6`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Search`})]})}var oH=(0,U.createContext)(null),sH=(0,U.createContext)(!1),cH=(0,U.createContext)(null);function lH(){return(0,U.useContext)(oH)!==null}function uH({primary:e,navbar:t,children:n,label:r,fallback:i=!1}){let a=(0,U.useContext)(oH),o=(0,U.useContext)(sH),s=ZV(),c=(0,U.useId)(),l=a!==null&&!o&&s&&!i,u=a!==null&&i,d=(0,W.jsx)(sH.Provider,{value:!0,children:n});return(0,U.useEffect)(()=>{if(!(!l&&!u))return a.register({id:c,primary:e,navbar:t,children:d,label:r??`Page options`,fallback:i}),()=>a.unregister(c)},[l,u,a,c,e,d,r,i]),i||a&&s&&!o?null:(0,W.jsx)(sH.Provider,{value:!0,children:(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t,e,n]})})}function dH({onSearch:e,children:t}){let[n,r]=(0,U.useState)([]),i=(0,U.useCallback)(e=>r(t=>[...t.filter(t=>t.id!==e.id),e]),[]),a=(0,U.useCallback)(e=>r(t=>t.filter(t=>t.id!==e)),[]),o=(0,U.useMemo)(()=>({register:i,unregister:a}),[i,a]),s=(0,U.useMemo)(()=>{for(let e=n.length-1;e>=0;--e)if(!n[e].fallback)return n[e].navbar??null;return null},[n]);return(0,W.jsx)(oH.Provider,{value:o,children:(0,W.jsxs)(cH.Provider,{value:s,children:[t,(0,W.jsx)(pH,{registrations:n,onSearch:e})]})})}function fH(){let e=(0,U.useContext)(cH);return e?(0,W.jsx)(W.Fragment,{children:e}):null}function pH({registrations:e,onSearch:t}){let n=ZV(),[r]=iH(),i=HC(),[a,o]=(0,U.useState)(!1),s=(0,U.useRef)(null),c=(0,U.useRef)(null),l=(0,U.useRef)(null),u=(0,U.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(!e[t].fallback)return e[t]},[e]),d=(0,U.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(e[t].fallback)return e[t]},[e]);(0,U.useLayoutEffect)(()=>{a&&s.current?.focus()},[a]);let[f,p]=(0,U.useState)({active:0,global:0});(0,U.useLayoutEffect)(()=>{let e=c.current?.childElementCount??0,t=l.current?.childElementCount??0;p(n=>n.active===e&&n.global===t?n:{active:e,global:t})},[u,d]);let m=f.active>0||f.global>0;return!n||!t&&!u&&!d?null:(0,W.jsxs)(`div`,{"data-testid":`actions-dock`,className:G(`lg:hidden relative z-40 mt-4 flex flex-col items-center gap-2`,`transition-[transform,visibility] duration-200 ease-out`,r===`left`?`self-start items-start`:`self-end items-end`),children:[(0,W.jsxs)(`div`,{className:`relative z-40 flex flex-col items-center gap-2`,children:[u?.primary&&(0,W.jsx)(`div`,{className:`[&_button]:min-h-11 [&_button]:min-w-11`,children:u.primary}),t&&(0,W.jsx)(aH,{onOpen:()=>{o(!1),t()}})]}),a&&m&&(0,W.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-hidden":`true`,className:`fixed inset-0 z-30 cursor-default`,onClick:()=>o(!1)}),(0,W.jsxs)(`div`,{ref:s,role:`dialog`,"aria-label":u?.label??d?.label??`Page options`,tabIndex:-1,hidden:!a||!m,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),o(!1))},className:G(`relative z-40 flex w-60 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto rounded-2xl bg-card p-3 shadow-xl ring-1 ring-foreground/5 outline-none`,`[&_button]:min-h-11 [&_button]:min-w-11`),style:{maxHeight:`calc(${i.height===null?`100dvh`:`${i.height}px`} - 6rem - env(safe-area-inset-bottom))`},children:[(0,W.jsx)(`div`,{ref:c,className:`contents`,children:u?.children}),f.active>0&&f.global>0&&(0,W.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,W.jsx)(`div`,{ref:l,className:`contents`,children:d?.children})]}),m&&(0,W.jsxs)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-label":u?.label??d?.label??`Page options`,title:u?.label??d?.label??`Page options`,"aria-expanded":a,"data-testid":`actions-overflow`,className:G(`relative z-40 flex size-12 items-center justify-center rounded-full`,`bg-card text-foreground shadow-lg ring-1 ring-foreground/10`,`hover:bg-muted active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:[a?(0,W.jsx)(er,{className:`size-6`}):(0,W.jsx)(ue,{className:`size-6`}),(0,W.jsx)(`span`,{className:`sr-only`,children:u?.label??d?.label??`Page options`})]})]})}function mH(){return(0,W.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,W.jsx)(`path`,{d:`M2 6.75C2 6.33579 2.33579 6 2.75 6H17.25C17.6642 6 18 6.33579 18 6.75C18 7.16421 17.6642 7.5 17.25 7.5H2.75C2.33579 7.5 2 7.16421 2 6.75ZM2 13.25C2 12.8358 2.33579 12.5 2.75 12.5H17.25C17.6642 12.5 18 12.8358 18 13.25C18 13.6642 17.6642 14 17.25 14H2.75C2.33579 14 2 13.6642 2 13.25Z`})})}function hH(){return(0,W.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,W.jsx)(`path`,{d:`M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z`})})}function gH(){let{tree:e,navState:t,contextNav:n}=mN(),r=ht(),i=eF();return!e.find(e=>e.id===t.activeL1Id)?.applyFooter||n?.pathname===r.pathname?null:(0,W.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,W.jsx)(`button`,{type:`button`,onClick:i,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})}function _H({open:e,close:t,onSearch:n,onCreate:r,children:i}){return(0,W.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,W.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,W.jsx)(A,{transition:!0,className:`fixed inset-y-0 left-0 w-full transition duration-300 ease-out data-closed:-translate-x-full`,children:(0,W.jsx)($P,{close:t,children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 bg-card`,children:[(0,W.jsx)(`div`,{className:`flex h-full w-14 shrink-0 flex-col items-center border-r border-zinc-950/5 bg-background/72 py-3 dark:border-white/5 [&_a]:size-11 [&_button]:size-11`,children:(0,W.jsx)(OB,{onSearch:()=>{t(),n?.()},onCreate:r?()=>{t(),r()}:void 0})}),(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,W.jsx)(`div`,{className:`flex items-center px-4 pt-3`,children:(0,W.jsxs)(it,{as:xR,"aria-label":`Close navigation`,title:`Close navigation`,children:[(0,W.jsx)(hH,{}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Close navigation`})]})}),(0,W.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i}),(0,W.jsx)(gH,{})]})]})})})]})}function vH({open:e,close:t,children:n}){return(0,W.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,W.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,W.jsx)(A,{transition:!0,className:`fixed inset-y-0 right-0 w-full transition duration-300 ease-out data-closed:translate-x-full`,children:(0,W.jsx)($P,{close:t,children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col bg-card`,children:[(0,W.jsx)(`div`,{className:`flex items-center justify-end px-4 pt-3`,children:(0,W.jsxs)(it,{as:xR,"aria-label":`Close page options`,title:`Close page options`,children:[(0,W.jsx)(hH,{}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Close page options`})]})}),(0,W.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-y-auto`,children:n}),(0,W.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,W.jsx)(`button`,{type:`button`,onClick:t,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})]})})})]})}function yH({navbar:e,sidebar:t,onSearch:n,onCreate:r,secondary:i,pageAction:a,hideDesktopSidebar:o,children:s}){let[c,l]=(0,U.useState)(!1),[u,d]=(0,U.useState)(!1),f=(0,U.useRef)(null),[p,m]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>m(t=>{let n=e.childElementCount>0;return t===n?t:n}),n=new MutationObserver(t);return n.observe(e,{childList:!0,subtree:!0}),t(),()=>n.disconnect()},[]);let{streamControls:h}=mN(),g=(0,U.useMemo)(()=>{let e=X(h?.query??``);return!e.error&&eh(e)&&e.filters.length>0},[h?.query]);return(0,W.jsx)(hV,{children:(0,W.jsx)(dH,{onSearch:n,children:(0,W.jsx)(`div`,{className:`relative isolate flex min-h-svh w-full bg-background max-lg:flex-col lg:flex-row`,children:(0,W.jsxs)(`div`,{className:`flex flex-1 w-full max-lg:flex-col lg:flex-row`,children:[(0,W.jsxs)(`nav`,{"aria-label":`Main`,className:`hidden lg:flex`,children:[(0,W.jsx)(`div`,{className:`w-14 shrink-0 sticky top-0 h-svh flex flex-col items-center border-r border-zinc-950/5 dark:border-white/5 bg-background/72 backdrop-blur-sm z-40 py-3`,children:(0,W.jsx)(OB,{onSearch:n??(()=>{}),onCreate:r})}),(0,W.jsx)(`div`,{className:G(`w-60 shrink-0 sticky top-0 self-start h-svh min-h-0 overflow-hidden border-r border-zinc-950/5 dark:border-white/5 bg-background/72 backdrop-blur-sm flex flex-col`,o&&`lg:hidden`),children:t})]}),(0,W.jsx)(_H,{open:c,close:()=>l(!1),onSearch:n,onCreate:r,children:t}),(0,W.jsxs)(`div`,{className:`flex flex-1 flex-col min-w-0 xl:max-w-[984px] 2xl:max-w-none`,children:[(0,W.jsxs)(`header`,{"data-page-sticky-boundary":`true`,className:`lg:hidden sticky top-0 z-20 flex items-center px-2 sm:px-4 bg-card`,children:[(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsxs)(xR,{onClick:()=>l(!0),"aria-label":`Open navigation`,title:`Open navigation`,children:[(0,W.jsx)(mH,{}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Open navigation`})]})}),(0,W.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),r&&(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsxs)(xR,{onClick:r,"aria-label":`New journal note`,title:`New journal note`,children:[(0,W.jsx)(dn,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`New journal note`})]})}),p&&(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsxs)(xR,{onClick:()=>d(!0),"aria-label":`Open page options`,title:`Open page options`,children:[(0,W.jsxs)(`span`,{className:`relative inline-flex`,children:[(0,W.jsx)(Hn,{className:`size-5`}),g&&(0,W.jsx)(`span`,{"data-testid":`drawer-filters-active`,className:`absolute -top-1 -right-1 size-2 rounded-full bg-amber-500`,"aria-hidden":`true`})]}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Open page options`})]})})]}),(0,W.jsxs)(`main`,{className:`flex flex-1 flex-col lg:min-w-0`,children:[(0,W.jsx)(`div`,{className:`grow w-full max-lg:pb-48 lg:overflow-visible`,children:s}),(0,W.jsx)(bH,{})]})]}),(0,W.jsx)(`aside`,{className:`hidden 2xl:flex w-60 shrink-0 sticky top-0 h-svh flex-col overflow-y-auto bg-background/72 backdrop-blur-sm`,children:(0,W.jsx)(`div`,{ref:f,className:`contents`,children:(0,W.jsx)(GV,{spec:i,pageAction:a})})}),(0,W.jsx)(vH,{open:u,close:()=>d(!1),children:(0,W.jsx)(GV,{spec:i,pageAction:a})})]})})})})}function bH(){let e=(0,U.useRef)(null),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=e.current;if(!t)return;let r=new ResizeObserver(e=>{let t=Math.round(e[0]?.contentRect.height??0);n(e=>e===t?e:t)});r.observe(t,{box:`content-box`});let i=Math.round(t.getBoundingClientRect().height);return n(e=>e===i?e:i),()=>r.disconnect()},[]),(0,U.useEffect)(()=>(document.documentElement.style.setProperty(`--thumb-dock-lift`,`${t}px`),()=>document.documentElement.style.setProperty(`--thumb-dock-lift`,`0px`)),[t]),(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:G(`lg:hidden fixed inset-x-0 bottom-0 z-30`,t>0&&`bg-card border-t border-border/50 px-3 py-2`),children:(0,W.jsx)(`div`,{ref:e,className:`w-full min-w-0`,children:(0,W.jsx)(gV,{className:`flex w-full min-w-0`})})}),(0,W.jsx)(`div`,{className:`lg:hidden`,"aria-hidden":`true`,style:{height:t}})]})}function xH(e){let t=e.indexOf(`markdown`);return t!==-1&&e.length>t+2?e[t+2]:`General`}function SH(e){return String(ib(Qy(e).meta,`search`)??``).toLowerCase()===`hidden`}function CH(e){let t=ib(Qy(e).meta,`date`);if(typeof t!=`string`||!/^\d{4}-\d{2}-\d{2}$/.test(t))return;let n=new Date(`${t}T12:00:00Z`);return Number.isFinite(n.getTime())&&n.toISOString().slice(0,10)===t?n.getTime():void 0}function wH(e){return Object.entries(e).map(([e,t])=>{let n=e.split(`/`),r=n[n.length-1].replace(`.md`,``),i=t,a=ib(Qy(i).meta,`title`);return{id:e,name:r,displayName:typeof a==`string`&&a.trim()?a.trim():ZO(r),category:xH(n),content:i,date:CH(i),searchHidden:SH(i)}})}function TH(){let e=bk();return(0,U.useMemo)(()=>e?wH(e):[],[e])}var EH={};function DH(e){if(!(`payload`in e))return;let t=e.payload;if(!t||typeof t!=`object`)return;let n=t;return n.targetDate??n.updatedAt}function OH(e,t){let{canvasPage:n,workoutItems:r,recentResults:i,selectWorkout:a}=t;if(e===`/`)return[];if(n){let t=/^\/notebook\//.test(e),i=t?e.split(`/`).pop()??null:null,o=[],s=e.startsWith(`/page/guide-`);return n.sections.filter(e=>e.level>1).forEach(e=>{if(o.push({id:e.id,label:e.heading,type:`heading`}),!s){let t=UL(e).split(`
102
+ `).map(e=>e.trim()).filter(Boolean).slice(0,Yz).map(e=>e.length>Xz?`${e.slice(0,119)}…`:e)}function Qz(e){let t=Kz(Jz(e));return{...t,blockContentId:e.blockContentId??t.blockContentId,block:{blockId:e.blockId,dataType:e.dataType,preview:Zz(e.rawContent)}}}function $z(e){return e?e.split(`-`).map(e=>{let t=e.toLowerCase();return t===`c2b`?`C2B`:t===`t2b`?`T2B`:t===`ghd`?`GHD`:t===`hspu`?`HSPU`:e.charAt(0).toUpperCase()+e.slice(1)}).join(` `):``}function eB(e){if(!Number.isFinite(e)||e<=0)return`00:00`;let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;if(n>=60){let e=Math.floor(n/60),t=n%60;return`${e}:${String(t).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function tB(e){if(!e)return`Workout Session`;let t=Nz(e);return t.kind===`journal`?t.id?`Journal: ${t.id}`:`Journal Entry`:t.kind===`workout`?$z(t.id)||t.id:t.id?$z(t.id):e}function nB(e){let t=[e.baseAttributes?.discipline,e.baseAttributes?.met==null?void 0:`MET ${e.baseAttributes.met.toFixed(1)}`,e.baseAttributes?.intensityTier].filter(Boolean);return{id:e.slug,kind:`effort`,sourceNotebook:e.registrySource??`effort`,sourceNote:e.slug,title:e.label,date:null,subtitle:t.join(` • `),detail:e.aliases&&e.aliases.length>0?`Aliases: ${e.aliases.join(`, `)}`:void 0,effort:{slug:e.slug,label:e.label,discipline:e.baseAttributes?.discipline,met:e.baseAttributes?.met,intensityTier:e.baseAttributes?.intensityTier,aliases:e.aliases,registrySource:e.registrySource}}}function rB(e){let t=(e.type??``).toLowerCase(),n=(`name`in e&&typeof e.name==`string`?e.name:``).toLowerCase(),r=typeof e.value==`number`?e.value:Number(e.value);return Number.isFinite(r)?t===`rep`||n===`reps`||n===`rep`?{kind:`rep`,val:r}:t===`weight`||t===`load`||n===`load`||n===`weight`||n===`volume`?{kind:`load`,val:r}:t===`distance`||n===`distance`?{kind:`distance`,val:r}:t===`tis`||n===`tis`?{kind:`tis`,val:r}:t===`duration`||n===`duration`?{kind:`duration`,val:r}:null:null}function iB(e){let t=1/0,n=-1/0,r=0,i=0,a=0,o=0,s=new Set;for(let c of e.events)if(c.outputType===`segment`&&o++,c.effortSlug&&s.add(c.effortSlug),c.timeSpan?.started!=null&&(c.timeSpan.started<t&&(t=c.timeSpan.started),c.timeSpan.ended!=null&&c.timeSpan.ended>n&&(n=c.timeSpan.ended)),Array.isArray(c.metrics))for(let e of c.metrics){let t=rB(e);t&&(t.kind===`rep`?r+=t.val:t.kind===`load`?i+=t.val:t.kind===`tis`&&t.val>a&&(a=t.val))}return{elapsedMs:Number.isFinite(t)&&Number.isFinite(n)&&n>t?n-t:void 0,reps:r>0?r:void 0,loadLbs:i>0?i:void 0,tis:a>0?a:void 0,segmentCount:o>0?o:void 0,effortSlugs:Array.from(s)}}function aB(e,t){let n=iB(e),r=[];n.elapsedMs!=null&&r.push(eB(n.elapsedMs)),n.tis!=null&&r.push(`TIS ${n.tis.toFixed(1)}`),n.loadLbs!=null&&r.push(`Volume: ${n.loadLbs.toLocaleString()} lbs`),n.reps!=null&&r.push(`${n.reps} reps`),n.segmentCount!=null&&r.push(`${n.segmentCount} splits`);let i=n.effortSlugs.map($z),a=VP(new Date(e.timestamp)),o=e.events.find(e=>!!e.blockContentId)?.blockContentId;return{id:e.resultId,kind:`result`,sourceNotebook:`results`,sourceNote:e.resultId,title:t?.noteTitle??tB(e.noteId),date:a,blockContentId:o,subtitle:r.join(` • `),detail:i.length>0?i.join(`, `):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:`all`,elapsedMs:n.elapsedMs,reps:n.reps,loadLbs:n.loadLbs,tis:n.tis,segmentCount:n.segmentCount,events:e.events}}}function oB(e,t){let n;e.timeSpan?.started!=null&&e.timeSpan?.ended!=null&&(n=e.timeSpan.ended-e.timeSpan.started);let r,i,a,o;if(Array.isArray(e.metrics))for(let t of e.metrics){let e=rB(t);e&&(e.kind===`rep`?r=e.val:e.kind===`load`?i=e.val:e.kind===`distance`?a=e.val:e.kind===`tis`?o=e.val:e.kind===`duration`&&!n&&(n=e.val))}let s=e.outputType===`segment`?`segment`:`event`,c=t?.index??0,l=e.effortSlug?$z(e.effortSlug):e.outputType===`segment`?`Round ${c+1}`:`${e.outputType.charAt(0).toUpperCase()+e.outputType.slice(1)} ${c+1}`,u=[];n!=null&&u.push(eB(n)),r!=null&&i!=null?u.push(`${r} reps @ ${i} lbs`):r==null?i!=null&&u.push(`${i} lbs`):u.push(`${r} reps`),a!=null&&u.push(`${a}m`),o!=null&&u.push(`TIS ${o.toFixed(1)}`);let d=VP(new Date(e.timestamp));return{id:e.id,kind:s,sourceNotebook:`results`,sourceNote:e.id,title:l,date:d,blockContentId:e.blockContentId,subtitle:u.join(` • `),detail:e.effortSlug?$z(e.effortSlug):void 0,execution:{resultId:e.resultId,noteId:e.noteId,timestamp:e.timestamp,outputType:e.outputType,effortSlug:e.effortSlug,elapsedMs:n,reps:r,loadLbs:i,distanceMeters:a,tis:o,metrics:e.metrics}}}function sB(e,t){if(!e||e.error||!e.runs)return[];let n=e.parsed?.filters?.find(e=>e.key===`plane`&&!e.negate),r=e.parsed?.outputType??n?.values[0]?.value;if(r===`segment`){let t=[];for(let n of e.runs){let e=0;for(let r of n.events)r.outputType===`segment`&&t.push(oB(r,{index:e++}))}return t}if(r&&r!==`all`){let t=[];for(let n of e.runs){let e=0;for(let i of n.events)i.outputType===r&&t.push(oB(i,{index:e++}))}return t}return e.runs.map(e=>aB(e,{noteTitle:t?.noteTitles?.get(e.noteId)}))}function cB(e,t,n){let r=typeof e.__id==`string`&&e.__id?e.__id:void 0,i=typeof e.__resultId==`string`&&e.__resultId?e.__resultId:void 0,a=typeof e.effort==`string`&&e.effort?e.effort:void 0,o=[];for(let[t,n]of Object.entries(e))t.startsWith(`__`)||t===`date`||t===`effort`||(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&o.push(`${t}: ${n}`);return{id:r??i??`${t}:${n}`,kind:t,sourceNotebook:`results`,sourceNote:i??r??`${t}:${n}`,title:a?$z(a):`${t===`segment`?`Segment`:`Event`} ${n+1}`,date:typeof e.date==`string`?e.date:null,subtitle:o.length>0?o.join(` • `):void 0}}function lB(e){let t=e.parsed.family===`aggregate`?e.parsed.metric:`metric`;return e.series.map(e=>{let n=e.points.map(t=>`${t.value}${e.unit?` ${e.unit}`:``}`).join(` • `);return{id:`aggregate:${t}:${e.key}`,kind:`result`,sourceNotebook:`results`,sourceNote:e.label,title:`${t}: ${n}`,subtitle:e.label,date:null}})}function uB(e,t,n){e&&e({selected:Math.max(t?.selected??0,n.length),matched:n.length})}function dB(e){return typeof e==`object`&&!!e&&`runFind`in e}var fB=new class e{customService;noteTitleResolver;noteTagsResolver;noteBlockInfo;constructor(e){dB(e)?this.customService=e:(this.customService=e?.service,this.noteTitleResolver=e?.noteTitleResolver,this.noteBlockInfo=e?.noteBlockInfo??!1,this.noteTagsResolver=e?.noteTagsResolver)}get service(){return this.customService??Mz}withNoteBlockInfo(){let t=new e({service:this.service,noteTitleResolver:this.noteTitleResolver,noteTagsResolver:this.noteTagsResolver,noteBlockInfo:!0});return Object.prototype.hasOwnProperty.call(this,`query`)&&(t.query=this.query),t}async hydrateEntries(e,t){let n=new Set;for(let r of e)r.sourceNotebook===`journal`&&n.add(r.id),t&&(!r.title||!r.tags||r.tags.length===0)&&n.add(r.id);if(n.size===0)return;let r=await Z.getDetailBatches([...n]);for(let t of e){if(t.sourceNotebook!==`journal`)continue;let e=r.get(t.id),n=ba(e?.links??[],e?.pages??[]);t.placements=n;let i=xa(n);t.pageId??=i.pageId,i.pageSlug&&(t.pageSlug=i.pageSlug)}if(t)for(let t of e){let e=r.get(t.id);!t.title&&e?.note.title&&(t.title=e.note.title),e&&e.tags.length>0&&((!t.tags||t.tags.length===0)&&(t.tags=e.tags.map(e=>e.label)),t.typedTags=e.tags.map(e=>({label:e.label,type:e.type})))}}async query(e,t){let n=typeof e==`string`?X(e):e;if(!n||n.error)return[];if(eh(n)){if(n.target===`effort`){let e=this.service.runFindEffort?await this.service.runFindEffort(n):await this.service.runFind(n),r=new Map(e.notes.map(e=>[e.id,e])),i=(e.efforts??[]).map(e=>e.ownerNoteId&&r.has(e.ownerNoteId)?Kz(r.get(e.ownerNoteId)):nB(e));return uB(t,e.stages,i),i}if(n.target===`block`){let e=await this.service.runFind(n),r=e.blocks.map(Qz);return await this.hydrateEntries(r,!0),uB(t,e.stages,r),r}if(n.target===`session`){let e=await this.service.runFind(n);t?.(e.stages);let r;if(this.noteTitleResolver&&e.runs){r=new Map;for(let t of e.runs)if(!r.has(t.noteId)){let e=await this.noteTitleResolver(t.noteId);e&&r.set(t.noteId,e)}}let i=sB(e,{noteTitles:r});return uB(t,e.stages,i),i}if(n.target===`segment`||n.target===`event`){let e=n.target,r=await this.service.runFind(n),i=(r.table?.rows??[]).map((t,n)=>cB(t,e,n));return uB(t,r.stages,i),i}let e=await this.service.runFind(n),r=e.notes.map(Kz);if(this.noteTagsResolver?(await this.hydrateEntries(r,!1),await Promise.all(r.map(async e=>{if(!e.tags||e.tags.length===0){let t=await this.noteTagsResolver(e.id);t&&t.length>0&&(e.tags=t)}}))):await this.hydrateEntries(r,!0),uB(t,e.stages,r),this.noteBlockInfo)for(let t=0;t<r.length;t++){let n=r[t],i=e.notes[t];n.excerpt=Zz(i.rawContent);try{Fa(i.rawContent,i.blocks,i.sourceRevision)}catch{continue}let a=Object.values(i.blocks).sort((e,t)=>e.from-t.from).find(e=>e.kind===`wod`),o=a&&Ma(i.rawContent).find(e=>e.from===a.from&&e.scriptBlock);if(a&&o?.scriptBlock){let e=o.scriptBlock.content,t=_a(e);n.wodBlock={blockId:a.id,blockVersion:a.version,blockContentId:t,content:e},n.blockContentId=t}}return r}if(n.family===`aggregate`){if(!this.service.runQuery)return[];let e=await this.service.runQuery(n.raw),r=lB(e);return t?.({selected:e.stages?.selected??r.length,matched:r.length}),r}return[]}};async function pB(e,t=fB,n){return t.query(e,n)}function mB(e){return e?e.map(e=>e.kind===`wql`?`${e.id}|${e.query}|${e.limit??``}`:`s:${e.id}`).join(`;`):``}async function hB(e){try{let t=(await pB(e.query)).filter(t=>!e.filterEntry||e.filterEntry(t)).slice(0,e.limit??6).map(t=>({kind:`link`,id:`${e.id}:${t.id}`,label:e.labelFromEntry?e.labelFromEntry(t):t.title,to:e.toEntry?e.toEntry(t):void 0,muted:!0}));return{kind:`section`,id:e.id,label:e.label,entries:t}}catch{return{kind:`section`,id:e.id,label:e.label,entries:[]}}}function gB(e){let t=mB(e),n=(0,U.useRef)(e);n.current=e;let[r,i]=(0,U.useState)(()=>e&&!e.some(e=>e.kind===`wql`)?e:[]);return(0,U.useEffect)(()=>{let e=n.current;if(!e){i([]);return}if(!e.some(e=>e.kind===`wql`)){i(e);return}let t=!1;return Promise.all(e.map(e=>e.kind===`wql`?hB(e):Promise.resolve(e))).then(e=>{t||i(e)}),()=>{t=!0}},[t]),r}function _B(){let[e]=ln(`s`,{shallow:!0}),{navState:t}=mN(),n=t.activeL3Id??``;return e||n||``}function vB({entry:e,active:t,onActivate:n}){let r=e.onRun;return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(e),className:G(`group flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors`,e.muted?`text-[11.5px]`:`text-[13px]`,t?`bg-primary/10 font-semibold text-primary`:G(`hover:bg-muted/60 hover:text-foreground`,e.muted?`text-muted-foreground/70`:`text-muted-foreground`)),children:[e.icon&&(0,W.jsx)(e.icon,{className:`size-4 shrink-0`}),e.timestamp&&(0,W.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/60`,children:e.timestamp}),(0,W.jsx)(`span`,{className:`min-w-0 flex-1 line-clamp-2 break-words`,title:e.label,children:e.label}),e.badge&&(0,W.jsx)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground/50`,children:e.badge}),r&&(0,W.jsx)(`span`,{role:`button`,tabIndex:-1,title:e.runIcon===`link`?`View workout`:e.runIcon===`stop`?`Stop workout`:e.runIcon===`edit`?`Edit note`:`Start workout`,onClick:t=>{t.stopPropagation(),e.onRun?.()},className:`flex size-5 shrink-0 items-center justify-center rounded text-primary opacity-0 transition-all group-hover:opacity-100 hover:bg-primary/10`,children:e.runIcon===`link`?(0,W.jsx)(dr,{className:`size-3.5`}):e.runIcon===`stop`?(0,W.jsx)(Ie,{className:`size-3.5`}):e.runIcon===`edit`?(0,W.jsx)(en,{className:`size-3.5`}):(0,W.jsx)(_e,{className:`size-3.5`})})]})}function yB({entries:e,activeId:t,onSection:n}){let r=yn(),{scrollToSection:i}=mN(),a=e=>{if(n)return n(e);if(e.onRun)return e.onRun();if(e.to)return r(e.to);if(e.sectionId)return i(e.sectionId)};return(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:e.map(e=>e.kind===`section`?e.entries.length===0?null:(0,W.jsxs)(`div`,{className:`mt-1 flex flex-col gap-0.5 first:mt-0`,children:[(0,W.jsx)(`div`,{className:`px-2 pb-1 pt-3 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:e.label}),(0,W.jsx)(yB,{entries:e.entries,activeId:t,onSection:n})]},e.id):e.kind===`wql`?null:(0,W.jsx)(vB,{entry:e,active:t!=null&&e.sectionId===t,onActivate:a},e.id))})}function bB(){let e=yn(),{scrollToSection:t}=mN();return{navigate:(t,n)=>e(t,{replace:n?.replace}),setQueryParam:(e,t)=>{},scrollToSection:t}}function xB(){let e=bB(),{openCreateJournal:t}=mN();return n=>{if(n.id===`home-new-journal`){t({mode:`blank`});return}TI(n.action,e)}}function SB(e,t,n){return e.isActive?e.isActive(n,t):e.action.type===`route`?e.action.to===`/`?n.pathname===`/`||n.pathname===``:n.pathname===e.action.to:e.action.type===`scroll`?t.activeL3Id===e.action.sectionId:e.action.type===`query`&&t.activeL3Id===e.id}function CB({items:e}){let{navState:t}=mN(),n=ht(),r=xB();return(0,W.jsx)(lF,{children:e.map(e=>{if(e.variant===`notable`)return(0,W.jsx)(`div`,{className:`mb-2`,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`nav-item-${e.id}`,onClick:()=>r(e),className:`flex w-full items-center justify-center gap-2 rounded-lg bg-primary/10 px-3 py-2 text-xs font-semibold text-primary transition-all hover:bg-primary hover:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-sm`,children:[(0,W.jsx)(Rt,{className:`size-4 shrink-0`}),(0,W.jsx)(`span`,{children:e.label})]})},e.id);let i=SB(e,t,n);return e.children&&e.children.length>0?(0,W.jsx)(AI,{title:e.label,count:e.children.length,defaultOpen:e.children.some(e=>SB(e,t,n)),collapsible:e.id!==`syntax-group`,children:e.children.map(e=>{let i=SB(e,t,n);return(0,W.jsxs)(uF,{onClick:()=>r(e),current:i,children:[e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:e.label})]},e.id)})},e.id):(0,W.jsxs)(uF,{onClick:e.disabled?void 0:()=>r(e),current:i,disabled:e.disabled,"aria-label":e.disabled?`${e.label} (coming soon)`:void 0,className:e.disabled?`opacity-60`:void 0,children:[e.icon&&(0,W.jsx)(e.icon,{"data-slot":`icon`}),(0,W.jsx)(dF,{children:e.disabled?`+`:e.label})]},e.id)})})}function wB({navSpec:e}){let{tree:t,navState:n,dispatch:r,contextNav:i}=mN(),a=ht(),o=gB(e),s=(t??[]).find(e=>e?.id===n.activeL1Id)??null,c=i?.pathname===a.pathname?i:null;return(0,W.jsxs)(oF,{children:[(0,W.jsx)(sF,{children:(0,W.jsx)(`div`,{className:`px-2 pt-3 pb-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:s?.label??`Wod Wiki`})}),(0,W.jsxs)(cF,{children:[(()=>{if(c||!s)return null;if(s.panel){let e=s.panel;return(0,W.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,W.jsx)(e,{item:s,navState:n,dispatch:r})})}return s.children&&s.children.length>0?(0,W.jsx)(`div`,{className:`border-b border-border/40 pb-2 mb-2`,children:(0,W.jsx)(CB,{items:s.children})}):null})(),c?(0,W.jsx)(`div`,{className:`pt-1`,children:(0,W.jsx)(yB,{entries:c.spec})}):o.length>0&&(0,W.jsx)(`div`,{className:`pt-1`,children:(0,W.jsx)(yB,{entries:o})})]})]})}var TB=`0.48.2174`,EB=`https://github.com/bitcobblers/wod-wiki/releases`;function DB(e){return/-pr\.\d+$/.test(e)?EB:`${EB}/tag/v${e}`}function OB({onSearch:e,onCreate:t}){let{tree:n,navState:r,dispatch:i}=mN(),a=yn(),s=ht(),c=eF(),l={navigate:(e,t)=>a(e,{replace:t?.replace}),setQueryParam:()=>{},scrollToSection:()=>{}},u=(n??[]).filter(e=>e!=null&&e.icon!=null&&e.id!==`settings`&&e.id!==`buy-me-a-coffee`),d=s.pathname.startsWith(`/settings`),f=s.pathname===`/`||s.pathname===``,p=`pointer-events-none absolute left-full top-1/2 -translate-y-1/2 z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`;return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>a(`/`),title:`Home`,"aria-label":`Wod Wiki home`,"aria-current":f?`page`:void 0,className:`group relative mb-3 grid size-8 shrink-0 place-items-center rounded-xl bg-primary text-primary-foreground shadow-md shadow-primary/20 rotate-3`,children:[(0,W.jsx)(k,{size:17}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Home`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Home`})]}),(0,W.jsx)(`nav`,{"aria-label":`Primary`,className:`flex flex-col items-center gap-1.5`,children:u.map(e=>{let t=e.icon,n=SB(e,r,s);return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{i({type:`SET_ACTIVE_L1`,id:e.id}),TI(e.action,l)},title:e.label,"aria-label":e.label,"aria-current":n?`page`:void 0,className:G(`group relative grid size-9 place-items-center rounded-lg transition-colors`,n?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[n&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(t,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:e.label}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:e.label})]},e.id)})}),(0,W.jsx)(`div`,{className:`flex-1`}),(0,W.jsxs)(`button`,{type:`button`,onClick:e,title:`Search (⌘/)`,"aria-label":`Search`,className:`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,W.jsx)(o,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Search`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Search (⌘/)`})]}),(0,W.jsxs)(`a`,{href:jL,target:`_blank`,rel:`noopener noreferrer`,title:`Buy Me a Coffee`,"aria-label":`Buy Me a Coffee`,className:`group relative grid size-9 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground`,children:[(0,W.jsx)(ML,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Buy Me a Coffee`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Buy Me a Coffee`})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{c(),a(`/settings/profile`)},title:`Profile`,"aria-label":`Profile`,"aria-current":s.pathname.startsWith(`/settings/profile`)?`page`:void 0,"data-testid":`nav-profile`,className:G(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,s.pathname.startsWith(`/settings/profile`)?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[s.pathname.startsWith(`/settings/profile`)&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(V,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Profile`}),(0,W.jsx)(`span`,{role:`tooltip`,className:p,children:`Profile`})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>{c(),a(`/settings/appearance`)},title:`Settings`,"aria-label":`Settings`,"aria-current":d?`page`:void 0,"data-testid":`nav-settings`,className:G(`group relative grid size-9 place-items-center rounded-lg transition-colors mt-1.5`,d?`bg-primary/10 text-primary`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:[d&&(0,W.jsx)(`span`,{className:`absolute -left-[14px] top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-primary`}),(0,W.jsx)(Jt,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Settings`}),(0,W.jsxs)(`span`,{role:`tooltip`,className:`pointer-events-none absolute bottom-0 left-full z-50 ml-2 w-max rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-focus-within:opacity-100 group-hover:opacity-100`,children:[`Settings (v`,TB,`)`]})]})]})}function kB({activations:e,activeSection:t,variant:n,deps:r,className:i}){return(0,W.jsx)(`nav`,{className:G(`lg:sticky z-20 flex items-center gap-1 px-4 py-2 bg-background/95 backdrop-blur-sm border-b border-border/50 overflow-x-auto`,n===`top-fixed`?`lg:top-0`:`lg:top-[104px]`,i),children:e.map(e=>(0,W.jsx)(`button`,{onClick:()=>TI(e.action,r),className:G(`px-3 py-1.5 rounded-full text-[10px] font-black uppercase tracking-[0.12em] whitespace-nowrap transition-all ring-1`,t===e.id?`bg-primary text-primary-foreground ring-primary/30 shadow-md`:`bg-muted/50 text-muted-foreground ring-transparent hover:bg-muted hover:ring-border`),children:e.label},e.id))})}var AB=class e{now;name=`tick`;timestamp;data;static _counter=0;constructor(t,n=El){this.now=n;let r=this.now.nowMs();e._counter++,this.timestamp=new Date(r+e._counter),this.data=t}},jB=20,MB=e=>{let[t,n]=(0,U.useState)(`idle`),[r,i]=(0,U.useState)(0),[a,o]=(0,U.useState)(0),[s,c]=(0,U.useState)(null),l=(0,U.useRef)(null),u=(0,U.useRef)(null),d=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),n(`idle`)},[]),f=(0,U.useCallback)(()=>{if(e)try{let t=new AB(void 0,e.nowProvider);e.handle(t),o(e=>e+1)}catch{d(),n(`error`)}},[e,d]);(0,U.useEffect)(()=>{if(e)return e.subscribeToStack(e=>{e.blocks.length===0&&t!==`completed`&&(l.current&&=(clearInterval(l.current),null),n(`completed`))})},[e,t]),(0,U.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]);let p=(0,U.useCallback)(()=>{if(!e){console.warn(`useRuntimeExecution: Cannot start execution without a runtime`);return}if(t===`running`){console.warn(`useRuntimeExecution: Runtime is already running`);return}t===`paused`&&e.handle({name:`timer:resume`,timestamp:new Date,data:{}}),n(`running`);let i=e?.nowProvider?.nowMs()??El.nowMs();u.current=i-r,r===0&&c(i),l.current=setInterval(f,jB)},[e,t,r,f]),m=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),e&&e.handle({name:`timer:pause`,timestamp:new Date,data:{}}),n(`paused`)},[e]),h=(0,U.useCallback)(()=>{l.current&&=(clearInterval(l.current),null),i(0),o(0),n(`idle`),c(null),u.current=null},[e]),g=(0,U.useCallback)(()=>{!e||t===`running`||(n(`paused`),f())},[e,t,f]);return(0,U.useEffect)(()=>{if(t!==`running`||!u.current)return;let n=setInterval(()=>{i((e?.nowProvider?.nowMs()??El.nowMs())-u.current)},100);return()=>clearInterval(n)},[t,e?.nowProvider]),(0,U.useEffect)(()=>()=>{l.current&&=(clearInterval(l.current),null)},[]),(0,U.useEffect)(()=>{h()},[e,h]),(0,U.useMemo)(()=>({status:t,elapsedTime:r,stepCount:a,startTime:s,start:p,pause:m,stop:d,reset:h,step:g}),[t,r,a,s,p,m,d,h,g])},NB=(e,t)=>!e||!Array.isArray(e)?0:e.reduce((e,n)=>{if(`started`in n){let r=n.started,i=n.ended??t;return e+Math.max(0,i-r)}let r=n.start instanceof Date?n.start.getTime():n.start||0,i=n.stop?n.stop instanceof Date?n.stop.getTime():n.stop:t;return e+Math.max(0,i-r)},0);function PB(e,t){let n=t,r=()=>{let t=e?.getMemoryByTag(n)[0];if(t)return n===`round`?t.metrics[0]:t.metrics[0]?.value},[i,a]=(0,U.useState)(r);return(0,U.useEffect)(()=>{if(!e){a(void 0);return}a(r());let t=e.getMemoryByTag(n)[0];if(t)return t.subscribe(e=>{a(n===`round`?e[0]:e[0]?.value)})},[e,t]),i}function FB(e){return PB(e,`round`)}function IB(e){return PB(e,`display`)}function LB(e){let t=FB(e),n=IB(e);return(0,U.useMemo)(()=>{if(!t)return null;let e=n?.roundDisplay??(t.total===void 0?`Round ${t.current}`:`Round ${t.current} of ${t.total}`),r=t.total===void 0?void 0:Math.min(1,(t.current-1)/t.total);return{current:t.current,total:t.total,label:e,progress:r}},[t,n?.roundDisplay])}var RB=(0,U.createContext)(void 0),zB=({runtime:e,children:t})=>(0,W.jsx)(RB.Provider,{value:e,children:t});function BB(){let e=(0,U.useContext)(RB);if(!e)throw Error(`useScriptRuntime must be used within ScriptRuntimeProvider`);return e}function VB(e){let t=BB(),n=e===void 0?t:e,[r,i]=(0,U.useState)(()=>n?.getOutputStatements?.()??[]);return(0,U.useEffect)(()=>{if(!n){i([]);return}return i(n.getOutputStatements()),n.subscribeToOutput?.(()=>{i(n.getOutputStatements())})},[n]),(0,U.useMemo)(()=>{let e=new Map,t=new Map,n=[],i=[];for(let a of r){e.set(a.id,a);let r=t.get(a.sourceBlockKey)??[];switch(r.push(a),t.set(a.sourceBlockKey,r),a.outputType){case`segment`:n.push(a);break;case`metric`:i.push(a)}}let a=n.filter(e=>e.completionReason!==void 0);return{outputs:r,byId:e,byBlockKey:t,segments:n,completions:a,metrics:i}},[r])}function HB(e){let t=BB(),n=e===void 0?t:e,[r,i]=(0,U.useState)(()=>n?.getLiveAnalytics?.()??[]);return(0,U.useEffect)(()=>{if(!n){i([]);return}return i(n.getLiveAnalytics?.()??[]),n.subscribeToOutput?.(()=>{i(n.getLiveAnalytics?.()??[])})},[n]),r}function UB(){let e=BB(),[t,n]=(0,U.useState)({type:`initial`,blocks:e.stack.blocks,depth:e.stack.count,clockTime:e.clock.currentDate});return(0,U.useEffect)(()=>e.subscribeToStack(e=>{n(e)}),[e]),t}function WB(){return UB().blocks}function GB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`metric:next`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{for(let t of e){let e=t.getMemoryByTag(`metric:next`);if(e.length===0)continue;let n=la.empty(t.key.toString());for(let t of e)n.merge(t.metrics);if(n.length>0)return{metrics:n,block:t}}return null},[e,t])}function KB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`time`)[0];if(e){let r=e.subscribe(()=>{n(e=>e+1)});t.push(r)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{let t=[];for(let n of e){let e=n.getMemoryByTag(`time`)[0];if(!e)continue;let r=e.metrics[0]?.value;r&&t.push({block:n,timer:r,isPinned:r.role===`primary`})}return t},[e,t])}function qB(){let e=KB();return(0,U.useMemo)(()=>{if(e.length===0)return;let t=e[0];return t.block.blockType===`Rest`?t:[...e].reverse().find(e=>e.isPinned)||t},[e])}function JB(){let e=KB(),t=qB();return(0,U.useMemo)(()=>t?e.filter(e=>e.block!==t.block):[],[e,t])}function YB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`controls`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{let t=[],n=[];for(let r=0;r<e.length;r++){let i=e[r].getMemoryByTag(`controls`);if(i.length===0)continue;let a=i[0].metrics.map(e=>e.value).filter(Boolean),o=r===e.length-1;for(let e of a)e.isPinned?t.push(e):o&&n.push(e)}let r=new Set,i=[];for(let e of t)r.has(e.id)||(r.add(e.id),i.push(e));for(let e of n)r.has(e.id)||(r.add(e.id),i.push(e));return i},[e,t])}function XB(){let e=WB(),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=[];for(let r of e){let e=r.getMemoryByTag(`metric:display`);for(let r of e){let e=r.subscribe(()=>{n(e=>e+1)});t.push(e)}}return()=>{t.forEach(e=>e())}},[e]),(0,U.useMemo)(()=>{if(e.length===0)return;let t=[],n=[...e].reverse();return n.forEach((e,r)=>{if(e.blockType===`Root`&&!e.label)return;let i=e.getMemoryByTag(`metric:display`),a=i.map(e=>e.metrics);if(a.length===0&&!e.label)return;let o=r===n.length-1,s=i.length>1?i.map(e=>e.metrics):void 0;t.push({block:e,displayRows:a,label:e.label,depth:r,isLeaf:o,metricGroups:s})}),t.length>0?t:void 0},[e,t])}function ZB(e){let t=BB(),n=(0,U.useMemo)(()=>t.stack.blocks.find(t=>t.key.toString()===e),[t,e]),[r,i]=(0,U.useState)(()=>n?.getMemoryByTag(`time`)[0]?.metrics[0]?.value);(0,U.useEffect)(()=>t.stack.subscribe(()=>{let n=t.stack.blocks.find(t=>t.key.toString()===e);if(n){let e=n.getMemoryByTag(`time`)[0];i(e?.metrics[0]?.value)}else i(void 0)}),[t,e]),(0,U.useEffect)(()=>{if(!n){i(void 0);return}let e=n.getMemoryByTag(`time`)[0];if(i(e?.metrics[0]?.value),e)return e.subscribe(e=>{i(e[0]?.value)})},[n]);let a=(0,U.useMemo)(()=>r?.spans??[],[r]),o=a.length>0&&a[a.length-1].ended===void 0,[s,c]=(0,U.useState)(cu()),l=(0,U.useMemo)(()=>a.length===0?0:NB(a,s),[a,s]);return(0,U.useEffect)(()=>{if(!o)return;let e,t=()=>{c(cu()),e=requestAnimationFrame(t)};return t(),()=>cancelAnimationFrame(e)},[o]),{elapsed:l,isRunning:o,timeSpans:a}}var QB=(0,U.createContext)(void 0),$B=(0,U.createContext)(null),eV={getState:()=>az().getState(),setState:(e,t)=>{let n=az();typeof e==`function`?n.setState(e(n.getState()),t):n.setState(e,t)},subscribe:e=>az().subscribe(e)},tV=({factory:e,children:t})=>{let[n,r]=(0,U.useState)(null),[i,a]=(0,U.useState)(null),[o,s]=(0,U.useState)(!1),[c,l]=(0,U.useState)(null),u=(0,U.useRef)(e);u.current=e;let d=(0,U.useRef)(null),f=(0,U.useRef)(null),p=(0,U.useRef)(!1),m=(0,U.useCallback)(()=>{f.current&&=(f.current.dispose(),null),a(null),eV.getState().setSubscriptionManager(null);let e=d.current;if(d.current=null,e)try{u.current.disposeRuntime(e)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime:`,e)}r(null),l(null)},[]),h=(0,U.useCallback)((e,t)=>{if(!p.current){p.current=!0,s(!0),l(null);try{f.current&&=(f.current.dispose(),null);let n=d.current;if(d.current=null,n)try{u.current.disposeRuntime(n)}catch(e){console.error(`[RuntimeProvider] Error disposing existing runtime:`,e)}let i=u.current.createRuntime(e,t);if(d.current=i,r(i),i){let e=new em(i);e.add(new $p({id:`local`})),f.current=e,a(e),eV.getState().setSubscriptionManager(e)}else f.current=null,a(null),eV.getState().setSubscriptionManager(null)}catch(e){console.error(`[RuntimeProvider] Error creating runtime:`,e),l(e instanceof Error?e:Error(String(e))),d.current=null}finally{p.current=!1,s(!1)}}},[]);(0,U.useEffect)(()=>()=>{if(f.current&&f.current.dispose(),d.current)try{u.current.disposeRuntime(d.current)}catch(e){console.error(`[RuntimeProvider] Error disposing runtime on unmount:`,e)}},[]);let g={runtime:n,isInitializing:o,error:c,initializeRuntime:h,disposeRuntime:m};return(0,W.jsx)(QB.Provider,{value:g,children:(0,W.jsx)($B.Provider,{value:i,children:t})})};function nV({factory:e,children:t}){return(0,W.jsx)(tV,{factory:e,children:t})}var rV=`bg-background ring-1 ring-zinc-950/5 shadow-sm lg:shadow-[-18px_0_36px_-28px_rgba(15,23,42,0.16),18px_0_36px_-28px_rgba(15,23,42,0.16)] dark:shadow-none dark:ring-white/10`,iV=`flex flex-col flex-1 min-w-0 xl:max-w-[984px] 2xl:max-w-none min-h-screen lg:rounded-[2.5rem]`;function aV({id:e,title:t,subtitle:n,titleAccessory:r,actions:i,queryBar:a,subheader:o,titleTestId:s,className:c}){return(0,W.jsxs)(`div`,{id:e,"data-page-sticky-boundary":`true`,className:G(`max-lg:hidden lg:sticky lg:top-0 z-30 bg-background/80 backdrop-blur-md transition-colors`,c),children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-3 px-4 sm:px-6 lg:px-8 py-2 sm:py-2.5`,children:[t&&(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5 sm:gap-3 min-w-0`,children:[(0,W.jsx)(`div`,{className:`h-5 w-1.5 shrink-0 rounded-full bg-primary`}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[(0,W.jsxs)(`div`,{className:`min-w-0`,children:[(0,W.jsx)(`h1`,{"data-testid":s,className:`text-base sm:text-lg font-black tracking-tight text-foreground leading-none truncate`,children:t}),n&&(0,W.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground truncate`,children:n})]}),r]})]}),a&&(0,W.jsx)(`div`,{className:`min-w-0 flex-1`,children:a}),i&&(0,W.jsx)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 shrink-0 ml-auto`,children:i})]}),o&&(0,W.jsx)(`div`,{className:`bg-background/40`,children:o})]})}function oV({ids:e,enabled:t=!0,rootMargin:n=`-10% 0px -40% 0px`,threshold:r=[0,.3,1],onChange:i,shouldAcceptChange:a,scrollDirection:o=`ratio`,dataAttribute:s,debounceMs:c=0}){let l=(0,U.useRef)(``),u=(0,U.useRef)(i),d=(0,U.useRef)(a),f=(0,U.useRef)(null),p=(0,U.useRef)(1);(0,U.useEffect)(()=>{u.current=i},[i]),(0,U.useEffect)(()=>{d.current=a},[a]);let m=e.filter(Boolean).join(`\0`),h=r.join(`,`),g=(0,U.useMemo)(()=>m?m.split(`\0`):[],[m]),_=(0,U.useMemo)(()=>h.split(`,`).map(Number),[h]),v=(0,U.useCallback)(()=>{f.current&&=(clearTimeout(f.current),null)},[]);(0,U.useEffect)(()=>{if(!t||g.length===0||typeof IntersectionObserver>`u`)return;let e=new Map,r=e=>s?e.getAttribute(s):e.id||null,i;if(o===`topmost-when-up`){let e=window.scrollY,t=()=>{let t=window.scrollY;t!==e&&(p.current=t>e?1:-1),e=t};window.addEventListener(`scroll`,t,{passive:!0}),i=()=>window.removeEventListener(`scroll`,t)}let a=new IntersectionObserver(t=>{if(t.forEach(t=>{let n=r(t.target);n&&(t.isIntersecting?e.set(n,t.intersectionRatio):e.delete(n))}),e.size===0)return;let n=``;if(o===`topmost-when-up`&&p.current===-1){let t=1/0;e.forEach((e,r)=>{let i=g.indexOf(r);i>=0&&i<t&&(t=i,n=r)})}else{let t=-1;e.forEach((e,r)=>{e>t&&(t=e,n=r)})}!n||n===l.current||d.current&&!d.current(n)||(l.current=n,c>0?(v(),f.current=setTimeout(()=>{u.current(n),f.current=null},c)):u.current(n))},{rootMargin:n,threshold:_});return g.forEach(e=>{let t=s?document.querySelector(`[${s}="${e}"]`):document.getElementById(e);t&&a.observe(t)}),()=>{a.disconnect(),v(),i?.()}},[t,g,_,n,o,s,c,v])}function sV({title:e,titleAccessory:t,actions:n,subheader:r,children:i,index:a=[],activeSectionId:o,hero:s,sections:c,className:l}){let u=!!(c&&c.length>0)&&!e,[,d]=ln(`s`,{defaultValue:o??a[0]?.id??``,shallow:!0,history:`replace`}),[f,p]=(0,U.useState)(c?.[0]?.id??``);if(oV({ids:a.map(e=>e.id),enabled:!u&&a.length>0,rootMargin:`-10% 0px -40% 0px`,threshold:[0,.3,1],onChange:e=>{d(e)},shouldAcceptChange:()=>!0}),oV({ids:c?.map(e=>e.id)??[],enabled:u,rootMargin:`-20% 0px -50% 0px`,threshold:[0,.25,.5,.75],onChange:p}),u){let e=c.map(e=>({id:e.id,label:e.label,action:{type:`scroll`,sectionId:e.id}}));return(0,W.jsxs)(`div`,{className:G(`flex flex-col min-h-screen bg-background`,l),children:[s,(0,W.jsx)(kB,{activations:e,activeSection:f,variant:`top-fixed`,deps:{navigate:()=>{},setQueryParam:()=>{},scrollToSection:e=>{let t=document.getElementById(e);if(t){let e=t.getBoundingClientRect().top+window.scrollY-64;window.scrollTo({top:e,behavior:`smooth`})}}}}),(0,W.jsx)(`div`,{className:`flex-1`,children:c.map(e=>{let t=(0,W.jsx)(`div`,{id:e.id,"data-section-id":e.id,className:`py-12 lg:py-16 px-6 lg:px-10 border-b border-border/30`,children:e.content},e.id);return e.runtimeFactory?(0,W.jsx)(nV,{factory:e.runtimeFactory,children:t},e.id):t})})]})}return(0,W.jsx)(`div`,{className:G(`relative flex w-full min-h-screen justify-start items-start`,l),children:(0,W.jsxs)(`div`,{className:G(iV,rV),children:[(0,W.jsx)(aV,{title:e,titleAccessory:t,actions:n,subheader:r}),(0,W.jsx)(`div`,{className:`flex-1`,children:i})]})})}var cV=`[data-page-sticky-boundary="true"]`,lV=0;function uV(e,t=lV){if(typeof document>`u`)return e;let n=Array.from(document.querySelectorAll(cV)).reduce((e,t)=>{let n=t.getBoundingClientRect();return n.height<=0||n.bottom<=0?e:Math.max(e,n.bottom)},0);return n>0?n+t:e}function dV(e,t=lV){let[n,r]=(0,U.useState)(e);return(0,U.useEffect)(()=>{let n=0,i=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(()=>r(uV(e,t)))};return i(),window.addEventListener(`scroll`,i,{passive:!0}),window.addEventListener(`resize`,i),()=>{cancelAnimationFrame(n),window.removeEventListener(`scroll`,i),window.removeEventListener(`resize`,i)}},[e,t]),n}function fV({top:e,label:t,icon:n,badge:r,meta:i,testId:a,className:o}){return(0,W.jsxs)(`div`,{"data-testid":a,className:G(`sticky z-10 flex items-center gap-2 border-y border-border/60 bg-card/95 px-6 py-2 shadow-[0_1px_2px_rgba(0,0,0,0.03)] backdrop-blur`,o),style:{top:`${e}px`},children:[n,(0,W.jsx)(`span`,{className:`min-w-0 truncate text-xs font-bold text-foreground`,children:t}),r,i&&(0,W.jsx)(`span`,{className:`ml-auto shrink-0 pl-2 font-mono text-[10px] text-muted-foreground`,children:i})]})}var pV=(0,U.createContext)(null),mV=(0,U.createContext)(null);function hV({children:e}){let[t,n]=(0,U.useState)(null);return(0,W.jsx)(mV.Provider,{value:n,children:(0,W.jsx)(pV.Provider,{value:t,children:e})})}function gV({className:e}){let t=(0,U.useContext)(mV);return(0,W.jsx)(`div`,{ref:t,className:e,"data-testid":`mobile-query-slot`})}function _V(){return(0,U.useContext)(pV)}function vV({editor:e,title:t,subtitle:n,titleTestId:r,actions:i,timerOverlay:a,reviewOverlay:o,isTimerOpen:s=!1,isReviewOpen:c=!1,onCloseTimer:l,onCloseReview:u,className:d}){return(0,W.jsxs)(`div`,{className:G(`relative flex w-full min-h-screen justify-start items-start`,d),children:[(0,W.jsxs)(`div`,{className:G(iV,rV),children:[(0,W.jsx)(aV,{title:t,subtitle:n,titleTestId:r,actions:i}),(0,W.jsx)(`main`,{className:`flex-1 min-w-0 max-w-full`,children:e})]}),s&&a&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,W.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,W.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,W.jsx)(`button`,{onClick:l,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:a})]})}),c&&o&&(0,W.jsx)(`div`,{className:`fixed inset-0 z-50 bg-background/95 backdrop-blur-sm`,children:(0,W.jsxs)(`div`,{className:`w-full h-full flex flex-col`,children:[(0,W.jsx)(`div`,{className:`flex justify-end p-4`,children:(0,W.jsx)(`button`,{onClick:u,className:`px-3 py-1.5 rounded-md text-sm font-bold text-muted-foreground hover:text-foreground bg-muted/60 hover:bg-muted transition-colors`,children:`Close`})}),(0,W.jsx)(`div`,{className:`flex-1 min-h-0`,children:o})]})})]})}function yV(e){return e.map(e=>{let t=e.action,n=e.secondaryAction?.action,r={kind:`link`,id:e.id,label:e.label};return n&&n.type===`call`&&(r.onRun=n.handler,r.runIcon=e.secondaryRunIcon??`play`),t.type===`route`?{...r,to:t.to}:t.type===`scroll`?{...r,sectionId:t.sectionId}:t.type===`call`?{...r,onRun:t.handler}:r})}var bV=U.createContext(null);function xV(){let e=U.useContext(bV);if(!e)throw Error(`DropdownMenu components must be used inside a DropdownMenu`);return e}function SV(){let e=U.useContext(bV);return U.useCallback(()=>{e?.setIsOpen(!1)},[e])}var CV=({children:e,open:t,onOpenChange:n})=>{let r=U.useContext(bV),i=U.useId(),a=r?`${r.portalChain}/${i}`:i,[o,s]=U.useState(t??!1),c=U.useRef(null),[l,u]=U.useState(-1),d=U.useRef(new Map),[,f]=U.useReducer(e=>e+1,0);U.useEffect(()=>{t!==void 0&&s(t)},[t]);let p=U.useCallback(e=>{s(e),u(-1),n?.(e)},[n]),m=U.useCallback((e,t)=>{d.current.set(e,t),f()},[]),h=U.useCallback(e=>{d.current.delete(e),f()},[]),g=U.useCallback(e=>Array.from(d.current.keys()).indexOf(e),[]),_=d.current.size,v=U.useMemo(()=>({isOpen:o,setIsOpen:p,triggerRef:c,registerItem:m,unregisterItem:h,getItemIndex:g,activeIndex:l,setActiveIndex:u,itemCount:_,menuId:i,portalChain:a}),[o,p,m,h,g,l,_,i,a]);return(0,W.jsx)(bV.Provider,{value:v,children:(0,W.jsx)(`div`,{ref:c,className:`relative inline-block`,children:e})})},wV=U.forwardRef(({className:e,children:t,asChild:n,...r},i)=>{let{isOpen:a,setIsOpen:o}=xV(),s=e=>{e.stopPropagation(),o(!a)};return n&&U.isValidElement(t)?U.cloneElement(t,{...r,onClick:s}):(0,W.jsx)(`button`,{ref:i,className:e,onClick:s,...r,children:t})});wV.displayName=`DropdownMenuTrigger`;var TV=U.forwardRef(({className:e,children:t,align:n=`center`,side:r=`bottom`,...i},a)=>{let{isOpen:o,setIsOpen:s,triggerRef:c,setActiveIndex:l,itemCount:u,menuId:d,portalChain:f}=xV(),p=U.useRef(null),m=a||p,[h,g]=U.useState({top:0,bottom:0,left:0,width:0}),_=r===`bottom`,[v,y]=U.useState(!1);U.useEffect(()=>{if(!o||!c.current)return;let e=c.current.getBoundingClientRect();g({top:e.bottom+8,bottom:window.innerHeight-e.top+8,left:e.left,width:e.width}),y(!1)},[o,c]),U.useLayoutEffect(()=>{if(!o||!_||!m.current)return;let e=m.current.getBoundingClientRect();y(h.top+e.height>window.innerHeight)},[o,_,h.top]),U.useEffect(()=>{if(!o||u===0)return;let e=setTimeout(()=>{l(0)},0);return()=>clearTimeout(e)},[o,u,l]),U.useEffect(()=>{if(!o)return;let e=e=>{let t=e.target;if(m.current&&m.current.contains(t)||c.current&&c.current.contains(t))return;let n=t.closest?.(`[data-dropdown-chain]`)?.getAttribute(`data-dropdown-chain`);n&&n.split(`/`).includes(d)||s(!1)},t=setTimeout(()=>{document.addEventListener(`mousedown`,e)},0);return()=>{clearTimeout(t),document.removeEventListener(`mousedown`,e)}},[o,s,m,c,d]);let b=e=>{if(u!==0)switch(e.key){case`ArrowDown`:e.preventDefault(),l(e=>e<u-1?e+1:0);break;case`ArrowUp`:e.preventDefault(),l(e=>e>0?e-1:u-1);break;case`Home`:e.preventDefault(),l(0);break;case`End`:e.preventDefault(),l(u-1);break;case`Escape`:e.preventDefault(),s(!1),c.current?.querySelector(`button`)?.focus();break;case`Tab`:s(!1)}};if(!o)return null;let x={position:`fixed`,zIndex:9999};return r===`top`||v?x.bottom=h.bottom:x.top=h.top,n===`end`?x.right=window.innerWidth-h.left-h.width:n===`start`?x.left=h.left:(x.left=h.left+h.width/2,x.transform=`translateX(-50%)`),BC.createPortal((0,W.jsx)(`div`,{ref:m,role:`menu`,"data-dropdown-chain":f,className:G(`min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95`,e),style:x,onKeyDown:b,...i,children:t}),document.body)});TV.displayName=`DropdownMenuContent`;var EV=U.forwardRef(({className:e,disabled:t,inset:n,onClick:r,onKeyDown:i,...a},o)=>{let{setIsOpen:s,registerItem:c,unregisterItem:l,getItemIndex:u,activeIndex:d}=xV(),f=U.useId(),p=U.useRef(null),m=U.useCallback(e=>{p.current=e,typeof o==`function`?o(e):o&&(o.current=e)},[o]);U.useEffect(()=>(c(f,p),()=>l(f)),[f,c,l]);let h=u(f)===d;return U.useEffect(()=>{h&&p.current?.focus()},[h]),(0,W.jsx)(`div`,{ref:m,role:`menuitem`,tabIndex:t?-1:h?0:-1,"aria-disabled":t,"data-active":h?`true`:void 0,className:G(`relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors`,`focus:bg-accent focus:text-accent-foreground`,`data-[active]:bg-accent data-[active]:text-accent-foreground`,n&&`pl-8`,t&&`pointer-events-none opacity-50`,e),onClick:e=>{t||(r?.(e),s(!1))},onKeyDown:e=>{t||(i?.(e),(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r?.(e),s(!1)))},...a})});EV.displayName=`DropdownMenuItem`;var DV=U.forwardRef(({className:e,inset:t,...n},r)=>(0,W.jsx)(`div`,{ref:r,className:G(`px-2 py-1.5 text-sm font-semibold`,t&&`pl-8`,e),...n}));DV.displayName=`DropdownMenuLabel`;var OV=U.forwardRef(({className:e,...t},n)=>(0,W.jsx)(`div`,{ref:n,className:G(`-mx-1 my-1 h-px bg-muted`,e),...t}));OV.displayName=`DropdownMenuSeparator`;function kV({className:e,children:t,...n}){return(0,W.jsx)(`div`,{className:G(`px-2 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground`,e),...n,children:t})}var AV=[{label:`Past 1 week`,value:`last 1w`},{label:`Past 2 weeks`,value:`last 2w`},{label:`Past 4 weeks`,value:`last 4w`},{label:`Past 8 weeks`,value:`last 8w`},{label:`Past 12 weeks`,value:`last 12w`},{label:`Past 1 year`,value:`last 52w`},{label:`All time`,value:`all`}],jV=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function MV(e,t){return new Date(e,t+1,0).getDate()}function NV(e,t){let n=new Date(e,t,1).getDay();return n===0?6:n-1}function PV(e,t){let n=X(e);if(n.error)return e;if(!t||t===`all`)return qh({...n,window:void 0});let r=X(`:note ${t}`);return r.error||r.family!==`find`||!r.window?e:qh({...n,window:r.window})}function FV(e){let t=X(e);return t.error||t.family===`pipeline`?null:`window`in t?t.window??null:null}function IV({query:e,onQueryChange:t,highlightDates:n=new Set,className:r}){let i=(0,U.useMemo)(()=>FV(e),[e]),[a,o]=(0,U.useState)(null),[s,c]=(0,U.useState)(()=>new Date),l=s.getFullYear(),u=s.getMonth(),d=(0,U.useMemo)(()=>i?i.kind===`relative`?`last ${i.size}${i.unit}`:i.end?`from ${i.start} to ${i.end}`:`from ${i.start}`:`All time`,[i]),f=(0,U.useMemo)(()=>{if(!i)return null;if(i.kind===`range`)return{start:i.start,end:i.end??i.start};let e=new Date,t=new Date;return i.unit===`d`?t.setDate(e.getDate()-i.size):t.setDate(e.getDate()-i.size*7),{start:VP(t),end:VP(e)}},[i]),p=(0,U.useMemo)(()=>{let e=MV(l,u),t=NV(l,u),n=[];for(let e=0;e<t;e++)n.push(null);for(let t=1;t<=e;t++)n.push(t);return n},[l,u]),m=n=>{if(!a)o(n),t(PV(e,`from ${n} to ${n}`));else{let[r,i]=a<=n?[a,n]:[n,a];o(null),t(PV(e,`from ${r} to ${i}`))}},h=e=>{e.stopPropagation(),c(new Date(l,u-1,1))},g=e=>{e.stopPropagation(),c(new Date(l,u+1,1))},_=s.toLocaleDateString(`en-US`,{month:`short`,year:`numeric`}),v=VP(new Date);return(0,W.jsxs)(`div`,{className:G(`relative inline-flex items-center`,r),children:[(0,W.jsxs)(CV,{children:[(0,W.jsx)(wV,{asChild:!0,children:(0,W.jsxs)(`button`,{type:`button`,"data-testid":`wql-window-picker-trigger`,className:`flex h-9 items-center gap-1.5 rounded-lg border border-border bg-background px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,W.jsx)(Tn,{className:`size-3.5 text-muted-foreground`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{className:`font-mono text-xs`,children:d}),(0,W.jsx)(Rn,{className:`size-3 text-muted-foreground`,"aria-hidden":`true`})]})}),(0,W.jsxs)(TV,{align:`end`,className:`w-72 p-3`,children:[(0,W.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-1 border-b border-border/60 pb-2`,children:AV.map(n=>{let r=n.value===`all`?!i:i?.kind===`relative`&&`last ${i.size}${i.unit}`===n.value;return(0,W.jsx)(`button`,{type:`button`,"data-testid":`wql-window-preset-${n.value}`,onClick:()=>{o(null),t(PV(e,n.value))},className:G(`rounded-md px-2 py-1 text-[11px] font-medium transition-colors`,r?`bg-primary text-primary-foreground`:`bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground`),children:n.label},n.value)})}),(0,W.jsxs)(`div`,{className:`mb-2 flex items-center justify-between`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:h,"data-testid":`wql-calendar-prev-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Previous month`,children:(0,W.jsx)(xn,{className:`size-4`})}),(0,W.jsx)(`span`,{className:`text-xs font-semibold text-foreground`,children:_}),(0,W.jsx)(`button`,{type:`button`,onClick:g,"data-testid":`wql-calendar-next-month`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Next month`,children:(0,W.jsx)(_t,{className:`size-4`})})]}),(0,W.jsx)(`div`,{className:`mb-1 grid grid-cols-7 gap-1`,children:jV.map(e=>(0,W.jsx)(`div`,{className:`text-center text-[10px] font-medium text-muted-foreground`,children:e},e))}),(0,W.jsx)(`div`,{className:`grid grid-cols-7 gap-1`,"data-testid":`wql-calendar-grid`,children:p.map((e,t)=>{if(e===null)return(0,W.jsx)(`div`,{className:`size-8`},`empty-${t}`);let r=`${l}-${String(u+1).padStart(2,`0`)}-${String(e).padStart(2,`0`)}`,i=f&&r>=f.start&&r<=f.end,o=f&&r===f.start||a===r,s=f&&r===f.end,c=r===v,d=n.has(r);return(0,W.jsxs)(`button`,{type:`button`,"data-testid":`wql-calendar-day-${r}`,onClick:()=>m(r),className:G(`relative flex size-8 items-center justify-center rounded-md text-xs transition-colors`,o||s?`bg-primary font-bold text-primary-foreground`:i?`bg-primary/15 font-semibold text-primary`:c?`border border-primary font-semibold text-primary`:`text-foreground hover:bg-muted`),children:[(0,W.jsx)(`span`,{children:e}),d&&!o&&!s&&(0,W.jsx)(`span`,{className:`absolute bottom-0.5 size-1 rounded-full bg-primary`})]},r)})}),a&&(0,W.jsxs)(`div`,{className:`mt-2 text-center text-[10px] text-muted-foreground`,children:[`Select second date to complete range (starting from `,a,`)`]})]})]}),i&&(0,W.jsx)(`button`,{type:`button`,"data-testid":`wql-window-picker-clear`,onClick:()=>{o(null),t(PV(e,null))},title:`Clear time window`,"aria-label":`Clear time window`,className:`ml-1 grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,W.jsx)(ge,{className:`size-3.5`})})]})}function LV({onOpen:e}){let t=SV();return(0,W.jsxs)(K,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{t(),e()},"data-testid":`query-settings-trigger`,className:`w-full justify-start gap-2 rounded-lg text-xs`,children:[(0,W.jsx)(Hn,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,W.jsx)(`span`,{className:`truncate`,children:`Query settings`})]})}function RV(e){switch(e.kind){case`note`:return`note`;case`result`:return`result`;case`segment`:case`event`:return`segment`;case`effort`:return`effort`;default:return`note`}}var zV=[{id:`title`,label:`Title`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`tags`,label:`Tags`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.tags??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)},{id:`excerpt`,label:`Text Excerpt`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.preview?.join(` `)||e.detail||``,formatValue:e=>String(e??``)},{id:`sourceNotebook`,label:`Notebook`,level:`note`,defaultVisible:!0,align:`left`,getValue:e=>e.sourceNotebook,formatValue:e=>String(e??``)},{id:`date`,label:`Date`,level:`note`,defaultVisible:!0,align:`right`,getValue:e=>e.date,formatValue:e=>String(e??``)}],BV={note:zV,session:[{id:`title`,label:`Title`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`protocol`,label:`Protocol`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.block?.dataType||e.subtitle||``,formatValue:e=>String(e??``)},{id:`movements`,label:`Movements`,level:`session`,defaultVisible:!0,align:`left`,getValue:e=>e.detail||``,formatValue:e=>String(e??``)},{id:`targetDuration`,label:`Target Duration`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:eB(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`sessionLoad`,label:`Session Load`,level:`session`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``}],result:[{id:`title`,label:`Title`,level:`result`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`elapsedTime`,label:`Elapsed Time`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:eB(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`totalTonnage`,label:`Total Tonnage`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`tis`,label:`TIS Score`,level:`result`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.tis,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`prBadges`,label:`PR Badges`,level:`result`,defaultVisible:!0,align:`center`,getValue:e=>e.detail&&/\bPR\b/.test(e.detail)?`PR`:``,formatValue:e=>String(e??``)}],segment:[{id:`splitDuration`,label:`Split Duration`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.elapsedMs==null?``:eB(e.execution.elapsedMs),formatValue:e=>String(e??``)},{id:`roundIndex`,label:`Round/Lap Index`,level:`segment`,defaultVisible:!0,align:`left`,getValue:e=>e.title,formatValue:e=>String(e??``)},{id:`reps`,label:`Reps`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.reps,formatValue:e=>e==null?``:String(e)},{id:`load`,label:`Load`,level:`segment`,defaultVisible:!0,align:`right`,getValue:e=>e.execution?.loadLbs,formatValue:e=>typeof e==`number`?`${e.toLocaleString()} lbs`:``},{id:`pacingTier`,label:`Pacing / HR Tier`,level:`segment`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier||e.execution?.effortSlug||``,formatValue:e=>String(e??``)}],effort:[{id:`label`,label:`Label`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.label||e.title,formatValue:e=>String(e??``)},{id:`canonicalSlug`,label:`Canonical Slug`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.slug||e.id,formatValue:e=>String(e??``)},{id:`discipline`,label:`Discipline`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.discipline??``,formatValue:e=>String(e??``)},{id:`met`,label:`MET Score`,level:`effort`,defaultVisible:!0,align:`right`,getValue:e=>e.effort?.met,formatValue:e=>typeof e==`number`?e.toFixed(1):``},{id:`intensityTier`,label:`Intensity Tier`,level:`effort`,defaultVisible:!0,align:`center`,getValue:e=>e.effort?.intensityTier??``,formatValue:e=>String(e??``)},{id:`aliases`,label:`Aliases`,level:`effort`,defaultVisible:!0,align:`left`,getValue:e=>e.effort?.aliases??[],formatValue:e=>Array.isArray(e)?e.join(`, `):String(e??``)}]};function VV(e){return BV[e]??zV}function HV(e){return VV(e).filter(e=>e.defaultVisible).map(e=>e.id)}var UV=[{id:`cards`,label:`Cards`,icon:v},{id:`rows`,label:`Rows`,icon:j},{id:`feed`,label:`Feed`,icon:on}];function WV({streamControls:e}){return(0,W.jsxs)(`div`,{className:`flex flex-col gap-3`,"data-testid":`l3-stream-controls`,children:[e.onOpenQuerySettings&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`This page`}),(0,W.jsx)(LV,{onOpen:e.onOpenQuerySettings})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Date window`}),(0,W.jsx)(IV,{query:e.query,onQueryChange:e.onQueryChange,className:`w-full justify-between`})]}),e.availableGroupDims.length>0&&(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Group by`}),(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-groupby-options`,children:e.availableGroupDims.map(t=>{let n=e.groupDims.some(e=>e.toLowerCase()===t.id.toLowerCase());return(0,W.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-groupby-${t.id}`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleGroupDim(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,W.jsx)(`span`,{children:t.label})]},t.id)})})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Layout`}),(0,W.jsx)(`div`,{className:`grid grid-cols-3 gap-1`,"data-testid":`l3-layout-options`,children:UV.map(t=>{let n=t.icon,r=e.settings.layout===t.id;return(0,W.jsxs)(`button`,{type:`button`,"aria-pressed":r,onClick:()=>e.onLayoutChange(t.id),"data-testid":`l3-layout-${t.id}`,className:`flex min-h-8 items-center justify-center gap-1 rounded-md border px-1.5 py-1 text-[11px] font-medium transition-colors ${r?`border-border/80 bg-card text-foreground shadow-sm`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[(0,W.jsx)(n,{"aria-hidden":!0,className:`size-3`}),t.label]},t.id)})})]}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`Fields`}),(0,W.jsx)(`div`,{className:`flex flex-col gap-0.5`,"data-testid":`l3-field-options`,children:VV(e.level).map(t=>{let n=e.settings.visibleFields.includes(t.id);return(0,W.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/80 hover:bg-muted/60 transition-colors`,"data-testid":`l3-field-${t.id}`,children:[(0,W.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>e.onToggleField(t.id),className:`size-3.5 rounded border-border accent-primary cursor-pointer`}),(0,W.jsx)(`span`,{children:t.label})]},t.id)})})]})]})}function GV({spec:e,pageAction:t}){let{l3Items:n,streamControls:r}=mN(),i=gB(e),a=(0,U.useMemo)(()=>yV(n),[n]),o=_B();return i.length===0&&a.length===0&&!r&&!t?null:(0,W.jsxs)(`div`,{className:`flex flex-col px-3 py-4 gap-4`,children:[r&&(0,W.jsx)(`div`,{className:`pb-3 border-b border-border/50`,children:(0,W.jsx)(WV,{streamControls:r})}),i.length>0&&(0,W.jsx)(yB,{entries:i,activeId:o}),a.length>0&&(0,W.jsxs)(`div`,{className:`flex flex-col`,children:[(0,W.jsx)(`div`,{className:`px-2 pb-1 pt-1 text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground`,children:`On this page`}),(0,W.jsx)(yB,{entries:a,activeId:o})]}),t&&(0,W.jsx)(`div`,{className:`pt-2 border-t border-border/50`,children:t})]})}var KV=1023;function qV(e){return e===`/`?`canvas:home`:`canvas:${e.replace(/^\//,``)}`}function JV(e,t){if(e===`query:new`)return``;let n=e=>{let n=`/${e}`;for(let r of Object.keys(t))if(r===e||r.endsWith(n))return r;return null},r=e=>{let r=n(e);if(r===null)return null;let i=t[r],{meta:a,body:o}=fv(i),s=new Set([`search`,`template`,`route`,`type`,`title`,`description`,`subtitle`,`section`,`order`]);return Object.keys(a).some(e=>!s.has(e.trim().toLowerCase()))?i:o};if(e.startsWith(`markdown/`)){let t=r(e);if(t!==null)return t}let i=e;if(e.startsWith(`wods/examples/`))i=`markdown/canvas/`+e.replace(/^wods\/examples\//,``);else if(e.startsWith(`wods/`))i=`markdown/canvas/`+e.replace(/^wods\//,``);else if(e.startsWith(`canvas/`))i=`markdown/canvas/`+e.replace(/^canvas\//,``);else{let t=r(`markdown/canvas/`+e);if(t!==null)return t;i=`markdown/`+e}return r(i)??`# Source not found\n\nPath: \`${e}\`\nResolved: \`${i}\``}function YV(e){return(e.examples??[]).length>0||e.commands.some(e=>e.pipeline.length>0)}function XV(e){let t=new Map,n=null;for(let r of e)YV(r)&&(n=r),t.set(r.id,n);return t}function ZV(){let[e,t]=(0,U.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: ${KV}px)`).matches);return(0,U.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(max-width: ${KV}px)`),n=e=>t(e.matches);return e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var QV=`wodwiki:fabAlignment`,$V=[{id:`left`,label:`Bottom left`,description:`Left-handed — search and page actions float near your left thumb`},{id:`right`,label:`Bottom right`,description:`Right-handed — search and page actions float near your right thumb`}];function eH(){try{return tH(localStorage.getItem(QV))}catch{return}}function tH(e){return e===`right`||e===`left`?e:void 0}var nH=typeof window>`u`?void 0:eH();typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===QV&&(nH=tH(e.newValue))});function rH(e){nH=e;try{e===`right`?localStorage.removeItem(QV):localStorage.setItem(QV,e)}catch{}window.dispatchEvent(new StorageEvent(`storage`,{key:QV,newValue:e}))}function iH(){let[e,t]=(0,U.useState)(()=>nH??`right`);return(0,U.useEffect)(()=>{let e=e=>{e.key===QV&&t(tH(e.newValue)??`right`)};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),[e,rH]}function aH({onOpen:e}){return(0,W.jsxs)(`button`,{type:`button`,onClick:e,"aria-label":`Search`,title:`Search`,"data-testid":`search-fab`,className:G(`size-14 rounded-full flex items-center justify-center`,`bg-primary text-primary-foreground shadow-lg`,`hover:bg-primary/90 active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:[(0,W.jsx)(o,{className:`size-6`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Search`})]})}var oH=(0,U.createContext)(null),sH=(0,U.createContext)(!1),cH=(0,U.createContext)(null);function lH(){return(0,U.useContext)(oH)!==null}function uH({primary:e,navbar:t,children:n,label:r,fallback:i=!1}){let a=(0,U.useContext)(oH),o=(0,U.useContext)(sH),s=ZV(),c=(0,U.useId)(),l=a!==null&&!o&&s&&!i,u=a!==null&&i,d=(0,W.jsx)(sH.Provider,{value:!0,children:n});return(0,U.useEffect)(()=>{if(!(!l&&!u))return a.register({id:c,primary:e,navbar:t,children:d,label:r??`Page options`,fallback:i}),()=>a.unregister(c)},[l,u,a,c,e,d,r,i]),i||a&&s&&!o?null:(0,W.jsx)(sH.Provider,{value:!0,children:(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t,e,n]})})}function dH({onSearch:e,children:t}){let[n,r]=(0,U.useState)([]),i=(0,U.useCallback)(e=>r(t=>[...t.filter(t=>t.id!==e.id),e]),[]),a=(0,U.useCallback)(e=>r(t=>t.filter(t=>t.id!==e)),[]),o=(0,U.useMemo)(()=>({register:i,unregister:a}),[i,a]),s=(0,U.useMemo)(()=>{for(let e=n.length-1;e>=0;--e)if(!n[e].fallback)return n[e].navbar??null;return null},[n]);return(0,W.jsx)(oH.Provider,{value:o,children:(0,W.jsxs)(cH.Provider,{value:s,children:[t,(0,W.jsx)(pH,{registrations:n,onSearch:e})]})})}function fH(){let e=(0,U.useContext)(cH);return e?(0,W.jsx)(W.Fragment,{children:e}):null}function pH({registrations:e,onSearch:t}){let n=ZV(),[r]=iH(),i=HC(),[a,o]=(0,U.useState)(!1),s=(0,U.useRef)(null),c=(0,U.useRef)(null),l=(0,U.useRef)(null),u=(0,U.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(!e[t].fallback)return e[t]},[e]),d=(0,U.useMemo)(()=>{for(let t=e.length-1;t>=0;--t)if(e[t].fallback)return e[t]},[e]);(0,U.useLayoutEffect)(()=>{a&&s.current?.focus()},[a]);let[f,p]=(0,U.useState)({active:0,global:0});(0,U.useLayoutEffect)(()=>{let e=c.current?.childElementCount??0,t=l.current?.childElementCount??0;p(n=>n.active===e&&n.global===t?n:{active:e,global:t})},[u,d]);let m=f.active>0||f.global>0;return!n||!t&&!u&&!d?null:(0,W.jsxs)(`div`,{"data-testid":`actions-dock`,className:G(`lg:hidden relative z-40 mt-4 flex flex-col items-center gap-2`,`transition-[transform,visibility] duration-200 ease-out`,r===`left`?`self-start items-start`:`self-end items-end`),children:[(0,W.jsxs)(`div`,{className:`relative z-40 flex flex-col items-center gap-2`,children:[u?.primary&&(0,W.jsx)(`div`,{className:`[&_button]:min-h-11 [&_button]:min-w-11`,children:u.primary}),t&&(0,W.jsx)(aH,{onOpen:()=>{o(!1),t()}})]}),a&&m&&(0,W.jsx)(`button`,{type:`button`,tabIndex:-1,"aria-hidden":`true`,className:`fixed inset-0 z-30 cursor-default`,onClick:()=>o(!1)}),(0,W.jsxs)(`div`,{ref:s,role:`dialog`,"aria-label":u?.label??d?.label??`Page options`,tabIndex:-1,hidden:!a||!m,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),o(!1))},className:G(`relative z-40 flex w-60 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto rounded-2xl bg-card p-3 shadow-xl ring-1 ring-foreground/5 outline-none`,`[&_button]:min-h-11 [&_button]:min-w-11`),style:{maxHeight:`calc(${i.height===null?`100dvh`:`${i.height}px`} - 6rem - env(safe-area-inset-bottom))`},children:[(0,W.jsx)(`div`,{ref:c,className:`contents`,children:u?.children}),f.active>0&&f.global>0&&(0,W.jsx)(`div`,{className:`my-1 border-t border-border/60`,"aria-hidden":`true`}),(0,W.jsx)(`div`,{ref:l,className:`contents`,children:d?.children})]}),m&&(0,W.jsxs)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-label":u?.label??d?.label??`Page options`,title:u?.label??d?.label??`Page options`,"aria-expanded":a,"data-testid":`actions-overflow`,className:G(`relative z-40 flex size-12 items-center justify-center rounded-full`,`bg-card text-foreground shadow-lg ring-1 ring-foreground/10`,`hover:bg-muted active:scale-95 transition-all`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`),children:[a?(0,W.jsx)(er,{className:`size-6`}):(0,W.jsx)(ue,{className:`size-6`}),(0,W.jsx)(`span`,{className:`sr-only`,children:u?.label??d?.label??`Page options`})]})]})}function mH(){return(0,W.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,W.jsx)(`path`,{d:`M2 6.75C2 6.33579 2.33579 6 2.75 6H17.25C17.6642 6 18 6.33579 18 6.75C18 7.16421 17.6642 7.5 17.25 7.5H2.75C2.33579 7.5 2 7.16421 2 6.75ZM2 13.25C2 12.8358 2.33579 12.5 2.75 12.5H17.25C17.6642 12.5 18 12.8358 18 13.25C18 13.6642 17.6642 14 17.25 14H2.75C2.33579 14 2 13.6642 2 13.25Z`})})}function hH(){return(0,W.jsx)(`svg`,{"data-slot":`icon`,viewBox:`0 0 20 20`,"aria-hidden":`true`,className:`[&>[data-slot=icon]]:size-5`,children:(0,W.jsx)(`path`,{d:`M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z`})})}function gH(){let{tree:e,navState:t,contextNav:n}=mN(),r=ht(),i=eF();return!e.find(e=>e.id===t.activeL1Id)?.applyFooter||n?.pathname===r.pathname?null:(0,W.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,W.jsx)(`button`,{type:`button`,onClick:i,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})}function _H({open:e,close:t,onSearch:n,onCreate:r,children:i}){return(0,W.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,W.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,W.jsx)(A,{transition:!0,className:`fixed inset-y-0 left-0 w-full transition duration-300 ease-out data-closed:-translate-x-full`,children:(0,W.jsx)($P,{close:t,children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 bg-card`,children:[(0,W.jsx)(`div`,{className:`flex h-full w-14 shrink-0 flex-col items-center border-r border-zinc-950/5 bg-background/72 py-3 dark:border-white/5 [&_a]:size-11 [&_button]:size-11`,children:(0,W.jsx)(OB,{onSearch:()=>{t(),n?.()},onCreate:r?()=>{t(),r()}:void 0})}),(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,W.jsx)(`div`,{className:`flex items-center px-4 pt-3`,children:(0,W.jsxs)(it,{as:xR,"aria-label":`Close navigation`,title:`Close navigation`,children:[(0,W.jsx)(hH,{}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Close navigation`})]})}),(0,W.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:i}),(0,W.jsx)(gH,{})]})]})})})]})}function vH({open:e,close:t,children:n}){return(0,W.jsxs)(He,{open:e,onClose:t,className:`relative z-50 lg:hidden`,children:[(0,W.jsx)(Ke,{transition:!0,className:`fixed inset-0 bg-black/30 dark:bg-black/30 transition data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in`}),(0,W.jsx)(A,{transition:!0,className:`fixed inset-y-0 right-0 w-full transition duration-300 ease-out data-closed:translate-x-full`,children:(0,W.jsx)($P,{close:t,children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col bg-card`,children:[(0,W.jsx)(`div`,{className:`flex items-center justify-end px-4 pt-3`,children:(0,W.jsxs)(it,{as:xR,"aria-label":`Close page options`,title:`Close page options`,children:[(0,W.jsx)(hH,{}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Close page options`})]})}),(0,W.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-y-auto`,children:n}),(0,W.jsx)(`div`,{className:`shrink-0 border-t border-border/50 bg-card p-3`,children:(0,W.jsx)(`button`,{type:`button`,onClick:t,className:`h-11 w-full rounded-lg bg-primary text-sm font-medium text-primary-foreground`,children:`Apply`})})]})})})]})}function yH({navbar:e,sidebar:t,onSearch:n,onCreate:r,secondary:i,pageAction:a,hideDesktopSidebar:o,children:s}){let[c,l]=(0,U.useState)(!1),[u,d]=(0,U.useState)(!1),f=(0,U.useRef)(null),[p,m]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>m(t=>{let n=e.childElementCount>0;return t===n?t:n}),n=new MutationObserver(t);return n.observe(e,{childList:!0,subtree:!0}),t(),()=>n.disconnect()},[]);let{streamControls:h}=mN(),g=(0,U.useMemo)(()=>{let e=X(h?.query??``);return!e.error&&eh(e)&&e.filters.length>0},[h?.query]);return(0,W.jsx)(hV,{children:(0,W.jsx)(dH,{onSearch:n,children:(0,W.jsx)(`div`,{className:`relative isolate flex min-h-svh w-full bg-background max-lg:flex-col lg:flex-row`,children:(0,W.jsxs)(`div`,{className:`flex flex-1 w-full max-lg:flex-col lg:flex-row`,children:[(0,W.jsxs)(`nav`,{"aria-label":`Main`,className:`hidden lg:flex`,children:[(0,W.jsx)(`div`,{className:`w-14 shrink-0 sticky top-0 h-svh flex flex-col items-center border-r border-zinc-950/5 dark:border-white/5 bg-background/72 backdrop-blur-sm z-40 py-3`,children:(0,W.jsx)(OB,{onSearch:n??(()=>{}),onCreate:r})}),(0,W.jsx)(`div`,{className:G(`w-60 shrink-0 sticky top-0 self-start h-svh min-h-0 overflow-hidden border-r border-zinc-950/5 dark:border-white/5 bg-background/72 backdrop-blur-sm flex flex-col`,o&&`lg:hidden`),children:t})]}),(0,W.jsx)(_H,{open:c,close:()=>l(!1),onSearch:n,onCreate:r,children:t}),(0,W.jsxs)(`div`,{className:`flex flex-1 flex-col min-w-0 xl:max-w-[984px] 2xl:max-w-none`,children:[(0,W.jsxs)(`header`,{"data-page-sticky-boundary":`true`,className:`lg:hidden sticky top-0 z-20 flex items-center px-2 sm:px-4 bg-card`,children:[(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsxs)(xR,{onClick:()=>l(!0),"aria-label":`Open navigation`,title:`Open navigation`,children:[(0,W.jsx)(mH,{}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Open navigation`})]})}),(0,W.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),r&&(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsxs)(xR,{onClick:r,"aria-label":`New journal note`,title:`New journal note`,children:[(0,W.jsx)(dn,{className:`size-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`New journal note`})]})}),p&&(0,W.jsx)(`div`,{className:`py-2.5 shrink-0`,children:(0,W.jsxs)(xR,{onClick:()=>d(!0),"aria-label":`Open page options`,title:`Open page options`,children:[(0,W.jsxs)(`span`,{className:`relative inline-flex`,children:[(0,W.jsx)(Hn,{className:`size-5`}),g&&(0,W.jsx)(`span`,{"data-testid":`drawer-filters-active`,className:`absolute -top-1 -right-1 size-2 rounded-full bg-amber-500`,"aria-hidden":`true`})]}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Open page options`})]})})]}),(0,W.jsxs)(`main`,{className:`flex flex-1 flex-col lg:min-w-0`,children:[(0,W.jsx)(`div`,{className:`grow w-full max-lg:pb-48 lg:overflow-visible`,children:s}),(0,W.jsx)(bH,{})]})]}),(0,W.jsx)(`aside`,{className:`hidden 2xl:flex w-60 shrink-0 sticky top-0 h-svh flex-col overflow-y-auto bg-background/72 backdrop-blur-sm`,children:(0,W.jsx)(`div`,{ref:f,className:`contents`,children:(0,W.jsx)(GV,{spec:i,pageAction:a})})}),(0,W.jsx)(vH,{open:u,close:()=>d(!1),children:(0,W.jsx)(GV,{spec:i,pageAction:a})})]})})})})}function bH(){let e=(0,U.useRef)(null),[t,n]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=e.current;if(!t)return;let r=new ResizeObserver(e=>{let t=Math.round(e[0]?.contentRect.height??0);n(e=>e===t?e:t)});r.observe(t,{box:`content-box`});let i=Math.round(t.getBoundingClientRect().height);return n(e=>e===i?e:i),()=>r.disconnect()},[]),(0,U.useEffect)(()=>(document.documentElement.style.setProperty(`--thumb-dock-lift`,`${t}px`),()=>document.documentElement.style.setProperty(`--thumb-dock-lift`,`0px`)),[t]),(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:G(`lg:hidden fixed inset-x-0 bottom-0 z-30`,t>0&&`bg-card border-t border-border/50 px-3 py-2`),children:(0,W.jsx)(`div`,{ref:e,className:`w-full min-w-0`,children:(0,W.jsx)(gV,{className:`flex w-full min-w-0`})})}),(0,W.jsx)(`div`,{className:`lg:hidden`,"aria-hidden":`true`,style:{height:t}})]})}function xH(e){let t=e.indexOf(`markdown`);return t!==-1&&e.length>t+2?e[t+2]:`General`}function SH(e){return String(ib(Qy(e).meta,`search`)??``).toLowerCase()===`hidden`}function CH(e){let t=ib(Qy(e).meta,`date`);if(typeof t!=`string`||!/^\d{4}-\d{2}-\d{2}$/.test(t))return;let n=new Date(`${t}T12:00:00Z`);return Number.isFinite(n.getTime())&&n.toISOString().slice(0,10)===t?n.getTime():void 0}function wH(e){return Object.entries(e).map(([e,t])=>{let n=e.split(`/`),r=n[n.length-1].replace(`.md`,``),i=t,a=ib(Qy(i).meta,`title`);return{id:e,name:r,displayName:typeof a==`string`&&a.trim()?a.trim():ZO(r),category:xH(n),content:i,date:CH(i),searchHidden:SH(i)}})}function TH(){let e=bk();return(0,U.useMemo)(()=>e?wH(e):[],[e])}var EH={};function DH(e){if(!(`payload`in e))return;let t=e.payload;if(!t||typeof t!=`object`)return;let n=t;return n.targetDate??n.updatedAt}function OH(e,t){let{canvasPage:n,workoutItems:r,recentResults:i,selectWorkout:a}=t;if(e===`/`)return[];if(n){let t=/^\/notebook\//.test(e),i=t?e.split(`/`).pop()??null:null,o=[],s=e.startsWith(`/page/guide-`);return n.sections.filter(e=>e.level>1).forEach(e=>{if(o.push({id:e.id,label:e.heading,type:`heading`}),!s){let t=UL(e).split(`
103
103
  `),n=0;t.forEach((t,r)=>{let i=t.trim().match(/^```(time|log)(:\w+)?\s*$/);if(i){let t=i[1];n++,o.push({id:`${e.id}-${t}-${r+1}`,label:`Workout ${n}`,type:t})}})}}),t&&i&&(o.push({id:`notebook-workouts`,label:`Explore`,type:`heading`}),r.filter(e=>e.category===i&&e.name.toLowerCase()!==`readme`).forEach(e=>{o.push({id:`workout-${e.id}`,label:e.name,type:`time`,onRun:()=>a(e),runIcon:`link`})})),o}if(e===`/journal`){let e=new Set;return i.forEach(t=>{let n=new Date(t.createdAt).getTime();Number.isFinite(n)&&e.add(VP(new Date(n)))}),r.forEach(t=>{let n=DH(t);n&&Number.isFinite(new Date(n).getTime())&&e.add(VP(new Date(n)))}),Array.from(e).sort().reverse().slice(0,10).map(e=>({id:e,label:Ky(new Date(e+`T00:00:00`)),type:`heading`}))}return[]}var kH=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function AH(e){return kH.test(e)}function jH(e){try{return decodeURIComponent(e)}catch{return null}}function MH(e){if(!WP(e))return!1;let t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return!1;let n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])));return n.getUTCFullYear()===Number(t[1])&&n.getUTCMonth()===Number(t[2])-1&&n.getUTCDate()===Number(t[3])}function NH(e){let t=(e.length>1?e.replace(/\/+$/,``):e).match(/^\/day\/([^/]+)$/);if(!t)return{kind:`invalid`};let n=jH(t[1]);return n!=null&&MH(n)?{kind:`date`,date:n}:{kind:`invalid`}}var PH=`# My Workout Notebook
104
104
 
105
105
  Welcome to the **WOD.WIKI** playground.
@@ -158,7 +158,7 @@ Timer 12:00
158
158
  border border-border/80 shadow-xl rounded-lg overflow-hidden pointer-events-auto`,style:{top:O,maxHeight:200},children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 bg-muted/40 border-b border-border/50 shrink-0`,children:[(0,W.jsx)(`span`,{className:`text-[11px] font-mono px-2 py-0.5 rounded bg-metric-time/10 text-metric-time uppercase tracking-wider font-semibold`,children:m.type}),(0,W.jsxs)(`div`,{className:`flex items-center min-w-0 gap-2`,children:[(0,W.jsxs)(`span`,{className:`text-xs text-muted-foreground/60`,children:[`L`,E]}),(0,W.jsx)(`span`,{className:`text-muted-foreground/40`,children:`·`}),(0,W.jsx)(`span`,{className:`text-xs font-mono text-foreground/90 truncate font-medium`,title:T,children:T||(0,W.jsx)(`span`,{className:`italic text-muted-foreground`,children:`—`})})]})]}),(0,W.jsx)(`div`,{className:`px-3 py-2.5 min-h-0 overflow-auto`,children:C.length>0?(0,W.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:C.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 px-2 py-1 rounded-md text-sm font-semibold ${e.color}`,title:e.label,children:[(0,W.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,W.jsx)(`span`,{className:`font-mono tracking-tight`,children:e.value})]},t))}):(0,W.jsx)(`span`,{className:`text-xs italic text-muted-foreground`,children:`No metrics on this line`})}),w&&(0,W.jsx)(MY,{summary:w}),(0,W.jsx)(`div`,{className:`border-t border-border/40 shrink-0`,children:(0,W.jsx)(IY,{commands:d,section:m,view:n})})]})]})},RY=({sectionId:e,widgetName:t,view:n,registry:r,docVersion:i})=>{let{rawContent:a,config:o}=(0,U.useMemo)(()=>{let t=n.state.field(NT).sections.find(t=>t.id===e),r=t?.contentFrom!==void 0&&t?.contentTo!==void 0?n.state.doc.sliceString(t.contentFrom,t.contentTo).trim():``,i={};if(r)try{i=JSON.parse(r)}catch{}return{rawContent:r,config:i}},[n,e,i]),s=r.get(t);return s?(0,W.jsx)(`div`,{className:`h-full w-full overflow-hidden rounded-l-md border-l border-border bg-background shadow-sm`,children:(0,W.jsx)(s,{config:o,rawContent:a,sectionId:e})}):(0,W.jsxs)(`div`,{className:`flex h-full w-full items-center justify-center rounded-l-md border-l border-border bg-muted/60 p-4 text-xs text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`font-mono`,children:[`widget:`,t]}),(0,W.jsx)(`span`,{className:`ml-2 opacity-60`,children:`— not registered`})]})};function zY(e,t,n,r,i){switch(t.type){case`fixed-field`:return BY(e,t);case`metric-type`:return VY(e,t);case`derived`:return HY(e,t,n,r,i);case`fallback`:return UY(e,t,n,r,i);default:return}}function BY(e,t){return e[t.field]}function VY(e,t){return e.cells.get(t.metricType)}function HY(e,t,n,r,i){let a=new Map;if(t.dependencies&&r)for(let o of t.dependencies){if(i?.includes(o))throw Error(`Circular dependency detected in column '${o}': ${(i??[]).join(` -> `)} -> ${o}`);let t=r.get(o);if(t){let s=zY(e,t.source,n,r,[...i??[],o]);a.set(o,s)}}let o={...n,allRows:n?.allRows??[e],rowIndex:n?.rowIndex??0,columnDef:n?.columnDef??{id:`unknown`,label:``,source:t,format:{type:`text`}},dependencies:a,...t.context};return t.compute(e,o)}function UY(e,t,n,r,i){return WY(e,t,n,r,i)}function WY(e,t,n,r,i){if(!(!t.sources||t.sources.length===0))switch(t.semantics){case`first-present`:return GY(e,t.sources,n,r,i);case`all-present-joined`:return KY(e,t.sources,t.joinString,n,r,i);case`all-present-combined`:return qY(e,t.sources,n,r,i);default:return}}function GY(e,t,n,r,i){for(let a of t){let t=zY(e,a,n,r,i);if(t!=null)return t}}function KY(e,t,n,r,i,a){let o=[];for(let n of t){let t=zY(e,n,r,i,a);if(t==null)return;o.push(t)}let s=n??` `;return o.map(e=>YY(e)).join(s)}function qY(e,t,n,r,i){let a=[];for(let o of t){let t=zY(e,o,n,r,i);if(t==null)return;a.push(t)}return a}function JY(e){if(e==null)return``;let t=Array.isArray(e)?e:e instanceof la?e.toArray():[];if(t.length===0)return``;let n=t[0];if(typeof n==`object`&&n){if(`image`in n&&typeof n.image==`string`)return n.image;if(`value`in n&&n.value!==void 0)return String(n.value)}return String(n)}function YY(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`object`&&`metrics`in e){let t=JY(e.metrics);if(t.length>0)return t}return String(e)}function XY(e,t,n,r){if(!t.sort)return``;let i=zY(e,t.source,n,r);return(t.sort.type===`custom`?typeof i==`number`||typeof i==`string`?i:String(i??``):t.sort.extractor(i))??``}function ZY(e,t){if(typeof e==`number`&&typeof t==`number`)return Number.isNaN(e)&&Number.isNaN(t)?0:Number.isNaN(e)?1:Number.isNaN(t)?-1:e-t;let n=String(e??``),r=String(t??``),i=parseFloat(n),a=parseFloat(r);return!Number.isNaN(i)&&!Number.isNaN(a)&&n===String(i)&&r===String(a)?i-a:n.localeCompare(r)}function QY(e,t,n,r){if(!t.graph)return;let i=zY(e,t.source,n,r);return t.graph.extractor(i)}function $Y(e,t,n,r){if(!t.filter)return``;let i=zY(e,t.source,n,r);return t.filter.extractor(i)??``}function eX(e,t,n,r,i){if(!n||n.trim().length===0||!t.filter)return!0;let a=$Y(e,t,r,i),o=t.filter.caseInsensitive===!1?n.trim():n.trim().toLowerCase(),s=t.filter.caseInsensitive===!1?a:a.toLowerCase();return t.filter.matcher?t.filter.matcher(s,o):s.includes(o)}var tX=({metric:e})=>{let t=e.origin===`hinted`||e.image===`?`,n=(0,U.useMemo)(()=>zW(wo.present(e,`review-grid-cell`)),[e]);return(0,W.jsxs)(`span`,{className:[`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium border transition-all`,t?`bg-warning/10 border-warning/40 text-warning animate-pulse-opacity`:`${n.colorClasses} ${n.originClasses}`].join(` `),title:t?`Missing value - click to fill`:n.tooltip,children:[t&&(0,W.jsx)(`span`,{className:`mr-0.5 text-[10px]`,children:`◉`}),n.label,n.userEntered&&!t&&(0,W.jsx)(`span`,{className:`text-[10px] opacity-70 ml-0.5`,children:`👤`})]})},nX=({columnDef:e,row:t,allRows:n,rowIndex:r,indent:i=0,onDoubleClick:a,className:o,style:s,definitionMap:c})=>{let l=(0,U.useRef)(null),u=(0,U.useMemo)(()=>{if(!(!n||r===void 0))return{allRows:n,rowIndex:r,columnDef:e,dependencies:new Map}},[n,r,e]),d=(0,U.useMemo)(()=>zY(t,e.source,u,c),[t,e.source,u,c]),f=e.source.type===`metric-type`,p=(0,U.useCallback)(n=>{if(n.stopPropagation(),f&&a&&l.current){let n=l.current.getBoundingClientRect();a(t.sourceBlockKey,e.source.metricType,n)}},[f,e.source,t.sourceBlockKey,a]),m=(0,U.useMemo)(()=>rX(d,e.format,i,t),[d,e.format,i,t]);return(0,W.jsx)(`td`,{ref:l,className:G(`py-1 px-2`,f&&`cursor-cell`,o),style:s,onDoubleClick:p,children:m})};function rX(e,t,n,r){if(e==null)return(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[gX(n),(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]});switch(t.type){case`text`:return iX(e,t,n);case`time`:return aX(e,t);case`number`:return oX(e,t);case`badge`:return sX(e,t);case`pill`:return cX(e,t);case`combined`:return uX(e,t,n);case`custom`:return fX(e,t,r);default:return mX(e,n)}}function iX(e,t,n){let r=t.transform?t.transform(e):_X(e);return(0,W.jsxs)(`span`,{className:G(`inline-flex items-center gap-1`,t.className),children:[gX(n),r]})}function aX(e,t){let n=vX(e);if(n==null||!Number.isFinite(n))return(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r;switch(t.style){case`long`:r=nW(n);break;case`precise`:r=`${n.toFixed(2)}s`;break;default:r=tW(n)}return t.transform&&(r=t.transform(r)),(0,W.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:r})}function oX(e,t){let n=vX(e);if(n==null||!Number.isFinite(n))return(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});let r=t.decimals??0,i=n.toFixed(r)+(t.unit??``);return t.transform?(0,W.jsx)(`span`,{children:t.transform(i)}):(0,W.jsx)(`span`,{children:i})}function sX(e,t){let n=t.styleResolver(e),r=t.textResolver(e);return(0,W.jsxs)(`span`,{className:G(`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium`,n.className),title:n.title,children:[n.icon&&(0,W.jsx)(`span`,{className:`mr-0.5`,children:n.icon}),r]})}function cX(e,t){let n=t.transform?t.transform(e):_X(e),r=t.backgroundColor??`bg-muted`,i=t.borderRadius??`rounded`;return(0,W.jsx)(`span`,{className:G(`inline-block px-1.5 py-0.5 text-xs font-medium`,r,i),children:n})}var lX={primary:`text-sm font-semibold text-foreground`,secondary:`text-xs text-muted-foreground`,tertiary:`text-[11px] text-muted-foreground opacity-80`};function uX(e,t,n,r){let[i,a,o]=Array.isArray(e)?e:[e],s=i===void 0?null:dX(i,t.primaryFormat??{type:`text`},r,`primary`),c=a===void 0?null:dX(a,t.secondaryFormat??{type:`text`},r,`secondary`),l=o===void 0?null:dX(o,t.tertiaryFormat??{type:`text`},r,`tertiary`),u=t.layout===`horizontal`;return(0,W.jsxs)(`div`,{className:G(`inline-flex`,u?`flex-row items-center gap-1`:`flex-col items-start gap-0.5`,t.containerClassName),children:[gX(n),s,c&&(0,W.jsxs)(W.Fragment,{children:[u&&t.separator&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),c]}),l&&(0,W.jsxs)(W.Fragment,{children:[u&&t.separator&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:t.separator}),l]})]})}function dX(e,t,n,r){let i=rX(e,t,0,n);return r?(0,W.jsx)(`span`,{className:G(`inline-flex items-center`,lX[r]),children:i}):i}function fX(e,t,n){let r=n?{...t.context,row:n}:t.context;return t.render(e,r)}function pX(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function mX(e,t){return e?.metrics?hX(e,t):(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[gX(t),_X(e)]})}function hX(e,t){let n=pX(e);return n.length===0?(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[gX(t),(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`})]}):(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-1 items-center`,children:[gX(t),n.map((e,t)=>(0,W.jsx)(tX,{metric:e},t))]})}function gX(e){return e<=0?null:(0,W.jsx)(`div`,{className:`flex-shrink-0 mr-1 border-l-2 border-muted h-4`,style:{width:`${e*1.25}rem`,marginLeft:`2px`}})}function _X(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);let t=pX(e);if(t.length>0){let e=t[0];if(e?.image)return e.image;if(e?.value!==void 0)return String(e.value)}return String(e)}function vX(e){if(e==null)return;if(typeof e==`number`)return e;if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}let t=pX(e);if(t.length>0&&typeof t[0]?.value==`number`)return t[0].value}var yX=e=>e;function bX(e){let t=e?.metrics;if(!t)return[];if(Array.isArray(t))return t;if(typeof t==`object`&&t&&`toArray`in t){let e=t;if(typeof e.toArray==`function`)return e.toArray()}return[]}function xX(e){let t=bX(e);if(t.length===0)return;let n=t[0];return typeof n?.value==`number`?n.value:n?.image?n.image:String(n?.value??``)}function SX(e){let t=bX(e);for(let e of t)if(typeof e?.value==`number`)return e.value}function CX(e){return bX(e).map(e=>e.image??String(e.value??``)).join(`, `)}function wX(e){return e==null?``:Array.isArray(e)?e.map(e=>wX(e)).filter(Boolean).join(` — `):typeof e==`string`?e:typeof e==`number`?String(e):CX(e)}function TX(e){switch(e){case q.Duration:case q.Rep:case q.Distance:case q.Rounds:case q.Resistance:case q.Increment:case q.Metric:case q.Volume:case q.Intensity:case q.Load:case q.Work:case q.CurrentRound:case q.Calculated:return!0;default:return!1}}function EX(e){switch(e){case q.Duration:return`s`;case q.Rep:return`reps`;case q.Distance:return`m`;case q.Rounds:return`rounds`;case q.Resistance:return`kg`;case q.Increment:return`Δ`;case q.Calculated:case q.Custom:return``;default:return``}}function DX(e,t){let n=so(e),r=xW(e)??void 0,i=t?.graphable??TX(e);return{id:e,label:n,icon:r,source:{type:`metric-type`,metricType:e},format:{type:`custom`,render:e=>hX(e,0)},sort:TX(e)?{type:`numeric`,extractor:e=>SX(e)}:{type:`text`,extractor:e=>{let t=xX(e);return t===void 0?void 0:String(t)}},graph:i?{extractor:e=>SX(e),axisLabel:n,unit:EX(e)}:void 0,filter:{extractor:e=>CX(e),caseInsensitive:!0},meta:{defaultVisible:t?.defaultVisible??!0,debugOnly:t?.debugOnly,tags:[e]}}}function OX(e){switch(e){case`segment`:return`bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-200`;case`milestone`:return`bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-200`;case`system`:return`bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400`;case`event`:return`bg-purple-100 text-purple-800 dark:bg-purple-900/50 dark:text-purple-200`;case`group`:return`bg-indigo-100 text-indigo-800 dark:bg-indigo-900/50 dark:text-indigo-200`;case`load`:return`bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-200`;case`compiler`:return`bg-pink-100 text-pink-800 dark:bg-pink-900/50 dark:text-pink-200`;default:return`bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300`}}function kX(e,t){if(!e||e.length===0)return``;let n=e=>tW(e);if(t===0)return n(e[0].started);let r=n(e[0].started),i=e[e.length-1];if(i.ended===void 0)return r;let a=n(i.ended);return r===a?r:`${r} — ${a}`}function AX(e,t=!0){if(e===void 0||e===0)return``;let n=new Date(e),r=n.getHours().toString().padStart(2,`0`),i=n.getMinutes().toString().padStart(2,`0`),a=n.getSeconds().toString().padStart(2,`0`);return t?`${r}:${i}:${a}.${n.getMilliseconds().toString().padStart(3,`0`)}`:`${r}:${i}:${a}`}function jX({value:e}){let t=e.match(/^(-?)(\d+)(:\d{2})(?::\d{2})?(\.\d+)?$/);if(!t)return(0,W.jsx)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:e});let[,n,r,i,a,o]=t,s=i.slice(1);return(0,W.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap inline-flex items-baseline`,children:[n&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:n}),(0,W.jsx)(`span`,{className:`font-semibold text-foreground`,children:r}),(0,W.jsxs)(`span`,{className:`text-muted-foreground/60`,children:[`:`,s]}),a&&(0,W.jsx)(`span`,{className:`text-muted-foreground/40`,children:a}),o&&(0,W.jsx)(`span`,{className:`text-muted-foreground/30 text-[10px]`,children:o})]})}function MX({elapsed:e,duration:t}){let n=tW(e);return(0,W.jsxs)(`span`,{className:`inline-flex items-baseline gap-0.5`,children:[(0,W.jsx)(jX,{value:n}),t!==void 0&&t>0&&t!==e&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`text-muted-foreground/40 mx-0.5`,children:`/`}),(0,W.jsx)(`span`,{className:`opacity-60`,children:(0,W.jsx)(jX,{value:tW(t)})})]})]})}var NX={id:`#`,label:`#`,source:{type:`derived`,compute:e=>({index:e.index,outputType:e.outputType,sourceBlockKey:e.sourceBlockKey})},format:{type:`custom`,render:e=>{let{index:t,outputType:n,sourceBlockKey:r}=e??{};return(0,W.jsx)(`span`,{className:G(`font-mono text-[11px] w-8 text-right inline-block`,OX(n)),title:`Type: ${n}\nBlock: ${r}`,children:t})}},sort:{type:`numeric`,extractor:e=>yX(e)?.index||0},meta:{tags:[`layout`],defaultVisible:!0,width:`40px`,resizable:!1}},PX={id:`timestamp`,label:`Timestamp`,source:{type:`fixed-field`,field:`absoluteStartTime`},format:{type:`custom`,render:(e,t)=>{let n=e,r=yX(t)?.hideMs!==!1;return(0,W.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-24 whitespace-nowrap`,children:AX(n,r)})},context:{hideMs:!1}},sort:{type:`numeric`,extractor:e=>yX(e)?.absoluteStartTime??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},FX={id:`spans`,label:`Time`,source:{type:`derived`,compute:e=>({spans:e.spans,duration:e.duration})},format:{type:`custom`,render:e=>{let{spans:t,duration:n}=e??{};return(0,W.jsx)(`span`,{className:`text-muted-foreground font-mono text-[10px] text-center w-40 whitespace-nowrap`,children:kX(t,n)})}},sort:{type:`numeric`,extractor:e=>(yX(e)?.spans)?.[0]?.started??0},meta:{tags:[`timing`,`layout`],defaultVisible:!0}},IX={id:`timeSpan`,label:`Time`,source:{type:`derived`,compute:e=>({timestamp:e.absoluteStartTime,elapsed:e.elapsed,duration:e.duration})},format:{type:`custom`,render:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{};return n===void 0?(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`}):(0,W.jsxs)(`div`,{className:`flex flex-col items-start gap-0 leading-tight`,children:[t!==void 0&&t>0&&(0,W.jsx)(`span`,{className:`text-muted-foreground/50 font-mono text-[10px] whitespace-nowrap`,children:AX(t,!1)}),(0,W.jsx)(MX,{elapsed:n,duration:r})]})}},sort:{type:`numeric`,extractor:e=>yX(e)?.elapsed??0},graph:{extractor:e=>yX(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`},filter:{extractor:e=>{let{timestamp:t,elapsed:n,duration:r}=e??{},i=[];return t!==void 0&&t>0&&i.push(AX(t,!1)),n!==void 0&&i.push(tW(n)),r!==void 0&&r>0&&r!==n&&i.push(tW(r)),i.join(` `)},caseInsensitive:!0},meta:{tags:[`timing`,`compound`],defaultVisible:!0,width:`100px`,subsumes:[`duration`,`elapsedTotal`]}},LX={id:`blockKey`,label:`Block`,source:{type:`fixed-field`,field:`sourceBlockKey`},format:{type:`text`,className:`truncate max-w-[160px] text-sm`},sort:{type:`text`,extractor:e=>yX(e)?.sourceBlockKey??``},filter:{extractor:e=>yX(e)?.sourceBlockKey??``,caseInsensitive:!0},meta:{tags:[`layout`],defaultVisible:!1}},RX={id:`outputType`,label:`Type`,source:{type:`fixed-field`,field:`outputType`},format:{type:`custom`,render:e=>{let t=String(e??``);return(0,W.jsx)(`span`,{className:G(`text-xs px-1.5 py-0.5 rounded font-medium`,OX(t)),children:t})}},sort:{type:`text`,extractor:e=>yX(e)?.outputType??``},filter:{extractor:e=>yX(e)?.outputType??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1}},zX={id:`stackLevel`,label:`Depth`,source:{type:`fixed-field`,field:`stackLevel`},format:{type:`text`,className:`text-muted-foreground font-mono text-xs text-center w-12`},sort:{type:`numeric`,extractor:e=>yX(e)?.stackLevel??0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},BX={id:`elapsedTotal`,label:`Elapsed`,source:{type:`derived`,compute:e=>({elapsed:e.elapsed,total:e.total})},format:{type:`custom`,render:e=>{let{elapsed:t,total:n}=e??{};if(t===void 0||n===void 0)return``;let r=t===n?tW(t):`${tW(t)} / ${tW(n)}`;return(0,W.jsx)(`span`,{className:`text-foreground font-mono text-xs text-right w-32 whitespace-nowrap`,children:r})}},sort:{type:`numeric`,extractor:e=>yX(e)?.elapsed??0},graph:{extractor:e=>yX(e)?.elapsed,axisLabel:`Elapsed`,unit:`s`,color:`#14b8a6`},meta:{tags:[`timing`],defaultVisible:!1}},VX={id:`completionReason`,label:`Reason`,source:{type:`fixed-field`,field:`completionReason`},format:{type:`text`,className:`text-muted-foreground text-xs truncate max-w-[120px]`},sort:{type:`text`,extractor:e=>yX(e)?.completionReason??``},filter:{extractor:e=>yX(e)?.completionReason??``,caseInsensitive:!0},meta:{tags:[`debug`],defaultVisible:!1,debugOnly:!0}},HX=DX(q.Effort,{defaultVisible:!1}),UX=DX(q.Duration,{debugOnly:!0}),WX=DX(q.Rep),GX=DX(q.Rounds,{defaultVisible:!1}),KX=DX(q.Distance),qX=DX(q.Resistance),JX=DX(q.Action),YX=DX(q.Increment),XX=DX(q.Metric),ZX=DX(q.Calculated),QX=DX(q.Custom,{defaultVisible:!1}),$X=DX(q.Group,{defaultVisible:!1}),eZ=DX(q.System,{defaultVisible:!1}),tZ=DX(q.Label,{defaultVisible:!1}),nZ=DX(q.Text),rZ=DX(q.CurrentRound,{defaultVisible:!1}),iZ=DX(q.Volume),aZ=DX(q.Intensity),oZ=DX(q.Load),sZ=DX(q.Work),cZ=DX(q.Diagnostic),lZ=[NX,IX,PX,FX,LX,RX,zX,BX,VX,{id:`exercise`,label:`Exercise`,icon:xW(q.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`fallback`,semantics:`all-present-combined`,sources:[{type:`metric-type`,metricType:q.Effort},{type:`metric-type`,metricType:q.Text}]},{type:`metric-type`,metricType:q.Text},{type:`metric-type`,metricType:q.Label},{type:`metric-type`,metricType:q.Effort}]},format:{type:`combined`,layout:`vertical`,primaryFormat:{type:`text`,className:`font-medium text-foreground`},secondaryFormat:{type:`text`,className:`text-muted-foreground text-xs`},containerClassName:`items-start`},sort:{type:`text`,extractor:e=>wX(e)},filter:{extractor:e=>wX(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`grouping`,`fallback`,`descriptor`],subsumes:[`effort`,`text`,`label`]}},{id:`descriptor`,label:`Descriptor`,icon:xW(q.Effort)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:q.Effort},{type:`metric-type`,metricType:q.Label},{type:`metric-type`,metricType:q.Rounds},{type:`metric-type`,metricType:q.CurrentRound}]},format:{type:`custom`,render:e=>hX(e,0)},sort:{type:`text`,extractor:e=>wX(e)},filter:{extractor:e=>wX(e),caseInsensitive:!0},meta:{defaultVisible:!0,subsumes:[`effort`,`label`,`rounds`,`current-round`]}},HX,nZ,tZ,UX,{id:`pace`,label:`Pace`,icon:`⏱️`,source:{type:`derived`,dependencies:[`distance`,`duration`],compute:(e,t)=>{let n=SX(t.dependencies.get(`distance`)),r=SX(t.dependencies.get(`duration`));if(!(!n||!r))return n/r}},format:{type:`custom`,render:e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return(0,W.jsx)(`span`,{className:`text-muted-foreground opacity-40`,children:`—`});let t=1e3/e;return(0,W.jsxs)(`span`,{className:`font-mono text-xs whitespace-nowrap`,children:[tW(t),`/km`]})}},sort:{type:`numeric`,extractor:e=>typeof e==`number`?e:void 0},graph:{extractor:e=>typeof e==`number`?e:void 0,axisLabel:`Pace`,unit:`m/s`},filter:{extractor:e=>typeof e!=`number`||!Number.isFinite(e)||e<=0?``:`${tW(1e3/e)}/km`,caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`endurance`,`derived`]}},WX,GX,KX,qX,JX,YX,XX,ZX,QX,rZ,iZ,aZ,{id:`loadFocus`,label:`Load`,icon:xW(q.Load)??xW(q.Resistance)??void 0,source:{type:`fallback`,semantics:`first-present`,sources:[{type:`metric-type`,metricType:q.Load},{type:`metric-type`,metricType:q.Resistance}]},format:{type:`custom`,render:e=>hX(e,0)},sort:{type:`numeric`,extractor:e=>SX(e)},graph:{extractor:e=>SX(e),axisLabel:`Load`,unit:`kg`},filter:{extractor:e=>CX(e),caseInsensitive:!0},meta:{defaultVisible:!1,tags:[`strength`,`fallback`]}},oZ,sZ,cZ,$X,eZ],uZ={outputTypes:[`segment`,`milestone`,`group`,`analytics`]},dZ={definitions:lZ,presets:{default:{label:`Default`,filters:uZ,visibleColumnIds:[`#`,`timeSpan`,`descriptor`,`rep`,`distance`,`resistance`,`action`,`increment`,`metric`,`calculated`,`custom`,`volume`,`intensity`,`load`,`work`,`diagnostic`]},debug:{label:`Debug`,filters:{},visibleColumnIds:`#.timeSpan.timestamp.spans.blockKey.outputType.stackLevel.descriptor.duration.rep.distance.resistance.action.increment.metric.calculated.custom.volume.intensity.load.work.diagnostic.group.system.elapsedTotal.completionReason`.split(`.`)},strength:{label:`Strength`,filters:uZ,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`rep`,`loadFocus`,`volume`,`intensity`,`load`,`work`,`elapsedTotal`]},endurance:{label:`Endurance`,filters:uZ,visibleColumnIds:[`#`,`timeSpan`,`exercise`,`distance`,`duration`,`pace`,`rounds`,`increment`,`work`,`elapsedTotal`]}},defaultPreset:`default`},fZ=class{config;definitionMap;constructor(e){this.config=e,this.definitionMap=new Map(e.definitions.map(e=>[e.id,e]))}getVisibleColumns(e){return this.getOrderedCandidates(e).filter(t=>this.computeVisibility(t.id,e))}getAvailableColumns(e){let t=new Set(this.getVisibleColumns(e).map(e=>e.id));return this.config.definitions.filter(n=>!t.has(n.id)&&this.isColumnAvailable(n,e))}getGraphableColumns(e){return this.getVisibleColumns(e).filter(e=>e.graph!==void 0)}getGraphTaggedColumns(e){let t=e.graphTaggedColumnIds;return!t||t.size===0?[]:this.getVisibleColumns(e).filter(e=>t.has(e.id))}isColumnVisible(e,t){return this.getDefinition(e)?this.computeVisibility(e,t):!1}getDefinition(e){return this.definitionMap.get(e)}getPreset(e){return this.config.presets[e]??this.config.presets[this.config.defaultPreset]}getAllDefinitions(){return this.config.definitions}get definitions(){return this.definitionMap}resolveColumnValue(e,t,n,r){let i=this.getDefinition(t);if(!i)return;let a={allRows:n,rowIndex:r??n.findIndex(t=>t.id===e.id),columnDef:i,dependencies:new Map};return zY(e,i.source,a,this.definitionMap)}getOrderedCandidates(e){let t=this.getPreset(e.activePresetId),n=[],r=new Set,i=e=>{if(r.has(e))return;let t=this.getDefinition(e);t&&(n.push(t),r.add(e))};for(let e of t.visibleColumnIds)i(e);for(let e of this.config.definitions)i(e.id);if(e.addedColumnIds)for(let t of e.addedColumnIds)i(t);return n}computeVisibility(e,t,n){if(t.visibilityOverrides&&e in t.visibilityOverrides)return t.visibilityOverrides[e];if(t.addedColumnIds?.has(e))return!0;let r=this.getDefinition(e);if(!r||r.meta?.debugOnly&&!t.isDebugMode||!n&&this.isColumnSubsumed(e,t))return!1;let i=this.getPreset(t.activePresetId).visibleColumnIds.includes(e),a=this.hasDataInRows(r,t.rows);switch(r.source.type){case`fixed-field`:return i;case`derived`:return i;case`metric-type`:return a;case`fallback`:return i&&a;default:return i}}isColumnSubsumed(e,t){for(let n of this.config.definitions)if(n.meta?.subsumes?.length&&this.getPreset(t.activePresetId).visibleColumnIds.includes(n.id)&&n.meta.subsumes.includes(e))return!0;return!1}isColumnAvailable(e,t){return e.meta?.debugOnly&&!t.isDebugMode?!1:this.getPreset(t.activePresetId).visibleColumnIds.includes(e.id)?!this.computeVisibility(e.id,t):e.source.type===`fixed-field`||e.source.type===`derived`||this.hasDataInRows(e,t.rows)}hasDataInRows(e,t){if(t.length===0)return!1;switch(e.source.type){case`fixed-field`:return!0;case`metric-type`:{let{metricType:n}=e.source;return t.some(e=>e.cells.has(n))}case`derived`:return!0;case`fallback`:{let{sources:n}=e.source;return t.some(e=>n.some(t=>this.sourceHasDataInRow(t,e)))}default:return!0}}sourceHasDataInRow(e,t){switch(e.type){case`fixed-field`:return t[e.field]!==void 0&&t[e.field]!==null;case`metric-type`:return t.cells.has(e.metricType);case`derived`:return!0;case`fallback`:return e.sources.some(e=>this.sourceHasDataInRow(e,t));default:return!1}}};function pZ(e){let{segments:t,userOutputOverrides:n,presetId:r,isDebugMode:i,sortConfigs:a,filterOverrides:o,graphTaggedColumns:s,extraMetricTypes:c,columnVisibilityOverrides:l,addedColumnIds:u}=e,d=(0,U.useMemo)(()=>mZ(t,n),[t,n]),f=(0,U.useMemo)(()=>{let e=[...dZ.definitions],t=new Set(e.map(e=>e.id));for(let n of d)for(let r of n.cells.keys())t.has(r)||(e.push(DX(r)),t.add(r));return new fZ({...dZ,definitions:e})},[d]),p=(0,U.useMemo)(()=>{let e=new Set(u??[]);for(let t of c??[])e.add(t);return e},[u,c]),m=(0,U.useMemo)(()=>({rows:d,activePresetId:r,isDebugMode:i,graphTaggedColumnIds:s,visibilityOverrides:l,addedColumnIds:p}),[d,r,i,s,l,p]),h=(0,U.useMemo)(()=>f.getVisibleColumns(m),[f,m]),g=(0,U.useMemo)(()=>f.getAvailableColumns(m),[f,m]),_=(0,U.useMemo)(()=>({...f.getPreset(r).filters??{},...o}),[r,o,f]);return{rows:(0,U.useMemo)(()=>vZ(_Z(d,_,h,f.definitions),a,h,f.definitions),[d,_,a,h,f]),visibleColumns:h,availableColumns:g,graphTaggedColumnIds:(0,U.useMemo)(()=>Array.from(s??[]),[s])}}function mZ(e,t){return e.map((e,n)=>{let r=new Map;if(e.metrics)for(let t of e.metrics)gZ(r,t);let i=hZ(e),a=i?t.get(i):void 0;if(a)for(let e of a)gZ(r,e);for(let[,e]of r)e.hasUserOverride=e.metrics.some(e=>e.origin===`user`);let o=e.context?.outputType??e.type;return{id:e.id,index:n+1,sourceBlockKey:i??`segment-${e.id}`,sourceStatementId:e.context?.sourceStatementId,outputType:o,stackLevel:e.depth,absoluteStartTime:e.absoluteStartTime,duration:e.duration,elapsed:e.elapsed,total:e.total,spans:e.spans?[...e.spans]:[],completionReason:e.context?.completionReason,cells:r}})}function hZ(e){let t=e.context;return t?.sourceBlockKey?t.sourceBlockKey:e.name}function gZ(e,t){let n=t.type;if(n===q.Sound)return;let r=e.get(n);r?e.set(n,{metrics:r.metrics.clone().add(t),hasUserOverride:r.hasUserOverride}):e.set(n,{metrics:la.empty(n).add(t),hasUserOverride:!1})}function _Z(e,t,n,r){let i=e;if(t.outputTypes&&t.outputTypes.length>0){let e=new Set(t.outputTypes);i=i.filter(t=>e.has(t.outputType))}if(t.origins&&t.origins.length>0){let e=new Set(t.origins);i=i.filter(t=>{for(let[,n]of t.cells)if(n.metrics.some(t=>t.origin&&e.has(t.origin)))return!0;return!1})}if(t.searchText&&t.searchText.trim().length>0){let a=t.searchText.trim().toLowerCase();i=i.filter(t=>{for(let i of n)if(i.filter&&$Y(t,i,{allRows:e,rowIndex:e.indexOf(t),columnDef:i,dependencies:new Map},r).toLowerCase().includes(a))return!0;return!1})}if(t.columnFilters)for(let[a,o]of Object.entries(t.columnFilters)){if(!o||o.trim().length===0)continue;let t=n.find(e=>e.id===a);t&&(i=i.filter(n=>{let i={allRows:e,rowIndex:e.indexOf(n),columnDef:t,dependencies:new Map};return eX(n,t,o,i,r)}))}return i}function vZ(e,t,n,r){if(t.length===0)return e;let i=[...e];return i.sort((i,a)=>{for(let o of t){let t=n.find(e=>e.id===o.columnId);if(!t||!t.sort)continue;let s={allRows:e,rowIndex:e.indexOf(i),columnDef:t,dependencies:new Map},c={allRows:e,rowIndex:e.indexOf(a),columnDef:t,dependencies:new Map},l=ZY(XY(i,t,s,r),XY(a,t,c,r));if(l!==0)return o.direction===`asc`?l:-l}return i.index-a.index}),i}function yZ(e,t){return{id:e,label:t.label,filters:t.filters??{},visibleColumns:[...t.visibleColumnIds],isDefault:e===dZ.defaultPreset}}var bZ=Object.fromEntries(Object.entries(dZ.presets).map(([e,t])=>[e,yZ(e,t)])),xZ=bZ.default;bZ.debug,bZ.strength,bZ.endurance;function ite(e){return bZ[e]??xZ}var SZ=({activePreset:e,onPresetChange:t,searchText:n,onSearchChange:r,showFilters:i,onToggleFilters:a,totalRows:o,visibleRows:s})=>(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2 border-b border-border bg-muted/10 dark:bg-muted/5`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,W.jsx)(`label`,{className:`text-xs text-muted-foreground font-medium`,children:`View:`}),(0,W.jsx)(`select`,{className:`text-xs rounded border border-border bg-background text-foreground px-1.5 py-1 focus:outline-none focus:ring-1 focus:ring-primary/40`,value:e.id,onChange:e=>t(e.target.value),children:Object.values(bZ).map(e=>(0,W.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,W.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,W.jsx)(`div`,{className:`flex items-center flex-1 max-w-md`,children:(0,W.jsxs)(`div`,{className:`flex w-full group`,children:[(0,W.jsx)(`input`,{type:`text`,className:`flex-1 px-2.5 py-1 text-xs rounded-l border border-r-0 border-border bg-background text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-1 focus:ring-primary/40 focus:z-10`,placeholder:`Filter results…`,value:n,onChange:e=>r(e.target.value)}),(0,W.jsxs)(`button`,{className:`px-2.5 py-1 text-xs rounded-r border border-border bg-muted/30 text-muted-foreground hover:bg-muted/50 hover:text-foreground transition-colors flex items-center gap-1.5 border-l-0`,title:`Filter results`,children:[(0,W.jsx)(`span`,{children:`🔍`}),(0,W.jsx)(`span`,{className:`font-medium`,children:`Search`})]})]})}),(0,W.jsx)(`div`,{className:`w-px h-5 bg-border`}),(0,W.jsx)(`button`,{className:[`text-xs px-2 py-1 rounded border transition-colors`,i?`bg-primary/10 border-primary/30 text-primary`:`bg-muted/30 border-border text-muted-foreground hover:text-foreground`].join(` `),onClick:a,title:i?`Hide column filters`:`Show column filters`,children:`🔽 Filters`}),(0,W.jsx)(`div`,{className:`ml-auto text-xs text-muted-foreground tabular-nums`,children:s===o?`${o} rows`:`${s} / ${o} rows`})]}),CZ={"#":`40px`,exercise:`180px`,text:`160px`,notes:`160px`,completionReason:`160px`,rep:`72px`,rounds:`72px`,"current-round":`72px`,duration:`96px`,distance:`96px`,resistance:`96px`,load:`96px`,volume:`96px`,intensity:`96px`,metric:`96px`,work:`96px`,elapsedTotal:`96px`,action:`96px`,increment:`96px`,timestamp:`96px`,spans:`96px`,blockKey:`180px`,outputType:`96px`,stackLevel:`72px`,elapsed:`96px`},wZ=`48px`;function TZ(e){return e.meta?.width??CZ[e.id]??`96px`}function EZ(){return wZ}var DZ=({columns:e,sortConfigs:t,onSort:n,onToggleGraph:r,showFilters:i,columnFilters:a,onColumnFilterChange:o,availableToAdd:s,onAddColumn:c,graphTaggedColumnIds:l})=>(0,W.jsxs)(`thead`,{className:`bg-muted/50 dark:bg-muted/30 sticky top-0 z-10`,children:[(0,W.jsxs)(`tr`,{className:`border-b border-border`,children:[e.map(e=>(0,W.jsx)(OZ,{column:e,sortConfig:t.find(t=>t.columnId===e.id),onSort:n,onToggleGraph:r,isGraphed:l?.has(e.id)??!1},e.id)),c&&(0,W.jsx)(`th`,{className:`py-2 px-1`,style:{minWidth:EZ()},children:(0,W.jsx)(jZ,{availableToAdd:s??[],onAddColumn:c})})]}),i&&(0,W.jsxs)(`tr`,{className:`border-b border-border/50 bg-muted/20 dark:bg-muted/10`,children:[e.map(e=>(0,W.jsx)(AZ,{column:e,value:a[e.id]??``,onChange:o},e.id)),c&&(0,W.jsx)(`th`,{className:`py-1 px-1`,style:{minWidth:EZ()}})]})]}),OZ=({column:e,sortConfig:t,onSort:n,onToggleGraph:r,isGraphed:i})=>{let a=e.sort!==void 0,o=e.graph!==void 0,s=(0,U.useCallback)(t=>{a&&n(e.id,t.shiftKey)},[e.id,a,n]),c=(0,U.useCallback)(t=>{t.stopPropagation(),r(e.id)},[e.id,r]);return(0,W.jsx)(`th`,{className:[`py-1.5 px-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap select-none`,a?`cursor-pointer hover:text-foreground transition-colors`:``].join(` `),style:{minWidth:TZ(e)},onClick:s,children:(0,W.jsxs)(`div`,{className:`flex items-center gap-1`,children:[e.icon&&(0,W.jsx)(`span`,{className:`text-sm`,children:e.icon}),(0,W.jsx)(`span`,{children:e.label}),t&&(0,W.jsx)(kZ,{direction:t.direction}),o&&(0,W.jsx)(`button`,{className:[`ml-auto text-sm opacity-40 hover:opacity-100 transition-opacity`,i?`opacity-100 text-primary`:``].join(` `),onClick:c,title:i?`Remove from graph`:`Add to graph`,children:`📊`})]})})},kZ=({direction:e})=>(0,W.jsx)(`span`,{className:`text-primary text-[10px] ml-0.5`,children:e===`asc`?`▲`:`▼`}),AZ=({column:e,value:t,onChange:n})=>e.filter?(0,W.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:TZ(e)},children:(0,W.jsx)(`input`,{type:`text`,className:`w-full px-1.5 py-0.5 text-xs rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary/40`,placeholder:`Filter…`,value:t,onChange:t=>n(e.id,t.target.value)})}):(0,W.jsx)(`th`,{className:`py-1 px-2`,style:{minWidth:TZ(e)}}),jZ=({availableToAdd:e,onAddColumn:t})=>{let[n,r]=(0,U.useState)(!1),i=(0,U.useRef)(null),a=(0,U.useRef)(null);return(0,U.useEffect)(()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&a.current&&!a.current.contains(e.target)&&r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]),e.length===0?null:(0,W.jsxs)(`div`,{className:`relative flex items-center justify-center`,children:[(0,W.jsx)(`button`,{ref:a,title:`Add metric column`,onClick:e=>{e.stopPropagation(),r(e=>!e)},className:[`flex items-center justify-center w-5 h-5 rounded text-[11px] font-bold transition-all`,`text-muted-foreground hover:text-foreground hover:bg-primary/10 hover:border-primary/40`,`border border-dashed border-muted-foreground/40`,n?`bg-primary/10 border-primary/40 text-foreground`:``].join(` `),children:`+`}),n&&(0,W.jsxs)(`div`,{ref:i,className:`absolute right-0 top-full mt-1 z-50 min-w-[160px] max-h-64 overflow-y-auto
159
159
  bg-popover border border-border rounded-md shadow-xl py-1`,onClick:e=>e.stopPropagation(),children:[(0,W.jsx)(`div`,{className:`px-3 py-1.5 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider border-b border-border/50 mb-1`,children:`Add metric column`}),e.map(e=>{let n=xW(e)??`•`,i=wo.columnLabel(e);return(0,W.jsxs)(`button`,{onClick:()=>{t(e),r(!1)},className:`w-full flex items-center gap-2 px-3 py-1.5 text-xs hover:bg-muted text-foreground transition-colors`,children:[(0,W.jsx)(`span`,{className:`text-sm w-4 text-center`,children:n}),(0,W.jsx)(`span`,{children:i})]},e)})]})]})},MZ=({row:e,allRows:t,rowIndex:n,columns:r,isSelected:i,onSelect:a,isHovered:o,onHover:s,onCellDoubleClick:c})=>{let l=t=>{a(e.id,{ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey})},u=e.outputType===`group`;return(0,W.jsx)(`tr`,{className:G(`border-b border-border transition-colors cursor-pointer`,u?`bg-muted/50 font-bold`:``,i?`bg-accent dark:bg-accent/20`:o?`bg-muted/50 dark:bg-muted/40`:`hover:bg-muted/30 dark:hover:bg-muted/20`),onClick:l,onMouseEnter:()=>s(e.sourceBlockKey),onMouseLeave:()=>s(null),children:r.map(r=>{let i=r.source.type===`metric-type`&&r.source.metricType===q.Effort;return(0,W.jsx)(nX,{columnDef:r,row:e,allRows:t,rowIndex:n,indent:i?e.stackLevel:0,onDoubleClick:c,style:{minWidth:TZ(r)}},r.id)})})};function NZ(e){let{rows:t,columns:n,graphTaggedColumnIds:r,definitionMap:i}=e,a=(0,U.useMemo)(()=>PZ(r,n),[r,n]),o=(0,U.useMemo)(()=>FZ(t,r,n,i),[t,r,n,i]);return{data:o,graphConfigs:a,hasData:a.length>0&&o.length>0}}function PZ(e,t){let n=[];for(let r of e){let e=t.find(e=>e.id===r);e&&n.push({id:r,label:e.label,unit:zZ(e),color:IZ(e),dataKey:r,icon:e.icon})}return n}function FZ(e,t,n,r){return t.length===0?[]:e.map((i,a)=>{let o={index:i.index,label:i.sourceBlockKey};for(let s of t){let t=n.find(e=>e.id===s);if(!t||!t.graph){o[s]=0;continue}o[s]=QY(i,t,{allRows:e,rowIndex:a,columnDef:t,dependencies:new Map},r)??0}return o})}function IZ(e){if(e.graph?.color)return e.graph.color;let t=LZ(e);return t?RZ[t]??`#888888`:`#888888`}function LZ(e){if(e.source.type===`metric-type`)return e.source.metricType}var RZ={[q.Time]:`#3b82f6`,[q.Rep]:`#22c55e`,[q.Effort]:`#eab308`,[q.Distance]:`#14b8a6`,[q.Rounds]:`#a855f7`,[q.Resistance]:`#ef4444`,[q.Increment]:`#6366f1`,[q.Action]:`#ec4899`};function zZ(e){if(e.graph?.unit)return e.graph.unit;let t=LZ(e);if(!t)return``;switch(t){case q.Time:return`ms`;case q.Rep:return`reps`;case q.Distance:return`m`;case q.Rounds:return`rounds`;case q.Resistance:return`kg`;case q.Increment:return`Δ`;default:return``}}var BZ=({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r,onSelectRow:i})=>{let[a,o]=(0,U.useState)(!1),{data:s,graphConfigs:c,hasData:l}=NZ({rows:e,columns:t,graphTaggedColumnIds:n,selectedIds:r}),u=(0,U.useCallback)(t=>{if(!t?.activePayload?.[0])return;let n=t.activePayload[0].payload,r=e.find(e=>e.index===n.index);r&&i&&i(r.id)},[e,i]);return n.length===0?null:(0,W.jsxs)(`div`,{className:`border-b border-border bg-background`,children:[(0,W.jsxs)(`button`,{className:`w-full flex items-center justify-between px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/20 transition-colors`,onClick:()=>o(e=>!e),children:[(0,W.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,W.jsx)(`span`,{children:`📊`}),(0,W.jsxs)(`span`,{children:[`Graph — `,c.map(e=>e.label).join(`, `)]})]}),(0,W.jsx)(`span`,{className:`text-[10px]`,children:a?`▼`:`▲`})]}),!a&&(0,W.jsx)(`div`,{className:`px-3 pb-3`,children:l?(0,W.jsx)(`div`,{className:`w-full bg-muted/30 rounded-lg border border-border p-2`,style:{height:220},children:(0,W.jsx)(_n,{width:`100%`,height:`100%`,children:(0,W.jsxs)(ie,{data:s,onClick:u,children:[(0,W.jsx)(ot,{strokeDasharray:`3 3`,stroke:`hsl(var(--border))`,vertical:!1}),(0,W.jsx)(z,{dataKey:`index`,stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},label:{value:`Row #`,position:`insideBottom`,offset:-5,fill:`hsl(var(--muted-foreground))`,fontSize:10}}),(0,W.jsx)(Dn,{stroke:`hsl(var(--muted-foreground))`,tick:{fontSize:10},domain:[`auto`,`auto`]}),(0,W.jsx)(Ft,{contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,fontSize:`12px`,color:`hsl(var(--popover-foreground))`},labelFormatter:e=>`Row ${e}`,formatter:(e,t)=>{let n=c.find(e=>e.dataKey===t);return[`${typeof e==`number`?e.toLocaleString():e}${n?.unit?` ${n.unit}`:``}`,n?.label??t]}}),(0,W.jsx)(Wn,{verticalAlign:`top`,height:24,wrapperStyle:{fontSize:`11px`}}),c.map(e=>(0,W.jsx)(Qe,{type:`monotone`,dataKey:e.dataKey,name:e.label,stroke:e.color,strokeWidth:2,dot:{r:3,fill:e.color},activeDot:{r:5,stroke:e.color,strokeWidth:2}},e.id))]})})}):(0,W.jsx)(`div`,{className:`h-32 flex items-center justify-center text-sm text-muted-foreground`,children:`No numeric data available for the tagged columns.`})})]})},VZ=({isOpen:e,blockKey:t,metricType:n,existingFragments:r,existingUserValue:i,anchorRect:a,onSave:o,onRemove:s,onClose:c})=>{let[l,u]=(0,U.useState)(``),d=(0,U.useRef)(null),f=(0,U.useRef)(null);(0,U.useEffect)(()=>{e&&(u(i===void 0?``:String(i)),setTimeout(()=>d.current?.focus(),0))},[e,i]),(0,U.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&c()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,c]),(0,U.useEffect)(()=>{if(!e)return;let t=e=>{f.current&&!f.current.contains(e.target)&&c()},n=setTimeout(()=>{document.addEventListener(`mousedown`,t)},100);return()=>{clearTimeout(n),document.removeEventListener(`mousedown`,t)}},[e,c]);let p=(0,U.useCallback)(()=>{if(l.trim()===``)return;let e=Number(l.trim()),r=!isNaN(e)&&l.trim()!==``?e:l.trim();o(t,n,r,String(r)),c()},[l,t,n,o,c]),m=(0,U.useCallback)(()=>{s(t,n),c()},[t,n,s,c]),h=(0,U.useCallback)(e=>{e.key===`Enter`&&(e.preventDefault(),p())},[p]);if(!e)return null;let g=xW(n),_=yW(n),v=i!==void 0,y=r.filter(e=>e.origin!==`user`),b=a?{position:`fixed`,top:a.bottom+4,left:Math.max(8,Math.min(a.left,window.innerWidth-280)),zIndex:50}:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,zIndex:50};return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`fixed inset-0 bg-black/20 dark:bg-black/40 z-40`}),(0,W.jsxs)(`div`,{ref:f,className:`w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-lg`,style:b,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border`,children:[g&&(0,W.jsx)(`span`,{className:`text-sm`,children:g}),(0,W.jsx)(`span`,{className:`text-sm font-medium capitalize`,children:n}),(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground ml-auto truncate max-w-[100px]`,title:t,children:t})]}),y.length>0&&(0,W.jsxs)(`div`,{className:`px-3 py-1.5 border-b border-border/50 bg-muted/10`,children:[(0,W.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1 uppercase tracking-wider`,children:`Current`}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:y.map((e,t)=>(0,W.jsx)(`span`,{className:`inline-flex items-center px-1.5 py-0.5 rounded text-xs border ${_}`,children:e.image??String(e.value??e.type)},t))})]}),(0,W.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,W.jsx)(`label`,{className:`text-[10px] text-muted-foreground uppercase tracking-wider mb-1 block`,children:v?`Update override`:`Enter value`}),(0,W.jsx)(`input`,{ref:d,type:`text`,className:`w-full px-2 py-1.5 text-sm rounded border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-2 focus:ring-primary/40`,placeholder:`Enter ${n} value…`,value:l,onChange:e=>u(e.target.value),onKeyDown:h})]}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-t border-border/50`,children:[(0,W.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted/30 transition-colors`,onClick:c,children:`Cancel`}),v&&(0,W.jsx)(`button`,{className:`px-2 py-1 text-xs rounded border border-destructive/30 text-destructive hover:bg-destructive/10 transition-colors`,onClick:m,title:`Remove user override`,children:`Clear`}),(0,W.jsx)(`button`,{className:`flex-1 px-2 py-1 text-xs rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50`,onClick:p,disabled:l.trim()===``,children:`Save`})]})]})]})},HZ=({segments:e,selectedSegmentIds:t,onSelectSegment:n,userOutputOverrides:r=new Map,gridViewPreset:i=`default`,onPresetChange:a,hoveredBlockKey:o,onHoverBlockKey:s})=>{let{isDebugMode:c}=zy(),[l,u]=(0,U.useState)([]),[d,f]=(0,U.useState)(``),[p,m]=(0,U.useState)({}),[h,g]=(0,U.useState)(!1),[_,v]=(0,U.useState)(new Set),[y,b]=(0,U.useState)({}),[x,S]=(0,U.useState)(new Set),{overrides:C,setOverride:w,removeOverride:T}=FK(!0),[E,D]=(0,U.useState)({isOpen:!1,blockKey:``,type:`Time`,anchorRect:null,existingFragments:[]}),O=(0,U.useMemo)(()=>{let e=new Map;for(let[t,n]of r)e.set(t,n instanceof la?n:la.from(n,t));for(let[t,n]of C)e.set(t,n);return e},[r,C]),k=c?`debug`:i,A=(0,U.useMemo)(()=>ite(k),[k]),{rows:j,visibleColumns:M,availableColumns:N,graphTaggedColumnIds:P}=pZ({segments:e,userOutputOverrides:O,presetId:k,isDebugMode:c,sortConfigs:l,filterOverrides:(0,U.useMemo)(()=>({searchText:d||void 0,columnFilters:Object.keys(p).length>0?p:void 0}),[d,p]),graphTaggedColumns:_,extraMetricTypes:x,columnVisibilityOverrides:y,addedColumnIds:x}),F=M,I=e.length,L=(0,U.useMemo)(()=>j.map(e=>e.id),[j]),R=(0,U.useCallback)((e,t)=>{u(n=>{let r=n.find(t=>t.columnId===e);return t?r?r.direction===`asc`?n.map(t=>t.columnId===e?{...t,direction:`desc`}:t):n.filter(t=>t.columnId!==e):[...n,{columnId:e,direction:`asc`}]:r?r.direction===`asc`?[{columnId:e,direction:`desc`}]:[]:[{columnId:e,direction:`asc`}]})},[]),ee=(0,U.useCallback)(e=>{v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),z=(0,U.useCallback)((e,t)=>{m(n=>{if(!t){let t={...n};return delete t[e],t}return{...n,[e]:t}})},[]),te=(0,U.useCallback)(e=>{b({}),m({}),f(``),a?.(e)},[a]),ne=(0,U.useCallback)(e=>{S(t=>{let n=new Set(t);return n.add(e),n})},[]),re=(0,U.useMemo)(()=>N.filter(e=>e.source.type===`metric-type`).map(e=>e.source.metricType),[N]),ie=(0,U.useCallback)((e,t)=>{n(e,t,L)},[n,L]),ae=(0,U.useCallback)(e=>{s?.(e)},[s]),oe=(0,U.useCallback)(e=>{n(e,{ctrlKey:!1,shiftKey:!1},L)},[n,L]),se=(0,U.useCallback)((e,t,n)=>{let r=(j.find(t=>t.sourceBlockKey===e)?.cells.get(t))?.metrics.toArray()??[],i=r.find(e=>e.origin===`user`),a=i?.value==null?void 0:String(i.value);D({isOpen:!0,blockKey:e,type:t,anchorRect:n,existingFragments:r,existingUserValue:a})},[j]),ce=(0,U.useCallback)((e,t,n,r)=>{w(e,t,n,r),D(e=>({...e,isOpen:!1}))},[w]),B=(0,U.useCallback)(()=>{T(E.blockKey,E.type),D(e=>({...e,isOpen:!1}))},[E.blockKey,E.type,T]),le=(0,U.useCallback)(()=>{D(e=>({...e,isOpen:!1}))},[]);return(0,W.jsxs)(`div`,{className:`h-full flex flex-col bg-background`,children:[(0,W.jsx)(SZ,{activePreset:A,onPresetChange:te,searchText:d,onSearchChange:f,showFilters:h,onToggleFilters:()=>g(e=>!e),totalRows:I,visibleRows:j.length}),(0,W.jsx)(BZ,{rows:j,columns:M,graphTaggedColumnIds:P,selectedIds:t,onSelectRow:oe}),(0,W.jsx)(`div`,{className:`flex-1 overflow-auto`,children:(0,W.jsxs)(`table`,{className:`text-left text-sm border-collapse min-w-[700px]`,children:[(0,W.jsx)(DZ,{columns:F,sortConfigs:l,onSort:R,onToggleGraph:ee,showFilters:h,columnFilters:p,onColumnFilterChange:z,availableToAdd:re,onAddColumn:ne,graphTaggedColumnIds:_}),(0,W.jsx)(`tbody`,{className:`divide-y divide-border`,children:j.length===0?(0,W.jsx)(`tr`,{children:(0,W.jsx)(`td`,{colSpan:F.length,className:`py-8 text-center text-muted-foreground text-sm`,children:e.length===0?`Finish or stop the timer — results land here`:`No rows match the current filters.`})}):j.map((e,n)=>(0,W.jsx)(MZ,{row:e,allRows:j,rowIndex:n,columns:F,isSelected:t.has(e.id),onSelect:ie,isHovered:o===e.sourceBlockKey,onHover:ae,onCellDoubleClick:se},e.id))})]})}),(0,W.jsx)(VZ,{isOpen:E.isOpen,blockKey:E.blockKey,metricType:E.type,existingFragments:E.existingFragments,existingUserValue:E.existingUserValue,anchorRect:E.anchorRect??void 0,onSave:ce,onRemove:B,onClose:le}),(0,W.jsxs)(`div`,{className:`px-3 py-1.5 border-t border-border bg-muted/10 text-xs text-muted-foreground flex items-center justify-between`,children:[(0,W.jsx)(`span`,{children:t.size>0?`${t.size} selected`:`Click a row to select`}),(0,W.jsxs)(`span`,{className:`tabular-nums`,children:[j.length,` / `,I,` rows`]})]})]})};Kt();var UZ=({title:e,onClose:t,children:n,closeButtonClassName:r,floatingClose:i=!1,variant:a=`default`,actions:o,closeLabel:s})=>{(0,U.useEffect)(()=>(document.body.style.overflow=`hidden`,()=>{document.body.style.overflow=``}),[]);let c=U.useRef(null);(0,U.useEffect)(()=>{let e=document.activeElement;return c.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[]);let l=e=>{if(e.key!==`Tab`||!c.current)return;let t=Array.from(c.current.querySelectorAll(`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(t.length===0){e.preventDefault();return}let n=document.activeElement,r=t[0],i=t[t.length-1];e.shiftKey&&(n===r||n===c.current||!c.current.contains(n))?(e.preventDefault(),i.focus()):!e.shiftKey&&n===i&&(e.preventDefault(),r.focus())},u=a===`minimal`,d=(0,W.jsx)(`button`,{onClick:t,className:r??`rounded-pill transition-colors shadow-[rgba(0,0,0,0.06)_0px_1px_2px] ${u?`bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground`:`bg-muted/50 hover:bg-muted text-muted-foreground hover:text-foreground`} ${s?`flex h-11 min-w-[44px] items-center justify-center px-4 text-sm font-medium hover:text-foreground`:`p-2`}`,title:s??`Close`,"data-testid":fW.FOCUSED_DIALOG_CLOSE,children:s??(0,W.jsx)(ge,{className:`h-5 w-5`})});return BC.createPortal((0,W.jsxs)(`div`,{ref:c,onKeyDown:l,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e??`Workout`,className:`fixed inset-0 z-[100] flex flex-col bg-background text-foreground outline-none animate-in fade-in duration-200`,children:[i||u&&!e?(0,W.jsxs)(`div`,{className:`absolute top-4 right-4 z-[110] flex items-center gap-2`,children:[o,d]}):e?(0,W.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border ${u?`bg-muted/10`:`bg-muted/30`} shrink-0`,children:[(0,W.jsx)(`h2`,{className:`text-lg ${u?`font-black tracking-tight uppercase text-[11px] text-muted-foreground`:`font-semibold`}`,children:e}),(0,W.jsxs)(`div`,{className:`flex items-center gap-2`,children:[o,d]})]}):null,(0,W.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden flex flex-col`,children:n})]}),document.body)},WZ=(0,U.createContext)({updateFromSegments:()=>{},clear:()=>{}}),GZ=({children:e,chromecastSubscription:t=null})=>(0,W.jsx)(WZ.Provider,{value:{updateFromSegments:(e,n,r)=>{t&&t.sendAnalyticsSummary([],n,r)},clear:()=>{}},children:e}),KZ=new class{resolve(e){let t=this.resolveMode(e);return t===`active`?{type:`rpc-workbench-update`,mode:`active`}:t===`review`?jK(e.analyticsSegments):NK(e.selectedBlock,e.documentItems)}resolveMode(e){return e.viewMode===`track`?e.runtime&&(e.executionStatus===`running`||e.executionStatus===`paused`)?`active`:e.analyticsSegments.length>0?`review`:e.runtime?`active`:`preview`:e.viewMode===`review`&&e.analyticsSegments.length>0?`review`:`preview`}};function qZ(){if(!(`wakeLock`in navigator))return;let e=navigator.wakeLock;if(!(typeof e!=`object`||!e||!(`request`in e)))return e}function JZ(e){let t=(0,U.useRef)(null);(0,U.useEffect)(()=>{let n=qZ();if(!n||!e)return;let r=!1,i=async()=>{if(document.visibilityState===`visible`)try{let e=await n.request(`screen`);if(r){e.release();return}t.current=e,e.addEventListener(`release`,()=>{t.current===e&&(t.current=null)})}catch{}},a=()=>{document.visibilityState===`visible`&&!t.current&&i()};return i(),document.addEventListener(`visibilitychange`,a),()=>{r=!0,document.removeEventListener(`visibilitychange`,a);let e=t.current;t.current=null,e&&!e.released&&e.release()}},[e])}function YZ(e){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let{code:t,description:n}=e;if(t!==void 0||n!==void 0)return[t===void 0?null:String(t),n?String(n):null].filter(e=>e!==null).join(`: `)||`unknown`;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}var XZ=``,ZZ=null,QZ=()=>{let e=DG(),[t,n]=(0,U.useState)(e.state),[r,i]=(0,U.useState)(!1);JZ(r);let[a,o]=(0,U.useState)(!1),[s,c]=(0,U.useState)(null),[l,u]=(0,U.useState)(null),d=(0,U.useRef)(null),f=WR,p=(0,U.useRef)(f.getActiveHandle()),m=(0,U.useRef)(!1),h=(0,U.useCallback)(e=>{let t=p.current;p.current=null,t&&f.dispose(e),mj(null),u(null),c(null),i(!1)},[f]),g=(0,U.useCallback)(async e=>{if(!m.current){m.current=!0;try{let t=eV.getState().subscriptionManager,n=f.connect(e,t);p.current=n,u(n),c(n.subscription),i(!0),mj(n.transport),n.eventProvider.onEvent(e=>{if(e.name===`clock-command`){let t=wK(e.data);if(!t){console.warn(`[CastButtonRpc] Dropped malformed clock-command payload`);return}GG(t.runId,t.command)||console.warn(`[CastButtonRpc] Clock command rejected by authority:`,t.command.kind);return}let t=UG(),n=TK(e.name,t);n&&t&&!GG(t.runId,n)&&console.warn(`[CastButtonRpc] Legacy receiver event rejected by authority:`,e.name)});let r=eV.getState(),a=KZ.resolve({viewMode:r.viewMode,executionStatus:r.execution.status,runtime:r.runtime,analyticsSegments:r.analyticsSegments,selectedBlock:r.selectedBlock,documentItems:r.documentItems});n.pushInitialWorkbench(a)}finally{m.current=!1}}},[f]),_=(0,U.useRef)(!1),v=(0,U.useCallback)(async()=>{if(f.isConnected&&f.getActiveHandle()){let e=f.getActiveHandle();p.current=e,u(e),c(e.subscription),i(!0);return}if(!(p.current||_.current)&&typeof e.resumeSession==`function`){_.current=!0;try{let t=await e.resumeSession();await g(t)}catch(t){console.warn(`[CastButtonRpc] Session resume failed:`,YZ(t)),h(!1),e.endSession()}finally{_.current=!1}}},[e,g,h,f]);(0,U.useEffect)(()=>e.onStateChanged(e=>{n(e),e===`session-active`?(i(!0),v()):e===`ready`||e===`unavailable`?i(!1):e===`session-ended`&&h(!1)}),[e,h,v]),(0,U.useEffect)(()=>{if(f.isConnected&&f.getActiveHandle()){let e=f.getActiveHandle();p.current=e,u(e),c(e.subscription),i(!0)}else e.state===`session-active`&&v()},[e,f]),(0,U.useEffect)(()=>{let e=l?.transport;if(!e)return;let t=()=>{let t=UG(),n=JSON.stringify(t);if(n!==XZ||e!==ZZ){XZ=n,ZZ=e;try{e.send({type:`rpc-clock-snapshot`,snapshot:t})}catch{}}};return t(),WG(t)},[l]),(0,U.useEffect)(()=>{let e=()=>{f.sendDisposeSignal()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[f]),(0,U.useEffect)(()=>{let t=d.current;if(!t)return;let n=async()=>{if(y.current===`session-active`){if(b.current)return;o(!0);try{h(!0),e.endSession()}finally{setTimeout(()=>o(!1),2e3)}return}try{let t=await e.startSession();i(!0),await g(t)}catch(e){let t=YZ(e);t===`cancel`||t.includes(`cancel`)?console.log(`[CastButtonRpc] Cast request canceled or gesture expired`):console.error(`[CastButtonRpc] Cast failed:`,t),h(!1)}};return t.addEventListener(`click`,n),()=>t.removeEventListener(`click`,n)},[e,g,h]);let y=(0,U.useRef)(t);y.current=t;let b=(0,U.useRef)(a);b.current=a;let x=t===`unavailable`,S=t===`ready`,C=t===`session-active`,w=t===`connecting`,T=r&&C,E=w,D=E||a,O=S||C;return x?(0,W.jsxs)(K,{variant:`ghost`,size:`icon`,disabled:!0,className:`opacity-20 cursor-not-allowed`,"aria-label":`Cast to TV (unavailable)`,title:`Cast to TV (unavailable)`,children:[(0,W.jsx)(At,{className:`h-5 w-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Cast to TV (unavailable)`})]}):(0,W.jsx)(yj,{transport:l?.transport??null,children:(0,W.jsx)(GZ,{chromecastSubscription:s,children:(0,W.jsxs)(K,{ref:d,variant:`ghost`,size:`icon`,disabled:D,onClick:()=>{},className:G(`transition-all`,T&&`text-signal-positive ring-2 ring-signal-positive/30`,E&&`animate-pulse text-signal-caution`,!O&&`opacity-50`),"aria-label":T?`Stop casting`:`Cast to TV`,title:T?`Stop casting`:E?`Connecting...`:`Cast to TV`,children:[T?(0,W.jsx)(mr,{className:`h-5 w-5`}):(0,W.jsx)(At,{className:`h-5 w-5`}),(0,W.jsx)(`span`,{className:`sr-only`,children:T?`Stop casting`:`Cast to TV`})]})})})};function $Z(){let{isEnabled:e,toggleAudio:t}=Cj();return(0,W.jsxs)(K,{variant:`ghost`,size:`icon`,onClick:t,className:`h-9 w-9 text-muted-foreground hover:text-foreground`,title:e?`Mute audio`:`Enable audio`,children:[e?(0,W.jsx)(ee,{className:`h-[1.2rem] w-[1.2rem]`}):(0,W.jsx)(D,{className:`h-[1.2rem] w-[1.2rem]`}),(0,W.jsx)(`span`,{className:`sr-only`,children:`Toggle audio`})]})}async function eQ(e,t={}){let{resultId:n,occurrence:r,metric:i}=e;if(!n||typeof n!=`string`)throw TypeError(`captureMetricCorrection: resultId is required`);if(!r?.blockKey||typeof r.blockKey!=`string`)throw TypeError(`captureMetricCorrection: occurrence.blockKey is required`);if(!i||typeof i.image!=`string`||i.image.length===0)throw TypeError(`captureMetricCorrection: metric.image is required`);if(typeof i.value!=`number`||!Number.isFinite(i.value))throw RangeError(`captureMetricCorrection: metric.value must be finite, got ${i.value}`);if(i.type===q.Rep&&(!Number.isSafeInteger(i.value)||i.value<0))throw RangeError(`captureMetricCorrection: rep corrections must be nonnegative safe integers, got ${i.value}`);let a=t.storage??Z,o=t.persistence??new NP(a);if(!await a.getSessionById(n)||await a.withTransaction([`events`],async e=>{let t=(await e.getEventsByResult(n)).filter(e=>e.grain===`event`&&e.outputType===`segment`&&e.sourceBlockKey===r.blockKey&&(r.sourceStatementId===void 0||e.sourceStatementId===r.sourceStatementId)&&(r.stackLevel===void 0||e.stackLevel===r.stackLevel));if(t.length===0)return`not-found`;if(t.length>1)throw Error(`captureMetricCorrection: ambiguous occurrence ${r.blockKey} in result ${n} — ${t.length} segments match; pass sourceStatementId/stackLevel`);let a=t[0],o=[...a.metrics.filter(e=>e.origin!==`user`||e.type!==i.type),{type:i.type,value:i.value,image:i.image,origin:`user`,timestamp:new Date}],s=a.timeSpan?.started??a.timestamp,c={...a,metrics:o,...a.metricTemporal?{metricTemporal:o.map(()=>({temporalKind:`instant`,instant:s}))}:{}};return await e.appendEvents([c]),`captured`})===`not-found`)return`not-found`;try{return await o.rederiveResultAnalytics(n),`captured`}catch(e){if(e instanceof yb&&e.code===`BLOCK_REVISION_NOT_FOUND`)return`captured-no-rederive`;throw e}}var tQ=new Map,nQ=({block:e,noteContent:t,prepareRun:n,view:r,onClose:i,onCompleteWorkout:a,resultId:o,autoStart:s,onRuntimeReady:c,onRunStarted:l,externalStop:u,adoptRuntime:d,parkOnUnmount:f,onPark:p})=>{let[m,h]=(0,U.useState)(n?null:e),[g,_]=(0,U.useState)(null),v=(0,U.useRef)(!1),y=(0,U.useCallback)(async()=>{if(!(!n||v.current)){v.current=!0,_(null);try{h(await n())}catch(e){_(e instanceof Error?e.message:String(e))}finally{v.current=!1}}},[n]);(0,U.useEffect)(()=>{y()},[y]);let[b,x]=(0,U.useState)(null),[S,C]=(0,U.useState)(new Set),{isDebugMode:w}=zy(),T=(0,U.useRef)(Date.now()),E=(0,U.useRef)(typeof document<`u`?document.title:`Wod.Wiki`),D=(0,U.useRef)(null);(0,U.useEffect)(()=>{let t=e.label||e.id,n=b!==null,r=n?`Wod.Wiki - Workout Complete${t?`: `+t:``}`:`Wod.Wiki - Workout Timer${t?`: `+t:``}`,i=n?`/workout/review`:`/workout/timer`;document.title=r,D.current!==i&&(D.current=i,window.gtag?.(`event`,`page_view`,{page_title:r,page_path:i,page_location:typeof window<`u`?window.location.href:i,engagement_time_msec:Lq()}));let a=Rq.consent;n?a&&window.gtag?.(`event`,`runtime_dialog_review`,{workout_label:t,block_type:e.blockType}):(Rq.record(`runtime:dialog_loaded`,{workout_label:t,block_type:e.blockType}),a&&window.gtag?.(`event`,`runtime_dialog_loaded`,{workout_label:t,block_type:e.blockType}))},[e.id,e.label,e.blockType,b]),(0,U.useEffect)(()=>{let t=E.current,n=e.label||e.id;return()=>{let e=Date.now()-T.current;e>=1e3&&window.gtag?.(`event`,`runtime_dialog_closed`,{workout_label:n,duration_seconds:Math.round(e/1e3),engagement_time_msec:e}),typeof document<`u`&&(document.title=t)}},[e.id,e.label]);let O=(0,U.useRef)(!1),k=(0,U.useRef)(!1),A=(0,U.useRef)(!1),[j,M]=(0,U.useState)(!1),[N,P]=(0,U.useState)(!1),F=(0,U.useRef)(!1),I=(0,U.useRef)(!1),L=(0,U.useRef)(null),[R,ee]=(0,U.useState)(`idle`),[z,te]=(0,U.useState)(null),[ne,re]=(0,U.useState)(!1),{collectionItems:ie}=oq(b??[],tQ,null),[ae,oe]=(0,U.useState)(new Set),[se,ce]=(0,U.useState)(new Set),[B,le]=(0,U.useState)(!1),V=(0,U.useMemo)(()=>ie.filter(e=>{let t=KK(e);return!ae.has(t)&&!se.has(t)}),[ie,ae,se]),ue=b!==null&&!!o&&V.length>0&&!B,de=(0,U.useCallback)(async(e,t)=>{if(typeof t!=`number`||!Number.isFinite(t))throw Error(`Invalid value`);if(e.kind!==`value`)throw Error(`Unsupported entry`);if(!o)throw Error(`The saved run is unavailable.`);if(await eQ({resultId:o,occurrence:{blockKey:e.blockKey,...e.sourceStatementId===void 0?{}:{sourceStatementId:e.sourceStatementId},...e.stackLevel===void 0?{}:{stackLevel:e.stackLevel}},metric:{type:e.metricType,value:t,image:String(t)}})===`not-found`)throw Error(`This result entry could not be found — retry or skip.`);let{segments:n}=DR(d_(await Z.getEventsByResult(o)).map(e=>yP(new fa(e))));x(n),oe(t=>new Set(t).add(KK(e)))},[o]),fe=(0,U.useCallback)(e=>{ce(t=>new Set(t).add(KK(e)))},[]),pe=(0,U.useMemo)(()=>b===null||ue?null:{runId:o?`result:${o}`:`review`,phase:`review`,status:`idle`,canNext:!1,canStop:!1,stopRequested:!1,reps:[],selectedOccurrenceId:null,entry:null,error:null,saving:!1},[b,ue,o]),me=async()=>{let e=L.current;if(!e||F.current)return;F.current=!0,I.current=!1,ee(`saving`),te(null);let t;try{t=a?.(e.blockId,e.results),await t}catch(e){I.current=!0,te(e instanceof Error?e.message:String(e)),ee(`error`),F.current=!1;return}F.current=!1,ee(`idle`),re(!0);let{results:n}=e;if(n.logs&&n.logs.length>0)try{let{segments:e}=DR(n.logs,n.startTime);x(e)}catch{x([])}else n.completed?x([]):A.current&&i()},he=(0,U.useCallback)(()=>{O.current=!0,l?.()},[l]),ge=()=>{if(F.current||I.current){A.current=!0;return}if(b!==null||k.current||!O.current){i();return}if(!j&&!u){P(!0);return}A.current=!0,M(!0)},_e=()=>{P(!1),A.current=!0,M(!0)},ve=(0,U.useRef)(ge);ve.current=ge,OG(pe,(0,U.useCallback)(e=>e.kind===`dismiss`&&(ve.current(),!0),[]),20,{keyboard:!0});let ye=(e,t)=>{k.current||(k.current=!0,L.current={blockId:e,results:t},me())},be=(e,t,n)=>{C(r=>{let i=new Set(r);if(t?.ctrlKey)i.has(e)?i.delete(e):i.add(e);else if(t?.shiftKey&&n){let t=Array.from(r).pop();if(t!==void 0){let r=n.indexOf(t),a=n.indexOf(e);if(r!==-1&&a!==-1){let e=Math.min(r,a),t=Math.max(r,a);for(let r=e;r<=t;r++)i.add(n[r])}else i.add(e)}else i.add(e)}else i.clear(),i.add(e);return i})},xe=R===`idle`?null:(0,W.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3 border-b border-border bg-muted/20 px-6 py-2 text-sm`,children:[R===`saving`&&(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Saving…`}),R===`error`&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(`span`,{role:`alert`,className:`text-destructive`,children:[`Save failed`,z?` — ${z}`:``]}),(0,W.jsx)(`button`,{type:`button`,onClick:()=>void me(),className:`rounded-pill border border-border px-3 py-1 text-xs font-medium text-foreground transition-colors hover:bg-accent`,children:`Retry save`})]})]});return m?b===null?(0,W.jsx)(UZ,{onClose:ge,title:`Workout`,closeLabel:`Exit`,actions:(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`button`,{type:`button`,onClick:ge,title:`Stop Session`,className:`flex h-11 min-w-[44px] items-center justify-center rounded-pill bg-muted/50 px-4 text-sm font-medium text-muted-foreground shadow-[rgba(0,0,0,0.06)_0px_1px_2px] transition-colors hover:bg-muted hover:text-foreground`,children:`Stop`}),(0,W.jsx)(QZ,{}),(0,W.jsx)($Z,{})]}),children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[xe,g?(0,W.jsxs)(`div`,{className:`space-y-2 p-4`,children:[(0,W.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,g]}),(0,W.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 hover:bg-accent focus-visible:ring-2`,onClick:()=>void y(),children:`Retry starting workout`})]}):m?null:(0,W.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:`p-4`,children:`Saving workout before starting…`}),(0,W.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,W.jsx)(Aq,{block:m,noteContent:t,view:r,onClose:ge,onComplete:ye,isExpanded:!0,autoStart:s,onRuntimeReady:c,onRunStarted:he,externalStop:u||j,adoptRuntime:d,parkOnUnmount:f,onPark:p})}),N&&(0,W.jsx)(UZ,{title:`Stop workout?`,onClose:()=>P(!1),closeLabel:`Keep going`,actions:void 0,children:(0,W.jsxs)(`div`,{className:`space-y-4 p-6`,children:[(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The run stops now and your partial results are kept.`}),(0,W.jsxs)(`div`,{className:`flex items-center justify-end gap-3`,children:[(0,W.jsx)(`button`,{type:`button`,"data-testid":`stop-cancel`,onClick:()=>P(!1),className:`rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-accent`,children:`Keep going`}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`stop-confirm`,onClick:_e,className:`rounded-lg bg-destructive px-4 py-2 text-sm font-bold text-destructive-foreground transition-colors hover:brightness-110`,children:`Stop — keep partial results`})]})]})})]})}):(0,W.jsx)(UZ,{title:`Workout Complete`,onClose:ge,actions:(0,W.jsxs)(W.Fragment,{children:[ne&&(0,W.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Saved ✓`}),(0,W.jsx)(QZ,{}),(0,W.jsx)($Z,{})]}),children:(0,W.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[xe,(0,W.jsx)(`div`,{className:`min-h-0 flex-1`,children:ue?(0,W.jsx)(dq,{mode:`post-run`,items:V,onSave:de,onSkip:fe,onClose:()=>le(!0),runId:o?`result:${o}`:void 0,className:`mx-auto max-w-md`}):(0,W.jsx)(HZ,{runtime:null,segments:b,selectedSegmentIds:S,onSelectSegment:be,groups:[],gridViewPreset:w?`debug`:`default`})})]})}):(0,W.jsx)(UZ,{title:`Starting workout`,onClose:i,children:g?(0,W.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,W.jsxs)(`p`,{role:`alert`,children:[`Workout not started. `,g,` Your draft is kept.`]}),(0,W.jsx)(`button`,{type:`button`,className:`rounded border px-3 py-2 focus-visible:ring-2`,onClick:()=>void y(),children:`Retry start`})]}):(0,W.jsx)(`p`,{role:`status`,className:`p-6`,children:`Saving workout before starting…`})})},rQ={play:!0,"add-to-today":!0,schedule:!0},iQ=`log`;function aQ(e,t){return e.filter(e=>e.id===iQ?t===`log`:!rQ[e.id]||t===`run`)}function oQ(e,t){let n=t.contentFrom!==void 0&&t.contentTo!==void 0?e.state.doc.sliceString(t.contentFrom,t.contentTo):``,r=t.type===`time`||t.type===`log`?t.type:`time`;return{id:t.id,contentId:t.contentId,dialect:r,sport:t.sport,startLine:t.startLine-1,endLine:t.endLine-1,content:n,state:`idle`,version:1,createdAt:Date.now(),widgetIds:{}}}function sQ(e){return function({className:t}){return U.isValidElement(e)?U.cloneElement(e,{className:G(e.props.className,t)}):(0,W.jsx)(`span`,{className:G(`flex items-center`,t),children:e})}}var cQ=({cmd:e,block:t})=>{let[n,r]=(0,U.useState)(!1),[i,a]=(0,U.useState)(!1),o=(0,U.useCallback)(async()=>{!e.onSplitClick||n||(await e.onSplitClick(t),r(!0),setTimeout(()=>r(!1),1500))},[e,t,n]),s=(0,U.useCallback)(async()=>{i||(await e.onClick(t),e.successIcon&&(a(!0),setTimeout(()=>a(!1),1500)))},[e,t,i]),c=(0,U.useMemo)(()=>sQ(i?e.successIcon??e.icon:e.icon),[e.icon,e.successIcon,i]),l=(0,U.useMemo)(()=>sQ(n?e.splitSuccessIcon??e.splitIcon:e.splitIcon),[n,e.splitIcon,e.splitSuccessIcon]),u=(0,U.useMemo)(()=>({id:e.id,label:e.label,icon:c,action:{type:`call`,handler:()=>s()}}),[e.id,e.label,c,s]),d=(0,U.useMemo)(()=>({id:`${e.id}-split`,label:`Copy link`,icon:l,action:{type:`call`,handler:o}}),[e.id,l,o]),f=(0,U.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]);if(!e.onSplitClick){let t=i?e.successIcon??e.icon:e.icon;return(0,W.jsxs)(K,{variant:e.primary?`default`:`secondary`,className:G(e.iconOnly?`h-11 w-11 rounded-full p-0 sm:h-auto sm:min-h-[44px] sm:min-w-[44px] sm:w-auto sm:rounded-sm sm:px-1.5 sm:py-0.5 text-[10px] font-medium shadow-sm`:`h-11 w-11 rounded-full p-0 text-[10px] font-medium shadow-sm gap-0 sm:h-auto sm:min-h-[44px] sm:w-auto sm:gap-1 sm:rounded-sm sm:px-2 sm:py-0.5`,!e.primary&&`border border-border/50`,i&&`text-emerald-600 bg-emerald-500/15 dark:text-emerald-400 dark:bg-emerald-500/20 border-emerald-500/30`),title:e.label,"aria-label":e.label,"data-testid":e.id===`run`?fW.EDITOR_START_WORKOUT:void 0,onClick:e=>{f(e),s()},onMouseDown:f,onPointerDown:f,children:[(0,W.jsx)(`span`,{className:`flex items-center justify-center size-4 sm:size-3`,children:t}),!e.iconOnly&&(0,W.jsx)(`span`,{className:`sr-only sm:not-sr-only sm:inline`,children:e.label})]})}return(0,W.jsx)(`div`,{onClick:f,onMouseDown:f,onPointerDown:f,children:(0,W.jsx)(wY,{primary:u,secondary:d,size:`xs`,variant:e.primary?`primary`:`default`,className:`rounded-full sm:rounded-sm`,labelClassName:`sr-only sm:not-sr-only sm:inline`})})},lQ=({view:e,commands:t})=>{let[n,r]=(0,U.useState)(()=>e?.plugin(aE)?.rects??[]),[i,a]=(0,U.useState)(0);(0,U.useEffect)(()=>{if(!e)return;let t=e.plugin(aE);t&&(r([...t.rects]),t.addListener(e=>r([...e])))},[e]),(0,U.useEffect)(()=>{if(!e)return;let t=e.scrollDOM,n=null,r=()=>{n===null&&(n=requestAnimationFrame(()=>{n=null,a(t.scrollTop)}))};return t.addEventListener(`scroll`,r,{passive:!0}),a(t.scrollTop),()=>{n!==null&&cancelAnimationFrame(n),t.removeEventListener(`scroll`,r)}},[e]);let o=e?e.plugin(aE):null,s=(n.length>0?n:o?.rects??[]).filter(e=>e.type===`time`||e.type===`log`);if(s.length===0)return null;let{sections:c}=e.state.field(NT),l=new Map(c.map(e=>[e.id,e]));return(0,W.jsx)(W.Fragment,{children:s.map(n=>{let r=l.get(n.sectionId);if(!r)return null;let a=oQ(e,r),o=aQ(t,Ca(r.type));return o.length===0?null:(0,W.jsx)(`div`,{className:`absolute right-1 z-10 flex items-end gap-1 pointer-events-auto`,style:{top:n.top-i,height:n.firstLineHeight},children:o.map(e=>(0,W.jsx)(cQ,{cmd:e,block:a},e.id))},n.sectionId)})})},uQ=({sections:e,isRuntimeActive:t,editorState:n,onSelectBlock:r})=>{let i=vj(),a=(0,U.useRef)(``);return(0,U.useEffect)(()=>{if(!i?.connected||t||!n)return;let r=e.filter(e=>e.type===`time`).map(e=>{let t=e.contentFrom!==void 0&&e.contentTo!==void 0?n.doc.sliceString(e.contentFrom,e.contentTo):``,r=t.split(`
160
160
  `).filter(e=>e.trim().length>0),i=r.slice(0,3).join(`
161
- `),a=t.match(/^(\d{1,2}:\d{2}(?::\d{2})?)/m)?.[1],o=r[0]?.substring(0,60)||`Workout`,s=e.type===`time`||e.type===`log`?e.type:`time`;return{id:e.id,title:o,statementCount:r.length,contentPreview:i,timerHint:a,dialect:s}}),o={type:`rpc-workbench-update`,mode:r.length>0?`preview`:`idle`,previewData:r.length>0?{title:r[0].title,blocks:r}:void 0},s=JSON.stringify(o);if(s!==a.current){a.current=s;try{i.send(o)}catch{}}},[i,e,t,n]),(0,U.useEffect)(()=>{i?.connected||(a.current=``)},[i]),(0,U.useEffect)(()=>{t||(a.current=``)},[t]),(0,U.useEffect)(()=>{if(!(!i?.connected||!r||!n))return i.onMessage(t=>{if(t.type!==`rpc-event`||t.name!==`select-block`)return;let{index:i,blockId:a}=t.data??{},o=e.filter(e=>e.type===`time`),s=a?o.find(e=>e.id===a):o[i??0];if(!s||!n)return;let c=s.contentFrom!==void 0&&s.contentTo!==void 0?n.doc.sliceString(s.contentFrom,s.contentTo):``;r({id:s.id,dialect:s.type===`time`||s.type===`log`?s.type:`time`,sport:s.sport,startLine:s.startLine-1,endLine:s.endLine-1,content:c,state:`idle`,version:1,createdAt:Date.now(),widgetIds:{}})})},[i,e,n,r,t]),null},dQ={[q.Duration]:{label:`Timer`,icon:`⏱`,textClass:`text-metric-time`,bgClass:`bg-metric-time/10`,borderClass:`border-metric-time/30`},[q.Rep]:{label:`Reps`,icon:`✕`,textClass:`text-metric-rep`,bgClass:`bg-metric-rep/10`,borderClass:`border-metric-rep/30`},[q.Effort]:{label:`Exercise`,icon:`🏋`,textClass:`text-metric-effort`,bgClass:`bg-metric-effort/10`,borderClass:`border-metric-effort/30`},[q.Rounds]:{label:`Rounds`,icon:`↻`,textClass:`text-metric-rounds`,bgClass:`bg-metric-rounds/10`,borderClass:`border-metric-rounds/30`},[q.Distance]:{label:`Distance`,icon:`📏`,textClass:`text-metric-distance`,bgClass:`bg-metric-distance/10`,borderClass:`border-metric-distance/30`},[q.Resistance]:{label:`Weight`,icon:`⚖`,textClass:`text-metric-resistance`,bgClass:`bg-metric-resistance/10`,borderClass:`border-metric-resistance/30`},[q.Equipment]:{label:`Equipment`,icon:`🧰`,textClass:`text-foreground`,bgClass:`bg-muted/40`,borderClass:`border-border/50`},[q.Action]:{label:`Action`,icon:`⚡`,textClass:`text-metric-action`,bgClass:`bg-metric-action/10`,borderClass:`border-metric-action/30`},[q.Label]:{label:`Label`,icon:`🏷`,textClass:`text-muted-foreground`,bgClass:`bg-muted/30`,borderClass:`border-border/40`}},fQ={[q.Rep]:`reps`,[q.Effort]:`movement`,[q.Resistance]:`weight`},pQ=({metric:e,tooltip:t,isFocused:n,onClick:r})=>{let i=dQ[e.type],a=e.type===q.Hint,o=e.image??(e.value===void 0?``:String(e.value)),s=i?.label??String(e.type);return(0,W.jsxs)(`span`,{title:t,onClick:r,className:G(`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium`,`pointer-events-auto transition-opacity hover:opacity-80`,i?.bgClass??`bg-muted/30`,i?.textClass??`text-muted-foreground`,i?.borderClass??`border-border/40`,r&&`cursor-pointer`,n&&`font-bold shadow-sm`),children:[(0,W.jsx)(`span`,{children:a?e.icon:i?.icon??`•`}),!a&&(0,W.jsx)(`span`,{children:s}),!a&&o&&(0,W.jsx)(`span`,{className:`font-semibold`,children:o})]})};function mQ(e){let t=sa(e.metadata);return{refs:t?.refs??[],diagnostics:t?.diagnostics??[]}}function hQ(e,t){try{let n=e.coordsAtPos(t);if(!n)return null;let r=e.dom?.getBoundingClientRect?.()??{top:0,left:0},i=e.contentDOM?.getBoundingClientRect?.()??{left:0,width:0};return{top:n.bottom-r.top,left:i.left-r.left,width:i.width}}catch{return null}}var gQ=({view:e,cursorVersion:t,getCursorFocusState:n})=>{let[r,i]=(0,U.useState)(null),[a,o]=(0,U.useState)(null),s=(0,U.useRef)(null),c=(0,U.useCallback)(()=>{if(!e){o(null),i(null);return}let t=(n??zJ)(e.state);o(t),i(t?hQ(e,t.lineFrom):null)},[e,n]);if((0,U.useEffect)(()=>{c()},[c,t]),(0,U.useEffect)(()=>{if(!e)return;let t=()=>c();return window.addEventListener(`scroll`,t,!0),window.addEventListener(`resize`,t,!0),()=>{window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t,!0)}},[e,c]),!r||!a?.section)return null;let l=a.allStatements?.filter(e=>e.meta?.line===a.cursorLine-a.section.startLine)??(a.statement?[a.statement]:[]),u=l.flatMap(e=>e.metrics.toArray()).filter(e=>e.type!==q.Sound&&e.type!==q.System&&!(e.type===q.Hint&&!e.icon)),d=BW(u,`runtime-badge`),f=l.flatMap(e=>e.metrics.toArray()),p=[],m=[],h=[];for(let e of f){let t=mQ(e);for(let e of t.refs){let t=`${e.kind}:${e.slug}`;p.includes(t)||(p.push(t),m.push(e))}h.push(...t.diagnostics)}let g=[];for(let e of f){let t=ga(e.metadata);t&&(g.some(e=>e.slug===t.slug)||g.push(t))}let _=typeof e?.state?.facet==`function`?e.state.facet(SE)?.()??null:null,v=typeof e?.state?.doc?.sliceString==`function`?DJ(e.state.doc.sliceString(a.lineFrom,a.lineTo)):null,y=e=>e.reason===`conflict`||e.reason.endsWith(`equipment`)||e.reason===`invalid-explicit`&&e.token&&v?.equipment.includes(e.token)?`equipment`:`effort`,b=e=>typeof e==`string`&&e.trim()?e:null,x=async t=>{if(!e)return;let n=e.state.doc.sliceString(a.lineFrom,a.lineTo),r=ZH.getState();if(t===`effort`){let t=await r.open({placeholder:`Change effort…`,sources:[TJ(`effort`)]});if(t.dismissed)return;let i=b(t.item.payload);if(!i)return;e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:OJ(n,{effort:i})}});return}let i=[...v?.equipment??[]];for(;;){let e=await r.open({placeholder:i.length>0?`Add equipment (Esc to finish)…`:`Set equipment…`,sources:[TJ(`equipment`)]});if(e.dismissed)break;let t=b(e.item.payload);t&&!i.includes(t)&&i.push(t)}((v?.jsonFrom??-1)>=0||i.length>0)&&e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:OJ(n,{equipment:i})}})},S=async()=>{if(!e)return;let t=e.state.doc.sliceString(a.lineFrom,a.lineTo),n=ZH.getState(),r,i=await n.open({placeholder:`Add effort (Esc to skip)…`,sources:[TJ(`effort`)]});i.dismissed||(r=b(i.item.payload)??void 0);let o=[];for(;;){let e=await n.open({placeholder:`Add equipment (Esc to finish)…`,sources:[TJ(`equipment`)]});if(e.dismissed)break;let t=b(e.item.payload);t&&!o.includes(t)&&o.push(t)}!r&&o.length===0||e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:OJ(t,{effort:r,equipment:o})}})},C=async t=>{if(!e||!t.token)return;let n=y(t),r=await ZH.getState().open({placeholder:`Replace “${t.token}”…`,sources:[TJ(n,t.candidates)]});if(r.dismissed)return;let i=b(r.item.payload);if(!i)return;let o=e.state.doc.sliceString(a.lineFrom,a.lineTo).indexOf(t.token);o<0||e.dispatch({changes:{from:a.lineFrom+o,to:a.lineFrom+o+t.token.length,insert:i}})},w=t=>{let n=fQ[t.type];if(!n||!e)return;let r=t.type===q.Effort?`effort`:t.type===q.Equipment?`equipment`:null;if(r&&v?.jsonFrom!==void 0&&v.jsonFrom>=0){x(r);return}an(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-D79YIu6s.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([3,1,0,2])).then(({runStatementBuilderFlow:t})=>{t(a,e,n)})};return(0,W.jsxs)(`div`,{ref:s,className:G(`cm-metric-inline-panel`,`absolute z-50 pointer-events-none`,`flex items-center gap-2 px-3 h-[28px]`,`bg-background/90 backdrop-blur-sm`,`border-l border-r border-border/50`,`transition-opacity duration-100`),style:{top:r.top,left:r.left,width:r.width,maxWidth:r.width},"aria-live":`polite`,"aria-label":`Metric inline panel`,children:[u.length>0?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-medium shrink-0 select-none`,children:`Metrics:`}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[u.map((e,t)=>(0,W.jsx)(pQ,{metric:e,tooltip:e.type===q.Hint?String(e.value??``):d[t]?.tooltip,isFocused:a.focusedMetric===e,onClick:fQ[e.type]?()=>w(e):void 0},`${e.type}-${t}`)),m.map(e=>(0,W.jsxs)(`span`,{title:`${e.kind===`effort`?`Effort`:`Equipment`} · click to change source`,onClick:()=>void x(e.kind),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium cursor-pointer hover:opacity-80 bg-muted/40 text-foreground border-border/50`,children:[(0,W.jsx)(`span`,{children:e.kind===`effort`?`🏋`:`🧰`}),(0,W.jsx)(`span`,{className:`font-semibold`,children:e.label}),_&&(0,W.jsx)(`a`,{href:_.openHref(e.kind,e.slug),title:`Open ${e.label} page`,"aria-label":`Open ${e.label} page`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`${e.kind}:${e.slug}`)),g.map(e=>(0,W.jsxs)(`span`,{title:e.soundProfileId?`Tag ${e.label} · names the ${e.soundProfileId} sound profile`:`Tag ${e.label}`,className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium bg-muted/40 text-foreground border-border/50`,children:[(0,W.jsx)(`span`,{children:`#`}),(0,W.jsx)(`span`,{className:`font-semibold font-mono`,children:e.label}),_&&(0,W.jsx)(`a`,{href:_.openHref(`tag`,e.slug),title:`Open the ${e.label} tag`,"aria-label":`Open the ${e.label} tag`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`tag:${e.slug}`)),v?.malformed&&(0,W.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:`Reference JSON on this line does not parse — fix it in the raw text.`,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,W.jsx)(`span`,{children:`⚠`}),(0,W.jsx)(`span`,{children:`Malformed reference JSON`})]}),h.map((e,t)=>{let n=y(e);return(0,W.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:e.message,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,W.jsx)(`span`,{children:`⚠`}),(0,W.jsx)(`span`,{children:e.token??e.reason}),(0,W.jsx)(`button`,{type:`button`,className:`underline cursor-pointer`,onClick:()=>void C(e),children:`Select existing`}),_&&(0,W.jsx)(`a`,{href:_.createHref(n),className:`underline hover:text-foreground`,children:`Create page`})]},`${e.reason}-${t}`)}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`editor-add-metric-line`,title:`Add effort/equipment reference to this line`,onClick:()=>void S(),className:`pointer-events-auto inline-flex items-center px-1.5 py-0.5 rounded border border-dashed border-border/60 text-[10px] text-muted-foreground hover:text-foreground hover:border-primary/50 cursor-pointer`,children:`+ Metric`})]})]}):(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground/50 italic select-none`,children:`No metrics on this line`}),(0,W.jsx)(`span`,{className:`ml-auto text-[9px] text-muted-foreground/40 shrink-0 select-none`,children:`Ctrl+↑↓ · adjust value`})]})},_Q=new ai,vQ=new ai,yQ=new ai;async function bQ(e){let t=new TextEncoder().encode(e);if(typeof CompressionStream<`u`)try{let e=new CompressionStream(`gzip`),n=e.writable.getWriter(),r=e.readable.getReader();n.write(t),n.close();let i=[];for(;;){let{done:e,value:t}=await r.read();if(e)break;i.push(t)}let a=i.reduce((e,t)=>e+t.length,0),o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.length;return btoa(String.fromCharCode(...o)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}catch{}return btoa(String.fromCharCode(...t)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}async function xQ(e){let t=await bQ(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`);return`${window.location.origin}/load?zip=${t}`}async function SQ(e){let t=await bQ(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`),n=`shared by ${Mx()}`;return`${window.location.origin}/?z=${t}&by=${encodeURIComponent(n)}`}var CQ=({noteId:e,noteBlocks:t,sourceRevision:n=0,onIdentityChange:r,onSaved:i,beforeRun:a,onSaveRequest:o,onCommitChange:s,value:c,onChange:l,onDocUpdate:u,onCursorPositionChange:d,onBlur:f,theme:p=`vs`,readonly:m=!1,className:h=``,ariaLabel:g=`Note editor`,onStartWorkout:_,onCompleteWorkout:v,onBlocksChange:y,onAddToPlan:b,notePersistence:x,onViewCreated:S,mode:C=`edit`,lineWrapping:w=!0,showLineNumbers:T=!0,enablePreview:E=!0,showFrontmatter:D=!0,enableLinting:O=!0,enableOverlay:k=!1,commands:A,hideDefaultCommands:j=!1,enableInlineRuntime:M=!0,extensions:N,widgetComponents:P,activeSectionId:F,scrollToSectionId:I,results:L,placeholder:R})=>{let ee=(0,U.useRef)(null),z=(0,U.useRef)(null),ne=(0,U.useRef)(null),re=(0,U.useRef)(``),ie=p===`dark`||p===`vs-dark`,ae=kJ(ne,x),[oe,se]=(0,U.useState)(null),[ce,B]=(0,U.useState)([]),[le,V]=(0,U.useState)(1),[ue,de]=(0,U.useState)(0),fe=F??oe,pe=pY(ce,fe),[me,he]=(0,U.useState)(null),[ge,_e]=(0,U.useState)(null),[ve,ye]=(0,U.useState)(null),[be,xe]=(0,U.useState)(!1),Se=(0,U.useRef)(null),Ce=(0,U.useRef)(!1),we=(0,U.useRef)(n??0);(0,U.useEffect)(()=>{we.current=n??0},[n]);let[Te,Ee]=(0,U.useState)(null),De=(0,U.useRef)(null),Oe=(0,U.useCallback)(async(t,n=!1)=>{let r=z.current;if(!(!r||Ce.current)){Ce.current=!0,Ee(null);try{let o=await a?.();typeof o==`number`&&(we.current=o);let s=r.state.field(NT),c=await QR({noteId:e??ze(),rawContent:s.rawContent,blocks:s.noteBlocks,expectedSourceRevision:we.current,...e?{}:{metadata:{title:`Playground workout`},noteType:`playground`}},t,ze(),e?void 0:`playground`,ae);Se.current=c,De.current=null,we.current=c.note.sourceRevision,r.dispatch({effects:TT.of({blocks:c.note.blocks,sourceRevision:c.note.sourceRevision})}),i?.({rawContent:c.note.rawContent,blocks:c.note.blocks,sourceRevision:c.note.sourceRevision}),xe(n),_e(c.block),ye(c.session.id)}catch(e){Ee(e instanceof Error?e.message:String(e))}finally{Ce.current=!1}}},[e,ae,i,a]),ke=(0,U.useCallback)(()=>{_e(null),ye(null),xe(!1)},[]),Ae=(0,U.useCallback)(e=>{M&&Oe(e,!0)},[M,Oe]),je=(0,U.useRef)(null),Me=(0,U.useCallback)((e,t)=>{let n=je.current,r=n!==null&&n.results===t,i=Se.current;if(!i||!t)return Promise.reject(Error(`The saved run pin is unavailable.`));let a=i.session.id;if(De.current===a)return Promise.resolve();let o={id:i.block.id,contentId:i.session.blockContentId};if(!r&&t&&z.current){let t=z.current,n=QD(t.state,e,a);if(n){let e=n.from+n.insert.indexOf("```");t.dispatch({changes:n,effects:[Sr.scrollIntoView(e,{y:`start`,yMargin:96})]}),l?.(t.state.doc.toString())}}r||(je.current={results:t,resultId:a,runBlock:o});let s;try{s=kK(ae).record({resultId:a,noteId:i.session.noteId,blockId:i.session.blockId,data:t,createdAt:t.endTime}).then(()=>v?.(e,t,a,o))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return Promise.resolve(s).then(()=>{je.current?.results===t&&(je.current=null),De.current=a},()=>{}),s},[l,v,ae]),Ne=(0,U.useMemo)(()=>{if(j)return[];if(A&&A.length>0)return A;let e=[];return M?e.push({id:`run`,label:`Run`,icon:(0,W.jsx)(wn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:Oe}):_&&e.push({id:`run`,label:`Run`,icon:(0,W.jsx)(wn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:_}),e.push({id:`playground`,label:`Playground`,icon:(0,W.jsx)(Ye,{className:`h-3 w-3`}),splitIcon:(0,W.jsx)(te,{className:`h-3 w-3`}),splitSuccessIcon:(0,W.jsx)(Tt,{className:`h-3 w-3`}),onClick:e=>{xQ(e.content).then(e=>{let t=window.open(e,`wodwiki-playground`);t&&t.focus()})},onSplitClick:async e=>{let t=await SQ(e.content);await navigator.clipboard.writeText(t)}}),b&&e.push({id:`plan`,label:`Plan`,icon:(0,W.jsx)(Rt,{className:`h-3 w-3`}),onClick:b}),e},[A,_,b,M,j,Oe]),Pe=(0,U.useMemo)(()=>ui({codeLanguages:RO}),[]),Fe=(0,U.useMemo)(()=>[...T?[Jr(),Rr()]:[],Br(),ci(),Tr(),li(),...w?[Sr.lineWrapping]:[],Qr.allowMultipleSelections.of(!0),Cr(),bi(),zr(),mi(),si.highest(hr.of([{key:`Tab`,run:e=>Pr(e.state)!==null&&(xi(e),!0)},{key:`Enter`,run:e=>{let t=e.state.selection.main,n=DQ(e.state,t.head),r=e.state.doc.lineAt(t.head);return!t.empty||n?.value.trim()!==``||r.text.slice(t.head-r.from).trim()?!1:(_r(e),aee(e))}}])),hr.of([...Nr,...Yr,...ii,...ri,...yi,...oi,Xr,{key:`Mod-s`,run:()=>(o?.(),!0)},{key:`Ctrl-.`,run:e=>{let t=zJ(e.state);if(!t?.focusedMetric)return!1;let n=t.focusedMetric.type;return!new Set([`duration`,`rep`,`rounds`,`distance`,`resistance`]).has(n)&&(an(()=>Promise.resolve().then(()=>XH).then(()=>{an(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-D79YIu6s.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([3,1,0,2])).then(({runStatementBuilderFlow:n})=>{n(t,e)}).catch(()=>{ZH.getState().open({placeholder:`Modify metric…`,sources:[]})})}),void 0),!0)}}]),iO,NT,ST.of({blocks:t??Pa(c,{sourceRevision:Math.max(1,n),registeredWidgets:P?[...P.keys()]:Oa}),sourceRevision:Math.max(1,n),rawContent:c}),CT.of(P?[...P.keys()]:Oa),PT,wE.of(D),...E||!D?[uD]:[],...E?[mE,_E,pJ(),SJ(),DD,xD(),RD]:[],...O?[zT]:[],rE,eT,GT,WT,KT.of(wQ),qT.of(TQ),...k?[aO]:[],aE,xT,HJ,...WD,_T,...P&&P.size>0?[LO(P)]:[],pO({executor:Mz,onResultSaved:DK,readOnly:m,noteHref:e=>DU(`blockContentId`in e||`dataType`in e?Qz(e):Kz(e))}),AJ(e,ae),Sr.domEventHandlers({blur:()=>(f?.(),!1)}),Sr.updateListener.of(e=>{if(e.docChanged){let t=e.state.field(NT);r?.({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:t.sourceRevision}),l(t.rawContent),u?.(e),kQ(e.state,y,re),e.transactions.some(e=>e.isUserEvent(`input`)||e.isUserEvent(`delete`)||e.isUserEvent(`paste`)||e.isUserEvent(`drop`))||s?.()}if(e.selectionSet||e.docChanged){de(e=>e+1),e.transactions.some(e=>e.isUserEvent(`delete.backward`))&&Pr(e.startState)!==null&&Pr(e.state)===null&&DQ(e.state,e.state.selection.main.head)?.value===``&&queueMicrotask(()=>{e.view.state===e.state&&$r(e.view)});let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t);d?.(n.number,t-n.from+1);let r=IT(e.state);se(r?.id??null),V(n.number);let{sections:i}=e.state.field(NT);B(i)}}),Qr.readOnly.of(m),Sr.editable.of(!m),...R?[hi(R)]:[],Sr.contentAttributes.of({"aria-label":g})],[l,d,f,u,y,r,m,o,s,T,w,E,D,O,k,e,ae,P,R,g]);return(0,U.useEffect)(()=>{let e=ee.current;if(!e)return;let t=Qr.create({doc:c,extensions:[...Fe,_Q.of(gT(ie)),vQ.of(Pe),yQ.of([]),...N??[]]}),n=new Sr({state:t,parent:e}),i=window.visualViewport,a=0,o=()=>{cancelAnimationFrame(a),a=requestAnimationFrame(()=>{n.hasFocus&&i?.scale===1&&i.height<window.innerHeight&&n.dispatch({effects:Sr.scrollIntoView(n.state.selection.main.head,{y:`nearest`,yMargin:24})})})};i?.addEventListener(`resize`,o),n.contentDOM.addEventListener(`focus`,o),z.current=n,he(n),e.__codemirrorView=n,S?.(n);let{sections:s}=n.state.field(NT);B(s);let l=n.state.doc.lineAt(n.state.selection.main.head).number;V(l);let u=IT(n.state);se(u?.id??null);let d=n.state.field(NT);return r?.({rawContent:d.rawContent,blocks:d.noteBlocks,sourceRevision:d.sourceRevision}),kQ(n.state,y,re),()=>{cancelAnimationFrame(a),i?.removeEventListener(`resize`,o),n.contentDOM.removeEventListener(`focus`,o),delete e.__codemirrorView,he(null),n.destroy()}},[]),(0,U.useEffect)(()=>{let e=z.current;if(!e)return;let r=e.state.field(NT);c===r.rawContent?t&&n!==r.sourceRevision&&e.dispatch({effects:TT.of({blocks:t,sourceRevision:Math.max(1,n)})}):e.dispatch({changes:{from:0,to:e.state.doc.length,insert:c},...t?{effects:ET.of({rawContent:c,blocks:t,sourceRevision:Math.max(1,n)})}:{}})},[c,t,n]),(0,U.useEffect)(()=>{z.current&&z.current.dispatch({effects:_Q.reconfigure(gT(ie))})},[ie]),(0,U.useEffect)(()=>{if(z.current){let e=[];z.current.dispatch({effects:[Kr.reconfigure.of([...Fe,_Q.of(gT(ie)),vQ.of(Pe),yQ.of(e),...N??[]])]})}},[Fe,N,C,ie,Pe]),(0,U.useEffect)(()=>{m||z.current?.focus()},[m]),(0,U.useEffect)(()=>{if(I&&z.current){let e=z.current,t=e.state.doc.toString().split(`
161
+ `),a=t.match(/^(\d{1,2}:\d{2}(?::\d{2})?)/m)?.[1],o=r[0]?.substring(0,60)||`Workout`,s=e.type===`time`||e.type===`log`?e.type:`time`;return{id:e.id,title:o,statementCount:r.length,contentPreview:i,timerHint:a,dialect:s}}),o={type:`rpc-workbench-update`,mode:r.length>0?`preview`:`idle`,previewData:r.length>0?{title:r[0].title,blocks:r}:void 0},s=JSON.stringify(o);if(s!==a.current){a.current=s;try{i.send(o)}catch{}}},[i,e,t,n]),(0,U.useEffect)(()=>{i?.connected||(a.current=``)},[i]),(0,U.useEffect)(()=>{t||(a.current=``)},[t]),(0,U.useEffect)(()=>{if(!(!i?.connected||!r||!n))return i.onMessage(t=>{if(t.type!==`rpc-event`||t.name!==`select-block`)return;let{index:i,blockId:a}=t.data??{},o=e.filter(e=>e.type===`time`),s=a?o.find(e=>e.id===a):o[i??0];if(!s||!n)return;let c=s.contentFrom!==void 0&&s.contentTo!==void 0?n.doc.sliceString(s.contentFrom,s.contentTo):``;r({id:s.id,dialect:s.type===`time`||s.type===`log`?s.type:`time`,sport:s.sport,startLine:s.startLine-1,endLine:s.endLine-1,content:c,state:`idle`,version:1,createdAt:Date.now(),widgetIds:{}})})},[i,e,n,r,t]),null},dQ={[q.Duration]:{label:`Timer`,icon:`⏱`,textClass:`text-metric-time`,bgClass:`bg-metric-time/10`,borderClass:`border-metric-time/30`},[q.Rep]:{label:`Reps`,icon:`✕`,textClass:`text-metric-rep`,bgClass:`bg-metric-rep/10`,borderClass:`border-metric-rep/30`},[q.Effort]:{label:`Exercise`,icon:`🏋`,textClass:`text-metric-effort`,bgClass:`bg-metric-effort/10`,borderClass:`border-metric-effort/30`},[q.Rounds]:{label:`Rounds`,icon:`↻`,textClass:`text-metric-rounds`,bgClass:`bg-metric-rounds/10`,borderClass:`border-metric-rounds/30`},[q.Distance]:{label:`Distance`,icon:`📏`,textClass:`text-metric-distance`,bgClass:`bg-metric-distance/10`,borderClass:`border-metric-distance/30`},[q.Resistance]:{label:`Weight`,icon:`⚖`,textClass:`text-metric-resistance`,bgClass:`bg-metric-resistance/10`,borderClass:`border-metric-resistance/30`},[q.Equipment]:{label:`Equipment`,icon:`🧰`,textClass:`text-foreground`,bgClass:`bg-muted/40`,borderClass:`border-border/50`},[q.Action]:{label:`Action`,icon:`⚡`,textClass:`text-metric-action`,bgClass:`bg-metric-action/10`,borderClass:`border-metric-action/30`},[q.Label]:{label:`Label`,icon:`🏷`,textClass:`text-muted-foreground`,bgClass:`bg-muted/30`,borderClass:`border-border/40`}},fQ={[q.Rep]:`reps`,[q.Effort]:`movement`,[q.Resistance]:`weight`},pQ=({metric:e,tooltip:t,isFocused:n,onClick:r})=>{let i=dQ[e.type],a=e.type===q.Hint,o=e.image??(e.value===void 0?``:String(e.value)),s=i?.label??String(e.type);return(0,W.jsxs)(`span`,{title:t,onClick:r,className:G(`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium`,`pointer-events-auto transition-opacity hover:opacity-80`,i?.bgClass??`bg-muted/30`,i?.textClass??`text-muted-foreground`,i?.borderClass??`border-border/40`,r&&`cursor-pointer`,n&&`font-bold shadow-sm`),children:[(0,W.jsx)(`span`,{children:a?e.icon:i?.icon??`•`}),!a&&(0,W.jsx)(`span`,{children:s}),!a&&o&&(0,W.jsx)(`span`,{className:`font-semibold`,children:o})]})};function mQ(e){let t=sa(e.metadata);return{refs:t?.refs??[],diagnostics:t?.diagnostics??[]}}function hQ(e,t){try{let n=e.coordsAtPos(t);if(!n)return null;let r=e.dom?.getBoundingClientRect?.()??{top:0,left:0},i=e.contentDOM?.getBoundingClientRect?.()??{left:0,width:0};return{top:n.bottom-r.top,left:i.left-r.left,width:i.width}}catch{return null}}var gQ=({view:e,cursorVersion:t,getCursorFocusState:n})=>{let[r,i]=(0,U.useState)(null),[a,o]=(0,U.useState)(null),s=(0,U.useRef)(null),c=(0,U.useCallback)(()=>{if(!e){o(null),i(null);return}let t=(n??zJ)(e.state);o(t),i(t?hQ(e,t.lineFrom):null)},[e,n]);if((0,U.useEffect)(()=>{c()},[c,t]),(0,U.useEffect)(()=>{if(!e)return;let t=()=>c();return window.addEventListener(`scroll`,t,!0),window.addEventListener(`resize`,t,!0),()=>{window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t,!0)}},[e,c]),!r||!a?.section)return null;let l=a.allStatements?.filter(e=>e.meta?.line===a.cursorLine-a.section.startLine)??(a.statement?[a.statement]:[]),u=l.flatMap(e=>e.metrics.toArray()).filter(e=>e.type!==q.Sound&&e.type!==q.System&&!(e.type===q.Hint&&!e.icon)),d=BW(u,`runtime-badge`),f=l.flatMap(e=>e.metrics.toArray()),p=[],m=[],h=[];for(let e of f){let t=mQ(e);for(let e of t.refs){let t=`${e.kind}:${e.slug}`;p.includes(t)||(p.push(t),m.push(e))}h.push(...t.diagnostics)}let g=[];for(let e of f){let t=ga(e.metadata);t&&(g.some(e=>e.slug===t.slug)||g.push(t))}let _=typeof e?.state?.facet==`function`?e.state.facet(SE)?.()??null:null,v=typeof e?.state?.doc?.sliceString==`function`?DJ(e.state.doc.sliceString(a.lineFrom,a.lineTo)):null,y=e=>e.reason===`conflict`||e.reason.endsWith(`equipment`)||e.reason===`invalid-explicit`&&e.token&&v?.equipment.includes(e.token)?`equipment`:`effort`,b=e=>typeof e==`string`&&e.trim()?e:null,x=async t=>{if(!e)return;let n=e.state.doc.sliceString(a.lineFrom,a.lineTo),r=ZH.getState();if(t===`effort`){let t=await r.open({placeholder:`Change effort…`,sources:[TJ(`effort`)]});if(t.dismissed)return;let i=b(t.item.payload);if(!i)return;e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:OJ(n,{effort:i})}});return}let i=[...v?.equipment??[]];for(;;){let e=await r.open({placeholder:i.length>0?`Add equipment (Esc to finish)…`:`Set equipment…`,sources:[TJ(`equipment`)]});if(e.dismissed)break;let t=b(e.item.payload);t&&!i.includes(t)&&i.push(t)}((v?.jsonFrom??-1)>=0||i.length>0)&&e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:OJ(n,{equipment:i})}})},S=async()=>{if(!e)return;let t=e.state.doc.sliceString(a.lineFrom,a.lineTo),n=ZH.getState(),r,i=await n.open({placeholder:`Add effort (Esc to skip)…`,sources:[TJ(`effort`)]});i.dismissed||(r=b(i.item.payload)??void 0);let o=[];for(;;){let e=await n.open({placeholder:`Add equipment (Esc to finish)…`,sources:[TJ(`equipment`)]});if(e.dismissed)break;let t=b(e.item.payload);t&&!o.includes(t)&&o.push(t)}!r&&o.length===0||e.dispatch({changes:{from:a.lineFrom,to:a.lineTo,insert:OJ(t,{effort:r,equipment:o})}})},C=async t=>{if(!e||!t.token)return;let n=y(t),r=await ZH.getState().open({placeholder:`Replace “${t.token}”…`,sources:[TJ(n,t.candidates)]});if(r.dismissed)return;let i=b(r.item.payload);if(!i)return;let o=e.state.doc.sliceString(a.lineFrom,a.lineTo).indexOf(t.token);o<0||e.dispatch({changes:{from:a.lineFrom+o,to:a.lineFrom+o+t.token.length,insert:i}})},w=t=>{let n=fQ[t.type];if(!n||!e)return;let r=t.type===q.Effort?`effort`:t.type===q.Equipment?`equipment`:null;if(r&&v?.jsonFrom!==void 0&&v.jsonFrom>=0){x(r);return}an(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-B_qji59I.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([3,1,0,2])).then(({runStatementBuilderFlow:t})=>{t(a,e,n)})};return(0,W.jsxs)(`div`,{ref:s,className:G(`cm-metric-inline-panel`,`absolute z-50 pointer-events-none`,`flex items-center gap-2 px-3 h-[28px]`,`bg-background/90 backdrop-blur-sm`,`border-l border-r border-border/50`,`transition-opacity duration-100`),style:{top:r.top,left:r.left,width:r.width,maxWidth:r.width},"aria-live":`polite`,"aria-label":`Metric inline panel`,children:[u.length>0?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground font-medium shrink-0 select-none`,children:`Metrics:`}),(0,W.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[u.map((e,t)=>(0,W.jsx)(pQ,{metric:e,tooltip:e.type===q.Hint?String(e.value??``):d[t]?.tooltip,isFocused:a.focusedMetric===e,onClick:fQ[e.type]?()=>w(e):void 0},`${e.type}-${t}`)),m.map(e=>(0,W.jsxs)(`span`,{title:`${e.kind===`effort`?`Effort`:`Equipment`} · click to change source`,onClick:()=>void x(e.kind),className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium cursor-pointer hover:opacity-80 bg-muted/40 text-foreground border-border/50`,children:[(0,W.jsx)(`span`,{children:e.kind===`effort`?`🏋`:`🧰`}),(0,W.jsx)(`span`,{className:`font-semibold`,children:e.label}),_&&(0,W.jsx)(`a`,{href:_.openHref(e.kind,e.slug),title:`Open ${e.label} page`,"aria-label":`Open ${e.label} page`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`${e.kind}:${e.slug}`)),g.map(e=>(0,W.jsxs)(`span`,{title:e.soundProfileId?`Tag ${e.label} · names the ${e.soundProfileId} sound profile`:`Tag ${e.label}`,className:`pointer-events-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium bg-muted/40 text-foreground border-border/50`,children:[(0,W.jsx)(`span`,{children:`#`}),(0,W.jsx)(`span`,{className:`font-semibold font-mono`,children:e.label}),_&&(0,W.jsx)(`a`,{href:_.openHref(`tag`,e.slug),title:`Open the ${e.label} tag`,"aria-label":`Open the ${e.label} tag`,className:`text-muted-foreground/70 hover:text-foreground`,onClick:e=>e.stopPropagation(),children:`↗`})]},`tag:${e.slug}`)),v?.malformed&&(0,W.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:`Reference JSON on this line does not parse — fix it in the raw text.`,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,W.jsx)(`span`,{children:`⚠`}),(0,W.jsx)(`span`,{children:`Malformed reference JSON`})]}),h.map((e,t)=>{let n=y(e);return(0,W.jsxs)(`span`,{"data-testid":`editor-ref-unknown`,title:e.message,className:`pointer-events-auto inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[11px] font-medium bg-destructive/10 text-destructive border-destructive/30`,children:[(0,W.jsx)(`span`,{children:`⚠`}),(0,W.jsx)(`span`,{children:e.token??e.reason}),(0,W.jsx)(`button`,{type:`button`,className:`underline cursor-pointer`,onClick:()=>void C(e),children:`Select existing`}),_&&(0,W.jsx)(`a`,{href:_.createHref(n),className:`underline hover:text-foreground`,children:`Create page`})]},`${e.reason}-${t}`)}),(0,W.jsx)(`button`,{type:`button`,"data-testid":`editor-add-metric-line`,title:`Add effort/equipment reference to this line`,onClick:()=>void S(),className:`pointer-events-auto inline-flex items-center px-1.5 py-0.5 rounded border border-dashed border-border/60 text-[10px] text-muted-foreground hover:text-foreground hover:border-primary/50 cursor-pointer`,children:`+ Metric`})]})]}):(0,W.jsx)(`span`,{className:`text-[10px] text-muted-foreground/50 italic select-none`,children:`No metrics on this line`}),(0,W.jsx)(`span`,{className:`ml-auto text-[9px] text-muted-foreground/40 shrink-0 select-none`,children:`Ctrl+↑↓ · adjust value`})]})},_Q=new ai,vQ=new ai,yQ=new ai;async function bQ(e){let t=new TextEncoder().encode(e);if(typeof CompressionStream<`u`)try{let e=new CompressionStream(`gzip`),n=e.writable.getWriter(),r=e.readable.getReader();n.write(t),n.close();let i=[];for(;;){let{done:e,value:t}=await r.read();if(e)break;i.push(t)}let a=i.reduce((e,t)=>e+t.length,0),o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.length;return btoa(String.fromCharCode(...o)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}catch{}return btoa(String.fromCharCode(...t)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}async function xQ(e){let t=await bQ(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`);return`${window.location.origin}/load?zip=${t}`}async function SQ(e){let t=await bQ(`\`\`\`time\n${e.trimEnd()}\n\`\`\`\n`),n=`shared by ${Mx()}`;return`${window.location.origin}/?z=${t}&by=${encodeURIComponent(n)}`}var CQ=({noteId:e,noteBlocks:t,sourceRevision:n=0,onIdentityChange:r,onSaved:i,beforeRun:a,onSaveRequest:o,onCommitChange:s,value:c,onChange:l,onDocUpdate:u,onCursorPositionChange:d,onBlur:f,theme:p=`vs`,readonly:m=!1,className:h=``,ariaLabel:g=`Note editor`,onStartWorkout:_,onCompleteWorkout:v,onBlocksChange:y,onAddToPlan:b,notePersistence:x,onViewCreated:S,mode:C=`edit`,lineWrapping:w=!0,showLineNumbers:T=!0,enablePreview:E=!0,showFrontmatter:D=!0,enableLinting:O=!0,enableOverlay:k=!1,commands:A,hideDefaultCommands:j=!1,enableInlineRuntime:M=!0,extensions:N,widgetComponents:P,activeSectionId:F,scrollToSectionId:I,results:L,placeholder:R})=>{let ee=(0,U.useRef)(null),z=(0,U.useRef)(null),ne=(0,U.useRef)(null),re=(0,U.useRef)(``),ie=p===`dark`||p===`vs-dark`,ae=kJ(ne,x),[oe,se]=(0,U.useState)(null),[ce,B]=(0,U.useState)([]),[le,V]=(0,U.useState)(1),[ue,de]=(0,U.useState)(0),fe=F??oe,pe=pY(ce,fe),[me,he]=(0,U.useState)(null),[ge,_e]=(0,U.useState)(null),[ve,ye]=(0,U.useState)(null),[be,xe]=(0,U.useState)(!1),Se=(0,U.useRef)(null),Ce=(0,U.useRef)(!1),we=(0,U.useRef)(n??0);(0,U.useEffect)(()=>{we.current=n??0},[n]);let[Te,Ee]=(0,U.useState)(null),De=(0,U.useRef)(null),Oe=(0,U.useCallback)(async(t,n=!1)=>{let r=z.current;if(!(!r||Ce.current)){Ce.current=!0,Ee(null);try{let o=await a?.();typeof o==`number`&&(we.current=o);let s=r.state.field(NT),c=await QR({noteId:e??ze(),rawContent:s.rawContent,blocks:s.noteBlocks,expectedSourceRevision:we.current,...e?{}:{metadata:{title:`Playground workout`},noteType:`playground`}},t,ze(),e?void 0:`playground`,ae);Se.current=c,De.current=null,we.current=c.note.sourceRevision,r.dispatch({effects:TT.of({blocks:c.note.blocks,sourceRevision:c.note.sourceRevision})}),i?.({rawContent:c.note.rawContent,blocks:c.note.blocks,sourceRevision:c.note.sourceRevision}),xe(n),_e(c.block),ye(c.session.id)}catch(e){Ee(e instanceof Error?e.message:String(e))}finally{Ce.current=!1}}},[e,ae,i,a]),ke=(0,U.useCallback)(()=>{_e(null),ye(null),xe(!1)},[]),Ae=(0,U.useCallback)(e=>{M&&Oe(e,!0)},[M,Oe]),je=(0,U.useRef)(null),Me=(0,U.useCallback)((e,t)=>{let n=je.current,r=n!==null&&n.results===t,i=Se.current;if(!i||!t)return Promise.reject(Error(`The saved run pin is unavailable.`));let a=i.session.id;if(De.current===a)return Promise.resolve();let o={id:i.block.id,contentId:i.session.blockContentId};if(!r&&t&&z.current){let t=z.current,n=QD(t.state,e,a);if(n){let e=n.from+n.insert.indexOf("```");t.dispatch({changes:n,effects:[Sr.scrollIntoView(e,{y:`start`,yMargin:96})]}),l?.(t.state.doc.toString())}}r||(je.current={results:t,resultId:a,runBlock:o});let s;try{s=kK(ae).record({resultId:a,noteId:i.session.noteId,blockId:i.session.blockId,data:t,createdAt:t.endTime}).then(()=>v?.(e,t,a,o))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}return Promise.resolve(s).then(()=>{je.current?.results===t&&(je.current=null),De.current=a},()=>{}),s},[l,v,ae]),Ne=(0,U.useMemo)(()=>{if(j)return[];if(A&&A.length>0)return A;let e=[];return M?e.push({id:`run`,label:`Run`,icon:(0,W.jsx)(wn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:Oe}):_&&e.push({id:`run`,label:`Run`,icon:(0,W.jsx)(wn,{className:`h-3 w-3 fill-current`}),primary:!0,onClick:_}),e.push({id:`playground`,label:`Playground`,icon:(0,W.jsx)(Ye,{className:`h-3 w-3`}),splitIcon:(0,W.jsx)(te,{className:`h-3 w-3`}),splitSuccessIcon:(0,W.jsx)(Tt,{className:`h-3 w-3`}),onClick:e=>{xQ(e.content).then(e=>{let t=window.open(e,`wodwiki-playground`);t&&t.focus()})},onSplitClick:async e=>{let t=await SQ(e.content);await navigator.clipboard.writeText(t)}}),b&&e.push({id:`plan`,label:`Plan`,icon:(0,W.jsx)(Rt,{className:`h-3 w-3`}),onClick:b}),e},[A,_,b,M,j,Oe]),Pe=(0,U.useMemo)(()=>ui({codeLanguages:RO}),[]),Fe=(0,U.useMemo)(()=>[...T?[Jr(),Rr()]:[],Br(),ci(),Tr(),li(),...w?[Sr.lineWrapping]:[],Qr.allowMultipleSelections.of(!0),Cr(),bi(),zr(),mi(),si.highest(hr.of([{key:`Tab`,run:e=>Pr(e.state)!==null&&(xi(e),!0)},{key:`Enter`,run:e=>{let t=e.state.selection.main,n=DQ(e.state,t.head),r=e.state.doc.lineAt(t.head);return!t.empty||n?.value.trim()!==``||r.text.slice(t.head-r.from).trim()?!1:(_r(e),aee(e))}}])),hr.of([...Nr,...Yr,...ii,...ri,...yi,...oi,Xr,{key:`Mod-s`,run:()=>(o?.(),!0)},{key:`Ctrl-.`,run:e=>{let t=zJ(e.state);if(!t?.focusedMetric)return!1;let n=t.focusedMetric.type;return!new Set([`duration`,`rep`,`rounds`,`distance`,`resistance`]).has(n)&&(an(()=>Promise.resolve().then(()=>XH).then(()=>{an(async()=>{let{runStatementBuilderFlow:e}=await import(`./statementBuilderFlow-B_qji59I.js`);return{runStatementBuilderFlow:e}},__vite__mapDeps([3,1,0,2])).then(({runStatementBuilderFlow:n})=>{n(t,e)}).catch(()=>{ZH.getState().open({placeholder:`Modify metric…`,sources:[]})})}),void 0),!0)}}]),iO,NT,ST.of({blocks:t??Pa(c,{sourceRevision:Math.max(1,n),registeredWidgets:P?[...P.keys()]:Oa}),sourceRevision:Math.max(1,n),rawContent:c}),CT.of(P?[...P.keys()]:Oa),PT,wE.of(D),...E||!D?[uD]:[],...E?[mE,_E,pJ(),SJ(),DD,xD(),RD]:[],...O?[zT]:[],rE,eT,GT,WT,KT.of(wQ),qT.of(TQ),...k?[aO]:[],aE,xT,HJ,...WD,_T,...P&&P.size>0?[LO(P)]:[],pO({executor:Mz,onResultSaved:DK,readOnly:m,noteHref:e=>DU(`blockContentId`in e||`dataType`in e?Qz(e):Kz(e))}),AJ(e,ae),Sr.domEventHandlers({blur:()=>(f?.(),!1)}),Sr.updateListener.of(e=>{if(e.docChanged){let t=e.state.field(NT);r?.({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:t.sourceRevision}),l(t.rawContent),u?.(e),kQ(e.state,y,re),e.transactions.some(e=>e.isUserEvent(`input`)||e.isUserEvent(`delete`)||e.isUserEvent(`paste`)||e.isUserEvent(`drop`))||s?.()}if(e.selectionSet||e.docChanged){de(e=>e+1),e.transactions.some(e=>e.isUserEvent(`delete.backward`))&&Pr(e.startState)!==null&&Pr(e.state)===null&&DQ(e.state,e.state.selection.main.head)?.value===``&&queueMicrotask(()=>{e.view.state===e.state&&$r(e.view)});let{head:t}=e.state.selection.main,n=e.state.doc.lineAt(t);d?.(n.number,t-n.from+1);let r=IT(e.state);se(r?.id??null),V(n.number);let{sections:i}=e.state.field(NT);B(i)}}),Qr.readOnly.of(m),Sr.editable.of(!m),...R?[hi(R)]:[],Sr.contentAttributes.of({"aria-label":g})],[l,d,f,u,y,r,m,o,s,T,w,E,D,O,k,e,ae,P,R,g]);return(0,U.useEffect)(()=>{let e=ee.current;if(!e)return;let t=Qr.create({doc:c,extensions:[...Fe,_Q.of(gT(ie)),vQ.of(Pe),yQ.of([]),...N??[]]}),n=new Sr({state:t,parent:e}),i=window.visualViewport,a=0,o=()=>{cancelAnimationFrame(a),a=requestAnimationFrame(()=>{n.hasFocus&&i?.scale===1&&i.height<window.innerHeight&&n.dispatch({effects:Sr.scrollIntoView(n.state.selection.main.head,{y:`nearest`,yMargin:24})})})};i?.addEventListener(`resize`,o),n.contentDOM.addEventListener(`focus`,o),z.current=n,he(n),e.__codemirrorView=n,S?.(n);let{sections:s}=n.state.field(NT);B(s);let l=n.state.doc.lineAt(n.state.selection.main.head).number;V(l);let u=IT(n.state);se(u?.id??null);let d=n.state.field(NT);return r?.({rawContent:d.rawContent,blocks:d.noteBlocks,sourceRevision:d.sourceRevision}),kQ(n.state,y,re),()=>{cancelAnimationFrame(a),i?.removeEventListener(`resize`,o),n.contentDOM.removeEventListener(`focus`,o),delete e.__codemirrorView,he(null),n.destroy()}},[]),(0,U.useEffect)(()=>{let e=z.current;if(!e)return;let r=e.state.field(NT);c===r.rawContent?t&&n!==r.sourceRevision&&e.dispatch({effects:TT.of({blocks:t,sourceRevision:Math.max(1,n)})}):e.dispatch({changes:{from:0,to:e.state.doc.length,insert:c},...t?{effects:ET.of({rawContent:c,blocks:t,sourceRevision:Math.max(1,n)})}:{}})},[c,t,n]),(0,U.useEffect)(()=>{z.current&&z.current.dispatch({effects:_Q.reconfigure(gT(ie))})},[ie]),(0,U.useEffect)(()=>{if(z.current){let e=[];z.current.dispatch({effects:[Kr.reconfigure.of([...Fe,_Q.of(gT(ie)),vQ.of(Pe),yQ.of(e),...N??[]])]})}},[Fe,N,C,ie,Pe]),(0,U.useEffect)(()=>{m||z.current?.focus()},[m]),(0,U.useEffect)(()=>{if(I&&z.current){let e=z.current,t=e.state.doc.toString().split(`
162
162
  `),n=-1,r=I.match(/-line-(\d+)$/);if(n=r?parseInt(r[1],10)-1:t.findIndex(e=>{let t=e.match(/^(#{1,6})\s+(.*)$/);if(t){let e=t[2].trim(),n=e.match(/(\d{1,2}:\d{2})/);if(n){let t=n[1];e=e.replace(t,``).replace(/\s+/g,` `).trim(),e||=t}return e.toLowerCase().replace(/[^\w]+/g,`-`)===I}return!1}),n>=0&&n<t.length){let t=e.state.doc.line(n+1).from;e.dispatch({selection:{anchor:t,head:t},effects:[Sr.scrollIntoView(t,{y:`start`,yMargin:20})]})}}},[I]),(0,W.jsxs)(`div`,{ref:ee,className:`cm-note-editor relative w-full min-w-0 ${h}`,children:[k&&(0,W.jsx)(cY,{view:me??z.current,widths:pe.widths,activeSectionId:fe,renderSlot:t=>{if(!D&&t.sectionType===`frontmatter`)return null;if(t.sectionType===`time`||t.sectionType===`log`)return(0,W.jsx)(LY,{noteId:e,sectionId:t.sectionId,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,cursorLine:le,docVersion:t.docVersion,commands:Ne,extendedResults:L,hoverLine:t.hoverLine,stickyTopOffset:t.stickyTopOffset,isPanelHovered:t.isPanelHovered,lineDocY:t.lineDocY,rect:t.rect});if(t.sectionType===`frontmatter`||t.sectionType===`embed`){let{sections:e}=t.view.state.field(NT),n=e.find(e=>e.id===t.sectionId);return(0,W.jsx)(_Y,{sectionId:t.sectionId,section:n,view:t.view,isActive:t.isActive,widthPercent:t.widthPercent,docVersion:t.docVersion})}return t.sectionType===`widget`&&t.widgetName?(0,W.jsx)(RY,{sectionId:t.sectionId,widgetName:t.widgetName,view:t.view,registry:P??new Map,docVersion:t.docVersion}):(0,W.jsx)(`div`,{className:`h-full w-full bg-popover/80 backdrop-blur-sm border-l border-border rounded-l-md p-2 text-xs text-muted-foreground`,children:(0,W.jsx)(`div`,{className:`font-medium text-foreground`,children:t.sectionType})})},cursorLine:le}),Te&&(0,W.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[`Workout not started. `,Te,` Your draft is kept.`]}),!k&&Ne.length>0&&(0,W.jsx)(lQ,{view:me??z.current,commands:Ne}),(0,W.jsx)(gQ,{view:me??z.current,cursorVersion:ue}),ge&&z.current&&(0,W.jsx)(nQ,{block:ge,view:me??z.current,onClose:ke,onCompleteWorkout:Me,resultId:ve??void 0,autoStart:be}),(0,W.jsx)(uQ,{sections:ce,isRuntimeActive:ge!==null,editorState:(me??z.current)?.state??null,onSelectBlock:Ae})]})},wQ=async e=>{if(!EQ(e.state,e.pos))return null;let t=e.state.doc.lineAt(e.pos),n=t.text.slice(0,e.pos-t.from).match(/^([a-zA-Z][\w.-]*)$/),r=DQ(e.state,e.pos);if(!n&&!r)return null;let[i,a]=await Promise.all([Z.getAllTagTypes().catch(()=>[]),Z.getAllTags().catch(()=>[])]);if(n)return{from:t.from,options:i.map(e=>({label:e.name,detail:`Tag Type (${e.label})`,type:`property`,apply:`${e.name}:\n - `})),validFor:(e,t,n,r)=>/^[a-zA-Z][\w.-]*$/.test(e)&&EQ(r,n)};if(!r)return null;let{propertyKey:o,from:s}=r,c={"metrics.effort":`effort`,"metrics.equipment":`equipment`,equipment:`equipment`}[o.toLowerCase()];if(c){let e=await CJ();return{from:s,options:(c===`effort`?e.efforts:e.equipment).map(e=>({label:`${e.label} (${e.slug})`,detail:c===`effort`?`Effort`:`Equipment`,type:`constant`,apply:e.slug})),validFor:(e,t,n,r)=>{let i=DQ(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}}let l=i.find(e=>e.name.toLowerCase()===o.toLowerCase());if(!l)return null;let u=a.filter(e=>e.type?.toLowerCase()===l.name.toLowerCase());return u.length===0?null:{from:s,options:u.map(e=>({label:e.label,detail:l.label,type:`constant`})),validFor:(e,t,n,r)=>{let i=DQ(r,n);return/^[\w-]*$/.test(e)&&i?.propertyKey===o&&i.from===t}}},TQ={wql:{values:async e=>(await Dw(e===`tags`?`tag`:e)).map(e=>({label:e.value,detail:e.label,type:`constant`}))},whiteboardScript:{efforts:async()=>(await CJ()).efforts.map(e=>({value:e.slug,label:`${e.label} (${e.slug})`})),equipment:async()=>(await CJ()).equipment.map(e=>({value:e.slug,label:`${e.label} (${e.slug})`})),tags:async()=>tM().list().map(e=>({value:e.slug})),sounds:()=>YJ().map(e=>({value:e.id,label:e.name}))}};function EQ(e,t){let n=e.doc.lineAt(t);if(n.number===1||e.doc.line(1).text.trim()!==`---`)return!1;for(let t=2;t<=n.number;t++)if(/^(---|\.\.\.)\s*$/.test(e.doc.line(t).text))return!1;return!0}function DQ(e,t){if(!EQ(e,t))return null;let n=e.doc.lineAt(t),r=n.text.slice(0,t-n.from),i=r.match(/^([a-zA-Z][\w.-]*)\s*:\s*(.*)$/);if(i)return{propertyKey:i[1],from:t-i[2].length,value:i[2]};let a=r.match(/^\s*-\s*(.*)$/);if(!a)return null;for(let r=n.number-1;r>1;r--){let n=e.doc.line(r).text.match(/^([a-zA-Z][\w.-]*)\s*:/);if(n)return{propertyKey:n[1],from:t-a[1].length,value:a[1]}}return null}function OQ(e,t){if(e.type!==`time`&&e.type!==`log`)return null;let n=e.contentFrom!==void 0&&e.contentTo!==void 0?t.doc.sliceString(e.contentFrom,e.contentTo):``,r=[];try{n.trim()&&(r=_c({tags:tM()}).read(n,e.sport).statements??[])}catch{}return{id:e.id,contentId:e.contentId,dialect:e.type,sport:e.sport,startLine:e.startLine-1,endLine:e.endLine-1,content:n,statements:r,state:`idle`,version:t.field(NT).noteBlocks[e.id]?.version??1,createdAt:Date.now(),widgetIds:{}}}function kQ(e,t,n){if(!t)return;let r=e.field(NT).sections.filter(e=>e.type===`time`||e.type===`log`).map(t=>OQ(t,e)).filter(e=>e!==null),i=JSON.stringify(r.map(e=>({id:e.id,startLine:e.startLine,endLine:e.endLine,content:e.content})));i!==n.current&&(n.current=i,t(r))}function AQ({title:e,subtitle:t,doc:n,onDocChange:r,noteId:i,onBlocksChange:a,theme:o,readonly:s=!1,showLineNumbers:c=!1,enableOverlay:l=!1,enableInlineRuntime:u=!1,enablePreview:d=!0,showFrontmatter:f=!1,enableLinting:p=!0,commands:m,hideDefaultCommands:h,onViewCreated:g,onReset:_,run:v,headerActions:y,subheader:b,children:x,className:S,editorClassName:C,bodyRef:w}){let T=(0,U.useRef)([]),E=(0,U.useCallback)(e=>{T.current=e,a?.(e)},[a]),D=(0,U.useCallback)(()=>{v?.onRun(n,T.current[0]??null)},[v,n]),O=(0,W.jsxs)(W.Fragment,{children:[y,v&&(0,W.jsxs)(`button`,{ref:v.ref,type:`button`,title:v.title??`Run the workout`,onClick:D,className:`inline-flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-[11px] font-medium text-primary-foreground transition-colors hover:bg-primary/90`,children:[(0,W.jsx)(wn,{size:11,fill:`currentColor`}),v.label??`Run`]})]});return(0,W.jsx)(fJ,{title:e,subtitle:t,onReset:_,headerActions:O,className:S,children:(0,W.jsxs)(`div`,{className:`flex h-full flex-col min-h-0`,children:[b,(0,W.jsxs)(`div`,{ref:w,className:G(`relative flex-1 min-h-0`,C),children:[(0,W.jsx)(CQ,{noteId:i,value:n,onChange:r,onBlocksChange:E,theme:o,readonly:s,showLineNumbers:c,enableOverlay:l,enableInlineRuntime:u,enablePreview:d,showFrontmatter:f,enableLinting:p,commands:m,hideDefaultCommands:h,onViewCreated:g,className:`h-full`}),x]})]})})}function jQ({editorSource:e,editorOpacity:t,activeOriginalSource:n,handleEditorChange:r,onResetToSource:i,canvasNoteId:a,theme:o,commands:s,onBlocksChange:c,onViewCreated:l,panelTitle:u,panelSubtitle:d,panelThemeClass:f,headerActions:p,onRun:m,readonly:h=!1,showFrontmatter:g}){return(0,W.jsx)(`div`,{className:`h-full`,style:{opacity:t,transition:`opacity 180ms ease`},children:(0,W.jsx)(AQ,{title:u,subtitle:d,doc:e,onDocChange:r,noteId:a,onBlocksChange:c,onViewCreated:l,theme:o,readonly:h,showLineNumbers:!1,showFrontmatter:g,enableOverlay:!1,enableInlineRuntime:!1,commands:s,hideDefaultCommands:!1,headerActions:p,className:f,subheader:(0,W.jsxs)(`div`,{style:{opacity:t,transition:`opacity 180ms ease`},className:`flex items-center justify-between gap-3 border-b border-border/40 bg-primary/5 px-4 py-2 text-[11px] font-bold uppercase tracking-[0.18em] text-muted-foreground`,children:[(0,W.jsx)(`span`,{children:`Try editing this example ↓`}),e===n?null:(0,W.jsx)(`button`,{type:`button`,onClick:()=>{i()},className:`rounded-full border border-primary/30 px-3 py-1 text-[10px] font-black text-primary transition-colors hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50`,children:`Reset to example`})]}),run:m?{onRun:m}:void 0})})}function MQ(e,t){return e>=t?`split`:`stack`}function NQ(e,t){let n=(0,U.useCallback)(()=>{if(typeof window>`u`)return{width:0,height:0,mode:`stack`};let t=window.innerWidth,n=Math.max(0,window.innerHeight-e);return{width:t,height:n,mode:MQ(t,n)}},[e]),[r,i]=(0,U.useState)(n);return(0,U.useEffect)(()=>{if(t&&typeof ResizeObserver<`u`){let e=new ResizeObserver(([e])=>{let{width:t,height:n}=e.contentRect;i(e=>e.width===t&&e.height===n?e:{width:t,height:n,mode:MQ(t,n)})});return e.observe(t),()=>e.disconnect()}let e=()=>i(e=>{let t=n();return e.width===t.width&&e.height===t.height?e:t});return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[t,n]),r}var PQ=e=>Math.max(0,Math.min(1,e)),FQ=(e,t,n)=>e+(t-e)*n,IQ=e=>1-(1-e)**2;function LQ(e,t){return e===``||t===e}var RQ={id:``,range:[0,1]};function zQ(e,t){if(!t||t.length===0)return{index:-1,stage:RQ,t:0,ring:null};let n=PQ(e),r=t.map(e=>({...e,start:PQ(Math.min(e.range[0],e.range[1])),end:PQ(Math.max(e.range[0],e.range[1]))})),i=r.findIndex(e=>n>=e.start&&n<e.end);i===-1&&(i=n>=1?r.length-1:0);let a=r[i]??RQ,o=(a.end??1)-(a.start??0),s=o>0?PQ((n-(a.start??0))/o):0,c=a.ring?{tag:a.ring===!0?void 0:a.ring.tag,key:a.ring===!0?void 0:a.ring.key,lines:a.ring===!0?void 0:a.ring.lines}:null;return{index:i,stage:a,t:s,ring:c}}function BQ(e,t,n){let r=t-n;return{progress:r>0?PQ(-e/r):0,reached:e<=0,inView:e<n&&e+t>0}}function VQ(e,t){let n=t/2;for(let t of e)if(t.top<=n&&t.bottom>n)return t.id;return null}var HQ=(0,U.createContext)(null);function UQ(){return(0,U.useContext)(HQ)}function WQ({children:e}){let t=(0,U.useRef)(new Map),n=(0,U.useRef)(new Map),r=(0,U.useRef)(null),i=(0,U.useRef)(0),[a,o]=(0,U.useState)(null),s=(0,U.useRef)(null),c=(0,U.useCallback)(e=>{r.current?.gateId===e&&(r.current=null,o(null))},[]),l=(0,U.useCallback)((e,t)=>{r.current={gateId:e,segmentId:t},o(e)},[]),u=(0,U.useCallback)(()=>{i.current&&cancelAnimationFrame(i.current),i.current=0;let e=window.innerHeight,a=new Map,c=(e,t)=>{let n=t();n&&a.set(e,n.getBoundingClientRect())};t.current.forEach((e,t)=>c(t,e)),n.current.forEach((e,t)=>c(t,e.getEl));let l=[];a.forEach((e,t)=>l.push({id:t,top:e.top,bottom:e.top+e.height}));let u=VQ(l,e);if(u!==s.current){s.current=u;let e=r.current;e&&e.segmentId!==u&&(r.current=null,o(null))}n.current.forEach((t,n)=>{let r=a.get(n);if(!r||r.height-e<=0)return;let i=BQ(r.top,r.height,e);t.onMeasure({slice:zQ(i.progress,t.getStages()),progress:i.progress,reached:i.reached})})},[]),d=(0,U.useCallback)(()=>{i.current||=requestAnimationFrame(u)},[u]);(0,U.useEffect)(()=>(window.addEventListener(`scroll`,d,{passive:!0,capture:!0}),window.addEventListener(`resize`,d),u(),()=>{window.removeEventListener(`scroll`,d,{capture:!0}),window.removeEventListener(`resize`,d),i.current&&cancelAnimationFrame(i.current)}),[d,u]);let f=(0,U.useCallback)((e,n)=>(t.current.set(e,n),d(),()=>{t.current.delete(e)}),[d]),p=(0,U.useCallback)((e,t)=>(n.current.set(e,t),d(),()=>{n.current.delete(e)}),[d]),m=(0,U.useCallback)(()=>u(),[u]),h=(0,U.useMemo)(()=>({registerAnchor:f,registerDriver:p,resync:m,capturedGateId:a,captureGate:l,releaseGate:c}),[f,p,m,a,l,c]);return(0,W.jsx)(HQ.Provider,{value:h,children:e})}function GQ(e,t){let n=UQ()?.registerAnchor;(0,U.useEffect)(()=>{if(n)return n(e,()=>t.current)},[n,e,t])}function KQ({gateId:e,segmentId:t,className:n,children:r}){let i=UQ(),a=(0,U.useRef)(null),[o,s]=(0,U.useState)(!1);if((0,U.useEffect)(()=>{let e=a.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.querySelectorAll(`.cm-scroller, [data-scroll-pane], .overflow-auto, .overflow-y-auto`);s(e.scrollHeight>e.clientHeight+1||[...t].some(e=>e.scrollHeight>e.clientHeight+1))},n=new ResizeObserver(t);n.observe(e);let r=0,i=new MutationObserver(()=>{t(),window.clearTimeout(r),r=window.setTimeout(t,400)});i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`]}),window.addEventListener(`resize`,t);let o=window.setTimeout(t,1200);return t(),()=>{window.clearTimeout(r),window.clearTimeout(o),n.disconnect(),i.disconnect(),window.removeEventListener(`resize`,t)}},[]),!i)return(0,W.jsx)(`div`,{className:n,children:r});let c=i.capturedGateId===e?`captured`:`yield`;return(0,W.jsxs)(`div`,{"data-scroll-gate":c,"data-gate-id":e,className:`${n??``} flex flex-col`,onFocus:n=>{let r=n.target;r instanceof HTMLElement&&r.closest(`input:not([readonly]):not([disabled]), textarea:not([readonly]):not([disabled]), select:not([disabled]), [contenteditable="true"]`)&&i.captureGate(e,t??null)},onBlur:t=>{(!(t.relatedTarget instanceof Node)||!t.currentTarget.contains(t.relatedTarget))&&i.releaseGate(e)},children:[(0,W.jsx)(`div`,{ref:a,className:`relative min-h-0 flex-1`,children:r}),(o||c===`captured`)&&(0,W.jsx)(`button`,{type:`button`,className:`min-h-11 self-start rounded px-3 py-2 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-primary`,"aria-label":`${c===`captured`?`Scroll page`:`Scroll panel`}: ${e.replace(/-/g,` `)} content`,"aria-pressed":c===`captured`,onClick:()=>c===`captured`?i.releaseGate(e):i.captureGate(e,t??null),onKeyDown:t=>{t.key===`Escape`&&i.releaseGate(e)},children:c===`captured`?`Scroll page`:`Scroll panel`})]})}function qQ({trackRef:e,height:t,stages:n,activeIndex:r,pane:i,captions:a,status:o,segmentId:s,testId:c,className:l}){let[u,d]=(0,U.useState)(null),f=NQ(104,u).mode===`split`,p={status:o,pips:(0,W.jsx)(`div`,{className:`flex items-center gap-1.5`,"aria-hidden":`true`,children:n.map((e,t)=>{let n=r===t;return(0,W.jsx)(`span`,{className:`h-1 rounded-full transition-all duration-300`,style:{width:n?30:10,background:n?e.accent??`hsl(var(--primary))`:r>t?`hsl(var(--foreground))`:`hsl(var(--foreground) / 0.15)`}},e.id)})})};return(0,W.jsx)(`section`,{ref:e,"data-testid":c,className:l?`relative ${l}`:`relative`,style:{height:t},children:(0,W.jsx)(uJ.Provider,{value:p,children:(0,W.jsx)(`div`,{className:`sticky top-[65px] flex h-[calc(100dvh-65px)] flex-col overflow-hidden lg:top-[104px] lg:h-[calc(100dvh-104px)]`,children:(0,W.jsxs)(`div`,{ref:d,className:`mx-auto flex min-h-0 w-full max-w-[1500px] 2xl:max-w-[1720px] flex-1 px-5 pt-2 pb-5 lg:px-10 lg:pt-3 xl:px-16 xl:pb-8 2xl:pb-10 ${f?`flex-row items-stretch gap-[clamp(20px,2.5vw,56px)] xl:gap-12 2xl:gap-16`:`flex-col gap-6 xl:gap-8`}`,children:[(0,W.jsx)(`div`,{className:`relative min-h-0 min-w-0 flex-[3_1_0%]`,children:i}),(0,W.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-[2_1_0%] flex-col`,children:s?(0,W.jsx)(KQ,{gateId:`${s}-captions`,segmentId:s,className:`relative min-h-0 flex-1`,children:a}):(0,W.jsx)(`div`,{className:`relative min-h-0 flex-1`,children:a})})]})})})})}function JQ(e){let t=e.parentElement;for(;t;){let e=window.getComputedStyle(t).overflowY;if(e===`auto`||e===`scroll`)return t;t=t.parentElement}return window}function YQ(e,t,n=`smooth`){let r=JQ(e),i=e.offsetHeight-window.innerHeight;if(i<=0)return;if(r instanceof HTMLElement){let a=e.offsetTop;r.scrollTo({top:a+t*i,behavior:n});return}let a=e.getBoundingClientRect().top+window.scrollY;window.scrollTo({top:a+t*i,behavior:n})}function XQ(e,t,n,r){let[i,a]=(0,U.useState)(()=>zQ(0,n)),[o,s]=(0,U.useState)(!1),c=(0,U.useRef)(0),l=(0,U.useRef)(i),u=(0,U.useRef)(new Set),d=(0,U.useRef)(0),f=(0,U.useRef)(t);f.current=t;let p=UQ(),m=p?.registerDriver,h=(0,U.useRef)(p);h.current=p;let g=(0,U.useId)(),_=r??g,v=(0,U.useRef)(n);v.current=n;let y=(0,U.useCallback)((e,t)=>{let n=l.current;l.current=e,c.current=t,(n.index!==e.index||n.ring?.key!==e.ring?.key)&&a(e),u.current.forEach(n=>n(e,t))},[]),b=(0,U.useCallback)(()=>{if(d.current=0,f.current)return;let t=e.current;if(!t)return;let n=t.getBoundingClientRect(),r=n.height-window.innerHeight;if(r<=0)return;let i=Math.max(0,Math.min(1,-n.top/r));s(n.top<=0),y(zQ(i,v.current),i)},[e,y]),x=(0,U.useCallback)(()=>{if(h.current){h.current.resync();return}b()},[b]),S=(0,U.useCallback)(()=>{d.current||=requestAnimationFrame(x)},[x]);(0,U.useEffect)(()=>{if(m)return m(_,{getEl:()=>e.current,getStages:()=>v.current,onMeasure:({slice:e,progress:t,reached:n})=>{f.current||(s(n),y(e,t))}})},[m,_,e,y]),(0,U.useEffect)(()=>{if(!m)return window.addEventListener(`scroll`,S,{passive:!0,capture:!0}),window.addEventListener(`resize`,S),b(),()=>{window.removeEventListener(`scroll`,S,{capture:!0}),window.removeEventListener(`resize`,S),d.current&&cancelAnimationFrame(d.current)}},[m,S,b]);let C=(0,U.useCallback)(e=>(u.current.add(e),e(l.current,c.current),()=>{u.current.delete(e)}),[]),w=(0,U.useCallback)(()=>{x()},[x]);return{slice:i,progress:c.current,runwayReached:o,subscribe:C,resync:w}}var ZQ={reference:!0},QQ={start:[[`fences`,`first-workout`],[`measurements`,`actions-comments`],[`system`,`try-it`]],protocols:[[`countdown-countup`,`required-rest`],[`amrap`,`emom`],[`tabata-intervals`,`caps`,`distance-intervals`,`try-it`]],structure:[[`rounds`,`rep-schemes`,`sets`],[`nesting`,`rep-math`,`named-sections`,`try-it`]],metrics:[[`planned-vs-recorded`,`custom-metrics`],[`capture`,`session-rpe`],[`calculated`,`try-it`]],clock:[[`run-next`,`pause-skip`],[`capture-prompts`,`casting`,`provenance`,`try-it`]],wql:[[`planes`,`aggregate`,`filters`,`sources`],[`windows`,`grouping-rollup`,`joins`],[`content`,`pipes`,`try-it`]],dashboards:[[`note-frontmatter`,`avg-tis`,`weekly-tonnage`,`widgets`],[`composer`,`cookbook`,`seeded-boards`,`try-it`]],sessions:[[`intent`,`full-session`],[`nested`,`partner`,`swimming`],[`barbell-cycling`,`climbing`,`try-it`]],"metrics-summaries":[[`frontmatter-metrics`,`tag-summaries`,`stacking-overrides`],[`querying-summaries`,`dependency-diagnostics`,`try-it`]]};function $Q(e,t){let n=e.filter(e=>!ZQ[e.id]),r=e.filter(e=>ZQ[e.id]);if(n.length===0)return{groups:[],tail:r};let i=t?QQ[t]:void 0;if(i){let e=new Map(n.map(e=>[e.id,e])),t=new Set,a=[];for(let n of i){let r=n.map(t=>e.get(t)).filter(e=>!!e&&!t.has(e.id));for(let e of r)t.add(e.id);r.length>0&&a.push(r)}let o=n.filter(e=>!t.has(e.id));if(o.length>0){let e=a[a.length-1];if(e&&e.length+o.length<=4)e.push(...o);else for(let e=0;e<o.length;e+=4)a.push(o.slice(e,e+4))}if(a.length>0)return{groups:a,tail:r}}let a=Math.max(1,Math.ceil(n.length/4)),o=Math.floor(n.length/a),s=n.length%a,c=[],l=0;for(let e=0;e<a;e++){let t=o+ +(e<s);c.push(n.slice(l,l+t)),l+=t}return{groups:c,tail:r}}function e$(e){let t=Math.max(1,e.length);return e.map((e,n)=>({id:e.id,range:[n/t,(n+1)/t]}))}var t$=[{src:`/images/hero/editing.png`,alt:`WhiteboardScript editor with live syntax highlighting and inline previews`,eyebrow:`Write`,title:`Type your workout in plain Markdown.`,caption:"Movements, reps, time caps, and rounds — fenced in a familiar ```time block. No drag-and-drop. No proprietary DSL."},{src:`/images/hero/timer.png`,alt:`Live runtime timer HUD counting down an interval with active round and rest indicators`,eyebrow:`Run`,title:`Press Run. The compiler takes over.`,caption:`Your Markdown becomes a live wallclock. The JIT engine dispatches rounds, counts reps, and tracks rest — all offline.`},{src:`/images/hero/journal.png`,alt:`Unified Library listing journal notes, notebook workouts, and dated entries`,eyebrow:`Library`,title:`Browse Journal and Notebook notes in one Library.`,caption:`Your dated journal notes and preloaded notebook benchmarks live in one unified surface. Search, filter by source, or clone to today’s note.`},{src:`/images/hero/results.png`,alt:`WQL Metric Explorer displaying volume trends and embedded dashboard blocks`,eyebrow:`Query`,title:`Ask questions with Wod Query Language (WQL).`,caption:`Aggregate volume, track TIS intensity trends, or embed live query and dashboard blocks directly in your Markdown notes.`}];function n$({slides:e=t$,className:t}){let n=(0,U.useRef)(null),[r,i]=(0,U.useState)(0);(0,U.useEffect)(()=>{let t=n.current;if(!t)return;let r=()=>{let n=t.clientWidth,r=Math.round(t.scrollLeft/n);i(Math.min(Math.max(r,0),e.length-1))};return t.addEventListener(`scroll`,r,{passive:!0}),()=>t.removeEventListener(`scroll`,r)},[e.length]);let a=e=>{let t=n.current;t&&t.scrollTo({left:e*t.clientWidth,behavior:`smooth`})};return(0,W.jsxs)(`div`,{className:G(`relative w-full`,t),children:[(0,W.jsx)(`div`,{ref:n,className:`flex w-full snap-x snap-mandatory overflow-x-auto scroll-smooth scrollbar-none`,style:{scrollbarWidth:`none`},children:e.map((t,n)=>(0,W.jsxs)(`article`,{className:`relative flex w-full shrink-0 snap-start flex-col gap-4 sm:flex-row sm:items-center sm:gap-8`,"aria-label":`Slide ${n+1} of ${e.length}: ${t.title}`,children:[(0,W.jsx)(`div`,{className:`relative aspect-[16/10] w-full overflow-hidden rounded-2xl border border-border/60 bg-muted shadow-sm sm:w-1/2`,children:(0,W.jsx)(`img`,{src:t.src,alt:t.alt,loading:n===0?`eager`:`lazy`,className:`h-full w-full object-cover`})}),(0,W.jsxs)(`div`,{className:`flex w-full flex-col gap-2 sm:w-1/2 sm:gap-3`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-black uppercase tracking-[0.24em] text-primary/80`,children:t.eyebrow}),(0,W.jsx)(`h3`,{className:`text-2xl font-black tracking-[-0.04em] text-foreground sm:text-3xl`,children:t.title}),(0,W.jsx)(`p`,{className:`text-sm leading-7 text-muted-foreground sm:text-base`,children:t.caption}),(0,W.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground`,children:[(0,W.jsxs)(`span`,{className:`text-primary`,children:[`Step `,n+1]}),(0,W.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),(0,W.jsx)(`span`,{children:e.length})]})]})]},t.src))}),(0,W.jsx)(`div`,{className:`mt-4 flex items-center justify-center gap-2`,children:e.map((e,t)=>(0,W.jsx)(`button`,{type:`button`,onClick:()=>a(t),"aria-label":`Go to slide ${t+1}: ${e.title}`,"aria-current":t===r?`true`:`false`,className:G(`h-2 rounded-full transition-all`,t===r?`w-8 bg-primary`:`w-2 bg-border hover:bg-muted-foreground/40`)},e.src))})]})}var r$=`wodwiki:text-filter-navigation`,i$=({paramName:e=`q`,placeholder:t=`Search…`,autoFocus:n=!1,className:r,navigationScope:i,inputTestId:a})=>{let[s,c]=ln(e,{defaultValue:``}),l=i??e,u=(0,U.useRef)(null);return(0,U.useEffect)(()=>{let e=e=>{e.key===`/`&&document.activeElement?.tagName!==`INPUT`&&document.activeElement?.tagName!==`TEXTAREA`&&(e.preventDefault(),u.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,W.jsxs)(`div`,{className:G(`flex items-center gap-3 px-6 lg:px-10 pb-3`,r),children:[(0,W.jsx)(o,{className:`size-5 text-muted-foreground shrink-0`}),(0,W.jsx)(`input`,{ref:u,type:`text`,"data-testid":a,value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{if(e.altKey||e.ctrlKey||e.metaKey||![`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Enter`].includes(e.key))return;let t=new CustomEvent(r$,{detail:{key:e.key,scopeId:l},cancelable:!0});window.dispatchEvent(t),t.defaultPrevented&&e.preventDefault()},placeholder:t,autoFocus:n,autoComplete:`off`,spellCheck:!1,className:`flex-1 bg-transparent border-none outline-none text-foreground placeholder:text-muted-foreground text-sm sm:text-base font-medium`}),s&&(0,W.jsx)(`button`,{onClick:()=>c(``),"aria-label":`Clear`,className:`text-muted-foreground hover:text-foreground transition-colors text-lg leading-none`,children:`×`})]})};function a$(e){let t=[],n=!1;for(let r of e){if(r.trim()===`---`){n=!n;continue}n||t.push(r)}return t}function o$(e){let t=e;return t=t.replace(/\*\*([^*]+)\*\*/g,`$1`),t=t.replace(/__([^_]+)__/g,`$1`),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`),t=t.replace(/\*\*/g,``),t=t.replace(/__/g,``),t=t.replace(/`/g,``),t.trim()}function s$(e){return new Date(e).toISOString().slice(0,10)}function c$(e,t){let n=t.trim().toLowerCase();return!n||e.name.toLowerCase().includes(n)||e.content.toLowerCase().includes(n)||e.date!==void 0&&s$(e.date).includes(n)}function l$(e){if(!e)return null;let t=a$(rb(e).split(`
163
163
  `)).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)&&!e.startsWith("```"))[0];return t?o$(t):null}var u$=({category:e,workoutItems:t,onSelect:n,showSearch:r=!0,variant:i=`card`,className:a,navigationScope:o=`q`,getItemActions:s})=>{let[c]=ln(`q`,{defaultValue:``}),[l,u]=(0,U.useState)(0),[d,f]=(0,U.useState)(0),p=(0,U.useRef)([]),m=(0,U.useMemo)(()=>t.filter(t=>t.category===e&&t.name.toLowerCase()!==`readme`).filter(e=>c$(e,c)),[t,e,c]),h=(0,U.useMemo)(()=>m.map(e=>({item:e,preview:l$(e.content),actions:s?.(e)??[{id:`open`,label:`Open`,onSelect:n}]})),[m,s,n]);return(0,U.useEffect)(()=>{if(h.length===0){u(0),f(0);return}let e=Math.min(l,h.length-1),t=h[e]?.actions.length??1;e!==l&&u(e),d>t-1&&f(t-1)},[h,d,l]),(0,U.useEffect)(()=>{p.current=[]},[h]),(0,U.useEffect)(()=>{u(0),f(0)},[c]),(0,U.useEffect)(()=>{(p.current[l]?.[d])?.scrollIntoView({block:`nearest`,inline:`nearest`})},[d,l]),(0,U.useEffect)(()=>{let e=e=>{let t=e;if(t.detail.scopeId===o&&h.length!==0)switch(t.detail.key){case`ArrowDown`:t.preventDefault(),u(e=>Math.min(e+1,h.length-1)),f(0);break;case`ArrowUp`:t.preventDefault(),u(e=>Math.max(e-1,0)),f(0);break;case`ArrowRight`:{let e=h[l]?.actions.length??1;if(e<=1)return;t.preventDefault(),f(t=>Math.min(t+1,e-1));break}case`ArrowLeft`:if((h[l]?.actions.length??1)<=1)return;t.preventDefault(),f(e=>Math.max(e-1,0));break;case`Enter`:{let e=h[l]?.actions[d],n=h[l]?.item;if(!e||!n)return;t.preventDefault(),e.onSelect(n);break}}};return window.addEventListener(r$,e),()=>{window.removeEventListener(r$,e)}},[h,o,d,l]),(0,W.jsxs)(`div`,{className:G(`flex flex-col`,i===`card`&&`rounded-3xl border border-border bg-card overflow-hidden shadow-2xl shadow-black/5`,a),children:[r?(0,W.jsx)(`div`,{className:`border-b border-border/60 bg-background/95 backdrop-blur-md`,children:(0,W.jsx)(i$,{placeholder:`Filter collection workouts…`,className:`pt-3`,navigationScope:o})}):null,h.length===0?(0,W.jsx)(`div`,{className:`px-6 py-10 text-sm font-medium text-muted-foreground`,children:`No workouts found.`}):(0,W.jsx)(`div`,{className:`divide-y divide-border/60`,role:`listbox`,"aria-label":`Collection workouts`,children:h.map((e,t)=>{let n=t===l;return(0,W.jsx)(`div`,{role:`option`,"aria-selected":n,className:G(`flex items-stretch gap-2 px-3 py-2 transition-colors`,n?`bg-muted/50`:`hover:bg-muted/40`),children:e.actions.map((r,i)=>{let a=i===0;return(0,W.jsx)(`button`,{ref:e=>{p.current[t]||(p.current[t]=[]),p.current[t][i]=e},onClick:()=>r.onSelect(e.item),onMouseEnter:()=>{u(t),f(i)},className:G(`transition-colors text-left`,a?`flex-1 flex items-center gap-4 rounded-2xl px-3 py-2 hover:bg-background/80`:`shrink-0 self-center rounded-full border border-border px-3 py-2 text-[11px] font-black uppercase tracking-[0.18em] text-muted-foreground hover:bg-background/80 hover:text-foreground`,n&&i===d&&`bg-background text-foreground ring-2 ring-primary/40`),children:a?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:`flex-shrink-0 size-10 rounded-xl bg-muted flex items-center justify-center transition-colors`,children:(0,W.jsx)(k,{className:`size-4 text-primary`})}),(0,W.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,W.jsx)(`h3`,{className:`text-sm font-bold text-foreground truncate uppercase tracking-tight`,children:e.item.displayName??e.item.name}),e.preview?(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground font-medium truncate mt-1`,children:e.preview}):null]}),e.item.date===void 0?null:(0,W.jsx)(`span`,{className:`shrink-0 self-center text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:Gy(new Date(e.item.date))}),(0,W.jsx)(_t,{className:`size-4 text-muted-foreground shrink-0 transition-opacity`})]}):r.label},r.id)})},e.item.id)})})]})};function d$(){return(0,U.useEffect)(()=>{Ez().catch(e=>console.warn(`[queryService] page source population failed`,e))},[]),(0,U.useSyncExternalStore)(kz,Oz)}function f$(e,t){let n=e.find(e=>e.key===t&&!e.negate);return n&&n.values.length===1?n.values[0].value:null}function p$(e){let t=e.trim();if(!t.startsWith(`:`))return null;let n=HF(t),r=X(n);if(r.error||!eh(r))return null;let i=`?q=${encodeURIComponent(n)}`;switch(r.target){case`effort`:return`/efforts${i}`;case`session`:case`segment`:case`event`:return`/sessions${i}`;case`notebook`:{let e=f$(r.filters,`notebook`);if(e){let t=wa(e);return`/notebook/${encodeURIComponent(t)}${i}`}return`/notebooks${i}`}case`page`:return`/pages${i}`;case`tag`:return`/tags${i}`;case`equipment`:return`/equipment${i}`;case`note`:case`block`:{let e=f$(r.filters,`notebook`);if(e){let t=wa(e);return t===`journal`?`/journal${i}`:t===`playground`?`/playgrounds${i}`:`/notebook/${encodeURIComponent(t)}${i}`}let t=f$(r.filters,`source`);return t===`journal`?`/journal${i}`:t===`playground`?`/playgrounds${i}`:t===`feeds`||t===`notebooks`||t===`notebook`||t===`guides`?`/notes${i}`:f$(r.filters,`type`)===`dashboard`?`/dashboards${i}`:`/notes${i}`}default:return null}}var m$=new Set([`pdf`,`doc`,`docx`,`xls`,`xlsx`,`ppt`,`pptx`,`zip`,`tar`,`gz`,`rar`,`mp4`,`mov`,`avi`,`mkv`,`webm`,`mp3`,`wav`,`flac`,`png`,`jpg`,`jpeg`,`gif`,`svg`,`webp`]);function h$(e){let t=e.split(`.`).pop()?.split(`?`)[0]?.toLowerCase()??``;return m$.has(t)}function g$(e){return/^https?:\/\//.test(e)||e.startsWith(`//`)}function _$({queryText:e,widgetType:t,widgetError:n}){return d$()?(0,W.jsx)(`div`,{className:`my-5 not-prose`,children:(0,W.jsx)(uT,{query:e,widgetType:t,widgetError:n,executor:Mz,readOnly:!0,noteHref:e=>DU(`blockContentId`in e||`dataType`in e?Qz(e):Kz(e))})}):(0,W.jsx)(`div`,{className:`my-5 not-prose text-xs text-muted-foreground py-2`,children:`Loading…`})}function v$(e){let{meta:t,body:n}=Qy(e);return Object.keys(t).length===0&&n===e?{fields:null,body:e}:{fields:t,body:n.trim()}}var y$={table({children:e}){return(0,W.jsx)(`div`,{className:`my-6 overflow-x-auto rounded-xl border border-border`,children:(0,W.jsx)(`table`,{className:`w-full text-sm border-collapse`,children:e})})},thead({children:e}){return(0,W.jsx)(`thead`,{className:`bg-muted/50 text-left`,children:e})},tbody({children:e}){return(0,W.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e})},tr({children:e}){return(0,W.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e})},th({children:e}){return(0,W.jsx)(`th`,{className:`px-4 py-2.5 text-[11px] font-black tracking-widest uppercase text-muted-foreground border-b border-border`,children:e})},td({children:e}){return(0,W.jsx)(`td`,{className:`px-4 py-2.5 text-sm text-foreground`,children:e})},img({src:e,alt:t,node:n}){let r=n?.properties??{},i=r.width,a=r.height;return(0,W.jsxs)(`figure`,{className:`my-6`,children:[(0,W.jsx)(`img`,{src:e??``,alt:t??``,loading:`lazy`,width:i,height:a,className:`rounded-xl border border-border max-w-full h-auto`}),t&&(0,W.jsx)(`figcaption`,{className:`mt-2 text-center text-xs text-muted-foreground italic`,children:t})]})},a({href:e,children:t}){let n=e??``;if(n.startsWith(`:`)){let e=n;try{e=decodeURIComponent(n)}catch{}let r=p$(e);if(r)return(0,W.jsx)(Vn,{to:r,className:`underline underline-offset-2 transition-colors text-primary hover:text-primary/70`,children:t})}let r=g$(n),i=h$(n);return(0,W.jsxs)(`a`,{href:n,rel:r?`noopener noreferrer`:void 0,target:r||i?`_blank`:void 0,className:G(`underline underline-offset-2 transition-colors`,i?`text-primary font-medium`:`text-primary hover:text-primary/70`),children:[t,r&&(0,W.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`↗`}),i&&!r&&(0,W.jsx)(`span`,{className:`ml-0.5 text-[10px] align-super opacity-60`,children:`⬇`})]})},code({children:e,className:t}){let n=t?.replace(`language-`,``)??``,r=typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``);if(!t&&!r.includes(`
164
164
  `))return(0,W.jsx)(`code`,{className:`px-1.5 py-0.5 rounded-md bg-muted font-mono text-[0.85em] text-foreground`,children:e});if(n===`query`||n.startsWith(`query:`)||n.startsWith(`query `)){let t=(typeof e==`string`?e:Array.isArray(e)?e.join(``):String(e??``)).trim(),r=n.replace(/^query[:\s]?/,``).trim(),i=r?av(r):void 0;return(0,W.jsx)(_$,{queryText:t,widgetType:i?.type,widgetError:i?.error})}return(0,W.jsxs)(`div`,{className:`my-5 rounded-xl overflow-hidden border border-border`,children:[n&&(0,W.jsx)(`div`,{className:`flex items-center gap-2 px-4 py-2 bg-muted border-b border-border`,children:(0,W.jsx)(`span`,{className:`text-[10px] font-black tracking-widest uppercase text-muted-foreground`,children:n})}),(0,W.jsx)(`pre`,{className:`overflow-x-auto p-4 bg-muted/30`,children:(0,W.jsx)(`code`,{className:`font-mono text-sm text-foreground`,children:e})})]})},h1({children:e,id:t}){return(0,W.jsx)(`h1`,{id:t,className:`text-2xl lg:text-3xl font-black tracking-tight text-foreground uppercase leading-tight mt-10 mb-4 first:mt-0`,children:e})},h2({children:e,id:t}){return(0,W.jsx)(`h2`,{id:t,className:`text-xl lg:text-2xl font-black tracking-tight text-foreground uppercase leading-tight mt-8 mb-3 first:mt-0`,children:e})},h3({children:e,id:t}){return(0,W.jsx)(`h3`,{id:t,className:`text-base lg:text-lg font-black tracking-wide text-foreground uppercase mt-6 mb-2 first:mt-0`,children:e})},h4({children:e,id:t}){return(0,W.jsx)(`h4`,{id:t,className:`text-sm font-black tracking-widest text-primary uppercase mt-5 mb-2 first:mt-0`,children:e})},p({children:e}){return(0,W.jsx)(`p`,{className:`text-sm lg:text-[15px] font-medium text-muted-foreground leading-relaxed my-4 first:mt-0`,children:e})},ul({children:e}){return(0,W.jsx)(`ul`,{className:`my-4 pl-5 space-y-1.5 list-disc list-outside text-left text-sm text-muted-foreground font-medium leading-relaxed`,children:e})},ol({children:e}){return(0,W.jsx)(`ol`,{className:`my-4 pl-5 space-y-1.5 list-decimal list-outside text-left text-sm text-muted-foreground font-medium leading-relaxed`,children:e})},li({children:e}){return(0,W.jsx)(`li`,{className:`leading-relaxed`,children:e})},blockquote({children:e}){return(0,W.jsx)(`blockquote`,{className:`my-5 pl-4 border-l-2 border-primary/40 text-muted-foreground italic text-sm`,children:e})},hr(){return(0,W.jsx)(`hr`,{className:`my-8 border-border/50`})},strong({children:e}){return(0,W.jsx)(`strong`,{className:`font-black text-foreground`,children:e})},em({children:e}){return(0,W.jsx)(`em`,{className:`italic text-foreground/80`,children:e})}},b$={...y$,p({children:e}){return(0,W.jsx)(`p`,{className:`text-3xl sm:text-4xl lg:text-5xl font-black tracking-tight text-foreground leading-[1.08] my-0`,children:e})},strong({children:e}){let t=U.Children.toArray(e).map(e=>typeof e==`string`||typeof e==`number`?String(e):``).join(``).trim();return t.includes(`Write it in Markdown`)&&t.includes(`Run it as a Timer`)&&t.includes(`Own the Analytics`)?(0,W.jsxs)(`span`,{className:`flex flex-col select-none mt-4 w-full gap-5 sm:gap-7`,children:[(0,W.jsxs)(`span`,{className:`block text-3xl sm:text-4xl lg:text-5xl text-primary font-black text-left pl-[5%] sm:pl-[10%] transform hover:translate-x-1 transition-transform duration-200`,children:[`Write it in `,(0,W.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Markdown`}),`.`]}),(0,W.jsxs)(`span`,{className:`block text-3xl sm:text-4xl lg:text-5xl text-primary font-black text-center transform hover:scale-[1.02] transition-transform duration-200`,children:[(0,W.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Run`}),` it as a Timer.`]}),(0,W.jsxs)(`span`,{className:`block text-3xl sm:text-4xl lg:text-5xl text-primary font-black text-right pr-[5%] sm:pr-[10%] transform hover:-translate-x-1 transition-transform duration-200`,children:[`Own the `,(0,W.jsx)(`span`,{className:`inline-block border-b-4 border-primary/70 pb-1 hover:scale-105 transition-transform duration-200`,children:`Analytics`}),`.`]})]}):(0,W.jsx)(`strong`,{className:`font-black text-foreground`,children:e})}},x$={...y$,p({children:e}){return(0,W.jsx)(`p`,{className:`text-base lg:text-lg font-medium text-foreground/75 leading-relaxed my-4 first:mt-0`,children:e})}},S$=[Bn];function C$(e){return e.startsWith(`:`)?e:iee(e)}function w$(e){return e.type===`text`&&typeof e.value==`string`?e.value:(e.children??[]).map(w$).join(``)}function T$(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N} _-]/gu,``).replace(/ /g,`-`).replace(/-+/g,`-`)||`heading`}var E$=()=>e=>{let t=new Map,n=e=>{if(e.tagName&&/^h[1-6]$/.test(e.tagName)){let n=T$(w$(e)),r=t.get(n)??0;t.set(n,r+1),(e.properties??={}).id=r===0?n:`${n}-${r}`}for(let t of e.children??[])n(t)};n(e)};function D$({fields:e}){let t=Object.entries(e);return t.length===0?null:(0,W.jsxs)(`div`,{className:`my-6 rounded-xl border border-border bg-muted/30 overflow-hidden`,children:[(0,W.jsx)(`div`,{className:`px-4 py-2 border-b border-border bg-muted/50`,children:(0,W.jsx)(`span`,{className:`text-[10px] font-black tracking-[0.2em] uppercase text-muted-foreground`,children:`Metadata`})}),(0,W.jsx)(`dl`,{className:`divide-y divide-border/50`,children:t.map(([e,t])=>(0,W.jsxs)(`div`,{className:`flex items-baseline gap-4 px-4 py-2`,children:[(0,W.jsx)(`dt`,{className:`text-[11px] font-semibold text-muted-foreground uppercase tracking-wide min-w-[100px] shrink-0`,children:e}),(0,W.jsx)(`dd`,{className:`text-sm text-foreground break-words`,children:Array.isArray(t)?t.join(`, `):String(t)})]},e))})]})}var O$={default:y$,heroLead:b$,heroBody:x$};function k$({prose:e,className:t,variant:n=`default`}){if(!e)return null;let{fields:r,body:i}=v$(e);return(0,W.jsxs)(`div`,{className:G(`prose-canvas`,t),children:[r&&(0,W.jsx)(D$,{fields:r}),i&&(0,W.jsx)(pn,{remarkPlugins:S$,rehypePlugins:[E$],urlTransform:C$,components:O$[n],children:i})]})}var A$=({activations:e,fullBleed:t,runState:n,deps:r})=>{if(e.length===0)return null;let i=e[0];if(OI(i)&&n){let a=e.slice(1),o=n.isReconnect?(0,W.jsxs)(`button`,{onClick:n.onReconnect,className:G(`flex items-center gap-2 px-5 py-2 text-[11px] font-black uppercase tracking-widest`,`rounded-full border transition-all active:scale-95`,`border-amber-500/40 bg-amber-500/15 text-amber-600 hover:bg-amber-500/20`,`dark:text-amber-400`,t&&`mx-auto`),children:[(0,W.jsx)(Ve,{className:`size-3.5`}),`View`]}):(0,W.jsxs)(`button`,{type:`button`,onClick:n.onRun,className:G(`flex items-center gap-2 transition-all active:scale-95 bg-primary text-primary-foreground hover:bg-primary/90 font-black uppercase tracking-widest rounded-full shadow-lg shadow-primary/25 min-h-[44px] px-6 py-2 text-xs`,t&&`mx-auto`),children:[(()=>{let e=i.icon||wn;return(0,W.jsx)(e,{className:`shrink-0 size-4 fill-current sm:size-3`})})(),(0,W.jsx)(`span`,{children:i.label})]});return(0,W.jsxs)(`div`,{className:G(`flex flex-wrap items-center gap-4 mt-8`,t&&`justify-center`),children:[o,a.map((e,t)=>(0,W.jsx)(`button`,{onClick:()=>TI(e.action,r),className:`flex items-center gap-2 px-6 py-2 text-xs font-black uppercase tracking-widest rounded-full bg-background border border-border text-foreground hover:bg-muted transition-all active:scale-95`,children:e.label},e.id||t))]})}return(0,W.jsx)(`div`,{className:G(`flex flex-wrap gap-4 mt-8`,t&&`justify-center`),children:e.map((e,t)=>(0,W.jsx)(`button`,{onClick:()=>TI(e.action,r),className:G(`flex items-center gap-2 px-8 py-4 text-xs font-black uppercase tracking-widest rounded-full transition-all active:scale-95`,t===0?`bg-primary text-primary-foreground shadow-xl shadow-primary/25 hover:scale-[1.04]`:`bg-background border border-border text-foreground hover:bg-muted`),children:e.label},e.id||t))})},j$=({examples:e,activeIndex:t,onSelect:n})=>e.length===0?null:(0,W.jsx)(`div`,{className:`mt-6 rounded-2xl border border-border/70 bg-card/80 backdrop-blur-sm`,children:(0,W.jsx)(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-3`,children:e.map((e,r)=>{let i=r===t,a=e.anchor===!0&&!i,o=!!e.badge&&a;return(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(r),"aria-current":i?`true`:void 0,className:G(`relative rounded-full px-4 py-2 text-[11px] font-black uppercase tracking-[0.18em] transition-all active:scale-95`,i?`bg-primary text-primary-foreground shadow-lg shadow-primary/25`:a?`border border-brand bg-brand/5 text-brand-deep hover:bg-brand/10 dark:text-brand-light`:`border border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground`),children:[e.label,o?(0,W.jsx)(`span`,{className:`ml-2 inline-block rounded-pill bg-brand px-1.5 py-0.5 align-middle text-[8px] font-black leading-none tracking-[0.12em] text-background`,children:e.badge}):null]},`${e.label}-${r}`)})})}),M$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M35 35 L65 35 L65 45 L45 45 L45 65 L35 65 Z`,fill:`url(#struct-grad)`}),(0,W.jsx)(`path`,{d:`M55 45 L65 45 L65 65 L45 65 L45 55 L55 55 Z`,fill:`url(#struct-grad)`,opacity:`0.7`})]}),N$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`4`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:`5`,fill:`url(#proto-grad)`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:`15`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`2`,strokeDasharray:`4 2`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`50`,r:`25`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`1`,opacity:`0.5`}),(0,W.jsx)(`line`,{x1:`50`,y1:`50`,x2:`50`,y2:`25`,stroke:`url(#proto-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]}),P$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`complex-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#F50057`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#D500F9`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#complex-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M40 35 H60 V45 A5 5 0 0 1 60 55 V65 H40 V55 A5 5 0 0 0 40 45 Z`,fill:`url(#complex-grad)`})]}),F$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsxs)(`defs`,{children:[(0,W.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]}),(0,W.jsxs)(`filter`,{id:`glow`,x:`-20%`,y:`-20%`,width:`140%`,height:`140%`,children:[(0,W.jsx)(`feGaussianBlur`,{stdDeviation:`3`,result:`blur`}),(0,W.jsx)(`feComposite`,{in:`SourceGraphic`,in2:`blur`,operator:`over`})]})]}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#basics-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M55 20 L30 55 L45 55 L40 85 L70 45 L55 45 Z`,fill:`url(#basics-grad)`,filter:`url(#glow)`})]}),I$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#basics-grad)`,strokeWidth:`4`}),(0,W.jsx)(`text`,{x:`50`,y:`65`,fontFamily:`monospace`,fontSize:`40`,fontWeight:`bold`,fill:`url(#basics-grad)`,textAnchor:`middle`,children:`10`})]}),L$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`basics-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00F2FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#6200EA`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#basics-grad)`,strokeWidth:`4`}),(0,W.jsx)(`rect`,{x:`30`,y:`30`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,W.jsx)(`rect`,{x:`30`,y:`45`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`}),(0,W.jsx)(`rect`,{x:`30`,y:`60`,width:`40`,height:`8`,rx:`2`,fill:`url(#basics-grad)`})]}),R$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M50 30 A20 20 0 1 1 35.8 35.8 L30 30 M35.8 35.8 L42 38`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`6`,strokeLinecap:`round`})]}),z$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`struct-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E676`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00F2FF`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M30 40 L45 40 M30 50 L55 50 M30 60 L70 60`,fill:`none`,stroke:`url(#struct-grad)`,strokeWidth:`6`,strokeLinecap:`round`}),(0,W.jsx)(`text`,{x:`50`,y:`30`,fontFamily:`monospace`,fontSize:`12`,fill:`url(#struct-grad)`,textAnchor:`middle`,children:`21-15-9`})]}),B$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`proto-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#FFD600`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#FFAB00`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#proto-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M35 35 H65 V55 L50 70 L35 55 Z`,fill:`url(#proto-grad)`}),(0,W.jsx)(`circle`,{cx:`50`,cy:`45`,r:`4`,fill:`#0b1326`})]}),V$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#metric-grad)`,strokeWidth:`4`}),(0,W.jsx)(`rect`,{x:`30`,y:`60`,width:`10`,height:`15`,fill:`url(#metric-grad)`}),(0,W.jsx)(`rect`,{x:`45`,y:`40`,width:`10`,height:`35`,fill:`url(#metric-grad)`}),(0,W.jsx)(`rect`,{x:`60`,y:`25`,width:`10`,height:`50`,fill:`url(#metric-grad)`})]}),H$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`metric-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#00E5FF`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#1DE9B6`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#metric-grad)`,strokeWidth:`4`}),(0,W.jsx)(`path`,{d:`M35 40 L65 60 M65 40 L35 60 M35 30 H65 M35 70 H65`,fill:`none`,stroke:`url(#metric-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]}),U$=e=>(0,W.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 100 100`,...e,children:[(0,W.jsx)(`defs`,{children:(0,W.jsxs)(`linearGradient`,{id:`dialect-grad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,W.jsx)(`stop`,{offset:`0%`,style:{stopColor:`#76FF03`,stopOpacity:1}}),(0,W.jsx)(`stop`,{offset:`100%`,style:{stopColor:`#00E676`,stopOpacity:1}})]})}),(0,W.jsx)(`path`,{d:`M50 5 L90 27.5 L90 72.5 L50 95 L10 72.5 L10 27.5 Z`,fill:`none`,stroke:`url(#dialect-grad)`,strokeWidth:`4`,strokeLinecap:`round`}),(0,W.jsx)(`path`,{d:`M35 30 H65 M35 45 H65 M35 60 H55 M35 75 H65`,fill:`none`,stroke:`url(#dialect-grad)`,strokeWidth:`4`,strokeLinecap:`round`})]});function W$(e){switch(e){case`trophy`:return F$;case`dumbbell`:return k;case`timer`:return N$;case`play`:return wn;case`blocks`:return M$;case`puzzle`:return P$;case`activity`:return V$;case`file-text`:return U$;default:return f}}function G$(e){switch(e){case`basics-movement`:return F$;case`basics-reps`:return I$;case`basics-load`:return L$;case`structure-rounds`:case`complex-rounds`:case`protocols-rounds`:return R$;case`structure-repscheme`:return z$;case`protocols-timer`:case`complex-time`:return N$;case`protocols-tag`:return B$;case`metrics-custom`:return V$;case`metrics-calc`:return H$;case`dialects-log`:case`dialects-climb`:return U$;default:return null}}function K$({quest:e,onClick:t,className:n,compact:r=!1,disabled:i=!1}){let a=G$(e.id),o=t?`Select to jump to its section.`:`Open the editor to begin.`,s=e.isCompleted?`Challenge complete.`:e.result?e.result.pass?`Ready — ${e.result.detail??`looks good`}`:e.result.reason??o:o,c={"data-testid":`challenge-row-${e.id}`,"data-completed":e.isCompleted?`true`:`false`,className:G(`w-full text-left flex items-start gap-3 rounded-xl border px-3 py-2 text-sm transition-colors`,e.isCompleted?`border-primary/40 bg-primary/5`:`border-border/50 bg-background/60`,t&&!i&&`cursor-pointer hover:bg-background/80`,i&&`opacity-60 cursor-default`,r&&`px-2.5 py-1.5`,n)},l=(0,W.jsxs)(W.Fragment,{children:[a?(0,W.jsxs)(`span`,{className:G(`relative shrink-0 mt-0.5`,r?`size-5`:`size-6`),children:[(0,W.jsx)(a,{className:`w-full h-full`}),e.isCompleted&&(0,W.jsx)(`span`,{className:`absolute -bottom-1 -right-1 flex size-3.5 items-center justify-center rounded-full bg-emerald-500 text-white border border-background shadow`,children:(0,W.jsx)(Tt,{className:`size-2`,strokeWidth:3})})]}):(0,W.jsx)(`span`,{className:G(`mt-0.5 shrink-0`,e.isCompleted?`text-primary`:`text-muted-foreground/50`),"aria-hidden":`true`,children:e.isCompleted?(0,W.jsx)(Un,{className:r?`size-3.5`:`size-4`}):(0,W.jsx)(Pt,{className:r?`size-3.5`:`size-4`})}),(0,W.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,W.jsx)(`p`,{className:G(`font-semibold`,e.isCompleted?`text-foreground line-through decoration-primary/40`:`text-foreground`,r&&`text-xs`),children:e.label}),e.desc&&!r&&(0,W.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:e.desc}),(0,W.jsx)(`p`,{"data-testid":`challenge-hint-${e.id}`,className:G(`mt-1 text-xs`,e.isCompleted||e.result?.pass?`text-primary/80`:`text-muted-foreground`),children:s})]})]});return t?(0,W.jsx)(`button`,{type:`button`,onClick:t,disabled:i,...c,children:l}):(0,W.jsx)(`div`,{...c,children:l})}function q$(e){let t=e.replace(/^\s+/,``),n=t.match(/\n\s*\n/);return!n||n.index===void 0?{lead:t,rest:``}:{lead:t.slice(0,n.index),rest:t.slice(n.index).trimStart()}}var J$=({section:e,idx:t,prose:n,blockId:r,keySuffix:i,showHeading:a=!0,showEyebrow:o=!0,renderButtons:s=!0,isActive:c=!1,hasViewDef:l=!1,runState:u,deps:d,onExampleSelect:f,selectedExampleIndex:p,chapters:m=[],challengeQuests:h=[],isCollection:g=!1,notebookSlug:_=null,workoutItems:v=[],handleSelectWorkout:y,onScrollToSection:b,variant:x=`default`})=>{let S=!!e.isFullBleed,C=!!e.isDark&&x!==`caption`,w=e.density,T=HL[e.theme||`slate`]??HL.slate,E=e.examples??[],D=t===-1,O=U.useMemo(()=>{if(!m||!h)return null;for(let t of m){let n=t.sectionIds.indexOf(e.id);if(n>=0&&t.questIds[n]){let e=t.questIds[n],r=h.find(t=>t.id===e);if(r)return{quest:r,chapterTitle:t.title}}}return null},[m,h,e.id]);if(D){let t=e.proseChunks.filter(e=>e.kind===`button`).map(e=>e.button),n=e.proseChunks.findIndex(e=>e.kind===`prose`&&e.text.trim()!==``),a=n>=0?e.proseChunks[n]:null,{lead:o,rest:s}=a&&a.kind===`prose`?q$(a.text.trim()):{lead:``,rest:``},c=e.proseChunks.slice(n+1);return(0,W.jsxs)(`div`,{id:r,"data-section-id":i==="default"?e.id:void 0,className:`group relative flex min-h-[70vh] lg:min-h-[80vh] items-center justify-center overflow-hidden border-b-2 border-primary/10 bg-gradient-to-b from-primary/[0.08] via-muted/30 to-background px-6 py-16 lg:px-10 lg:py-24`,children:[(0,W.jsx)(`div`,{className:`pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_75%_60%_at_50%_0%,_var(--tw-gradient-stops))] from-primary/30 via-primary/5 to-transparent`}),(0,W.jsx)(`div`,{className:`pointer-events-none absolute inset-0 text-primary opacity-[0.15]`,style:{backgroundImage:`radial-gradient(circle, currentColor 1.5px, transparent 1.5px)`,backgroundSize:`24px 24px`,maskImage:`radial-gradient(ellipse 70% 60% at 50% 40%, black 40%, transparent 90%)`,WebkitMaskImage:`radial-gradient(ellipse 70% 60% at 50% 40%, black 40%, transparent 90%)`}}),(0,W.jsxs)(`div`,{className:`relative max-w-2xl w-full text-center`,children:[o&&(0,W.jsx)(k$,{prose:o,variant:`heroLead`,className:`mb-5`}),s&&(0,W.jsx)(k$,{prose:s,variant:`heroBody`,className:`mb-2`}),c.map((e,t)=>{if(e.kind===`prose`){let n=e.text.trim();return n?(0,W.jsx)(k$,{prose:n,className:`mt-6 mb-2`},`hero-prose-${t}`):null}if(e.kind===`challenge`){let n=h.find(t=>t.id===e.id);return n?(0,W.jsx)(`div`,{className:`my-4 flex justify-center`,children:(0,W.jsx)(K$,{quest:n,onClick:()=>b?.(r),compact:!0})},`hero-challenge-${t}`):null}return null}),t.length>0&&(0,W.jsx)(A$,{activations:t.map((e,t)=>DI(e,t)),fullBleed:!0,runState:l?u:void 0,deps:d})]})]})}let k=n===void 0?e.proseChunks??[]:[{kind:`prose`,text:n}],A=!k.some(e=>e.kind===`button`)&&(e.buttons??[]).length>0;return(0,W.jsxs)(`div`,{id:r,"data-section-id":i==="default"||i===`before-workouts`?e.id:void 0,className:G(`group relative border-b border-border/50 transition-colors duration-300`,x===`caption`?`py-6 pb-10`:l?S?`flex items-center justify-center min-h-[35vh] py-12 lg:py-16 px-6 lg:px-10`:w===`compact`?`py-10 lg:py-12 px-6 lg:px-10`:`py-14 lg:py-20 px-6 lg:px-10`:w===`compact`?`py-10 lg:py-12 px-6 lg:px-12`:`py-16 lg:py-20 px-6 lg:px-12`,!x||x==="default"?C&&`bg-muted/20 overflow-hidden`:void 0,x!==`caption`&&!C&&!S&&(t%2==0?`bg-background`:`bg-muted/[0.18]`)),children:[x!==`caption`&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`div`,{className:G(`pointer-events-none absolute inset-y-0 left-0 w-px bg-gradient-to-b opacity-0 transition-opacity duration-300`,T.accent,c&&`opacity-100`)}),(0,W.jsx)(`div`,{className:G(`pointer-events-none absolute left-0 top-0 h-full w-1 origin-top rounded-r-full bg-gradient-to-b transition-all duration-300`,T.progress,c?`scale-y-100 opacity-100`:`scale-y-[0.18] opacity-25`)})]}),C&&(0,W.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-40 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-primary/20 via-transparent to-transparent`}),(0,W.jsxs)(`div`,{className:G(`relative`,x===`caption`?`max-w-none`:l?S?`max-w-md w-full text-center`:`max-w-sm`:`max-w-4xl w-full mx-auto`),children:[o&&(!S||!l)&&O&&(0,W.jsx)(`div`,{className:`mb-4 flex items-center gap-2 select-none min-h-[14px]`,children:O.quest.isCompleted?(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-emerald-800 dark:text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20`,children:[(0,W.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-emerald-500 dark:bg-emerald-400 animate-pulse`}),`Challenge Complete`]}):(0,W.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-[9px] font-black uppercase tracking-wider text-muted-foreground bg-muted/60 px-2 py-0.5 rounded-full border border-border/50`,children:[(0,W.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full bg-zinc-400 dark:bg-zinc-500`}),O.chapterTitle,`: Challenge Pending`]})}),a?(0,W.jsx)(`h2`,{className:G(`font-bold tracking-tight text-foreground leading-tight`,x===`caption`?`text-xl lg:text-2xl mb-4`:`text-2xl lg:text-3xl font-black uppercase mb-5`),children:e.heading}):null,k.map((e,t)=>{if(e.kind===`prose`){let n=e.text.trim();return n?(0,W.jsx)(k$,{prose:n,className:t===0?`mb-6`:`mt-4 mb-6`},`prose-${t}`):null}if(e.kind===`button`)return(0,W.jsx)(A$,{activations:[DI(e.button,t)],fullBleed:S,runState:l?u:void 0,deps:d},`button-${t}`);if(e.kind===`widget`){if(e.widget===`hero-carousel`)return(0,W.jsx)(`div`,{className:`my-6`,children:(0,W.jsx)(n$,{})},`hero-carousel-${t}`);if(e.widget===`workouts-list`&&g&&_&&y)return(0,W.jsx)(`div`,{id:`notebook-workouts`,className:`border-b border-border/50 bg-card my-6`,children:(0,W.jsx)(`div`,{className:`w-full mx-auto`,children:(0,W.jsx)(u$,{category:_,workoutItems:v,onSelect:y,showSearch:!1,variant:`flat`})})},`workouts-${t}`)}if(e.kind===`challenge`){let n=h.find(t=>t.id===e.id);return n?(0,W.jsx)(`div`,{className:`my-4`,children:(0,W.jsx)(K$,{quest:n,onClick:()=>b?.(r),compact:!0})},`challenge-${t}`):null}return null}),E.length>0?(0,W.jsx)(j$,{examples:E,activeIndex:Math.min(p,E.length-1),onSelect:t=>f(e,t)}):null,s&&A?(0,W.jsx)(A$,{activations:e.buttons.map((e,t)=>DI(e,t)),fullBleed:S,runState:l?u:void 0,deps:d}):null]})]},`${e.id}-${i}`)};function Y$({sections:e,activeIndex:t,part:n,args:r}){return(0,W.jsx)(`div`,{className:`h-full min-h-0 pr-1`,"data-testid":`guide-captions-${n}`,children:e.map((e,n)=>{let i=n===t;return(0,W.jsx)(`div`,{className:`absolute inset-0 min-h-0 overflow-y-auto transition-opacity duration-300 ${i?`opacity-100`:`pointer-events-none invisible opacity-0`}`,"aria-hidden":!i,children:(0,W.jsx)(J$,{section:e,idx:n,blockId:`guide-caption-${e.id}`,keySuffix:`caption`,variant:`caption`,isActive:i,hasViewDef:r.hasViewDef??!0,runState:r.runState,deps:r.deps,onExampleSelect:r.onExampleSelect,selectedExampleIndex:r.selectedExamples[e.id]??0,chapters:r.chapters,challengeQuests:r.challengeQuests,onScrollToSection:r.onScrollToSection})},e.id)})})}function X$({sections:e,part:t,partCount:n,title:r,pane:i,cardArgs:a,onActivateSection:o}){let s=(0,U.useRef)(null),c=(0,U.useMemo)(()=>e$(e),[e]),{slice:l,subscribe:u}=XQ(s,!1,c),d=(0,U.useRef)(e);d.current=e;let[f,p]=(0,U.useState)(!1);(0,U.useEffect)(()=>{let e=s.current;if(!e||typeof IntersectionObserver>`u`){p(!0);return}let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(p(!0),t.disconnect())},{rootMargin:`100px`});return t.observe(e),()=>t.disconnect()},[]);let m=()=>{let e=s.current;if(!e)return!1;let{top:t,bottom:n}=e.getBoundingClientRect();return t<=0&&n>window.innerHeight},[h,g]=(0,U.useState)(!1);(0,U.useEffect)(()=>u(()=>{let e=m();g(t=>t===e?t:e)}),[u]);let _=(0,U.useRef)(!1),v=(0,U.useRef)(-1),y=(0,U.useRef)(o);y.current=o,(0,U.useEffect)(()=>{let e=_.current,t=v.current;if(_.current=h,v.current=l.index,!h||e&&t===l.index)return;let n=d.current[l.index];n&&y.current(n)},[h,l.index]);let b=e[l.index]??null;return(0,W.jsxs)(`div`,{children:[(0,W.jsxs)(`header`,{"data-testid":`guide-runway-header-${t}`,className:`mx-auto w-full max-w-[1500px] px-6 pt-12 pb-6 lg:px-12`,children:[(0,W.jsxs)(`div`,{className:`font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[`Part `,t,` / `,n]}),(0,W.jsx)(`h2`,{className:`mt-1 text-xl font-black uppercase tracking-tight text-foreground`,children:r})]}),(0,W.jsxs)(`div`,{className:`relative`,children:[(0,W.jsx)(qQ,{trackRef:s,height:`${(e.length+1)*100}vh`,stages:c,activeIndex:l.index,pane:f?i:null,captions:(0,W.jsx)(Y$,{sections:e,activeIndex:l.index,part:t,args:a}),status:(0,W.jsxs)(`div`,{className:`truncate font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground`,children:[String(l.index+1).padStart(2,`0`),b?` — ${b.heading}`:``]}),testId:`guide-runway-${t}`}),e.map((t,n)=>(0,W.jsx)(`span`,{id:t.id,"data-section-id":t.id,"aria-hidden":`true`,className:`pointer-events-none absolute left-0 h-px w-px`,style:{top:`calc((100% - 100vh) * ${n/e.length} + 50vh + 120px)`}},t.id))]})]})}function Z$({sections:e,groupKey:t,title:n,pane:r,cardArgs:i,onActivateSection:a}){let{groups:o,tail:s}=$Q(e,t);return(0,W.jsxs)(W.Fragment,{children:[o.map((e,t)=>(0,W.jsx)(X$,{sections:e,part:t+1,partCount:o.length,title:n,pane:r,cardArgs:i,onActivateSection:a},e[0]?.id??t)),s.length>0&&(0,W.jsx)(`div`,{className:`mx-auto w-full max-w-[1500px] px-6 lg:px-12`,"data-testid":`guide-static-tail`,children:(0,W.jsx)(`div`,{className:`lg:max-w-[50%]`,children:s.map((e,t)=>(0,W.jsx)(J$,{section:e,idx:t,blockId:e.id,keySuffix:`default`,isActive:i.activeSectionId===e.id,hasViewDef:i.hasViewDef??!0,runState:i.runState,deps:i.deps,onExampleSelect:i.onExampleSelect,selectedExampleIndex:i.selectedExamples[e.id]??0,chapters:i.chapters,challengeQuests:i.challengeQuests,onScrollToSection:i.onScrollToSection},`tail-${e.id}`))})})]})}function Q$({videoId:e,title:t=`YouTube video`,onClose:n}){return(0,U.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,BC.createPortal)((0,W.jsxs)(`div`,{className:`fixed inset-0 z-[100] flex items-center justify-center bg-black/90 p-4 animate-in fade-in duration-200`,"data-testid":`youtube-lightbox`,onClick:e=>{e.target===e.currentTarget&&n()},children:[(0,W.jsx)(`button`,{type:`button`,onClick:n,title:`Close video`,"data-testid":`youtube-lightbox-close`,className:`absolute right-4 top-4 z-[110] flex size-11 items-center justify-center rounded-full border border-border bg-background/80 text-foreground transition-colors hover:bg-accent`,children:(0,W.jsx)(ge,{className:`size-5`})}),(0,W.jsx)(`div`,{className:`aspect-video w-full max-w-5xl overflow-hidden rounded-lg border border-border bg-black shadow-2xl`,children:(0,W.jsx)(`iframe`,{className:`h-full w-full border-0`,src:`https://www.youtube-nocookie.com/embed/${encodeURIComponent(e)}?autoplay=1&rel=0`,title:t,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0})})]}),document.body)}function $$({index:e,before:t,accentText:n,after:r,accent:i,blurb:a}){return(0,W.jsx)(`header`,{className:`flex items-center px-6 py-14 lg:px-12 xl:py-20 2xl:py-24 xl:px-16`,children:(0,W.jsxs)(`div`,{className:`mx-auto w-full max-w-[1500px] 2xl:max-w-[1720px]`,children:[(0,W.jsxs)(`h2`,{className:`flex items-baseline gap-4 xl:gap-6 text-[clamp(26px,3.6vw,52px)] font-extrabold leading-[1.1] tracking-[-0.03em]`,children:[(0,W.jsx)(`span`,{className:`font-mono text-xs font-normal tracking-normal text-muted-foreground`,children:e}),(0,W.jsxs)(`span`,{children:[t,n,r]})]}),(0,W.jsx)(`p`,{className:`mt-3 xl:mt-4 max-w-xl xl:max-w-2xl 2xl:max-w-3xl text-[clamp(14px,1.2vw,18px)] leading-[1.65] text-muted-foreground`,children:a})]})})}var e1=`hsl(var(--primary))`,t1={ink:`hsl(var(--foreground))`,editor:e1,timer:e1,analytics:e1,library:e1,rounds:e1},n1={editor:`WOD Editor & Autocomplete`,timer:`Clock`,analytics:`WQL Analytics`,metrics:`Own the Metrics`,result:`Run Results`},r1={start:`/page/guide-start`,protocols:`/page/guide-protocols`,structure:`/page/guide-structure`,metrics:`/page/guide-metrics`,clock:`/page/guide-clock`,wql:`/page/guide-wql`,dashboards:`/page/guide-dashboards`,sessions:`/page/guide-sessions`,basics:`/page/guide-start`,"custom-metrics":`/page/guide-metrics`,dialects:`/page/guide-sessions#intent`,complex:`/page/guide-sessions#full-session`},i1=`dQw4w9WgXcQ`,a1=`https://i.ytimg.com/vi/${i1}/hqdefault.jpg`;function o1({variant:e=`index`}){let t=vR(),{pathname:n}=ht(),[r,i]=(0,U.useState)(null),a=(0,U.useMemo)(()=>PL(t).flatMap(e=>e.action?.type===`route`?[{id:e.id,label:e.label,to:e.action.to}]:[]),[t]),o=(0,U.useMemo)(()=>{let e=new Map;for(let n of t){if(n.route.startsWith(`/notebook`)||n.page.frontmatter?.type!==`guide`)continue;let t=n.page.frontmatter?.description;t&&e.set(`guide-${n.route}`,String(t))}return e},[t]);if(a.length===0)return null;let s=a.findIndex(e=>e.to===n),c=s>=0,l=c&&a.length>1?(s+1)%a.length:-1,u=r&&(0,W.jsx)(Q$,{videoId:i1,title:r.label,onClose:()=>i(null)});return e===`university`?(0,W.jsxs)(`section`,{id:`tour-section-university`,"data-testid":`tour-section-university`,"aria-label":`Wod Wiki University`,children:[(0,W.jsx)($$,{index:`05`,before:`Wod Wiki `,accentText:`University`,after:``,accent:t1.library,blurb:`Eight short chapters take you from your first workout to querying your training history. Each guide pairs a video walkthrough with a runnable example.`}),(0,W.jsx)(`nav`,{"aria-label":`Wod Wiki University`,className:`px-6 pb-16 lg:px-12 xl:px-16`,children:(0,W.jsx)(`ul`,{className:`mx-auto flex w-full max-w-5xl flex-col gap-5`,children:a.map((e,t)=>(0,W.jsxs)(`li`,{className:G(`flex flex-col gap-5 rounded-lg border border-border p-5 md:flex-row md:items-center md:gap-8 md:p-6`,t%2==1&&`md:flex-row-reverse`),children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>i({id:e.id,label:e.label}),title:`Watch: ${e.label}`,"aria-label":`Watch: ${e.label}`,"data-testid":`guide-watch`,className:`group relative block w-full flex-none overflow-hidden rounded-md border border-border md:w-56`,children:[(0,W.jsx)(`img`,{src:a1,alt:``,loading:`lazy`,className:`aspect-video w-full object-cover transition-transform duration-300 group-hover:scale-105`}),(0,W.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/25 transition-colors group-hover:bg-black/40`,children:(0,W.jsx)(wn,{className:`size-9 fill-white text-white`})})]}),(0,W.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1.5`,children:[(0,W.jsx)(Vn,{to:e.to,className:`font-semibold hover:underline`,children:e.label}),(0,W.jsx)(`p`,{className:`text-sm leading-relaxed text-muted-foreground`,children:o.get(e.id)??e.to})]})]},e.id))})}),u]}):(0,W.jsxs)(`nav`,{"aria-label":c?`What’s Next`:`Syntax & Guides`,"data-testid":`guide-index-footer`,className:`border-t border-border px-6 py-12 xl:py-16`,children:[(0,W.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col rounded-lg border border-border overflow-hidden`,children:[(0,W.jsxs)(`h2`,{className:`px-4 py-2 text-xs font-black uppercase tracking-wider text-muted-foreground bg-muted/40`,children:[c?`What’s Next`:`Syntax & Guides`,` · `,a.length]}),(0,W.jsx)(`ul`,{className:`flex flex-col divide-y divide-border`,children:a.map((e,t)=>(0,W.jsxs)(`li`,{className:`flex items-stretch`,children:[(0,W.jsxs)(Vn,{to:e.to,"aria-current":t===s?`page`:void 0,className:G(`flex min-w-0 flex-1 flex-col gap-0.5 px-4 py-3 hover:bg-muted/50`,t===s&&`bg-muted/50`),children:[(0,W.jsxs)(`span`,{className:`flex w-full items-baseline justify-between gap-3`,children:[(0,W.jsx)(`span`,{className:`font-medium`,children:e.label}),t===l&&(0,W.jsx)(`span`,{className:`text-xs font-semibold text-primary`,"data-testid":`guide-next-marker`,children:`Next →`})]}),(0,W.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.to})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>i({id:e.id,label:e.label}),title:`Watch: ${e.label}`,"aria-label":`Watch: ${e.label}`,"data-testid":`guide-watch`,className:`flex flex-none items-center gap-1.5 border-l border-border px-4 text-xs font-semibold text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground`,children:[(0,W.jsx)(wn,{className:`size-3.5`}),`Watch`]})]},e.id))})]}),u]})}var s1=`22rem`,c1=`42rem`,l1=`20rem`,u1=`calc(100dvh - var(--canvas-sticky-top) - 2rem)`;function d1(e){return{editorWidth:e||`50%`,editorMinWidth:s1,editorMaxWidth:c1,editorMinHeight:l1,editorMaxHeight:u1}}function f1(e){let t=Math.max(1,e.split(`
@@ -459,7 +459,7 @@ domain: swimming
459
459
  `),[e.lines]);return(0,U.useEffect)(()=>{if(r.current)return i.current?.destroy(),i.current=new Sr({state:Qr.create({doc:a,extensions:[Jr(),ui(),Qr.readOnly.of(!1),Sr.theme({"&":{fontSize:`13px`,borderRadius:`12px`,border:`1px solid var(--cm-border)`},".cm-scroller":{fontFamily:`JetBrains Mono, ui-monospace, SFMono-Regular, monospace`,lineHeight:`1.6`,minHeight:`180px`},".cm-content":{padding:`14px 0`},".cm-gutters":{backgroundColor:`transparent`,borderRight:`1px solid var(--cm-border)`}}),Sr.theme({"&":{"--cm-border":t?`rgba(82, 82, 91, 0.7)`:`rgba(212, 212, 216, 0.9)`}},{dark:t}),...t?[Zr]:[]]}),parent:r.current}),()=>{i.current?.destroy(),i.current=null}},[t,a]),e.lines.length===0?(0,W.jsxs)(`section`,{className:`rounded-2xl border border-amber-400/50 bg-amber-50 p-6 text-amber-900 dark:border-amber-500/40 dark:bg-amber-950/30 dark:text-amber-100`,children:[`Invalid `,(0,W.jsx)(`code`,{children:`code-example`}),` widget config.`]}):(0,W.jsxs)(`section`,{className:`p-5`,children:[(0,W.jsxs)(`div`,{className:`mb-4 flex items-center justify-between gap-3`,children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold text-zinc-900 dark:text-zinc-100`,children:`Code example`}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>n(i.current?.state.doc.toString()??a),className:`inline-flex items-center gap-2 rounded-full bg-emerald-600 px-4 py-2 text-xs font-semibold text-white transition hover:bg-emerald-500`,children:[(0,W.jsx)(wn,{className:`size-3.5`,"aria-hidden":`true`}),e.cta]})]}),(0,W.jsx)(`div`,{ref:r}),(0,W.jsx)(`ul`,{className:`mt-4 space-y-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.lines.map((e,t)=>(0,W.jsxs)(`li`,{className:`flex gap-2`,children:[(0,W.jsx)(`span`,{className:`mt-1 inline-block size-1.5 rounded-full bg-zinc-400`,"aria-hidden":`true`}),(0,W.jsxs)(`span`,{children:[(0,W.jsx)(`code`,{className:`rounded bg-zinc-200/70 px-1 py-0.5 text-[12px] dark:bg-zinc-800`,children:e.code}),` — `,e.annotation]})]},`${e.code}-${t}`))})]})}function n8({config:e,onOpenDocs:t}){return!e.category||!e.title||!e.docsPath?(0,W.jsxs)(`article`,{className:`rounded-2xl border border-amber-400/50 bg-amber-50 p-5 text-amber-900 dark:border-amber-500/40 dark:bg-amber-950/30 dark:text-amber-100`,children:[`Invalid `,(0,W.jsx)(`code`,{children:`syntax-group`}),` widget config.`]}):(0,W.jsxs)(`article`,{className:`p-5`,children:[(0,W.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`p`,{className:`text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500 dark:text-zinc-400`,children:e.category}),(0,W.jsxs)(`h3`,{className:`mt-2 text-sm font-semibold text-zinc-900 dark:text-zinc-100`,children:[(0,W.jsx)(`span`,{className:`mr-2`,"aria-hidden":`true`,children:e.icon}),e.title]}),(0,W.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-zinc-600 dark:text-zinc-300`,children:e.description})]}),(0,W.jsxs)(`button`,{type:`button`,onClick:()=>t(e.docsPath),className:`inline-flex items-center gap-1.5 rounded-lg border border-zinc-300 px-2.5 py-1.5 text-xs font-semibold text-zinc-700 transition hover:bg-zinc-100 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800`,children:[`Docs`,(0,W.jsx)(Ye,{className:`size-3`,"aria-hidden":`true`})]})]}),(0,W.jsx)(`pre`,{className:`mt-4 overflow-x-auto rounded-xl border border-zinc-200 bg-white px-3 py-2 text-xs text-zinc-700 dark:border-zinc-700 dark:bg-zinc-950/70 dark:text-zinc-200`,children:(0,W.jsx)(`code`,{children:e.example})})]})}function r8(e){return({config:t})=>(0,W.jsx)(e8,{config:t,onAction:e})}function i8(e,t){return({config:n})=>(0,W.jsx)(t8,{config:n,isDarkMode:e,onRun:t})}function a8(e){return({config:t})=>(0,W.jsx)(n8,{config:t,onOpenDocs:e})}var o8=[`visitedLanding`,`editedNote`,`ranWorkout`,`loggedEffort`,`openedReview`],s8=`wodwiki.onboarding.v1`,c8={visitedLanding:!1,editedNote:!1,ranWorkout:!1,loggedEffort:!1,openedReview:!1};function l8(){if(typeof window>`u`||!window.localStorage)return{...c8};try{let e=window.localStorage.getItem(s8);if(!e)return{...c8};let t=JSON.parse(e),n={...c8};for(let e of o8)n[e]=t[e]===!0;return n}catch{return{...c8}}}function u8(e){if(!(typeof window>`u`||!window.localStorage))try{window.localStorage.setItem(s8,JSON.stringify(e))}catch{}}function d8(){let[e,t]=(0,U.useState)(l8);(0,U.useEffect)(()=>{let e=e=>{e.key===s8&&t(l8())};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]);let n=(0,U.useCallback)(e=>{t(t=>{if(t[e])return t;let n={...t,[e]:!0};return u8(n),n})},[]),r=o8.length,i=o8.reduce((t,n)=>t+ +!!e[n],0);return{progress:e,stepsComplete:i,totalSteps:r,isComplete:i===r,mark:n}}function f8(){let{mark:e}=d8();return{onEditNote:(0,U.useCallback)(()=>{e(`editedNote`)},[e]),onRunWorkout:(0,U.useCallback)(()=>{e(`ranWorkout`)},[e]),onLogEffort:(0,U.useCallback)(()=>{e(`loggedEffort`)},[e])}}var p8=new _A;function m8({theme:e,onViewCreated:t,onScrollToSection:n,onSearch:r}){let{id:i}=In(),a=i??`playground`,o=pU(`playground`,a),s=(0,U.useMemo)(()=>i?_b(i):`Playground`,[i]),c=yn(),l=!i||i===`playground`,{content:u,loading:d,entryId:f,noteBlocks:p,sourceRevision:m,onIdentityChange:h,onSaved:g,error:_,onChange:v,onLineChange:y,onBlur:b,flush:x,committedSourceRevision:S,resetToOriginal:C}=i0({category:`playground`,name:a,mdContent:B0.content,seedOnMount:l}),w=f??o,{onEditNote:T,onRunWorkout:E,onLogEffort:D}=f8(),O=(0,U.useCallback)(e=>{T(),v(e)},[T,v]),[k,A]=(0,U.useState)([]),j=(0,U.useCallback)(()=>{Z.getSessionsForNote(w).then(e=>A(e.filter(e=>e.completed))).catch(()=>{})},[w]);(0,U.useEffect)(()=>{j()},[j]);let M=(0,U.useRef)(!1),N=(0,U.useRef)(null),P=(0,U.useCallback)(e=>{if(N.current=e,t?.(e),M.current)return;M.current=!0;let n=Math.min(B0.cursorOffset,e.state.doc.length);e.dispatch({selection:di.cursor(n)})},[t]),F=(0,U.useCallback)(async e=>{try{await x();let t=ze(),n=await $R(w,e,t,`playground`);g({rawContent:n.note.rawContent,blocks:n.note.blocks,sourceRevision:n.note.sourceRevision}),o0.set(t,{block:n.block,noteId:n.session.noteId,captured:n,origin:`playground`,returnTo:`/playground/${encodeURIComponent(a)}`}),E(),c(QN(t))}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[w,a,c,E,x,g]),I=(0,U.useCallback)(async e=>{try{D();let t=await a0({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content}),n=Yy(new Date);Q({title:`Added to journal`,description:t.journalDate===n?`Added to today's journal`:`Added to ${t.journalDate}`,action:(0,W.jsx)(JM,{altText:`Open journal`,onClick:()=>c(qN(t.journalDate??n)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not add to journal`,variant:`destructive`})}},[s,a,c,D]),[L,R]=(0,U.useState)(null),[ee,z]=(0,U.useState)(!1),te=(0,U.useCallback)(async e=>{let t=`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`;try{await Yq(w,t),Q({title:`Moved to journal`,description:`This playground now lives on ${t}.`,action:(0,W.jsx)(JM,{altText:`Open journal`,onClick:()=>c(qN(t)),children:`Open`})}),c(YN(w))}catch{Q({title:`Error`,description:`Could not move to journal`,variant:`destructive`})}},[w,c]),ne=(0,U.useCallback)(async(e,t)=>{let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await a0({workoutName:s,category:`playground`,sourceNoteLabel:s,sourceNotePath:`/playground/${a}`,wodContent:e.content,date:t}),c(qN(n)),Q({title:`Scheduled`,description:`Added to journal for ${n}`,action:(0,W.jsx)(JM,{altText:`Open journal`,onClick:()=>c(qN(n)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[s,a,c]),[re,ie]=(0,U.useState)([]),ae=m0({content:u,scriptBlocks:re,onStartWorkout:F,results:k}),oe=(0,U.useMemo)(()=>y0({id:w,type:`playground`}),[w]),se=T0({noteId:w,stamps:oe.stamps}),[ce,B]=(0,U.useState)(null);(0,U.useEffect)(()=>{let e=!1;return Z.getNote(w).then(t=>{if(e||!t?.sourceId)return;let n=b0(t.sourceId);n&&B({noteId:w,link:n})}).catch(()=>{}),()=>{e=!0}},[w]);let le=(0,W.jsxs)(uH,{label:`Playground actions`,children:[(0,W.jsxs)(`button`,{type:`button`,onClick:()=>z(!0),title:`Move this playground to a journal date`,className:`inline-flex items-center gap-1 rounded-pill border border-border bg-card px-2.5 py-1 text-xs font-semibold text-muted-foreground transition-colors hover:bg-accent`,children:[(0,W.jsx)(dn,{className:`size-3.5`,"aria-hidden":`true`}),`Move to journal`]}),(0,W.jsx)(V0,{mode:`playground`,currentWorkout:{name:s,content:u},index:ae,onReset:C})]}),V=D0(`playground`,{onPlay:F,onShare:N0,onAddToToday:I,onSchedule:R}),ue=(0,U.useCallback)(e=>{if(e===`scroll-to-workout`){let e=ae.find(e=>e.type===`time`||e.type===`log`);e&&n?.(e.id)}else e===`open-search`&&r?.()},[ae,n,r]),de=(0,U.useCallback)(e=>{let t={id:`code-example-block`,line:0,endLine:e.split(`
460
460
  `).length,content:e};F(t)},[F]),fe=(0,U.useCallback)(e=>{e.startsWith(`/`)?window.open(e,`_blank`):c(e)},[c]),pe=(0,U.useCallback)((e,t)=>{if(e===`route`&&t.route)c(t.route);else if(e===`start-workout`){let e=re[0];e&&F(e)}else e===`new-note`&&c(`/playground`)},[c,re,F]),me=(0,U.useMemo)(()=>new Map([[`playground-run-tip`,$6],[`attention`,r8(ue)],[`code-example`,i8(e===`dark`,de)],[`syntax-group`,a8(fe)]]),[ue,de,fe,e]);return(0,U.useEffect)(()=>{document.title=`Wod.Wiki - ${s}`},[s]),d?(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(sz,{notePersistence:PP,provider:p8,children:(0,W.jsx)(vV,{title:s,actions:le,editor:(0,W.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,W.jsx)(E0,{data:se,up:oe.up,source:ce?.noteId===w?ce.link:null}),(0,W.jsx)(CQ,{value:u,onChange:O,onCursorPositionChange:y,onBlur:b,noteId:w,noteBlocks:p,sourceRevision:m,onIdentityChange:e=>h({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:g,beforeRun:async()=>(await x(),S()),onSaveRequest:x,onCommitChange:x,commands:V,enableInlineRuntime:!1,onViewCreated:P,theme:e,showLineNumbers:!1,onBlocksChange:ie,onButtonAction:pe,widgetComponents:me}),_?(0,W.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,_ instanceof Error?_.message:String(_),` Your draft is kept.`]}):null,(0,W.jsx)(kR,{noteId:w,blocks:p,sourceRevision:m,onRevert:async e=>{await x();let t=N.current?.state.field(NT);if(!t)throw Error(`The current note editor is unavailable.`);let n=OR({rawContent:t.rawContent,blocks:t.noteBlocks,sourceRevision:S()},e);h({rawContent:n.rawContent,noteBlocks:n.blocks,sourceRevision:n.sourceRevision}),await x()}})]})})}),L&&(0,W.jsx)(WC,{open:!0,onClose:()=>R(null),title:`Schedule workout`,children:(0,W.jsx)(t0,{selectedDate:null,onDateSelect:e=>{ne(L,e),R(null)}})}),ee&&(0,W.jsx)(WC,{open:!0,onClose:()=>z(!1),title:`Move playground to Journal`,description:`Choose a date. This keeps the workout's existing results and attachments.`,children:(0,W.jsx)(t0,{selectedDate:null,onDateSelect:e=>{z(!1),te(e)}})})]})}function h8({category:e,name:t,mdContent:n,theme:r,runMode:i,hidePlanningCommands:a,onViewCreated:o}){let s=i?i===`inline`:WU.has(e),c=!GU[e],l=pU(e,t),u=yn(),{content:d,loading:f,entryId:p,noteBlocks:m,sourceRevision:h,onIdentityChange:g,onSaved:_,error:v,onChange:y,onLineChange:b,onBlur:x,flush:S,committedSourceRevision:C}=i0({category:e,name:t,mdContent:n,seedOnMount:!c}),w=(0,U.useMemo)(()=>c?{label:`${e}-${t}`,path:ZN(e,t)}:null,[e,c,t]),[T,E]=(0,U.useState)(null),D=(0,U.useCallback)(async n=>{let r=ze();if(s){try{await S();let e=await QR({noteId:p??l,rawContent:d,blocks:m,expectedSourceRevision:C(),metadata:{title:t},noteType:`playground`},n,r);_({rawContent:e.note.rawContent,blocks:e.note.blocks,sourceRevision:e.note.sourceRevision}),o0.set(r,{block:e.block,noteId:e.session.noteId,captured:e}),u(QN(r))}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}return}try{let i=await a0({workoutName:t,category:e,sourceNoteLabel:w?.label,sourceNotePath:w?.path,wodContent:n.content}),a=Object.values(i.blocks??{}).find(e=>e.kind===`wod`);if(!a)throw Error(`The saved journal workout is unavailable.`);o0.set(r,{block:{...n,id:a.id},noteId:i.id}),u(JN(i.journalDate??``,r))}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:`Save failed. Your draft is kept.`,variant:`destructive`})}},[s,l,p,t,e,w,u,d,m,S,C,_]),O=(0,U.useCallback)(async(n,r)=>{let i=Wy(r),a;try{a=(await a0({workoutName:t,category:e,sourceNoteLabel:w?.label,sourceNotePath:w?.path,wodContent:n.content,date:r,wrapInWod:!0})).journalDate??``}catch{Q({variant:`destructive`,title:`Could not save workout`,description:`Failed to add "${t}" to ${i}. Please try again.`});return}u(qN(a));let o=qN(a);Q({title:`Added to ${i}`,description:`"${t}" was added to your journal.`,action:(0,W.jsx)(JM,{altText:`View journal entry`,onClick:()=>u(o),children:`View Note`}),duration:7e3})},[t,e,w,u]),k=D0(`notebook-readonly`,{onPlay:D,onShare:N0,onAddToToday:a?void 0:e=>O(e,new Date),onSchedule:a?void 0:E,onOpenInPlayground:e=>A0(e,u)}),[A,j]=(0,U.useState)([]),M=(0,U.useCallback)(()=>{u(YN(l))},[u,l]),N=m0({content:d,scriptBlocks:A,onStartWorkout:D,onEditNote:c?M:void 0}),P=(0,U.useMemo)(()=>c?y0({id:l,type:`note`}):null,[c,l]),F=T0({noteId:l,stamps:P?.stamps??[]}),I=(0,W.jsx)(uH,{children:(0,W.jsx)(V0,{mode:`notebook-readonly`,currentWorkout:{name:l,content:d},index:N})});return f?(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}):(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(vV,{title:t,actions:I,editor:(0,W.jsxs)(`div`,{className:`flex flex-col gap-3 px-4 py-6 sm:px-6`,children:[(0,W.jsx)(E0,{data:F,up:P?.up}),(0,W.jsx)(CQ,{value:d,onChange:y,onCursorPositionChange:b,onBlur:x,noteId:l,noteBlocks:m,sourceRevision:h,onIdentityChange:e=>g({rawContent:e.rawContent,noteBlocks:e.blocks,sourceRevision:e.sourceRevision}),onSaved:_,beforeRun:async()=>(await S(),C()),onSaveRequest:S,onCommitChange:S,readonly:!0,enableInlineRuntime:s,commands:k,onViewCreated:o,theme:r,showLineNumbers:!1,onBlocksChange:j}),v?(0,W.jsxs)(`p`,{role:`alert`,children:[`Save failed. `,v instanceof Error?v.message:String(v),` Your draft is kept.`]}):null]})}),T&&(0,W.jsx)(WC,{open:!0,onClose:()=>E(null),title:`Schedule ${t}`,children:(0,W.jsx)(t0,{selectedDate:null,onDateSelect:e=>{e&&O(T,e),E(null)}})})]})}var g8=ye(`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2`,{variants:{variant:{default:`border-transparent bg-primary text-primary-foreground hover:bg-primary/80`,secondary:`border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80`,destructive:`border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80`,outline:`text-foreground`}},defaultVariants:{variant:`default`}}),_8=U.memo(({className:e,variant:t,...n})=>(0,W.jsx)(`div`,{className:G(g8({variant:t}),e),...n})),v8=(0,U.forwardRef)(function({className:e,multiple:t,...n},r){return(0,W.jsxs)(`span`,{"data-slot":`control`,className:G(`group relative block w-full`,`before:absolute before:inset-px before:rounded-[calc(var(--radius-lg)-1px)] before:bg-background before:shadow-sm`,`dark:before:hidden`,`after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-transparent after:ring-inset`,`has-data-[focus]:after:ring-2 has-data-[focus]:after:ring-ring`,`has-data-[disabled]:opacity-50 has-data-[disabled]:before:bg-muted/50 has-data-[disabled]:before:shadow-none`),children:[(0,W.jsx)(R,{ref:r,multiple:t,...n,className:G(`relative block w-full appearance-none rounded-lg py-[calc(theme(spacing.2.5)-1px)]`,`sm:py-[calc(theme(spacing.1.5)-1px)]`,t?`px-[calc(theme(spacing.3.5)-1px)] sm:px-[calc(theme(spacing.3)-1px)]`:`pr-[calc(theme(spacing.10)-1px)] pl-[calc(theme(spacing.3.5)-1px)] sm:pr-[calc(theme(spacing.9)-1px)] sm:pl-[calc(theme(spacing.3)-1px)]`,`[&_optgroup]:font-semibold`,`text-base/6 text-foreground placeholder:text-muted-foreground sm:text-sm/6 dark:[&>*]:text-white`,`border border-border/60 data-[hover]:border-border dark:border-white/10 dark:data-[hover]:border-white/20`,`bg-transparent dark:bg-white/5 dark:[&>*]:bg-muted`,`focus:outline-hidden`,`data-invalid:border-destructive data-invalid:data-[hover]:border-destructive`,`data-[disabled]:border-border/40 data-[disabled]:opacity-100 dark:data-[disabled]:border-white/15 dark:data-[disabled]:bg-white/2.5 dark:data-[hover]:data-[disabled]:border-white/15`,`dark:scheme-dark`,e)}),!t&&(0,W.jsx)(`span`,{className:`pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2`,children:(0,W.jsxs)(`svg`,{className:`size-5 stroke-muted-foreground group-has-data-[disabled]:stroke-muted-foreground/70 sm:size-4 forced-colors:stroke-[CanvasText]`,viewBox:`0 0 16 16`,"aria-hidden":`true`,fill:`none`,children:[(0,W.jsx)(`path`,{d:`M5.75 10.75L8 13L10.25 10.75`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,W.jsx)(`path`,{d:`M10.25 5.25L8 3L5.75 5.25`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]})}),y8={effort:`efforts`,equipment:`equipment`,tag:`tags`,"tag-type":`tag_types`},b8=[`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`efforts`,`equipment`,`page`,`page_notes`,`note_tags`,`tags`,`tag_types`,`attachments`];function x8(e){let t=[];for(let[n,r]of Object.entries(e.metrics)){if(typeof r!=`string`&&typeof r!=`number`)continue;let e=String(r).trim().match(/^([+-]?\d+(?:\.\d+)?)\s*([A-Za-z%/][\w%/.-]*)$/);e?t.push({kind:`metric`,type:n,value:Number(e[1]),unit:e[2]}):t.push({kind:`metric`,type:n,value:r})}for(let[n,r]of Object.entries(e.summaries))t.push({kind:`metric`,type:`summaries.${n}`,value:r});for(let n of e.tags)t.push({kind:`tag`,slug:n});for(let n of e.functions)t.push({kind:`function`,name:n});return t}async function S8(e){if(e.kind===`tag`){let t=ul(e.rawContent,e.category??`tag`);if(t.errors.length>0)throw Error(t.errors.join(`
461
461
  `));let n=t.tag.category||e.category||`tag`,r=e.noteId??`t/${n}/${e.slug}`;return Z.withTransaction([...b8],async i=>{let a=x8(t.tag),o={id:t.tag.id||`tag-${e.slug}`,label:t.tag.label||e.slug,...n===`tag`?{}:{type:n},contributions:a,createdAt:Date.now()};await i.putTag(o);let s=await i.saveNoteSource({noteId:r,rawContent:e.rawContent,expectedSourceRevision:e.expectedSourceRevision,metadata:{title:t.tag.label||e.title,sourceId:y8.tag},createdAt:Date.now()});return{id:r,sourceRevision:s.sourceRevision}})}if(e.kind===`tag-type`){let t=Fv(e.rawContent),n=typeof t.slug==`string`&&t.slug.trim()?t.slug.trim():e.slug,r=typeof t.label==`string`&&t.label.trim()?t.label.trim():e.title,i=typeof t.color==`string`&&t.color.trim()?t.color.trim():void 0,a=typeof t.id==`string`&&t.id.trim()?t.id.trim():`tag-type-${n}`,o=e.noteId??`t/${n}`,s=x8(ul(e.rawContent,`tag`).tag);return Z.withTransaction([...b8],async t=>{let c=await t.getTagType(n);await t.putTagType({id:c?.id??a,name:n,label:r,...i?{color:i}:c?.color?{color:c.color}:{},...s.length>0?{contributions:s}:{},createdAt:c?.createdAt??Date.now()});let l=await t.saveNoteSource({noteId:o,rawContent:e.rawContent,expectedSourceRevision:e.expectedSourceRevision,metadata:{title:r,sourceId:y8[`tag-type`]},createdAt:Date.now()});return{id:o,sourceRevision:l.sourceRevision}})}let t=e.kind===`effort`?al(e.rawContent):void 0,n=e.kind===`equipment`?cl(e.rawContent):void 0,r=t?.effort??n?.equipment,i=[...t?.errors??n?.errors??[]],a=Fv(e.rawContent),o=typeof a.id==`string`?a.id.trim():``;if(o||i.push("Frontmatter must declare a stable `id` (the clone flow patches it into the source)"),r&&r.slug!==e.slug&&i.push(`Document slug "${r.slug}" does not match "${e.slug}"`),r&&r.label.trim()!==e.title.trim()&&i.push(`Document label "${r.label}" does not match title "${e.title}"`),i.length>0)throw Error(i.join(`
462
- `));return Z.withTransaction([...b8],async i=>{let a=e.kind===`effort`?await i.getEffort(e.slug):await i.getEquipment(e.slug);if(a?.registrySource===`bundled`)throw Error(`"${e.slug}" is a bundled definition and cannot be saved over — clone it first`);if(a&&a.id!==o)throw Error(`Document id "${o}" does not match record id "${a.id}" — clone instead of re-keying`);let s=a?.ownerNoteId,c=e.noteId??s??`${e.kind}/${e.slug}`;if(s!==void 0&&c!==s)throw Error(`"${e.slug}" is owned by note ${s}; refusing to save against ${c}`);let l=new Date().toISOString();if(e.kind===`effort`){let n={...t.effort,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:y8.effort,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEffort(n)}else{let t={...n.equipment,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:y8.equipment,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEquipment(t)}return{id:c,sourceRevision:(await i.saveNoteSource({noteId:c,rawContent:e.rawContent,expectedSourceRevision:e.expectedSourceRevision,metadata:{title:r.label,sourceId:y8[e.kind]},createdAt:Date.now()})).sourceRevision}})}async function C8(e,t){await Z.withTransaction([...b8],async n=>{if(e===`tag-type`){let e=await n.getTagType(t);e&&await n.deleteTagType(e.id);let r=`t/${t}`;await n.getNote(r)&&await n.deleteNote(r);return}if(e===`tag`){let e=(await n.getAllTags()).find(e=>e.label===t||e.id===t);e&&await n.deleteTag(e.id);let r=`t/${e?.type??`tag`}/${t}`;await n.getNote(r)&&await n.deleteNote(r);return}let r=e===`effort`?await n.getEffort(t):await n.getEquipment(t);if(r?.registrySource!==`user`)throw Error(`"${t}" is not user-owned ${e}`);e===`effort`?await n.deleteEffort(t):await n.deleteEquipment(t);let i=r.ownerNoteId??`${e}/${t}`;await n.getNote(i)&&await n.deleteNote(i)})}function w8(e,t,n,r){let i=`${e}-user-${crypto.randomUUID()}`,a=`${n}-custom`,o=`${r} (Custom)`,s=Ja(t,[`id`],i);return s=Ja(s,[`slug`],a),s=Ja(s,[`label`],o),s=Ja(s,[`registrySource`],`user`),e===`effort`&&(s=Ja(s,[`derivation`,`parentSlug`],n)),{raw:s,id:i,slug:a,label:o}}function T8(e,t=`tag`){let n={},r={},i=[],a=[];for(let t of e.contributions??[])t.kind===`metric`&&t.type.startsWith(`summaries.`)?r[t.type.slice(10)]=String(t.value):t.kind===`metric`&&t.type?n[t.type]=t.unit?`${String(t.value)} ${t.unit}`:typeof t.value==`boolean`?String(t.value):t.value:t.kind===`tag`&&t.slug?i.push(t.slug):t.kind===`function`&&t.name&&a.push(t.name);return dl({id:e.id,slug:e.label,label:e.label,category:e.type||t,aliases:[],metrics:n,summaries:r,tags:i,functions:a})}function E8(e,t){let n=t?.label||e.replace(/[-_]+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase());return fl({id:t?.id??`tag-type-${e}`,name:e,label:n||e,color:t?.color})}function D8(e,t,n,r){let[i,a]=(0,U.useState)(``),[o,s]=(0,U.useState)(0),[c,l]=(0,U.useState)(!1),u=(e??`tag`).trim()||`tag`,d=t?`t/${u}/${t}`:`t/${u}`;return(0,U.useEffect)(()=>{let i=!1;async function o(){if(!e&&!t){a(``),s(0);return}l(!0);try{let o=await Z.getNote(d);if(i)return;o?(a(o.rawContent),s(o.sourceRevision)):t&&n?(a(T8(n,u)),s(0)):!t&&e?(a(E8(u,r??void 0)),s(0)):(a(``),s(0))}finally{i||l(!1)}}return o(),()=>{i=!0}},[d,e,t,n,r,u]),{document:i,setDocument:a,sourceRevision:o,isLoading:c,save:(0,U.useCallback)(async e=>{let a=e??i;if(t){let e=await S8({kind:`tag`,slug:t,category:u,title:n?.label??t,rawContent:a,expectedSourceRevision:o,noteId:d});return await iM(),s(e.sourceRevision),e}let c=await S8({kind:`tag-type`,slug:u,title:r?.label??u,rawContent:a,expectedSourceRevision:o,noteId:d});return s(c.sourceRevision),c},[i,t,u,n,r,o,d])}}function O8(e,t,n){return w8(`effort`,e,t,n)}function k8(e){let{registry:t,isReady:n,revision:r,refresh:i}=BM(),[a,o]=(0,U.useState)(``),[s,c]=(0,U.useState)(!0),[l,u]=(0,U.useState)(null),[d,f]=(0,U.useState)(null),[p,m]=(0,U.useState)(!1),[h,g]=(0,U.useState)(!1),_=d?.registrySource===`user`,v=(0,U.useRef)(null),y=(0,U.useRef)(void 0);(0,U.useEffect)(()=>{if(!n){c(!1);return}if(!e){y.current=void 0,f(null),m(!1),g(!1),v.current=null,u(null),c(!1);return}let r=y.current!==e;y.current=e;let i=!1;r&&(v.current=null,c(!0),u(null),m(!1),f(null),o(``));async function a(){try{let n=t.resolve(e),a=n??t.resolveByAlias(e);if(!a){r&&!i&&(m(!0),c(!1));return}let s=a.ownerNoteId??`effort/${a.slug}`;if(!r&&v.current?.id===s){i||(f(a),g(!n));return}if(!r&&v.current)return;let l=await Z.getNote(s);if(i)return;f(a),g(!n),v.current={id:s,revision:l?.sourceRevision??0},o(l?.rawContent??ol(a)),m(!1),c(!1)}catch(e){i||(u(e instanceof Error?e.message:`Failed to load effort.`),c(!1))}}return a(),()=>{i=!0}},[e,n,r,t]);let b=(0,U.useCallback)(async t=>{if(!e&&!d)return null;let{effort:n,errors:r}=al(t,d??void 0);if(r.length>0)throw Q({title:`Invalid YAML`,description:r.join(`
462
+ `));return Z.withTransaction([...b8],async i=>{let a=e.kind===`effort`?await i.getEffort(e.slug):await i.getEquipment(e.slug);if(a?.registrySource===`bundled`)throw Error(`"${e.slug}" is a bundled definition and cannot be saved over — clone it first`);if(a&&a.id!==o)throw Error(`Document id "${o}" does not match record id "${a.id}" — clone instead of re-keying`);let s=a?.ownerNoteId,c=e.noteId??s??`${e.kind}/${e.slug}`;if(s!==void 0&&c!==s)throw Error(`"${e.slug}" is owned by note ${s}; refusing to save against ${c}`);let l=new Date().toISOString();if(e.kind===`effort`){let n={...t.effort,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:y8.effort,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEffort(n)}else{let t={...n.equipment,id:o,slug:e.slug,registrySource:`user`,ownerNoteId:c,sourceId:y8.equipment,sourcePath:c,createdAt:a?.createdAt??l,updatedAt:l};await i.saveEquipment(t)}return{id:c,sourceRevision:(await i.saveNoteSource({noteId:c,rawContent:e.rawContent,expectedSourceRevision:e.expectedSourceRevision,metadata:{title:r.label,sourceId:y8[e.kind]},createdAt:Date.now()})).sourceRevision}})}async function C8(e,t){await Z.withTransaction([...b8],async n=>{if(e===`tag-type`){let e=await n.getTagType(t);e&&await n.deleteTagType(e.id);let r=`t/${t}`;await n.getNote(r)&&await n.deleteNote(r);return}if(e===`tag`){let e=(await n.getAllTags()).find(e=>e.label===t||e.id===t);e&&await n.deleteTag(e.id);let r=`t/${e?.type??`tag`}/${t}`;await n.getNote(r)&&await n.deleteNote(r);return}let r=e===`effort`?await n.getEffort(t):await n.getEquipment(t);if(r?.registrySource!==`user`)throw Error(`"${t}" is not user-owned ${e}`);e===`effort`?await n.deleteEffort(t):await n.deleteEquipment(t);let i=r.ownerNoteId??`${e}/${t}`;await n.getNote(i)&&await n.deleteNote(i)})}function w8(e,t,n,r){let i=`${e}-user-${crypto.randomUUID()}`,a=`${n}-custom`,o=`${r} (Custom)`,s=Ja(t,[`id`],i);return s=Ja(s,[`slug`],a),s=Ja(s,[`label`],o),s=Ja(s,[`registrySource`],`user`),e===`effort`&&(s=Ja(s,[`derivation`,`parentSlug`],n)),{raw:s,id:i,slug:a,label:o}}function T8(e,t=`tag`){let n={},r={},i=[],a=[];for(let t of e.contributions??[])t.kind===`metric`&&t.type.startsWith(`summaries.`)?r[t.type.slice(10)]=String(t.value):t.kind===`metric`&&t.type?n[t.type]=t.unit?`${String(t.value)} ${t.unit}`:typeof t.value==`boolean`?String(t.value):t.value:t.kind===`tag`&&t.slug?i.push(t.slug):t.kind===`function`&&t.name&&a.push(t.name);return dl({id:e.id,slug:e.label,label:e.label,category:e.type||t,aliases:[],metrics:n,summaries:r,tags:i,functions:a})}function E8(e,t){let n=t?.label||e.replace(/[-_]+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase());return fl({id:t?.id??`tag-type-${e}`,name:e,label:n||e,color:t?.color})}function D8(e,t,n,r){let[i,a]=(0,U.useState)(``),[o,s]=(0,U.useState)(0),[c,l]=(0,U.useState)(!1),u=(e??`tag`).trim()||`tag`,d=t?`t/${u}/${t}`:`t/${u}`;return(0,U.useEffect)(()=>{let i=!1;async function o(){if(!e&&!t){a(``),s(0);return}l(!0);try{let o=await Z.getNote(d);if(i)return;o?(a(o.rawContent),s(o.sourceRevision)):t&&n?(a(T8(n,u)),s(0)):!t&&e?(a(E8(u,r??void 0)),s(0)):(a(``),s(0))}finally{i||l(!1)}}return o(),()=>{i=!0}},[d,e,t,n,r,u]),{document:i,setDocument:a,sourceRevision:o,isLoading:c,save:(0,U.useCallback)(async e=>{let a=e??i;if(t){let e=await S8({kind:`tag`,slug:t,category:u,title:n?.label??t,rawContent:a,expectedSourceRevision:o,noteId:d});return await iM(),s(e.sourceRevision),e}let c=await S8({kind:`tag-type`,slug:u,title:r?.label??u,rawContent:a,expectedSourceRevision:o,noteId:d});return await iM(),s(c.sourceRevision),c},[i,t,u,n,r,o,d])}}function O8(e,t,n){return w8(`effort`,e,t,n)}function k8(e){let{registry:t,isReady:n,revision:r,refresh:i}=BM(),[a,o]=(0,U.useState)(``),[s,c]=(0,U.useState)(!0),[l,u]=(0,U.useState)(null),[d,f]=(0,U.useState)(null),[p,m]=(0,U.useState)(!1),[h,g]=(0,U.useState)(!1),_=d?.registrySource===`user`,v=(0,U.useRef)(null),y=(0,U.useRef)(void 0);(0,U.useEffect)(()=>{if(!n){c(!1);return}if(!e){y.current=void 0,f(null),m(!1),g(!1),v.current=null,u(null),c(!1);return}let r=y.current!==e;y.current=e;let i=!1;r&&(v.current=null,c(!0),u(null),m(!1),f(null),o(``));async function a(){try{let n=t.resolve(e),a=n??t.resolveByAlias(e);if(!a){r&&!i&&(m(!0),c(!1));return}let s=a.ownerNoteId??`effort/${a.slug}`;if(!r&&v.current?.id===s){i||(f(a),g(!n));return}if(!r&&v.current)return;let l=await Z.getNote(s);if(i)return;f(a),g(!n),v.current={id:s,revision:l?.sourceRevision??0},o(l?.rawContent??ol(a)),m(!1),c(!1)}catch(e){i||(u(e instanceof Error?e.message:`Failed to load effort.`),c(!1))}}return a(),()=>{i=!0}},[e,n,r,t]);let b=(0,U.useCallback)(async t=>{if(!e&&!d)return null;let{effort:n,errors:r}=al(t,d??void 0);if(r.length>0)throw Q({title:`Invalid YAML`,description:r.join(`
463
463
  `),variant:`destructive`}),Error(r.join(`
464
464
  `));let a=t,o=n.slug.trim().toLowerCase().replace(/\s+/g,`-`);if(o!==n.slug&&(n.slug=o,a=Ja(a,[`slug`],o)),n.label.trim()!==n.label&&(n.label=n.label.trim(),a=Ja(a,[`label`],n.label)),n.updatedAt=new Date().toISOString(),n.registrySource===`bundled`){let e=O8(a,n.slug,n.label);a=e.raw,n.id=e.id,n.slug=e.slug,n.label=e.label,n.registrySource=`user`,n.derivation={parentSlug:d?.slug,coefficients:{},hardOverrides:{}},n.ownerNoteId=`effort/${n.slug}`}try{let e=n.ownerNoteId??v.current?.id??`effort/${n.slug}`,t=v.current?.id===e?v.current.revision:0,r=await S8({kind:`effort`,slug:n.slug,rawContent:a,title:n.label,expectedSourceRevision:t});return v.current={id:r.id,revision:r.sourceRevision},await i(),f(n),n}catch(e){throw Q({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`}),e}},[e,d,i]),{onChange:x,onLineChange:S,onBlur:C,flush:w}=n0({onSave:async e=>{await b(e)}});return{document:a,setDocument:(0,U.useCallback)(e=>{o(e),x(e)},[x]),isLoading:s,effort:d,isEditable:_,notFound:p,flush:w,onLineChange:S,onBlur:C,save:(0,U.useCallback)(e=>b(e??a),[b,a]),remove:(0,U.useCallback)(async()=>{let t=d?.slug??e;if(t)try{await C8(`effort`,t),v.current=null,f(null),await i()}catch(e){throw Q({title:`Delete failed`,description:e instanceof Error?e.message:`Failed to delete effort.`,variant:`destructive`}),e}},[d,e,i]),cloneForEdit:(0,U.useCallback)(async()=>{if(!d||d.registrySource!==`bundled`)return null;let e=O8(a||ol(d),d.slug,d.label),t={...d,id:e.id,slug:e.slug,label:e.label,registrySource:`user`,derivation:{parentSlug:d.slug,coefficients:{},hardOverrides:{}},ownerNoteId:`effort/${e.slug}`,sourceId:`efforts`,sourcePath:`effort/${e.slug}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};f(t),o(e.raw);try{let t=await S8({kind:`effort`,slug:e.slug,rawContent:e.raw,title:e.label,expectedSourceRevision:0});v.current={id:t.id,revision:t.sourceRevision},await i()}catch(e){throw Q({title:`Clone not saved`,description:e instanceof Error?e.message:`Failed to save the cloned copy.`,variant:`destructive`}),e}return t},[d,a,i]),error:l,isAliasMatch:h}}function A8({resolved:e,effort:t}){return(0,W.jsxs)(`div`,{className:`my-6 p-4 border rounded-lg bg-muted/30 space-y-4`,children:[(0,W.jsxs)(`h3`,{className:`text-sm font-semibold flex items-center gap-2`,children:[(0,W.jsx)(Ve,{className:`size-4`}),`Effective Resolution`]}),(0,W.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Effective MET`}),(0,W.jsx)(`p`,{className:`text-xl font-bold`,children:e.met.toFixed(1)}),Math.abs(e.met-(t.baseAttributes.met||0))>.01&&(0,W.jsxs)(`span`,{className:`text-xs text-amber-600 dark:text-amber-400`,children:[`(base: `,t.baseAttributes.met.toFixed(1),`)`]})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase`,children:`Discipline Factor`}),(0,W.jsxs)(`p`,{className:`text-xl font-bold`,children:[e.disciplineFactor.toFixed(2),`×`]})]})]}),Object.keys(e.modifiers).length>0&&(0,W.jsxs)(`div`,{className:`border-t pt-3`,children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-2`,children:`Applied Modifiers`}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Object.entries(e.modifiers).map(([e,t])=>(0,W.jsxs)(_8,{variant:`outline`,children:[e,`: `,t]},e))})]}),e.definition.derivation?.parentSlug&&(0,W.jsxs)(`div`,{className:`border-t pt-3 text-sm`,children:[(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground uppercase mb-1`,children:`Parent`}),(0,W.jsx)(`span`,{className:`font-mono text-primary`,children:e.definition.derivation.parentSlug})]})]})}function j8(){let{slug:e,tag:t}=In(),n=e??t,[r]=Ct(),i=yn(),{theme:a}=Ei(),o=a===`dark`?`dark`:`vs`,{registry:s,isReady:c,refresh:l}=BM(),{document:u,setDocument:d,isLoading:f,effort:p,isEditable:m,notFound:h,cloneForEdit:g,error:_,onLineChange:v,onBlur:y,flush:b}=k8(n),x=(0,U.useRef)(p?.slug);(0,U.useEffect)(()=>{let e=x.current;p&&e&&p.slug!==e&&p.registrySource===`user`&&i(lP(p.slug)),x.current=p?.slug},[p,i]);let[S,C]=(0,U.useState)([]),[w]=(0,U.useState)([]),[T,E]=(0,U.useState)(null),[D,O]=(0,U.useState)(!1),k=uP(r).mode===`create`,[A,j]=(0,U.useState)(()=>{let e=n&&n!==`new`?n.trim().toLowerCase().replace(/\s+/g,`-`):``,t=e?ZO(e):``;return ol({id:`effort-user-${crypto.randomUUID()}`,slug:e,label:t,aliases:e?[e.replace(/[-_]+/g,` `)]:[],baseAttributes:{met:5},registrySource:`user`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()})}),[M,N]=(0,U.useState)(!1),[P,F]=(0,U.useState)(``),I=(0,U.useMemo)(()=>s?[...s.list()].sort((e,t)=>e.label.localeCompare(t.label)):[],[s]),L=(0,U.useCallback)(async()=>{if(!(!n||!P||!s))try{await xl(s,P,n),await l(),Q({title:`Alias Linked`,description:`Linked "${n}" as an alias to ${P}.`}),i(lP(P))}catch(e){Q({title:`Failed to link alias`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[n,P,s,l,i]),R=(0,U.useCallback)(async()=>{let{effort:e,errors:t}=al(A);if(t.length>0){Q({title:`Invalid YAML`,description:t.join(`
465
465
  `),variant:`destructive`});return}let n=e.slug.trim();if(!n){Q({title:`Missing slug`,description:`A unique slug is required.`,variant:`destructive`});return}if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(n)){Q({title:`Invalid slug`,description:`Slug must be lowercase and hyphenated — fix "slug: ${n}" in the document.`,variant:`destructive`});return}try{await S8({kind:`effort`,slug:n,rawContent:A,title:e.label.trim()||ZO(n),expectedSourceRevision:0}),await l(),i(lP(n),{replace:!0})}catch(e){Q({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save effort.`,variant:`destructive`})}},[A,l,i]),ee=(0,U.useMemo)(()=>new ml(s),[s]),z=(0,U.useMemo)(()=>!p||!c?null:ee.resolveEffort(p.slug),[p,c,ee]),te=(0,U.useCallback)(async e=>{try{let t=await a0({workoutName:p?.label??n??`Effort`,category:`effort`,sourceNotePath:lP(n??``),wodContent:e.content}),r=Object.values(t.blocks??{}).find(e=>e.kind===`wod`);if(!r)throw Error(`The saved journal workout is unavailable.`);let a=ze();o0.set(a,{block:{...e,id:r.id},noteId:t.id}),i(`/run/${a}`)}catch(e){Q({title:`Workout not started`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[n,p?.label,i]),ne=(0,U.useCallback)(async(e,t)=>{if(!p)return;let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`;try{await a0({workoutName:p.label,category:`effort`,sourceNoteLabel:p.label,sourceNotePath:lP(p.slug),wodContent:e.content,date:t}),i(qN(n)),Q({title:`Scheduled`,description:`Added to journal for ${n}`,action:(0,W.jsx)(JM,{altText:`Open journal`,onClick:()=>i(qN(n)),children:`Open`})})}catch{Q({title:`Error`,description:`Could not schedule workout`,variant:`destructive`})}},[p,i]);m0({content:u,scriptBlocks:S,onStartWorkout:te,results:w});let re=p?.ownerNoteId??`effort/${n}`,ie=(0,U.useMemo)(()=>n?y0({id:re,type:`note`}):null,[n,re]),ae=T0({noteId:re,stamps:ie?.stamps??[],effortSlug:n}),oe=D0(`notebook-readonly`,{onPlay:te,onShare:N0,onSchedule:E});(0,U.useEffect)(()=>{p&&(window.document.title=`Wod.Wiki - ${p.label}`)},[p]);let se=(0,U.useCallback)(async()=>{if(p)try{let e=await g();e&&(i(lP(e.slug)),Q({title:`Cloned`,description:`Created a custom copy of "${p.label}". You can now edit it.`}))}catch(e){Q({title:`Clone failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},[g,p,i]);if(!c)return(0,W.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,W.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(k){let e=(0,W.jsx)(uH,{primary:(0,W.jsx)(K,{onClick:R,"data-testid":`effort-create-btn`,children:`Create Effort`}),children:(0,W.jsx)(K,{variant:`outline`,onClick:()=>i(rP()),children:`Cancel`})});return(0,W.jsx)(`div`,{"data-testid":fW.EFFORT_DETAIL_ROOT,className:`contents`,children:(0,W.jsx)(vV,{title:n&&n!==`new`?`New effort: ${n}`:`Create Custom Effort`,actions:e,editor:(0,W.jsx)(`div`,{className:`relative`,"data-testid":`effort-create-editor`,children:(0,W.jsx)(CQ,{value:A,onChange:j,theme:o,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:oe,onBlocksChange:C})})})})}if(f)return(0,W.jsx)(`div`,{className:`flex items-center justify-center py-20`,children:(0,W.jsx)(`div`,{className:`animate-pulse h-4 w-32 bg-muted rounded`})});if(_)return(0,W.jsxs)(`div`,{"data-testid":`effort-load-error`,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsx)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:`Effort could not be loaded`}),(0,W.jsx)(`p`,{className:`text-sm text-destructive`,children:_})]}),(0,W.jsx)(K,{variant:`outline`,onClick:()=>i(rP()),children:`Back to library`})]});if(h||!p)return(0,W.jsxs)(`div`,{"data-testid":fW.EFFORT_NOT_FOUND,className:`flex flex-col items-center justify-center gap-6 py-16 px-4 text-center max-w-lg mx-auto`,children:[(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsxs)(`h2`,{className:`text-xl font-semibold tracking-tight`,children:[`Effort “`,n,`” not found`]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This movement has not been populated in the effort catalog yet. You can create a new definition page for it or link it as an alias to an existing effort.`})]}),M?(0,W.jsxs)(`div`,{className:`w-full space-y-4 p-4 border rounded-lg bg-card text-left`,children:[(0,W.jsxs)(`div`,{className:`space-y-1`,children:[(0,W.jsxs)(`label`,{className:`text-xs font-medium text-foreground`,children:[`Select target effort for “`,n,`”:`]}),(0,W.jsx)(v8,{value:P,onChange:e=>F(e.target.value),"data-testid":fW.EFFORT_NOT_FOUND_ALIAS_SELECT,children:I.map(e=>(0,W.jsxs)(`option`,{value:e.slug,children:[e.label,` (`,e.slug,`)`]},e.slug))})]}),(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(K,{variant:`ghost`,size:`sm`,onClick:()=>N(!1),children:`Cancel`}),(0,W.jsx)(K,{size:`sm`,onClick:L,disabled:!P,"data-testid":fW.EFFORT_NOT_FOUND_ALIAS_CONFIRM,children:`Confirm Link`})]})]}):(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-3`,children:[(0,W.jsx)(K,{onClick:()=>i(lP(n,void 0,{mode:`create`})),"data-testid":fW.EFFORT_NOT_FOUND_CREATE_BTN,children:`Create Effort Page`}),(0,W.jsx)(K,{variant:`secondary`,onClick:()=>{N(!0),I.length>0&&!P&&F(I[0].slug)},"data-testid":fW.EFFORT_NOT_FOUND_ALIAS_BTN,children:`Link as Alias`}),(0,W.jsx)(K,{variant:`outline`,onClick:()=>i(rP()),children:`Back to library`})]})]});let ce=(0,W.jsxs)(uH,{primary:m?void 0:(0,W.jsxs)(K,{variant:`outline`,onClick:se,"data-testid":fW.EFFORT_DETAIL_CLONE_BTN,children:[(0,W.jsx)(pe,{className:`size-4 mr-1.5`}),`Clone`]}),children:[(0,W.jsx)(K,{variant:`ghost`,size:`icon`,onClick:()=>JU()?i(-1):i(rP()),"aria-label":`Back to catalog`,title:JU()?`Back`:`Back to catalog`,children:(0,W.jsx)(We,{className:`size-4`})}),(0,W.jsx)(_8,{"data-testid":fW.EFFORT_DETAIL_SOURCE,variant:p.registrySource===`bundled`?`secondary`:`default`,children:p.registrySource===`bundled`?`Bundled`:`Custom`}),z&&(0,W.jsxs)(K,{variant:D?`default`:`outline`,onClick:()=>O(e=>!e),children:[(0,W.jsx)(Ve,{className:`size-4 mr-1.5`}),D?`Hide Resolved`:`Show Resolved`]})]}),B=re;return(0,W.jsxs)(`div`,{"data-testid":fW.EFFORT_DETAIL_ROOT,className:`contents`,children:[(0,W.jsx)(vV,{title:p.label,titleTestId:fW.EFFORT_DETAIL_LABEL,actions:ce,editor:(0,W.jsxs)(`div`,{className:`relative`,"data-testid":fW.EFFORT_DETAIL_NOTEBOOK_EDITOR,children:[D&&z&&(0,W.jsx)(`div`,{className:`px-6 lg:px-10 pt-4`,children:(0,W.jsx)(A8,{resolved:z,effort:p})}),(0,W.jsx)(CQ,{noteId:B,value:u,onChange:d,onCursorPositionChange:v,onBlur:y,onSaveRequest:b,onCommitChange:b,theme:o,readonly:!1,showLineNumbers:!0,enablePreview:!0,enableLinting:!0,enableOverlay:!0,mode:`edit`,commands:oe,onBlocksChange:C}),(0,W.jsx)(E0,{data:ae,up:ie?.up,relatedLabel:`Used in`})]})}),T&&(0,W.jsx)(WC,{open:!0,onClose:()=>E(null),title:`Schedule workout`,children:(0,W.jsx)(t0,{selectedDate:null,onDateSelect:e=>{ne(T,e),E(null)}})})]})}function M8(e,t){let n=t??e.replace(/[-_]+/g,` `).trim().replace(/\b\w/g,e=>e.toUpperCase());return ll({id:`equipment-user-${crypto.randomUUID()}`,slug:e,label:n||e,aliases:[],registrySource:`user`})}function N8(e,t,n){return w8(`equipment`,e,t,n)}function P8(e){let{registry:t,isReady:n,refresh:r}=UM(),[i,a]=(0,U.useState)(``),[o,s]=(0,U.useState)(!0),[c,l]=(0,U.useState)(null),[u,d]=(0,U.useState)(null),[f,p]=(0,U.useState)(!1),[m,h]=(0,U.useState)(!1),g=u?.registrySource===`user`,_=(0,U.useRef)(null);(0,U.useEffect)(()=>{if(!n){s(!1);return}if(!e){d(null),p(!1),h(!1),_.current=null,l(null),s(!1);return}let r=!1;s(!0),l(null),p(!1),d(null),a(``);async function i(){try{let n=t.resolve(e),i=n??t.resolveByAlias(e);if(!i){r||(p(!0),s(!1));return}let o=i.ownerNoteId??`equipment/${i.slug}`,c=await Z.getNote(o);if(r)return;d(i),h(!n),_.current={id:o,revision:c?.sourceRevision??0},a(c?.rawContent??ll(i)),s(!1)}catch(e){r||(l(e instanceof Error?e.message:`Failed to load equipment.`),s(!1))}}return i(),()=>{r=!0}},[e,n,t]);let v=(0,U.useCallback)(async e=>{let{equipment:t,errors:n}=cl(e,u??void 0);if(n.length>0)throw Q({title:`Invalid YAML`,description:n.join(`
@@ -491,4 +491,4 @@ Fran went unbroken until round three. Throat on fire.
491
491
  `,k9]})]})}var Wte=`✎`;function Gte({wql:e,setWql:t}){let[n,r]=(0,U.useState)(!1),[i,a]=(0,U.useState)(e);return(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsxs)(`div`,{className:`relative`,children:[(0,W.jsx)(j9,{wql:e}),!n&&(0,W.jsx)(`button`,{onClick:()=>{a(e),r(!0)},className:`absolute top-2 right-2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted`,children:Wte})]}),n&&(0,W.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-card p-3 space-y-2 shadow-lg shadow-sky-500/5`,children:[(0,W.jsx)(`div`,{className:`text-[10px] text-sky-400 font-mono`,children:`editing query:table — Apply writes the fence`}),(0,W.jsx)(cT,{query:i,onQueryChange:a,autoFocus:!0,placeholder:`:session…`}),(0,W.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,W.jsx)(`button`,{onClick:()=>r(!1),className:`px-3 py-1 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground`,children:`Cancel`}),(0,W.jsx)(`button`,{onClick:()=>{t(i),r(!1)},className:`px-3 py-1 text-xs rounded-md bg-sky-500 text-zinc-950 font-medium`,children:`Apply to fence`})]})]})]})}function Kte({wql:e,setWql:t}){let[n,r]=(0,U.useState)(!1);return(0,W.jsxs)(`div`,{className:`space-y-3 pb-24`,children:[(0,W.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left rounded-lg transition-shadow ${n?`ring-2 ring-sky-500/70`:`hover:ring-1 hover:ring-border`}`,children:(0,W.jsx)(j9,{wql:e})}),(0,W.jsxs)(`div`,{className:`sticky bottom-20 rounded-xl border p-3 space-y-2 shadow-xl backdrop-blur transition-colors ${n?`border-sky-500/60 bg-card/95`:`border-border bg-card/80 opacity-70`}`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-mono ${n?`text-sky-400`:`text-muted-foreground`}`,children:n?`◉ bound: query:table · ${D9.slice(0,8)}…`:`○ click a query block to bind the composer`}),n&&(0,W.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-muted-foreground hover:text-foreground`,children:`Done`})]}),n&&(0,W.jsx)(cT,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`})]})]})}function qte({wql:e,setWql:t}){let[n,r]=(0,U.useState)(!1);return(0,U.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`&&r(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),n?(0,W.jsxs)(`div`,{className:`rounded-lg border border-sky-500/50 bg-muted/60 shadow-lg shadow-sky-500/5`,children:[(0,W.jsx)(`div`,{className:`px-3 pt-2 text-[10px] font-mono text-muted-foreground select-none`,children:"```query:table"}),(0,W.jsx)(`div`,{className:`px-3 py-2`,children:(0,W.jsx)(cT,{query:e,onQueryChange:t,autoFocus:!0,showDiagnostics:!1,placeholder:`:session…`,className:`bg-transparent border-0 shadow-none`})}),(0,W.jsxs)(`div`,{className:`px-3 pb-2 flex items-center justify-between`,children:[(0,W.jsx)(`span`,{className:`text-[10px] font-mono text-muted-foreground select-none`,children:"```"}),(0,W.jsx)(`button`,{onClick:()=>r(!1),className:`text-[10px] text-sky-400 hover:text-sky-300 font-mono`,children:`Esc / leave fence ↩`})]})]}):(0,W.jsx)(`button`,{onClick:()=>r(!0),className:`block w-full text-left hover:ring-1 hover:ring-border rounded-lg`,children:(0,W.jsx)(j9,{wql:e})})}var N9=[[`inline`,`A · in-flow expansion`],[`dock`,`B · bound dock`],[`fence`,`C · fence-as-composer`]];function Jte(){let[e,t]=Ct(),n=e.get(`v`)??`inline`,[r,i]=(0,U.useState)(Bte),a=e=>{let r=N9[(N9.findIndex(([e])=>e===n)+e+N9.length)%N9.length][0];t({v:r})};return(0,U.useEffect)(()=>{let e=e=>{e.target.closest(`input, textarea, [contenteditable]`)||(e.key===`ArrowLeft`&&a(-1),e.key===`ArrowRight`&&a(1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)}),(0,W.jsxs)(`div`,{className:`min-h-screen bg-background text-foreground p-6`,children:[(0,W.jsxs)(`div`,{className:`max-w-5xl mx-auto grid grid-cols-[1fr_320px] gap-6 items-start`,children:[(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`div`,{className:`text-[11px] text-amber-500 mb-1`,children:`PROTOTYPE — throwaway · query:table editing via WqlComposer`}),(0,W.jsx)(`h1`,{className:`text-xl font-bold`,children:`Journal — 2026-09-13`})]}),(0,W.jsx)(M9,{children:O9.split("```time")[0].trim()}),(0,W.jsx)(Hte,{}),n===`inline`&&(0,W.jsx)(Gte,{wql:r,setWql:i}),n===`dock`&&(0,W.jsx)(Kte,{wql:r,setWql:i}),n===`fence`&&(0,W.jsx)(qte,{wql:r,setWql:i}),(0,W.jsx)(M9,{children:k9})]}),(0,W.jsx)(`div`,{className:`sticky top-6`,children:(0,W.jsx)(Ute,{wql:r})})]}),(0,W.jsxs)(`div`,{className:`fixed bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 rounded-xl border border-border bg-card/95 backdrop-blur px-2 py-1.5 shadow-2xl z-50`,children:[(0,W.jsx)(`button`,{onClick:()=>a(-1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`←`}),N9.map(([e,r])=>(0,W.jsx)(`button`,{onClick:()=>t({v:e}),className:`px-3 py-1 rounded-lg text-xs transition-colors ${n===e?`bg-sky-400 text-zinc-950 font-medium`:`text-muted-foreground hover:text-foreground`}`,children:r},e)),(0,W.jsx)(`button`,{onClick:()=>a(1),className:`px-2 text-muted-foreground hover:text-foreground`,children:`→`})]})]})}function P9(e,t,n=`absent`){return{id:e,fields:t,missPolicy:n,get:()=>void 0}}function Yte(){let e=new mp;return e.register(P9(`effort`,{met:{dimension:J,type:`number`},disciplineFactor:{dimension:J,type:`number`},discipline:{dimension:J,type:`string`},intensityTier:{dimension:J,type:`string`},resolvedFrom:{dimension:J,type:`string`}},`default-row`)),e.register(P9(`rpe-labels`,{rpe:{dimension:J,type:`number`}})),e.register(P9(`profile`,{vo2max:{dimension:J,type:`number`}})),e.register(P9(`disciplines`,{disciplineFactor:{dimension:J,type:`number`}},`default-row`)),e}function Xte(e,t){for(let n of t)try{e.register(n)}catch{}}function F9(e,t=`segment`){let n=[],r=[];try{let i=Ed(e,{scope:t});r=i.defs;for(let e of i.warnings)n.push({severity:`warning`,message:e})}catch(e){return{defs:r,diagnostics:[{severity:`error`,message:e instanceof Error?e.message:String(e)}],dim:void 0,compound:void 0}}let i=new Qf(Yte());Xte(i,[...gp,...bp]);let a;for(let e of r){try{i.register(e)}catch(e){n.push({severity:`error`,message:e instanceof Error?e.message:String(e)});continue}let t=Bd(e)??(e.kind===`library`?Object.keys(e.variants[0]?.nodes??{})[0]:void 0),r=[...e.variants].sort((e,t)=>t.priority-e.priority)[0],o=t&&r.nodeDims?.[t];o&&(a=o)}let o;return a&&(o=Hu(a)),r.length===0&&n.push({severity:`warning`,message:`No calc line parsed.`}),{defs:r,diagnostics:n,dim:a,compound:o}}var Zte=[`segment`,`workout`,`store`],I9=[`when`,`where`,`key`,`grouped`,`label`,`emit`,`meta`,`estimated`,`library`,`on`,`by`,`without`,`and`,`or`,`not`],L9=[`convert`,`lookup`,`has`,`round`,`floor`,`ceil`,`abs`,`clamp`,`min`,`max`,`sum`,`avg`,`count`,`last`,`windowMean`,`windowSum`,`windowSd`,`mean`],R9=[{name:`elapsed`,dim:Uu.elapsed.dim,detail:`s (time)`},{name:`reps`,dim:Uu.reps.dim,detail:`count`},{name:`resistance`,dim:Uu.resistance.dim,detail:`kg (mass)`},{name:`distance`,dim:Uu.distance.dim,detail:`m (length)`},{name:`effort`,dim:Wu.effort,detail:`resolved effort slug`},{name:`effortLabel`,dim:Wu.effortLabel,detail:`raw effort label`}],z9=[{name:`sessionRpe`,dim:Wu.sessionRpe,detail:`captured session RPE`},{name:`session.duration`,dim:Wu[`session.duration`],detail:`workout duration`},{name:`profile.vo2max`,dim:Wu[`profile.vo2max`],detail:`user VO₂max (mL/kg/min)`}],B9=Object.keys(Uu),Qte=Object.keys(Gu),V9=[{name:`effort`,detail:`effort library`,fields:[`met`,`disciplineFactor`,`discipline`,`intensityTier`,`resolvedFrom`]},{name:`rpe-labels`,detail:`effort label → RPE`,fields:[`rpe`]},{name:`profile`,detail:`user profile`,fields:[`vo2max`]},{name:`disciplines`,detail:`canonical disciplines`,fields:[`disciplineFactor`]}],H9=Object.keys(Yu),$te=Object.keys(Gu);function ene(e){return e?H9.filter(t=>{let n=Yu[t];return n?n.dim.every((t,n)=>t===e[n]):!1}):H9}var tne=new Set([...I9,...Zte,`lookup`]),nne=new Set(L9),rne=new Set([...R9.map(e=>e.name),...z9.map(e=>e.name),...B9,...V9.map(e=>e.name)]),ine=/^\d*\.?\d+(?:d)?/,ane=/^[A-Za-z_][\w.]*/,one=br.define({name:`calcLine`,token(e){if(e.eatSpace())return null;if(e.match(`#`,!1))return e.skipToEnd(),`comment`;if(e.match(/^"([^"]*)"/)||e.match(/^'([^']*)'/))return`string`;if(e.match(/^(->|==|!=|<=|>=)/)||e.match(/^[+\-*/=<>(),:{}[\]]/))return`operator`;if(e.match(ine))return`number`;if(e.match(ane)){let t=e.current();return tne.has(t)?`keyword`:nne.has(t)?`function`:(rne.has(t),`variableName`)}return e.next(),null}}),sne=Dr.define([{tag:H.keyword,color:`#c084fc`},{tag:H.function(H.variableName),color:`#60a5fa`},{tag:H.variableName,color:`#e4e4e7`},{tag:H.number,color:`#fbbf24`},{tag:H.string,color:`#34d399`},{tag:H.operator,color:`#a1a1aa`},{tag:H.comment,color:`#71717a`,fontStyle:`italic`}]);function cne(){return new Ar(one,[Er(sne)])}var lne=[`effort`,`thruster`,`push-press`,`front-squat`,`wall-ball`,`row`,`run`];function U9(e,t){return`${t?``:`"`}${e}"`}function une(e={}){let t=e.scope??`segment`,n=()=>{let t=e.effortKeys?.().filter(Boolean)??[];return[`effort`,...t.length?t:lne.slice(1)]};return e=>{let r=e.state.sliceDoc(0,e.pos),i=e.matchBefore(/[\w./"]*/);if(!i)return null;if(/lookup\(\s*/.test(r)){let t=r.lastIndexOf(`lookup(`),i=r.slice(t+7);if(!/,/.test(i)&&/^"?[\w.-]*"?$/.test(i.replace(/"/g,``).trim()||``)){let t=i.replace(/"/g,``).trim(),n=i.trimStart().startsWith(`"`),r=V9.filter(e=>e.name.startsWith(t)).map(e=>({label:e.name,apply:U9(e.name,n),detail:e.detail}));if(r.length)return{from:e.pos-t.length,to:e.pos+ +(e.state.sliceDoc(e.pos,e.pos+1)===`"`),options:r,validFor:/^[\w.-]*$/}}let a=/lookup\(\s*"[^"]+"\s*,\s*[^,]+,\s*"?([\w-]*)"?$/.exec(r);if(a){let t=/lookup\(\s*"([^"]+)"/.exec(r)?.[1],n=V9.find(e=>e.name===t),i=e.pos-a[1].length,o=e.state.sliceDoc(i-1,i)===`"`,s=(n?.fields??[]).filter(e=>e.startsWith(a[1])).map(e=>({label:e,apply:U9(e,o),detail:`${t} field`}));return{from:i,to:e.pos+ +(e.state.sliceDoc(e.pos,e.pos+1)===`"`),options:s,validFor:/^[\w-]*$/}}let o=/lookup\(\s*"(effort)"\s*,\s*"?([\w.-]*)"?$/.exec(r);if(o){let t=n().filter(e=>e.startsWith(o[2])),r=e.pos-o[2].length,i=e.state.sliceDoc(r-1,r)===`"`,a=t.map(e=>({label:e,apply:e===`effort`?e:U9(e,i),detail:`effort key`}));return{from:r,to:e.pos+ +(e.state.sliceDoc(e.pos,e.pos+1)===`"`),options:a,validFor:/^[\w.-]*$/}}}let a=/->\s*([\w/]*)$/.exec(r);if(a){let n=e.state.doc.lineAt(e.pos).text,r=F9(n,t);if(!r.dim){let e=n.lastIndexOf(`->`);if(e>=0){let i=F9(n.slice(0,e),t);i.diagnostics.length===0&&(r=i)}}let i=r.diagnostics.length===0?r.dim:void 0,o=ene(i).filter(e=>e.startsWith(a[1])).map(e=>({label:e,detail:i?`matches inferred dimension`:`unit`}));return{from:e.pos-a[1].length,options:o,validFor:/^[\w/]*$/}}if(t===`store`){let e=/^(sum|avg|max|min|count|last):([\w.]*)$/.exec(i.text);if(e){let t=B9.filter(t=>t.startsWith(e[2])).map(e=>({label:e,detail:`metric key`}));return{from:i.from+i.text.indexOf(`:`)+1,options:t,validFor:/^[\w.]*$/}}}let o=[];if(t===`segment`)o.push(...R9.map(e=>({label:e.name,apply:e.name,detail:e.detail})));else if(o.push(...z9.map(e=>({label:e.name,apply:e.name,detail:e.detail}))),t===`workout`){for(let e of Qte)for(let t of[`reps`,`distance`,`segmentVolume`,`metMinutes`,`elapsed`,`effortRpe`])o.push({label:`${e}(${t})`,apply:`${e}(${t})`,detail:`aggregate`});o.push({label:`sum(reps, without: rest)`,apply:`sum(reps, without: rest)`,detail:`exclusion aggregate`})}o.push(...L9.map(e=>({label:`${e}()`,apply:`${e}()`,detail:`function`}))),t===`store`&&o.push(...$te.map(e=>({label:`${e}:{}`,apply:`${e}:`,detail:`WQL atom`}))),o.push(...I9.map(e=>({label:e,apply:e===`when`?`when `:e,detail:`clause`}))),o.push({label:`estimated`,apply:`estimated`,detail:`variant origin`}),o.push({label:`(library)`,apply:`(library)`,detail:`library calc`});let s=o.filter(e=>e.label.startsWith(i.text)).slice(0,20);return s.length?{from:i.from,options:s,validFor:/^[\w./]*$/}:null}}function dne(e){return Wr({override:[une(e)],interactionDelay:0})}function fne({value:e,onChange:t,scope:n=`segment`,placeholder:r,readOnly:i=!1,autoFocus:a=!1,className:o}){let s=(0,U.useRef)(null),c=(0,U.useRef)(null),l=(0,U.useRef)(t);return l.current=t,(0,U.useEffect)(()=>{let t=s.current;if(!t)return;c.current?.destroy();let r=Sr.updateListener.of(e=>{e.docChanged&&l.current(e.state.doc.toString())}),o=new Sr({state:Qr.create({doc:e,extensions:[cne(),dne({scope:n,effortKeys:()=>KO().list().map(e=>e.slug)}),eT,Jr(),ci(),hr.of([Xr,...Yr,...ri]),Sr.lineWrapping,Qr.readOnly.of(i),r,Sr.theme({"&":{height:`auto`,minHeight:`120px`,fontSize:`13px`,border:`1px solid rgb(63 63 70)`,borderRadius:`8px`},".cm-scroller":{fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,lineHeight:`1.55`},".cm-content":{padding:`8px 4px`},".cm-gutters":{borderRight:`1px solid rgb(63 63 70)`,minWidth:`28px`},"&.cm-focused":{outline:`2px solid rgb(139 92 246 / 0.5)`,outlineOffset:`1px`}})]}),parent:t});return a&&requestAnimationFrame(()=>o.focus()),c.current=o,()=>o.destroy()},[n,i]),(0,U.useEffect)(()=>{let t=c.current;if(!t)return;let n=t.state.doc.toString();n!==e&&t.dispatch({changes:{from:0,to:n.length,insert:e}})},[e]),(0,W.jsx)(`div`,{ref:s,className:`calc-line-editor ${o??``}`,"data-testid":`calc-line-editor`})}function pne({analysis:e}){let{dim:t,compound:n,diagnostics:r}=e,i=r.filter(e=>e.severity===`error`),a=r.filter(e=>e.severity===`warning`),o=i.length===0&&a.length===0&&t!==void 0;return(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 px-3 py-2 text-xs`,"data-testid":`calc-diagnostics`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[t?(0,W.jsxs)(`div`,{className:`text-muted-foreground`,children:[`computes `,(0,W.jsx)(`b`,{className:`text-foreground`,children:mne(t)}),n&&(0,W.jsxs)(`span`,{className:`text-purple-400 dark:text-purple-300`,children:[` → `,n]})]}):!o&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`dimension unknown`}),o&&(0,W.jsx)(`span`,{className:`text-signal-positive`,children:`✓ valid`})]}),i.map((e,t)=>(0,W.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e.message]},`e-${t}`)),a.map((e,t)=>(0,W.jsxs)(`div`,{className:`text-signal-caution`,children:[`⚠ `,e.message]},`w-${t}`)),i.length===0&&a.length===0&&t===void 0&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`Type a calc line to see diagnostics.`})]})}var W9=[[`L`,`length`],[`M`,`mass`],[`T`,`time`],[`C`,`count`],[`E`,`energy`]];function mne(e){let t=[];return e.forEach((e,n)=>{e!==0&&t.push(e===1?W9[n][1]:`${W9[n][1]}${e}`)}),t.length?t.join(`·`):`dimensionless`}function G9(e){return new fa({outputType:e.outputType,timeSpan:e.timeSpan,sourceBlockKey:e.sourceBlockKey,stackLevel:e.stackLevel,sourceStatementId:e.sourceStatementId,line:e.line,text:e.text,dialect:e.dialect,metrics:e.metrics,parent:e.parent,completionReason:e.completionReason})}function K9(e){return{...e,metrics:e.metrics.filter(e=>e.origin!==`analyzed`)}}function hne(e){return e.output?.emitType??e.output?.key??e.id}function gne(e,t){for(let n of e){if(n.outputType!==`analytics`||!(n.metrics.find(e=>e.type?.toLowerCase()===`label`&&String(e.value)===t)??n.metrics.find(e=>String(e.value)===t)))continue;let e=n.metrics.find(e=>typeof e.value==`number`);if(e)return{value:e.value,unit:e.unit,origin:e.origin}}}function q9(e){return String(Number.isInteger(e)?e:Math.round(e*100)/100)}function J9(e,t,n){return jp(e,{userProfile:t.vo2max===void 0?void 0:{vo2max:t.vo2max},calcs:n}).engine}function _ne(e){let t=[],n=e.defs[0];if(!n)return{rows:[],errors:[`No calc line to preview.`]};let r=hne(n),i=e.logs.filter(e=>e.outputType===`segment`);if(e.scope===`segment`){let n=J9(e.block,e,e.defs),a=[];for(let e of i){let t=n.run(G9(K9(e))).metrics.rawMetrics.find(e=>e.type===r);if(!t){a.push(null);continue}let i=typeof t.value==`number`?t.value:NaN;if(!Number.isFinite(i)){a.push(null);continue}a.push({label:e.metrics.find(e=>e.type===`effort-data`)?.value?.label??`segment`,text:q9(i),unit:t.unit,estimated:t.origin===`analyzed-estimated`,raw:i})}return{rows:a,errors:t}}if(e.scope===`workout`){let n=i.map(K9),a=[];for(let t=1;t<=n.length;t++){let i=J9(e.block,e,e.defs);for(let e=0;e<t;e++)i.run(G9(n[e]));let o=gne(i.finalize(),r),s=o&&typeof o.value==`number`?o.value:NaN;o&&Number.isFinite(s)?a.push({label:`after line ${t}`,text:q9(s),unit:o.unit,estimated:o.origin===`analyzed-estimated`,raw:s}):a.push(null)}return{rows:a,errors:t}}return vne(n,t)}var Y9=[420,0,380,510,0,290,610,450,0,520,340,0,480,390,560,0,410,470,0,530,360,440,0,500,580,320,0,460];function vne(e,t){let n=[],r=e.variants[0]?.nodes[Bd(e)??`value`]?.expression??``,i=e=>e.reduce((e,t)=>e+t,0)/e.length,a=e=>{let t=i(e);return Math.sqrt(i(e.map(e=>(e-t)**2)))},o=(e,t)=>Y9.map((n,r)=>r+1>=e?t(Y9.slice(r+1-e,r+1)):NaN),s=o(7,i),c=o(28,i),l=o(7,a),u=o(7,e=>e.reduce((e,t)=>e+t,0)),d=r.includes(`windowSd`)||r.length===0?s.map((e,t)=>e/l[t]):s.map((e,t)=>e/c[t]);return yne(r.includes(`windowSum`)||r.includes(` * sum`)?u:d,n),{rows:[],series:n,errors:t}}function yne(e,t){for(let n of e.slice(-7))t.push(Number.isNaN(n)?null:Number(Math.round(n*100)/100))}var bne=[{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:21,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:21,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:15,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:15,resistanceKg:0},{label:`Thruster`,slug:`thruster`,met:8.5,discipline:`strength`,elapsedMs:15e4,reps:9,resistanceKg:43},{label:`Pull-up`,slug:`pull-up`,met:7,discipline:`gymnastics`,elapsedMs:12e4,reps:9,resistanceKg:0}];function xne(e){return{type:`effort-data`,origin:`analyzed`,value:{slug:e.slug,label:e.label,aliases:[],baseAttributes:{met:e.met,discipline:e.discipline},registrySource:`bundled`}}}function Sne(e,t){let n=[xne(e)];return n.push({type:`elapsed`,value:e.elapsedMs,origin:`runtime`}),e.reps!==void 0&&n.push({type:`rep`,value:e.reps,origin:`runtime`}),e.resistanceKg!==void 0&&n.push({type:`resistance`,value:e.resistanceKg,origin:`runtime`}),yP(new fa({outputType:`segment`,timeSpan:{started:t*1e3,ended:t*1e3+e.elapsedMs},sourceBlockKey:`preview-block`,stackLevel:1,metrics:n}))}function Cne(){return{id:`preview-block`,dialect:`time`,startLine:0,endLine:10,content:"```time\nFran preview\n```",state:`idle`,widgetIds:{},version:1,createdAt:0}}var wne=bne.map((e,t)=>Sne(e,t+1)),Tne=Cne();function Ene(e){return e==null?`—`:String(e)}function Dne({scope:e,analysis:t,vo2max:n}){let r=(0,U.useMemo)(()=>t.defs.filter(()=>t.diagnostics.length===0),[t]),i=r[0],a=(0,U.useMemo)(()=>{if(i)return _ne({logs:wne,block:Tne,defs:r,scope:e,vo2max:n})},[i,e,n]);return(0,W.jsxs)(`div`,{className:`rounded-lg border border-border bg-card/60 p-3 text-xs`,"data-testid":`calc-preview`,children:[(0,W.jsxs)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wide text-muted-foreground`,children:[`Live preview — `,e===`store`?`last 7 of 28 fixture days`:`Fran (fixture)`]}),!i&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`Enter a valid calc line to see live results.`}),i&&a?.rows&&(0,W.jsxs)(`div`,{className:`space-y-1 font-mono`,children:[a.rows.length===0&&(0,W.jsx)(`div`,{className:`text-muted-foreground`,children:`No applicable segments.`}),a.rows.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:e?e.label:`segment ${t+1}`}),(0,W.jsx)(`span`,{className:e?`text-sky-300 dark:text-sky-400`:`text-muted-foreground`,children:e?`${e.text}${e.unit?` ${e.unit}`:``}${e.estimated?` (est.)`:``}`:`—`})]},t))]}),i&&a?.series&&(0,W.jsx)(`div`,{className:`space-y-1 font-mono`,children:a.series.map((e,t)=>(0,W.jsxs)(`div`,{className:`flex justify-between text-foreground`,children:[(0,W.jsxs)(`span`,{className:`text-muted-foreground`,children:[`D-`,6-t]}),(0,W.jsx)(`span`,{className:`text-sky-300 dark:text-sky-400`,children:Ene(e)})]},t))}),a?.errors?.length?a.errors.map((e,t)=>(0,W.jsxs)(`div`,{className:`text-destructive`,children:[`⚠ `,e]},`e-${t}`)):null]})}var One=[`segment`,`workout`,`store`];function kne(e,t){let n=e[0]?.id;if(n)return n;let r=/^[\s\S]*?^\s*([A-Za-z_][\w.-]*)\s*=.*$/m.exec(t);return r?r[1]:`custom-${Date.now().toString(36)}`}function Ane({defaultScope:e=`segment`,initialId:t}){let[n,r]=(0,U.useState)(`# ${e} calc line
492
492
  segmentVolume = reps * resistance (library) when has(reps) and has(resistance)
493
493
  `),[i,a]=(0,U.useState)(e),[o,s]=(0,U.useState)([]),[c,l]=(0,U.useState)(),u=(0,U.useMemo)(()=>F9(n,i),[n,i]),d=kne(u.defs,n),f=u.diagnostics.every(e=>e.severity!==`error`)&&u.defs.length>0,p=async()=>{s(await W8())};(0,U.useEffect)(()=>{p()},[]),(0,U.useEffect)(()=>{t&&(async()=>{let e=(await W8()).find(e=>e.id===t);e&&(r(e.lineForm),l(`Loaded "${e.id}".`))})()},[t]);let m=async()=>{if(!f){l(`Cannot save: fix the errors first.`);return}try{await G8({id:d,lineForm:n,updatedAt:Date.now()}),await p(),l(`Saved "${d}".`)}catch(e){console.error(`[CalcAuthoringPanel] save failed:`,e),l(`Save failed: ${e instanceof Error?e.message:String(e)}`)}},h=async e=>{try{await K8(e),await p(),l(`Deleted "${e}".`)}catch(e){console.error(`[CalcAuthoringPanel] delete failed:`,e),l(`Delete failed: ${e instanceof Error?e.message:String(e)}`)}},g=e=>{let t=/^\s*(segment|workout|store)\b/.exec(e.lineForm);t&&a(t[1]),r(e.lineForm),l(`Loaded "${e.id}".`)};return(0,W.jsxs)(`div`,{className:`space-y-3`,"data-testid":`calc-authoring-panel`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Scope`}),(0,W.jsx)(`div`,{className:`flex gap-1`,children:One.map(e=>(0,W.jsx)(`button`,{onClick:()=>a(e),className:`rounded px-2.5 py-1 text-xs font-medium transition-colors ${i===e?`bg-purple-600 text-white dark:bg-purple-700 dark:text-white`:`bg-muted text-muted-foreground hover:bg-muted/80`}`,children:e},e))}),(0,W.jsx)(`div`,{className:`ml-auto flex gap-2`,children:(0,W.jsx)(`button`,{onClick:m,disabled:!f,className:`rounded bg-signal-positive px-3 py-1 text-xs font-medium text-white dark:text-white disabled:opacity-40`,children:`Save`})})]}),(0,W.jsx)(fne,{value:n,onChange:r,scope:i,autoFocus:!0}),(0,W.jsx)(pne,{analysis:u}),(0,W.jsx)(Dne,{scope:i,analysis:u}),c&&(0,W.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:c}),o.length>0&&(0,W.jsxs)(`div`,{className:`mt-2`,children:[(0,W.jsx)(`div`,{className:`mb-1 text-[11px] uppercase tracking-wide text-muted-foreground`,children:`Saved user calcs`}),(0,W.jsx)(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,children:o.map(e=>(0,W.jsxs)(`li`,{className:`flex items-center justify-between px-3 py-2 text-sm`,children:[(0,W.jsx)(`button`,{onClick:()=>g(e),className:`text-left font-mono text-purple-300 dark:text-purple-400 hover:underline`,children:e.id}),(0,W.jsx)(`button`,{onClick:()=>h(e.id),className:`text-xs text-muted-foreground hover:text-destructive`,children:`delete`})]},e.id))})]})]})}function jne(){let e=yn(),[t]=ln(`zip`),[n]=ln(`z`),[r]=(0,U.useState)(()=>{let e=window.location.search;return e.includes(`zip=`)||e.includes(`z=`)});return(0,U.useEffect)(()=>{!t&&!n&&!r&&e(`/`,{replace:!0})},[t,n,e,r]),(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}async function X9(e){try{let t=e.replace(/-/g,`+`).replace(/_/g,`/`);for(;t.length%4!=0;)t+=`=`;let n=atob(t),r=Uint8Array.from(n,e=>e.charCodeAt(0));try{let e=new DecompressionStream(`gzip`),t=e.writable.getWriter(),n=e.readable.getReader();t.write(r),t.close();let i=[];for(;;){let{done:e,value:t}=await n.read();if(e)break;i.push(t)}let a=i.reduce((e,t)=>e+t.length,0),o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.length;return new TextDecoder().decode(o)}catch{return new TextDecoder().decode(r)}}catch{return null}}function Z9(){let e=yn(),t=ht(),{date:n}=In(),[r]=ln(`zip`),[i,a]=(0,U.useState)({state:`loading`});return(0,U.useEffect)(()=>{if(!(t.pathname===`/load/journal`||t.pathname.startsWith(`/load/journal/`)))return;if(!r){e($.journal,{replace:!0});return}let i=!1,o=async()=>{try{a({state:`loading`});let t;try{t=await X9(r)}catch(e){console.error(`Failed to decode zip:`,e),a({state:`error`,error:`Failed to decode the journal entry`,onRetry:()=>{o()}}),Q({title:`Error`,description:`Failed to decode the journal entry. Please check the link.`,variant:`destructive`});return}if(i)return;let c;if(n){let t=WP(n);if(!t){a({state:`error`,error:`Invalid date format`}),Q({title:`Error`,description:`Invalid date format. Expected YYYY-MM-DD.`,variant:`destructive`}),e($.journal,{replace:!0});return}c=t.dateKey}else c=HP();if(i)return;if(UP(c)){a({state:`pending-confirmation`,content:t,dateKey:c,onConfirmBackdate:async()=>{i||await s(t,c)}});return}await s(t,c)}catch(e){console.error(`Unexpected error in journal zip processor:`,e),i||(a({state:`error`,error:`An unexpected error occurred`,onRetry:()=>{o()}}),Q({title:`Error`,description:`An unexpected error occurred.`,variant:`destructive`}))}},s=async(t,n)=>{if(!i)try{a({state:`creating`});let r=await JP.create({journalDate:n,title:n,rawContent:t});i||(a({state:`success`,content:t,dateKey:n}),e(YN(r.id),{replace:!0}))}catch(e){console.error(`Failed to create journal entry:`,e),i||(a({state:`error`,error:`Failed to create journal entry`,onRetry:()=>{s(t,n)}}),Q({title:`Error`,description:`Failed to create journal entry.`,variant:`destructive`}))}};return o(),()=>{i=!0}},[r,n,e]),i}var Mne=({selectedDate:e,onImportToday:t,onDateSelect:n,entryDates:r,isLoading:i=!1,className:a})=>{let[o,s]=(0,U.useState)(!1),[c,l]=(0,U.useState)(!1),{triggerRef:u,align:d,recompute:f}=P0(`end`),p=async()=>{l(!0);try{await t()}finally{l(!1)}},m=async e=>{l(!0),s(!1);try{await n(e)}finally{l(!1)}},h=e=>{e&&f(),s(e)},g=e?Gy(e):`Date`,_=i||c;return(0,W.jsxs)(`div`,{className:G(`inline-flex items-stretch rounded-lg overflow-hidden border border-border/70`,`bg-muted text-muted-foreground shadow-sm hover:shadow-md transition-shadow font-medium`,`text-xs`,a),children:[(0,W.jsxs)(`button`,{type:`button`,title:`Import to today's journal`,onClick:p,disabled:_,className:G(`flex items-center gap-2 px-3 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,_&&`opacity-60 cursor-not-allowed`),children:[c?(0,W.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}):(0,W.jsx)(Un,{className:`h-4 w-4 shrink-0`}),(0,W.jsx)(`span`,{children:`Import Today`})]}),(0,W.jsx)(`div`,{className:`w-px bg-border/60 self-stretch`}),(0,W.jsxs)(CV,{open:o,onOpenChange:h,children:[(0,W.jsx)(wV,{asChild:!0,children:(0,W.jsxs)(`button`,{ref:e=>{u.current=e},type:`button`,title:`Select a date to plan for the future`,className:G(`flex items-center gap-1.5 px-2.5 py-2 transition-colors`,`hover:bg-accent hover:text-accent-foreground`,e&&`text-primary`,_&&`opacity-60 cursor-not-allowed`),disabled:_,children:[(0,W.jsx)(Wt,{className:`h-4 w-4 shrink-0`}),e&&(0,W.jsx)(`span`,{className:`leading-none text-xs`,children:g})]})}),(0,W.jsx)(TV,{align:d,className:`p-0 w-auto`,children:(0,W.jsx)(t0,{selectedDate:e||null,onDateSelect:m,entryDates:r})})]})]})},Nne=({dateKey:e,onConfirm:t,onCancel:n,isLoading:r=!1})=>{let[i,a]=U.useState(!1),o=Wy(new Date(`${e}T00:00:00`));return(0,W.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-50 flex items-center justify-center`,onKeyDown:e=>{e.key===`Escape`&&n()},onClick:e=>{e.target===e.currentTarget&&n()},children:[(0,W.jsx)(`div`,{className:`absolute inset-0 bg-black/50 animate-in fade-in`}),(0,W.jsx)(`div`,{className:`relative z-10 w-full max-w-sm mx-auto px-4 animate-in zoom-in-95 fade-in`,children:(0,W.jsxs)(`div`,{className:`bg-background rounded-lg border border-border shadow-lg`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between px-6 py-4 border-b border-border`,children:[(0,W.jsx)(`h2`,{className:`text-base font-semibold`,children:`Backdate Journal Entry`}),(0,W.jsx)(`button`,{onClick:n,className:`p-1 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors`,"aria-label":`Close modal`,children:(0,W.jsx)(ge,{className:`h-4 w-4`})})]}),(0,W.jsxs)(`div`,{className:`px-6 py-4 space-y-4`,children:[(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The date you selected is in the past.`}),(0,W.jsxs)(`p`,{className:`text-sm`,children:[(0,W.jsx)(`span`,{className:`text-muted-foreground`,children:`Import to: `}),(0,W.jsx)(`span`,{className:`font-medium text-foreground`,children:o})]}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This will create a journal entry for the selected date. Are you sure you want to proceed?`})]}),(0,W.jsxs)(`div`,{className:`px-6 py-4 border-t border-border flex gap-2 justify-end`,children:[(0,W.jsx)(K,{variant:`outline`,onClick:n,disabled:r||i,children:`Cancel`}),(0,W.jsx)(K,{onClick:async()=>{a(!0);try{await t()}finally{a(!1)}},disabled:r||i,className:G(r||i?`opacity-70`:``),children:i?(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(`span`,{className:`inline-block animate-spin mr-2`,children:`⏳`}),`Importing...`]}):`Confirm & Import`})]})]})})]})},Pne={h1:({children:e})=>(0,W.jsx)(`h1`,{className:`text-3xl font-bold mt-8 mb-4 first:mt-0 text-foreground`,children:e}),h2:({children:e})=>(0,W.jsx)(`h2`,{className:`text-2xl font-bold mt-6 mb-3 text-foreground`,children:e}),h3:({children:e})=>(0,W.jsx)(`h3`,{className:`text-xl font-semibold mt-5 mb-2 text-foreground`,children:e}),h4:({children:e})=>(0,W.jsx)(`h4`,{className:`text-lg font-semibold mt-4 mb-2 text-foreground`,children:e}),h5:({children:e})=>(0,W.jsx)(`h5`,{className:`text-base font-semibold mt-3 mb-1 text-foreground`,children:e}),h6:({children:e})=>(0,W.jsx)(`h6`,{className:`text-sm font-semibold mt-2 mb-1 text-muted-foreground`,children:e}),p:({children:e})=>(0,W.jsx)(`p`,{className:`text-sm leading-relaxed mb-4 text-muted-foreground`,children:e}),strong:({children:e})=>(0,W.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e}),em:({children:e})=>(0,W.jsx)(`em`,{className:`italic text-muted-foreground`,children:e}),ul:({children:e})=>(0,W.jsx)(`ul`,{className:`list-disc list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),ol:({children:e})=>(0,W.jsx)(`ol`,{className:`list-decimal list-inside space-y-1 mb-4 text-sm text-muted-foreground`,children:e}),li:({children:e})=>(0,W.jsx)(`li`,{className:`ml-2`,children:e}),code:({children:e,className:t})=>t?null:(0,W.jsx)(`code`,{className:`px-1.5 py-0.5 rounded bg-muted text-primary font-mono text-xs`,children:e}),pre:({children:e})=>(0,W.jsx)(`pre`,{className:`bg-muted rounded-lg p-4 overflow-x-auto mb-4 text-xs font-mono text-muted-foreground border border-border`,children:e}),blockquote:({children:e})=>(0,W.jsx)(`blockquote`,{className:`border-l-4 border-primary/30 pl-4 py-2 mb-4 italic text-muted-foreground text-sm`,children:e}),a:({href:e,children:t})=>(0,W.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary hover:underline font-medium`,children:t}),table:({children:e})=>(0,W.jsx)(`div`,{className:`my-4 overflow-x-auto rounded border border-border`,children:(0,W.jsx)(`table`,{className:`w-full text-xs`,children:e})}),thead:({children:e})=>(0,W.jsx)(`thead`,{className:`bg-muted/50`,children:e}),tbody:({children:e})=>(0,W.jsx)(`tbody`,{className:`divide-y divide-border/50`,children:e}),tr:({children:e})=>(0,W.jsx)(`tr`,{className:`hover:bg-muted/20 transition-colors`,children:e}),th:({children:e})=>(0,W.jsx)(`th`,{className:`px-3 py-2 text-left font-semibold text-foreground text-xs`,children:e}),td:({children:e})=>(0,W.jsx)(`td`,{className:`px-3 py-2 text-muted-foreground`,children:e}),hr:()=>(0,W.jsx)(`hr`,{className:`my-6 border-border/50`})};function Q9(){let e=yn(),t=Z9(),[n,r]=(0,U.useState)(!1),[i,a]=(0,U.useState)(null),{state:o,content:s,dateKey:c,error:l,onConfirmBackdate:u,onRetry:d}=t;return(0,W.jsxs)(`div`,{className:`flex flex-col h-screen bg-background`,children:[(0,W.jsxs)(`div`,{className:`border-b border-border/50 bg-muted/30 px-6 py-4 flex items-center justify-between gap-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,W.jsx)(`button`,{onClick:()=>{e(-1)},className:`p-1.5 rounded hover:bg-muted transition-colors text-muted-foreground hover:text-foreground`,title:`Go back`,children:(0,W.jsx)(h,{className:`h-5 w-5`})}),(0,W.jsx)(`h1`,{className:`text-lg font-semibold text-foreground`,children:`Import Journal Entry`})]}),o===`loading`?(0,W.jsxs)(`div`,{className:`text-xs text-muted-foreground flex items-center gap-2`,children:[(0,W.jsx)(`span`,{className:`inline-block animate-spin`,children:`⏳`}),`Preparing preview...`]}):o===`error`?(0,W.jsx)(K,{variant:`outline`,size:`sm`,onClick:d,children:`Retry`}):o===`pending-confirmation`||o===`creating`?null:(0,W.jsx)(Mne,{selectedDate:i,onImportToday:async()=>{u&&await u()},onDateSelect:async e=>{a(e);let t=new Date;t.setHours(0,0,0,0);let n=new Date(e);n.setHours(0,0,0,0),n<t?r(!0):u&&await u()},isLoading:o===`creating`})]}),(0,W.jsxs)(`div`,{className:`flex-1 overflow-auto px-6 py-6`,children:[o===`loading`&&(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,W.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading preview...`})]}),o===`error`&&(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,W.jsx)(`div`,{className:`bg-destructive/10 border border-destructive/50 rounded-lg p-4 max-w-md`,children:(0,W.jsxs)(`div`,{className:`flex gap-3 items-start`,children:[(0,W.jsx)(Nn,{className:`h-5 w-5 text-destructive mt-0.5 shrink-0`}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h3`,{className:`font-semibold text-foreground`,children:`Error Loading Preview`}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:l||`Failed to decode the zip content`})]})]})}),(0,W.jsx)(K,{onClick:d,variant:`outline`,children:`Try Again`})]}),o===`pending-confirmation`&&(0,W.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,W.jsxs)(`div`,{className:`text-center`,children:[(0,W.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`Backdate Confirmation Required`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm mb-4`,children:`This date is in the past. Please confirm to proceed.`})]})}),o===`creating`&&(0,W.jsxs)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:[(0,W.jsx)(`div`,{className:`animate-spin`,children:`⏳`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Creating journal entry...`})]}),o===`success`&&(0,W.jsx)(`div`,{className:`flex flex-col items-center justify-center min-h-96 gap-4`,children:(0,W.jsxs)(`div`,{className:`text-center`,children:[(0,W.jsx)(`h2`,{className:`text-lg font-semibold text-foreground mb-2`,children:`✓ Entry Created`}),(0,W.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Redirecting...`})]})}),o===`loading`||o===`error`||o===`pending-confirmation`||o===`creating`||o===`success`?null:s?(0,W.jsx)(`article`,{className:`prose prose-sm max-w-2xl mx-auto`,children:(0,W.jsx)(pn,{remarkPlugins:[Bn],components:Pne,children:s})}):null]}),n&&c&&(0,W.jsx)(Nne,{dateKey:c,onConfirm:async()=>{u&&(r(!1),await u())},onCancel:()=>r(!1),isLoading:o===`creating`})]})}function Fne(){let e=ht(),t=yn();return(0,U.useEffect)(()=>{let n=new URLSearchParams(e.search).get(`source`);t(n?`${$.notebooks}?feed=${encodeURIComponent(n)}`:$.notebooks,{replace:!0})},[e.search,t]),(0,W.jsx)(`div`,{className:`p-8 text-center text-xs text-muted-foreground`,"data-testid":`feed-subscription-intake`,children:`Redirecting to Library…`})}async function Ine(e,t,n){let r=await Z.getNote(e);if(!r)return;let i=`:session{result:${n}}`;if(r.rawContent.includes(i))return;let a=Object.values(r.blocks??{}).find(e=>e.id===t);if(!a||a.to==null)return;let o=`${r.rawContent.slice(0,a.to)}\n\n\`\`\`query:table\n${i}\n\`\`\`${r.rawContent.slice(a.to)}`;await new _A().updateRecord(r.id,{rawContent:o,expectedSourceRevision:r.sourceRevision})}function Lne(){let{runtimeId:e}=In(),t=yn(),n=(0,U.useRef)(e?o0.get(e):void 0),r=(0,U.useRef)(null),i=(0,U.useCallback)(async()=>{let t=n.current;if(!t||!e)throw Error(`The pending workout is unavailable.`);return t.captured?(r.current=t.captured,t.captured.block):(r.current||=t.snapshot?await QR(t.snapshot,t.block,e,t.origin):await $R(t.noteId,t.block,e,t.origin),r.current.block)},[e]);(0,U.useEffect)(()=>{e&&o0.delete(e)},[e]);let a=n.current,o=(0,U.useRef)(!1),s=(0,U.useCallback)((t,n)=>!n||!e||!a?Promise.reject(Error(`Run cannot be saved — its session data or runtime id is missing.`)):(o.current=n.completed,AK.record({runBlock:a.block,blockId:a.block.id,noteId:a.noteId,resultId:e,data:n,createdAt:n.endTime||Date.now(),...a.origin?{origin:a.origin}:{}}).then(async()=>{if(n.completed)try{await Ine(a.noteId,a.block.id,e)}catch{}})),[e,a]),c=(0,U.useCallback)(()=>{if(!a){t(`/`);return}if(o.current){t(eP(e),{replace:!0});return}if(a.returnTo){t(a.returnTo,{replace:!0});return}t(h0(Nz(a.noteId)),{replace:!0})},[e,a,t]);if(!a)return(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-red-400`,children:`Runtime not found. Please start the workout from the editor.`});let l=r.current?.note.rawContent??a.captured?.note.rawContent??a.snapshot?.rawContent;return(0,W.jsx)(nQ,{block:a.block,noteContent:l,prepareRun:i,onClose:c,onCompleteWorkout:s,resultId:e,autoStart:!0})}var $9=null;async function Rne(e){(!$9||$9.attempt!==e)&&($9={attempt:e,promise:qq(B0.content)});try{return await $9.promise}finally{$9?.attempt===e&&($9=null)}}function zne(){let e=yn(),[t,n]=(0,U.useState)(!1),[r,i]=(0,U.useState)(0);return(0,U.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await Rne(r);t||e(KN(n),{replace:!0})}catch{t||n(!0)}})(),()=>{t=!0}},[e,r]),t?(0,W.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center gap-3 text-zinc-300 px-4 text-center`,children:[(0,W.jsx)(`p`,{role:`alert`,children:`Unable to create a new playground note.`}),(0,W.jsx)(`button`,{type:`button`,className:`rounded border border-zinc-600 px-3 py-1 text-sm hover:bg-zinc-800`,onClick:()=>{n(!1),i(e=>e+1)},children:`Try again`})]}):(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`})}function Bne(){let e=yn(),t=ht(),[n]=ln(`zip`),[r]=ln(`z`),[i]=ln(`by`),[a]=ln(`src`);(0,U.useEffect)(()=>{if(t.pathname!==`/load`&&!(t.pathname===`/`&&r))return;if(r){let t=!1;return(async()=>{try{let e=await X9(r);if(e===null)throw Error(`Invalid workout link`);if(t)return;let n=t2(e,i??void 0);if(await Jq(n,{reuseKey:`home`,title:`Home playground`}),t)return;i2({content:n,by:i??void 0})}catch(e){console.error(`Failed to decode zip:`,e),t||Q({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`})}t||e(`/`,{replace:!0})})(),()=>{t=!0}}if(!n)return;let o=!1,s=a&&a.startsWith(`/`)?a:void 0;return(async()=>{try{let t=await X9(n);if(t===null)throw Error(`Invalid workout link`);if(o)return;let r=s?await qq(t,{sourcePath:s}):await qq(t);o||e(KN(r),{replace:!0})}catch(t){console.error(`Failed to decode zip:`,t),o||(Q({title:`Could not import workout`,description:`The link was invalid or the workout could not be saved.`,variant:`destructive`}),e($.home,{replace:!0}))}})(),()=>{o=!0}},[n,r,i,a,e,t.pathname])}function Vne(){let{pathname:e,hash:t}=ht(),{scrollToSection:n}=mN();return(0,U.useEffect)(()=>{if(t){let e=t.slice(1);n(e);let r=setTimeout(()=>{n(e)},50);return()=>clearTimeout(r)}window.scrollTo(0,0)},[e,t]),null}function Hne(){return Bne(),Z9(),(0,U.useEffect)(()=>{$k.current().catch(console.error),Sk(),u3(),rM().catch(()=>{})},[]),null}function Une({settling:e}){let t=c3();if(e){let e=x4(t);return(0,W.jsxs)(`div`,{role:`status`,className:`flex min-h-dvh flex-col items-center justify-center gap-2 text-muted-foreground`,children:[(0,W.jsx)(`span`,{children:t?b4(t):`Loading library…`}),e&&(0,W.jsx)(`span`,{className:`text-xs`,"data-testid":`boot-progress-detail`,children:e})]})}return(0,W.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:`The library's routed content failed to load.`}),(0,W.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:`The feed corpus has not supplied this page. Re-running the feed import usually restores it.`}),(0,W.jsx)(K,{variant:`outline`,size:`sm`,"data-testid":`root-refeed`,onClick:()=>{wM().then(()=>_k())},children:`Re-import library`})]})}function Wne(){let e=(0,U.useRef)(()=>{}),t=vR(),n=s3(),r=(0,U.useMemo)(()=>VL(()=>e.current(),t),[t]);return(0,W.jsx)(Ti,{defaultTheme:`system`,storageKey:`wod-wiki-playground-theme`,children:(0,W.jsx)(Ry,{children:(0,W.jsx)(zM,{children:(0,W.jsx)(HM,{children:(0,W.jsx)(xj,{children:(0,W.jsx)(Mt,{children:(0,W.jsxs)(i,{children:[(0,W.jsx)(Hne,{}),(0,W.jsx)(lN,{}),(0,W.jsxs)(gN,{tree:r,children:[(0,W.jsx)(Vne,{}),(0,W.jsxs)(qt,{children:[(0,W.jsx)(jn,{path:$.home,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:`*`,element:t.length===0?(0,W.jsx)(Une,{settling:n===`preparing`||uM()&&n!==`error`}):(0,W.jsx)(Ete,{})}),(0,W.jsx)(jn,{path:`/proto/calc-authoring`,element:(0,W.jsx)(Rte,{})}),(0,W.jsx)(jn,{path:`/proto/query-block-composer`,element:(0,W.jsx)(Jte,{})}),(0,W.jsx)(jn,{path:`/settings`,element:(0,W.jsx)(mn,{to:`/settings/appearance`,replace:!0})}),(0,W.jsx)(jn,{path:`/settings/appearance`,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.settingsProfile,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.settingsData,element:(0,W.jsx)(mn,{to:$.settingsStorage,replace:!0})}),(0,W.jsx)(jn,{path:$.settingsDatabase,element:(0,W.jsx)(mn,{to:$.settingsStorage,replace:!0})}),(0,W.jsx)(jn,{path:$.settingsStorage,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.settingsSync,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:`/settings/system`,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.settingsQueries,element:(0,W.jsx)(mn,{to:$.journal,replace:!0})}),(0,W.jsx)(jn,{path:$.settingsTags,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.settingsSoundProfiles,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:`/settings/library/calcs`,element:(0,W.jsx)(`div`,{className:`p-6`,children:(0,W.jsx)(Ane,{})})}),(0,W.jsx)(jn,{path:`/legacy`,element:(0,W.jsx)(fte,{})}),(0,W.jsx)(jn,{path:`/syntax`,element:(0,W.jsx)(Tte,{})}),(0,W.jsx)(jn,{path:$.plan,element:(0,W.jsx)(J7,{})}),(0,W.jsx)(jn,{path:$.feeds,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.feed,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.notebooks,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.notebook,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.notebookTarget,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.notebookItem,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.subscribe,element:(0,W.jsx)(Fne,{})}),(0,W.jsx)(jn,{path:$.pages,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.page,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.load,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(jne,{})})}),(0,W.jsx)(jn,{path:$.loadJournal,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(Q9,{})})}),(0,W.jsx)(jn,{path:$.loadJournalDate,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(Q9,{})})}),(0,W.jsx)(jn,{path:$.playgroundRoot,element:(0,W.jsx)(zne,{})}),(0,W.jsx)(jn,{path:$.playground,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.playgrounds,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.notes,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.note,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.journal,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.day,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.run,element:(0,W.jsx)(U.Suspense,{fallback:(0,W.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-zinc-400`,children:`Loading…`}),children:(0,W.jsx)(Lne,{})})}),(0,W.jsx)(jn,{path:$.tracker,element:(0,W.jsx)(K7,{})}),(0,W.jsx)(jn,{path:`/results/segments`,element:(0,W.jsx)(G7,{})}),(0,W.jsx)(jn,{path:$.sessionDetail,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.sessions,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.sessionDate,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:`/review/:runtimeId`,element:(0,W.jsx)(q7,{})}),(0,W.jsx)(jn,{path:`/note/:noteId/review`,element:(0,W.jsx)(q7,{})}),(0,W.jsx)(jn,{path:`/note/:noteId/review/:sectionId`,element:(0,W.jsx)(q7,{})}),(0,W.jsx)(jn,{path:`/note/:noteId/review/:sectionId/:resultId`,element:(0,W.jsx)(q7,{})}),(0,W.jsx)(jn,{path:$.efforts,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.effort,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.equipment,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.equipmentSlug,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.tags,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.tagCategory,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.tag,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.dashboards,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),(0,W.jsx)(jn,{path:$.dashboardView,element:(0,W.jsx)(U7,{searchHandlerRef:e})}),t.map(({route:t})=>(0,W.jsx)(jn,{path:t,element:(0,W.jsx)(U7,{searchHandlerRef:e})},t))]}),(0,W.jsx)(ate,{})]})]})})})})})})})}function Gne({error:e,onRetry:t}){let n=e instanceof Error?e.message:String(e),r=Uk();return(0,W.jsxs)(`div`,{role:`alert`,className:`flex min-h-dvh flex-col items-center justify-center gap-4 p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:`The local database could not be opened.`}),(0,W.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground font-mono break-all`,"data-testid":`boot-recovery-error`,children:n}),(0,W.jsxs)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:[`Your stored data has not been cleared. Retry after resolving the error above.`,r.state!==`indexed-db`&&` Turn off Turso Sync to skip backup comparison. Settings → Storage has the full controls once the app loads.`]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,W.jsx)(`button`,{type:`button`,onClick:t,"data-testid":`boot-recovery-retry`,className:`rounded-md border border-border bg-card px-3 py-1.5 text-xs font-medium hover:bg-accent`,children:`Retry`}),r.state!==`indexed-db`&&(0,W.jsx)(`button`,{type:`button`,onClick:()=>{Yk(),window.location.reload()},"data-testid":`boot-recovery-local`,className:`rounded-md border border-border bg-card px-3 py-1.5 text-xs font-medium hover:bg-accent`,children:`Turn off Turso Sync`})]}),r.state!==`indexed-db`&&(0,W.jsxs)(`details`,{className:`w-full max-w-md rounded-xl border border-border bg-card p-4 text-left`,children:[(0,W.jsx)(`summary`,{className:`cursor-pointer text-xs font-medium`,children:`Fix Turso credentials`}),(0,W.jsx)(`div`,{className:`pt-3`,children:(0,W.jsx)(C7,{saved:r.state===`turso`?{url:r.url,authToken:r.authToken}:void 0})})]})]})}function Kne(){let e=(0,U.useSyncExternalStore)(sS,oS),t=e.phase===`updating`;return(0,W.jsxs)(`div`,{role:`status`,"aria-live":`polite`,className:`flex min-h-dvh flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-sm font-semibold`,children:t?`Updating local database…`:`Checking for storage updates…`}),t&&e.fromVersion!==null&&(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Schema v`,e.fromVersion,` → v`,e.toVersion]}),e.message&&(0,W.jsx)(`p`,{className:`max-w-md text-xs text-muted-foreground`,children:e.message})]})}var qne=(0,Ci.createRoot)(document.getElementById(`root`));function Jne(){let[e,t]=(0,U.useState)(!1),[n,r]=(0,U.useState)(null),[i,a]=(0,U.useState)(0),o=(0,U.useSyncExternalStore)(sS,oS);return(0,U.useEffect)(()=>{let e=!1,n;return aA().then(()=>fF?_F():void 0).then(()=>dj.ensureNotebooks().catch(e=>qR(`NotebookService`,`ensureNotebooks failed`,e))).then(()=>{e||(n=lA(),t(!0))}).catch(t=>{e||r(t)}),()=>{e=!0,n?.()}},[i]),n?(0,W.jsx)(Gne,{error:n,onRetry:()=>{r(null),a(e=>e+1)}}):o.phase===`checking`||o.phase===`updating`?(0,W.jsx)(Kne,{}):e?(0,W.jsx)(Wne,{}):(0,W.jsx)(`div`,{role:`status`,className:`flex min-h-dvh items-center justify-center text-muted-foreground`,children:`Opening local library…`})}qne.render((0,W.jsx)(U.StrictMode,{children:(0,W.jsx)(Jne,{})}));export{ZH as t};
494
- //# sourceMappingURL=main-CpZctqfe.js.map
494
+ //# sourceMappingURL=main-0VA1ZMB5.js.map