@bitcobblers/wod-wiki-tools 0.45.2166 → 0.46.2168

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 (626) hide show
  1. package/dist/bin/wod.cjs +145 -117
  2. package/dist/bin/wod.cjs.map +1 -1
  3. package/dist/bin/wod.mjs +5 -5
  4. package/dist/{chunk-PF5BTGWZ.mjs → chunk-76AHBG3R.mjs} +14 -14
  5. package/dist/chunk-76AHBG3R.mjs.map +1 -0
  6. package/dist/{chunk-O5ZCOUQE.mjs → chunk-IIUCTIX5.mjs} +3 -3
  7. package/dist/chunk-IIUCTIX5.mjs.map +1 -0
  8. package/dist/{chunk-EAFF2GVB.mjs → chunk-MKGVKC2X.mjs} +77 -79
  9. package/dist/chunk-MKGVKC2X.mjs.map +1 -0
  10. package/dist/chunk-QUUX6NX2.mjs +28 -0
  11. package/dist/{chunk-6L5ZDZJ7.mjs.map → chunk-QUUX6NX2.mjs.map} +1 -1
  12. package/dist/{chunk-FSOBPDUC.mjs → chunk-Z2IQPTDI.mjs} +3 -3
  13. package/dist/{chunk-FSOBPDUC.mjs.map → chunk-Z2IQPTDI.mjs.map} +1 -1
  14. package/dist/{chunk-F7IXIJ4I.mjs → chunk-ZUZMRH3G.mjs} +3 -3
  15. package/dist/{chunk-F7IXIJ4I.mjs.map → chunk-ZUZMRH3G.mjs.map} +1 -1
  16. package/dist/compiler-Z6VNF53G.mjs +9 -0
  17. package/dist/{compiler-ZMG22VH4.mjs.map → compiler-Z6VNF53G.mjs.map} +1 -1
  18. package/dist/index.cjs +145 -117
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.mjs +6 -6
  21. package/dist/{scaffoldFeed-UXH3L5HM.mjs → scaffoldFeed-ALXZOKRV.mjs} +4 -4
  22. package/dist/{scaffoldFeed-UXH3L5HM.mjs.map → scaffoldFeed-ALXZOKRV.mjs.map} +1 -1
  23. package/dist/server/app.mjs +1 -1
  24. package/dist/server-QK2CXCDJ.mjs +11 -0
  25. package/dist/{server-5XDT7ITA.mjs.map → server-QK2CXCDJ.mjs.map} +1 -1
  26. package/dist/{skills-CZDOAQUB.mjs → skills-5F737S2K.mjs} +3 -3
  27. package/dist/{skills-CZDOAQUB.mjs.map → skills-5F737S2K.mjs.map} +1 -1
  28. package/dist/web/playground/assets/{feedSync.worker-CEbxagtY.js → feedSync.worker-BKsDG4P0.js} +4 -4
  29. package/dist/web/playground/assets/main-Cb5hwnvu.js +494 -0
  30. package/dist/web/playground/assets/main-Cye5g1Tm.css +2 -0
  31. package/dist/web/playground/assets/{statementBuilderFlow-DHSfYrHi.js → statementBuilderFlow-y8YIyGuW.js} +2 -2
  32. package/dist/web/playground/assets/{vendor-DKhA8bPd.js → vendor-D0x8W9No.js} +19 -19
  33. package/dist/web/{server/assets/vendor-codemirror-CnY0iCTs.js → playground/assets/vendor-codemirror-Bw_t2lTd.js} +7 -7
  34. package/dist/web/playground/index.html +4 -4
  35. package/dist/web/{server/seed/core/chunks/canvas.9ad327d4.json → playground/seed/core/chunks/canvas.dc1d093c.json} +1 -1
  36. package/dist/web/playground/seed/core/chunks/{dashboards.f4196444.json → dashboards.e349f3be.json} +1 -1
  37. package/dist/web/playground/seed/core/chunks/efforts.84f30fa3.json +1 -0
  38. package/dist/web/{server/seed/core/chunks/equipment.e7531ab5.json → playground/seed/core/chunks/equipment.f07ad76e.json} +1 -1
  39. package/dist/web/playground/seed/core/indexes/notebooks/canvas.json +178 -173
  40. package/dist/web/playground/seed/core/indexes/notebooks/dashboards.json +18 -13
  41. package/dist/web/playground/seed/core/indexes/notebooks/efforts.json +328 -323
  42. package/dist/web/playground/seed/core/indexes/notebooks/equipment.json +52 -47
  43. package/dist/web/playground/seed/core/manifest.json +40 -2512
  44. package/dist/web/playground/seed/core/markdown/canvas/ai-first/README.json +1 -1
  45. package/dist/web/playground/seed/core/markdown/canvas/guide/README.json +4 -4
  46. package/dist/web/playground/seed/core/markdown/canvas/guide/clock.json +1 -1
  47. package/dist/web/playground/seed/core/markdown/canvas/guide/dashboards.json +2 -2
  48. package/dist/web/playground/seed/core/markdown/canvas/guide/metrics.json +12 -12
  49. package/dist/web/playground/seed/core/markdown/canvas/guide/protocols.json +20 -20
  50. package/dist/web/playground/seed/core/markdown/canvas/guide/sessions.json +30 -30
  51. package/dist/web/playground/seed/core/markdown/canvas/guide/start.json +10 -10
  52. package/dist/web/playground/seed/core/markdown/canvas/guide/structure.json +24 -24
  53. package/dist/web/playground/seed/core/markdown/canvas/guide/wql.json +5 -5
  54. package/dist/web/playground/seed/core/markdown/canvas/home/sample-script.json +4 -4
  55. package/dist/web/playground/seed/core/markdown/canvas/home/welcome-1.json +2 -2
  56. package/dist/web/playground/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
  57. package/dist/web/playground/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
  58. package/dist/web/playground/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
  59. package/dist/web/playground/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
  60. package/dist/web/playground/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
  61. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
  62. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-full-session.json +9 -9
  63. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
  64. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
  65. package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-swimming.json +3 -3
  66. package/dist/web/playground/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
  67. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +7 -7
  68. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
  69. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
  70. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
  71. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-3.json +2 -2
  72. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
  73. package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
  74. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
  75. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
  76. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
  77. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
  78. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
  79. package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
  80. package/dist/web/playground/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
  81. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-1.json +4 -4
  82. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-2.json +5 -5
  83. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-3.json +10 -10
  84. package/dist/web/playground/seed/core/markdown/canvas/syntax/document-4.json +4 -4
  85. package/dist/web/playground/seed/core/markdown/canvas/syntax/effort-notes.json +4 -4
  86. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
  87. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
  88. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
  89. package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
  90. package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
  91. package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
  92. package/dist/web/playground/seed/core/markdown/canvas/syntax/measurements.json +4 -4
  93. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
  94. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
  95. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
  96. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-4.json +5 -5
  97. package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
  98. package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-sections.json +8 -8
  99. package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
  100. package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
  101. package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
  102. package/dist/web/playground/seed/core/markdown/canvas/syntax/named-groups.json +5 -5
  103. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
  104. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
  105. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
  106. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
  107. package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
  108. package/dist/web/playground/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
  109. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
  110. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
  111. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
  112. package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
  113. package/dist/web/playground/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
  114. package/dist/web/playground/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
  115. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
  116. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
  117. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-3.json +3 -3
  118. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
  119. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
  120. package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
  121. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
  122. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
  123. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
  124. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
  125. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
  126. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
  127. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
  128. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
  129. package/dist/web/playground/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
  130. package/dist/web/playground/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
  131. package/dist/web/playground/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
  132. package/dist/web/playground/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
  133. package/dist/web/playground/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
  134. package/dist/web/playground/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
  135. package/dist/web/playground/seed/core/markdown/dashboards/training-block-review.json +11 -11
  136. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/air-squat.json +2 -2
  137. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/box-jump.json +2 -2
  138. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/broad-jump.json +2 -2
  139. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +2 -2
  140. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +2 -2
  141. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee.json +2 -2
  142. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +2 -2
  143. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +2 -2
  144. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ground-kong.json +2 -2
  145. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/jumping-jack.json +2 -2
  146. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/kong-walk.json +2 -2
  147. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/lunge.json +2 -2
  148. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/overhead-squat.json +2 -2
  149. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-roll.json +2 -2
  150. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-squat.json +2 -2
  151. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/pistol-squat.json +2 -2
  152. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/plank.json +2 -2
  153. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-burpee.json +2 -2
  154. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-jump.json +2 -2
  155. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +2 -2
  156. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/russian-twist.json +2 -2
  157. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/sit-up.json +2 -2
  158. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-clean.json +2 -2
  159. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-hold.json +2 -2
  160. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-snatch.json +2 -2
  161. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/tuck-jump.json +2 -2
  162. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-ball.json +2 -2
  163. package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-burpee.json +2 -2
  164. package/dist/web/playground/seed/core/markdown/efforts/cycling/assault-bike.json +2 -2
  165. package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-moderate.json +2 -2
  166. package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-vigorous.json +2 -2
  167. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +2 -2
  168. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +2 -2
  169. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +2 -2
  170. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/dip.json +2 -2
  171. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/double-under.json +2 -2
  172. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-hold.json +2 -2
  173. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +2 -2
  174. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-walk.json +2 -2
  175. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jump-rope.json +2 -2
  176. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +2 -2
  177. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +2 -2
  178. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +2 -2
  179. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/muscle-up.json +2 -2
  180. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/pull-up.json +2 -2
  181. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/push-up.json +2 -2
  182. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +2 -2
  183. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/rope-climb.json +2 -2
  184. package/dist/web/playground/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +2 -2
  185. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +2 -2
  186. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +2 -2
  187. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +2 -2
  188. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +2 -2
  189. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +2 -2
  190. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +2 -2
  191. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +2 -2
  192. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +2 -2
  193. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +2 -2
  194. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +2 -2
  195. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +2 -2
  196. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +2 -2
  197. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +2 -2
  198. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +2 -2
  199. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +2 -2
  200. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +2 -2
  201. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +2 -2
  202. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +2 -2
  203. package/dist/web/playground/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +2 -2
  204. package/dist/web/playground/seed/core/markdown/efforts/recovery/rest.json +2 -2
  205. package/dist/web/playground/seed/core/markdown/efforts/recovery/stretching.json +2 -2
  206. package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing-sprint.json +2 -2
  207. package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing.json +2 -2
  208. package/dist/web/playground/seed/core/markdown/efforts/rowing/ski-erg.json +2 -2
  209. package/dist/web/playground/seed/core/markdown/efforts/running/backward-running.json +2 -2
  210. package/dist/web/playground/seed/core/markdown/efforts/running/running-6-mph.json +2 -2
  211. package/dist/web/playground/seed/core/markdown/efforts/running/running-8-mph.json +2 -2
  212. package/dist/web/playground/seed/core/markdown/efforts/running/running-sprint.json +2 -2
  213. package/dist/web/playground/seed/core/markdown/efforts/snatch.json +7 -7
  214. package/dist/web/playground/seed/core/markdown/efforts/strength/back-squat.json +2 -2
  215. package/dist/web/playground/seed/core/markdown/efforts/strength/bench-press.json +2 -2
  216. package/dist/web/playground/seed/core/markdown/efforts/strength/box-step-up.json +2 -2
  217. package/dist/web/playground/seed/core/markdown/efforts/strength/carioca.json +2 -2
  218. package/dist/web/playground/seed/core/markdown/efforts/strength/clean-and-jerk.json +2 -2
  219. package/dist/web/playground/seed/core/markdown/efforts/strength/cluster.json +2 -2
  220. package/dist/web/playground/seed/core/markdown/efforts/strength/dead-hang.json +2 -2
  221. package/dist/web/playground/seed/core/markdown/efforts/strength/deadlift.json +2 -2
  222. package/dist/web/playground/seed/core/markdown/efforts/strength/devils-press.json +2 -2
  223. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +2 -2
  224. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-clean.json +2 -2
  225. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-fly.json +2 -2
  226. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-row.json +2 -2
  227. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-snatch.json +2 -2
  228. package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-thruster.json +2 -2
  229. package/dist/web/playground/seed/core/markdown/efforts/strength/elbows-to-knees.json +2 -2
  230. package/dist/web/playground/seed/core/markdown/efforts/strength/farmer-carry.json +2 -2
  231. package/dist/web/playground/seed/core/markdown/efforts/strength/frog-stand.json +2 -2
  232. package/dist/web/playground/seed/core/markdown/efforts/strength/front-squat.json +2 -2
  233. package/dist/web/playground/seed/core/markdown/efforts/strength/good-morning.json +2 -2
  234. package/dist/web/playground/seed/core/markdown/efforts/strength/hanging-leg-raise.json +2 -2
  235. package/dist/web/playground/seed/core/markdown/efforts/strength/hollow-rock.json +2 -2
  236. package/dist/web/playground/seed/core/markdown/efforts/strength/knees-to-elbows.json +2 -2
  237. package/dist/web/playground/seed/core/markdown/efforts/strength/l-sit.json +2 -2
  238. package/dist/web/playground/seed/core/markdown/efforts/strength/man-maker.json +2 -2
  239. package/dist/web/playground/seed/core/markdown/efforts/strength/medicine-ball-clean.json +2 -2
  240. package/dist/web/playground/seed/core/markdown/efforts/strength/overhead-press.json +2 -2
  241. package/dist/web/playground/seed/core/markdown/efforts/strength/parkour-vault.json +2 -2
  242. package/dist/web/playground/seed/core/markdown/efforts/strength/pig-flip.json +2 -2
  243. package/dist/web/playground/seed/core/markdown/efforts/strength/power-clean.json +2 -2
  244. package/dist/web/playground/seed/core/markdown/efforts/strength/power-snatch.json +2 -2
  245. package/dist/web/playground/seed/core/markdown/efforts/strength/push-jerk.json +2 -2
  246. package/dist/web/playground/seed/core/markdown/efforts/strength/push-press.json +2 -2
  247. package/dist/web/playground/seed/core/markdown/efforts/strength/romanian-deadlift.json +2 -2
  248. package/dist/web/playground/seed/core/markdown/efforts/strength/single-leg-deadlift.json +2 -2
  249. package/dist/web/playground/seed/core/markdown/efforts/strength/skull-crusher.json +2 -2
  250. package/dist/web/playground/seed/core/markdown/efforts/strength/slam-ball.json +2 -2
  251. package/dist/web/playground/seed/core/markdown/efforts/strength/sled-pull.json +2 -2
  252. package/dist/web/playground/seed/core/markdown/efforts/strength/sled-push.json +2 -2
  253. package/dist/web/playground/seed/core/markdown/efforts/strength/sumo-deadlift.json +2 -2
  254. package/dist/web/playground/seed/core/markdown/efforts/strength/thruster.json +2 -2
  255. package/dist/web/playground/seed/core/markdown/efforts/strength/triceps-extension.json +2 -2
  256. package/dist/web/playground/seed/core/markdown/efforts/strength/v-sit-hold.json +2 -2
  257. package/dist/web/playground/seed/core/markdown/efforts/strength/wall-walk.json +2 -2
  258. package/dist/web/playground/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +2 -2
  259. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +2 -2
  260. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-backstroke.json +2 -2
  261. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +2 -2
  262. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +2 -2
  263. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-butterfly.json +2 -2
  264. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +2 -2
  265. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +2 -2
  266. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dive-start.json +2 -2
  267. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +2 -2
  268. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-drafting.json +2 -2
  269. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +2 -2
  270. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-freestyle.json +2 -2
  271. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +2 -2
  272. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-kick.json +2 -2
  273. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-pull.json +2 -2
  274. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +2 -2
  275. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +2 -2
  276. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-sighting.json +2 -2
  277. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +2 -2
  278. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +2 -2
  279. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +2 -2
  280. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-vigorous.json +2 -2
  281. package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming.json +2 -2
  282. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +2 -2
  283. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-circles.json +2 -2
  284. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-mill.json +2 -2
  285. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +2 -2
  286. package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +2 -2
  287. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +2 -2
  288. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +2 -2
  289. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +2 -2
  290. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-flow.json +2 -2
  291. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +2 -2
  292. package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +2 -2
  293. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +2 -2
  294. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +2 -2
  295. package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +2 -2
  296. package/dist/web/playground/seed/core/markdown/efforts/walking/walking-3-mph.json +2 -2
  297. package/dist/web/playground/seed/core/markdown/equipment/air-bike.json +1 -1
  298. package/dist/web/playground/seed/core/markdown/equipment/barbell.json +1 -1
  299. package/dist/web/playground/seed/core/markdown/equipment/bench.json +1 -1
  300. package/dist/web/playground/seed/core/markdown/equipment/bike-erg.json +1 -1
  301. package/dist/web/playground/seed/core/markdown/equipment/climbing-rope.json +1 -1
  302. package/dist/web/playground/seed/core/markdown/equipment/clubs.json +1 -1
  303. package/dist/web/playground/seed/core/markdown/equipment/dumbbell.json +1 -1
  304. package/dist/web/playground/seed/core/markdown/equipment/ghd.json +1 -1
  305. package/dist/web/playground/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
  306. package/dist/web/playground/seed/core/markdown/equipment/jump-rope.json +1 -1
  307. package/dist/web/playground/seed/core/markdown/equipment/kettlebell.json +1 -1
  308. package/dist/web/playground/seed/core/markdown/equipment/macebell.json +1 -1
  309. package/dist/web/playground/seed/core/markdown/equipment/medicine-ball.json +1 -1
  310. package/dist/web/playground/seed/core/markdown/equipment/parallettes.json +1 -1
  311. package/dist/web/playground/seed/core/markdown/equipment/plyo-box.json +1 -1
  312. package/dist/web/playground/seed/core/markdown/equipment/pull-up-bar.json +1 -1
  313. package/dist/web/playground/seed/core/markdown/equipment/rower.json +1 -1
  314. package/dist/web/playground/seed/core/markdown/equipment/sandbag.json +1 -1
  315. package/dist/web/playground/seed/core/markdown/equipment/ski-erg.json +1 -1
  316. package/dist/web/playground/seed/core/markdown/equipment/slam-ball.json +1 -1
  317. package/dist/web/playground/seed/core/markdown/equipment/sled.json +1 -1
  318. package/dist/web/playground/seed/core/markdown/equipment/sledgehammer.json +1 -1
  319. package/dist/web/playground/seed/core/markdown/equipment/weight-vest.json +1 -1
  320. package/dist/web/playground/seed/core/report.html +13 -13
  321. package/dist/web/server/assets/{feedSync.worker-CEbxagtY.js → feedSync.worker-BKsDG4P0.js} +4 -4
  322. package/dist/web/server/assets/main-CRlqN3LF.js +494 -0
  323. package/dist/web/server/assets/main-Cye5g1Tm.css +2 -0
  324. package/dist/web/server/assets/{statementBuilderFlow-BPmNsGND.js → statementBuilderFlow-C7gh8ABR.js} +2 -2
  325. package/dist/web/server/assets/{vendor-DKhA8bPd.js → vendor-D0x8W9No.js} +19 -19
  326. package/dist/web/{playground/assets/vendor-codemirror-CnY0iCTs.js → server/assets/vendor-codemirror-Bw_t2lTd.js} +7 -7
  327. package/dist/web/server/index.html +4 -4
  328. package/dist/web/{playground/seed/core/chunks/canvas.9ad327d4.json → server/seed/core/chunks/canvas.dc1d093c.json} +1 -1
  329. package/dist/web/server/seed/core/chunks/{dashboards.f4196444.json → dashboards.e349f3be.json} +1 -1
  330. package/dist/web/server/seed/core/chunks/efforts.84f30fa3.json +1 -0
  331. package/dist/web/{playground/seed/core/chunks/equipment.e7531ab5.json → server/seed/core/chunks/equipment.f07ad76e.json} +1 -1
  332. package/dist/web/server/seed/core/indexes/notebooks/canvas.json +178 -173
  333. package/dist/web/server/seed/core/indexes/notebooks/dashboards.json +18 -13
  334. package/dist/web/server/seed/core/indexes/notebooks/efforts.json +328 -323
  335. package/dist/web/server/seed/core/indexes/notebooks/equipment.json +52 -47
  336. package/dist/web/server/seed/core/manifest.json +40 -2512
  337. package/dist/web/server/seed/core/markdown/canvas/ai-first/README.json +1 -1
  338. package/dist/web/server/seed/core/markdown/canvas/guide/README.json +4 -4
  339. package/dist/web/server/seed/core/markdown/canvas/guide/clock.json +1 -1
  340. package/dist/web/server/seed/core/markdown/canvas/guide/dashboards.json +2 -2
  341. package/dist/web/server/seed/core/markdown/canvas/guide/metrics.json +12 -12
  342. package/dist/web/server/seed/core/markdown/canvas/guide/protocols.json +20 -20
  343. package/dist/web/server/seed/core/markdown/canvas/guide/sessions.json +30 -30
  344. package/dist/web/server/seed/core/markdown/canvas/guide/start.json +10 -10
  345. package/dist/web/server/seed/core/markdown/canvas/guide/structure.json +24 -24
  346. package/dist/web/server/seed/core/markdown/canvas/guide/wql.json +5 -5
  347. package/dist/web/server/seed/core/markdown/canvas/home/sample-script.json +4 -4
  348. package/dist/web/server/seed/core/markdown/canvas/home/welcome-1.json +2 -2
  349. package/dist/web/server/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
  350. package/dist/web/server/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
  351. package/dist/web/server/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
  352. package/dist/web/server/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
  353. package/dist/web/server/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
  354. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
  355. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-full-session.json +9 -9
  356. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
  357. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
  358. package/dist/web/server/seed/core/markdown/canvas/syntax/complex-swimming.json +3 -3
  359. package/dist/web/server/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
  360. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +7 -7
  361. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
  362. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
  363. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
  364. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-3.json +2 -2
  365. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
  366. package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
  367. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
  368. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
  369. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
  370. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
  371. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
  372. package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
  373. package/dist/web/server/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
  374. package/dist/web/server/seed/core/markdown/canvas/syntax/document-1.json +4 -4
  375. package/dist/web/server/seed/core/markdown/canvas/syntax/document-2.json +5 -5
  376. package/dist/web/server/seed/core/markdown/canvas/syntax/document-3.json +10 -10
  377. package/dist/web/server/seed/core/markdown/canvas/syntax/document-4.json +4 -4
  378. package/dist/web/server/seed/core/markdown/canvas/syntax/effort-notes.json +4 -4
  379. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
  380. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
  381. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
  382. package/dist/web/server/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
  383. package/dist/web/server/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
  384. package/dist/web/server/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
  385. package/dist/web/server/seed/core/markdown/canvas/syntax/measurements.json +4 -4
  386. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
  387. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
  388. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
  389. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-4.json +5 -5
  390. package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
  391. package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-sections.json +8 -8
  392. package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
  393. package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
  394. package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
  395. package/dist/web/server/seed/core/markdown/canvas/syntax/named-groups.json +5 -5
  396. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
  397. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
  398. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
  399. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
  400. package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
  401. package/dist/web/server/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
  402. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
  403. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
  404. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
  405. package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
  406. package/dist/web/server/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
  407. package/dist/web/server/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
  408. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
  409. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
  410. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-3.json +3 -3
  411. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
  412. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
  413. package/dist/web/server/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
  414. package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
  415. package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
  416. package/dist/web/server/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
  417. package/dist/web/server/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
  418. package/dist/web/server/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
  419. package/dist/web/server/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
  420. package/dist/web/server/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
  421. package/dist/web/server/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
  422. package/dist/web/server/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
  423. package/dist/web/server/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
  424. package/dist/web/server/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
  425. package/dist/web/server/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
  426. package/dist/web/server/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
  427. package/dist/web/server/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
  428. package/dist/web/server/seed/core/markdown/dashboards/training-block-review.json +11 -11
  429. package/dist/web/server/seed/core/markdown/efforts/bodyweight/air-squat.json +2 -2
  430. package/dist/web/server/seed/core/markdown/efforts/bodyweight/box-jump.json +2 -2
  431. package/dist/web/server/seed/core/markdown/efforts/bodyweight/broad-jump.json +2 -2
  432. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +2 -2
  433. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +2 -2
  434. package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee.json +2 -2
  435. package/dist/web/server/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +2 -2
  436. package/dist/web/server/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +2 -2
  437. package/dist/web/server/seed/core/markdown/efforts/bodyweight/ground-kong.json +2 -2
  438. package/dist/web/server/seed/core/markdown/efforts/bodyweight/jumping-jack.json +2 -2
  439. package/dist/web/server/seed/core/markdown/efforts/bodyweight/kong-walk.json +2 -2
  440. package/dist/web/server/seed/core/markdown/efforts/bodyweight/lunge.json +2 -2
  441. package/dist/web/server/seed/core/markdown/efforts/bodyweight/overhead-squat.json +2 -2
  442. package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-roll.json +2 -2
  443. package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-squat.json +2 -2
  444. package/dist/web/server/seed/core/markdown/efforts/bodyweight/pistol-squat.json +2 -2
  445. package/dist/web/server/seed/core/markdown/efforts/bodyweight/plank.json +2 -2
  446. package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-burpee.json +2 -2
  447. package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-jump.json +2 -2
  448. package/dist/web/server/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +2 -2
  449. package/dist/web/server/seed/core/markdown/efforts/bodyweight/russian-twist.json +2 -2
  450. package/dist/web/server/seed/core/markdown/efforts/bodyweight/sit-up.json +2 -2
  451. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-clean.json +2 -2
  452. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-hold.json +2 -2
  453. package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-snatch.json +2 -2
  454. package/dist/web/server/seed/core/markdown/efforts/bodyweight/tuck-jump.json +2 -2
  455. package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-ball.json +2 -2
  456. package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-burpee.json +2 -2
  457. package/dist/web/server/seed/core/markdown/efforts/cycling/assault-bike.json +2 -2
  458. package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-moderate.json +2 -2
  459. package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-vigorous.json +2 -2
  460. package/dist/web/server/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +2 -2
  461. package/dist/web/server/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +2 -2
  462. package/dist/web/server/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +2 -2
  463. package/dist/web/server/seed/core/markdown/efforts/gymnastics/dip.json +2 -2
  464. package/dist/web/server/seed/core/markdown/efforts/gymnastics/double-under.json +2 -2
  465. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-hold.json +2 -2
  466. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +2 -2
  467. package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-walk.json +2 -2
  468. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jump-rope.json +2 -2
  469. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +2 -2
  470. package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +2 -2
  471. package/dist/web/server/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +2 -2
  472. package/dist/web/server/seed/core/markdown/efforts/gymnastics/muscle-up.json +2 -2
  473. package/dist/web/server/seed/core/markdown/efforts/gymnastics/pull-up.json +2 -2
  474. package/dist/web/server/seed/core/markdown/efforts/gymnastics/push-up.json +2 -2
  475. package/dist/web/server/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +2 -2
  476. package/dist/web/server/seed/core/markdown/efforts/gymnastics/rope-climb.json +2 -2
  477. package/dist/web/server/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +2 -2
  478. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +2 -2
  479. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +2 -2
  480. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +2 -2
  481. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +2 -2
  482. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +2 -2
  483. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +2 -2
  484. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +2 -2
  485. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +2 -2
  486. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +2 -2
  487. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +2 -2
  488. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +2 -2
  489. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +2 -2
  490. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +2 -2
  491. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +2 -2
  492. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +2 -2
  493. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +2 -2
  494. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +2 -2
  495. package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +2 -2
  496. package/dist/web/server/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +2 -2
  497. package/dist/web/server/seed/core/markdown/efforts/recovery/rest.json +2 -2
  498. package/dist/web/server/seed/core/markdown/efforts/recovery/stretching.json +2 -2
  499. package/dist/web/server/seed/core/markdown/efforts/rowing/rowing-sprint.json +2 -2
  500. package/dist/web/server/seed/core/markdown/efforts/rowing/rowing.json +2 -2
  501. package/dist/web/server/seed/core/markdown/efforts/rowing/ski-erg.json +2 -2
  502. package/dist/web/server/seed/core/markdown/efforts/running/backward-running.json +2 -2
  503. package/dist/web/server/seed/core/markdown/efforts/running/running-6-mph.json +2 -2
  504. package/dist/web/server/seed/core/markdown/efforts/running/running-8-mph.json +2 -2
  505. package/dist/web/server/seed/core/markdown/efforts/running/running-sprint.json +2 -2
  506. package/dist/web/server/seed/core/markdown/efforts/snatch.json +7 -7
  507. package/dist/web/server/seed/core/markdown/efforts/strength/back-squat.json +2 -2
  508. package/dist/web/server/seed/core/markdown/efforts/strength/bench-press.json +2 -2
  509. package/dist/web/server/seed/core/markdown/efforts/strength/box-step-up.json +2 -2
  510. package/dist/web/server/seed/core/markdown/efforts/strength/carioca.json +2 -2
  511. package/dist/web/server/seed/core/markdown/efforts/strength/clean-and-jerk.json +2 -2
  512. package/dist/web/server/seed/core/markdown/efforts/strength/cluster.json +2 -2
  513. package/dist/web/server/seed/core/markdown/efforts/strength/dead-hang.json +2 -2
  514. package/dist/web/server/seed/core/markdown/efforts/strength/deadlift.json +2 -2
  515. package/dist/web/server/seed/core/markdown/efforts/strength/devils-press.json +2 -2
  516. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +2 -2
  517. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-clean.json +2 -2
  518. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-fly.json +2 -2
  519. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-row.json +2 -2
  520. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-snatch.json +2 -2
  521. package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-thruster.json +2 -2
  522. package/dist/web/server/seed/core/markdown/efforts/strength/elbows-to-knees.json +2 -2
  523. package/dist/web/server/seed/core/markdown/efforts/strength/farmer-carry.json +2 -2
  524. package/dist/web/server/seed/core/markdown/efforts/strength/frog-stand.json +2 -2
  525. package/dist/web/server/seed/core/markdown/efforts/strength/front-squat.json +2 -2
  526. package/dist/web/server/seed/core/markdown/efforts/strength/good-morning.json +2 -2
  527. package/dist/web/server/seed/core/markdown/efforts/strength/hanging-leg-raise.json +2 -2
  528. package/dist/web/server/seed/core/markdown/efforts/strength/hollow-rock.json +2 -2
  529. package/dist/web/server/seed/core/markdown/efforts/strength/knees-to-elbows.json +2 -2
  530. package/dist/web/server/seed/core/markdown/efforts/strength/l-sit.json +2 -2
  531. package/dist/web/server/seed/core/markdown/efforts/strength/man-maker.json +2 -2
  532. package/dist/web/server/seed/core/markdown/efforts/strength/medicine-ball-clean.json +2 -2
  533. package/dist/web/server/seed/core/markdown/efforts/strength/overhead-press.json +2 -2
  534. package/dist/web/server/seed/core/markdown/efforts/strength/parkour-vault.json +2 -2
  535. package/dist/web/server/seed/core/markdown/efforts/strength/pig-flip.json +2 -2
  536. package/dist/web/server/seed/core/markdown/efforts/strength/power-clean.json +2 -2
  537. package/dist/web/server/seed/core/markdown/efforts/strength/power-snatch.json +2 -2
  538. package/dist/web/server/seed/core/markdown/efforts/strength/push-jerk.json +2 -2
  539. package/dist/web/server/seed/core/markdown/efforts/strength/push-press.json +2 -2
  540. package/dist/web/server/seed/core/markdown/efforts/strength/romanian-deadlift.json +2 -2
  541. package/dist/web/server/seed/core/markdown/efforts/strength/single-leg-deadlift.json +2 -2
  542. package/dist/web/server/seed/core/markdown/efforts/strength/skull-crusher.json +2 -2
  543. package/dist/web/server/seed/core/markdown/efforts/strength/slam-ball.json +2 -2
  544. package/dist/web/server/seed/core/markdown/efforts/strength/sled-pull.json +2 -2
  545. package/dist/web/server/seed/core/markdown/efforts/strength/sled-push.json +2 -2
  546. package/dist/web/server/seed/core/markdown/efforts/strength/sumo-deadlift.json +2 -2
  547. package/dist/web/server/seed/core/markdown/efforts/strength/thruster.json +2 -2
  548. package/dist/web/server/seed/core/markdown/efforts/strength/triceps-extension.json +2 -2
  549. package/dist/web/server/seed/core/markdown/efforts/strength/v-sit-hold.json +2 -2
  550. package/dist/web/server/seed/core/markdown/efforts/strength/wall-walk.json +2 -2
  551. package/dist/web/server/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +2 -2
  552. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +2 -2
  553. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-backstroke.json +2 -2
  554. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +2 -2
  555. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +2 -2
  556. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-butterfly.json +2 -2
  557. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +2 -2
  558. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +2 -2
  559. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dive-start.json +2 -2
  560. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +2 -2
  561. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-drafting.json +2 -2
  562. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +2 -2
  563. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-freestyle.json +2 -2
  564. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +2 -2
  565. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-kick.json +2 -2
  566. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-pull.json +2 -2
  567. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +2 -2
  568. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +2 -2
  569. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-sighting.json +2 -2
  570. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +2 -2
  571. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +2 -2
  572. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +2 -2
  573. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-vigorous.json +2 -2
  574. package/dist/web/server/seed/core/markdown/efforts/swimming/swimming.json +2 -2
  575. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +2 -2
  576. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-circles.json +2 -2
  577. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-mill.json +2 -2
  578. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +2 -2
  579. package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +2 -2
  580. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +2 -2
  581. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +2 -2
  582. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +2 -2
  583. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-flow.json +2 -2
  584. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +2 -2
  585. package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +2 -2
  586. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +2 -2
  587. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +2 -2
  588. package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +2 -2
  589. package/dist/web/server/seed/core/markdown/efforts/walking/walking-3-mph.json +2 -2
  590. package/dist/web/server/seed/core/markdown/equipment/air-bike.json +1 -1
  591. package/dist/web/server/seed/core/markdown/equipment/barbell.json +1 -1
  592. package/dist/web/server/seed/core/markdown/equipment/bench.json +1 -1
  593. package/dist/web/server/seed/core/markdown/equipment/bike-erg.json +1 -1
  594. package/dist/web/server/seed/core/markdown/equipment/climbing-rope.json +1 -1
  595. package/dist/web/server/seed/core/markdown/equipment/clubs.json +1 -1
  596. package/dist/web/server/seed/core/markdown/equipment/dumbbell.json +1 -1
  597. package/dist/web/server/seed/core/markdown/equipment/ghd.json +1 -1
  598. package/dist/web/server/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
  599. package/dist/web/server/seed/core/markdown/equipment/jump-rope.json +1 -1
  600. package/dist/web/server/seed/core/markdown/equipment/kettlebell.json +1 -1
  601. package/dist/web/server/seed/core/markdown/equipment/macebell.json +1 -1
  602. package/dist/web/server/seed/core/markdown/equipment/medicine-ball.json +1 -1
  603. package/dist/web/server/seed/core/markdown/equipment/parallettes.json +1 -1
  604. package/dist/web/server/seed/core/markdown/equipment/plyo-box.json +1 -1
  605. package/dist/web/server/seed/core/markdown/equipment/pull-up-bar.json +1 -1
  606. package/dist/web/server/seed/core/markdown/equipment/rower.json +1 -1
  607. package/dist/web/server/seed/core/markdown/equipment/sandbag.json +1 -1
  608. package/dist/web/server/seed/core/markdown/equipment/ski-erg.json +1 -1
  609. package/dist/web/server/seed/core/markdown/equipment/slam-ball.json +1 -1
  610. package/dist/web/server/seed/core/markdown/equipment/sled.json +1 -1
  611. package/dist/web/server/seed/core/markdown/equipment/sledgehammer.json +1 -1
  612. package/dist/web/server/seed/core/markdown/equipment/weight-vest.json +1 -1
  613. package/dist/web/server/seed/core/report.html +12 -12
  614. package/package.json +6 -6
  615. package/dist/chunk-6L5ZDZJ7.mjs +0 -15
  616. package/dist/chunk-EAFF2GVB.mjs.map +0 -1
  617. package/dist/chunk-O5ZCOUQE.mjs.map +0 -1
  618. package/dist/chunk-PF5BTGWZ.mjs.map +0 -1
  619. package/dist/compiler-ZMG22VH4.mjs +0 -9
  620. package/dist/server-5XDT7ITA.mjs +0 -11
  621. package/dist/web/playground/assets/main-BKDG9P36.css +0 -2
  622. package/dist/web/playground/assets/main-DAHoAykp.js +0 -491
  623. package/dist/web/playground/seed/core/chunks/efforts.7f0d2160.json +0 -1
  624. package/dist/web/server/assets/main-BKDG9P36.css +0 -2
  625. package/dist/web/server/assets/main-C_b1CczJ.js +0 -491
  626. package/dist/web/server/seed/core/chunks/efforts.7f0d2160.json +0 -1
@@ -1,6 +1,6 @@
1
- (function(){let e=(e,t)=>t.some(t=>e instanceof t),t,n;function r(){return t||=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]}function i(){return n||=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]}let a=new WeakMap,o=new WeakMap,s=new WeakMap;function c(e){let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`success`,i),e.removeEventListener(`error`,a)},i=()=>{t(m(e.result)),r()},a=()=>{n(e.error),r()};e.addEventListener(`success`,i),e.addEventListener(`error`,a)});return s.set(t,e),t}function l(e){if(a.has(e))return;let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`complete`,i),e.removeEventListener(`error`,a),e.removeEventListener(`abort`,a)},i=()=>{t(),r()},a=()=>{n(e.error||new DOMException(`AbortError`,`AbortError`)),r()};e.addEventListener(`complete`,i),e.addEventListener(`error`,a),e.addEventListener(`abort`,a)});a.set(e,t)}let u={get(e,t,n){if(e instanceof IDBTransaction){if(t===`done`)return a.get(e);if(t===`store`)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return m(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t===`done`||t===`store`)||t in e}};function d(e){u=e(u)}function f(e){return i().includes(e)?function(...t){return e.apply(h(this),t),m(this.request)}:function(...t){return m(e.apply(h(this),t))}}function p(t){return typeof t==`function`?f(t):(t instanceof IDBTransaction&&l(t),e(t,r())?new Proxy(t,u):t)}function m(e){if(e instanceof IDBRequest)return c(e);if(o.has(e))return o.get(e);let t=p(e);return t!==e&&(o.set(e,t),s.set(t,e)),t}let h=e=>s.get(e);function g(e,t,{blocked:n,upgrade:r,blocking:i,terminated:a}={}){let o=indexedDB.open(e,t),s=m(o);return r&&o.addEventListener(`upgradeneeded`,e=>{r(m(o.result),e.oldVersion,e.newVersion,m(o.transaction),e)}),n&&o.addEventListener(`blocked`,e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{a&&e.addEventListener(`close`,()=>a()),i&&e.addEventListener(`versionchange`,e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}let _=[`get`,`getKey`,`getAll`,`getAllKeys`,`count`],v=[`put`,`add`,`delete`,`clear`],y=new Map;function b(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t==`string`))return;if(y.get(t))return y.get(t);let n=t.replace(/FromIndex$/,``),r=t!==n,i=v.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||_.includes(n)))return;let a=async function(e,...t){let a=this.transaction(e,i?`readwrite`:`readonly`),o=a.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&a.done]))[0]};return y.set(t,a),a}d(e=>({...e,get:(t,n,r)=>b(t,n)||e.get(t,n,r),has:(t,n)=>!!b(t,n)||e.has(t,n)}));let x=[`continue`,`continuePrimaryKey`,`advance`],S={},C=new WeakMap,ee=new WeakMap,te={get(e,t){if(!x.includes(t))return e[t];let n=S[t];return n||=S[t]=function(...e){C.set(this,ee.get(this)[t](...e))},n}};async function*ne(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let n=new Proxy(t,te);for(ee.set(n,t),s.set(n,h(t));t;)yield n,t=await(C.get(n)||t.continue()),C.delete(n)}function re(t,n){return n===Symbol.asyncIterator&&e(t,[IDBIndex,IDBObjectStore,IDBCursor])||n===`iterate`&&e(t,[IDBIndex,IDBObjectStore])}d(e=>({...e,get(t,n,r){return re(t,n)?ne:e.get(t,n,r)},has(t,n){return re(t,n)||e.has(t,n)}}));let w=[{name:`notes`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-created`,keyPath:[`createdAt`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`page`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`],unique:!0},{name:`by-slug`,keyPath:[`slug`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`page_notes`,keyPath:[`id`],indexes:[{name:`by-page`,keyPath:[`pageId`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-page-note`,keyPath:[`pageId`,`noteId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`tags`,keyPath:[`id`],indexes:[{name:`by-label`,keyPath:[`label`],unique:!0},{name:`by-type`,keyPath:[`type`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`tag_types`,keyPath:[`id`],indexes:[{name:`by-name`,keyPath:[`name`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`note_tags`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-tag`,keyPath:[`tagId`]},{name:`by-note-tag`,keyPath:[`noteId`,`tagId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_revisions`,keyPath:[`noteId`,`blockId`,`version`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-block`,keyPath:[`noteId`,`blockId`]}]},{name:`sessions`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-completed`,keyPath:[`createdAt`]},{name:`by-content`,keyPath:[`blockContentId`]},{name:`by-block`,keyPath:[`blockId`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-origin`,keyPath:[`origin`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`attachments`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-time`,keyPath:[`createdAt`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-result`,keyPath:[`resultId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`events`,keyPath:[`id`],indexes:[{name:`by-timestamp`,keyPath:[`timestamp`]},{name:`by-result-grain`,keyPath:[`resultId`,`grain`]},{name:`by-content-grain`,keyPath:[`blockContentId`,`grain`]},{name:`by-effort`,keyPath:[`effortSlug`]},{name:`by-outputType`,keyPath:[`outputType`]},{name:`by-grain`,keyPath:[`grain`]},{name:`by-metric-date`,keyPath:[`metricDateKeys`],multiEntry:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`field_catalog`,keyPath:[`id`],indexes:[{name:`by-path`,keyPath:[`path`]}]},{name:`field_sources`,keyPath:[`id`],indexes:[]},{name:`field_values`,keyPath:[`key`],indexes:[{name:`by-field`,keyPath:[`fieldId`]}]},{name:`field_catalog_meta`,keyPath:[`id`],indexes:[]},{name:`efforts`,keyPath:[`slug`],indexes:[{name:`by-discipline`,keyPath:[`baseAttributes.discipline`]},{name:`by-source`,keyPath:[`registrySource`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`equipment`,keyPath:[`slug`],indexes:[{name:`by-source`,keyPath:[`registrySource`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_index`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-content`,keyPath:[`blockContentId`]},{name:`by-type`,keyPath:[`dataType`]},{name:`by-source`,keyPath:[`sourceId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_efforts`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-effort`,keyPath:[`effortSlug`]},{name:`by-block`,keyPath:[`blockContentId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_equipment`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-equipment`,keyPath:[`equipmentSlug`]},{name:`by-block`,keyPath:[`blockContentId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`meta`,keyPath:[`key`],indexes:[]},{name:`memberships`,keyPath:[`id`],indexes:[],system:!0}],T=[`notes`,`page`,`page_notes`,`tags`,`tag_types`,`note_tags`,`sessions`,`attachments`,`events`,`efforts`,`block_index`,`block_efforts`,`equipment`,`block_equipment`],ie=Object.fromEntries(T.map(e=>[e,!0]));function ae(e,t,n){if(!ie[e]||typeof t!=`object`||!t||Array.isArray(t))return t;let r=t;return r.seedOrigin===`seed`||r.userId===n?t:{...r,userId:n}}function oe(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;let t=n;if(!(e in t))return;n=t[e]}if(n!==null&&typeof n!=`object`&&n!==void 0)return n}function se(e,t){let n=e.keyPath.map(e=>oe(t,e));for(let[t,r]of n.entries())if(r===void 0)throw Error(`keyFromValue(${e.name}): keyPath part '${e.keyPath[t]}' missing on value`);let r=n;return r.length===1?r[0]:r}let ce=[`parser`,`dialect`,`user-plan`,`runtime`,`user-entry`],le={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`};function ue(e){return le[e??`parser`]??`parser`}let E=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.Choice=`choice`,e}({}),de={parser:0,dialect:1,"user-plan":2,runtime:3,"user-entry":4};function fe(e){return e.ownershipLayer??ue(e.origin)}function pe(e){let t=fe(e);return de[t]??0}function me(e){return e.map((e,t)=>{let n=fe(e);return{metric:e,type:e.type,layer:n,layerRank:de[n]??0,index:t,isSuppressor:e.action===`suppress`}})}function he(e,t){return t?e.filter(e=>!(t.types&&!t.types.includes(e.type)||t.layers&&!t.layers.includes(e.layer))):[...e]}function ge(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 _e(e){let t;for(let n of e)n.isSuppressor||(t==null||n.layerRank>t)&&(t=n.layerRank);return t}function ve(e,t){return{metric:e.metric,type:e.type,layer:e.layer,outcome:t}}function ye(e,t){return e.index-t.index}function be(e){let t=me(e);return{raw(e){return he(t,e).map(e=>e.metric)},visible(e){let n=ge(he(t,e)),r=[];for(let e of n.values()){if(e.some(e=>e.isSuppressor))continue;let t=_e(e);if(t!=null)for(let n of e)!n.isSuppressor&&n.layerRank===t&&r.push(n)}return r.sort(ye),r.map(e=>e.metric)},byLayer(e){let n=he(t,e),r={};for(let e of ce)r[e]=[];for(let e of n)r[e.layer].push(e.metric);for(let e of ce)r[e]?.length===0&&delete r[e];return r},promotionCandidates(e){let n=ge(he(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:ce[i]});continue}let i=_e(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:ce[i]})}return r.sort((e,t)=>{let n=(de[t.layer]??0)-(de[e.layer]??0);return n===0?0:n}),r},explain(e){let n=ge(he(t,e)),r=[];for(let[e,t]of n.entries()){let n=t.some(e=>e.isSuppressor),i=n?void 0:_e(t),a=t.map(e=>e.isSuppressor?ve(e,`suppressor`):n?ve(e,`hidden-by-suppressor`):i!=null&&e.layerRank===i?ve(e,`visible`):ve(e,`hidden-by-layer`));r.push({type:e,winnerLayer:i==null?void 0:ce[i],suppressed:n,entries:a})}return r}}}function xe(e,t){let n=[...e];return(t?.types?.includes(E.Hint)??!1)||(n=n.filter(e=>e.type!==E.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 Se=class{resolve(e,t){return be(xe(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)=>pe(t)-pe(e))}};function Ce(e){return JSON.stringify([e.path,e.kind,e.dimension??null])}let we=[{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`]}];(()=>{let e=new Map;for(let t of we){e.set(t.canonical.toLowerCase(),t);for(let n of t.aliases??[])e.has(n.toLowerCase())||e.set(n.toLowerCase(),t)}return e})(),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});var D=class e{_metrics;_indexedLength=0;_resolver=new Se;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)=>pe(t)-pe(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=>pe(e))),i=Math.max(...t.map(e=>pe(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(`, `)}]`}},Te=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 Ee(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`)}`}let De=[`playground-run-tip`,`attention`,`code-example`,`syntax-group`];function Oe(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 ke(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`,`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 Ae(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 je(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
1
+ (function(){let e=(e,t)=>t.some(t=>e instanceof t),t,n;function r(){return t||=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]}function i(){return n||=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]}let a=new WeakMap,o=new WeakMap,s=new WeakMap;function c(e){let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`success`,i),e.removeEventListener(`error`,a)},i=()=>{t(m(e.result)),r()},a=()=>{n(e.error),r()};e.addEventListener(`success`,i),e.addEventListener(`error`,a)});return s.set(t,e),t}function l(e){if(a.has(e))return;let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`complete`,i),e.removeEventListener(`error`,a),e.removeEventListener(`abort`,a)},i=()=>{t(),r()},a=()=>{n(e.error||new DOMException(`AbortError`,`AbortError`)),r()};e.addEventListener(`complete`,i),e.addEventListener(`error`,a),e.addEventListener(`abort`,a)});a.set(e,t)}let u={get(e,t,n){if(e instanceof IDBTransaction){if(t===`done`)return a.get(e);if(t===`store`)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return m(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t===`done`||t===`store`)||t in e}};function d(e){u=e(u)}function f(e){return i().includes(e)?function(...t){return e.apply(h(this),t),m(this.request)}:function(...t){return m(e.apply(h(this),t))}}function p(t){return typeof t==`function`?f(t):(t instanceof IDBTransaction&&l(t),e(t,r())?new Proxy(t,u):t)}function m(e){if(e instanceof IDBRequest)return c(e);if(o.has(e))return o.get(e);let t=p(e);return t!==e&&(o.set(e,t),s.set(t,e)),t}let h=e=>s.get(e);function g(e,t,{blocked:n,upgrade:r,blocking:i,terminated:a}={}){let o=indexedDB.open(e,t),s=m(o);return r&&o.addEventListener(`upgradeneeded`,e=>{r(m(o.result),e.oldVersion,e.newVersion,m(o.transaction),e)}),n&&o.addEventListener(`blocked`,e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{a&&e.addEventListener(`close`,()=>a()),i&&e.addEventListener(`versionchange`,e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}let _=[`get`,`getKey`,`getAll`,`getAllKeys`,`count`],v=[`put`,`add`,`delete`,`clear`],y=new Map;function b(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t==`string`))return;if(y.get(t))return y.get(t);let n=t.replace(/FromIndex$/,``),r=t!==n,i=v.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||_.includes(n)))return;let a=async function(e,...t){let a=this.transaction(e,i?`readwrite`:`readonly`),o=a.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&a.done]))[0]};return y.set(t,a),a}d(e=>({...e,get:(t,n,r)=>b(t,n)||e.get(t,n,r),has:(t,n)=>!!b(t,n)||e.has(t,n)}));let x=[`continue`,`continuePrimaryKey`,`advance`],S={},C=new WeakMap,ee=new WeakMap,te={get(e,t){if(!x.includes(t))return e[t];let n=S[t];return n||=S[t]=function(...e){C.set(this,ee.get(this)[t](...e))},n}};async function*ne(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let n=new Proxy(t,te);for(ee.set(n,t),s.set(n,h(t));t;)yield n,t=await(C.get(n)||t.continue()),C.delete(n)}function re(t,n){return n===Symbol.asyncIterator&&e(t,[IDBIndex,IDBObjectStore,IDBCursor])||n===`iterate`&&e(t,[IDBIndex,IDBObjectStore])}d(e=>({...e,get(t,n,r){return re(t,n)?ne:e.get(t,n,r)},has(t,n){return re(t,n)||e.has(t,n)}}));let w=[{name:`notes`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-created`,keyPath:[`createdAt`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`page`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`],unique:!0},{name:`by-slug`,keyPath:[`slug`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`page_notes`,keyPath:[`id`],indexes:[{name:`by-page`,keyPath:[`pageId`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-page-note`,keyPath:[`pageId`,`noteId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`tags`,keyPath:[`id`],indexes:[{name:`by-label`,keyPath:[`label`],unique:!0},{name:`by-type`,keyPath:[`type`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`tag_types`,keyPath:[`id`],indexes:[{name:`by-name`,keyPath:[`name`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`note_tags`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-tag`,keyPath:[`tagId`]},{name:`by-note-tag`,keyPath:[`noteId`,`tagId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_revisions`,keyPath:[`noteId`,`blockId`,`version`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-block`,keyPath:[`noteId`,`blockId`]}]},{name:`sessions`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-completed`,keyPath:[`createdAt`]},{name:`by-content`,keyPath:[`blockContentId`]},{name:`by-block`,keyPath:[`blockId`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-origin`,keyPath:[`origin`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`attachments`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-time`,keyPath:[`createdAt`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-result`,keyPath:[`resultId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`events`,keyPath:[`id`],indexes:[{name:`by-timestamp`,keyPath:[`timestamp`]},{name:`by-result-grain`,keyPath:[`resultId`,`grain`]},{name:`by-content-grain`,keyPath:[`blockContentId`,`grain`]},{name:`by-effort`,keyPath:[`effortSlug`]},{name:`by-outputType`,keyPath:[`outputType`]},{name:`by-grain`,keyPath:[`grain`]},{name:`by-metric-date`,keyPath:[`metricDateKeys`],multiEntry:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`field_catalog`,keyPath:[`id`],indexes:[{name:`by-path`,keyPath:[`path`]}]},{name:`field_sources`,keyPath:[`id`],indexes:[]},{name:`field_values`,keyPath:[`key`],indexes:[{name:`by-field`,keyPath:[`fieldId`]}]},{name:`field_catalog_meta`,keyPath:[`id`],indexes:[]},{name:`efforts`,keyPath:[`slug`],indexes:[{name:`by-discipline`,keyPath:[`baseAttributes.discipline`]},{name:`by-source`,keyPath:[`registrySource`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`equipment`,keyPath:[`slug`],indexes:[{name:`by-source`,keyPath:[`registrySource`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_index`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-content`,keyPath:[`blockContentId`]},{name:`by-type`,keyPath:[`dataType`]},{name:`by-source`,keyPath:[`sourceId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_efforts`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-effort`,keyPath:[`effortSlug`]},{name:`by-block`,keyPath:[`blockContentId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`block_equipment`,keyPath:[`id`],indexes:[{name:`by-note`,keyPath:[`noteId`]},{name:`by-equipment`,keyPath:[`equipmentSlug`]},{name:`by-block`,keyPath:[`blockContentId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`meta`,keyPath:[`key`],indexes:[]},{name:`memberships`,keyPath:[`id`],indexes:[],system:!0}],T=[`notes`,`page`,`page_notes`,`tags`,`tag_types`,`note_tags`,`sessions`,`attachments`,`events`,`efforts`,`block_index`,`block_efforts`,`equipment`,`block_equipment`],ie=Object.fromEntries(T.map(e=>[e,!0]));function ae(e,t,n){if(!ie[e]||typeof t!=`object`||!t||Array.isArray(t))return t;let r=t;return r.seedOrigin===`seed`||r.userId===n?t:{...r,userId:n}}function oe(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;let t=n;if(!(e in t))return;n=t[e]}if(n!==null&&typeof n!=`object`&&n!==void 0)return n}function se(e,t){let n=e.keyPath.map(e=>oe(t,e));for(let[t,r]of n.entries())if(r===void 0)throw Error(`keyFromValue(${e.name}): keyPath part '${e.keyPath[t]}' missing on value`);let r=n;return r.length===1?r[0]:r}let ce=[`parser`,`dialect`,`user-plan`,`runtime`,`user-entry`],le={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 ue(e){return le[e??`parser`]??`parser`}let E=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}({}),de={parser:0,dialect:1,"user-plan":2,runtime:3,"user-entry":4};function fe(e){return e.ownershipLayer??ue(e.origin)}function pe(e){let t=fe(e);return de[t]??0}function me(e){return e.map((e,t)=>{let n=fe(e);return{metric:e,type:e.type,layer:n,layerRank:de[n]??0,index:t,isSuppressor:e.action===`suppress`}})}function he(e,t){return t?e.filter(e=>!(t.types&&!t.types.includes(e.type)||t.layers&&!t.layers.includes(e.layer))):[...e]}function ge(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 _e(e){let t;for(let n of e)n.isSuppressor||(t==null||n.layerRank>t)&&(t=n.layerRank);return t}function ve(e,t){return{metric:e.metric,type:e.type,layer:e.layer,outcome:t}}function ye(e,t){return e.index-t.index}function be(e){let t=me(e);return{raw(e){return he(t,e).map(e=>e.metric)},visible(e){let n=ge(he(t,e)),r=[];for(let e of n.values()){if(e.some(e=>e.isSuppressor))continue;let t=_e(e);if(t!=null)for(let n of e)!n.isSuppressor&&n.layerRank===t&&r.push(n)}return r.sort(ye),r.map(e=>e.metric)},byLayer(e){let n=he(t,e),r={};for(let e of ce)r[e]=[];for(let e of n)r[e.layer].push(e.metric);for(let e of ce)r[e]?.length===0&&delete r[e];return r},promotionCandidates(e){let n=ge(he(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:ce[i]});continue}let i=_e(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:ce[i]})}return r.sort((e,t)=>{let n=(de[t.layer]??0)-(de[e.layer]??0);return n===0?0:n}),r},explain(e){let n=ge(he(t,e)),r=[];for(let[e,t]of n.entries()){let n=t.some(e=>e.isSuppressor),i=n?void 0:_e(t),a=t.map(e=>e.isSuppressor?ve(e,`suppressor`):n?ve(e,`hidden-by-suppressor`):i!=null&&e.layerRank===i?ve(e,`visible`):ve(e,`hidden-by-layer`));r.push({type:e,winnerLayer:i==null?void 0:ce[i],suppressed:n,entries:a})}return r}}}function xe(e,t){let n=[...e];return(t?.types?.includes(E.Hint)??!1)||(n=n.filter(e=>e.type!==E.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 Se=class{resolve(e,t){return be(xe(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)=>pe(t)-pe(e))}};function Ce(e){return JSON.stringify([e.path,e.kind,e.dimension??null])}let we=[{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`]}];(()=>{let e=new Map;for(let t of we){e.set(t.canonical.toLowerCase(),t);for(let n of t.aliases??[])e.has(n.toLowerCase())||e.set(n.toLowerCase(),t)}return e})(),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});var D=class e{_metrics;_indexedLength=0;_resolver=new Se;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)=>pe(t)-pe(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=>pe(e))),i=Math.max(...t.map(e=>pe(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(`, `)}]`}},Te=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 Ee(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`)}`}let De=[`playground-run-tip`,`attention`,`code-example`,`syntax-group`];function Oe(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 ke(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 Ae(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 je(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
2
2
  `,a)?`\r
3
- `:/[\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]==="`"?Oe(`\`\`\`${h}`):null,_=a[0]==="`"?h.match(/^widget:([\w-]+)$/):null,v=a[0]==="`"?h.match(/^query(?:[:\s](.*))?$/i):null,y=t.registeredWidgets??De,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=Ee(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=ke(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=Ae(m.displayContent.trim()),a&&(c=!1),o.push(m),l=p+1}return o}function Me(e){return e.type===`time`||e.type===`log`?`wod`:e.type===`query`||e.type===`widget`||e.type===`embed`?e.type:null}function Ne(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 je(e,t)){let e=Me(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 Pe(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=Ne(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 Fe(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 Ie=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n,this.name=`StorageError`}};function Le(e,t){if(Object.is(e,t))return!0;if(e instanceof ArrayBuffer&&t instanceof ArrayBuffer){let n=new Uint8Array(e),r=new Uint8Array(t);return n.length===r.length&&n.every((e,t)=>e===r[t])}if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>Le(e,t[n]));let n=Object.keys(e).filter(t=>Reflect.get(e,t)!==void 0),r=Object.keys(t).filter(e=>Reflect.get(t,e)!==void 0);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&Le(Reflect.get(e,n),Reflect.get(t,n)))}function Re(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new Ie(400,`storage row must be an object`);return e}function ze(e,t){if(e!==`notes`&&e!==`block_revisions`&&e!==`sessions`&&e!==`block_index`)return;let n=Re(t),r=e=>typeof n[e]==`number`&&Number.isSafeInteger(n[e])&&n[e]>0,i=e=>typeof n[e]==`string`&&n[e].length>0;if(e===`notes`){if(!i(`id`)||typeof n.title!=`string`||typeof n.rawContent!=`string`||!r(`sourceRevision`)||typeof n.createdAt!=`number`||!Number.isFinite(n.createdAt)||`segments`in n||`segmentIds`in n||n.date!==void 0&&(typeof n.date!=`number`||!Number.isFinite(n.date))||n.seedOrigin!==void 0&&n.seedOrigin!==`seed`&&n.seedOrigin!==`user`||n.feedOrigin!==void 0&&n.feedOrigin!==`feed`&&n.feedOrigin!==`user`||n.feedOrigin===`feed`&&(n.seedOrigin===void 0||typeof n.feedSourceId!=`string`||n.feedSourceId.length===0)||n.feedOrigin===`user`&&n.seedOrigin===`seed`||n.feedSourceId!==void 0&&n.feedOrigin!==`feed`||n.seedVersion!==void 0&&!(typeof n.seedVersion==`number`&&Number.isSafeInteger(n.seedVersion)&&n.seedVersion>=0)||n.tags!==void 0&&(!Array.isArray(n.tags)||!n.tags.every(e=>typeof e==`string`))||[`type`,`sourceId`,`sourcePath`,`notebookId`,`seedChunkId`,`feedSourceId`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new Ie(400,`invalid whole Note`,`invalid_note_blocks`);try{Pe(n.rawContent,Re(n.blocks),n.sourceRevision)}catch(e){throw new Ie(400,e instanceof Error?e.message:`invalid block map`,`invalid_note_blocks`)}}else if(e===`block_revisions`){if(!i(`noteId`)||!i(`blockId`)||!r(`version`)||typeof n.rawContent!=`string`||typeof n.savedAt!=`number`||!Number.isFinite(n.savedAt)||![`wod`,`query`,`widget`,`embed`].includes(String(n.kind))||(n.kind===`wod`?n.dialect!==`time`&&n.dialect!==`log`:n.dialect!==void 0||n.sport!==void 0)||n.sport!==void 0&&typeof n.sport!=`string`)throw new Ie(400,`invalid block revision`,`invalid_note_blocks`);try{Pe(n.rawContent,{[String(n.blockId)]:{id:String(n.blockId),kind:n.kind,version:n.version,sourceRevision:1,from:0,to:n.rawContent.length,...n.dialect===void 0?{}:{dialect:n.dialect},...n.sport===void 0?{}:{sport:n.sport}}},1)}catch(e){throw new Ie(400,e instanceof Error?e.message:`invalid revision source`,`invalid_note_blocks`)}}else if(e===`sessions`){if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||[`segmentId`,`segmentVersion`,`version`,`rawContent`,`script`,`serializedScript`,`source`,`data`,`logs`].some(e=>e in n))throw new Ie(400,`Session requires immutable block pin`,`invalid_session_pin`)}else if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||!r(`sourceRevision`)||n.id!==`${n.noteId}:${n.blockId}`||!Number.isSafeInteger(n.from)||!Number.isSafeInteger(n.to)||`segmentId`in n||`segmentVersion`in n||![`wod`,`query`,`widget`,`embed`].includes(String(n.dataType))||typeof n.rawContent!=`string`||typeof n.noteTitle!=`string`||typeof n.from!=`number`||typeof n.to!=`number`||n.from<0||n.to<=n.from)throw new Ie(400,`invalid actionable block projection`,`invalid_note_blocks`)}function Be(e,t){if(e===void 0||Le(e,t))return;let n=Re(e),r=Re(t);if(typeof n.sourceRevision!=`number`||typeof r.sourceRevision!=`number`||r.sourceRevision<n.sourceRevision||(!Le(n.blocks,r.blocks)||n.rawContent!==r.rawContent)&&r.sourceRevision<=n.sourceRevision)throw new Ie(409,`stale Note source revision`,`transaction_conflict`)}function Ve(e,t){if(e===void 0)return;let n=Re(e),r=Re(t);if(n.noteId!==r.noteId||n.blockId!==r.blockId||n.blockVersion!==r.blockVersion)throw new Ie(409,`Session pin is immutable`,`invalid_session_pin`)}async function He(e,t,n){let r=[];for(let t of e)for(let e of Object.values(t.blocks))r.push([t.id,e.id,e.version]);for(let e of t)r.push([e.noteId,e.blockId,e.blockVersion]);let i=await n(r),a=0;for(let t of e)for(let e of Object.values(t.blocks)){let n=i[a++];if(!n||n.kind!==e.kind||n.rawContent!==t.rawContent.slice(e.from,e.to)||n.dialect!==e.dialect||n.sport!==e.sport)throw new Ie(409,`Note block has no matching immutable revision`,`invalid_note_blocks`)}for(let e=0;e<t.length;e++){let e=i[a++];if(!e||e.kind!==`wod`)throw new Ie(409,`Session pin must reference a saved workout revision`,`invalid_session_pin`)}}function Ue(e){if(!(typeof e!=`string`||!e.startsWith(`user-deleted-seed:`)))return e.slice(18)||void 0}function We(e){return typeof e==`string`&&e.startsWith(`seed:`)}function Ge(e){let t=new Set;for(let n of e)typeof n==`object`&&n&&`seedOrigin`in n&&n.seedOrigin===`seed`&&`id`in n&&typeof n.id==`string`&&t.add(n.id);return{seedNoteIds:t}}function Ke(e,t,n){if(typeof t!=`object`||!t)return!0;switch(e){case`notes`:return!(`seedOrigin`in t&&t.seedOrigin===`seed`);case`block_index`:case`block_efforts`:case`block_equipment`:return!(`isStatic`in t&&t.isStatic===!0&&`noteId`in t&&typeof t.noteId==`string`&&n.seedNoteIds.has(t.noteId));case`efforts`:case`equipment`:return!(`registrySource`in t&&t.registrySource===`bundled`);case`meta`:return!We(`key`in t?t.key:void 0);default:return!0}}Object.fromEntries(w.map(e=>[e.name,!0]));let qe=[`reps`,`distance`,`resistance`,`elapsed`,`power`,`pace`],Je=[`totalVolume`,`totalDistance`,`tis`,`sessionLoad`],Ye=[`sum`,`avg`,`min`,`max`,`count`,`last`,`delta`],Xe=[`domain`,`format`,`equipment`,`quality`,`intent`],Ze=[...Xe,`effort`,`discipline`,`intensity`,`grade`,`note`,`page`,`origin`,`grain`,`metric`,`block`,`result`,`tags`],Qe=[`effort`,`discipline`,`intensity`,`origin`,`text`],$e=[`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`],et=[`note`,`block`,`effort`,`session`,`segment`,`event`,`notebook`,`page`,`tag`,`equipment`],tt=[`note`,`notes`,`block`,`effort`,`session`,`segment`,`event`,`journal`,`notebook`,`notebooks`,`playground`,`page`,`tag`,`equipment`,`dashboard`],nt=Ye,rt=[`timeseries`,`bar`,`table`,`donut`,`toplist`,`value`],it=[`@session`,`@today`];[...Ze];let at=[`kg`,`lb`],ot={time:!0,groupby:!0,rollup:!0,unit:!0,where:!0,agg:!0},st=Ze.filter(e=>e!==`metric`),ct=Ze.filter(e=>e!==`tags`);[...st.map(e=>e===`tags`?`tag`:e)];let lt={notebook:new Set([`text`,`notebook`,`tag`,`effort`,...Xe,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`]),note:new Set([`text`,`notebook`,`tag`,`effort`,...Xe,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`]),block:new Set([`text`,`notebook`,`tag`,`effort`,`type`,`source`,`note`,`time`,`groupby`,`where`]),effort:new Set([...Qe,`groupby`]),session:new Set([`result`,`block`,`note`,`plane`,`time`,`groupby`]),segment:new Set([...ct,`time`,`groupby`,`unit`]),event:new Set([...ct,`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`])},ut=Ze,dt=Object.fromEntries(Object.entries(lt).map(([e,t])=>[e,[...t].filter(e=>!ot[e]).map(e=>e===`tag`?`tags`:e)]));[...Ze],[...qe,...Je,...$e];function ft(e,t){return t===`aggregate`?ut:dt[e]??[]}let pt=1024,mt=0;var ht=class{constructor(e,t){this.from=e,this.to=t}},O=class{constructor(e={}){this.id=mt++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw Error(`This node type doesn't define a deserialize function`)}),this.combine=e.combine||null}add(e){if(this.perNode)throw RangeError(`Can't add per-node props to node types`);return typeof e!=`function`&&(e=vt.match(e)),t=>{let n=e(t);return n===void 0?null:[this,n]}}};O.closedBy=new O({deserialize:e=>e.split(` `)}),O.openedBy=new O({deserialize:e=>e.split(` `)}),O.group=new O({deserialize:e=>e.split(` `)}),O.isolate=new O({deserialize:e=>{if(e&&e!=`rtl`&&e!=`ltr`&&e!=`auto`)throw RangeError(`Invalid value for isolate: `+e);return e||`auto`}}),O.contextHash=new O({perNode:!0}),O.lookAhead=new O({perNode:!0}),O.mounted=new O({perNode:!0});var gt=class{constructor(e,t,n,r=!1){this.tree=e,this.overlay=t,this.parser=n,this.bracketed=r}static get(e){return e&&e.props&&e.props[O.mounted.id]}};let _t=Object.create(null);var vt=class e{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(t){let n=t.props&&t.props.length?Object.create(null):_t,r=!!t.top|(t.skipped?2:0)|(t.error?4:0)|(t.name==null?8:0),i=new e(t.name||``,n,t.id,r);if(t.props){for(let e of t.props)if(Array.isArray(e)||(e=e(i)),e){if(e[0].perNode)throw RangeError(`Can't store a per-node prop on a node type`);n[e[0].id]=e[1]}}return i}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e==`string`){if(this.name==e)return!0;let t=this.prop(O.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(` `))t[r]=e[n];return e=>{for(let n=e.prop(O.group),r=-1;r<(n?n.length:0);r++){let i=t[r<0?e.name:n[r]];if(i)return i}}}};vt.none=new vt(``,Object.create(null),0,8);var yt=class e{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw RangeError(`Node type ids should correspond to array positions when creating a node set`)}extend(...t){let n=[];for(let e of this.types){let r=null;for(let n of t){let t=n(e);if(t){r||=Object.assign({},e.props);let n=t[1],i=t[0];i.combine&&i.id in r&&(n=i.combine(r[i.id],n)),r[i.id]=n}}n.push(r?new vt(e.name,r,e.id,e.flags):e)}return new e(n)}};let bt=new WeakMap,xt=new WeakMap;var k;(function(e){e[e.ExcludeBuffers=1]=`ExcludeBuffers`,e[e.IncludeAnonymous=2]=`IncludeAnonymous`,e[e.IgnoreMounts=4]=`IgnoreMounts`,e[e.IgnoreOverlays=8]=`IgnoreOverlays`,e[e.EnterBracketed=16]=`EnterBracketed`})(k||={});var A=class e{constructor(e,t,n,r,i){if(this.type=e,this.children=t,this.positions=n,this.length=r,this.props=null,i&&i.length){this.props=Object.create(null);for(let[e,t]of i)this.props[typeof e==`number`?e:e.id]=t}}toString(){let e=gt.get(this);if(e&&!e.overlay)return e.tree.toString();let t=``;for(let e of this.children){let n=e.toString();n&&(t&&(t+=`,`),t+=n)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?`(`+t+`)`:``):t}cursor(e=0){return new Ft(this.topNode,e)}cursorAt(e,t=0,n=0){let r=new Ft(bt.get(this)||this.topNode);return r.moveTo(e,t),bt.set(this,r._tree),r}get topNode(){return new Dt(this,0,0,null)}resolve(e,t=0){let n=Tt(bt.get(this)||this.topNode,e,t,!1);return bt.set(this,n),n}resolveInner(e,t=0){let n=Tt(xt.get(this)||this.topNode,e,t,!0);return xt.set(this,n),n}resolveStack(e,t=0){return Pt(this,e,t)}iterate(e){let{enter:t,leave:n,from:r=0,to:i=this.length}=e,a=e.mode||0,o=(a&k.IncludeAnonymous)>0;for(let e=this.cursor(a|k.IncludeAnonymous);;){let a=!1;if(e.from<=i&&e.to>=r&&(!o&&e.type.isAnonymous||t(e)!==!1)){if(e.firstChild())continue;a=!0}for(;a&&n&&(o||!e.type.isAnonymous)&&n(e),!e.nextSibling();){if(!e.parent())return;a=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(t={}){return this.children.length<=8?this:Bt(vt.none,this.children,this.positions,0,this.children.length,0,this.length,(t,n,r)=>new e(this.type,t,n,r,this.propValues),t.makeTree||((t,n,r)=>new e(vt.none,t,n,r)))}static build(e){return Lt(e)}};A.empty=new A(vt.none,[],[],0);var St=class e{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new e(this.buffer,this.index)}},Ct=class e{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return vt.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(`,`)}childString(e){let t=this.buffer[e],n=this.buffer[e+3],r=this.set.types[t],i=r.name;if(/\W/.test(i)&&!r.isError&&(i=JSON.stringify(i)),e+=4,n==e)return i;let a=[];for(;e<n;)a.push(this.childString(e)),e=this.buffer[e+3];return i+`(`+a.join(`,`)+`)`}findChild(e,t,n,r,i){let{buffer:a}=this,o=-1;for(let s=e;s!=t&&!(wt(i,r,a[s+1],a[s+2])&&(o=s,n>0));s=a[s+3]);return o}slice(t,n,r){let i=this.buffer,a=new Uint16Array(n-t),o=0;for(let e=t,s=0;e<n;){a[s++]=i[e++],a[s++]=i[e++]-r;let n=a[s++]=i[e++]-r;a[s++]=i[e++]-t,o=Math.max(o,n)}return new e(a,o,this.set)}};function wt(e,t,n,r){switch(e){case-2:return n<t;case-1:return r>=t&&n<t;case 0:return n<t&&r>t;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function Tt(e,t,n,r){for(;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to<t);){let t=!r&&e instanceof Dt&&e.index<0?null:e.parent;if(!t)return e;e=t}let i=r?0:k.IgnoreOverlays;if(r)for(let r=e,a=r.parent;a;r=a,a=r.parent)r instanceof Dt&&r.index<0&&a.enter(t,n,i)?.from!=r.from&&(e=a);for(;;){let r=e.enter(t,n,i);if(!r)return e;e=r}}var Et=class{cursor(e=0){return new Ft(this,e)}getChild(e,t=null,n=null){let r=Ot(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return Ot(this,e,t,n)}resolve(e,t=0){return Tt(this,e,t,!1)}resolveInner(e,t=0){return Tt(this,e,t,!0)}matchContext(e){return kt(this.parent,e)}enterUnfinishedNodesBefore(e){let t=this.childBefore(e),n=this;for(;t;){let e=t.lastChild;if(!e||e.to!=t.to)break;e.type.isError&&e.from==e.to?(n=t,t=e.prevSibling):t=e}return n}get node(){return this}get next(){return this.parent}},Dt=class e extends Et{constructor(e,t,n,r){super(),this._tree=e,this.from=t,this.index=n,this._parent=r}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(t,n,r,i,a=0){for(let o=this;;){for(let{children:s,positions:c}=o._tree,l=n>0?s.length:-1;t!=l;t+=n){let l=s[t],u=c[t]+o.from,d;if(!(!(a&k.EnterBracketed&&l instanceof A&&(d=gt.get(l))&&!d.overlay&&d.bracketed&&r>=u&&r<=u+l.length)&&!wt(i,r,u,u+l.length))){if(l instanceof Ct){if(a&k.ExcludeBuffers)continue;let e=l.findChild(0,l.buffer.length,n,r-u,i);if(e>-1)return new jt(new At(o,l,t,u),null,e)}else if(a&k.IncludeAnonymous||!l.type.isAnonymous||It(l)){let s;if(!(a&k.IgnoreMounts)&&(s=gt.get(l))&&!s.overlay)return new e(s.tree,u,t,o);let c=new e(l,u,t,o);return a&k.IncludeAnonymous||!c.type.isAnonymous?c:c.nextChild(n<0?l.children.length-1:0,n,r,i,a)}}}if(a&k.IncludeAnonymous||!o.type.isAnonymous||(t=o.index>=0?o.index+n:n<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(t,n,r=0){let i;if(!(r&k.IgnoreOverlays)&&(i=gt.get(this._tree))&&i.overlay){let a=t-this.from,o=r&k.EnterBracketed&&i.bracketed;for(let{from:t,to:r}of i.overlay)if((n>0||o?t<=a:t<a)&&(n<0||o?r>=a:r>a))return new e(i.tree,i.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,t,n,r)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Ot(e,t,n,r){let i=e.cursor(),a=[];if(!i.firstChild())return a;if(n!=null){for(let e=!1;!e;)if(e=i.type.is(n),!i.nextSibling())return a}for(;;){if(r!=null&&i.type.is(r))return a;if(i.type.is(t)&&a.push(i.node),!i.nextSibling())return r==null?a:[]}}function kt(e,t,n=t.length-1){for(let r=e;n>=0;r=r.parent){if(!r)return!1;if(!r.type.isAnonymous){if(t[n]&&t[n]!=r.name)return!1;n--}}return!0}var At=class{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}},jt=class e extends Et{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,n){super(),this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(t,n,r){let{buffer:i}=this.context,a=i.findChild(this.index+4,i.buffer[this.index+3],t,n-this.context.start,r);return a<0?null:new e(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(t,n,r=0){if(r&k.ExcludeBuffers)return null;let{buffer:i}=this.context,a=i.findChild(this.index+4,i.buffer[this.index+3],n>0?1:-1,t-this.context.start,n);return a<0?null:new e(this.context,this,a)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:t}=this.context,n=t.buffer[this.index+3];return n<(this._parent?t.buffer[this._parent.index+3]:t.buffer.length)?new e(this.context,this._parent,n):this.externalSibling(1)}get prevSibling(){let{buffer:t}=this.context,n=this._parent?this._parent.index+4:0;return this.index==n?this.externalSibling(-1):new e(this.context,this._parent,t.findChild(n,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,i=n.buffer[this.index+3];if(i>r){let a=n.buffer[this.index+1];e.push(n.slice(r,i,a)),t.push(0)}return new A(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function Mt(e){if(!e.length)return null;let t=0,n=e[0];for(let r=1;r<e.length;r++){let i=e[r];(i.from>n.from||i.to<n.to)&&(n=i,t=r)}let r=n instanceof Dt&&n.index<0?null:n.parent,i=e.slice();return r?i[t]=r:i.splice(t,1),new Nt(i,n)}var Nt=class{constructor(e,t){this.heads=e,this.node=t}get next(){return Mt(this.heads)}};function Pt(e,t,n){let r=e.resolveInner(t,n),i=null;for(let e=r instanceof Dt?r:r.context.parent;e;e=e.parent)if(e.index<0){let a=e.parent;(i||=[r]).push(a.resolve(t,n)),e=a}else{let a=gt.get(e.tree);if(a&&a.overlay&&a.overlay[0].from<=t&&a.overlay[a.overlay.length-1].to>=t){let o=new Dt(a.tree,a.overlay[0].from+e.from,-1,e);(i||=[r]).push(Tt(o,t,n,!1))}}return i?Mt(i):r}var Ft=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~k.EnterBracketed,e instanceof Dt)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return e?e instanceof Dt?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,i=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=this.mode){return this.buffer?n&k.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&k.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&k.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index<r.buffer.buffer.length)return!1}else for(let e=0;e<this.index;e++)if(r.buffer.buffer[e+3]<this.index)return!1;({index:t,parent:n}=r)}else({index:t,_parent:n}=this._tree);for(;n;{index:t,_parent:n}=n)if(t>-1)for(let r=t+e,i=e<0?-1:n._tree.children.length;r!=i;r+=e){let e=n._tree.children[r];if(this.mode&k.IncludeAnonymous||e instanceof Ct||!e.type.isAnonymous||It(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,n=0;if(e&&e.context==this.buffer)scan:for(let r=this.index,i=this.stack.length;i>=0;){for(let a=e;a;a=a._parent)if(a.index==r){if(r==this.index)return a;t=a,n=i+1;break scan}r=this.stack[--i]}for(let e=n;e<this.stack.length;e++)t=new jt(this.buffer,t,this.stack[e]);return this.bufferNode=new jt(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let n=0;;){let r=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){n++;continue}this.type.isAnonymous||(r=!0)}for(;;){if(r&&t&&t(this),r=this.type.isAnonymous,!n)return;if(this.nextSibling())break;this.parent(),n--,r=!0}}}matchContext(e){if(!this.buffer)return kt(this.node.parent,e);let{buffer:t}=this.buffer,{types:n}=t.set;for(let r=e.length-1,i=this.stack.length-1;r>=0;i--){if(i<0)return kt(this._tree,e,r);let a=n[t.buffer[this.stack[i]]];if(!a.isAnonymous){if(e[r]&&e[r]!=a.name)return!1;r--}}return!0}};function It(e){return e.children.some(e=>e instanceof Ct||!e.type.isAnonymous||It(e))}function Lt(e){let{buffer:t,nodeSet:n,maxBufferLength:r=pt,reused:i=[],minRepeatType:a=n.types.length}=e,o=Array.isArray(t)?new St(t,t.length):t,s=n.types,c=0,l=0;function u(e,t,_,v,y,b){let{id:x,start:S,end:C,size:ee}=o,te=l,ne=c;if(ee<0){if(o.next(),ee==-1){let t=i[x];_.push(t),v.push(S-e);return}if(ee==-3){c=x;return}if(ee==-4){l=x;return}throw RangeError(`Unrecognized record size: ${ee}`)}let re=s[x],w,T,ie=S-e;if(C-S<=r&&(T=h(o.pos-t,y))){let t=new Uint16Array(T.size-T.skip),r=o.pos-T.size,i=t.length;for(;o.pos>r;)i=g(T.start,t,i);w=new Ct(t,C-T.start,n),ie=T.start-e}else{let e=o.pos-ee;o.next();let t=[],n=[],i=x>=a?x:-1,s=0,c=C;for(;o.pos>e;)i>=0&&o.id==i&&o.size>=0?(o.end<=c-r&&(p(t,n,S,s,o.end,c,i,te,ne),s=t.length,c=o.end),o.next()):b>2500?d(S,e,t,n):u(S,e,t,n,i,b+1);if(i>=0&&s>0&&s<t.length&&p(t,n,S,s,S,c,i,te,ne),t.reverse(),n.reverse(),i>-1&&s>0){let e=f(re,ne);w=Bt(re,t,n,0,t.length,0,C-S,e,e)}else w=m(re,t,n,C-S,te-C,ne)}_.push(w),v.push(ie)}function d(e,t,i,a){let s=[],c=0,l=-1;for(;o.pos>t;){let{id:e,start:t,end:n,size:i}=o;if(i>4)o.next();else if(l>-1&&t<l)break;else l<0&&(l=n-r),s.push(e,t,n),c++,o.next()}if(c){let t=new Uint16Array(c*4),r=s[s.length-2];for(let e=s.length-3,n=0;e>=0;e-=3)t[n++]=s[e],t[n++]=s[e+1]-r,t[n++]=s[e+2]-r,t[n++]=n;i.push(new Ct(t,s[2]-r,n)),a.push(r-e)}}function f(e,t){return(n,r,i)=>{let a=0,o=n.length-1,s,c;if(o>=0&&(s=n[o])instanceof A){if(!o&&s.type==e&&s.length==i)return s;(c=s.prop(O.lookAhead))&&(a=r[o]+s.length+c)}return m(e,n,r,i,a,t)}}function p(e,t,r,i,a,o,s,c,l){let u=[],d=[];for(;e.length>i;)u.push(e.pop()),d.push(t.pop()+r-a);e.push(m(n.types[s],u,d,o-a,c-o,l)),t.push(a-r)}function m(e,t,n,r,i,a,o){if(a){let e=[O.contextHash,a];o=o?[e].concat(o):[e]}if(i>25){let e=[O.lookAhead,i];o=o?[e].concat(o):[e]}return new A(e,t,n,r,o)}function h(e,t){let n=o.fork(),i=0,s=0,c=0,l=n.end-r,u={size:0,start:0,skip:0};scan:for(let r=n.pos-e;n.pos>r;){let e=n.size;if(n.id==t&&e>=0){u.size=i,u.start=s,u.skip=c,c+=4,i+=4,n.next();continue}let o=n.pos-e;if(e<0||o<r||n.start<l)break;let d=n.id>=a?4:0,f=n.start;for(n.next();n.pos>o;){if(n.size<0){if(n.size==-3||n.size==-4)d+=4;else break scan}else n.id>=a&&(d+=4);n.next()}s=f,i+=e,c+=d}return(t<0||i==e)&&(u.size=i,u.start=s,u.skip=c),u.size>4?u:void 0}function g(e,t,n){let{id:r,start:i,end:s,size:u}=o;if(o.next(),u>=0&&r<a){let a=n;if(u>4){let r=o.pos-(u-4);for(;o.pos>r;)n=g(e,t,n)}t[--n]=a,t[--n]=s-e,t[--n]=i-e,t[--n]=r}else u==-3?c=r:u==-4&&(l=r);return n}let _=[],v=[];for(;o.pos>0;)u(e.start||0,e.bufferStart||0,_,v,-1,0);let y=e.length??(_.length?v[0]+_[0].length:0);return new A(s[e.topID],_.reverse(),v.reverse(),y)}let Rt=new WeakMap;function zt(e,t){if(!e.isAnonymous||t instanceof Ct||t.type!=e)return 1;let n=Rt.get(t);if(n==null){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof A)){n=1;break}n+=zt(e,r)}Rt.set(t,n)}return n}function Bt(e,t,n,r,i,a,o,s,c){let l=0;for(let n=r;n<i;n++)l+=zt(e,t[n]);let u=Math.ceil(l*1.5/8),d=[],f=[];function p(t,n,r,i,o){for(let s=r;s<i;){let r=s,l=n[s],m=zt(e,t[s]);for(s++;s<i;s++){let n=zt(e,t[s]);if(m+n>=u)break;m+=n}if(s==r+1){if(m>u){let e=t[r];p(e.children,e.positions,0,e.children.length,n[r]+o);continue}d.push(t[r])}else{let i=n[s-1]+t[s-1].length-l;d.push(Bt(e,t,n,r,s,l,i,null,c))}f.push(l+o-a)}}return p(t,n,r,i,0),(s||c)(d,f,o)}var Vt=class e{constructor(e,t,n,r,i=!1,a=!1){this.from=e,this.to=t,this.tree=n,this.offset=r,this.open=!!i|(a?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(t,n=[],r=!1){let i=[new e(0,t.length,t,0,!1,r)];for(let e of n)e.to>t.length&&i.push(e);return i}static applyChanges(t,n,r=128){if(!n.length)return t;let i=[],a=1,o=t.length?t[0]:null;for(let s=0,c=0,l=0;;s++){let u=s<n.length?n[s]:null,d=u?u.fromA:1e9;if(d-c>=r)for(;o&&o.from<d;){let n=o;if(c>=n.from||d<=n.to||l){let t=Math.max(n.from,c)-l,r=Math.min(n.to,d)-l;n=t>=r?null:new e(t,r,n.tree,n.offset+l,s>0,!!u)}if(n&&i.push(n),o.to>d)break;o=a<t.length?t[a++]:null}if(!u)break;c=u.toA,l=u.toA-u.toB}return i}},Ht=class{startParse(e,t,n){return typeof e==`string`&&(e=new Ut(e)),n=n?n.length?n.map(e=>new ht(e.from,e.to)):[new ht(0,0)]:[new ht(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}},Ut=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};new O({perNode:!0});var Wt=class e{constructor(e,t,n,r,i,a,o,s,c,l=0,u){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=i,this.score=a,this.buffer=o,this.bufferBase=s,this.curContext=c,this.lookAhead=l,this.parent=u}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?`!`+this.score:``}`}static start(t,n,r=0){let i=t.parser.context;return new e(t,[],n,r,r,0,[],0,i?new Gt(i,i.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=e&65535,{parser:r}=this.p,i=this.reducePos<this.pos-25&&this.setLookAhead(this.pos),a=r.dynamicPrecedence(n);if(a&&(this.score+=a),t==0){n<r.minRepeatTerm&&this.reducePos<this.pos&&(this.reducePos=this.pos),this.pushState(r.getGoto(this.state,n,!0),this.reducePos),n<r.minRepeatTerm&&this.storeNode(n,this.reducePos,this.reducePos,i?8:4,!0),this.reduceContext(n,this.reducePos);return}let o=this.stack.length-(t-1)*3-(e&262144?6:0),s=o?this.stack[o-2]:this.p.ranges[0].from;n<r.minRepeatTerm&&s==this.reducePos&&this.reducePos<this.pos&&(this.reducePos=this.pos);let c=this.reducePos-s;c>=2e3&&!this.p.parser.nodeSet.types[n]?.isAnonymous&&(s==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSize<c&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=s,this.p.lastBigReductionSize=c));let l=o?this.stack[o-1]:0,u=this.bufferBase+this.buffer.length-l;if(n<r.minRepeatTerm||e&131072){let e=r.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(n,s,e,u+4,!0)}if(e&262144)this.state=this.stack[o];else{let e=this.stack[o-3];this.state=r.getGoto(e,n,!0)}for(;this.stack.length>o;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,i=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let e=this.buffer.length;if(e>0&&this.buffer[e-4]==0&&this.buffer[e-1]>-1){if(t==n)return;if(this.buffer[e-2]>=t){this.buffer[e-2]=n;return}}}if(!i||this.pos==n)this.buffer.push(e,t,n,r);else{let i=this.buffer.length;if(i>0&&(this.buffer[i-4]!=0||this.buffer[i-1]<0)){let e=!1;for(let t=i;t>0&&this.buffer[t-2]>n;t-=4)if(this.buffer[t-1]>=0){e=!0;break}if(e)for(;i>0&&this.buffer[i-2]>n;)this.buffer[i]=this.buffer[i-4],this.buffer[i+1]=this.buffer[i-3],this.buffer[i+2]=this.buffer[i-2],this.buffer[i+3]=this.buffer[i-1],i-=4,r>4&&(r-=4)}this.buffer[i]=e,this.buffer[i+1]=t,this.buffer[i+2]=n,this.buffer[i+3]=r}}shift(e,t,n,r){if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=r,this.shiftContext(t,n),t<=this.p.parser.maxNode&&this.buffer.push(t,n,r,4);else{let i=e,{parser:a}=this.p;this.pos=r;let o=a.stateFlag(i,1);!o&&(r>n||t<=a.maxNode)&&(this.reducePos=r),this.pushState(i,o?n:Math.min(n,this.reducePos)),this.shiftContext(t,n),t<=a.maxNode&&this.buffer.push(t,n,r,4)}}apply(e,t,n,r){e&65536?this.reduce(e):this.shift(e,t,n,r)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let t=this,n=t.buffer.length;for(n&&t.buffer[n-4]==0&&(n-=4);n>0&&t.buffer[n-2]>t.reducePos;)n-=4;let r=t.buffer.slice(n),i=t.bufferBase+n;for(;t&&i==t.bufferBase;)t=t.parent;return new e(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,r,i,this.curContext,this.lookAhead,t)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new Kt(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(n==0)return!1;if(!(n&65536))return!0;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r=0,i;r<t.length;r+=2)(i=t[r+1])!=this.state&&this.p.parser.hasAction(i,e)&&n.push(t[r],i);if(this.stack.length<120)for(let e=0;n.length<8&&e<t.length;e+=2){let r=t[e+1];n.some((e,t)=>t&1&&e==r)||n.push(t[e],r)}t=n}let n=[];for(let e=0;e<t.length&&n.length<4;e+=2){let r=t[e+1];if(r==this.state)continue;let i=this.split();i.pushState(r,this.pos),i.storeNode(0,i.pos,i.pos,4,!0),i.shiftContext(t[e],this.pos),i.reducePos=this.pos,i.score-=200,n.push(i)}return n}forceReduce(){let{parser:e}=this.p,t=e.stateSlot(this.state,5);if(!(t&65536))return!1;if(!e.validAction(this.state,t)){let n=t>>19,r=t&65535,i=this.stack.length-n*3;if(i<0||e.getGoto(this.stack[i],r,!1)<0){let e=this.findForcedReduction();if(e==null)return!1;t=e}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],n=(r,i)=>{if(!t.includes(r))return t.push(r),e.allActions(r,t=>{if(!(t&393216)){if(t&65536){let n=(t>>19)-i;if(n>1){let r=t&65535,i=this.stack.length-n*3;if(i>=0&&e.getGoto(this.stack[i],r,!1)>=0)return n<<19|65536|r}}else{let e=n(t,i+1);if(e!=null)return e}}})};return n(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new Gt(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){return e<=this.lookAhead?!1:(this.emitLookAhead(),this.lookAhead=e,!0)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},Gt=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},Kt=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,n=e>>19;n==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(n-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}},qt=class e{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(t,n=t.bufferBase+t.buffer.length){return new e(t,n,n-t.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new e(this.stack,this.pos,this.index)}};function Jt(e,t=Uint16Array){if(typeof e!=`string`)return e;let n=null;for(let r=0,i=0;r<e.length;){let a=0;for(;;){let t=e.charCodeAt(r++),n=!1;if(t==126){a=65535;break}t>=92&&t--,t>=34&&t--;let i=t-32;if(i>=46&&(i-=46,n=!0),a+=i,n)break;a*=46}n?n[i++]=a:n=new t(a)}return n}var Yt=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};let Xt=new Yt;var Zt=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk=``,this.chunkOff=0,this.chunk2=``,this.chunk2Pos=0,this.next=-1,this.token=Xt,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,i=this.pos+e;for(;i<n.from;){if(!r)return null;let e=this.ranges[--r];i-=n.from-e.to,n=e}for(;t<0?i>n.to:i>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];i+=e.from-n.to,n=e}return i}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,n,r;if(t>=0&&t<this.chunk.length)n=this.pos+e,r=this.chunk.charCodeAt(t);else{let t=this.resolveOffset(e,1);if(t==null)return-1;if(n=t,n>=this.chunk2Pos&&n<this.chunk2Pos+this.chunk2.length)r=this.chunk2.charCodeAt(n-this.chunk2Pos);else{let e=this.rangeIndex,t=this.range;for(;t.to<=n;)t=this.ranges[++e];this.chunk2=this.input.chunk(this.chunk2Pos=n),n+this.chunk2.length>t.to&&(this.chunk2=this.chunk2.slice(0,t.to-n)),r=this.chunk2.charCodeAt(0)}}return n>=this.token.lookAhead&&(this.token.lookAhead=n+1),r}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(n==null||n<this.token.start)throw RangeError(`Token end out of bounds`);this.token.value=e,this.token.end=n}acceptTokenTo(e,t){this.token.value=e,this.token.end=t}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.next=this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?-1:this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk=``,this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Xt,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk=``,this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n=``;for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}},Qt=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:n}=t.p;en(this.data,e,t,this.id,n.data,n.tokenPrecTable)}};Qt.prototype.contextual=Qt.prototype.fallback=Qt.prototype.extend=!1;var $t=class{constructor(e,t,n){this.precTable=t,this.elseToken=n,this.data=typeof e==`string`?Jt(e):e}token(e,t){let n=e.pos,r=0;for(;;){let n=e.next<0,i=e.resolveOffset(1,1);if(en(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(n||r++,i==null)break;e.reset(i,e.token)}r&&(e.reset(n,e.token),e.acceptToken(this.elseToken,r))}};$t.prototype.contextual=Qt.prototype.fallback=Qt.prototype.extend=!1;function en(e,t,n,r,i,a){let o=0,s=1<<r,{dialect:c}=n.p.parser;scan:for(;(s&e[o])!=0;){let n=e[o+1];for(let r=o+3;r<n;r+=2)if((e[r+1]&s)>0){let n=e[r];if(c.allows(n)&&(t.token.value==-1||t.token.value==n||nn(n,t.token.value,i,a))){t.acceptToken(n);break}}let r=t.next,l=0,u=e[o+2];if(t.next<0&&u>l&&e[n+u*3-3]==65535){o=e[n+u*3-1];continue scan}for(;l<u;){let i=l+u>>1,a=n+i+(i<<1),s=e[a],c=e[a+1]||65536;if(r<s)u=i;else if(r>=c)l=i+1;else{o=e[a+2],t.advance();continue scan}}break}}function tn(e,t,n){for(let r=t,i;(i=e[r])!=65535;r++)if(i==n)return r-t;return-1}function nn(e,t,n,r){let i=tn(n,r,t);return i<0||tn(n,r,e)<i}let j=typeof process<`u`&&/\bparse\b/.test({}.LOG),rn=null;function an(e,t,n){let r=e.cursor(k.IncludeAnonymous);for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.to<t:r.from>t)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}var on=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?an(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?an(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let n=this.trees[t],r=this.index[t];if(r==n.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let i=n.children[r],a=this.start[t]+n.positions[r];if(a>e)return this.nextStart=a,null;if(i instanceof A){if(a==e){if(a<this.safeFrom)return null;let e=a+i.length;if(e<=this.safeTo){let t=i.prop(O.lookAhead);if(!t||e+t<this.fragment.to)return i}}this.index[t]++,a+i.length>=Math.max(this.safeFrom,e)&&(this.trees.push(i),this.start.push(a),this.index.push(0))}else this.index[t]++,this.nextStart=a+i.length}}},sn=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(e=>new Yt)}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:i}=r,a=r.stateSlot(e.state,3),o=e.curContext?e.curContext.hash:0,s=0;for(let r=0;r<i.length;r++){if(!(1<<r&a))continue;let c=i[r],l=this.tokens[r];if(!(n&&!c.fallback)&&((c.contextual||l.start!=e.pos||l.mask!=a||l.context!=o)&&(this.updateCachedToken(l,c,e),l.mask=a,l.context=o),l.lookAhead>l.end+25&&(s=Math.max(l.lookAhead,s)),l.value!=0)){let r=t;if(l.extended>-1&&(t=this.addActions(e,l.extended,l.end,t)),t=this.addActions(e,l.value,l.end,t),!c.extend&&(n=l,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return s&&e.setLookAhead(s),!n&&e.pos==this.stream.end&&(n=new Yt,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Yt,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){let r=this.stream.clipPos(n.pos);if(t.token(this.stream.reset(r,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r<t.specialized.length;r++)if(t.specialized[r]==e.value){let i=t.specializers[r](this.stream.read(e.start,e.end),n);if(i>=0&&n.p.parser.dialect.allows(i>>1)){i&1?e.extended=i>>1:e.value=i>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,n,r){for(let t=0;t<r;t+=3)if(this.actions[t]==e)return r;return this.actions[r++]=e,this.actions[r++]=t,this.actions[r++]=n,r}addActions(e,t,n,r){let{state:i}=e,{parser:a}=e.p,{data:o}=a;for(let e=0;e<2;e++)for(let s=a.stateSlot(i,e?2:1);;s+=3){if(o[s]==65535){if(o[s+1]==1)s=fn(o,s+2);else{r==0&&o[s+1]==2&&(r=this.putAction(fn(o,s+2),t,n,r));break}}o[s]==t&&(r=this.putAction(fn(o,s+1),t,n,r))}return r}},cn=class{constructor(e,t,n,r){this.parser=e,this.input=t,this.ranges=r,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new Zt(t,r),this.tokens=new sn(e,this.stream),this.topTerm=e.top[1];let{from:i}=r[0];this.stacks=[Wt.start(this,e.top[0],i)],this.fragments=n.length&&this.stream.end-i>e.bufferLength*4?new on(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,n=this.stacks=[],r,i;if(this.bigReductionCount>300&&e.length==1){let[t]=e;for(;t.forceReduce()&&t.stack.length&&t.stack[t.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let a=0;a<e.length;a++){let o=e[a];for(;;){if(this.tokens.mainToken=null,o.pos>t)n.push(o);else if(this.advanceStack(o,n,e))continue;else{r||(r=[],i=[]),r.push(o);let e=this.tokens.getMainToken(o);i.push(e.value,e.end)}break}}if(!n.length){let e=r&&pn(r);if(e)return j&&console.log(`Finish with `+this.stackID(e)),this.stackToTree(e);if(this.parser.strict)throw j&&r&&console.log(`Stuck with token `+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):`none`)),SyntaxError(`No parse at `+t);this.recovering||=5}if(this.recovering&&r){let e=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,i,n);if(e)return j&&console.log(`Force-finish `+this.stackID(e)),this.stackToTree(e.forceAll())}if(this.recovering){let e=this.recovering==1?1:this.recovering*3;if(n.length>e)for(n.sort((e,t)=>t.score-e.score);n.length>e;)n.pop();n.some(e=>e.reducePos>t)&&this.recovering--}else if(n.length>1){outer:for(let e=0;e<n.length-1;e++){let t=n[e];for(let r=e+1;r<n.length;r++){let i=n[r];if(t.sameState(i)||t.buffer.length>500&&i.buffer.length>500){if((t.score-i.score||t.buffer.length-i.buffer.length)>0)n.splice(r--,1);else{n.splice(e--,1);continue outer}}}}n.length>12&&(n.sort((e,t)=>t.score-e.score),n.splice(12,n.length-12))}this.minStackPos=n[0].pos;for(let e=1;e<n.length;e++)n[e].pos<this.minStackPos&&(this.minStackPos=n[e].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw RangeError(`Can't move stoppedAt forward`);this.stoppedAt=e}advanceStack(e,t,n){let r=e.pos,{parser:i}=this,a=j?this.stackID(e)+` -> `:``;if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let o=this.fragments.nodeAt(r);o;){let r=this.parser.nodeSet.types[o.type.id]==o.type?i.getGoto(e.state,o.type.id):-1;if(r>-1&&o.length&&(!t||(o.prop(O.contextHash)||0)==n))return e.useNode(o,r),j&&console.log(a+this.stackID(e)+` (via reuse of ${i.getName(o.type.id)})`),!0;if(!(o instanceof A)||o.children.length==0||o.positions[0]>0)break;let s=o.children[0];if(s instanceof A&&o.positions[0]==0)o=s;else break}}let o=i.stateSlot(e.state,4);if(o>0)return e.reduce(o),j&&console.log(a+this.stackID(e)+` (via always-reduce ${i.getName(o&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let s=this.tokens.getActions(e);for(let o=0;o<s.length;){let c=s[o++],l=s[o++],u=s[o++],d=o==s.length||!n,f=d?e:e.split(),p=this.tokens.mainToken;if(f.apply(c,l,p?p.start:f.pos,u),j&&console.log(a+this.stackID(f)+` (via ${c&65536?`reduce of ${i.getName(c&65535)}`:`shift`} for ${i.getName(l)} @ ${r}${f==e?``:`, split`})`),d)return!0;f.pos>r?t.push(f):n.push(f)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return ln(e,t),!0}}runRecovery(e,t,n){let r=null,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=t[a<<1],c=t[(a<<1)+1],l=j?this.stackID(o)+` -> `:``;if(o.deadEnd&&(i||(i=!0,o.restart(),j&&console.log(l+this.stackID(o)+` (restarted)`),this.advanceFully(o,n))))continue;let u=o.split(),d=l;for(let e=0;e<10&&u.forceReduce()&&(j&&console.log(d+this.stackID(u)+` (via force-reduce)`),!this.advanceFully(u,n));e++)j&&(d=this.stackID(u)+` -> `);for(let e of o.recoverByInsert(s))j&&console.log(l+this.stackID(e)+` (via recover-insert)`),this.advanceFully(e,n);this.stream.end>o.pos?(c==o.pos&&(c++,s=0),o.recoverByDelete(s,c),j&&console.log(l+this.stackID(o)+` (via recover-delete ${this.parser.getName(s)})`),ln(o,n)):(!r||r.score<u.score)&&(r=u)}return r}stackToTree(e){return e.close(),A.build({buffer:qt.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(rn||=new WeakMap).get(e);return t||rn.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function ln(e,t){for(let n=0;n<t.length;n++){let r=t[n];if(r.pos==e.pos&&r.sameState(e)){t[n].score<e.score&&(t[n]=e);return}}t.push(e)}var un=class{constructor(e,t,n){this.source=e,this.flags=t,this.disabled=n}allows(e){return!this.disabled||this.disabled[e]==0}},dn=class e extends Ht{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(` `);this.minRepeatTerm=t.length;for(let n=0;n<e.repeatNodeCount;n++)t.push(``);let n=Object.keys(e.topRules).map(t=>e.topRules[t][1]),r=[];for(let e=0;e<t.length;e++)r.push([]);function i(e,t,n){r[e].push([t,t.deserialize(String(n))])}if(e.nodeProps)for(let t of e.nodeProps){let e=t[0];typeof e==`string`&&(e=O[e]);for(let n=1;n<t.length;){let r=t[n++];if(r>=0)i(r,e,t[n++]);else{let a=t[n+-r];for(let o=-r;o>0;o--)i(t[n++],e,a);n++}}}this.nodeSet=new yt(t.map((t,i)=>vt.define({name:i>=this.minRepeatTerm?void 0:t,id:i,props:r[i],top:n.indexOf(i)>-1,error:i==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(i)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=pt;let a=Jt(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let e=0;e<this.specializerSpecs.length;e++)this.specialized[e]=this.specializerSpecs[e].term;this.specializers=this.specializerSpecs.map(mn),this.states=Jt(e.states,Uint32Array),this.data=Jt(e.stateData),this.goto=Jt(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(e=>typeof e==`number`?new Qt(a,e):e),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new cn(this,e,t,n);for(let i of this.wrappers)r=i(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let i=r[t+1];;){let t=r[i++],a=t&1,o=r[i++];if(a&&n)return o;for(let n=i+(t>>1);i<n;i++)if(r[i]==e)return o;if(a)return-1}}hasAction(e,t){let n=this.data;for(let r=0;r<2;r++)for(let i=this.stateSlot(e,r?2:1),a;;i+=3){if((a=n[i])==65535){if(n[i+1]==1)a=n[i=fn(n,i+2)];else if(n[i+1]==2)return fn(n,i+2);else break}if(a==t||a==0)return fn(n,i+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){return!!this.allActions(e,e=>e==t||null)}allActions(e,t){let n=this.stateSlot(e,4),r=n?t(n):void 0;for(let n=this.stateSlot(e,1);r==null;n+=3){if(this.data[n]==65535){if(this.data[n+1]==1)n=fn(this.data,n+2);else break}r=t(fn(this.data,n+1))}return r}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(this.data[n]==65535){if(this.data[n+1]==1)n=fn(this.data,n+2);else break}if(!(this.data[n+2]&1)){let e=this.data[n+1];t.some((t,n)=>n&1&&t==e)||t.push(this.data[n],e)}}return t}configure(t){let n=Object.assign(Object.create(e.prototype),this);if(t.props&&(n.nodeSet=this.nodeSet.extend(...t.props)),t.top){let e=this.topRules[t.top];if(!e)throw RangeError(`Invalid top rule name ${t.top}`);n.top=e}return t.tokenizers&&(n.tokenizers=this.tokenizers.map(e=>{let n=t.tokenizers.find(t=>t.from==e);return n?n.to:e})),t.specializers&&(n.specializers=this.specializers.slice(),n.specializerSpecs=this.specializerSpecs.map((e,r)=>{let i=t.specializers.find(t=>t.from==e.external);if(!i)return e;let a=Object.assign(Object.assign({},e),{external:i.to});return n.specializers[r]=mn(a),a})),t.contextTracker&&(n.context=t.contextTracker),t.dialect&&(n.dialect=this.parseDialect(t.dialect)),t.strict!=null&&(n.strict=t.strict),t.wrap&&(n.wrappers=n.wrappers.concat(t.wrap)),t.bufferLength!=null&&(n.bufferLength=t.bufferLength),n}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map(()=>!1);if(e)for(let r of e.split(` `)){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;e<t.length;e++)if(!n[e])for(let n=this.dialects[t[e]],i;(i=this.data[n++])!=65535;)(r||=new Uint8Array(this.maxTerm+1))[i]=1;return new un(e,n,r)}static deserialize(t){return new e(t)}};function fn(e,t){return e[t]|e[t+1]<<16}function pn(e){let t=null;for(let n of e){let e=n.p.stoppedAt;(n.pos==n.p.stream.end||e!=null&&n.pos>e)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score<n.score)&&(t=n)}return t}function mn(e){if(e.external){let t=+!!e.extend;return(n,r)=>e.external(n,r)<<1|t}return e.get}let hn=dn.deserialize({version:14,states:"+^OVQPOOOOQO'#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%aQPO,59PO%fQPO'#CxO%nQPO1G.jOOQO1G.j1G.jOVQPO'#CyO%vQPO7+$OOOQO'#Cq'#CqOOQO1G.u1G.uO&OQPO1G.uO&WQPO1G.xOOQO,59a,59aOOQO-E6s-E6sO&]QPO'#CiO&qQPO'#CiO'PQPO'#ChOOQO1G.k1G.kO%XQPO1G.kOOQO,59d,59dOOQO-E6v-E6vOOQO7+$U7+$UO'[QPO'#CcOOQO,59e,59eOOQO-E6w-E6wO'jQPO'#CzO'oQPO7+$aOOQO7+$a7+$aO'wQPO7+$dO'|QPO'#CvO(RQPO,59TOOQO,59T,59TO%XQPO'#CwO(gQPO,59SOOQO7+$V7+$VO(rQPO,58}OOQO,59f,59fOOQO-E6x-E6xOOQO<<G{<<G{OOQO<<HO<<HOOOQO,59b,59bOOQO-E6t-E6tOOQO1G.o1G.oOOQO,59c,59cOOQO-E6u-E6uO)QQPO,58zO)VQPO'#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!OO_!PO~Or!SO~OTeOYgO~OvsOw!VO~OuvOoQq~Ov!ZOw!]O~OT!^O~O^!aOr!_Os!_Ou]Xv]Xw]X~O^!aOu]Xv]Xw]X~Ou!bOv[Xw[X~OsoOoVXtVXuVX~OTxO~Ov!ZOw!hO~Oy!iO~OT!jO~O^!lOr!_Os!_Ou]av]aw]a~Ou!bOv[aw[a~OsoOoVatVauVa~OT!WO~Or!oO~O",goto:"$^oPPps|P!T![!`!dP!j!q!wPP#OPp#TP#W#^PP#d#n#t#z$Q$WRWOQVOQk^R!XvQTOTj^vQROT!p^vTdY!oT]TjQi[R!TsSf[sRrgQ!RqR!d!SS!Qq!SR!m!bVUO^vRbVQzlR!f!ZQaVRnbQpcS}p!eR!e!WQ!`!OR!k!`Q!c!QR!n!cQtiR!UtQwkR!YwQ![zR!g![",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}),gn=[],_n=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?_n:gn).push(n+=e[t])})();function vn(e){if(e<768)return!1;for(let t=0,n=gn.length;;){let r=t+n>>1;if(e<gn[r])n=r;else if(e>=_n[r])t=r+1;else return!0;if(t==n)return!1}}function yn(e){return e>=127462&&e<=127487}let bn=8205;function xn(e,t,n=!0,r=!0){return(n?Sn:Cn)(e,t,r)}function Sn(e,t,n){if(t==e.length)return t;t&&Tn(e.charCodeAt(t))&&En(e.charCodeAt(t-1))&&t--;let r=wn(e,t);for(t+=Dn(r);t<e.length;){let i=wn(e,t);if(r==bn||i==bn||n&&vn(i))t+=Dn(i),r=i;else if(yn(i)){let n=0,r=t-2;for(;r>=0&&yn(wn(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function Cn(e,t,n){for(;t>0;){let r=Sn(e,t-2,n);if(r<t)return r;t--}return 0}function wn(e,t){let n=e.charCodeAt(t);if(!En(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return Tn(r)?(n-55296<<10)+(r-56320)+65536:n}function Tn(e){return e>=56320&&e<57344}function En(e){return e>=55296&&e<56320}function Dn(e){return e<65536?1:2}var M=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=Ln(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),kn.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Ln(this,e,t);let n=[];return this.decompose(e,t,n,0),kn.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new Nn(this),i=new Nn(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new Nn(this,e)}iterRange(e,t=this.length){return new Pn(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Fn(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new On(t):kn.from(On.split(t,[]))}},On=class e extends M{constructor(e,t=An(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new In(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(Mn(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=jn(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=Ln(this,t,n);let i=jn(this.text,jn(r.text,Mn(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):kn.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
3
+ `:/[\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]==="`"?Oe(`\`\`\`${h}`):null,_=a[0]==="`"?h.match(/^widget:([\w-]+)$/):null,v=a[0]==="`"?h.match(/^query(?:[:\s](.*))?$/i):null,y=t.registeredWidgets??De,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=Ee(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=ke(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=Ae(m.displayContent.trim()),a&&(c=!1),o.push(m),l=p+1}return o}function Me(e){return e.type===`time`||e.type===`log`?`wod`:e.type===`query`||e.type===`widget`||e.type===`embed`?e.type:null}function Ne(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 je(e,t)){let e=Me(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 Pe(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=Ne(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 Fe(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 Ie=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n,this.name=`StorageError`}};function Le(e,t){if(Object.is(e,t))return!0;if(e instanceof ArrayBuffer&&t instanceof ArrayBuffer){let n=new Uint8Array(e),r=new Uint8Array(t);return n.length===r.length&&n.every((e,t)=>e===r[t])}if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>Le(e,t[n]));let n=Object.keys(e).filter(t=>Reflect.get(e,t)!==void 0),r=Object.keys(t).filter(e=>Reflect.get(t,e)!==void 0);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&Le(Reflect.get(e,n),Reflect.get(t,n)))}function Re(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new Ie(400,`storage row must be an object`);return e}function ze(e,t){if(e!==`notes`&&e!==`block_revisions`&&e!==`sessions`&&e!==`block_index`)return;let n=Re(t),r=e=>typeof n[e]==`number`&&Number.isSafeInteger(n[e])&&n[e]>0,i=e=>typeof n[e]==`string`&&n[e].length>0;if(e===`notes`){if(!i(`id`)||typeof n.title!=`string`||typeof n.rawContent!=`string`||!r(`sourceRevision`)||typeof n.createdAt!=`number`||!Number.isFinite(n.createdAt)||`segments`in n||`segmentIds`in n||n.date!==void 0&&(typeof n.date!=`number`||!Number.isFinite(n.date))||n.seedOrigin!==void 0&&n.seedOrigin!==`seed`&&n.seedOrigin!==`user`||n.feedOrigin!==void 0&&n.feedOrigin!==`feed`&&n.feedOrigin!==`user`||n.feedOrigin===`feed`&&(n.seedOrigin===void 0||typeof n.feedSourceId!=`string`||n.feedSourceId.length===0)||n.feedOrigin===`user`&&n.seedOrigin===`seed`||n.feedSourceId!==void 0&&n.feedOrigin!==`feed`||n.seedVersion!==void 0&&!(typeof n.seedVersion==`number`&&Number.isSafeInteger(n.seedVersion)&&n.seedVersion>=0)||n.tags!==void 0&&(!Array.isArray(n.tags)||!n.tags.every(e=>typeof e==`string`))||[`type`,`sourceId`,`sourcePath`,`notebookId`,`seedChunkId`,`feedSourceId`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new Ie(400,`invalid whole Note`,`invalid_note_blocks`);try{Pe(n.rawContent,Re(n.blocks),n.sourceRevision)}catch(e){throw new Ie(400,e instanceof Error?e.message:`invalid block map`,`invalid_note_blocks`)}}else if(e===`block_revisions`){if(!i(`noteId`)||!i(`blockId`)||!r(`version`)||typeof n.rawContent!=`string`||typeof n.savedAt!=`number`||!Number.isFinite(n.savedAt)||![`wod`,`query`,`widget`,`embed`].includes(String(n.kind))||(n.kind===`wod`?n.dialect!==`time`&&n.dialect!==`log`:n.dialect!==void 0||n.sport!==void 0)||n.sport!==void 0&&typeof n.sport!=`string`)throw new Ie(400,`invalid block revision`,`invalid_note_blocks`);try{Pe(n.rawContent,{[String(n.blockId)]:{id:String(n.blockId),kind:n.kind,version:n.version,sourceRevision:1,from:0,to:n.rawContent.length,...n.dialect===void 0?{}:{dialect:n.dialect},...n.sport===void 0?{}:{sport:n.sport}}},1)}catch(e){throw new Ie(400,e instanceof Error?e.message:`invalid revision source`,`invalid_note_blocks`)}}else if(e===`sessions`){if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||[`segmentId`,`segmentVersion`,`version`,`rawContent`,`script`,`serializedScript`,`source`,`data`,`logs`].some(e=>e in n))throw new Ie(400,`Session requires immutable block pin`,`invalid_session_pin`)}else if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||!r(`sourceRevision`)||n.id!==`${n.noteId}:${n.blockId}`||!Number.isSafeInteger(n.from)||!Number.isSafeInteger(n.to)||`segmentId`in n||`segmentVersion`in n||![`wod`,`query`,`widget`,`embed`].includes(String(n.dataType))||typeof n.rawContent!=`string`||typeof n.noteTitle!=`string`||typeof n.from!=`number`||typeof n.to!=`number`||n.from<0||n.to<=n.from)throw new Ie(400,`invalid actionable block projection`,`invalid_note_blocks`)}function Be(e,t){if(e===void 0||Le(e,t))return;let n=Re(e),r=Re(t);if(typeof n.sourceRevision!=`number`||typeof r.sourceRevision!=`number`||r.sourceRevision<n.sourceRevision||(!Le(n.blocks,r.blocks)||n.rawContent!==r.rawContent)&&r.sourceRevision<=n.sourceRevision)throw new Ie(409,`stale Note source revision`,`transaction_conflict`)}function Ve(e,t){if(e===void 0)return;let n=Re(e),r=Re(t);if(n.noteId!==r.noteId||n.blockId!==r.blockId||n.blockVersion!==r.blockVersion)throw new Ie(409,`Session pin is immutable`,`invalid_session_pin`)}async function He(e,t,n){let r=[];for(let t of e)for(let e of Object.values(t.blocks))r.push([t.id,e.id,e.version]);for(let e of t)r.push([e.noteId,e.blockId,e.blockVersion]);let i=await n(r),a=0;for(let t of e)for(let e of Object.values(t.blocks)){let n=i[a++];if(!n||n.kind!==e.kind||n.rawContent!==t.rawContent.slice(e.from,e.to)||n.dialect!==e.dialect||n.sport!==e.sport)throw new Ie(409,`Note block has no matching immutable revision`,`invalid_note_blocks`)}for(let e=0;e<t.length;e++){let e=i[a++];if(!e||e.kind!==`wod`)throw new Ie(409,`Session pin must reference a saved workout revision`,`invalid_session_pin`)}}function Ue(e){if(!(typeof e!=`string`||!e.startsWith(`user-deleted-seed:`)))return e.slice(18)||void 0}function We(e){return typeof e==`string`&&e.startsWith(`seed:`)}function Ge(e){let t=new Set;for(let n of e)typeof n==`object`&&n&&`seedOrigin`in n&&n.seedOrigin===`seed`&&`id`in n&&typeof n.id==`string`&&t.add(n.id);return{seedNoteIds:t}}function Ke(e,t,n){if(typeof t!=`object`||!t)return!0;switch(e){case`notes`:return!(`seedOrigin`in t&&t.seedOrigin===`seed`);case`block_index`:case`block_efforts`:case`block_equipment`:return!(`isStatic`in t&&t.isStatic===!0&&`noteId`in t&&typeof t.noteId==`string`&&n.seedNoteIds.has(t.noteId));case`efforts`:case`equipment`:return!(`registrySource`in t&&t.registrySource===`bundled`);case`meta`:return!We(`key`in t?t.key:void 0);default:return!0}}Object.fromEntries(w.map(e=>[e.name,!0]));let qe=[`reps`,`distance`,`resistance`,`elapsed`,`power`,`pace`],Je=[`totalVolume`,`totalDistance`,`tis`,`sessionLoad`],Ye=[`sum`,`avg`,`min`,`max`,`count`,`last`,`delta`],Xe=[`domain`,`format`,`equipment`,`quality`,`intent`],Ze=[...Xe,`effort`,`discipline`,`intensity`,`grade`,`note`,`page`,`origin`,`grain`,`metric`,`block`,`result`,`tags`],Qe=[`effort`,`discipline`,`intensity`,`origin`,`text`],$e=[`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`],et=[`note`,`block`,`effort`,`session`,`segment`,`event`,`notebook`,`page`,`tag`,`equipment`],tt=[`note`,`notes`,`block`,`effort`,`session`,`segment`,`event`,`journal`,`notebook`,`notebooks`,`playground`,`page`,`tag`,`equipment`,`dashboard`],nt=Ye,rt=[`timeseries`,`bar`,`table`,`donut`,`toplist`,`value`],it=[`@session`,`@today`];[...Ze];let at=[`kg`,`lb`],ot={time:!0,groupby:!0,rollup:!0,unit:!0,where:!0,agg:!0},st=Ze.filter(e=>e!==`metric`),ct=Ze.filter(e=>e!==`tags`);[...st.map(e=>e===`tags`?`tag`:e)];let lt={notebook:new Set([`text`,`notebook`,`tag`,`effort`,...Xe,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`]),note:new Set([`text`,`notebook`,`tag`,`effort`,...Xe,`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([...Qe,`groupby`]),session:new Set([`result`,`block`,`note`,`plane`,`time`,`groupby`]),segment:new Set([...ct,`time`,`groupby`,`unit`]),event:new Set([...ct,`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`])},ut=Ze,dt=Object.fromEntries(Object.entries(lt).map(([e,t])=>[e,[...t].filter(e=>!ot[e]).map(e=>e===`tag`?`tags`:e)]));[...Ze],[...qe,...Je,...$e];function ft(e,t){return t===`aggregate`?ut:dt[e]??[]}let pt=1024,mt=0;var ht=class{constructor(e,t){this.from=e,this.to=t}},O=class{constructor(e={}){this.id=mt++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw Error(`This node type doesn't define a deserialize function`)}),this.combine=e.combine||null}add(e){if(this.perNode)throw RangeError(`Can't add per-node props to node types`);return typeof e!=`function`&&(e=vt.match(e)),t=>{let n=e(t);return n===void 0?null:[this,n]}}};O.closedBy=new O({deserialize:e=>e.split(` `)}),O.openedBy=new O({deserialize:e=>e.split(` `)}),O.group=new O({deserialize:e=>e.split(` `)}),O.isolate=new O({deserialize:e=>{if(e&&e!=`rtl`&&e!=`ltr`&&e!=`auto`)throw RangeError(`Invalid value for isolate: `+e);return e||`auto`}}),O.contextHash=new O({perNode:!0}),O.lookAhead=new O({perNode:!0}),O.mounted=new O({perNode:!0});var gt=class{constructor(e,t,n,r=!1){this.tree=e,this.overlay=t,this.parser=n,this.bracketed=r}static get(e){return e&&e.props&&e.props[O.mounted.id]}};let _t=Object.create(null);var vt=class e{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(t){let n=t.props&&t.props.length?Object.create(null):_t,r=!!t.top|(t.skipped?2:0)|(t.error?4:0)|(t.name==null?8:0),i=new e(t.name||``,n,t.id,r);if(t.props){for(let e of t.props)if(Array.isArray(e)||(e=e(i)),e){if(e[0].perNode)throw RangeError(`Can't store a per-node prop on a node type`);n[e[0].id]=e[1]}}return i}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e==`string`){if(this.name==e)return!0;let t=this.prop(O.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(` `))t[r]=e[n];return e=>{for(let n=e.prop(O.group),r=-1;r<(n?n.length:0);r++){let i=t[r<0?e.name:n[r]];if(i)return i}}}};vt.none=new vt(``,Object.create(null),0,8);var yt=class e{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw RangeError(`Node type ids should correspond to array positions when creating a node set`)}extend(...t){let n=[];for(let e of this.types){let r=null;for(let n of t){let t=n(e);if(t){r||=Object.assign({},e.props);let n=t[1],i=t[0];i.combine&&i.id in r&&(n=i.combine(r[i.id],n)),r[i.id]=n}}n.push(r?new vt(e.name,r,e.id,e.flags):e)}return new e(n)}};let bt=new WeakMap,xt=new WeakMap;var k;(function(e){e[e.ExcludeBuffers=1]=`ExcludeBuffers`,e[e.IncludeAnonymous=2]=`IncludeAnonymous`,e[e.IgnoreMounts=4]=`IgnoreMounts`,e[e.IgnoreOverlays=8]=`IgnoreOverlays`,e[e.EnterBracketed=16]=`EnterBracketed`})(k||={});var A=class e{constructor(e,t,n,r,i){if(this.type=e,this.children=t,this.positions=n,this.length=r,this.props=null,i&&i.length){this.props=Object.create(null);for(let[e,t]of i)this.props[typeof e==`number`?e:e.id]=t}}toString(){let e=gt.get(this);if(e&&!e.overlay)return e.tree.toString();let t=``;for(let e of this.children){let n=e.toString();n&&(t&&(t+=`,`),t+=n)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?`(`+t+`)`:``):t}cursor(e=0){return new Ft(this.topNode,e)}cursorAt(e,t=0,n=0){let r=new Ft(bt.get(this)||this.topNode);return r.moveTo(e,t),bt.set(this,r._tree),r}get topNode(){return new Dt(this,0,0,null)}resolve(e,t=0){let n=Tt(bt.get(this)||this.topNode,e,t,!1);return bt.set(this,n),n}resolveInner(e,t=0){let n=Tt(xt.get(this)||this.topNode,e,t,!0);return xt.set(this,n),n}resolveStack(e,t=0){return Pt(this,e,t)}iterate(e){let{enter:t,leave:n,from:r=0,to:i=this.length}=e,a=e.mode||0,o=(a&k.IncludeAnonymous)>0;for(let e=this.cursor(a|k.IncludeAnonymous);;){let a=!1;if(e.from<=i&&e.to>=r&&(!o&&e.type.isAnonymous||t(e)!==!1)){if(e.firstChild())continue;a=!0}for(;a&&n&&(o||!e.type.isAnonymous)&&n(e),!e.nextSibling();){if(!e.parent())return;a=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(t={}){return this.children.length<=8?this:Bt(vt.none,this.children,this.positions,0,this.children.length,0,this.length,(t,n,r)=>new e(this.type,t,n,r,this.propValues),t.makeTree||((t,n,r)=>new e(vt.none,t,n,r)))}static build(e){return Lt(e)}};A.empty=new A(vt.none,[],[],0);var St=class e{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new e(this.buffer,this.index)}},Ct=class e{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return vt.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(`,`)}childString(e){let t=this.buffer[e],n=this.buffer[e+3],r=this.set.types[t],i=r.name;if(/\W/.test(i)&&!r.isError&&(i=JSON.stringify(i)),e+=4,n==e)return i;let a=[];for(;e<n;)a.push(this.childString(e)),e=this.buffer[e+3];return i+`(`+a.join(`,`)+`)`}findChild(e,t,n,r,i){let{buffer:a}=this,o=-1;for(let s=e;s!=t&&!(wt(i,r,a[s+1],a[s+2])&&(o=s,n>0));s=a[s+3]);return o}slice(t,n,r){let i=this.buffer,a=new Uint16Array(n-t),o=0;for(let e=t,s=0;e<n;){a[s++]=i[e++],a[s++]=i[e++]-r;let n=a[s++]=i[e++]-r;a[s++]=i[e++]-t,o=Math.max(o,n)}return new e(a,o,this.set)}};function wt(e,t,n,r){switch(e){case-2:return n<t;case-1:return r>=t&&n<t;case 0:return n<t&&r>t;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function Tt(e,t,n,r){for(;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to<t);){let t=!r&&e instanceof Dt&&e.index<0?null:e.parent;if(!t)return e;e=t}let i=r?0:k.IgnoreOverlays;if(r)for(let r=e,a=r.parent;a;r=a,a=r.parent)r instanceof Dt&&r.index<0&&a.enter(t,n,i)?.from!=r.from&&(e=a);for(;;){let r=e.enter(t,n,i);if(!r)return e;e=r}}var Et=class{cursor(e=0){return new Ft(this,e)}getChild(e,t=null,n=null){let r=Ot(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return Ot(this,e,t,n)}resolve(e,t=0){return Tt(this,e,t,!1)}resolveInner(e,t=0){return Tt(this,e,t,!0)}matchContext(e){return kt(this.parent,e)}enterUnfinishedNodesBefore(e){let t=this.childBefore(e),n=this;for(;t;){let e=t.lastChild;if(!e||e.to!=t.to)break;e.type.isError&&e.from==e.to?(n=t,t=e.prevSibling):t=e}return n}get node(){return this}get next(){return this.parent}},Dt=class e extends Et{constructor(e,t,n,r){super(),this._tree=e,this.from=t,this.index=n,this._parent=r}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(t,n,r,i,a=0){for(let o=this;;){for(let{children:s,positions:c}=o._tree,l=n>0?s.length:-1;t!=l;t+=n){let l=s[t],u=c[t]+o.from,d;if(!(!(a&k.EnterBracketed&&l instanceof A&&(d=gt.get(l))&&!d.overlay&&d.bracketed&&r>=u&&r<=u+l.length)&&!wt(i,r,u,u+l.length))){if(l instanceof Ct){if(a&k.ExcludeBuffers)continue;let e=l.findChild(0,l.buffer.length,n,r-u,i);if(e>-1)return new jt(new At(o,l,t,u),null,e)}else if(a&k.IncludeAnonymous||!l.type.isAnonymous||It(l)){let s;if(!(a&k.IgnoreMounts)&&(s=gt.get(l))&&!s.overlay)return new e(s.tree,u,t,o);let c=new e(l,u,t,o);return a&k.IncludeAnonymous||!c.type.isAnonymous?c:c.nextChild(n<0?l.children.length-1:0,n,r,i,a)}}}if(a&k.IncludeAnonymous||!o.type.isAnonymous||(t=o.index>=0?o.index+n:n<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(t,n,r=0){let i;if(!(r&k.IgnoreOverlays)&&(i=gt.get(this._tree))&&i.overlay){let a=t-this.from,o=r&k.EnterBracketed&&i.bracketed;for(let{from:t,to:r}of i.overlay)if((n>0||o?t<=a:t<a)&&(n<0||o?r>=a:r>a))return new e(i.tree,i.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,t,n,r)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Ot(e,t,n,r){let i=e.cursor(),a=[];if(!i.firstChild())return a;if(n!=null){for(let e=!1;!e;)if(e=i.type.is(n),!i.nextSibling())return a}for(;;){if(r!=null&&i.type.is(r))return a;if(i.type.is(t)&&a.push(i.node),!i.nextSibling())return r==null?a:[]}}function kt(e,t,n=t.length-1){for(let r=e;n>=0;r=r.parent){if(!r)return!1;if(!r.type.isAnonymous){if(t[n]&&t[n]!=r.name)return!1;n--}}return!0}var At=class{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}},jt=class e extends Et{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,n){super(),this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(t,n,r){let{buffer:i}=this.context,a=i.findChild(this.index+4,i.buffer[this.index+3],t,n-this.context.start,r);return a<0?null:new e(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(t,n,r=0){if(r&k.ExcludeBuffers)return null;let{buffer:i}=this.context,a=i.findChild(this.index+4,i.buffer[this.index+3],n>0?1:-1,t-this.context.start,n);return a<0?null:new e(this.context,this,a)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:t}=this.context,n=t.buffer[this.index+3];return n<(this._parent?t.buffer[this._parent.index+3]:t.buffer.length)?new e(this.context,this._parent,n):this.externalSibling(1)}get prevSibling(){let{buffer:t}=this.context,n=this._parent?this._parent.index+4:0;return this.index==n?this.externalSibling(-1):new e(this.context,this._parent,t.findChild(n,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,i=n.buffer[this.index+3];if(i>r){let a=n.buffer[this.index+1];e.push(n.slice(r,i,a)),t.push(0)}return new A(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function Mt(e){if(!e.length)return null;let t=0,n=e[0];for(let r=1;r<e.length;r++){let i=e[r];(i.from>n.from||i.to<n.to)&&(n=i,t=r)}let r=n instanceof Dt&&n.index<0?null:n.parent,i=e.slice();return r?i[t]=r:i.splice(t,1),new Nt(i,n)}var Nt=class{constructor(e,t){this.heads=e,this.node=t}get next(){return Mt(this.heads)}};function Pt(e,t,n){let r=e.resolveInner(t,n),i=null;for(let e=r instanceof Dt?r:r.context.parent;e;e=e.parent)if(e.index<0){let a=e.parent;(i||=[r]).push(a.resolve(t,n)),e=a}else{let a=gt.get(e.tree);if(a&&a.overlay&&a.overlay[0].from<=t&&a.overlay[a.overlay.length-1].to>=t){let o=new Dt(a.tree,a.overlay[0].from+e.from,-1,e);(i||=[r]).push(Tt(o,t,n,!1))}}return i?Mt(i):r}var Ft=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~k.EnterBracketed,e instanceof Dt)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return e?e instanceof Dt?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,i=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=this.mode){return this.buffer?n&k.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&k.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&k.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index<r.buffer.buffer.length)return!1}else for(let e=0;e<this.index;e++)if(r.buffer.buffer[e+3]<this.index)return!1;({index:t,parent:n}=r)}else({index:t,_parent:n}=this._tree);for(;n;{index:t,_parent:n}=n)if(t>-1)for(let r=t+e,i=e<0?-1:n._tree.children.length;r!=i;r+=e){let e=n._tree.children[r];if(this.mode&k.IncludeAnonymous||e instanceof Ct||!e.type.isAnonymous||It(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,n=0;if(e&&e.context==this.buffer)scan:for(let r=this.index,i=this.stack.length;i>=0;){for(let a=e;a;a=a._parent)if(a.index==r){if(r==this.index)return a;t=a,n=i+1;break scan}r=this.stack[--i]}for(let e=n;e<this.stack.length;e++)t=new jt(this.buffer,t,this.stack[e]);return this.bufferNode=new jt(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let n=0;;){let r=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){n++;continue}this.type.isAnonymous||(r=!0)}for(;;){if(r&&t&&t(this),r=this.type.isAnonymous,!n)return;if(this.nextSibling())break;this.parent(),n--,r=!0}}}matchContext(e){if(!this.buffer)return kt(this.node.parent,e);let{buffer:t}=this.buffer,{types:n}=t.set;for(let r=e.length-1,i=this.stack.length-1;r>=0;i--){if(i<0)return kt(this._tree,e,r);let a=n[t.buffer[this.stack[i]]];if(!a.isAnonymous){if(e[r]&&e[r]!=a.name)return!1;r--}}return!0}};function It(e){return e.children.some(e=>e instanceof Ct||!e.type.isAnonymous||It(e))}function Lt(e){let{buffer:t,nodeSet:n,maxBufferLength:r=pt,reused:i=[],minRepeatType:a=n.types.length}=e,o=Array.isArray(t)?new St(t,t.length):t,s=n.types,c=0,l=0;function u(e,t,_,v,y,b){let{id:x,start:S,end:C,size:ee}=o,te=l,ne=c;if(ee<0){if(o.next(),ee==-1){let t=i[x];_.push(t),v.push(S-e);return}if(ee==-3){c=x;return}if(ee==-4){l=x;return}throw RangeError(`Unrecognized record size: ${ee}`)}let re=s[x],w,T,ie=S-e;if(C-S<=r&&(T=h(o.pos-t,y))){let t=new Uint16Array(T.size-T.skip),r=o.pos-T.size,i=t.length;for(;o.pos>r;)i=g(T.start,t,i);w=new Ct(t,C-T.start,n),ie=T.start-e}else{let e=o.pos-ee;o.next();let t=[],n=[],i=x>=a?x:-1,s=0,c=C;for(;o.pos>e;)i>=0&&o.id==i&&o.size>=0?(o.end<=c-r&&(p(t,n,S,s,o.end,c,i,te,ne),s=t.length,c=o.end),o.next()):b>2500?d(S,e,t,n):u(S,e,t,n,i,b+1);if(i>=0&&s>0&&s<t.length&&p(t,n,S,s,S,c,i,te,ne),t.reverse(),n.reverse(),i>-1&&s>0){let e=f(re,ne);w=Bt(re,t,n,0,t.length,0,C-S,e,e)}else w=m(re,t,n,C-S,te-C,ne)}_.push(w),v.push(ie)}function d(e,t,i,a){let s=[],c=0,l=-1;for(;o.pos>t;){let{id:e,start:t,end:n,size:i}=o;if(i>4)o.next();else if(l>-1&&t<l)break;else l<0&&(l=n-r),s.push(e,t,n),c++,o.next()}if(c){let t=new Uint16Array(c*4),r=s[s.length-2];for(let e=s.length-3,n=0;e>=0;e-=3)t[n++]=s[e],t[n++]=s[e+1]-r,t[n++]=s[e+2]-r,t[n++]=n;i.push(new Ct(t,s[2]-r,n)),a.push(r-e)}}function f(e,t){return(n,r,i)=>{let a=0,o=n.length-1,s,c;if(o>=0&&(s=n[o])instanceof A){if(!o&&s.type==e&&s.length==i)return s;(c=s.prop(O.lookAhead))&&(a=r[o]+s.length+c)}return m(e,n,r,i,a,t)}}function p(e,t,r,i,a,o,s,c,l){let u=[],d=[];for(;e.length>i;)u.push(e.pop()),d.push(t.pop()+r-a);e.push(m(n.types[s],u,d,o-a,c-o,l)),t.push(a-r)}function m(e,t,n,r,i,a,o){if(a){let e=[O.contextHash,a];o=o?[e].concat(o):[e]}if(i>25){let e=[O.lookAhead,i];o=o?[e].concat(o):[e]}return new A(e,t,n,r,o)}function h(e,t){let n=o.fork(),i=0,s=0,c=0,l=n.end-r,u={size:0,start:0,skip:0};scan:for(let r=n.pos-e;n.pos>r;){let e=n.size;if(n.id==t&&e>=0){u.size=i,u.start=s,u.skip=c,c+=4,i+=4,n.next();continue}let o=n.pos-e;if(e<0||o<r||n.start<l)break;let d=n.id>=a?4:0,f=n.start;for(n.next();n.pos>o;){if(n.size<0){if(n.size==-3||n.size==-4)d+=4;else break scan}else n.id>=a&&(d+=4);n.next()}s=f,i+=e,c+=d}return(t<0||i==e)&&(u.size=i,u.start=s,u.skip=c),u.size>4?u:void 0}function g(e,t,n){let{id:r,start:i,end:s,size:u}=o;if(o.next(),u>=0&&r<a){let a=n;if(u>4){let r=o.pos-(u-4);for(;o.pos>r;)n=g(e,t,n)}t[--n]=a,t[--n]=s-e,t[--n]=i-e,t[--n]=r}else u==-3?c=r:u==-4&&(l=r);return n}let _=[],v=[];for(;o.pos>0;)u(e.start||0,e.bufferStart||0,_,v,-1,0);let y=e.length??(_.length?v[0]+_[0].length:0);return new A(s[e.topID],_.reverse(),v.reverse(),y)}let Rt=new WeakMap;function zt(e,t){if(!e.isAnonymous||t instanceof Ct||t.type!=e)return 1;let n=Rt.get(t);if(n==null){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof A)){n=1;break}n+=zt(e,r)}Rt.set(t,n)}return n}function Bt(e,t,n,r,i,a,o,s,c){let l=0;for(let n=r;n<i;n++)l+=zt(e,t[n]);let u=Math.ceil(l*1.5/8),d=[],f=[];function p(t,n,r,i,o){for(let s=r;s<i;){let r=s,l=n[s],m=zt(e,t[s]);for(s++;s<i;s++){let n=zt(e,t[s]);if(m+n>=u)break;m+=n}if(s==r+1){if(m>u){let e=t[r];p(e.children,e.positions,0,e.children.length,n[r]+o);continue}d.push(t[r])}else{let i=n[s-1]+t[s-1].length-l;d.push(Bt(e,t,n,r,s,l,i,null,c))}f.push(l+o-a)}}return p(t,n,r,i,0),(s||c)(d,f,o)}var Vt=class e{constructor(e,t,n,r,i=!1,a=!1){this.from=e,this.to=t,this.tree=n,this.offset=r,this.open=!!i|(a?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(t,n=[],r=!1){let i=[new e(0,t.length,t,0,!1,r)];for(let e of n)e.to>t.length&&i.push(e);return i}static applyChanges(t,n,r=128){if(!n.length)return t;let i=[],a=1,o=t.length?t[0]:null;for(let s=0,c=0,l=0;;s++){let u=s<n.length?n[s]:null,d=u?u.fromA:1e9;if(d-c>=r)for(;o&&o.from<d;){let n=o;if(c>=n.from||d<=n.to||l){let t=Math.max(n.from,c)-l,r=Math.min(n.to,d)-l;n=t>=r?null:new e(t,r,n.tree,n.offset+l,s>0,!!u)}if(n&&i.push(n),o.to>d)break;o=a<t.length?t[a++]:null}if(!u)break;c=u.toA,l=u.toA-u.toB}return i}},Ht=class{startParse(e,t,n){return typeof e==`string`&&(e=new Ut(e)),n=n?n.length?n.map(e=>new ht(e.from,e.to)):[new ht(0,0)]:[new ht(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}},Ut=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};new O({perNode:!0});var Wt=class e{constructor(e,t,n,r,i,a,o,s,c,l=0,u){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=i,this.score=a,this.buffer=o,this.bufferBase=s,this.curContext=c,this.lookAhead=l,this.parent=u}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?`!`+this.score:``}`}static start(t,n,r=0){let i=t.parser.context;return new e(t,[],n,r,r,0,[],0,i?new Gt(i,i.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=e&65535,{parser:r}=this.p,i=this.reducePos<this.pos-25&&this.setLookAhead(this.pos),a=r.dynamicPrecedence(n);if(a&&(this.score+=a),t==0){n<r.minRepeatTerm&&this.reducePos<this.pos&&(this.reducePos=this.pos),this.pushState(r.getGoto(this.state,n,!0),this.reducePos),n<r.minRepeatTerm&&this.storeNode(n,this.reducePos,this.reducePos,i?8:4,!0),this.reduceContext(n,this.reducePos);return}let o=this.stack.length-(t-1)*3-(e&262144?6:0),s=o?this.stack[o-2]:this.p.ranges[0].from;n<r.minRepeatTerm&&s==this.reducePos&&this.reducePos<this.pos&&(this.reducePos=this.pos);let c=this.reducePos-s;c>=2e3&&!this.p.parser.nodeSet.types[n]?.isAnonymous&&(s==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSize<c&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=s,this.p.lastBigReductionSize=c));let l=o?this.stack[o-1]:0,u=this.bufferBase+this.buffer.length-l;if(n<r.minRepeatTerm||e&131072){let e=r.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(n,s,e,u+4,!0)}if(e&262144)this.state=this.stack[o];else{let e=this.stack[o-3];this.state=r.getGoto(e,n,!0)}for(;this.stack.length>o;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,i=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let e=this.buffer.length;if(e>0&&this.buffer[e-4]==0&&this.buffer[e-1]>-1){if(t==n)return;if(this.buffer[e-2]>=t){this.buffer[e-2]=n;return}}}if(!i||this.pos==n)this.buffer.push(e,t,n,r);else{let i=this.buffer.length;if(i>0&&(this.buffer[i-4]!=0||this.buffer[i-1]<0)){let e=!1;for(let t=i;t>0&&this.buffer[t-2]>n;t-=4)if(this.buffer[t-1]>=0){e=!0;break}if(e)for(;i>0&&this.buffer[i-2]>n;)this.buffer[i]=this.buffer[i-4],this.buffer[i+1]=this.buffer[i-3],this.buffer[i+2]=this.buffer[i-2],this.buffer[i+3]=this.buffer[i-1],i-=4,r>4&&(r-=4)}this.buffer[i]=e,this.buffer[i+1]=t,this.buffer[i+2]=n,this.buffer[i+3]=r}}shift(e,t,n,r){if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=r,this.shiftContext(t,n),t<=this.p.parser.maxNode&&this.buffer.push(t,n,r,4);else{let i=e,{parser:a}=this.p;this.pos=r;let o=a.stateFlag(i,1);!o&&(r>n||t<=a.maxNode)&&(this.reducePos=r),this.pushState(i,o?n:Math.min(n,this.reducePos)),this.shiftContext(t,n),t<=a.maxNode&&this.buffer.push(t,n,r,4)}}apply(e,t,n,r){e&65536?this.reduce(e):this.shift(e,t,n,r)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let t=this,n=t.buffer.length;for(n&&t.buffer[n-4]==0&&(n-=4);n>0&&t.buffer[n-2]>t.reducePos;)n-=4;let r=t.buffer.slice(n),i=t.bufferBase+n;for(;t&&i==t.bufferBase;)t=t.parent;return new e(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,r,i,this.curContext,this.lookAhead,t)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new Kt(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(n==0)return!1;if(!(n&65536))return!0;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r=0,i;r<t.length;r+=2)(i=t[r+1])!=this.state&&this.p.parser.hasAction(i,e)&&n.push(t[r],i);if(this.stack.length<120)for(let e=0;n.length<8&&e<t.length;e+=2){let r=t[e+1];n.some((e,t)=>t&1&&e==r)||n.push(t[e],r)}t=n}let n=[];for(let e=0;e<t.length&&n.length<4;e+=2){let r=t[e+1];if(r==this.state)continue;let i=this.split();i.pushState(r,this.pos),i.storeNode(0,i.pos,i.pos,4,!0),i.shiftContext(t[e],this.pos),i.reducePos=this.pos,i.score-=200,n.push(i)}return n}forceReduce(){let{parser:e}=this.p,t=e.stateSlot(this.state,5);if(!(t&65536))return!1;if(!e.validAction(this.state,t)){let n=t>>19,r=t&65535,i=this.stack.length-n*3;if(i<0||e.getGoto(this.stack[i],r,!1)<0){let e=this.findForcedReduction();if(e==null)return!1;t=e}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],n=(r,i)=>{if(!t.includes(r))return t.push(r),e.allActions(r,t=>{if(!(t&393216)){if(t&65536){let n=(t>>19)-i;if(n>1){let r=t&65535,i=this.stack.length-n*3;if(i>=0&&e.getGoto(this.stack[i],r,!1)>=0)return n<<19|65536|r}}else{let e=n(t,i+1);if(e!=null)return e}}})};return n(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new Gt(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){return e<=this.lookAhead?!1:(this.emitLookAhead(),this.lookAhead=e,!0)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},Gt=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},Kt=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,n=e>>19;n==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(n-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}},qt=class e{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(t,n=t.bufferBase+t.buffer.length){return new e(t,n,n-t.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new e(this.stack,this.pos,this.index)}};function Jt(e,t=Uint16Array){if(typeof e!=`string`)return e;let n=null;for(let r=0,i=0;r<e.length;){let a=0;for(;;){let t=e.charCodeAt(r++),n=!1;if(t==126){a=65535;break}t>=92&&t--,t>=34&&t--;let i=t-32;if(i>=46&&(i-=46,n=!0),a+=i,n)break;a*=46}n?n[i++]=a:n=new t(a)}return n}var Yt=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};let Xt=new Yt;var Zt=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk=``,this.chunkOff=0,this.chunk2=``,this.chunk2Pos=0,this.next=-1,this.token=Xt,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,i=this.pos+e;for(;i<n.from;){if(!r)return null;let e=this.ranges[--r];i-=n.from-e.to,n=e}for(;t<0?i>n.to:i>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];i+=e.from-n.to,n=e}return i}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,n,r;if(t>=0&&t<this.chunk.length)n=this.pos+e,r=this.chunk.charCodeAt(t);else{let t=this.resolveOffset(e,1);if(t==null)return-1;if(n=t,n>=this.chunk2Pos&&n<this.chunk2Pos+this.chunk2.length)r=this.chunk2.charCodeAt(n-this.chunk2Pos);else{let e=this.rangeIndex,t=this.range;for(;t.to<=n;)t=this.ranges[++e];this.chunk2=this.input.chunk(this.chunk2Pos=n),n+this.chunk2.length>t.to&&(this.chunk2=this.chunk2.slice(0,t.to-n)),r=this.chunk2.charCodeAt(0)}}return n>=this.token.lookAhead&&(this.token.lookAhead=n+1),r}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(n==null||n<this.token.start)throw RangeError(`Token end out of bounds`);this.token.value=e,this.token.end=n}acceptTokenTo(e,t){this.token.value=e,this.token.end=t}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.next=this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?-1:this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk=``,this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Xt,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk=``,this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n=``;for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}},Qt=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:n}=t.p;en(this.data,e,t,this.id,n.data,n.tokenPrecTable)}};Qt.prototype.contextual=Qt.prototype.fallback=Qt.prototype.extend=!1;var $t=class{constructor(e,t,n){this.precTable=t,this.elseToken=n,this.data=typeof e==`string`?Jt(e):e}token(e,t){let n=e.pos,r=0;for(;;){let n=e.next<0,i=e.resolveOffset(1,1);if(en(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(n||r++,i==null)break;e.reset(i,e.token)}r&&(e.reset(n,e.token),e.acceptToken(this.elseToken,r))}};$t.prototype.contextual=Qt.prototype.fallback=Qt.prototype.extend=!1;function en(e,t,n,r,i,a){let o=0,s=1<<r,{dialect:c}=n.p.parser;scan:for(;(s&e[o])!=0;){let n=e[o+1];for(let r=o+3;r<n;r+=2)if((e[r+1]&s)>0){let n=e[r];if(c.allows(n)&&(t.token.value==-1||t.token.value==n||nn(n,t.token.value,i,a))){t.acceptToken(n);break}}let r=t.next,l=0,u=e[o+2];if(t.next<0&&u>l&&e[n+u*3-3]==65535){o=e[n+u*3-1];continue scan}for(;l<u;){let i=l+u>>1,a=n+i+(i<<1),s=e[a],c=e[a+1]||65536;if(r<s)u=i;else if(r>=c)l=i+1;else{o=e[a+2],t.advance();continue scan}}break}}function tn(e,t,n){for(let r=t,i;(i=e[r])!=65535;r++)if(i==n)return r-t;return-1}function nn(e,t,n,r){let i=tn(n,r,t);return i<0||tn(n,r,e)<i}let j=typeof process<`u`&&/\bparse\b/.test({}.LOG),rn=null;function an(e,t,n){let r=e.cursor(k.IncludeAnonymous);for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.to<t:r.from>t)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}var on=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?an(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?an(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let n=this.trees[t],r=this.index[t];if(r==n.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let i=n.children[r],a=this.start[t]+n.positions[r];if(a>e)return this.nextStart=a,null;if(i instanceof A){if(a==e){if(a<this.safeFrom)return null;let e=a+i.length;if(e<=this.safeTo){let t=i.prop(O.lookAhead);if(!t||e+t<this.fragment.to)return i}}this.index[t]++,a+i.length>=Math.max(this.safeFrom,e)&&(this.trees.push(i),this.start.push(a),this.index.push(0))}else this.index[t]++,this.nextStart=a+i.length}}},sn=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(e=>new Yt)}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:i}=r,a=r.stateSlot(e.state,3),o=e.curContext?e.curContext.hash:0,s=0;for(let r=0;r<i.length;r++){if(!(1<<r&a))continue;let c=i[r],l=this.tokens[r];if(!(n&&!c.fallback)&&((c.contextual||l.start!=e.pos||l.mask!=a||l.context!=o)&&(this.updateCachedToken(l,c,e),l.mask=a,l.context=o),l.lookAhead>l.end+25&&(s=Math.max(l.lookAhead,s)),l.value!=0)){let r=t;if(l.extended>-1&&(t=this.addActions(e,l.extended,l.end,t)),t=this.addActions(e,l.value,l.end,t),!c.extend&&(n=l,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return s&&e.setLookAhead(s),!n&&e.pos==this.stream.end&&(n=new Yt,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Yt,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){let r=this.stream.clipPos(n.pos);if(t.token(this.stream.reset(r,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r<t.specialized.length;r++)if(t.specialized[r]==e.value){let i=t.specializers[r](this.stream.read(e.start,e.end),n);if(i>=0&&n.p.parser.dialect.allows(i>>1)){i&1?e.extended=i>>1:e.value=i>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,n,r){for(let t=0;t<r;t+=3)if(this.actions[t]==e)return r;return this.actions[r++]=e,this.actions[r++]=t,this.actions[r++]=n,r}addActions(e,t,n,r){let{state:i}=e,{parser:a}=e.p,{data:o}=a;for(let e=0;e<2;e++)for(let s=a.stateSlot(i,e?2:1);;s+=3){if(o[s]==65535){if(o[s+1]==1)s=fn(o,s+2);else{r==0&&o[s+1]==2&&(r=this.putAction(fn(o,s+2),t,n,r));break}}o[s]==t&&(r=this.putAction(fn(o,s+1),t,n,r))}return r}},cn=class{constructor(e,t,n,r){this.parser=e,this.input=t,this.ranges=r,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new Zt(t,r),this.tokens=new sn(e,this.stream),this.topTerm=e.top[1];let{from:i}=r[0];this.stacks=[Wt.start(this,e.top[0],i)],this.fragments=n.length&&this.stream.end-i>e.bufferLength*4?new on(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,n=this.stacks=[],r,i;if(this.bigReductionCount>300&&e.length==1){let[t]=e;for(;t.forceReduce()&&t.stack.length&&t.stack[t.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let a=0;a<e.length;a++){let o=e[a];for(;;){if(this.tokens.mainToken=null,o.pos>t)n.push(o);else if(this.advanceStack(o,n,e))continue;else{r||(r=[],i=[]),r.push(o);let e=this.tokens.getMainToken(o);i.push(e.value,e.end)}break}}if(!n.length){let e=r&&pn(r);if(e)return j&&console.log(`Finish with `+this.stackID(e)),this.stackToTree(e);if(this.parser.strict)throw j&&r&&console.log(`Stuck with token `+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):`none`)),SyntaxError(`No parse at `+t);this.recovering||=5}if(this.recovering&&r){let e=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,i,n);if(e)return j&&console.log(`Force-finish `+this.stackID(e)),this.stackToTree(e.forceAll())}if(this.recovering){let e=this.recovering==1?1:this.recovering*3;if(n.length>e)for(n.sort((e,t)=>t.score-e.score);n.length>e;)n.pop();n.some(e=>e.reducePos>t)&&this.recovering--}else if(n.length>1){outer:for(let e=0;e<n.length-1;e++){let t=n[e];for(let r=e+1;r<n.length;r++){let i=n[r];if(t.sameState(i)||t.buffer.length>500&&i.buffer.length>500){if((t.score-i.score||t.buffer.length-i.buffer.length)>0)n.splice(r--,1);else{n.splice(e--,1);continue outer}}}}n.length>12&&(n.sort((e,t)=>t.score-e.score),n.splice(12,n.length-12))}this.minStackPos=n[0].pos;for(let e=1;e<n.length;e++)n[e].pos<this.minStackPos&&(this.minStackPos=n[e].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw RangeError(`Can't move stoppedAt forward`);this.stoppedAt=e}advanceStack(e,t,n){let r=e.pos,{parser:i}=this,a=j?this.stackID(e)+` -> `:``;if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let o=this.fragments.nodeAt(r);o;){let r=this.parser.nodeSet.types[o.type.id]==o.type?i.getGoto(e.state,o.type.id):-1;if(r>-1&&o.length&&(!t||(o.prop(O.contextHash)||0)==n))return e.useNode(o,r),j&&console.log(a+this.stackID(e)+` (via reuse of ${i.getName(o.type.id)})`),!0;if(!(o instanceof A)||o.children.length==0||o.positions[0]>0)break;let s=o.children[0];if(s instanceof A&&o.positions[0]==0)o=s;else break}}let o=i.stateSlot(e.state,4);if(o>0)return e.reduce(o),j&&console.log(a+this.stackID(e)+` (via always-reduce ${i.getName(o&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let s=this.tokens.getActions(e);for(let o=0;o<s.length;){let c=s[o++],l=s[o++],u=s[o++],d=o==s.length||!n,f=d?e:e.split(),p=this.tokens.mainToken;if(f.apply(c,l,p?p.start:f.pos,u),j&&console.log(a+this.stackID(f)+` (via ${c&65536?`reduce of ${i.getName(c&65535)}`:`shift`} for ${i.getName(l)} @ ${r}${f==e?``:`, split`})`),d)return!0;f.pos>r?t.push(f):n.push(f)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return ln(e,t),!0}}runRecovery(e,t,n){let r=null,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=t[a<<1],c=t[(a<<1)+1],l=j?this.stackID(o)+` -> `:``;if(o.deadEnd&&(i||(i=!0,o.restart(),j&&console.log(l+this.stackID(o)+` (restarted)`),this.advanceFully(o,n))))continue;let u=o.split(),d=l;for(let e=0;e<10&&u.forceReduce()&&(j&&console.log(d+this.stackID(u)+` (via force-reduce)`),!this.advanceFully(u,n));e++)j&&(d=this.stackID(u)+` -> `);for(let e of o.recoverByInsert(s))j&&console.log(l+this.stackID(e)+` (via recover-insert)`),this.advanceFully(e,n);this.stream.end>o.pos?(c==o.pos&&(c++,s=0),o.recoverByDelete(s,c),j&&console.log(l+this.stackID(o)+` (via recover-delete ${this.parser.getName(s)})`),ln(o,n)):(!r||r.score<u.score)&&(r=u)}return r}stackToTree(e){return e.close(),A.build({buffer:qt.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(rn||=new WeakMap).get(e);return t||rn.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function ln(e,t){for(let n=0;n<t.length;n++){let r=t[n];if(r.pos==e.pos&&r.sameState(e)){t[n].score<e.score&&(t[n]=e);return}}t.push(e)}var un=class{constructor(e,t,n){this.source=e,this.flags=t,this.disabled=n}allows(e){return!this.disabled||this.disabled[e]==0}},dn=class e extends Ht{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(` `);this.minRepeatTerm=t.length;for(let n=0;n<e.repeatNodeCount;n++)t.push(``);let n=Object.keys(e.topRules).map(t=>e.topRules[t][1]),r=[];for(let e=0;e<t.length;e++)r.push([]);function i(e,t,n){r[e].push([t,t.deserialize(String(n))])}if(e.nodeProps)for(let t of e.nodeProps){let e=t[0];typeof e==`string`&&(e=O[e]);for(let n=1;n<t.length;){let r=t[n++];if(r>=0)i(r,e,t[n++]);else{let a=t[n+-r];for(let o=-r;o>0;o--)i(t[n++],e,a);n++}}}this.nodeSet=new yt(t.map((t,i)=>vt.define({name:i>=this.minRepeatTerm?void 0:t,id:i,props:r[i],top:n.indexOf(i)>-1,error:i==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(i)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=pt;let a=Jt(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let e=0;e<this.specializerSpecs.length;e++)this.specialized[e]=this.specializerSpecs[e].term;this.specializers=this.specializerSpecs.map(mn),this.states=Jt(e.states,Uint32Array),this.data=Jt(e.stateData),this.goto=Jt(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(e=>typeof e==`number`?new Qt(a,e):e),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new cn(this,e,t,n);for(let i of this.wrappers)r=i(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let i=r[t+1];;){let t=r[i++],a=t&1,o=r[i++];if(a&&n)return o;for(let n=i+(t>>1);i<n;i++)if(r[i]==e)return o;if(a)return-1}}hasAction(e,t){let n=this.data;for(let r=0;r<2;r++)for(let i=this.stateSlot(e,r?2:1),a;;i+=3){if((a=n[i])==65535){if(n[i+1]==1)a=n[i=fn(n,i+2)];else if(n[i+1]==2)return fn(n,i+2);else break}if(a==t||a==0)return fn(n,i+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){return!!this.allActions(e,e=>e==t||null)}allActions(e,t){let n=this.stateSlot(e,4),r=n?t(n):void 0;for(let n=this.stateSlot(e,1);r==null;n+=3){if(this.data[n]==65535){if(this.data[n+1]==1)n=fn(this.data,n+2);else break}r=t(fn(this.data,n+1))}return r}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(this.data[n]==65535){if(this.data[n+1]==1)n=fn(this.data,n+2);else break}if(!(this.data[n+2]&1)){let e=this.data[n+1];t.some((t,n)=>n&1&&t==e)||t.push(this.data[n],e)}}return t}configure(t){let n=Object.assign(Object.create(e.prototype),this);if(t.props&&(n.nodeSet=this.nodeSet.extend(...t.props)),t.top){let e=this.topRules[t.top];if(!e)throw RangeError(`Invalid top rule name ${t.top}`);n.top=e}return t.tokenizers&&(n.tokenizers=this.tokenizers.map(e=>{let n=t.tokenizers.find(t=>t.from==e);return n?n.to:e})),t.specializers&&(n.specializers=this.specializers.slice(),n.specializerSpecs=this.specializerSpecs.map((e,r)=>{let i=t.specializers.find(t=>t.from==e.external);if(!i)return e;let a=Object.assign(Object.assign({},e),{external:i.to});return n.specializers[r]=mn(a),a})),t.contextTracker&&(n.context=t.contextTracker),t.dialect&&(n.dialect=this.parseDialect(t.dialect)),t.strict!=null&&(n.strict=t.strict),t.wrap&&(n.wrappers=n.wrappers.concat(t.wrap)),t.bufferLength!=null&&(n.bufferLength=t.bufferLength),n}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map(()=>!1);if(e)for(let r of e.split(` `)){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;e<t.length;e++)if(!n[e])for(let n=this.dialects[t[e]],i;(i=this.data[n++])!=65535;)(r||=new Uint8Array(this.maxTerm+1))[i]=1;return new un(e,n,r)}static deserialize(t){return new e(t)}};function fn(e,t){return e[t]|e[t+1]<<16}function pn(e){let t=null;for(let n of e){let e=n.p.stoppedAt;(n.pos==n.p.stream.end||e!=null&&n.pos>e)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score<n.score)&&(t=n)}return t}function mn(e){if(e.external){let t=+!!e.extend;return(n,r)=>e.external(n,r)<<1|t}return e.get}let hn=dn.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}),gn=[],_n=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?_n:gn).push(n+=e[t])})();function vn(e){if(e<768)return!1;for(let t=0,n=gn.length;;){let r=t+n>>1;if(e<gn[r])n=r;else if(e>=_n[r])t=r+1;else return!0;if(t==n)return!1}}function yn(e){return e>=127462&&e<=127487}let bn=8205;function xn(e,t,n=!0,r=!0){return(n?Sn:Cn)(e,t,r)}function Sn(e,t,n){if(t==e.length)return t;t&&Tn(e.charCodeAt(t))&&En(e.charCodeAt(t-1))&&t--;let r=wn(e,t);for(t+=Dn(r);t<e.length;){let i=wn(e,t);if(r==bn||i==bn||n&&vn(i))t+=Dn(i),r=i;else if(yn(i)){let n=0,r=t-2;for(;r>=0&&yn(wn(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function Cn(e,t,n){for(;t>0;){let r=Sn(e,t-2,n);if(r<t)return r;t--}return 0}function wn(e,t){let n=e.charCodeAt(t);if(!En(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return Tn(r)?(n-55296<<10)+(r-56320)+65536:n}function Tn(e){return e>=56320&&e<57344}function En(e){return e>=55296&&e<56320}function Dn(e){return e<65536?1:2}var M=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=Ln(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),kn.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Ln(this,e,t);let n=[];return this.decompose(e,t,n,0),kn.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new Nn(this),i=new Nn(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new Nn(this,e)}iterRange(e,t=this.length){return new Pn(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Fn(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new On(t):kn.from(On.split(t,[]))}},On=class e extends M{constructor(e,t=An(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new In(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(Mn(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=jn(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=Ln(this,t,n);let i=jn(this.text,jn(r.text,Mn(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):kn.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
4
4
  `){[e,t]=Ln(this,e,t);let r=``;for(let i=0,a=0;i<=t&&a<this.text.length;a++){let o=this.text[a],s=i+o.length;i>e&&a&&(r+=n),e<s&&t>i&&(r+=o.slice(Math.max(0,e-i),t-i)),i=s+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(t,n){let r=[],i=-1;for(let a of t)r.push(a),i+=a.length+1,r.length==32&&(n.push(new e(r,i)),r=[],i=-1);return i>-1&&n.push(new e(r,i)),n}},kn=class e extends M{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let t of e)this.lines+=t.lines}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.children[i],o=r+a.length,s=n+a.lines-1;if((t?s:o)>=e)return a.lineInner(e,t,n,r);r=o+1,n=s+1}}decompose(e,t,n,r){for(let i=0,a=0;a<=t&&i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(e<=s&&t>=a){let i=r&(a<=e|(s>=t?2:0));a>=e&&s<=t&&!i?n.push(o):o.decompose(e-a,t-a,n,i)}a=s+1}}replace(t,n,r){if([t,n]=Ln(this,t,n),r.lines<this.lines)for(let i=0,a=0;i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(t>=a&&n<=s){let c=o.replace(t-a,n-a,r),l=this.lines-o.lines+c.lines;if(c.lines<l>>4&&c.lines>l>>6){let a=this.children.slice();return a[i]=c,new e(a,this.length-(n-t)+r.length)}return super.replace(a,s,c)}a=s+1}return super.replace(t,n,r)}sliceString(e,t=this.length,n=`
5
5
  `){[e,t]=Ln(this,e,t);let r=``;for(let i=0,a=0;i<this.children.length&&a<=t;i++){let o=this.children[i],s=a+o.length;a>e&&i&&(r+=n),e<s&&t>a&&(r+=o.sliceString(e-a,t-a,n)),a=s+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(t,n){if(!(t instanceof e))return 0;let r=0,[i,a,o,s]=n>0?[0,0,this.children.length,t.children.length]:[this.children.length-1,t.children.length-1,-1,-1];for(;;i+=n,a+=n){if(i==o||a==s)return r;let e=this.children[i],c=t.children[a];if(e!=c)return r+e.scanIdentical(c,n);r+=e.length+1}}static from(t,n=t.reduce((e,t)=>e+t.length+1,-1)){let r=0;for(let e of t)r+=e.lines;if(r<32){let e=[];for(let n of t)n.flatten(e);return new On(e,n)}let i=Math.max(32,r>>5),a=i<<1,o=i>>1,s=[],c=0,l=-1,u=[];function d(t){let n;if(t.lines>a&&t instanceof e)for(let e of t.children)d(e);else t.lines>o&&(c>o||!c)?(f(),s.push(t)):t instanceof On&&c&&(n=u[u.length-1])instanceof On&&t.lines+n.lines<=32?(c+=t.lines,l+=t.length+1,u[u.length-1]=new On(n.text.concat(t.text),n.length+1+t.length)):(c+t.lines>i&&f(),c+=t.lines,l+=t.length+1,u.push(t))}function f(){c!=0&&(s.push(u.length==1?u[0]:e.from(u,l)),l=-1,c=u.length=0)}for(let e of t)d(e);return f(),s.length==1?s[0]:new e(s,n)}};M.empty=new On([``],0);function An(e){let t=-1;for(let n of e)t+=n.length+1;return t}function jn(e,t,n=0,r=1e9){for(let i=0,a=0,o=!0;a<e.length&&i<=r;a++){let s=e[a],c=i+s.length;c>=n&&(c>r&&(s=s.slice(0,r-i)),i<n&&(s=s.slice(n-i)),o?(t[t.length-1]+=s,o=!1):t.push(s)),i=c+1}return t}function Mn(e,t,n){return jn(e,[``],t,n)}var Nn=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value=``,this.nodes=[e],this.offsets=[t>0?1:(e instanceof On?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,r=this.nodes[n],i=this.offsets[n],a=i>>1,o=r instanceof On?r.text.length:r.children.length;if(a==(t>0?o:0)){if(n==0)return this.done=!0,this.value=``,this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((i&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=`
6
6
  `,this;e--}else if(r instanceof On){let i=r.text[a+(t<0?-1:0)];if(this.offsets[n]+=t,i.length>Math.max(0,e))return this.value=e==0?i:t>0?i.slice(e):i.slice(0,i.length-e),this;e-=i.length}else{let i=r.children[a+(t<0?-1:0)];e>i.length?(e-=i.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(i),this.offsets.push(t>0?1:(i instanceof On?i.text.length:i.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Pn=class{constructor(e,t,n){this.value=``,this.done=!1,this.cursor=new Nn(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value=``,this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=n?r:t<0?r.slice(r.length-n):r.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=``}},Fn=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value=``,this.done=!1}next(e=0){let{done:t,lineBreak:n,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value=``,this.afterBreak=!1):t?(this.done=!0,this.value=``):n?this.afterBreak?this.value=``:(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<`u`&&(M.prototype[Symbol.iterator]=function(){return this.iter()},Nn.prototype[Symbol.iterator]=Pn.prototype[Symbol.iterator]=Fn.prototype[Symbol.iterator]=function(){return this});var In=class{constructor(e,t,n,r){this.from=e,this.to=t,this.number=n,this.text=r}get length(){return this.to-this.from}};function Ln(e,t,n){return t=Math.max(0,Math.min(e.length,t)),[t,Math.max(t,Math.min(e.length,n))]}function Rn(e,t,n=!0,r=!0){return xn(e,t,n,r)}let zn=/\r\n?|\n/;var Bn=(function(e){return e[e.Simple=0]=`Simple`,e[e.TrackDel=1]=`TrackDel`,e[e.TrackBefore=2]=`TrackBefore`,e[e.TrackAfter=3]=`TrackAfter`,e})(Bn||={}),Vn=class e{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t+1];e+=n<0?this.sections[t]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,n=0,r=0;t<this.sections.length;){let i=this.sections[t++],a=this.sections[t++];a<0?(e(n,r,i),r+=i):r+=a,n+=i}}iterChangedRanges(e,t=!1){Wn(this,e,t)}get invertedDesc(){let t=[];for(let e=0;e<this.sections.length;){let n=this.sections[e++],r=this.sections[e++];r<0?t.push(n,r):t.push(r,n)}return new e(t)}composeDesc(e){return this.empty?e:e.empty?this:Kn(this,e)}mapDesc(e,t=!1){return e.empty?this:Gn(this,e,t)}mapPos(e,t=-1,n=Bn.Simple){let r=0,i=0;for(let a=0;a<this.sections.length;){let o=this.sections[a++],s=this.sections[a++],c=r+o;if(s<0){if(c>e)return i+(e-r);i+=o}else{if(n!=Bn.Simple&&c>=e&&(n==Bn.TrackDel&&r<e&&c>e||n==Bn.TrackBefore&&r<e||n==Bn.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!o)return e==r||t<0?i:i+s;i+=s}r=c}if(e>r)throw RangeError(`Position ${e} is out of range for changeset of length ${r}`);return i}touchesRange(e,t=e){for(let n=0,r=0;n<this.sections.length&&r<=t;){let i=this.sections[n++],a=this.sections[n++],o=r+i;if(a>=0&&r<=t&&o>=e)return r<e&&o>t?`cover`:!0;r=o}return!1}toString(){let e=``;for(let t=0;t<this.sections.length;){let n=this.sections[t++],r=this.sections[t++];e+=(e?` `:``)+n+(r>=0?`:`+r:``)}return e}toJSON(){return this.sections}static fromJSON(t){if(!Array.isArray(t)||t.length%2||t.some(e=>typeof e!=`number`))throw RangeError(`Invalid JSON representation of ChangeDesc`);return new e(t)}static create(t){return new e(t)}},Hn=class e extends Vn{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw RangeError(`Applying change set to a document with the wrong length`);return Wn(this,(t,n,r,i,a)=>e=e.replace(r,r+(n-t),a),!1),e}mapDesc(e,t=!1){return Gn(this,e,t,!0)}invert(t){let n=this.sections.slice(),r=[];for(let e=0,i=0;e<n.length;e+=2){let a=n[e],o=n[e+1];if(o>=0){n[e]=o,n[e+1]=a;let s=e>>1;for(;r.length<s;)r.push(M.empty);r.push(a?t.slice(i,i+a):M.empty)}i+=a}return new e(n,r)}compose(e){return this.empty?e:e.empty?this:Kn(this,e,!0)}map(e,t=!1){return e.empty?this:Gn(this,e,t,!0)}iterChanges(e,t=!1){Wn(this,e,t)}get desc(){return Vn.create(this.sections)}filter(t){let n=[],r=[],i=[],a=new qn(this);done:for(let e=0,o=0;;){let s=e==t.length?1e9:t[e++];for(;o<s||o==s&&a.len==0;){if(a.done)break done;let e=Math.min(a.len,s-o);N(i,e,-1);let t=a.ins==-1?-1:a.off==0?a.ins:0;N(n,e,t),t>0&&Un(r,n,a.text),a.forward(e),o+=e}let c=t[e++];for(;o<c;){if(a.done)break done;let e=Math.min(a.len,c-o);N(n,e,-1),N(i,e,a.ins==-1?-1:a.off==0?a.ins:0),a.forward(e),o+=e}}return{changes:new e(n,r),filtered:Vn.create(i)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t],r=this.sections[t+1];r<0?e.push(n):r==0?e.push([n]):e.push([n].concat(this.inserted[t>>1].toJSON()))}return e}static of(t,n,r){let i=[],a=[],o=0,s=null;function c(t=!1){if(!t&&!i.length)return;o<n&&N(i,n-o,-1);let r=new e(i,a);s=s?s.compose(r.map(s)):r,i=[],a=[],o=0}function l(t){if(Array.isArray(t))for(let e of t)l(e);else if(t instanceof e){if(t.length!=n)throw RangeError(`Mismatched change set length (got ${t.length}, expected ${n})`);c(),s=s?s.compose(t.map(s)):t}else{let{from:e,to:s=e,insert:l}=t;if(e>s||e<0||s>n)throw RangeError(`Invalid change range ${e} to ${s} (in doc of length ${n})`);let u=l?typeof l==`string`?M.of(l.split(r||zn)):l:M.empty,d=u.length;if(e==s&&d==0)return;e<o&&c(),e>o&&N(i,e-o,-1),N(i,s-e,d),Un(a,i,u),o=s}}return l(t),c(!s),s}static empty(t){return new e(t?[t,-1]:[],[])}static fromJSON(t){if(!Array.isArray(t))throw RangeError(`Invalid JSON representation of ChangeSet`);let n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i==`number`)n.push(i,-1);else if(!Array.isArray(i)||typeof i[0]!=`number`||i.some((e,t)=>t&&typeof e!=`string`))throw RangeError(`Invalid JSON representation of ChangeSet`);else if(i.length==1)n.push(i[0],0);else{for(;r.length<e;)r.push(M.empty);r[e]=M.of(i.slice(1)),n.push(i[0],r[e].length)}}return new e(n,r)}static createSet(t,n){return new e(t,n)}};function N(e,t,n,r=!1){if(t==0&&n<=0)return;let i=e.length-2;i>=0&&n<=0&&n==e[i+1]?e[i]+=t:i>=0&&t==0&&e[i]==0?e[i+1]+=n:r?(e[i]+=t,e[i+1]+=n):e.push(t,n)}function Un(e,t,n){if(n.length==0)return;let r=t.length-2>>1;if(r<e.length)e[e.length-1]=e[e.length-1].append(n);else{for(;e.length<r;)e.push(M.empty);e.push(n)}}function Wn(e,t,n){let r=e.inserted;for(let i=0,a=0,o=0;o<e.sections.length;){let s=e.sections[o++],c=e.sections[o++];if(c<0)i+=s,a+=s;else{let l=i,u=a,d=M.empty;for(;l+=s,u+=c,c&&r&&(d=d.append(r[o-2>>1])),!(n||o==e.sections.length||e.sections[o+1]<0);)s=e.sections[o++],c=e.sections[o++];t(i,l,a,u,d),i=l,a=u}}}function Gn(e,t,n,r=!1){let i=[],a=r?[]:null,o=new qn(e),s=new qn(t);for(let e=-1;;)if(o.done&&s.len||s.done&&o.len)throw Error(`Mismatched change set lengths`);else if(o.ins==-1&&s.ins==-1){let e=Math.min(o.len,s.len);N(i,e,-1),o.forward(e),s.forward(e)}else if(s.ins>=0&&(o.ins<0||e==o.i||o.off==0&&(s.len<o.len||s.len==o.len&&!n))){let t=s.len;for(N(i,s.ins,-1);t;){let n=Math.min(o.len,t);o.ins>=0&&e<o.i&&o.len<=n&&(N(i,0,o.ins),a&&Un(a,i,o.text),e=o.i),o.forward(n),t-=n}s.next()}else if(o.ins>=0){let t=0,n=o.len;for(;n;)if(s.ins==-1){let e=Math.min(n,s.len);t+=e,n-=e,s.forward(e)}else if(s.ins==0&&s.len<n)n-=s.len,s.next();else break;N(i,t,e<o.i?o.ins:0),a&&e<o.i&&Un(a,i,o.text),e=o.i,o.forward(o.len-n)}else if(o.done&&s.done)return a?Hn.createSet(i,a):Vn.create(i);else throw Error(`Mismatched change set lengths`)}function Kn(e,t,n=!1){let r=[],i=n?[]:null,a=new qn(e),o=new qn(t);for(let e=!1;;)if(a.done&&o.done)return i?Hn.createSet(r,i):Vn.create(r);else if(a.ins==0)N(r,a.len,0,e),a.next();else if(o.len==0&&!o.done)N(r,0,o.ins,e),i&&Un(i,r,o.text),o.next();else if(a.done||o.done)throw Error(`Mismatched change set lengths`);else{let t=Math.min(a.len2,o.len),n=r.length;if(a.ins==-1){let n=o.ins==-1?-1:o.off?0:o.ins;N(r,t,n,e),i&&n&&Un(i,r,o.text)}else o.ins==-1?(N(r,a.off?0:a.len,t,e),i&&Un(i,r,a.textBit(t))):(N(r,a.off?0:a.len,o.off?0:o.ins,e),i&&!o.off&&Un(i,r,o.text));e=(a.ins>t||o.ins>=0&&o.len>t)&&(e||r.length>n),a.forward2(t),o.forward(t)}}var qn=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?M.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?M.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},Jn=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.flags=n,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(t,n=-1){let r,i;return this.empty?r=i=t.mapPos(this.from,n):(r=t.mapPos(this.from,1),i=t.mapPos(this.to,-1)),r==this.from&&i==this.to?this:new e(r,i,this.flags,this.goalColumn)}extend(e,t=e,n=0){if(e<=this.anchor&&t>=this.anchor)return P.range(e,t,void 0,void 0,n);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return P.range(this.anchor,r,void 0,void 0,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!=`number`||typeof e.head!=`number`)throw RangeError(`Invalid JSON representation for SelectionRange`);return P.range(e.anchor,e.head)}static create(t,n,r,i){return new e(t,n,r,i)}},P=class e{constructor(e,t){this.ranges=e,this.mainIndex=t}map(t,n=-1){return t.empty?this:e.create(this.ranges.map(e=>e.map(t,n)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new e([this.main],0)}addRange(t,n=!0){return e.create([t].concat(this.ranges),n?0:this.mainIndex+1)}replaceRange(t,n=this.mainIndex){let r=this.ranges.slice();return r[n]=t,e.create(r,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(t){if(!t||!Array.isArray(t.ranges)||typeof t.main!=`number`||t.main>=t.ranges.length)throw RangeError(`Invalid JSON representation for EditorSelection`);return new e(t.ranges.map(e=>Jn.fromJSON(e)),t.main)}static single(t,n=t){return new e([e.range(t,n)],0)}static create(t,n=0){if(t.length==0)throw RangeError(`A selection needs at least one range`);for(let r=0,i=0;i<t.length;i++){let a=t[i];if(a.empty?a.from<=r:a.from<r)return e.normalized(t.slice(),n);r=a.to}return new e(t,n)}static cursor(e,t=0,n,r){return Jn.create(e,e,(t==0?0:t<0?8:16)|(n==null?7:Math.min(6,n)),r)}static range(e,t,n,r,i){let a=r==null?7:Math.min(6,r);return!i&&e!=t&&(i=t<e?1:-1),i&&(a|=i<0?8:16),t<e?Jn.create(t,e,a|32,n):Jn.create(e,t,a,n)}static undirectionalRange(e,t){return Jn.create(e,t,64,void 0)}static normalized(t,n=0){let r=t[n];t.sort((e,t)=>e.from-t.from),n=t.indexOf(r);for(let r=1;r<t.length;r++){let i=t[r],a=t[r-1];if(i.empty?i.from<=a.to:i.from<a.to){let o=a.from,s=Math.max(i.to,a.to);r<=n&&n--,t.splice(--r,2,i.anchor>i.head?e.range(s,o):e.range(o,s))}}return new e(t,n)}};function Yn(e,t){for(let n of e.ranges)if(n.to>t)throw RangeError(`Selection points outside of document`)}let Xn=0;var F=class e{constructor(e,t,n,r,i){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=r,this.id=Xn++,this.default=e([]),this.extensions=typeof i==`function`?i(this):i}get reader(){return this}static define(t={}){return new e(t.combine||(e=>e),t.compareInput||((e,t)=>e===t),t.compare||(t.combine?(e,t)=>e===t:Zn),!!t.static,t.enables)}of(e){return new Qn([],this,0,e)}compute(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new Qn(e,this,1,t)}computeN(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new Qn(e,this,2,t)}from(e,t){return t||=e=>e,this.compute([e],n=>t(n.field(e)))}};function Zn(e,t){return e==t||e.length==t.length&&e.every((e,n)=>e===t[n])}var Qn=class{constructor(e,t,n,r){this.dependencies=e,this.facet=t,this.type=n,this.value=r,this.id=Xn++}dynamicSlot(e){let t=this.value,n=this.facet.compareInput,r=this.id,i=e[r]>>1,a=this.type==2,o=!1,s=!1,c=[];for(let t of this.dependencies)t==`doc`?o=!0:t==`selection`?s=!0:(e[t.id]??1)&1||c.push(e[t.id]);return{create(e){return e.values[i]=t(e),1},update(e,r){if(o&&r.docChanged||s&&(r.docChanged||r.selection)||er(e,c)){let r=t(e);if(a?!$n(r,e.values[i],n):!n(r,e.values[i]))return e.values[i]=r,1}return 0},reconfigure:(e,o)=>{let s,c=o.config.address[r];if(c!=null){let r=pr(o,c);if(this.dependencies.every(t=>t instanceof F?o.facet(t)===e.facet(t):t instanceof rr?o.field(t,!1)==e.field(t,!1):!0)||(a?$n(s=t(e),r,n):n(s=t(e),r)))return e.values[i]=r,0}else s=t(e);return e.values[i]=s,1}}}get extension(){return this}};function $n(e,t,n){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function er(e,t){let n=!1;for(let r of t)fr(e,r)&1&&(n=!0);return n}function tr(e,t,n){let r=n.map(t=>e[t.id]),i=n.map(e=>e.type),a=r.filter(e=>!(e&1)),o=e[t.id]>>1;function s(e){let n=[];for(let t=0;t<r.length;t++){let a=pr(e,r[t]);if(i[t]==2)for(let e of a)n.push(e);else n.push(a)}return t.combine(n)}return{create(e){for(let t of r)fr(e,t);return e.values[o]=s(e),1},update(e,n){if(!er(e,a))return 0;let r=s(e);return t.compare(r,e.values[o])?0:(e.values[o]=r,1)},reconfigure(e,i){let a=er(e,r),c=i.config.facets[t.id],l=i.facet(t);if(c&&!a&&Zn(n,c))return e.values[o]=l,0;let u=s(e);return t.compare(u,l)?(e.values[o]=l,0):(e.values[o]=u,1)}}}let nr=F.define({static:!0});var rr=class e{constructor(e,t,n,r,i){this.id=e,this.createF=t,this.updateF=n,this.compareF=r,this.spec=i,this.provides=void 0}static define(t){let n=new e(Xn++,t.create,t.update,t.compare||((e,t)=>e===t),t);return t.provide&&(n.provides=t.provide(n)),n}create(e){return(e.facet(nr).find(e=>e.field==this)?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:e=>(e.values[t]=this.create(e),1),update:(e,n)=>{let r=e.values[t],i=this.updateF(r,n);return this.compareF(r,i)?0:(e.values[t]=i,1)},reconfigure:(e,n)=>{let r=e.facet(nr),i=n.facet(nr),a;return(a=r.find(e=>e.field==this))&&a!=i.find(e=>e.field==this)?(e.values[t]=a.create(e),1):n.config.address[this.id]==null?(e.values[t]=this.create(e),1):(e.values[t]=n.field(this),0)}}}init(e){return[this,nr.of({field:this,create:e})]}get extension(){return this}};let ir={lowest:4,low:3,default:2,high:1,highest:0};function ar(e){return t=>new sr(t,e)}let or={highest:ar(ir.highest),high:ar(ir.high),default:ar(ir.default),low:ar(ir.low),lowest:ar(ir.lowest)};var sr=class{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}},cr=class e{of(e){return new lr(this,e)}reconfigure(t){return e.reconfigure.of({compartment:this,extension:t})}get(e){return e.config.compartments.get(this)}},lr=class{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}},ur=class e{constructor(e,t,n,r,i,a){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=r,this.staticValues=i,this.facets=a,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(t,n,r){let i=[],a=Object.create(null),o=new Map;for(let e of dr(t,n,o))e instanceof rr?i.push(e):(a[e.facet.id]||(a[e.facet.id]=[])).push(e);let s=Object.create(null),c=[],l=[];for(let e of i)s[e.id]=l.length<<1,l.push(t=>e.slot(t));let u=r?.config.facets;for(let e in a){let t=a[e],n=t[0].facet,i=u&&u[e]||[];if(t.every(e=>e.type==0)){if(s[n.id]=c.length<<1|1,Zn(i,t))c.push(r.facet(n));else{let e=n.combine(t.map(e=>e.value));c.push(r&&n.compare(e,r.facet(n))?r.facet(n):e)}}else{for(let e of t)e.type==0?(s[e.id]=c.length<<1|1,c.push(e.value)):(s[e.id]=l.length<<1,l.push(t=>e.dynamicSlot(t)));s[n.id]=l.length<<1,l.push(e=>tr(e,n,t))}}let d=l.map(e=>e(s));return new e(t,o,d,s,c,a)}};function dr(e,t,n){let r=[[],[],[],[],[]],i=new Map;function a(e,o){let s=i.get(e);if(s!=null){if(s<=o)return;let t=r[s].indexOf(e);t>-1&&r[s].splice(t,1),e instanceof lr&&n.delete(e.compartment)}if(i.set(e,o),Array.isArray(e))for(let t of e)a(t,o);else if(e instanceof lr){if(n.has(e.compartment))throw RangeError(`Duplicate use of compartment in extensions`);let r=t.get(e.compartment)||e.inner;n.set(e.compartment,r),a(r,o)}else if(e instanceof sr)a(e.inner,e.prec);else if(e instanceof rr)r[o].push(e),e.provides&&a(e.provides,o);else if(e instanceof Qn)r[o].push(e),e.facet.extensions&&a(e.facet.extensions,ir.default);else{let t=e.extension;if(!t)throw Error(`Unrecognized extension value in extension set (${e}).`);if(t==e)throw Error(`Unrecognized extension value in extension set (${e}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);a(t,o)}}return a(e,ir.default),r.reduce((e,t)=>e.concat(t))}function fr(e,t){if(t&1)return 2;let n=t>>1,r=e.status[n];if(r==4)throw Error(`Cyclic dependency between fields and/or facets`);if(r&2)return r;e.status[n]=4;let i=e.computeSlot(e,e.config.dynamicSlots[n]);return e.status[n]=2|i}function pr(e,t){return t&1?e.config.staticValues[t>>1]:e.values[t>>1]}let mr=F.define(),hr=F.define({combine:e=>e.some(e=>e),static:!0}),gr=F.define({combine:e=>e.length?e[0]:void 0,static:!0}),_r=F.define(),vr=F.define(),yr=F.define(),br=F.define({combine:e=>e.length?e[0]:!1});var xr=class{constructor(e,t){this.type=e,this.value=t}static define(){return new Sr}},Sr=class{of(e){return new xr(this,e)}},Cr=class{constructor(e){this.map=e}of(e){return new I(this,e)}},I=class e{constructor(e,t){this.type=e,this.value=t}map(t){let n=this.type.map(this.value,t);return n===void 0?void 0:n==this.value?this:new e(this.type,n)}is(e){return this.type==e}static define(e={}){return new Cr(e.map||(e=>e))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let r of e){let e=r.map(t);e&&n.push(e)}return n}};I.reconfigure=I.define(),I.appendConfig=I.define();var wr=class e{constructor(t,n,r,i,a,o){this.startState=t,this.changes=n,this.selection=r,this.effects=i,this.annotations=a,this.scrollIntoView=o,this._doc=null,this._state=null,r&&Yn(r,n.newLength),a.some(t=>t.type==e.time)||(this.annotations=a.concat(e.time.of(Date.now())))}static create(t,n,r,i,a,o){return new e(t,n,r,i,a,o)}get newDoc(){return this._doc||=this.changes.apply(this.startState.doc)}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(t){let n=this.annotation(e.userEvent);return!!(n&&(n==t||n.length>t.length&&n.slice(0,t.length)==t&&n[t.length]==`.`))}};wr.time=xr.define(),wr.userEvent=xr.define(),wr.addToHistory=xr.define(),wr.remote=xr.define();function Tr(e,t){let n=[];for(let r=0,i=0;;){let a,o;if(r<e.length&&(i==t.length||t[i]>=e[r]))a=e[r++],o=e[r++];else if(i<t.length)a=t[i++],o=t[i++];else return n;!n.length||n[n.length-1]<a?n.push(a,o):n[n.length-1]<o&&(n[n.length-1]=o)}}function Er(e,t,n){let r,i,a;return n?(r=t.changes,i=Hn.empty(t.changes.length),a=e.changes.compose(t.changes)):(r=t.changes.map(e.changes),i=e.changes.mapDesc(t.changes,!0),a=e.changes.compose(r)),{changes:a,selection:t.selection?t.selection.map(i):e.selection?.map(r),effects:I.mapEffects(e.effects,r).concat(I.mapEffects(t.effects,i)),annotations:e.annotations.length?e.annotations.concat(t.annotations):t.annotations,scrollIntoView:e.scrollIntoView||t.scrollIntoView}}function Dr(e,t,n){let r=t.selection,i=Mr(t.annotations);return t.userEvent&&(i=i.concat(wr.userEvent.of(t.userEvent))),{changes:t.changes instanceof Hn?t.changes:Hn.of(t.changes||[],n,e.facet(gr)),selection:r&&(r instanceof P?r:P.single(r.anchor,r.head)),effects:Mr(t.effects),annotations:i,scrollIntoView:!!t.scrollIntoView}}function Or(e,t,n){let r=Dr(e,t.length?t[0]:{},e.doc.length);t.length&&t[0].filter===!1&&(n=!1);for(let i=1;i<t.length;i++){t[i].filter===!1&&(n=!1);let a=!!t[i].sequential;r=Er(r,Dr(e,t[i],a?r.changes.newLength:e.doc.length),a)}let i=wr.create(e,r.changes,r.selection,r.effects,r.annotations,r.scrollIntoView);return Ar(n?kr(i):i)}function kr(e){let t=e.startState,n=!0;for(let r of t.facet(_r)){let t=r(e);if(t===!1){n=!1;break}Array.isArray(t)&&(n=n===!0?t:Tr(n,t))}if(n!==!0){let r,i;if(n===!1)i=e.changes.invertedDesc,r=Hn.empty(t.doc.length);else{let t=e.changes.filter(n);r=t.changes,i=t.filtered.mapDesc(t.changes).invertedDesc}e=wr.create(t,r,e.selection&&e.selection.map(i),I.mapEffects(e.effects,i),e.annotations,e.scrollIntoView)}let r=t.facet(vr);for(let n=r.length-1;n>=0;n--){let i=r[n](e);e=i instanceof wr?i:Array.isArray(i)&&i.length==1&&i[0]instanceof wr?i[0]:Or(t,Mr(i),!1)}return e}function Ar(e){let t=e.startState,n=t.facet(yr),r=e;for(let i=n.length-1;i>=0;i--){let a=n[i](e);a&&Object.keys(a).length&&(r=Er(r,Dr(t,a,e.changes.newLength),!0))}return r==e?e:wr.create(t,e.changes,e.selection,r.effects,r.annotations,r.scrollIntoView)}let jr=[];function Mr(e){return e==null?jr:Array.isArray(e)?e:[e]}var Nr=(function(e){return e[e.Word=0]=`Word`,e[e.Space=1]=`Space`,e[e.Other=2]=`Other`,e})(Nr||={});let Pr=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Fr;try{Fr=RegExp(`[\\p{Alphabetic}\\p{Number}_]`,`u`)}catch{}function Ir(e){if(Fr)return Fr.test(e);for(let t=0;t<e.length;t++){let n=e[t];if(/\w/.test(n)||n>`€`&&(n.toUpperCase()!=n.toLowerCase()||Pr.test(n)))return!0}return!1}function Lr(e){return t=>{if(!/\S/.test(t))return Nr.Space;if(Ir(t))return Nr.Word;for(let n=0;n<e.length;n++)if(t.indexOf(e[n])>-1)return Nr.Word;return Nr.Other}}var L=class e{constructor(e,t,n,r,i,a){this.config=e,this.doc=t,this.selection=n,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=i,a&&(a._state=this);for(let e=0;e<this.config.dynamicSlots.length;e++)fr(this,e<<1);this.computeSlot=null}field(e,t=!0){let n=this.config.address[e.id];if(n==null){if(t)throw RangeError(`Field is not present in this state`);return}return fr(this,n),pr(this,n)}update(...e){return Or(this,e,!0)}applyTransaction(t){let n=this.config,{base:r,compartments:i}=n;for(let e of t.effects)e.is(cr.reconfigure)?(n&&=(i=new Map,n.compartments.forEach((e,t)=>i.set(t,e)),null),i.set(e.value.compartment,e.value.extension)):e.is(I.reconfigure)?(n=null,r=e.value):e.is(I.appendConfig)&&(n=null,r=Mr(r).concat(e.value));let a;n?a=t.startState.values.slice():(n=ur.resolve(r,i,this),a=new e(n,this.doc,this.selection,n.dynamicSlots.map(()=>null),(e,t)=>t.reconfigure(e,this),null).values);let o=t.startState.facet(hr)?t.newSelection:t.newSelection.asSingle();new e(n,t.newDoc,o,a,(e,n)=>n.update(e,t),t)}replaceSelection(e){return typeof e==`string`&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:P.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),r=this.changes(n.changes),i=[n.range],a=Mr(n.effects);for(let n=1;n<t.ranges.length;n++){let o=e(t.ranges[n]),s=this.changes(o.changes),c=s.map(r);for(let e=0;e<n;e++)i[e]=i[e].map(c);let l=r.mapDesc(s,!0);i.push(o.range.map(l)),r=r.compose(c),a=I.mapEffects(a,c).concat(I.mapEffects(Mr(o.effects),l))}return{changes:r,selection:P.create(i,t.mainIndex),effects:a}}changes(t=[]){return t instanceof Hn?t:Hn.of(t,this.doc.length,this.facet(e.lineSeparator))}toText(t){return M.of(t.split(this.facet(e.lineSeparator)||zn))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(fr(this,t),pr(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let r=e[n];r instanceof rr&&this.config.address[r.id]!=null&&(t[n]=r.spec.toJSON(this.field(e[n]),this))}return t}static fromJSON(t,n={},r){if(!t||typeof t.doc!=`string`)throw RangeError(`Invalid JSON representation for EditorState`);let i=[];if(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(t,e)){let n=r[e],a=t[e];i.push(n.init(e=>n.spec.fromJSON(a,e)))}}return e.create({doc:t.doc,selection:P.fromJSON(t.selection),extensions:n.extensions?i.concat([n.extensions]):i})}static create(t={}){let n=ur.resolve(t.extensions||[],new Map),r=t.doc instanceof M?t.doc:M.of((t.doc||``).split(n.staticFacet(e.lineSeparator)||zn)),i=t.selection?t.selection instanceof P?t.selection:P.single(t.selection.anchor,t.selection.head):P.single(0);return Yn(i,r.length),n.staticFacet(hr)||(i=i.asSingle()),new e(n,r,i,n.dynamicSlots.map(()=>null),(e,t)=>t.create(e),null)}get tabSize(){return this.facet(e.tabSize)}get lineBreak(){return this.facet(e.lineSeparator)||`
@@ -12,5 +12,5 @@
12
12
  `))};if((V.mac||V.android)&&u.from==a-1&&/^\. ?$/.test(n.text)&&e.contentDOM.getAttribute(`autocorrect`)==`off`&&(u={from:o,to:s,insert:M.of([n.text.replace(`.`,` `)])}),this.pendingContextChange=u,!e.state.readOnly){let t=this.to-this.from+(u.to-u.from+u.insert.length);vs(e,u,P.single(this.toEditorPos(n.selectionStart,t),this.toEditorPos(n.selectionEnd,t)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from<u.to&&!u.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,n.updateRangeStart-1),Math.min(t.text.length,n.updateRangeStart+1)))&&this.handlers.compositionend(n)},this.handlers.characterboundsupdate=n=>{let r=[],i=null;for(let t=this.toEditorPos(n.rangeStart),a=this.toEditorPos(n.rangeEnd);t<a;t++){let n=e.coordsForChar(t);i=n&&new DOMRect(n.left,n.top,n.right-n.left,n.bottom-n.top)||i||new DOMRect,r.push(i)}t.updateCharacterBounds(n.rangeStart,r)},this.handlers.textformatupdate=t=>{let n=[];for(let e of t.getTextFormats()){let t=e.underlineStyle,r=e.underlineThickness;if(!/none/i.test(t)&&!/none/i.test(r)){let i=this.toEditorPos(e.rangeStart),a=this.toEditorPos(e.rangeEnd);if(i<a){let e=`text-decoration: underline ${/^[a-z]/.test(t)?t+` `:t==`Dashed`?`dashed `:t==`Squiggle`?`wavy `:``}${/thin/i.test(r)?1:2}px`;n.push(H.mark({attributes:{style:e}}).range(i,a))}}}e.dispatch({effects:Ga.of(H.set(n))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:t}=this.composing;this.composing=null,t&&this.reset(e.state)}};for(let e in this.handlers)t.addEventListener(e,this.handlers[e]);this.measureReq={read:e=>{let t=Ii(e.root);t&&t.rangeCount&&this.editContext.updateSelectionBounds(t.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,n=!1,r=this.pendingContextChange;return e.changes.iterChanges((i,a,o,s,c)=>{if(n)return;let l=c.length-(a-i);if(r&&a>=r.to){if(r.from==i&&r.to==a&&r.insert.eq(c)){r=this.pendingContextChange=null,t+=l,this.to+=l;return}r=null,this.revertPending(e.state)}if(i+=t,a+=t,a<=this.from)this.from+=l,this.to+=l;else if(i<this.to){if(i<this.from||a>this.to||this.to-this.from+c.length>3e4){n=!0;return}this.editContext.updateText(this.toContextPos(i),this.toContextPos(a),c.toString()),this.to+=l}t+=l}),r&&!n&&this.revertPending(e.state),!n}update(e){let t=this.pendingContextChange,n=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(n.from,n.to)&&e.transactions.some(e=>!e.isUserEvent(`input.type`)&&e.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,n=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),r=this.toContextPos(t.head);(this.editContext.selectionStart!=n||this.editContext.selectionEnd!=r)&&this.editContext.updateSelection(n,r)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>3e4)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let n=this.composing;return n&&n.drifted?n.editorBase+(e-n.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},J=class e{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement(`div`),this.scrollDOM=document.createElement(`div`),this.scrollDOM.tabIndex=-1,this.scrollDOM.className=`cm-scroller`,this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement(`div`),this.announceDOM.className=`cm-announced`,this.announceDOM.setAttribute(`aria-live`,`polite`),this.dom=document.createElement(`div`),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:t}=e;this.dispatchTransactions=e.dispatchTransactions||t&&(e=>e.forEach(e=>t(e,this)))||(e=>this.update(e)),this.dispatch=this.dispatch.bind(this),this._root=e.root||ia(e.parent)||document,this.viewState=new kc(this,e.state||L.create(e)),e.scrollTo&&e.scrollTo.is(Wa)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ya).map(e=>new Za(e));for(let e of this.plugins)e.update(this);this.observer=new Yc(this),this.inputState=new ws(this),this.inputState.ensureHandlers(this.plugins),this.docView=new zo(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),document.fonts?.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent=`refresh`,this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof wr?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(t){if(this.updateState!=0)throw Error(`Calls to EditorView.update are not allowed while an update is in progress`);let n=!1,r=!1,i,a=this.state;for(let e of t){if(e.startState!=a)throw RangeError(`Trying to update state with a transaction that doesn't start from the previous state.`);a=e.state}if(this.destroyed){this.viewState.state=a;return}let o=this.hasFocus,s=0,c=null;t.some(e=>e.annotation(tc))?(this.inputState.notifiedFocused=o,s=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,c=nc(a,o),c||(s=1));let l=this.observer.delayedAndroidKey,u=null;if(l?(this.observer.clearDelayedAndroidKey(),u=this.observer.readChange(),(u&&!this.state.doc.eq(a.doc)||!this.state.selection.eq(a.selection))&&(u=null)):this.observer.clear(),a.facet(L.phrases)!=this.state.facet(L.phrases))return this.setState(a);i=uo.create(this,a,t),i.flags|=s;let d=this.viewState.scrollTarget;try{this.updateState=2;for(let n of t){if(d&&=d.map(n.changes),n.scrollIntoView){let{main:t}=n.state.selection,{x:r,y:i}=this.state.facet(e.cursorScrollMargin);d=new Ua(t.empty?t:P.cursor(t.head,t.head>t.anchor?-1:1),`nearest`,`nearest`,i,r)}for(let e of n.effects)e.is(Wa)&&(d=e.value.clip(this.state))}this.viewState.update(i,d),this.bidiCache=nl.update(this.bidiCache,i.changes),i.empty||(this.updatePlugins(i),this.inputState.update(i)),n=this.docView.update(i),this.state.facet(co)!=this.styleModules&&this.mountStyles(),r=this.updateAttrs(),this.showAnnouncements(t),this.docView.updateSelection(n,t.some(e=>e.isUserEvent(`select.pointer`)))}finally{this.updateState=0}if(i.startState.facet(zc)!=i.state.facet(zc)&&(this.viewState.mustMeasureContent=!0),(n||r||d||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),n&&this.docViewUpdate(),!i.empty)for(let e of this.state.facet(Fa))try{e(i)}catch(e){Ka(this.state,e,`update listener`)}(c||u)&&Promise.resolve().then(()=>{c&&this.state==c.startState&&this.dispatch(c),u&&!_s(this,u)&&l.force&&ra(this.contentDOM,l.key,l.keyCode)})}setState(e){if(this.updateState!=0)throw Error(`Calls to EditorView.setState are not allowed while an update is in progress`);if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let e of this.plugins)e.destroy(this);this.viewState=new kc(this,e),this.plugins=e.facet(Ya).map(e=>new Za(e)),this.pluginMap.clear();for(let e of this.plugins)e.update(this);this.docView.destroy(),this.docView=new zo(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Ya),n=e.state.facet(Ya);if(t!=n){let r=[];for(let i of n){let n=t.indexOf(i);if(n<0)r.push(new Za(i));else{let t=this.plugins[n];t.mustUpdate=e,r.push(t)}}for(let t of this.plugins)t.mustUpdate!=e&&t.destroy(this);this.plugins=r,this.pluginMap.clear()}else for(let t of this.plugins)t.mustUpdate=e;for(let e=0;e<this.plugins.length;e++)this.plugins[e].update(this);t!=n&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let t=e.value;if(t&&t.docViewUpdate)try{t.docViewUpdate(this)}catch(e){Ka(this.state,e,`doc view update listener`)}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,n=this.viewState.scrollParent,r=this.viewState.getScrollOffset(),{scrollAnchorPos:i,scrollAnchorHeight:a}=this.viewState;Math.abs(r-this.viewState.scrollOffset)>1&&(a=-1),this.viewState.scrollAnchorHeight=-1;try{for(let e=0;;e++){if(a<0){if(oa(n||this.win))i=-1,a=this.viewState.heightMap.height;else{let e=this.viewState.scrollAnchorAt(r);i=e.from,a=e.top}}this.updateState=1;let o=this.viewState.measure();if(!o&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(e>5){console.warn(this.measureRequests.length?`Measure loop restarted more than 5 times`:`Viewport failed to stabilize`);break}let s=[];o&4||([this.measureRequests,s]=[s,this.measureRequests]);let c=s.map(e=>{try{return e.read(this)}catch(e){return Ka(this.state,e),tl}}),l=uo.create(this,this.state,[]),u=!1;l.flags|=o,t?t.flags|=o:t=l,this.updateState=2,l.empty||(this.updatePlugins(l),this.inputState.update(l),this.updateAttrs(),u=this.docView.update(l),u&&this.docViewUpdate());for(let e=0;e<s.length;e++)if(c[e]!=tl)try{let t=s[e];t.write&&t.write(c[e],this)}catch(e){Ka(this.state,e)}if(u&&this.docView.updateSelection(!0),!l.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight){if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,a=-1;continue}{let e=((i<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(i).top)-a)/this.scaleY;if((e>1||e<-1)&&!(V.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(n==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){r+=e,n?i<0?n.scrollTop=n.scrollHeight:n.scrollTop+=e:this.win.scrollBy(0,e),a=-1;continue}}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let e of this.state.facet(Fa))e(t)}get themeClasses(){return Vc+` `+(this.state.facet(Bc)?Uc:Hc)+` `+this.state.facet(zc)}updateAttrs(){let e=rl(this,Qa,{class:`cm-editor`+(this.hasFocus?` cm-focused `:` `)+this.themeClasses}),t={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,translate:`no`,contenteditable:this.state.facet(qa)?`true`:`false`,class:`cm-content`,style:`${V.tabSize}: ${this.state.tabSize}`,role:`textbox`,"aria-multiline":`true`};this.state.readOnly&&(t[`aria-readonly`]=`true`),rl(this,$a,t);let n=this.observer.ignore(()=>{let n=Ti(this.contentDOM,this.contentAttrs,t),r=Ti(this.dom,this.editorAttrs,e);return n||r});return this.editorAttrs=e,this.contentAttrs=t,n}showAnnouncements(t){let n=!0;for(let r of t)for(let t of r.effects)if(t.is(e.announce)){n&&(this.announceDOM.textContent=``),n=!1;let e=this.announceDOM.appendChild(document.createElement(`div`));e.textContent=t.value}}mountStyles(){this.styleModules=this.state.facet(co);let t=this.state.facet(e.cspNonce);ai.mount(this.root,this.styleModules.concat(Kc).reverse(),t?{nonce:t}:void 0)}readMeasured(){if(this.updateState==2)throw Error(`Reading the editor layout isn't allowed during an update`);this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;t<this.measureRequests.length;t++)if(this.measureRequests[t].key===e.key){this.measureRequests[t]=e;return}}this.measureRequests.push(e)}}plugin(e){let t=this.pluginMap.get(e);return(t===void 0||t&&t.plugin!=e)&&this.pluginMap.set(e,t=this.plugins.find(t=>t.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,n){return ss(this,e,ns(this,e,t,n))}moveByGroup(e,t){return ss(this,e,ns(this,e,t,t=>rs(this,e.head,t)))}visualLineSide(e,t){let n=this.bidiSpans(e),r=this.textDirectionAt(e.from),i=n[t?n.length-1:0];return P.cursor(i.side(t,r)+e.from,i.forward(!t,r)?1:-1)}moveToLineBoundary(e,t,n=!0){return ts(this,e,t,n)}moveVertically(e,t,n){return ss(this,e,is(this,e,t,n))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let n=ls(this,e,t);return n&&n.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),ls(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let n=this.state.doc.lineAt(e),r=this.bidiSpans(n),i=r[ya.find(r,e-n.from,-1,t)];return this.docView.coordsAt(e,t,i.dir==U.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Ba)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>el)return Da(e.length);let t=this.textDirectionAt(e.from),n;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||ba(r.isolates,n=ao(this,e))))return r.order;n||=ao(this,e);let r=Ea(e.text,t,n);return this.bidiCache.push(new nl(e.from,e.to,t,n,!0,r)),r}get hasFocus(){return(this.dom.ownerDocument.hasFocus()||V.safari&&this.inputState?.lastContextMenu>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{ea(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return Wa.of(new Ua(typeof e==`number`?P.cursor(e):e,t.y??`nearest`,t.x??`nearest`,t.yMargin??5,t.xMargin??5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return Wa.of(new Ua(P.cursor(n.from),`start`,`start`,n.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e==`boolean`?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return Xa.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return Xa.define(()=>({}),{eventObservers:e})}static theme(e,t){let n=ai.newName(),r=[zc.of(n),co.of(Gc(`.${n}`,e))];return t&&t.dark&&r.push(Bc.of(!0)),r}static baseTheme(e){return or.lowest(co.of(Gc(`.`+Vc,e,Wc)))}static findFromDOM(e){let t=e.querySelector(`.cm-content`);return(t&&G.get(t)||G.get(e))?.root?.view||null}};J.styleModule=co,J.inputHandler=Ia,J.clipboardInputFilter=Ra,J.clipboardOutputFilter=za,J.scrollHandler=Ha,J.focusChangeEffect=La,J.perLineTextDirection=Ba,J.exceptionSink=Pa,J.updateListener=Fa,J.editable=qa,J.mouseSelectionStyle=Na,J.dragMovesSelection=Ma,J.clickAddsSelectionRange=ja,J.decorations=eo,J.blockWrappers=to,J.outerDecorations=no,J.atomicRanges=ro,J.bidiIsolatedRanges=io,J.cursorScrollMargin=F.define({combine:e=>{let t=5,n=5;for(let r of e)typeof r==`number`?t=n=r:{x:t,y:n}=r;return{x:t,y:n}}}),J.scrollMargins=oo,J.darkTheme=Bc,J.cspNonce=F.define({combine:e=>e.length?e[0]:``}),J.contentAttributes=$a,J.editorAttributes=Qa,J.lineWrapping=J.contentAttributes.of({class:`cm-lineWrapping`}),J.announce=I.define();let el=4096,tl={};var nl=class e{constructor(e,t,n,r,i,a){this.from=e,this.to=t,this.dir=n,this.isolates=r,this.fresh=i,this.order=a}static update(t,n){if(n.empty&&!t.some(e=>e.fresh))return t;let r=[],i=t.length?t[t.length-1].dir:U.LTR;for(let a=Math.max(0,t.length-10);a<t.length;a++){let o=t[a];o.dir==i&&!n.touchesRange(o.from,o.to)&&r.push(new e(n.mapPos(o.from,1),n.mapPos(o.to,-1),o.dir,o.isolates,!1,o.order))}return r}};function rl(e,t,n){for(let r=e.state.facet(t),i=r.length-1;i>=0;i--){let t=r[i],a=typeof t==`function`?t(e):t;a&&xi(a,n)}return n}V.mac||V.windows||V.linux,V.gecko&&V.gecko_version,/x/.unicode;var il=class extends Rr{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};il.prototype.elementClass=``,il.prototype.toDOM=void 0,il.prototype.mapMode=Bn.TrackBefore,il.prototype.startSide=il.prototype.endSide=-1,il.prototype.point=!0;let al=0;var ol=class e{constructor(e,t,n,r){this.name=e,this.set=t,this.base=n,this.modified=r,this.id=al++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(t,n){let r=typeof t==`string`?t:`?`;if(t instanceof e&&(n=t),n?.base)throw Error(`Can not derive from a modified tag`);let i=new e(r,[],null,[]);if(i.set.push(i),n)for(let e of n.set)i.set.push(e);return i}static defineModifier(e){let t=new cl(e);return e=>e.modified.indexOf(t)>-1?e:cl.get(e.base||e,e.modified.concat(t).sort((e,t)=>e.id-t.id))}};let sl=0;var cl=class e{constructor(e){this.name=e,this.instances=[],this.id=sl++}static get(t,n){if(!n.length)return t;let r=n[0].instances.find(e=>e.base==t&&ll(n,e.modified));if(r)return r;let i=[],a=new ol(t.name,i,t,n);for(let e of n)e.instances.push(a);let o=ul(n);for(let n of t.set)if(!n.modified.length)for(let t of o)i.push(e.get(n,t));return a}};function ll(e,t){return e.length==t.length&&e.every((e,n)=>e==t[n])}function ul(e){let t=[[]];for(let n=0;n<e.length;n++)for(let r=0,i=t.length;r<i;r++)t.push(t[r].concat(e[n]));return t.sort((e,t)=>t.length-e.length)}function dl(e){let t=Object.create(null);for(let n in e){let r=e[n];Array.isArray(r)||(r=[r]);for(let e of n.split(` `))if(e){let n=[],i=2,a=e;for(let t=0;;){if(a==`...`&&t>0&&t+3==e.length){i=1;break}let r=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!r)throw RangeError(`Invalid path: `+e);if(n.push(r[0]==`*`?``:r[0][0]==`"`?JSON.parse(r[0]):r[0]),t+=r[0].length,t==e.length)break;let o=e[t++];if(t==e.length&&o==`!`){i=0;break}if(o!=`/`)throw RangeError(`Invalid path: `+e);a=e.slice(t)}let o=n.length-1,s=n[o];if(!s)throw RangeError(`Invalid path: `+e);t[s]=new pl(r,i,o>0?n.slice(0,o):null).sort(t[s])}}return fl.add(t)}let fl=new O({combine(e,t){let n,r,i;for(;e||t;){if(!e||t&&e.depth>=t.depth?(i=t,t=t.next):(i=e,e=e.next),n&&n.mode==i.mode&&!i.context&&!n.context)continue;let a=new pl(i.tags,i.mode,i.context);n?n.next=a:r=a,n=a}return r}});var pl=class{constructor(e,t,n,r){this.tags=e,this.mode=t,this.context=n,this.next=r}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}};pl.empty=new pl([],2,null);function ml(e,t){let n=Object.create(null);for(let t of e)if(!Array.isArray(t.tag))n[t.tag.id]=t.class;else for(let e of t.tag)n[e.id]=t.class;let{scope:r,all:i=null}=t||{};return{style:e=>{let t=i;for(let r of e)for(let e of r.set){let r=n[e.id];if(r){t=t?t+` `+r:r;break}}return t},scope:r}}let Y=ol.define,hl=Y(),gl=Y(),_l=Y(gl),vl=Y(gl),yl=Y(),bl=Y(yl),xl=Y(yl),Sl=Y(),Cl=Y(Sl),wl=Y(),Tl=Y(),El=Y(),Dl=Y(El),Ol=Y(),X={comment:hl,lineComment:Y(hl),blockComment:Y(hl),docComment:Y(hl),name:gl,variableName:Y(gl),typeName:_l,tagName:Y(_l),propertyName:vl,attributeName:Y(vl),className:Y(gl),labelName:Y(gl),namespace:Y(gl),macroName:Y(gl),literal:yl,string:bl,docString:Y(bl),character:Y(bl),attributeValue:Y(bl),number:xl,integer:Y(xl),float:Y(xl),bool:Y(yl),regexp:Y(yl),escape:Y(yl),color:Y(yl),url:Y(yl),keyword:wl,self:Y(wl),null:Y(wl),atom:Y(wl),unit:Y(wl),modifier:Y(wl),operatorKeyword:Y(wl),controlKeyword:Y(wl),definitionKeyword:Y(wl),moduleKeyword:Y(wl),operator:Tl,derefOperator:Y(Tl),arithmeticOperator:Y(Tl),logicOperator:Y(Tl),bitwiseOperator:Y(Tl),compareOperator:Y(Tl),updateOperator:Y(Tl),definitionOperator:Y(Tl),typeOperator:Y(Tl),controlOperator:Y(Tl),punctuation:El,separator:Y(El),bracket:Dl,angleBracket:Y(Dl),squareBracket:Y(Dl),paren:Y(Dl),brace:Y(Dl),content:Sl,heading:Cl,heading1:Y(Cl),heading2:Y(Cl),heading3:Y(Cl),heading4:Y(Cl),heading5:Y(Cl),heading6:Y(Cl),contentSeparator:Y(Sl),list:Y(Sl),quote:Y(Sl),emphasis:Y(Sl),strong:Y(Sl),link:Y(Sl),monospace:Y(Sl),strikethrough:Y(Sl),inserted:Y(),deleted:Y(),changed:Y(),invalid:Y(),meta:Ol,documentMeta:Y(Ol),annotation:Y(Ol),processingInstruction:Y(Ol),definition:ol.defineModifier(`definition`),constant:ol.defineModifier(`constant`),function:ol.defineModifier(`function`),standard:ol.defineModifier(`standard`),local:ol.defineModifier(`local`),special:ol.defineModifier(`special`)};for(let e in X){let t=X[e];t instanceof ol&&(t.name=e)}ml([{tag:X.link,class:`tok-link`},{tag:X.heading,class:`tok-heading`},{tag:X.emphasis,class:`tok-emphasis`},{tag:X.strong,class:`tok-strong`},{tag:X.keyword,class:`tok-keyword`},{tag:X.atom,class:`tok-atom`},{tag:X.bool,class:`tok-bool`},{tag:X.url,class:`tok-url`},{tag:X.labelName,class:`tok-labelName`},{tag:X.inserted,class:`tok-inserted`},{tag:X.deleted,class:`tok-deleted`},{tag:X.literal,class:`tok-literal`},{tag:X.string,class:`tok-string`},{tag:X.number,class:`tok-number`},{tag:[X.regexp,X.escape,X.special(X.string)],class:`tok-string2`},{tag:X.variableName,class:`tok-variableName`},{tag:X.local(X.variableName),class:`tok-variableName tok-local`},{tag:X.definition(X.variableName),class:`tok-variableName tok-definition`},{tag:X.special(X.variableName),class:`tok-variableName2`},{tag:X.definition(X.propertyName),class:`tok-propertyName tok-definition`},{tag:X.typeName,class:`tok-typeName`},{tag:X.namespace,class:`tok-namespace`},{tag:X.className,class:`tok-className`},{tag:X.macroName,class:`tok-macroName`},{tag:X.propertyName,class:`tok-propertyName`},{tag:X.operator,class:`tok-operator`},{tag:X.comment,class:`tok-comment`},{tag:X.meta,class:`tok-meta`},{tag:X.invalid,class:`tok-invalid`},{tag:X.punctuation,class:`tok-punctuation`}]);let kl=new O;function Al(e){return F.define({combine:e?t=>t.concat(e):void 0})}let jl=new O;var Ml=class{constructor(e,t,n=[],r=``){this.data=e,this.name=r,L.prototype.hasOwnProperty(`tree`)||Object.defineProperty(L.prototype,"tree",{get(){return Fl(this)}}),this.parser=t,this.extension=[Wl.of(this),L.languageData.of((e,t,n)=>{let r=Nl(e,t,n),i=r.type.prop(kl);if(!i)return[];let a=e.facet(i),o=r.type.prop(jl);if(o){let i=r.resolve(t-r.from,n);for(let t of o)if(t.test(i,e)){let n=e.facet(t.facet);return t.type==`replace`?n:n.concat(a)}}return a})].concat(n)}isActiveAt(e,t,n=-1){return Nl(e,t,n).type.prop(kl)==this.data}findRegions(e){let t=e.facet(Wl);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let n=[],r=(e,t)=>{if(e.prop(kl)==this.data){n.push({from:t,to:t+e.length});return}let i=e.prop(O.mounted);if(i){if(i.tree.prop(kl)==this.data){if(i.overlay)for(let e of i.overlay)n.push({from:e.from+t,to:e.to+t});else n.push({from:t,to:t+e.length});return}if(i.overlay){let e=n.length;if(r(i.tree,i.overlay[0].from+t),n.length>e)return}}for(let n=0;n<e.children.length;n++){let i=e.children[n];i instanceof A&&r(i,e.positions[n]+t)}};return r(Fl(e),0),n}get allowsNesting(){return!0}};Ml.setState=I.define();function Nl(e,t,n){let r=e.facet(Wl),i=Fl(e).topNode;if(!r||r.allowsNesting)for(let e=i;e;e=e.enter(t,n,k.ExcludeBuffers|k.EnterBracketed))e.type.isTop&&(i=e);return i}var Pl=class e extends Ml{constructor(e,t,n){super(e,t,[],n),this.parser=t}static define(t){let n=Al(t.languageData);return new e(n,t.parser.configure({props:[kl.add(e=>e.isTop?n:void 0)]}),t.name)}configure(t,n){return new e(this.data,this.parser.configure(t),n||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function Fl(e){let t=e.field(Ml.state,!1);return t?t.tree:A.empty}var Il=class{constructor(e){this.doc=e,this.cursorPos=0,this.string=``,this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let n=this.cursorPos-this.string.length;return e<n||t>=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-n,t-n)}};let Ll=null;var Rl=class e{constructor(e,t,n=[],r,i,a,o,s){this.parser=e,this.state=t,this.fragments=n,this.tree=r,this.treeLen=i,this.viewport=a,this.skipped=o,this.scheduleOn=s,this.parse=null,this.tempSkipped=[]}static create(t,n,r){return new e(t,n,[],A.empty,0,r,[],null)}startParse(){return this.parser.startParse(new Il(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=A.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{if(typeof e==`number`){let t=Date.now()+e;e=()=>Date.now()>t}for(this.parse||=this.startParse(),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t<this.state.doc.length&&this.parse.stopAt(t);;){let n=this.parse.advance();if(n){if(this.fragments=this.withoutTempSkipped(Vt.addTree(n,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=this.parse.stoppedAt??this.state.doc.length,this.tree=n,this.parse=null,this.treeLen<(t??this.state.doc.length))this.parse=this.startParse();else return!0}if(e())return!1}})}takeTree(){let e,t;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Vt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Ll;Ll=this;try{return e()}finally{Ll=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=zl(e,t.from,t.to);return e}changes(t,n){let{fragments:r,tree:i,treeLen:a,viewport:o,skipped:s}=this;if(this.takeTree(),!t.empty){let e=[];if(t.iterChangedRanges((t,n,r,i)=>e.push({fromA:t,toA:n,fromB:r,toB:i})),r=Vt.applyChanges(r,e),i=A.empty,a=0,o={from:t.mapPos(o.from,-1),to:t.mapPos(o.to,1)},this.skipped.length){s=[];for(let e of this.skipped){let n=t.mapPos(e.from,1),r=t.mapPos(e.to,-1);n<r&&s.push({from:n,to:r})}}}return new e(this.parser,n,r,i,a,o,s,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let t=this.skipped.length;for(let t=0;t<this.skipped.length;t++){let{from:n,to:r}=this.skipped[t];n<e.to&&r>e.from&&(this.fragments=zl(this.fragments,n,r),this.skipped.splice(t--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&=(this.takeTree(),null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends Ht{createParse(t,n,r){let i=r[0].from,a=r[r.length-1].to;return{parsedPos:i,advance(){let t=Ll;if(t){for(let e of r)t.tempSkipped.push(e);e&&(t.scheduleOn=t.scheduleOn?Promise.all([t.scheduleOn,e]):e)}return this.parsedPos=a,new A(vt.none,[],[],a-i)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Ll}};function zl(e,t,n){return Vt.applyChanges(e,[{fromA:t,toA:n,fromB:t,toB:n}])}var Bl=class e{constructor(e){this.context=e,this.tree=e.tree}apply(t){if(!t.docChanged&&this.tree==this.context.tree)return this;let n=this.context.changes(t.changes,t.state),r=this.context.treeLen==t.startState.doc.length?void 0:Math.max(t.changes.mapPos(this.context.treeLen),n.viewport.to);return n.work(20,r)||n.takeTree(),new e(n)}static init(t){let n=Math.min(3e3,t.doc.length),r=Rl.create(t.facet(Wl).parser,t,{from:0,to:n});return r.work(20,n)||r.takeTree(),new e(r)}};Ml.state=rr.define({create:Bl.init,update(e,t){for(let e of t.effects)if(e.is(Ml.setState))return e.value;return t.startState.facet(Wl)==t.state.facet(Wl)?e.apply(t):Bl.init(t.state)}});let Vl=e=>{let t=setTimeout(()=>e(),500);return()=>clearTimeout(t)};typeof requestIdleCallback<`u`&&(Vl=e=>{let t=-1,n=setTimeout(()=>{t=requestIdleCallback(e,{timeout:400})},100);return()=>t<0?clearTimeout(n):cancelIdleCallback(t)});let Hl=typeof navigator<`u`&&navigator.scheduling?.isInputPending?()=>navigator.scheduling.isInputPending():null,Ul=Xa.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Ml.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Ml.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Vl(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnd<t&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=t+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:n,viewport:{to:r}}=this.view,i=n.field(Ml.state);if(i.tree==i.context.tree&&i.context.isDone(r+1e5))return;let a=Date.now()+Math.min(this.chunkBudget,100,e&&!Hl?Math.max(25,e.timeRemaining()-5):1e9),o=i.context.treeLen<r&&n.doc.length>r+1e3,s=i.context.work(()=>Hl&&Hl()||Date.now()>a,r+(o?0:1e5));this.chunkBudget-=Date.now()-t,(s||this.chunkBudget<=0)&&(i.context.takeTree(),this.view.dispatch({effects:Ml.setState.of(new Bl(i.context))})),this.chunkBudget>0&&!(s&&!o)&&this.scheduleWork(),this.checkAsyncSchedule(i.context)}checkAsyncSchedule(e){e.scheduleOn&&=(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(e=>Ka(this.view.state,e)).then(()=>this.workScheduled--),null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),Wl=F.define({combine(e){return e.length?e[0]:null},enables:e=>[Ml.state,Ul,J.contentAttributes.compute([e],t=>{let n=t.facet(e);return n&&n.name?{"data-language":n.name}:{}})]});var Gl=class e{constructor(e,t){this.specs=e;let n;function r(e){let t=ai.newName();return(n||=Object.create(null))[`.`+t]=e,t}let i=typeof t.all==`string`?t.all:t.all?r(t.all):void 0,a=t.scope;this.scope=a instanceof Ml?e=>e.prop(kl)==a.data:a?e=>e==a:void 0,this.style=ml(e.map(e=>({tag:e.tag,class:e.class||r(Object.assign({},e,{tag:null}))})),{all:i}).style,this.module=n?new ai(n):null,this.themeType=t.themeType}static define(t,n){return new e(t,n||{})}};X.meta,X.link,X.heading,X.emphasis,X.strong,X.strikethrough,X.keyword,X.atom,X.bool,X.url,X.contentSeparator,X.labelName,X.literal,X.inserted,X.string,X.deleted,X.regexp,X.escape,X.string,X.variableName,X.variableName,X.typeName,X.namespace,X.className,X.variableName,X.macroName,X.propertyName,X.comment,X.invalid;let Kl=Object.create(null),ql=[vt.none],Jl=[],Yl=Object.create(null),Xl=Object.create(null);for(let[e,t]of[[`variable`,`variableName`],[`variable-2`,`variableName.special`],[`string-2`,`string.special`],[`def`,`variableName.definition`],[`tag`,`tagName`],[`attribute`,`attributeName`],[`type`,`typeName`],[`builtin`,`variableName.standard`],[`qualifier`,`modifier`],[`error`,`invalid`],[`header`,`heading`],[`property`,`propertyName`]])Xl[e]=Ql(Kl,t);function Zl(e,t){Jl.indexOf(e)>-1||(Jl.push(e),console.warn(t))}function Ql(e,t){let n=[];for(let r of t.split(` `)){let t=[];for(let n of r.split(`.`)){let r=e[n]||X[n];r?typeof r==`function`?t.length?t=t.map(r):Zl(n,`Modifier ${n} used at start of tag`):t.length?Zl(n,`Tag ${n} used as modifier`):t=Array.isArray(r)?r:[r]:Zl(n,`Unknown highlighting tag ${n}`)}for(let e of t)n.push(e)}if(!n.length)return 0;let r=t.replace(/ /g,`_`),i=r+` `+n.map(e=>e.id),a=Yl[i];if(a)return a.id;let o=Yl[i]=vt.define({id:ql.length,name:r,props:[dl({[r]:n})]});return ql.push(o),o.id}U.RTL,U.LTR,Pl.define({parser:hn.configure({props:[dl({"Aggregator/Word":X.keyword,"Metric/Word":X.variableName,"Head/Word":X.keyword,DatasetReference:X.keyword,"DatasetReference/Word":X.keyword,At:X.punctuation,TagKey:X.propertyName,"TagKey/Word":X.propertyName,TagValue:X.string,"TagValue/Value/Word":X.string,"TagValue/Word":X.string,Negate:X.operator,Star:X.operator,Dimension:X.attributeName,"Dimension/Word":X.attributeName,By:X.keyword,RollupDot:X.keyword,Int:X.number,"Rollup/Word":X.unit,braceOpen:X.bracket,braceClose:X.bracket,parenOpen:X.bracket,parenClose:X.bracket,colon:X.punctuation,comma:X.punctuation,pipe:X.punctuation,dot:X.punctuation})]}),languageData:{closeBrackets:{brackets:[`{`,`(`]}}}),[...nt.map(e=>({label:e,detail:`function head`,type:`keyword`})),...tt.map(e=>({label:e,detail:`source head`,type:`keyword`})),...rt.map(e=>({label:e,detail:`chart head`,type:`class`})),...it.map(e=>({label:e,detail:`page dataset`,type:`class`}))],Ye.map(e=>({label:e,type:`keyword`})),[...qe,...Je],at.map(e=>({label:e,detail:`display unit`,type:`constant`})),[...new Set(et.flatMap(e=>[...ft(e,`find`)]))],Gl.define([{tag:X.keyword,color:`hsl(var(--primary))`},{tag:X.variableName,color:`hsl(var(--accent-foreground))`,fontWeight:`600`},{tag:X.propertyName,color:`hsl(var(--secondary-foreground))`},{tag:X.string,color:`hsl(var(--success))`},{tag:X.attributeName,color:`hsl(var(--warning))`},{tag:X.number,color:`hsl(var(--primary))`},{tag:X.unit,color:`hsl(var(--muted-foreground))`},{tag:X.operator,color:`hsl(var(--destructive))`},{tag:[X.bracket,X.punctuation],color:`hsl(var(--muted-foreground))`}]);function $l(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 eu(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}function tu(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 nu(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 ru(e){let t=new Map;for(let n of e){if(n.outputType!==`analytics`)continue;let e=n.metrics.find(e=>e.type===E.Label),r=n.metrics.find(e=>e.type!==E.Label&&typeof e.value==`number`);if(!e||!r)continue;let i=String(e.value??e.image??``);if(!i)continue;let a=tu(r.metadata),o=eu(r.metadata,`canonicalKey`)??a?.path??$l(i),s=eu(r.metadata,`effortSlug`),c=eu(r.metadata,`effortDiscipline`),l=eu(r.metadata,`effortIntensityTier`),u=eu(r.metadata,`grade`),d=nu(r.metadata)??(s?{effort:s}:void 0),f=a?`${Ce(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 iu(e){let t=e;for(let e of t){let t=eu(e.metadata,`effortSlug`);if(t)return t;if((e.type===`effort`||e.type===E.Effort)&&typeof e.value==`string`&&e.value)return e.value}}function au(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:iu(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 ou(e,t){let n=Date.now();return Array.from(ru(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 su(e){return e.startsWith(`collection.`)?`notebook.${e.slice(11)}`:e.startsWith(`feed.`)?`notebook.${e.slice(5)}`:e}function cu(e){return e.startsWith(`markdown/collections/`)?`markdown/notebooks/${e.slice(21)}`:e.startsWith(`markdown/feeds/`)?`markdown/notebooks/${e.slice(15)}`:e}function lu(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 uu(e){return e.startsWith(`feeds/`)?e.slice(6):e}function du(e){let t=e,n=e=>{t={...t,...e}},r=e.sourceId;if(typeof r==`string`){let e=lu(r);e!==r&&n({sourceId:e})}let i=e.sourcePath;if(typeof i==`string`){let e=cu(i);e!==i&&n({sourcePath:e})}let a=e.seedChunkId;if(typeof a==`string`){let e=su(a);e!==a&&n({seedChunkId:e})}let o=e.routeId;if(typeof o==`string`){let e=uu(o);e!==o&&n({routeId:e})}return`catalog`in t&&(t={...t},delete t.catalog),t.type===`feed`&&n({type:`note`}),t}function fu(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`)}new Set($e);let Z=`sync_outbox`,pu=`sync_state`,mu=[{name:Z,keyPath:`seq`,autoIncrement:!0},{name:pu,keyPath:`key`}],hu=w.filter(e=>!e.system).map(e=>e.name),gu={attachments:`data`},_u=[{name:`segments`,keyPath:[`id`,`version`]},{name:`results`,keyPath:`id`}];var vu=class{ops=[];ctx};let yu=new Set;function bu(){for(let e of yu)e()}function xu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(`lower`in e||`upper`in e||`lowerOpen`in e||`upperOpen`in e)}function Su(e){if(e.op!==`put`)return 32;let t=32,n=gu[e.store],r=e.value,i=n&&typeof r==`object`&&r&&!Array.isArray(r)&&n in r?Reflect.get(r,n):void 0;return t+=typeof i==`string`?i.length:i instanceof ArrayBuffer?Math.ceil(i.byteLength/3)*4+64:JSON.stringify(e.value)?.length??0,t}let Cu=[`block_revisions`,`notes`,`sessions`,...hu.filter(e=>e!==`block_revisions`&&e!==`notes`&&e!==`sessions`)];async function wu(e){let t=Ge(await e(`notes`)),n=[];for(let r of Cu){let i=w.find(e=>e.name===r);for(let a of await e(r))Ke(r,a,t)&&n.push({op:`put`,store:r,key:se(i,a),value:a})}return n}var Tu=class e{owner;name;tx;mutable;touched;journal;constructor(e,t,n,r=!1,i,a){this.owner=e,this.name=t,this.tx=n,this.mutable=r,this.touched=i,this.journal=a}async get(e){return this.tx?this.tx.objectStore(this.name).get(e):(await this.owner.open()).get(this.name,e)}async getMany(e){return this.tx?Promise.all(e.map(e=>this.tx.objectStore(this.name).get(e))):this.owner.transaction([this.name],`readonly`,t=>t.readonly(this.name).getMany(e))}async getAll(e,t){return this.tx?this.tx.objectStore(this.name).getAll(e,t):(await this.owner.open()).getAll(this.name,e,t)}async getAllFromIndex(e,t,n){return this.tx?this.tx.objectStore(this.name).index(e).getAll(t,n):(await this.owner.open()).getAllFromIndex(this.name,e,t,n)}async getAllFromIndexMany(e,t){return this.tx?Promise.all(t.map(t=>this.tx.objectStore(this.name).index(e).getAll(t))):this.owner.transaction([this.name],`readonly`,n=>n.readonly(this.name).getAllFromIndexMany(e,t))}async count(e){return this.tx?this.tx.objectStore(this.name).count(e):(await this.owner.open()).count(this.name,e)}async countFromIndex(e,t){return this.tx?this.tx.objectStore(this.name).index(e).count(t):(await this.owner.open()).countFromIndex(this.name,e,t)}async put(e,t){if(!this.mutable)throw Error(`read-only store`);if(!this.tx){let t=this.name===`notes`?[this.name,`block_revisions`]:[this.name,`block_revisions`,`notes`];return this.owner.transaction([...t],`readwrite`,t=>t.readwrite(this.name).put(e))}let n=this.owner.stamp(this.name,e);ze(this.name,n);let r=w.find(e=>e.name===this.name),i=se(r,n),a=this.tx.objectStore(this.name),o=await a.get(i);if(this.name===`block_revisions`&&o!==void 0&&!Le(o,n))throw Error(`immutable block revision collision`);if(this.name===`notes`&&Be(o,n),this.name===`sessions`&&Ve(o,n),Le(o,n))return i;let s=await a.put(n);if(!r.system&&this.journal){let e=this.name===`notes`?void 0:await(this.journal.ctx??=this.owner.policyContext(this.tx)),t=o!==void 0&&Ke(this.name,o,e??Ge([]));if(Ke(this.name,n,e??Ge([]))){if(this.name===`notes`&&typeof n==`object`&&n&&`id`in n)for(let e of await this.tx.objectStore(`block_revisions`).index(`by-note`).getAll(String(n.id)))this.journal.ops.push({op:`put`,store:`block_revisions`,key:[e.noteId,e.blockId,e.version],value:e});else if(this.name===`sessions`&&typeof n==`object`&&n&&`noteId`in n&&`blockId`in n&&`blockVersion`in n){let e=[n.noteId,n.blockId,n.blockVersion],t=await this.tx.objectStore(`block_revisions`).get(e);t&&this.journal.ops.push({op:`put`,store:`block_revisions`,key:e,value:t})}this.journal.ops.push({op:`put`,store:this.name,key:i,value:n})}else t&&this.journal.ops.push({op:`delete`,store:this.name,key:i});this.name===`notes`&&(this.journal.ctx=void 0)}return this.name===`notes`&&this.touched?.notes.add(String(i)),this.name===`sessions`&&this.touched?.sessions.add(String(i)),s}async putMany(e,t){if(t&&t.length!==e.length)throw Error(`putMany key count mismatch`);if(!this.tx){let n=this.name===`notes`?[this.name,`block_revisions`]:[this.name,`block_revisions`,`notes`];return this.owner.transaction([...n],`readwrite`,n=>n.readwrite(this.name).putMany(e,t))}let n=[];for(let r=0;r<e.length;r++)n.push(await this.put(e[r],t?.[r]));return n}async delete(t){if(!this.mutable)throw Error(`read-only store`);if(this.name===`block_revisions`)throw Error(`block history requires explicit wipe`);if(!this.tx){let e=this.name===`notes`?[this.name]:[this.name,`notes`];return this.owner.transaction([...e],`readwrite`,e=>e.readwrite(this.name).delete(t))}if(this.name===`notes`)for(let n of await this.tx.objectStore(`notes`).getAll(t))for(let t of[`block_index`,`block_efforts`,`block_equipment`]){let r=this.tx.objectStore(t);for(let i of await r.index(`by-note`).getAllKeys(n.id))await new e(this.owner,t,this.tx,!0,this.touched,this.journal).delete(i)}await this.recordDelete(t),await this.tx.objectStore(this.name).delete(t)}async recordDelete(e){if(!this.journal)return;let t=this.tx.objectStore(this.name),n=xu(e)?await t.getAllKeys(e):[e],r=this.name===`notes`?void 0:await(this.journal.ctx??=this.owner.policyContext(this.tx));for(let e of n){let n=await t.get(e);n!==void 0&&!Ke(this.name,n,r??Ge([]))||this.journal.ops.push({op:`delete`,store:this.name,key:e})}}async clear(){if(!this.mutable)throw Error(`read-only store`);if(this.name===`block_revisions`)throw Error(`block history requires explicit wipe`);if(!this.tx){let e=this.name===`notes`?[`notes`,`block_index`,`block_efforts`]:[this.name,`notes`];return this.owner.transaction([...e],`readwrite`,e=>e.readwrite(this.name).clear())}let e=this.tx.objectStore(this.name),t=await e.getAll(),n=Ge(this.name===`notes`?t:await this.tx.objectStore(`notes`).getAll());for(let r of t){let t=se(w.find(e=>e.name===this.name),r);if(Ke(this.name,r,n)&&!(this.name===`meta`&&typeof t==`string`&&t.startsWith(`user-deleted-seed:`))){if(this.name===`notes`&&typeof t==`string`)for(let e of[`block_index`,`block_efforts`,`block_equipment`]){let n=this.tx.objectStore(e);for(let r of await n.index(`by-note`).getAllKeys(t))this.journal?.ops.push({op:`delete`,store:e,key:r}),await n.delete(r)}await this.recordDelete(t),await e.delete(t)}}}};let Eu={script:`wod`,wod:`wod`};function Du(e){return Oe(e.slice(0,e.indexOf(`
13
13
  `)).trim())??{}}var Ou=class{options;opening;constructor(e={}){this.options=e}open(){if(typeof indexedDB>`u`)return Promise.reject(Error(`IndexedDB is unavailable in this environment`));if(!this.opening){let e=!1,t=0,n;this.opening=g(this.options.dbName??`wodwiki-db`,32,{upgrade:async(r,i,a,o)=>{if(o.done.catch(()=>{}),i>32){e=!0,o.abort();return}if(i!==0&&i<20){t=i,o.abort();return}try{Au(r,o),i!==0&&i<32&&this.options.onUpgradeStart?.(i),await ju(r,i,o)}catch(e){n=e instanceof Error?e:Error(String(e));try{o.abort()}catch{}}},blocking:()=>{this.close()}}).catch(r=>{throw this.opening=void 0,n||(t===0?e||r instanceof DOMException&&r.name===`VersionError`?Error(`database schema is newer than this client supports (v32); refusing to downgrade`):r:Error(`local database schema v${t} predates the supported migration chain (v20+). Open this browser profile in an intermediate app version to export your data, or clear site data to start fresh — the old database was left untouched.`))})}return this.opening}stamp(e,t){let n=this.options.getUserId?.();return n?ae(e,t,n):t}async policyContext(e){return Ge(e?await e.objectStore(`notes`).getAll():await(await this.open()).getAll(`notes`))}readonly(e){return new Tu(this,e)}readwrite(e){return new Tu(this,e,void 0,!0)}async transaction(e,t,n){let r=await this.open(),i=t===`readwrite`?new vu:void 0,a=new Set(e);t===`readwrite`&&(a.add(`block_revisions`),a.add(Z),a.add(`notes`),a.has(`notes`)&&(a.add(`block_index`),a.add(`block_efforts`),a.add(`block_equipment`)));let o=r.transaction([...a],t),s=o.done;s.catch(()=>{});let c={notes:new Set,sessions:new Set},l={readonly:e=>{if(!a.has(e))throw Error(`store outside transaction scope`);return new Tu(this,e,o)},readwrite:e=>{if(t!==`readwrite`)throw Error(`read-only transaction`);if(!a.has(e))throw Error(`store outside transaction scope`);return new Tu(this,e,o,!0,c,i)}};try{let e=await n(l);return await He((await Promise.all([...c.notes].map(e=>o.objectStore(`notes`).get(e)))).filter(Boolean),(await Promise.all([...c.sessions].map(e=>o.objectStore(`sessions`).get(e)))).filter(Boolean),e=>Promise.all(e.map(e=>o.objectStore(`block_revisions`).get(e)))),i&&i.ops.length>0&&await o.objectStore(Z).put({id:crypto.randomUUID(),at:Date.now(),ops:i.ops}),await s,i&&i.ops.length>0&&bu(),e}catch(e){try{o.abort()}catch{}throw await s.catch(()=>{}),e}}async wipeUserData(){let e=w.filter(e=>!e.system&&e.name!==`block_revisions`).map(e=>e.name);await this.transaction(e,`readwrite`,async t=>{for(let n of e)await t.readwrite(n).clear()})}async wipe(){let e=await this.open(),t=w.filter(e=>!e.system).map(e=>e.name),n=e.transaction([...t,Z],`readwrite`);await Promise.all(t.map(e=>n.objectStore(e).clear())),await n.objectStore(Z).put({id:crypto.randomUUID(),at:Date.now(),ops:[{op:`wipe`}]}),await n.done,bu()}async readOutbox(e,t){let n=await this.open(),r=IDBKeyRange.lowerBound(e,!0);return await n.getAll(Z,r,Math.min(t,4294967295))}async ackOutbox(e){let t=await this.open(),n=await t.getAllKeys(Z,IDBKeyRange.upperBound(e)),r=t.transaction(Z,`readwrite`);await Promise.all(n.map(e=>r.store.delete(e))),await r.done}async getSyncState(e){return(await(await this.open()).get(pu,e))?.value}async setSyncState(e,t){await(await this.open()).put(pu,{key:e,value:t})}async captureSyncBootstrap(e){let t=(await this.open()).transaction([...hu,Z,pu],`readwrite`),n=t.objectStore(pu),r=await n.get(e);if(r!==void 0&&Array.isArray(r.value))return await t.done,r.value;let i=new Set,a=new Set,o=!1;for(let e of await t.objectStore(Z).getAll())for(let t of e.ops)t.op===`put`||t.op===`delete`?i.add(`${t.store}:${JSON.stringify(t.key)}`):t.op===`clear`?a.add(t.store):o=!0;let s=crypto.randomUUID(),c=[];if(!o){let e=[],n=0,r=()=>{e.length!==0&&(c.push({id:`bootstrap:${s}:${c.length}`,at:Date.now(),ops:e}),e=[],n=0)};for(let o of await wu(e=>t.objectStore(e).getAll())){if(a.has(o.store)||o.store!==`block_revisions`&&i.has(`${o.store}:${JSON.stringify(o.key)}`))continue;let t=Su(o);e.length>0&&(e.length>=500||n+t>1e6)&&r(),e.push(o),n+=t}r()}return await n.put({key:e,value:c}),await t.done,c}async validateSyncState(){let e=(await this.open()).transaction([`notes`,`sessions`,`block_revisions`],`readonly`),t=await e.objectStore(`notes`).getAll(),n=await e.objectStore(`sessions`).getAll(),r=e.objectStore(`block_revisions`);await He(t,n,e=>Promise.all(e.map(e=>r.get(e)))),await e.done}async applySyncMutations(e,t,n=`cursor`){let r=new Map(w.map(e=>[e.name,e]));for(let t of e){if(t.op===`clear`||t.op===`wipe`)continue;let e=r.get(t.store);if(!e)throw Error(`unknown store in sync mutation: ${String(t.store)}`);if(t.op===`put`||t.op===`delete`){let n=Array.isArray(t.key)?t.key:[t.key];if(n.length!==e.keyPath.length||!n.every(e=>typeof e==`string`||typeof e==`number`))throw Error(`sync ${t.op} key arity/shape mismatch for ${t.store}`)}t.op===`put`&&ze(t.store,t.value)}let i=await this.open(),a=hu,o=i.transaction([...a,Z,pu],`readwrite`),s=e=>e===`notes`||e===`efforts`,c=new Map;for(let t of e){if(t.op===`clear`||t.op===`wipe`||!s(t.store))continue;let e=`${t.store}:${JSON.stringify(t.key)}`;if(c.has(e))continue;let n=t.key,r=await o.objectStore(t.store).get(n);c.set(e,{store:t.store,key:n,before:r,beforeExists:r!==void 0})}let l=async(e,t)=>{if(e.op===`wipe`){for(let e of a)await o.objectStore(e).clear();return}if(e.store===`memberships`)return;if(e.op===`clear`){if(e.store===`block_revisions`)return;let n=o.objectStore(e.store),i=Ge(await o.objectStore(`notes`).getAll());for(let a of await n.getAll()){if(!Ke(e.store,a,i))continue;let n=se(r.get(e.store),a);e.store===`meta`&&typeof n==`string`&&n.startsWith(`user-deleted-seed:`)||await l({op:`delete`,store:e.store,key:n},t)}return}if(e.op===`delete`){if(e.store===`notes`){let t=String(Array.isArray(e.key)?e.key[0]:e.key);for(let e of[`block_index`,`block_efforts`,`block_equipment`]){let n=o.objectStore(e);for(let e of await n.index(`by-note`).getAllKeys(t))await n.delete(e)}}e.store!==`block_revisions`&&await o.objectStore(e.store).delete(e.key);return}let n=o.objectStore(e.store);if(e.store===`block_revisions`){let r=await n.get(e.key);if(r!==void 0&&!Le(r,e.value)&&!t){let t=e.value,i=r.version+1;for(;await n.get([t.noteId,t.blockId,i])!==void 0;)i+=1;await n.put({...t,version:i});return}(r===void 0||!Le(r,e.value))&&await n.put(e.value);return}if(e.store===`notes`&&!t){let t=await n.get(e.key);if(t!==void 0){let n=t,r=e.value;if(n.sourceRevision>r.sourceRevision)return}}await n.put(e.value)};for(let t of e)await l(t,!1);let u=(await o.objectStore(Z).getAll()).sort((e,t)=>e.seq-t.seq);for(let e of u)for(let t of e.ops)await l(t,!0);let d=0,f=0;for(let e of c.values()){let t=await o.objectStore(e.store).get(e.key);t!==void 0&&(e.beforeExists?Le(e.before,t)||(f+=1):d+=1)}return t!==null&&await o.objectStore(pu).put({key:n,value:{rev:t}}),await o.done,{added:d,updated:f}}async snapshotRows(){let e=await this.open(),t=w.filter(e=>!e.system),n=e.transaction(t.map(e=>e.name),`readonly`),r=Ge(await n.objectStore(`notes`).getAll()),i=await Promise.all(t.map(async e=>({store:e.name,rows:(await n.objectStore(e.name).getAll()).filter(t=>Ke(e.name,t,r))})));return await n.done,i}async snapshotAllRows(){let e=await this.open(),t=w.filter(e=>!e.system),n=e.transaction(t.map(e=>e.name),`readonly`),r=await Promise.all(t.map(async e=>({store:e.name,rows:await n.objectStore(e.name).getAll()})));return await n.done,r}async close(){let e=this.opening;this.opening=void 0,(await e?.catch(()=>void 0))?.close()}};let ku=[...w.map(e=>({name:e.name,keyPath:e.keyPath})),..._u.map(e=>({name:e.name,keyPath:Array.isArray(e.keyPath)?e.keyPath:[e.keyPath]}))];Object.fromEntries(ku.map(e=>[e.name,e.keyPath]));function Au(e,t){for(let n of w){if(e.objectStoreNames.contains(n.name)){let e=t.objectStore(n.name);for(let t of n.indexes)e.indexNames.contains(t.name)||e.createIndex(t.name,t.keyPath.length===1?t.keyPath[0]:t.keyPath,{unique:t.unique,multiEntry:t.multiEntry});continue}let r=e.createObjectStore(n.name,{keyPath:n.keyPath.length===1?n.keyPath[0]:n.keyPath});for(let e of n.indexes)r.createIndex(e.name,e.keyPath.length===1?e.keyPath[0]:e.keyPath,{unique:e.unique,multiEntry:e.multiEntry})}for(let t of mu)e.objectStoreNames.contains(t.name)||e.createObjectStore(t.name,{keyPath:t.keyPath,autoIncrement:`autoIncrement`in t&&t.autoIncrement})}async function ju(e,t,n){let r=e=>n.objectStore(e);if(t===20&&e.objectStoreNames.contains(`sessions`)){let e=r(`sessions`),t=r(`events`);for await(let n of e){let e=n.value,r=e.data?.logs??[],i=!1;for await(let n of t.index(`by-result-grain`).iterate(IDBKeyRange.bound([e.id,``],[e.id,[]]))){i=!0;break}if(!i&&r.length>0){let n={noteId:e.noteId,resultId:e.id,segmentId:e.segmentId,segmentVersion:e.segmentVersion,blockContentId:e.blockContentId,origin:e.origin,pageId:e.pageId,workoutTimestamp:e.data?.endTime??e.createdAt};for(let e of au(r,n))await t.put(e);for(let e of ou(r,n))await t.put(e)}let a={...e,startTime:e.data?.startTime??e.createdAt,endTime:e.data?.endTime??e.createdAt,duration:e.data?.duration??0,completed:e.data?.completed??!0,roundsCompleted:e.data?.roundsCompleted,totalRounds:e.data?.totalRounds,repsCompleted:e.data?.repsCompleted};delete a.data,await n.update(a)}}if(t===21&&e.objectStoreNames.contains(`meta`)&&await r(`meta`).delete(`seed`),t<25)for(let t of T){if(!e.objectStoreNames.contains(t))continue;let n=r(t);n.indexNames.contains(`by-user`)||n.createIndex(`by-user`,`userId`)}if(e.objectStoreNames.contains(`results`)){let t=r(`sessions`),n=r(`results`),i=r(`events`);for await(let e of n){let{data:n,...r}=e.value,a=n?.logs??[];if(a.length>0){let e={noteId:r.noteId,resultId:r.id,segmentId:r.segmentId,segmentVersion:r.segmentVersion,blockContentId:r.blockContentId,origin:r.origin,pageId:r.pageId,workoutTimestamp:n?.endTime??r.createdAt};for(let t of au(a,e))await i.get(t.id)===void 0&&await i.put(t);for(let t of ou(a,e))await i.get(t.id)===void 0&&await i.put(t)}await t.getKey(r.id)===void 0&&await t.put({...r,startTime:n?.startTime??r.startTime??r.createdAt,endTime:n?.endTime??r.endTime??r.createdAt,duration:n?.duration??r.duration??0,completed:n?.completed??r.completed??!0,roundsCompleted:n?.roundsCompleted??r.roundsCompleted,totalRounds:n?.totalRounds??r.totalRounds,repsCompleted:n?.repsCompleted??r.repsCompleted})}e.deleteObjectStore(`results`)}if(e.objectStoreNames.contains(`block_index`)&&!r(`block_index`).indexNames.contains(`by-source`)&&r(`block_index`).createIndex(`by-source`,`sourceId`),e.objectStoreNames.contains(`notes`)&&!r(`notes`).indexNames.contains(`by-created`)&&r(`notes`).createIndex(`by-created`,`createdAt`),e.objectStoreNames.contains(`efforts`)&&!r(`efforts`).indexNames.contains(`by-source`)&&r(`efforts`).createIndex(`by-source`,`registrySource`),e.objectStoreNames.contains(`note_tags`)&&!r(`note_tags`).indexNames.contains(`by-note-tag`)){let e=r(`note_tags`),t=new Map,n=[];for await(let r of e){let e=r.value,i=`${e.noteId}${e.tagId}`,a=t.get(i);a===void 0||e.id<a?(t.set(i,e.id),a!==void 0&&n.push(a)):n.push(e.id)}for(let t of n)await e.delete(t);e.createIndex(`by-note-tag`,[`noteId`,`tagId`],{unique:!0})}if(e.objectStoreNames.contains(`notes`)&&e.objectStoreNames.contains(`segments`)){let e=r(`segments`),t=r(`notes`),n=new Set;for await(let r of e){let e=r.value;if(e.dataType!==`frontmatter`||n.has(e.noteId)||!/(^|\n)dashboard:\s*["']?true["']?\s*(\n|$)/.test(e.rawContent))continue;n.add(e.noteId);let i=await t.get(e.noteId);!i||i.type===`dashboard`&&i.sourceId===`dashboards`||await t.put({...i,type:`dashboard`,sourceId:i.sourceId??`dashboards`})}}if(e.objectStoreNames.contains(`segments`)&&await Mu(e,n),t>=30&&t<32&&e.objectStoreNames.contains(Z)){let t=r(Z),n=[];for(let e of await t.getAll())for(let t of e.ops)if(t.op===`wipe`)for(let e of hu)e!==`block_revisions`&&n.push({op:`clear`,store:e});else t.op!==`put`&&t.store!==`memberships`&&t.store!==`block_revisions`&&n.push(t);if(n.push(...await wu(e=>r(e).getAll())),await t.clear(),n.length>0&&await t.put({id:crypto.randomUUID(),at:Date.now(),ops:n}),e.objectStoreNames.contains(pu)){let e=r(pu);for(let t of await e.getAllKeys())typeof t==`string`&&t.startsWith(`bootstrap-run:`)&&await e.delete(t)}}}async function Mu(e,t){let n=e=>t.objectStore(e),r=await n(`segments`).getAll(),i=n(`notes`),a=n(`block_revisions`),o=new Map;for(let e of r){let t=o.get(e.noteId);t?t.push(e):o.set(e.noteId,[e])}let s=new Map,c=new Map;for(let[e,t]of o){let n=new Map;for(let e of t){let t=n.get(e.id);(!t||e.version>t.version)&&n.set(e.id,e)}let r=[...n.values()].sort((e,t)=>(e.position??2**53-1)-(t.position??2**53-1)||e.id.localeCompare(t.id)),o=r.map(e=>e.sourceContent??`${e.rawContent}\n`).join(``),l=await i.get(e);if(!l)continue;let u=je(o,{registeredWidgets:De}).filter(e=>Me(e)!==null),d=r.filter(e=>e.dataType in Eu),f={};u.forEach((t,n)=>{let r=Me(t),i=d[n],a=i?.id??`migrated-${n}`;for(;Object.hasOwn(f,a);)a=`${a}-${n}`;let o=r===`wod`&&(t.type===`time`||t.type===`log`)?{dialect:t.type,...t.sport?{sport:t.sport}:{}}:{};f[a]={id:a,kind:r,version:i?.version??1,sourceRevision:1,from:t.from,to:t.to,...o},i&&s.set(`${e}${i.id}`,a),c.set(`${e}${a}`,{noteId:e,from:t.from,to:t.to,version:f[a].version})});let p=l;delete p.segments,delete p.segmentIds,await i.put({...p,rawContent:o,sourceRevision:1,blocks:f});let m=new Set(d.map(e=>e.id));for(let n of t){if(!m.has(n.id))continue;let t=Du(n.rawContent);await a.put({noteId:e,blockId:n.id,version:n.version,kind:`wod`,rawContent:n.rawContent,savedAt:n.createdAt,...t})}}let l=n(`sessions`);for(let e of await l.getAll()){if(e.segmentId===void 0&&e.segmentVersion===void 0&&e.version===void 0)continue;let{segmentId:t,segmentVersion:n,version:r,...i}=e;await l.put({...i,blockId:i.blockId??t??``,blockVersion:i.blockVersion??n??r??1})}let u=n(`events`);for(let e of await u.getAll()){if(e.segmentVersion===void 0&&e.segmentId===void 0)continue;let{segmentVersion:t,segmentId:n,...r}=e;await u.put({...r,...r.blockId===void 0&&n!==void 0?{blockId:n}:{},...r.blockVersion===void 0&&t!==void 0?{blockVersion:t}:{}})}let d=n(`block_index`);for(let e of await d.getAll()){let t=s.get(`${e.noteId}${e.segmentId}`)??e.segmentId,n=c.get(`${e.noteId}${t}`),r={...e,id:`${e.noteId}:${t}`,blockId:t,blockVersion:n?.version??e.segmentVersion??1,sourceRevision:1,...n?{from:n.from,to:n.to}:{},dataType:e.dataType===`script`?`wod`:e.dataType};delete r.segmentId,delete r.segmentVersion,r.id!==e.id&&await d.delete(e.id),await d.put(r)}e.deleteObjectStore(`segments`)}var Nu=class{items=new Map;constructor(e=[]){for(let t of e)this.items.set(t.id,t)}register(e){this.items.set(e.id,e)}unregister(e){this.items.delete(e)}has(e){return this.items.has(e)}get(e){return this.items.get(e)}list(){return[...this.items.values()].sort((e,t)=>(t.priority??0)-(e.priority??0))}get size(){return this.items.size}};let Pu={REPEATING_INTERVAL:`behavior.repeating_interval`,REQUIRED_TIMER:`behavior.required_timer`,INJECT_REST:`behavior.inject_rest`,LABEL_AMRAP:`workout.amrap`,LABEL_EMOM:`workout.emom`,LABEL_TABATA:`workout.tabata`,LABEL_FOR_TIME:`workout.for_time`};Object.values(Pu);function Fu(e){if(!e)return[];if(Array.isArray(e.rawMetrics))return e.rawMetrics;let t=e.metrics;return t?Array.isArray(t)?t:t.rawMetrics??[]:[]}function Iu(e,t=`dialect`,n){return{type:E.Hint,value:e,image:e,origin:t,...n?{icon:n}:{}}}function Lu(e,t,n=`dialect`){let r=t??D.empty(`dialect`),i=new Set(Ru(r));for(let t of e)i.has(t)||(i.add(t),r.add(Iu(t,n)));return r}function Ru(e){return Fu(e).filter(e=>e.type===E.Hint&&typeof e.value==`string`).map(e=>e.value)}function zu(e,t){return Fu(e).some(e=>e.type===E.Hint&&e.value===t)}let Bu=/^([a-zA-Z]+)([\s\S]*)$/;var Vu=class e{defs;byToken;constructor(e=[]){this.defs=e,this.byToken=new Map;for(let t of e){this.byToken.set(t.canonical.toLowerCase(),t);for(let e of t.aliases)this.byToken.set(e.toLowerCase(),t)}}get(e){return this.byToken.get(e.trim().toLowerCase())}has(e){return this.byToken.has(e.trim().toLowerCase())}consumeLeading(e){let t=Bu.exec(e.trimStart());if(!t)return null;let n=t[1],r=this.get(n);return r?{unit:r,token:n,rest:t[2].trim()}:null}extend(...t){return new e([...this.defs,...t])}toArray(){return[...this.defs]}};let Hu=[{canonical:`m`,dimension:`length`,aliases:[`meter`,`meters`,`metre`,`metres`]},{canonical:`km`,dimension:`length`,aliases:[`kilometer`,`kilometers`,`kilometre`,`kilometres`]},{canonical:`cm`,dimension:`length`,aliases:[`centimeter`,`centimeters`,`centimetre`,`centimetres`]},{canonical:`mm`,dimension:`length`,aliases:[`millimeter`,`millimeters`,`millimetre`,`millimetres`]},{canonical:`ft`,dimension:`length`,aliases:[`foot`,`feet`]},{canonical:`in`,dimension:`length`,aliases:[`inch`,`inches`]},{canonical:`yd`,dimension:`length`,aliases:[`yard`,`yards`]},{canonical:`mi`,dimension:`length`,aliases:[`mile`,`miles`]},{canonical:`kg`,dimension:`mass`,aliases:[`kilo`,`kilos`,`kilogram`,`kilograms`]},{canonical:`g`,dimension:`mass`,aliases:[`gram`,`grams`]},{canonical:`lb`,dimension:`mass`,aliases:[`lbs`,`pound`,`pounds`]},{canonical:`bw`,dimension:`mass`,aliases:[`bodyweight`]},{canonical:`cal`,dimension:`energy`,aliases:[`cals`,`calorie`,`calories`]},{canonical:`kcal`,dimension:`energy`,aliases:[`kcals`,`kilocalorie`,`kilocalories`]}],Uu={standard(){return new Vu(Hu)},of(e){return new Vu(e)}},Wu=e=>{if(e==null||!Number.isFinite(e))return`--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/60),i=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}`},Gu=e=>{if(e==null||!Number.isFinite(e))return`--:--:--`;let t=e<0,n=Math.floor(Math.abs(e)/1e3),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return`${t?`-`:``}${r.toString().padStart(2,`0`)}:${i.toString().padStart(2,`0`)}:${a.toString().padStart(2,`0`)}`},Ku=e=>e==null||!Number.isFinite(e)?`--:--`:Math.floor(Math.abs(e)/1e3)>=3600?Gu(e):Wu(e),qu=new Set([E.Duration,E.Time,E.Elapsed,E.Total]);function Ju(e){return qu.has(e)}function Yu(e){if(e.image)return e.image;if(e.value===void 0||e.value===null)return e.type;if(typeof e.value==`object`){let t=e.value;return`text`in t?String(t.text):`current`in t?`Round ${t.current}`:JSON.stringify(e.value)}return String(e.value)}function Xu(e,t){if(Ju(e.type)&&typeof e.value==`number`)return Ku(e.value);let n=Yu(e);if(e.type===E.Rounds||e.type===`rounds`){let e=n.trim();if(/^\d+$/.test(e))return`${n} ${Number(e)===1?`Round`:`Rounds`}`}return n}function Zu(e){let t=[];return t.push(`Type: ${e.type}`),e.value!==void 0&&t.push(`Value: ${e.value}`),e.origin&&t.push(`Origin: ${e.origin}`),e.sourceBlockKey&&t.push(`Block: ${e.sourceBlockKey}`),e.timestamp&&t.push(`Time: ${e.timestamp.toISOString()}`),t.join(`
14
14
  `)}let Qu={duration:`Duration`,rep:`Reps`,effort:`Effort`,distance:`Distance`,rounds:`Rounds`,resistance:`Resistance`,action:`Action`,increment:`Increment`,metric:`Metric`,label:`Label`,text:`Text`,custom:`Custom`,calculated:`Calculated`,"current-round":`Current Round`,volume:`Volume`,intensity:`Intensity`,load:`Load`,work:`Work`,lap:`Lap`,group:`Group`,time:`Time`,elapsed:`Elapsed`,total:`Total`,"system-time":`System Time`,spans:`Spans`,system:`System`,rir:`RIR`,"session-rpe":`Session RPE`,"session-load":`Session Load`,"met-score":`MET Score`,tis:`TIS`,sound:`Sound`};function $u(e){let t=e.replace(/[_-]+/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).trim();return t.length===0?``:t.split(/\s+/).map(e=>e===e.toUpperCase()||/^[A-Z]{2,}$/.test(e)?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(` `)}function ed(e){let t=String(e).trim(),n=t.toLowerCase();return Qu[n]??$u(t)}function td(e){return e.type.toLowerCase()===`effort`&&(e.value??e.image??``).trim().toLowerCase()===`rest`}function nd(e,t){return t?`rest`:{time:`time`,duration:`time`,elapsed:`time`,total:`time`,spans:`time`,rep:`rep`,effort:`effort`,distance:`distance`,rounds:`rounds`,increment:`rounds`,"current-round":`rounds`,action:`action`,resistance:`resistance`,text:`muted`,label:`muted`,group:`muted`,lap:`muted`,system:`system`,"system-time":`system`,volume:`rep`,intensity:`effort`,load:`resistance`,work:`effort`,rir:`effort`,"session-rpe":`effort`,"session-load":`resistance`,"met-score":`distance`,tis:`action`,sound:`system`,metric:`effort`,custom:`muted`,calculated:`effort`}[e.type.toLowerCase()]??`unknown`}function rd(){return{isStructural(e){let t=e.type;if(t===E.Group||t===`group`){let t=e.image??``;return t===`+`||t===`-`}return t===E.Lap||t===`lap`},isHidden(e,t){if(this.isStructural(e))return t!==`debug`;let n=e.type;return!!((n===E.Sound||n===`sound`)&&t!==`debug`||n.startsWith(`tag.`)&&t!==`debug`||t===`review-grid-column`&&(n===E.Elapsed||n===`elapsed`||n===E.Total||n===`total`||n===E.System||n===`system`))},present(e,t){let n=this.isStructural(e),r=this.isHidden(e,t),i=td(e),a=(e.type===E.Text||e.type===`text`)&&e.origin===`parser`,o=e.origin===`user`,s;return s=r?`hidden`:a?`comment`:t===`timer-subtitle`||t===`history-label`||t===`label-composer`?`plain-text`:t===`review-grid-column`?`column-heading`:`badge`,{metric:e,label:Xu(e,t),tooltip:Zu(e),renderKind:s,tone:nd(e,i),iconKey:i?`rest`:e.type,visible:!r,structural:n,rest:i,comment:a,userEntered:o,columnLabel:ed(e.type)}},presentGroup(e,t){return e.map(e=>this.present(e,t))},columnLabel(e){return ed(e)}}}let id=rd();var ad=class{effort;value;image;origin=`parser`;metadata;constructor(e,t){this.effort=e,this.value=t?.resolvedSlug??e,this.image=e,t?.references&&(this.metadata={references:t.references})}type=E.Effort},od=class{unit;value;image;origin;constructor(e,t){this.unit=t,this.value={amount:e,unit:t},this.image=e===void 0?`? ${t}`:`${e} ${t}`,this.origin=e===void 0?`hinted`:`parser`}type=E.Distance},sd=class{unit;value;image;origin;constructor(e,t){this.unit=t,this.value={amount:e,unit:t},this.image=e===void 0?`? ${t}`:`${e} ${t}`,this.origin=e===void 0?`hinted`:`parser`}type=E.Resistance},cd=class{unit;dimension;value;image;origin;type;constructor(e,t,n){this.unit=t,this.dimension=n,this.value={amount:e,unit:t},this.image=e===void 0?`? ${t}`:`${e} ${t}`,this.origin=e===void 0?`hinted`:`parser`,this.type=n===`energy`?`energy`:E.Custom}};function ld(e,t,n){switch(n){case`length`:return new od(e,t);case`mass`:return new sd(e,t);default:return new cd(e,t,n)}}var ud=class{alternatives;type=E.Choice;origin=`parser`;value;image;constructor(e){this.alternatives=e,this.value={alternatives:e},this.image=e.map(e=>e.image??String(e.value??``)).join(` | `)}},dd=class{unit;value;image;origin;constructor(e,t=`%`){this.unit=t,this.value={amount:e,unit:t},this.image=e===void 0?`?${t}`:`${e}${t}`,this.origin=e===void 0?`hinted`:`parser`}type=E.Intensity};function fd(e){return e.type===E.Rep&&(typeof e.value==`number`||e.value===void 0)}function pd(e){return e.type===E.Effort&&(typeof e.value==`string`?e.value:e.image)===`/`}function md(e){return e.type===E.Effort&&(typeof e.value==`string`?e.value:e.image)===`|`}function hd(e){return e.type!==E.Effort&&e.type!==E.Text?null:typeof e.value==`string`?e.value:typeof e.image==`string`?e.image:null}function gd(e){if(e.type!==E.Distance&&e.type!==E.Resistance)return!1;let t=e.value;return!!t&&t.amount!==void 0&&(!t.unit||t.unit===``)}function _d(e,t,n){if(!e||!t)return e??t;let r=e.startOffset,i=(t.startOffset??0)+n.length,a=(t.startOffset??0)-(e.endOffset??0),o=e.raw===void 0?void 0:e.raw+` `.repeat(Math.max(0,a))+n,s=r===void 0?void 0:i-r;return{line:e.line,startOffset:r,endOffset:i,columnStart:e.columnStart,columnEnd:e.columnStart!==void 0&&s!==void 0?e.columnStart+s:e.columnEnd,length:s,raw:o}}function vd(e,t){if(!e||e.raw===void 0)return e&&{...e,raw:t};let n=e.raw.indexOf(t),r=n>=0?n:0,i=(e.startOffset??0)+r;return{line:e.line,startOffset:i,endOffset:e.endOffset,columnStart:(e.columnStart??0)+r,columnEnd:e.columnEnd,length:t.length,raw:t}}let yd=/^([\s\S]*?)([a-zA-Z]+)$/;function bd(e){let t=yd.exec(e.trimEnd());return t?{rest:t[1].trim(),token:t[2]}:null}function xd(e,t){return e&&{line:e.line,startOffset:e.startOffset,endOffset:e.startOffset===void 0?e.endOffset:e.startOffset+t.length,columnStart:e.columnStart,columnEnd:e.columnStart===void 0?e.columnEnd:e.columnStart+t.length,length:t.length,raw:t}}function Sd(e,t){if(!e)return e;let n=Math.max(0,(e.raw?.trimEnd().length??(e.endOffset??0)-(e.startOffset??0))-t.length);return{line:e.line,startOffset:e.startOffset===void 0?void 0:e.startOffset+n,endOffset:e.startOffset===void 0?e.endOffset:e.startOffset+n+t.length,columnStart:e.columnStart===void 0?void 0:e.columnStart+n,columnEnd:e.columnStart===void 0?e.columnEnd:e.columnStart+n+t.length,length:t.length,raw:t}}function Cd(e,t){if(!e||!t)return e??t;let n=e.startOffset,r=t.endOffset,i=n!==void 0&&r!==void 0?r-n:void 0;return{line:e.line,startOffset:n,endOffset:r,columnStart:e.columnStart,columnEnd:t.columnEnd,length:i,raw:e.raw}}function wd(e,t){let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=e[r+1];if(!(pd(i.metric)||md(i.metric))){if(a){let t=hd(i.metric),o=e[r+2]?hd(e[r+2].metric):null;if(t!==null&&md(a.metric)&&o!==null){let t=[i.metric],a=r+1;for(;a+1<e.length&&md(e[a].metric)&&hd(e[a+1].metric)!==null;)t.push(e[a+1].metric),a+=2;n.push({metric:new ud(t),meta:Cd(i.meta,e[a-1].meta)}),r=a-1;continue}}if(a&&e[r+2]&&e[r+3]){let o=e[r+2],s=e[r+3],c=fd(i.metric)||gd(i.metric),l=fd(o.metric)||gd(o.metric);if(c&&md(a.metric)&&l){let e=hd(s.metric),a=e===null?null:t.consumeLeading(e);if(a){let e=fd(i.metric)?i.metric.value:i.metric.value.amount,t=fd(o.metric)?o.metric.value:o.metric.value.amount,c=ld(e,a.token,a.unit.dimension),l=ld(t,a.token,a.unit.dimension);if(c.type===l.type){let e=_d(i.meta,s.meta,a.token);n.push({metric:new ud([c,l]),meta:e}),a.rest&&n.push({metric:new ad(a.rest),meta:vd(s.meta,a.rest)}),r+=3;continue}}}}if(a&&e[r+2]&&e[r+3]){let o=e[r+2],s=e[r+3],c=fd(i.metric)||gd(i.metric),l=fd(o.metric)||gd(o.metric);if(c&&pd(a.metric)&&l){let e=hd(s.metric),a=e===null?null:t.consumeLeading(e);if(a){let e=fd(i.metric)?i.metric.value:i.metric.value.amount,t=fd(o.metric)?o.metric.value:o.metric.value.amount;if(e!==void 0&&t!==void 0&&t!==0){let o=ld(e/t,a.token,a.unit.dimension),c=_d(i.meta,s.meta,a.token);n.push({metric:o,meta:c}),a.rest&&n.push({metric:new ad(a.rest),meta:vd(s.meta,a.rest)}),r+=3;continue}}}}if(a&&fd(i.metric)){let e=hd(a.metric);if(e!==null&&e.trim()===`%`){n.push({metric:new dd(i.metric.value),meta:_d(i.meta,a.meta,`%`)}),r++;continue}}if(a&&(fd(i.metric)||gd(i.metric))){let e=hd(a.metric),o=e===null?null:t.consumeLeading(e);if(o){let e=fd(i.metric)?i.metric.value:i.metric.value.amount;n.push({metric:ld(e,o.token,o.unit.dimension),meta:_d(i.meta,a.meta,o.token)}),o.rest&&n.push({metric:new ad(o.rest),meta:vd(a.meta,o.rest)}),r++;continue}}if(!a){let e=hd(i.metric),r=e===null?null:bd(e),a=r?t.get(r.token):void 0;if(r&&r.rest&&a&&a.canonical===`bw`){n.push({metric:new ad(r.rest),meta:xd(i.meta,r.rest)}),n.push({metric:ld(void 0,r.token,a.dimension),meta:Sd(i.meta,r.token)});continue}}n.push(i)}}return n}function Td(e,t){let n=e.metrics.toArray(),r=wd(n.map(t=>({metric:t,meta:e.metricMeta?.get(t)})),t);if((r.length!==n.length||r.some((e,t)=>e.metric!==n[t]))&&(e.metrics.clear().add(...r.map(e=>e.metric)),e.metricMeta)){let t=new Map(e.metricMeta);for(let e of n)r.some(t=>t.metric===e)||t.delete(e);for(let e of r)e.meta&&t.set(e.metric,e.meta);e.metricMeta=t}}var Ed=class{id=`units`;name=`Units Dialect`;units;constructor(e=Uu.standard()){this.units=e}transform(e){Td(e,this.units)}analyze(e){return{}}},Dd=class{id=`crossfit`;name=`CrossFit Dialect`;hasKeyword(e,t){return e.some(e=>(e.type===E.Action||e.type===E.Effort)&&typeof e.value==`string`&&e.value.toUpperCase().includes(t))}hasChildren(e){return e.children&&e.children.length>0}analyze(e){let t=[],n=D.from(e.metrics),r=this.hasKeyword(n,`AMRAP`);r&&(t.push(`behavior.time_bound`),t.push(`workout.amrap`));let i=this.hasKeyword(n,`EMOM`);if(i&&(t.push(`behavior.repeating_interval`),t.push(`workout.emom`)),!i&&!r){let r=n.some(e=>e.type===E.Rounds),i=n.some(e=>e.type===E.Duration),a=this.hasChildren(e);r&&i&&a&&(t.push(`behavior.repeating_interval`),t.push(`workout.emom`),t.push(`workout.implicit_emom`))}return this.hasKeyword(n,`FOR TIME`)&&(t.push(`behavior.time_bound`),t.push(`workout.for_time`)),this.hasKeyword(n,`TABATA`)&&(t.push(`behavior.repeating_interval`),t.push(`workout.tabata`)),{metrics:Lu(t)}}},Od=class{id=`wod`;name=`WOD Dialect`;hasKeyword(e,t){return e.some(e=>(e.type===E.Action||e.type===E.Effort)&&typeof e.value==`string`&&e.value.toUpperCase().includes(t.toUpperCase()))}analyze(e){let t=[],n=D.from(e.metrics);return this.hasKeyword(n,`STRENGTH`)&&(t.push(`domain.wod`),t.push(`workout.strength`),t.push(`behavior.load_bearing`)),(this.hasKeyword(n,`METCON`)||this.hasKeyword(n,`METABOLIC`))&&(t.push(`domain.wod`),t.push(`workout.metcon`)),(this.hasKeyword(n,`SKILL`)||this.hasKeyword(n,`TECHNIQUE`))&&(t.push(`domain.wod`),t.push(`workout.skills`)),this.hasKeyword(n,`WOD`)&&t.push(`domain.wod`),this.hasKeyword(n,`SUPERSET`)&&(t.push(`domain.wod`),t.push(`workout.superset`)),{metrics:Lu(t)}}};let kd=[{keywords:[`RUN`,`JOG`,`SPRINT`],hints:[`workout.run`,`behavior.aerobic`]},{keywords:[`ROW`,`ROWING`],hints:[`workout.row`,`behavior.aerobic`]},{keywords:[`BIKE`,`CYCLE`,`CYCLING`],hints:[`workout.bike`,`behavior.aerobic`]},{keywords:[`SWIM`,`SWIMMING`],hints:[`workout.swim`,`behavior.aerobic`]},{keywords:[`WALK`,`WALKING`],hints:[`workout.walk`]}];var Ad=class{id=`cardio`;name=`Cardio Dialect`;hasKeyword(e,t){return e.some(e=>(e.type===E.Action||e.type===E.Effort)&&typeof e.value==`string`&&e.value.toUpperCase().includes(t.toUpperCase()))}hasDistance(e){return e.some(e=>e.type===E.Distance)}analyze(e){let t=[],n=D.from(e.metrics);for(let e of kd)e.keywords.some(e=>this.hasKeyword(n,e))&&t.push(`domain.cardio`,...e.hints);return t.length===0&&this.hasDistance(n)&&(t.push(`domain.cardio`),t.push(`behavior.distance_based`)),t.includes(`domain.cardio`)&&this.hasDistance(n)&&(t.push(`behavior.distance_based`),t.push(`behavior.pace_based`)),{metrics:Lu(t)}}},jd=class e{id=`yoga`;name=`Yoga Dialect`;static POSE_KEYWORDS=[`WARRIOR`,`DOWNWARD`,`UPWARD`,`CHILD'S POSE`,`COBRA`,`PIGEON`,`TRIANGLE`,`MOUNTAIN`,`TREE POSE`,`LOTUS`,`CORPSE`,`SAVASANA`,`TADASANA`,`VIRABHADRASANA`,`BALASANA`,`ADHO`,`URDHVA`,`UTTANASANA`,`VRKSASANA`];static FLOW_KEYWORDS=[`SUN SALUTATION`,`VINYASA`,`FLOW`,`SEQUENCE`];static BREATHING_KEYWORDS=[`PRANAYAMA`,`BREATH`,`BREATHING`,`NADI SHODHANA`,`KAPALABHATI`,`UJJAYI`,`BOX BREATH`,`WIM HOF`];static MEDITATION_KEYWORDS=[`MEDITATION`,`MEDITATE`,`MINDFULNESS`,`BODY SCAN`,`VISUALIZATION`];hasAnyKeyword(e,t){return e.some(e=>(e.type===E.Action||e.type===E.Effort||e.type===E.Text)&&typeof e.value==`string`&&t.some(t=>e.value.toString().toUpperCase().includes(t)))}analyze(t){let n=[],r=D.from(t.metrics),i=r.some(e=>e.type===E.Duration);return this.hasAnyKeyword(r,e.POSE_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.pose`),i&&n.push(`behavior.hold`)),this.hasAnyKeyword(r,e.FLOW_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.flow`)),this.hasAnyKeyword(r,e.BREATHING_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.breathing`),n.push(`behavior.mindful`)),this.hasAnyKeyword(r,e.MEDITATION_KEYWORDS)&&(n.push(`domain.yoga`),n.push(`workout.meditation`),n.push(`behavior.mindful`)),{metrics:Lu(n)}}},Md=class e{id=`habits`;name=`Habits Dialect`;static HABIT_KEYWORDS=[`DAILY`,`HABIT`,`STREAK`,`CHECK`,`LOG`,`MORNING`,`EVENING`,`ROUTINE`];static STREAK_KEYWORDS=[`STREAK`,`CONSECUTIVE`,`IN A ROW`];hasAnyKeyword(e,t){return e.some(e=>(e.type===E.Action||e.type===E.Effort||e.type===E.Text||e.type===E.Label)&&typeof e.value==`string`&&t.some(t=>e.value.toString().toUpperCase().includes(t)))}analyze(t){let n=[],r=D.from(t.metrics),i=r.some(e=>e.type===E.Duration),a=r.some(e=>e.type===E.Rep);return this.hasAnyKeyword(r,e.HABIT_KEYWORDS)&&(n.push(`domain.habits`),n.push(`behavior.completable`),i?n.push(`workout.habit_timed`):a?n.push(`workout.habit_rep`):(n.push(`workout.habit_check`),n.push(`behavior.daily`))),this.hasAnyKeyword(r,e.STREAK_KEYWORDS)&&(n.includes(`domain.habits`)||n.push(`domain.habits`),n.push(`behavior.streak`),n.push(`behavior.recurring`)),{metrics:Lu(n)}}};let Nd={Discipline:`climb-discipline`,Grade:`climb-grade`,SendType:`climb-send-type`,AttemptCount:`climb-attempt-count`,RouteName:`climb-route-name`,HighPoint:`climb-high-point`},Pd={onsight:`onsight`,os:`onsight`,flash:`flash`,fl:`flash`,redpoint:`redpoint`,rp:`redpoint`,sent:`redpoint`,send:`redpoint`,repeat:`repeat`,"re-send":`repeat`,resend:`repeat`,dogged:`dogged`,hangdog:`dogged`,a0:`dogged`,tr:`top-rope`,toprope:`top-rope`,"top-rope":`top-rope`,dnf:`did-not-finish`,attempted:`did-not-finish`},Fd={boulder:`bouldering`,bouldering:`bouldering`,sport:`sport`,trad:`trad`,"top rope":`top-rope`,toprope:`top-rope`,hangboard:`hangboard`,moonboard:`training-board`,kilter:`training-board`,board:`training-board`};function Id(e){return e?typeof e.value==`string`?e.value:e.value&&typeof e.value==`object`&&`text`in e.value?String(e.value.text??``):typeof e.value==`number`?String(e.value):``:``}function Ld(e){return e.toLowerCase().replace(/[_\s]+/g,`-`).trim()}function Rd(e,t,n,r){e.add({type:t,value:n,origin:`dialect`,unit:r})}function zd(e,t){e.includes(t)||e.push(t)}var Bd=class{id=`climb`;name=`Climb Dialect`;analyze(e){let t=[],n=D.empty(`climb-dialect`),r=D.from(e.metrics).toArray(),i=r.map(Id).filter(Boolean).join(` `),a=this.findRouteName(r);a&&Rd(n,Nd.RouteName,a);let o=this.findGrade(r);o&&Rd(n,Nd.Grade,o);let s=this.findSendType(i);s&&Rd(n,Nd.SendType,s);let c=this.findAttemptCount(r);c!==void 0&&Rd(n,Nd.AttemptCount,c);let l=this.findHighPoint(i);l&&Rd(n,Nd.HighPoint,l);let u=this.findDisciplines(i,o);for(let e of u)Rd(n,Nd.Discipline,e);(a||o||s||l||u.length>0)&&(t.push(`domain.climb`),t.push(`behavior.route_based`)),o&&t.push(`behavior.grade_based`),c!==void 0&&t.push(`behavior.attempt_based`),s===`did-not-finish`&&t.push(`climb.project`);for(let e of u)t.push(`climb.${e.replace(`-`,`_`)}`);return{metrics:Lu(t,n)}}findRouteName(e){let t=e.find(e=>e.type===E.Action&&typeof e.value==`string`);return t?.value?String(t.value):void 0}findGrade(e){for(let t=0;t<e.length;t+=1){let n=e[t],r=Id(n),i=Id(e[t+1]),a=r.match(/\bV(\d{1,2})(?:[-+])?\b/i);if(a){let e=Number(a[1]);return{raw:a[0].toUpperCase(),system:`v-scale`,normalizedRank:e}}if(typeof n.value==`number`&&n.value>=5&&n.value<6){let e=i.match(/^\s*([abcd])\b/i)?.[1],t=e?`${n.value}${e}`:String(n.value);if(/^5\.\d{1,2}[abcd]?$/i.test(t))return{raw:t,system:`yds`,normalizedRank:this.ydsRank(t)}}let o=r.match(/\b5\.(\d{1,2})([abcd])?\b/i);if(o)return{raw:o[0],system:`yds`,normalizedRank:this.ydsRank(o[0])};let s=r.match(/\b([3-9][ABC](?:\+)?)\b/);if(s)return{raw:s[1],system:`font`};if(typeof n.value==`number`&&n.value>=3&&n.value<=9){let e=i.match(/^\s*([ABC]\+?)\b/)?.[1];if(e)return{raw:`${n.value}${e}`,system:`font`}}let c=r.match(/\b([3-9][abc](?:\+)?)\b/);if(c)return{raw:c[1],system:`french`}}}ydsRank(e){let t=e.match(/^5\.(\d{1,2})([abcd])?$/i);if(!t)return;let n=Number(t[1]),r=t[2]?.toLowerCase();return n+(r?[`a`,`b`,`c`,`d`].indexOf(r)/4:0)}findSendType(e){let t=e.toLowerCase().match(/[a-z0-9-]+/g)??[];for(let e of t){let t=Ld(e);if(t in Pd)return Pd[t]}if(/\bnot\s+sent\b/i.test(e))return`did-not-finish`;if(/\bwith\s+falls\b/i.test(e))return`dogged`}findAttemptCount(e){return e.find(e=>{if(e.type!==E.Resistance)return!1;let t=e.value;return t&&typeof t.amount==`number`&&String(t.unit??e.unit??``)===``})?.value?.amount}findHighPoint(e){let t=e.match(/\b(?:bolt|move|crux|high\s*point)\s*\d+\b/i)?.[0];return t?t.toLowerCase().replace(/\s+/g,` `):void 0}findDisciplines(e,t){let n=[],r=e.toLowerCase();for(let[e,t]of Object.entries(Fd))r.includes(e)&&zd(n,t);return(t?.system===`v-scale`||t?.system===`font`)&&zd(n,`bouldering`),(t?.system===`yds`||t?.system===`french`)&&zd(n,`sport`),n}};function Vd(e){console.warn(e)}let Hd={climbing:`climb`},Ud=new Set;new class{dialects;registry;constructor(e){e instanceof Nu?this.registry=e:this.dialects=e}get effectiveDialects(){return this.registry?this.registry.list():this.dialects??[]}dialectsFor(e){let t=this.effectiveDialects;if(!e)return t;let n=Hd[e]??e;return t.some(e=>e.id===n)?t.filter(e=>e.id===`units`||e.id===n):(Ud.has(e)||(Ud.add(e),Vd(`[DialectStack] Unknown :sport suffix "${e}" — falling back to the full dialect stack. Known dialect ids: ${t.map(e=>e.id).join(`, `)}.`)),t)}process(e,t){this.applyDialects(e,this.dialectsFor(t))}processAll(e,t){let n=this.dialectsFor(t);for(let t of e)this.applyDialects(t,n)}applyDialects(e,t){for(let n of t){n.transform?.(e);let t=n.analyze(e);t?.metrics?.length&&e.metrics.add(...t.metrics)}}get list(){return this.effectiveDialects}}(new Nu([new Ed,new Dd,new Od,new Ad,new jd,new Md,new Bd]));let Wd={rpe:E.SessionRPE,rir:E.RIR,intensity:E.Intensity,load:E.Load,volume:E.Volume,work:E.Work,sound:E.Sound};Uu.standard();let Gd=dn.deserialize({version:14,states:`(dQVQPOOO!mQPO'#DPO$TQPO'#CdOOQO'#Cd'#CdOOQO'#Cg'#CgOOQO'#Ch'#ChOOQO'#Cf'#CfO%hQPO'#CfO%pQPO'#CjOOQO'#Cl'#ClOOQO'#DP'#DPOOQO'#Cu'#CuO%xQPO'#CmOOQO'#Cn'#CnOOQO'#Co'#CoOOQO'#Cq'#CqOOQO'#Cr'#CrOOQO'#Cp'#CpO%}QPO'#CpOOQO'#Cs'#CsOOQO'#Ct'#CtO&tQPO'#CvOOQO'#Ce'#CeOOQO'#C|'#C|O(]QPO'#CcO&{QPO'#CcOOQO'#Cz'#CzQVQPOOO(dQPO,58xOOQO,59Q,59QO(rQPO'#CkOOQO'#C}'#C}O)QQPO,59UOOQO-E6}-E6}O)]QPO,59XOOQO,59[,59[OOQO'#DQ'#DQO)hQPO,59bOOQO,59b,59bOOQO-E6z-E6zOOQO,58},58}O)oQPO,58}OOQO-E6x-E6xOOQO'#C{'#C{OOQO1G.d1G.dO)vQPO'#DOO){QPO,59VOOQO-E6{-E6{OOQO1G.p1G.pO*ZQPO1G.sOOQO-E7O-E7OOOQO1G.|1G.|OOQO1G.i1G.iPOQO-E6y-E6yOOQO,59j,59jOOQO-E6|-E6|OOQO7+$_7+$_`,stateData:"+V~OwOS~ORPOTaOUfO]UOyQOzRO{SO|VO}TO!OWO!QXO!RXO!S[O!TYO!V]O!W^O!X_O!Y`O!ZcO![dO!]eO!`jO~OxlORsXTsXUsX]sXysX{sX|sX}sX!OsX!QsX!RsX!SsX!TsX!VsX!WsX!XsX!YsX!ZsX![sX!]sX!`sX~ORWXTWXUWX]WXyWX{WX|WX}WX!OWX!QWX!RWX!SWX!TWX!VWX!WWX!XWX!YWX!ZWX![WX!]WX!`sX~O]mO}TO~ORoOTnO~OxrO~OTsO!Y`O~ORtOStOTtOktOltOmtOxtO!TtO!^tO~O!_vO~P&VORYOTaOUfO]UOyYO{SO|VO}TO!OWO!QXO!RXO!S[O!TYO!V]O!W^O!X_O!Y`O!ZcO![dO!]eO~O!`xO~P&{OR|OS|OT|OU{O~Oy}OR_XT_X!P_X~ORoOTnO!P!QO~ORYOyYO!TYO~O!_!TO~P&VO!`!UO~P&{OT!WO~Oy}OR_aT_a!P_a~ORYOyYO!TYO!U!YO~O!VU!W!Q!R}]!X{|x!Z![!T!]!_!^klmRyzT!`w!T~",goto:`$ZuPPvPPPPvz!O!V!^!eP!V!o!V!V!V!V!V!s!z!V!V!V!VPPP#U#[#_#j#p#v$TTjOkTiOkZgOhikyZfOhikyZVOhikyYUOhikyRmVToWpZbOhikyYaOhikyRsbQkORzkR|lShOkSwhyRyiQpWR!PpQ!OnR!X!OYZOhikyQq!RR!RrQueR!Su`,nodeNames:`⚠ Program Property Identifier String Number TagRef Block Lap Fragment Duration Trend CollectibleTimer Timer Rounds Sequence RoundScheme Action Text Heading Quantity AtSign Question Slash Pipe Effort MetricObject True False Null`,maxTerm:62,skippedNodes:[0],repeatNodeCount:7,tokenData:"7o~RvXY#iYZ#z]^$Ppq#iqr$Vrs$}st'dtu$Vuv$Vvw$Vxy)Pyz)Uz{)Z{|*T|}*Y}!O+S!O!P+X!P!Q,[!Q![-R![!]/U!_!`$V!a!b/n!b!c/s!c!}0m!}#O0{#O#P$V#P#Q1Q#Q#R1V#T#Y0m#Y#Z2P#Z#b0m#b#c4Q#c#h0m#h#i5p#i#o0m#o#p7`#p#q7e#q#r7j~#nSw~XY#iYZ#z]^$Ppq#i~$PO!`~~$SPYZ#z~$[Z!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~%QXOY$}Z]$}^r$}rs%ms#O$}#O#P&_#P;'S$};'S;=`'^<%lO$}~%rXS~OY$}Z]$}^r$}rs%ms#O$}#O#P&_#P;'S$};'S;=`'^<%lO$}~&bRO;'S$};'S;=`&k;=`O$}~&nYOY$}Z]$}^r$}rs%ms#O$}#O#P&_#P;'S$};'S;=`'^;=`<%l$}<%lO$}~'aP;=`<%l$}~'gXO!Q(S!Q![(n![!c(S!c!}(n!}#T(S#T#o(n#o;'S(S;'S;=`(h<%lO(S~(XT!W~OY(SZ](S^;'S(S;'S;=`(h<%lO(S~(kP;=`<%l(S~(sSU~}!O(n!Q![(n!c!}(n#T#o(n~)UO!O~~)ZO!P~~)bZ|~!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~*YOz~~*aZ!T~!^~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~+XOy~~+^[!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!Q![,S!_!`$V!b!c$V#O#P$V#Q#R$V~,XPT~!Q![,S~,aP!Z~!P!Q,d~,iU!V~OY,dZ],d^s,dt;'S,d;'S;=`,{<%lO,d~-OP;=`<%l,d~-WUT~pq-j!O!P._!Q![-R![!].e!z!{.v#l#m.v~-mRpq-j!z!{-v#l#m-v~-yPpq-|~.PQpq-|!Q![.V~.[P!R~!Q![.V~.bP!Q![,S~.hP!Q![.k~.pQ]~!Q![.k![!].e~.yP!Q![.|~/RP!Q~!Q![.|~/ZQx~!Q![/a!a!b/i~/fP]~!Q![/a~/nO}~~/sO!Y~~/zZ!X~!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~0rRR~!Q![0m!c!}0m#T#o0m~1QO!S~~1VO!U~~1^Z{~!T~qr$Vtu$Vuv$Vvw$Vz{$V|}$V!O!P$V!_!`$V!b!c$V#O#P$V#Q#R$V~2USR~!Q![0m!c!}0m#T#U2b#U#o0m~2gTR~!Q![0m!c!}0m#T#`0m#`#a2v#a#o0m~2{TR~!Q![0m!c!}0m#T#g0m#g#h3[#h#o0m~3aTR~!Q![0m!c!}0m#T#X0m#X#Y3p#Y#o0m~3wRl~R~!Q![0m!c!}0m#T#o0m~4VTR~!Q![0m!c!}0m#T#i0m#i#j4f#j#o0m~4kTR~!Q![0m!c!}0m#T#`0m#`#a4z#a#o0m~5PTR~!Q![0m!c!}0m#T#`0m#`#a5`#a#o0m~5gRm~R~!Q![0m!c!}0m#T#o0m~5uTR~!Q![0m!c!}0m#T#f0m#f#g6U#g#o0m~6ZTR~!Q![0m!c!}0m#T#i0m#i#j6j#j#o0m~6oTR~!Q![0m!c!}0m#T#X0m#X#Y7O#Y#o0m~7VRk~R~!Q![0m!c!}0m#T#o0m~7eO!]~~7jO![~~7oO!_~",tokenizers:[0],topRules:{Program:[0,1]},tokenPrec:439}),Kd={defaultMet:5,defaultThreshold:2};[...Object.keys(Wd)],Pl.define({parser:Gd.configure({props:[dl({Identifier:X.variableName,String:X.string,Number:X.number,"schemeNumber schemeSpaced":X.number,Timer:X.keyword,collectibleTimer:X.keyword,textComment:X.lineComment,heading:X.heading,minus:X.operator,plus:X.operator,trend:X.operator,atSign:X.operator,"Slash/slash":X.operator,question:X.keyword,actionOpen:X.bracket,actionClose:X.bracket,groupOpen:X.bracket,groupClose:X.bracket,colon:X.punctuation,Property:X.propertyName,"Block/Lap":X.keyword})]}),languageData:{commentTokens:{line:`//`},closeBrackets:{brackets:[`(`,`[`,`'`,`"`]}}});let qd=[`bodyweight`,`cycling`,`gymnastics`,`kettlebell`,`recovery`,`rowing`,`running`,`strength`,`swimming`,`walking`];function Jd(e){return typeof e==`string`&&qd.includes(e.toLowerCase())}let Q=[];for(let e=0;e<256;++e)Q.push((e+256).toString(16).slice(1));function Yd(e,t=0){return(Q[e[t+0]]+Q[e[t+1]]+Q[e[t+2]]+Q[e[t+3]]+`-`+Q[e[t+4]]+Q[e[t+5]]+`-`+Q[e[t+6]]+Q[e[t+7]]+`-`+Q[e[t+8]]+Q[e[t+9]]+`-`+Q[e[t+10]]+Q[e[t+11]]+Q[e[t+12]]+Q[e[t+13]]+Q[e[t+14]]+Q[e[t+15]]).toLowerCase()}let Xd,Zd=new Uint8Array(16);function Qd(){if(!Xd){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);Xd=crypto.getRandomValues.bind(crypto)}return Xd(Zd)}let $d={};function ef(e,t,n){let r;if(e)r=nf(e.random??e.rng?.()??Qd(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=Qd();tf($d,e,i),r=nf(i,$d.msecs,$d.seq,t,n)}return t??Yd(r)}function tf(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function nf(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}let rf=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/,af=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function of(e){return e.replace(/^(['"])(.*)\1$/,(e,t,n)=>t===`"`?n.replace(/\\(["\\nrt])/g,(e,t)=>t===`n`?`
15
- `:t===`r`?`\r`:t===`t`?` `:t):n)}function sf(e){let t=e.match(rf);if(!t)return{meta:{},body:e};let n=t[1].split(/\r?\n/),r={};for(let e=0;e<n.length;e++){let t=n[e].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);if(!t)continue;let i=t[1],a=t[2].trim();if(a===``){let t=[];for(;e+1<n.length;){let r=n[e+1].match(/^\s+-\s+(.+)$/);if(!r)break;t.push(of(r[1].trim())),e++}r[i]=t.length>0?t:``}else{let e=/^(['"])(.*)\1$/.test(a),t=of(a),n=Number(t);r[i]=!e&&t!==``&&!isNaN(n)?n:t}}return{meta:r,body:e.slice(t[0].length)}}function cf(e,t){let n=e[t];return typeof n==`string`||typeof n==`number`?n:void 0}function lf(e,t){let n=e[t];return n===void 0||typeof n==`string`&&n===`[]`?[]:Array.isArray(n)?n:void 0}function uf(e){return e===`true`?!0:e===`false`?!1:e!==``&&!Number.isNaN(Number(e))?Number(e):of(e)}function df(e,t){let n=e.findIndex(e=>RegExp(`^${t}:\\s*$`).test(e));if(n===-1)return;let r={},i=null;for(let t=n+1;t<e.length;t++){let n=e[t];if(/^\S/.test(n))break;let a=n.trim();if(!a||a.startsWith(`#`))continue;let o=n.length-n.trimStart().length,s=a.match(/^([\w.-]+):\s*(.*)$/);if(!s)continue;let[,c,l]=s;o===2?l===``?(i=c,r[c]={}):(i=null,r[c]=uf(l)):o>=4&&i!==null&&(r[i][c]=uf(l))}return Object.keys(r).length>0?r:void 0}function ff(e){if(!e)return;let t=of(e.trim()).toLowerCase();if(Jd(t))return t;console.warn(`[definition-markdown] unknown discipline '${e}' — expected one of the canonical values; treating as unset`)}function pf(e,t){let n=[],r=e===void 0?``:String(e);return r?af.test(r)||n.push(`Invalid slug: must be lowercase letters, numbers, and hyphens only`):n.push(`Missing required field: slug`),(t===void 0||!String(t).trim())&&n.push(`Missing required field: label`),n}function mf(e,t){let n=[];for(let r of e)r.trim()?t===`equipment`&&!af.test(r)&&n.push(`Invalid ${t}: '${r}' must be a canonical slug (lowercase letters, numbers, hyphens)`):n.push(`Invalid ${t}: blank entries are not allowed`);let r=e.find((t,n)=>e.indexOf(t)!==n);return r!==void 0&&n.push(`Invalid ${t}: duplicate entry '${r}'`),n}function hf(e){return e===void 0?`Missing required field: baseAttributes.met`:typeof e!=`number`||!Number.isFinite(e)||e<=0?`Invalid baseAttributes.met: must be a positive number`:null}function gf(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return null;let n=t[1].split(/\r?\n/),{meta:r,body:i}=sf(e),a=cf(r,`type`);if(a!==void 0&&a!==`effort`)return null;let o=cf(r,`id`),s=cf(r,`slug`),c=cf(r,`label`),l=lf(r,`aliases`),u=lf(r,`equipment`);if(l===void 0||u===void 0||pf(s,c).length>0||mf(l,`aliases`).length>0||u.length>0&&mf(u,`equipment`).length>0)return null;let d=df(n,`baseAttributes`)??{};if(hf(d.met)!==null)return null;let f=d.met,p=ff(typeof d.discipline==`string`?d.discipline:void 0),m=d.intensityTier,h=typeof d.disciplineFactor==`number`&&Number.isFinite(d.disciplineFactor)?d.disciplineFactor:void 0,g=df(n,`hints`),_=df(n,`derivation`),v=i.trim();return{id:String(o??``),slug:String(s),label:String(c),aliases:l,baseAttributes:{met:f,...p?{discipline:p}:{},...h===void 0?{}:{disciplineFactor:h},...m?{intensityTier:m}:{}},registrySource:`bundled`,...u.length>0?{equipment:u}:{},...v?{body:v}:{},...g?{hints:g}:{},..._?{derivation:_}:{}}}function _f(e){let{meta:t,body:n}=sf(e);if(cf(t,`type`)!==`equipment`)return null;let r=cf(t,`id`),i=cf(t,`slug`),a=cf(t,`label`),o=lf(t,`aliases`);if(r===void 0||o===void 0||pf(i,a).length>0||mf(o,`aliases`).length>0)return null;let s=n.trim();return{id:String(r),slug:String(i),label:String(a),aliases:o,registrySource:`bundled`,...s?{body:s}:{}}}let vf=[{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`}];[...vf],vf.length;var yf=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}},bf=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)}};let xf={now:()=>new Date,nowMs:()=>Date.now()};var Sf=class{options;now;type=`next`;constructor(e,t=xf){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:bf.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}};let Cf=e=>String(e).padStart(2,`0`),wf=e=>String(e).padStart(3,`0`);function Tf(e){return`${Cf(e.getHours())}:${Cf(e.getMinutes())}:${Cf(e.getSeconds())}.${wf(e.getMilliseconds())}`}function Ef(e){return(e+` `).slice(0,5)}function Df(e){return(e+` `.repeat(24)).slice(0,24)}function Of(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 kf=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)}] ${Af(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${Of(e)}`,`color: #94a3b8`)}writeLine(e,t,n){let r=Tf(new Date);this._console.log(`${r} %c${Ef(e)}%c ${Df(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 Af(e){try{return JSON.stringify(e)??``}catch{return String(e)}}let jf=new kf;typeof window<`u`&&(window.RuntimeLogger=jf);var Mf=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`),jf.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`&&jf.logPop(a,a.completionReason,e.stack.blocks.length+1),e.stack.current?[...i,new Sf(r,e.nowProvider)]:i):[]}},Nf=class{_memory;ownerId;type;visibility;_logger;id=ef();_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=ef(),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)}}},Pf=class{_references=[];allocate(e,t,n,r=`private`){let i=new Nf(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 Nf&&r.hasSubscribers()&&r.notifySubscribers(void 0,n),this._references.splice(t,1)}}};let Ff=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}({});var If=class{timestamp;constructor(e=xf){this.timestamp=e.now()}},Lf=class extends If{name=`memory:allocate`;data;constructor(e,t,n=xf){super(n),this.data={ref:e,value:t}}},Rf=class extends If{name=`memory:set`;data;constructor(e,t,n,r=xf){super(r),this.data={ref:e,value:t,oldValue:n}}},zf=class extends If{name=`memory:release`;data;constructor(e,t,n=xf){super(n),this.data={ref:e,lastValue:t}}},Bf=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 Pf}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 Lf(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 Rf(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 zf(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===Ff.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(Ff.ANCHOR,this.ownerId,void 0,`public`);return n.id=e,this._references.push(n),n}};let Vf=`time`;function Hf(e){return[new yf(e)]}function Uf(e,t){return e.map((n,r)=>r===e.length-1&&n.ended===void 0?new yf(n.started,t):n)}function Wf(e,t){return[...e,new yf(t)]}function Gf(e){return e.getMemoryByTag(Vf)[0]?.metrics[0]?.value}function Kf(e,t){let n=e.getMemoryByTag(Vf)[0]?.metrics[0],r=n?.value;if(!r||!n)return!1;let i=t(r.spans,e.clock.currentDate.getTime());return e.updateMemory(Vf,[{...n,value:{...r,spans:i}}]),!0}var qf=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 Mf().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 Sf(void 0,e.nowProvider)),t}};function Jf(e,t){let n=0;for(let r of e.spans){let e=r.ended??t;n+=e-r.started}return n}function Yf(e){let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}var Xf=class{current;total;sourceBlockKey;timestamp;type=E.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}`)}},Zf=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:Hf(t),direction:`down`,durationMs:this.config.durationMs,label:n,role:r})]),this.config.durationMs<=0?(this.handleExpiry(e,i),[new qf(e.block.key.toString())]):(this.subscriptions.push(e.subscribe(`tick`,(e,t)=>{let n=Gf(t);return!n||n.direction!==`down`||n.durationMs===void 0||i===`complete-block`&&t.block.isComplete||Jf(n,t.clock.currentDate.getTime())<n.durationMs?[]:(this.handleExpiry(t,i),[new qf(t.block.key.toString())])},{scope:`bubble`})),this.subscriptions.push(e.subscribe(`timer:reset`,(e,t)=>(i===`reset-interval`&&Kf(t,(e,t)=>Hf(t)),[]))),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||Kf(t,Uf)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&Kf(t,Wf)&&(this.isPaused=!1),[]))),[])}onNext(e){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=Gf(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 Kf(e,Uf),[]}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(Kf(e,(e,t)=>Hf(t)),e.hasCapability(`childSelection`))return;let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t){let n=new Xf(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}])}}getRemainingCountdownMs(e){let t=Gf(e);if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=Jf(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}createFragment(e,t){return{type:E.Time,image:Qf(t.durationMs),origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}};function Qf(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 $f=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=D.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:E.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:E.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])}},ep=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 Mf]));this.unsubscribers.push(n)}return[]}onNext(e){return this.config.mode===`deferred`?e.block.isComplete?[new Mf]:[]:this.config.onNext?(e.block.isComplete||e.markComplete(`user-advance`),[new Mf]):[]}onUnmount(e){return[]}onDispose(e){for(let e of this.unsubscribers)e();this.unsubscribers=[]}},tp=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=D.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:E.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`}};Kd.defaultMet;var np=class{value;sourceBlockKey;timestamp;type=E.Elapsed;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return Yf(this.value)}},rp=class{value;sourceBlockKey;timestamp;type=E.Total;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return Yf(this.value)}},ip=class e{spans;sourceBlockKey;timestamp;type=E.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`)}`}},ap=class{value;sourceBlockKey;type=E.SystemTime;origin=`tracked`;constructor(e,t){this.value=e,this.sourceBlockKey=t}get timestamp(){return this.value}get image(){return this.value.toISOString()}},op=class{config;_now;lastEmittedRound;constructor(e={},t=xf){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=Gf(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):D.from([new ap(this._now.now(),e.block.key.toString())],e.block.key.toString());return this.writeResultMemory(e,a),[]}onDispose(e){}collectDisplayFragments(e){let t=D.empty(e.block.key.toString());for(let n of e.block.getMemoryByTag(`metric:display`))t.merge(n.metrics);return t}collectStateFragments(e){let t=D.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=D.empty(e.block.key.toString()).add(new Xf(t.current,t.total,e.block.key.toString(),e.clock.currentDate)),r=Gf(e);if(r){let t=Jf(r,e.clock.currentDate.getTime());n.add(new np(t,e.block.key.toString(),e.clock.currentDate)),r.spans.length>0&&n.add(new ip([...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=Jf(t,i),s=t.spans[0].started,c=t.spans[t.spans.length-1].ended??i,l=Math.max(0,c-s),u=D.empty(a).add(new np(e,a,r),new rp(l,a,r),new ip([...t.spans],a,r),new ap(this._now.now(),a));return o&&u.add(new Xf(o.current,o.total,a,r,n)),u}let s=new yf(i,i),c=D.empty(a).add(new np(0,a,r),new rp(0,a,r),new ip([s],a,r),new ap(this._now.now(),a));return o&&c.add(new Xf(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 np(0,o,i),new rp(0,o,i),new ip([new yf(a,a)],o,i),new ap(this._now.now(),o));return s&&t.add(new Xf(s.current,s.total,o,i,r)),t});let c=Jf(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===E.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 np(a,o,i),new rp(m,o,i),new ip([new yf(h,g)],o,i),new ap(this._now.now(),o));return s&&_.add(new Xf(s.current,s.total,o,i,r)),_})}writeResultMemory(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length>0){let r=sp(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?sp([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 sp(e){let t=[];for(let n of e)for(let e of n.metrics)e.origin===`user`&&t.push(e);return t}var cp=class{sound;trigger;type=E.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 lp(e,t){return e.rules.filter(e=>{let{anchor:n,offsetMs:r}=e.trigger;return n===`start`||r===0||t!==void 0&&r<=t})}let up={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`}]};var dp=class{config;rules=[];fired=new Set;durationMs;constructor(e){this.config=e}onMount(e){let t=Gf(e);return this.durationMs=t?.durationMs,this.rules=lp(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=Gf(e);if(t)return Jf(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 cp(t.sound,i,{atSecond:r/1e3})],{label:`Sound: ${t.sound}`}),e.emitEvent({name:`sound:play`,timestamp:e.clock.currentDate,data:{sound:t.sound,volume:1}})}};let fp=E.Sound;function pp(e,t){let n=mp(e);if(n){let e=hp(t?.profiles,n);if(e)return e}if(t?.noteProfileId){let e=hp(t?.profiles,t.noteProfileId);if(e)return e}return up}function mp(e){for(let t of e){let e=t.metrics.find(e=>e.type===fp);if(!e)continue;let n=e.value;if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function hp(e,t){if(e)return e.find(e=>e.id===t)}let gp=(e,t,n)=>({id:e,kind:`expr`,expression:t,unit:n});_p(),_p(),_p(),vp(),vp();function _p(){return{sRPE:gp(`sRPE`,`rpeSource.rpe`),durationMinutes:gp(`durationMinutes`,`convert(session.duration, min)`),load:gp(`load`,`round(rpeSource.rpe * convert(session.duration, min))`)}}function vp(){return{elapsedMin:gp(`elapsedMin`,`convert(sum(elapsed), min)`),avgMets:gp(`avgMets`,`sum(metMinutes) / elapsedMin`),metMax:gp(`metMax`,`sharedMet.metMax`),metScore:gp(`metScore`,`min(100, avgMets / metMax * 100)`),rpeScore:gp(`rpeScore`,`rpeSource.rpe * 10`),durationScore:gp(`durationScore`,`elapsedMin / 60 * metScore`,`pts`),disciplineFactor:gp(`disciplineFactor`,`lookup("effort", effort, "disciplineFactor")`),tis:gp(`tis`,`round(0.30 * metScore + 0.35 * rpeScore + 0.20 * durationScore + 0.15 * disciplineFactor, 1)`)}}new Nu([]),new Nu([]);var yp=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=D.from(e.flatMap(e=>D.from(e.metrics).toArray()).filter(e=>e.origin!==`runtime`&&e.type!==E.Hint));if(c.length===0)return o;let l=c.find(e=>e.type===E.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&&!id.isStructural(e)).map(e=>e.image).join(` `)||o:m.join(` `).trim().replace(/\s+/g,` `)}static getPrimaryMetric(e){let t=e.find(e=>e.type===E.Rounds);if(t&&t.image)return t.image;let n=e.find(e=>e.type===E.Duration);if(n&&n.image)return n.image}static getLogicKeyword(e,t){if(e.some(e=>zu(e,Pu.LABEL_AMRAP)))return`AMRAP`;if(e.some(e=>zu(e,Pu.LABEL_EMOM)))return`EMOM`;if(e.some(e=>zu(e,Pu.LABEL_TABATA)))return`TABATA`;if(e.some(e=>zu(e,Pu.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===E.Duration||e.type===E.Rounds||e.type===E.Resistance||e.type===E.Distance||e.type===E.Lap||e.type===E.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===E.Resistance||e.type===E.Distance);if(t.length!==0)return t.map(e=>e.image).join(` `).trim()}},bp=class{distribute(e,t){return[e.clone()]}};let xp=e=>e[0];function Sp(e,t){let{statements:n,runtime:r,blockType:i,defaultLabel:a}=t,o=(t.pickStatement??xp)(n),s=t.key??new Te,c=t.context??new Bf(r,s.toString(),o.exerciseId||``),l=yp.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 bp,f=t.filterMetrics,p=n.flatMap(e=>{let t=f?D.from(e.metrics.filter(f)):D.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 Cp=class{priority=90;id=`amrap-logic`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.hasMetric(E.Duration)),r=e.some(e=>e.hasMetric(E.Rounds)),i=e.some(e=>e.metrics.some(e=>(e.type===E.Effort||e.type===E.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(E.Duration))||t[0]).metrics.find(e=>e.type===E.Duration)?.value||0,i=Sp(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(E.Duration))||e[0]});e.addBehavior(new tp({mode:`countdown`,label:i}))}},wp=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===E.Duration)),r=e.some(e=>zu(e,Pu.REPEATING_INTERVAL)),i=e.some(e=>e.metrics.some(e=>(e.type===E.Action||e.type===E.Effort)&&typeof e.value==`string`&&e.value.toLowerCase()===`emom`)),a=e.some(e=>zu(e,Pu.LABEL_AMRAP)||e.metrics.some(e=>e.type===E.Rounds&&typeof e.value==`string`&&e.value.toLowerCase()===`amrap`)),o=e.some(e=>zu(e,Pu.LABEL_TABATA)||e.metrics.some(e=>e.type===E.Effort&&typeof e.value==`string`&&e.value.toLowerCase()===`tabata`)),s=i||e.some(e=>e.metrics.some(e=>e.type===E.Rounds));return n&&(r||i)&&!a&&(!o||s)}apply(e,t,n){let r=(t.find(e=>e.metrics.some(e=>e.type===E.Duration))||t[0]).metrics.find(e=>e.type===E.Duration),i=t.flatMap(e=>D.from(e.metrics).toArray()).find(e=>e.type===E.Rounds),a=r?.value||6e4,o=typeof i?.value==`number`?i.value:10,s=Sp(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(E.Duration))||e[0],metricDistributorType:`EMOM`});e.addBehavior(new tp({mode:`countdown`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===E.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===E.Distance)),u=[...c?[{metricType:E.Resistance,origin:`compiler`}]:[],...l?[{metricType:E.Distance,origin:`compiler`}]:[]];u.length>0&&e.addBehavior(new $f({promotions:u}))}},Tp=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===E.Duration&&e.origin!==`runtime`)),r=e.some(e=>e.metrics.some(e=>e.type===E.Rounds&&e.origin!==`runtime`)),i=e.some(e=>e.children&&e.children.length>0);return!n&&!r&&!i}apply(e,t,n){Sp(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 ep({mode:`immediate`,onNext:!0}))}},Ep=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===E.Duration&&e.origin!==`runtime`)),i=e.some(e=>e.metrics.some(e=>e.type===E.Rounds&&e.origin!==`runtime`));return n&&!r&&!i}apply(e,t,n){if(e.hasTimerBehavior()||e.hasRoundConfig())return;let r=Sp(e,{blockType:`Group`,defaultLabel:`Group`,statements:t,runtime:n});e.addBehavior(new tp({mode:`clock`,label:r}));let i=t.some(e=>e.metrics.some(e=>e.type===E.Resistance)),a=t.some(e=>e.metrics.some(e=>e.type===E.Distance)),o=[...i?[{metricType:E.Resistance,origin:`compiler`}]:[],...a?[{metricType:E.Distance,origin:`compiler`}]:[]];o.length>0&&e.addBehavior(new $f({promotions:o}))}},Dp=class{priority=50;id=`generic-loop`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===E.Rounds))}apply(e,t,n){if(e.hasRoundConfig())return;let r=(t.find(e=>e.metrics.some(e=>e.type===E.Rounds))||t[0]).metrics.find(e=>e.type===E.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===E.Rep&&typeof e.value==`number`)).map(e=>e.value);o.length>0&&(a=o,i<=1&&(i=a.length));let s=Sp(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===E.Rounds))||e[0],filterMetrics:e=>e.type!==E.Rep});e.addBehavior(new tp({mode:`clock`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===E.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===E.Distance)),u=[...c?[{metricType:E.Resistance,origin:`compiler`}]:[],...l?[{metricType:E.Distance,origin:`compiler`}]:[]];e.addBehavior(new $f({repScheme:a,promotions:u})),e.declareExit(`immediate`)}},Op=class{priority=50;id=`generic-timer`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===E.Duration&&e.origin!==`runtime`))}apply(e,t,n){if(e.hasTimerBehavior())return;let r=(t.find(e=>e.metrics.some(e=>e.type===E.Duration&&e.origin!==`runtime`))||t[0]).metrics.find(e=>e.type===E.Duration&&e.origin!==`runtime`),i=r?.direction||`up`,a=r?.value||void 0,o=t.some(e=>zu(e,Pu.REQUIRED_TIMER)),s=t.some(e=>zu(e,Pu.INJECT_REST)),c=!!(a&&i===`down`),l=Sp(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===E.Duration&&e.origin!==`runtime`))||e[0]});o&&c?e.addBehavior(new ep({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})):e.addBehavior(new ep({mode:`immediate`,onNext:!0})),e.addBehavior(new tp({mode:a?`countdown`:`clock`,label:l}))}},kp=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(Zf),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`)}},Ap=class{priority=15;id=`report-output`;match(e,t){return e&&e.length>0}apply(e,t,n){e.hasBehavior(op)||e.addBehavior(new op)}},jp=class{priority=20;id=`sound`;match(e,t){return e.length>0}apply(e,t,n){if(e.hasBehavior(dp)||!e.hasTimerBehavior())return;let r=pp(t,n.options?.soundOptions);e.addBehavior(new dp({profile:r}))}};new Nu([new Cp,new wp,new Op,new Dp,new Ep,new jp,new Ap,new kp,new Tp]).list();let Mp=/^---\r?\n([\s\S]*?)\r?\n---/;function Np(e){let t=Mp.exec(e);if(!t)return{};let n={},r=t[1].split(/\r?\n/),i;for(let e of r){let t=e.trimEnd(),r=t.match(/^\s+-\s+(.*)$/);if(r&&i){n[i].push(r[1].trim());continue}let a=t.match(/^([^:]+):\s*(.*)$/);if(!a)continue;let o=a[1].trim().toLowerCase(),s=a[2].trim();s===``?(n[o]=[],i=o):s.startsWith(`[`)&&s.endsWith(`]`)?(n[o]=s.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^['"]|['"]$/g,``)).filter(e=>e.length>0),i=void 0):(n[o]=s,i=void 0)}return n}let Pp=e=>Array.isArray(e)?e:typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];function Fp(e,t=Xe){let n=Np(e),r=Pp(n.tags).map(e=>({label:e})),i=Object.keys(n);for(let e of t){if(e===`tags`)continue;let t=i.find(t=>t===e.toLowerCase());if(t)for(let i of Pp(n[t]))r.push({label:i,type:e})}return r.filter(e=>e.label.length>0)}let Ip=[`sessionId`,`noteId`,`blockId`,`blockVersion`,`blockContentId`,`origin`,`status`,`startTime`,`endTime`,`duration`,`completed`,`sessionCreatedAt`,`sessionExtraJson`],Lp=`eventId.grain.outputType.timestamp.pageId.effortSlug.eventBlockId.eventBlockVersion.eventBlockContentId.eventOrigin.timeSpan.sourceBlockKey.sourceStatementId.line.text.dialect.stackLevel.completionReason.representationKind.metricType.metricValue.metricUnit.metricImage.metricOrigin.metricMetadata.metricTemporal.metricJson.eventExtraJson`.split(`.`);[...Ip,...Lp];let Rp=De,zp={core:0,community:1,imported:2,user:3};function Bp(e,t){if(t)return t;if(!e)return`core`;if(e===`user`)return`user`;let n=e.startsWith(`seed:`)?e.slice(5):e;return n===`core`||n===`efforts`||n===`equipment`?`core`:n===`community`||n.startsWith(`community-`)||n===`common`?`community`:`imported`}function Vp(e,t){return zp[Bp(e,t)]}let Hp=`canvas`;function Up(e){return`seed:${e}`}function Wp(e){return e.startsWith(`seed:`)?e.slice(5):e}function Gp(e){return{key:e,schema:9,seedVersion:0,builtAt:``,importedAt:0,chunks:{},claim:null}}function Kp(e){let t=/^notebook\.(.+)$/.exec(e)?.[1];return t&&t!==`_root`?t:void 0}function qp(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e);return t?.[1]&&!/^template:\s*canvas\s*$/m.test(t[1])?null:t?.[1]?.match(/^route:\s*(\S+)\s*$/m)?.[1]?.replace(/^\//,``)||null}function Jp(e,t,n){let r=e.split(`/`),i=(r.at(-1)??``).replace(/\.md$/i,``),a=r.slice(2).map(e=>e.replace(/\.md$/i,``)).join(`/`);if(n===`canvas`)return`guides:${qp(t)??a}`;if(n===`dashboards`)return`dashboards`;if(n===`efforts`)return`efforts`;if(n===`equipment`)return`equipment`;if(n.startsWith(`notebook.`)){let e=Kp(n);return e?i.toLowerCase()===`readme`?`notebook:${e}`:`notebook:${a}`:`notebook:_root`}}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function Xp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Zp(e){if(!$(e)||e.schema!==9)throw Error(`Incompatible seed schema; rebuild seed artifacts`);if(!Xp(e.version)||typeof e.builtAt!=`string`||!Number.isFinite(Date.parse(e.builtAt))||!Array.isArray(e.chunks))throw Error(`seed manifest failed shape validation`);for(let t of[`versionLabel`,`commit`,`name`,`description`])if(e[t]!==void 0&&typeof e[t]!=`string`)throw Error(`invalid seed manifest metadata`);if(e.repositoryUrl!==void 0&&(typeof e.repositoryUrl!=`string`||!/^https:\/\//.test(e.repositoryUrl)||new URL(e.repositoryUrl).username||new URL(e.repositoryUrl).password))throw Error(`invalid seed repository URL`);if(e.dirty!==void 0&&typeof e.dirty!=`boolean`)throw Error(`invalid seed manifest metadata`);let t=new Set,n=new Set;for(let r of e.chunks){if(!$(r)||typeof r.id!=`string`||!r.id||typeof r.path!=`string`||!/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(r.path)||typeof r.sha256!=`string`||!/^[0-9a-f]{64}$/.test(r.sha256)||!Xp(r.bytes)||!Xp(r.count)||r.kind!==void 0&&r.kind!==`notes`||t.has(r.id)||n.has(r.path))throw Error(`seed manifest failed shape validation`);t.add(r.id),n.add(r.path)}if(e.notebooks!==void 0){if(!Array.isArray(e.notebooks))throw Error(`seed manifest failed shape validation`);for(let t of e.notebooks)if(!$(t)||typeof t.notebookId!=`string`||typeof t.label!=`string`||!Xp(t.count)||!Array.isArray(t.records))throw Error(`seed manifest failed shape validation`)}return e}function Qp(e){if(!Array.isArray(e))throw Error(`seed chunk is not an array`);let t=new Set;for(let n of e){if(!$(n)||typeof n.path!=`string`||!n.path||n.path.startsWith(`/`)||n.path.split(`/`).includes(`..`)||t.has(n.path)||typeof n.content!=`string`||!$(n.blocks)||!Array.isArray(n.blockIndex)||!Array.isArray(n.blockEfforts)||!Array.isArray(n.blockEquipment))throw Error(`seed chunk row failed shape validation`);t.add(n.path);for(let[e,t]of Object.entries(n.blocks))if(!$(t)||t.id!==e||!e||t.version!==1||t.sourceRevision!==1||!Xp(t.from)||!Yp(t.to)||t.from>=t.to||t.to>n.content.length||![`wod`,`query`,`widget`,`embed`].includes(String(t.kind))||(t.kind===`wod`?![`time`,`log`].includes(String(t.dialect)):t.dialect!==void 0)||t.sport!==void 0&&typeof t.sport!=`string`)throw Error(`invalid seed block range or revision`);Pe(n.content,n.blocks,1,{registeredWidgets:Rp});let e=new Set,r=je(n.content,{registeredWidgets:Rp});for(let t of n.blockIndex){if(!$(t)||typeof t.blockId!=`string`)throw Error(`invalid seed projection`);let i=n.blocks[t.blockId];if(!$(i)||e.has(t.blockId)||typeof t.id!=`string`||typeof t.noteId!=`string`||t.id!==`${t.noteId}:${t.blockId}`||t.blockVersion!==1||t.sourceRevision!==1||t.from!==i.from||t.to!==i.to||t.dataType!==i.kind||t.rawContent!==n.content.slice(Number(i.from),Number(i.to))||typeof t.noteTitle!=`string`||typeof t.createdAt!=`number`||!Number.isFinite(t.createdAt)||t.sourcePath!==n.path||t.isStatic!==!0)throw Error(`orphan or incompatible seed projection`);if(`segmentId`in t||`segmentVersion`in t)throw Error(`incompatible seed projection`);for(let e of[`sourceId`,`routeId`,`blockContentId`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw Error(`invalid seed projection metadata`);if(t.position!==void 0&&!Xp(t.position))throw Error(`invalid seed projection position`);if(i.kind===`wod`){let e=r.find(e=>e.from===i.from&&e.to===i.to);if(t.blockContentId!==Ee(e?.scriptBlock?.content??n.content.slice(Number(i.from),Number(i.to))))throw Error(`invalid seed workout fingerprint`)}else if(t.blockContentId!==void 0)throw Error(`non-workout seed fingerprint`);e.add(t.blockId)}if(e.size!==Object.keys(n.blocks).length)throw Error(`missing actionable seed projection`);let i=new Set;for(let t of n.blockEfforts){if(!$(t)||typeof t.blockId!=`string`||typeof t.noteId!=`string`||typeof t.effortSlug!=`string`||!t.effortSlug)throw Error(`invalid seed effort identity`);let r=n.blocks[t.blockId];if(t.id!==`${t.noteId}:${t.blockId}:${t.effortSlug}`||i.has(String(t.id))||!$(r)||r.kind!==`wod`||!e.has(t.blockId)||t.sourcePath!==n.path||t.isStatic!==!0||typeof t.createdAt!=`number`)throw Error(`orphan or incompatible seed effort link`);let a=n.blockIndex.find(e=>$(e)&&e.blockId===t.blockId);if(!$(a)||t.noteId!==a.noteId||t.blockContentId!==a.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed effort metadata`);i.add(String(t.id))}let a=new Set;for(let t of n.blockEquipment){if(!$(t)||typeof t.blockId!=`string`||typeof t.noteId!=`string`||typeof t.equipmentSlug!=`string`||!t.equipmentSlug)throw Error(`invalid seed equipment identity`);let r=n.blocks[t.blockId];if(t.id!==`${t.noteId}:${t.blockId}:${t.equipmentSlug}`||a.has(String(t.id))||!$(r)||r.kind!==`wod`||!e.has(t.blockId)||t.sourcePath!==n.path||t.isStatic!==!0||typeof t.createdAt!=`number`)throw Error(`orphan or incompatible seed equipment link`);let i=n.blockIndex.find(e=>$(e)&&e.blockId===t.blockId);if(!$(i)||t.noteId!==i.noteId||t.blockContentId!==i.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed equipment metadata`);a.add(String(t.id))}}return e}function $p(e){return Qp([e])[0]}async function em(e){let t=await crypto.subtle.digest(`SHA-1`,new TextEncoder().encode(`1b671a64-40d5-491e-99b0-da01ff1f3341:${e}`)),n=new Uint8Array(t.slice(0,16));n[6]=n[6]&15|80,n[8]=n[8]&63|128;let r=Array.from(n,e=>e.toString(16).padStart(2,`0`)).join(``);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function tm(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!=`object`||typeof t!=`object`)return!1;let n=Object.keys(e).filter(t=>Reflect.get(e,t)!==void 0),r=Object.keys(t).filter(e=>Reflect.get(t,e)!==void 0);return n.length===r.length&&n.every(n=>n in t&&tm(Reflect.get(e,n),Reflect.get(t,n)))}function nm(e){return(e.split(`/`).at(-1)??e).replace(/\.md$/,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}function rm(e,t,n){let r=e.rawContent,i=0,a=r.length,o=t.length;for(;i<a&&i<o&&r[i]===t[i];)i++;for(;a>i&&o>i&&r[a-1]===t[o-1];)a--,o--;let s=Object.values(e.blocks).filter(e=>i<e.to&&a>e.from),c=Fe(s.length<=1?e.blocks:Object.fromEntries(Object.entries(e.blocks).filter(([,e])=>!s.includes(e))),[{from:i,to:a,insert:t.slice(i,o)}]),l=0;return Ne(t,{sourceRevision:n,blocks:c,registeredWidgets:Rp,createId:()=>`seed:${e.id}:r${n}:${l++}`})}async function im(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=new Set(s),m=e=>{let t=-1;for(let n of o)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},h=[],g=i;for(let[e,t]of c.entries()){if(!u.has(l[e]))continue;let r=n(t.content);r&&h.push({...r,registrySource:`bundled`,ownerNoteId:l[e],sourceId:g,sourcePath:t.path})}let _=await e.getMany(h.map(e=>e.slug)),v=h.filter((e,t)=>{let n=_[t];if(!n)return!0;if(n.registrySource!==`bundled`)return!1;let r;if(n.ownerNoteId===e.ownerNoteId||n.ownerNoteId&&p.has(n.ownerNoteId)&&m(n.ownerNoteId)<a)r=a;else{let e=n.ownerNoteId?m(n.ownerNoteId):-1;r=e>=0?e:Vp(n.sourceId)}return a>=r&&!tm(e,n)});v.length&&await e.putMany(v);let y=new Set(h.map(e=>e.slug)),b=new Map;for(let e of f){let t=d.get(e);if(!t||t.seedOrigin!==`seed`)continue;let r=n(t.rawContent)?.slug;r&&!y.has(r)&&b.set(r,e)}let x=[...b.keys()];if(x.length){let a=await e.getMany(x);for(let[s,c]of a.entries()){let a=x[s];if(!c||c.registrySource!==`bundled`)continue;let l=b.get(a);if(!(c.ownerNoteId===l&&(!c.sourceId||c.sourceId===i||c.sourceId===r)))continue;let u=!1;for(let i of o){let o=i.meta.chunks?.[r]?.noteIds??[];if(!o.length)continue;let s=await t.getMany(o);for(let t of s){if(!t||t.seedOrigin!==`seed`)continue;let r=n(t.rawContent);if(r&&r.slug===a){await e.put({...r,registrySource:`bundled`,ownerNoteId:t.id,sourceId:i.sourceId,sourcePath:t.sourcePath??``}),u=!0;break}}if(u)break}u||await e.delete(a)}}return v.length}async function am(e,t,n){if(!t.length)return;let r=await e.getMany(n),i=t.filter((e,t)=>!tm(e,r[t]));i.length&&await e.putMany(i)}async function om(e,t){Zp(t.manifest),Qp(t.rows);let n={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,addedNotes:0,updatedNotes:0},r=await Promise.all(t.rows.map(e=>em(e.path))),i=new Map,a=new Map,o=new Map;for(let[e,n]of t.rows.entries()){let t=Np(n.content).slug;typeof t==`string`&&t.trim()&&(i.set(t,await em(`page:${t}`)),a.set(r[e],await em(`pagenote:${t}:${n.path}`)));for(let{label:e}of Fp(n.content))o.has(e)||o.set(e,await em(`tag:${e}`))}return e.transaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`tags`,`note_tags`,`efforts`,`equipment`,`meta`],`readwrite`,async e=>{let s=e.readwrite(`meta`),c=new Set;for(let e of await s.getAll()){let t=Ue(e?.key);t!==void 0&&c.add(t)}if(!tm(await s.get(t.meta.key),t.expectedMeta))throw Error(`Seed checkpoint changed during import`);if(t.meta.schema!==9||t.manifest.schema!==9)throw Error(`Incompatible seed schema; recreate artifacts`);let l=e.readwrite(`notes`),u=t.chunkId?t.expectedMeta?.chunks[t.chunkId]?.noteIds??[]:[],d=new Set((t.chunkId?t.meta.chunks[t.chunkId]?.noteIds:void 0)??r),f=u.filter(e=>!d.has(e)),p=[...new Set([...r,...f])],m=await l.getMany(p),h=new Map(p.map((e,t)=>[e,m[t]])),g=t.meta.key.startsWith(`seed:`)?t.meta.key.slice(5):t.meta.key,_=Wp(t.meta.key),v=Vp(t.meta.key,t.meta.tier),y=[];for(let e of await s.getAll()){let n=e;if(!n||typeof n.key!=`string`||!n.key.startsWith(`seed:`)||n.key===t.meta.key)continue;let r=new Set;for(let e of Object.values(n.chunks??{}))for(let t of e.noteIds??[])r.add(t);y.push({key:n.key,sourceId:n.key.slice(5),rank:Vp(n.key,n.tier),meta:n,noteIds:r})}y.sort((e,t)=>t.rank-e.rank);let b=e=>{let t=-1;for(let n of y)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},x=p.filter(e=>{if(c.has(e))return!1;let n=h.get(e);if(!n)return d.has(e);if(n.seedOrigin!==`seed`)return!1;let r=b(e);return d.has(e)?v>=r:r<0&&n.seedChunkId===t.chunkId}),S=new Set(x),C=e.readwrite(`block_revisions`),ee=r.filter((e,n)=>S.has(e)&&h.get(e)?.rawContent!==t.rows[n].content),te=await C.getAllFromIndexMany(`by-note`,ee),ne=new Map(ee.map((e,t)=>[e,te[t]])),re=e.readwrite(`block_index`),w=e.readwrite(`block_efforts`),T=e.readwrite(`block_equipment`),ie=e.readwrite(`note_tags`),ae=e.readwrite(`page_notes`),oe=await re.getAllFromIndexMany(`by-note`,x),se=await w.getAllFromIndexMany(`by-note`,x),ce=await T.getAllFromIndexMany(`by-note`,x),le=await ie.getAllFromIndexMany(`by-note`,x),ue=await ae.getAllFromIndexMany(`by-note`,x),E=new Map(x.map((e,t)=>[e,t])),de=e.readwrite(`tags`),fe=[...o.keys()],pe=await de.getAllFromIndexMany(`by-label`,fe),me=new Map(fe.map((e,t)=>[e,pe[t][0]])),he=[],ge=[],_e=[],ve=[],ye=[],be=[],xe=[],Se=[],Ce=[];for(let[e,s]of t.rows.entries()){let c=r[e],l=h.get(c);if(!S.has(c)){l&&l.seedOrigin!==`seed`&&n.skippedUserOwned++;continue}l?l.rawContent!==s.content&&n.updatedNotes++:n.addedNotes++,Pe(s.content,s.blocks,1,{registeredWidgets:Rp});let u=l?l.sourceRevision+(l.rawContent===s.content?0:1):1,d=0,f=ne.get(c)??[],p=l?l.rawContent===s.content?structuredClone(l.blocks):rm(l,s.content,u):f.length?Ne(s.content,{sourceRevision:u,registeredWidgets:Rp,createId:()=>`seed:${c}:new${f.length}:${d++}`}):structuredClone(s.blocks);for(let e of Object.values(p)){let n=(ne.get(c)??[]).filter(t=>t.blockId===e.id).sort((e,t)=>t.version-e.version)[0],r=s.content.slice(e.from,e.to);if(l?.rawContent===s.content)continue;let i=n&&n.kind===e.kind&&n.rawContent===r&&n.dialect===e.dialect&&n.sport===e.sport;e.version=l?i?n.version:(n?.version??0)+1:1,(!l||!i)&&_e.push({noteId:c,blockId:e.id,version:e.version,kind:e.kind,rawContent:r,savedAt:t.meta.importedAt,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}})}Pe(s.content,p,u,{registeredWidgets:Rp});let m=Np(s.content),g=typeof m.title==`string`&&m.title.trim()?m.title.trim():nm(s.path),v=t.chunkId?Jp(s.path,s.content,t.chunkId):void 0;if(!v)throw Error(`Unknown seed source family ${t.chunkId}`);let y=typeof m.date==`string`?m.date.match(/^(\d{4})-(\d{2})-(\d{2})$/):null,b;if(y){let e=Date.parse(`${m.date}T12:00:00Z`);if(!(Number.isFinite(e)&&new Date(e).getUTCMonth()===Number(y[2])-1&&new Date(e).getUTCDate()===Number(y[3])))throw Error(`invalid frontmatter date '${m.date}' in '${s.path}' — expected a real calendar day (YYYY-MM-DD)`);b=e}let x=s.commit??t.manifest.commit,C={...l,id:c,title:g,rawContent:s.content,sourceRevision:u,blocks:p,createdAt:t.manifest.version,...b===void 0?{}:{date:b},type:t.chunkId===`dashboards`?`dashboard`:`note`,sourceId:v,seedOrigin:`seed`,seedVersion:t.manifest.version,seedChunkId:t.chunkId??void 0,feedOrigin:`feed`,feedSourceId:_,sourcePath:s.path,...x?{seedCommit:x}:{}};b===void 0&&delete C.date,tm(C,l)||ge.push(C);let ee=new Map(Object.values(p).map(e=>[`${e.from}:${e.to}`,e])),te=new Map(s.blockIndex.map(e=>[e.blockId,e])),re=new Map;for(let e of s.blockIndex){let t=ee.get(`${e.from}:${e.to}`);if(!t||t.kind!==e.dataType)throw Error(`Orphan seed projection`);re.set(e.blockId,t.id);let n={...e,id:`${c}:${t.id}`,noteId:c,blockId:t.id,blockVersion:t.version,sourceRevision:u,noteTitle:g,sourceId:v,sourcePath:s.path,rawContent:s.content.slice(t.from,t.to)},r=oe[E.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&xe.push(n)}for(let e of s.blockEfforts){let t=re.get(e.blockId);if(!t||te.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed effort link`);let n={...e,id:`${c}:${t}:${e.effortSlug}`,noteId:c,blockId:t,sourcePath:s.path},r=se[E.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&Se.push(r?{...n,createdAt:r.createdAt}:n)}for(let e of s.blockEquipment){let t=re.get(e.blockId);if(!t||te.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed equipment link`);let n={...e,id:`${c}:${t}:${e.equipmentSlug}`,noteId:c,blockId:t,sourcePath:s.path},r=ce[E.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&Ce.push(r?{...n,createdAt:r.createdAt}:n)}let w=E.get(c),T=new Set;for(let e of Fp(s.content)){let n=me.get(e.label);n?e.type&&!n.type&&(n={...n,type:e.type},he.push(n),me.set(e.label,n)):(n={id:o.get(e.label),label:e.label,type:e.type,createdAt:t.meta.importedAt},he.push(n),me.set(e.label,n)),!T.has(n.id)&&(T.add(n.id),le[w].find(e=>e.tagId===n.id)||be.push({id:`${c}:${n.id}`,noteId:c,tagId:n.id}))}for(let e of le[w])T.has(e.tagId)||await ie.delete(e.id);let ae=m.slug;if(typeof ae==`string`&&i.has(ae)){let e=i.get(ae);ve.push({id:e,slug:ae,title:nm(s.path),createdAt:t.manifest.version}),ye.push({id:a.get(c),pageId:e,noteId:c,createdAt:t.manifest.version})}n.totalNotes++,n.totalBlocks+=Object.keys(p).length}let we=new Set(xe.map(e=>e.id)),D=new Set(Se.map(e=>e.id)),Te=new Set(Ce.map(e=>e.id));for(let e of oe)for(let t of e)t.isStatic===!0&&!we.has(t.id)&&await re.delete(t.id);for(let e of se)for(let t of e)t.isStatic===!0&&!D.has(t.id)&&await w.delete(t.id);for(let e of ce)for(let t of e)t.isStatic===!0&&!Te.has(t.id)&&await T.delete(t.id);for(let e of f){if(!S.has(e)||!h.get(e))continue;let t=E.get(e);await l.delete(e);for(let e of le[t])await ie.delete(e.id);for(let e of ue[t])await ae.delete(e.id);n.deleted++}return t.chunkId===`efforts`&&(n.totalEfforts=await im(e.readwrite(`efforts`),l,gf,`efforts`,g,v,y,u,t.rows,r,S,h,p)),t.chunkId===`equipment`&&(n.totalEquipment=await im(e.readwrite(`equipment`),l,_f,`equipment`,g,v,y,u,t.rows,r,S,h,p)),ge.length&&await l.putMany(ge),_e.length&&await C.putMany(_e),await am(re,xe,xe.map(e=>e.id)),await am(w,Se,Se.map(e=>e.id)),await am(T,Ce,Ce.map(e=>e.id)),he.length&&await de.putMany([...new Map(he.map(e=>[e.id,e])).values()]),be.length&&await ie.putMany(be),await am(e.readwrite(`page`),ve,ve.map(e=>e.id)),await am(ae,ye,ye.map(e=>e.id)),await s.put(t.meta),n})}function sm(e,t){let n=t.seedChunkId?e.filter(e=>e.chunkId===t.seedChunkId):[];return[...n.length>0?n:e].sort((e,t)=>t.rank-e.rank||(e.key<t.key?-1:+(e.key>t.key)))[0]}async function cm(e){return await e.transaction([`meta`,`notes`,`block_index`],`readwrite`,async e=>{let t=e.readwrite(`meta`),n=new Map;for(let e of await t.getAll()){let t=e;if(!t||typeof t.key!=`string`||!t.key.startsWith(`seed:`))continue;let r=t.key.slice(5),i=Vp(t.key,t.tier);for(let[e,a]of Object.entries(t.chunks??{}))for(let o of a.noteIds??[]){let a=n.get(o)??[];a.push({sourceId:r,chunkId:e,rank:i,key:t.key}),n.set(o,a)}}if(n.size===0)return 0;let r=e.readwrite(`notes`),i=e.readwrite(`block_index`),a=[...n.keys()],o=await r.getMany(a),s=[];for(let e=0;e<a.length;e++){let t=a[e],i=o[e];if(!i||i.seedOrigin!==`seed`||i.feedSourceId)continue;let c=sm(n.get(t),i),l=i.sourceRevision+1,u=Object.fromEntries(Object.entries(i.blocks).map(([e,t])=>[e,{...t,sourceRevision:l}]));await r.put({...i,blocks:u,sourceRevision:l,feedOrigin:`feed`,feedSourceId:c.sourceId}),s.push({id:t,sourceRevision:l})}if(s.length>0){let e=new Map(s.map(e=>[e.id,e.sourceRevision])),t=(await i.getAllFromIndexMany(`by-note`,s.map(e=>e.id))).flatMap(t=>t.flatMap(t=>{let n=e.get(t.noteId);return n!==void 0&&t.sourceRevision!==n?[{...t,sourceRevision:n}]:[]}));t.length>0&&await i.putMany(t)}return s.length})}async function lm(e){return await e.transaction([`meta`,`notes`,`block_index`,`block_efforts`,`block_equipment`],`readwrite`,async e=>{let t=0,n=e.readwrite(`meta`);for(let e of await n.getAll()){let r=e;if(!r||typeof r.key!=`string`||!r.key.startsWith(`seed:`))continue;let i=r.chunks??{},a=!1,o={};for(let[e,t]of Object.entries(i)){let n=su(e);n!==e&&(a=!0),o[n]=o[n]&&o[n]!==t?{...o[n],noteIds:[...new Set([...o[n].noteIds??[],...t.noteIds??[]])]}:t}a&&(await n.put({...r,chunks:o}),t++)}for(let n of[`notes`,`block_index`,`block_efforts`,`block_equipment`]){let r=e.readwrite(n);for(let e of await r.getAll()){let n=e;fu(n)&&(await r.put(du(n)),t++)}}return t})}var um=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},dm=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 um(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return Zp(await e.json())}async fetchChunk(e){let t=await this.fetchImpl(`${this.baseUrl}${e}`);if(!t.ok)throw new um(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}},fm=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 om(this.storageInstance,e)}backfillFeedProvenance(){return cm(this.storageInstance)}migrateNotebookVocabulary(){return lm(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:Vp(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:gf},{storeName:`equipment`,familyPathPrefix:`markdown/equipment/`,parse:_f}];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})}},pm=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=Zp(await this.source.fetchManifest()),n=Up(this.sourceId),r=await this.storage.getSeedMeta(n),i=r?.schema===9?r:void 0,a=i??Gp(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=t.version!==a.seedVersion||t.builtAt!==a.builtAt,s=t.chunks.filter(t=>e.notebookIds&&!e.notebookIds.includes(t.id)?!1:e.forceAll||o||a.chunks[t.id]?.sha256!==t.sha256);s.sort((e,t)=>Number(t.id===Hp)-Number(e.id===Hp));let c=Object.keys(a.chunks).filter(e=>!t.chunks.some(t=>t.id===e)),l={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,addedNotes:0,updatedNotes:0};if(!s.length&&!c.length&&!o)return l;l.status=`imported`;let u=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:l.appliedChunks,totalChunks:s.length,totalNotes:l.totalNotes,totalEfforts:l.totalEfforts,totalEquipment:l.totalEquipment,totalBlocks:l.totalBlocks,skippedUserOwned:l.skippedUserOwned,deleted:l.deleted,addedNotes:l.addedNotes,updatedNotes:l.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}});for(let n=0;n<s.length;){let r=s.slice(n,n+(s[n]?.id===`canvas`?1:4));for(let n of r){let r,o=t.notebooks?.find(e=>e.notebookId===n.id)?.records??n.records;if(e.granularRecords&&o&&o.length>0){let t=!e.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(o.map(e=>e.uuid)):void 0,i=t?o.filter(e=>t.get(e.uuid)!==e.commit):o,a=[],s=0;for(let e of i){u(`fetching`,n.id,e.uuid,s,i.length);let t=await this.source.fetchChunk(e.recordPath),r=Array.isArray(t)?Qp(t):[$p(t)];a.push(...r),s++}r=a}else if(u(`fetching`,n.id),r=Qp(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`);let s=e.granularRecords&&o&&o.length>0?o.map(e=>e.uuid):await Promise.all(r.map(e=>em(e.path))),c={...a,chunks:{...a.chunks,[n.id]:{sha256:n.sha256,noteIds:s}},importedAt:this.now()};u(`applying`,n.id);let d=await this.storage.applyChunk({chunkId:n.id,rows:r,manifest:t,expectedMeta:i,meta:c});l.totalNotes+=d.totalNotes,l.totalEfforts+=d.totalEfforts,l.totalEquipment+=d.totalEquipment,l.totalBlocks+=d.totalBlocks,l.skippedUserOwned+=d.skippedUserOwned,l.deleted+=d.deleted,l.addedNotes+=d.addedNotes,l.updatedNotes+=d.updatedNotes,l.appliedChunks++,a=c,i=c,u(`committed`,n.id),n.id===`canvas`&&e.onFirstPaintApplied?.()}n+=r.length}for(let e of c){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});l.deleted+=o.deleted,a=r,i=r}let d={...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:d}),u(`finalizing`,null),l}};function mm(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function hm(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}function gm(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 _m(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function vm(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=Up(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&&hm(c,e.embeddedVersion))return s.outcome=`current`,s;if(_m(c,i,a()))return s.outcome=`busy`,s;let l=Zp(await e.source.fetchManifest());s.manifestChecked=!0;let u=t.force?`import`:mm(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=u===`import`?`update-pending`:`current`,s;if(!t.force&&u===`current`&&c?.schema===9&&c.builtAt===l.builtAt)return s.outcome=`current`,s;let d={...c??Gp(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(d,c??null);try{let i=await new pm(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:e.granularRecords});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=gm(t),s}}let ym=self;ym.onmessage=e=>{if(e.data.type!==`run`)return;let t=e.data;(async()=>{let e=new fm(new Ou({dbName:t.dbName,...t.userId?{getUserId:()=>t.userId}:{}})),n=[];for(let r of t.sources){let i=await vm({id:r.id,label:r.label,source:new dm(r.url),embeddedVersion:r.embeddedVersion,autoSyncOn:r.autoSyncOn,...r.tier?{tier:r.tier}:{},notebookIds:r.notebookIds,granularRecords:r.granularRecords??!0},{storage:e,owner:t.owner,now:Date.now,force:t.force,probeManifests:t.probeManifests,background:t.background},{onProgress:e=>ym.postMessage({type:`progress`,sourceId:r.id,progress:e}),onFirstPaint:()=>ym.postMessage({type:`first-paint`,sourceId:r.id})});ym.postMessage({type:`source-result`,sourceId:r.id,result:i}),n.push(i.outcome)}ym.postMessage({type:`done`,outcomes:n})})()}})();
16
- //# sourceMappingURL=feedSync.worker-CEbxagtY.js.map
15
+ `:t===`r`?`\r`:t===`t`?` `:t):n)}function sf(e){let t=e.match(rf);if(!t)return{meta:{},body:e};let n=t[1].split(/\r?\n/),r={};for(let e=0;e<n.length;e++){let t=n[e].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);if(!t)continue;let i=t[1],a=t[2].trim();if(a===``){let t=[];for(;e+1<n.length;){let r=n[e+1].match(/^\s+-\s+(.+)$/);if(!r)break;t.push(of(r[1].trim())),e++}r[i]=t.length>0?t:``}else{let e=/^(['"])(.*)\1$/.test(a),t=of(a),n=Number(t);r[i]=!e&&t!==``&&!isNaN(n)?n:t}}return{meta:r,body:e.slice(t[0].length)}}function cf(e,t){let n=e[t];return typeof n==`string`||typeof n==`number`?n:void 0}function lf(e,t){let n=e[t];return n===void 0||typeof n==`string`&&n===`[]`?[]:Array.isArray(n)?n:void 0}function uf(e){return e===`true`?!0:e===`false`?!1:e!==``&&!Number.isNaN(Number(e))?Number(e):of(e)}function df(e,t){let n=e.findIndex(e=>RegExp(`^${t}:\\s*$`).test(e));if(n===-1)return;let r={},i=null;for(let t=n+1;t<e.length;t++){let n=e[t];if(/^\S/.test(n))break;let a=n.trim();if(!a||a.startsWith(`#`))continue;let o=n.length-n.trimStart().length,s=a.match(/^([\w.-]+):\s*(.*)$/);if(!s)continue;let[,c,l]=s;o===2?l===``?(i=c,r[c]={}):(i=null,r[c]=uf(l)):o>=4&&i!==null&&(r[i][c]=uf(l))}return Object.keys(r).length>0?r:void 0}function ff(e){if(!e)return;let t=of(e.trim()).toLowerCase();if(Jd(t))return t;console.warn(`[definition-markdown] unknown discipline '${e}' — expected one of the canonical values; treating as unset`)}function pf(e,t){let n=[],r=e===void 0?``:String(e);return r?af.test(r)||n.push(`Invalid slug: must be lowercase letters, numbers, and hyphens only`):n.push(`Missing required field: slug`),(t===void 0||!String(t).trim())&&n.push(`Missing required field: label`),n}function mf(e,t){let n=[];for(let r of e)r.trim()?t===`equipment`&&!af.test(r)&&n.push(`Invalid ${t}: '${r}' must be a canonical slug (lowercase letters, numbers, hyphens)`):n.push(`Invalid ${t}: blank entries are not allowed`);let r=e.find((t,n)=>e.indexOf(t)!==n);return r!==void 0&&n.push(`Invalid ${t}: duplicate entry '${r}'`),n}function hf(e){return e===void 0?`Missing required field: baseAttributes.met`:typeof e!=`number`||!Number.isFinite(e)||e<=0?`Invalid baseAttributes.met: must be a positive number`:null}function gf(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return null;let n=t[1].split(/\r?\n/),{meta:r,body:i}=sf(e),a=cf(r,`type`);if(a!==void 0&&a!==`effort`)return null;let o=cf(r,`id`),s=cf(r,`slug`),c=cf(r,`label`),l=lf(r,`aliases`),u=lf(r,`equipment`);if(l===void 0||u===void 0||pf(s,c).length>0||mf(l,`aliases`).length>0||u.length>0&&mf(u,`equipment`).length>0)return null;let d=df(n,`baseAttributes`)??{},f=df(n,`metrics`)??{},p=r[`metrics.met`]??f.met??d.met;if(hf(p)!==null)return null;let m=Number(p),h=cf(r,`discipline`),g=ff(typeof h==`string`?h:typeof d.discipline==`string`?d.discipline:void 0),_=cf(r,`intensityTier`)??cf(r,`intensity`)??d.intensityTier,v=r[`metrics.disciplineFactor`]??f.disciplineFactor??d.disciplineFactor,y=typeof v==`number`&&Number.isFinite(v)?v:void 0,b=df(n,`hints`),x=df(n,`derivation`),S=i.trim();return{id:String(o??``),slug:String(s),label:String(c),aliases:l,baseAttributes:{met:m,...g?{discipline:g}:{},...y===void 0?{}:{disciplineFactor:y},..._?{intensityTier:_}:{}},registrySource:`bundled`,...u.length>0?{equipment:u}:{},...S?{body:S}:{},...b?{hints:b}:{},...x?{derivation:x}:{}}}function _f(e){let{meta:t,body:n}=sf(e);if(cf(t,`type`)!==`equipment`)return null;let r=cf(t,`id`),i=cf(t,`slug`),a=cf(t,`label`),o=lf(t,`aliases`);if(r===void 0||o===void 0||pf(i,a).length>0||mf(o,`aliases`).length>0)return null;let s=n.trim();return{id:String(r),slug:String(i),label:String(a),aliases:o,registrySource:`bundled`,...s?{body:s}:{}}}let vf=[{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`}];[...vf],vf.length;var yf=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}},bf=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)}};let xf={now:()=>new Date,nowMs:()=>Date.now()};var Sf=class{options;now;type=`next`;constructor(e,t=xf){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:bf.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}};let Cf=e=>String(e).padStart(2,`0`),wf=e=>String(e).padStart(3,`0`);function Tf(e){return`${Cf(e.getHours())}:${Cf(e.getMinutes())}:${Cf(e.getSeconds())}.${wf(e.getMilliseconds())}`}function Ef(e){return(e+` `).slice(0,5)}function Df(e){return(e+` `.repeat(24)).slice(0,24)}function Of(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 kf=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)}] ${Af(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${Of(e)}`,`color: #94a3b8`)}writeLine(e,t,n){let r=Tf(new Date);this._console.log(`${r} %c${Ef(e)}%c ${Df(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 Af(e){try{return JSON.stringify(e)??``}catch{return String(e)}}let jf=new kf;typeof window<`u`&&(window.RuntimeLogger=jf);var Mf=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`),jf.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`&&jf.logPop(a,a.completionReason,e.stack.blocks.length+1),e.stack.current?[...i,new Sf(r,e.nowProvider)]:i):[]}},Nf=class{_memory;ownerId;type;visibility;_logger;id=ef();_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=ef(),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)}}},Pf=class{_references=[];allocate(e,t,n,r=`private`){let i=new Nf(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 Nf&&r.hasSubscribers()&&r.notifySubscribers(void 0,n),this._references.splice(t,1)}}};let Ff=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}({});var If=class{timestamp;constructor(e=xf){this.timestamp=e.now()}},Lf=class extends If{name=`memory:allocate`;data;constructor(e,t,n=xf){super(n),this.data={ref:e,value:t}}},Rf=class extends If{name=`memory:set`;data;constructor(e,t,n,r=xf){super(r),this.data={ref:e,value:t,oldValue:n}}},zf=class extends If{name=`memory:release`;data;constructor(e,t,n=xf){super(n),this.data={ref:e,lastValue:t}}},Bf=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 Pf}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 Lf(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 Rf(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 zf(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===Ff.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(Ff.ANCHOR,this.ownerId,void 0,`public`);return n.id=e,this._references.push(n),n}};let Vf=`time`;function Hf(e){return[new yf(e)]}function Uf(e,t){return e.map((n,r)=>r===e.length-1&&n.ended===void 0?new yf(n.started,t):n)}function Wf(e,t){return[...e,new yf(t)]}function Gf(e){return e.getMemoryByTag(Vf)[0]?.metrics[0]?.value}function Kf(e,t){let n=e.getMemoryByTag(Vf)[0]?.metrics[0],r=n?.value;if(!r||!n)return!1;let i=t(r.spans,e.clock.currentDate.getTime());return e.updateMemory(Vf,[{...n,value:{...r,spans:i}}]),!0}var qf=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 Mf().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 Sf(void 0,e.nowProvider)),t}};function Jf(e,t){let n=0;for(let r of e.spans){let e=r.ended??t;n+=e-r.started}return n}function Yf(e){let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}var Xf=class{current;total;sourceBlockKey;timestamp;type=E.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}`)}},Zf=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:Hf(t),direction:`down`,durationMs:this.config.durationMs,label:n,role:r})]),this.config.durationMs<=0?(this.handleExpiry(e,i),[new qf(e.block.key.toString())]):(this.subscriptions.push(e.subscribe(`tick`,(e,t)=>{let n=Gf(t);return!n||n.direction!==`down`||n.durationMs===void 0||i===`complete-block`&&t.block.isComplete||Jf(n,t.clock.currentDate.getTime())<n.durationMs?[]:(this.handleExpiry(t,i),[new qf(t.block.key.toString())])},{scope:`bubble`})),this.subscriptions.push(e.subscribe(`timer:reset`,(e,t)=>(i===`reset-interval`&&Kf(t,(e,t)=>Hf(t)),[]))),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||Kf(t,Uf)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&Kf(t,Wf)&&(this.isPaused=!1),[]))),[])}onNext(e){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=Gf(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 Kf(e,Uf),[]}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(Kf(e,(e,t)=>Hf(t)),e.hasCapability(`childSelection`))return;let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t){let n=new Xf(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}])}}getRemainingCountdownMs(e){let t=Gf(e);if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=Jf(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}createFragment(e,t){return{type:E.Time,image:Qf(t.durationMs),origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}};function Qf(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 $f=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=D.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:E.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:E.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])}},ep=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 Mf]));this.unsubscribers.push(n)}return[]}onNext(e){return this.config.mode===`deferred`?e.block.isComplete?[new Mf]:[]:this.config.onNext?(e.block.isComplete||e.markComplete(`user-advance`),[new Mf]):[]}onUnmount(e){return[]}onDispose(e){for(let e of this.unsubscribers)e();this.unsubscribers=[]}},tp=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=D.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:E.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`}};Kd.defaultMet;var np=class{value;sourceBlockKey;timestamp;type=E.Elapsed;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return Yf(this.value)}},rp=class{value;sourceBlockKey;timestamp;type=E.Total;origin=`analyzed`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return Yf(this.value)}},ip=class e{spans;sourceBlockKey;timestamp;type=E.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`)}`}},ap=class{value;sourceBlockKey;type=E.SystemTime;origin=`tracked`;constructor(e,t){this.value=e,this.sourceBlockKey=t}get timestamp(){return this.value}get image(){return this.value.toISOString()}},op=class{config;_now;lastEmittedRound;constructor(e={},t=xf){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=Gf(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):D.from([new ap(this._now.now(),e.block.key.toString())],e.block.key.toString());return this.writeResultMemory(e,a),[]}onDispose(e){}collectDisplayFragments(e){let t=D.empty(e.block.key.toString());for(let n of e.block.getMemoryByTag(`metric:display`))t.merge(n.metrics);return t}collectStateFragments(e){let t=D.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=D.empty(e.block.key.toString()).add(new Xf(t.current,t.total,e.block.key.toString(),e.clock.currentDate)),r=Gf(e);if(r){let t=Jf(r,e.clock.currentDate.getTime());n.add(new np(t,e.block.key.toString(),e.clock.currentDate)),r.spans.length>0&&n.add(new ip([...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=Jf(t,i),s=t.spans[0].started,c=t.spans[t.spans.length-1].ended??i,l=Math.max(0,c-s),u=D.empty(a).add(new np(e,a,r),new rp(l,a,r),new ip([...t.spans],a,r),new ap(this._now.now(),a));return o&&u.add(new Xf(o.current,o.total,a,r,n)),u}let s=new yf(i,i),c=D.empty(a).add(new np(0,a,r),new rp(0,a,r),new ip([s],a,r),new ap(this._now.now(),a));return o&&c.add(new Xf(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 np(0,o,i),new rp(0,o,i),new ip([new yf(a,a)],o,i),new ap(this._now.now(),o));return s&&t.add(new Xf(s.current,s.total,o,i,r)),t});let c=Jf(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===E.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 np(a,o,i),new rp(m,o,i),new ip([new yf(h,g)],o,i),new ap(this._now.now(),o));return s&&_.add(new Xf(s.current,s.total,o,i,r)),_})}writeResultMemory(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length>0){let r=sp(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?sp([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 sp(e){let t=[];for(let n of e)for(let e of n.metrics)e.origin===`user`&&t.push(e);return t}var cp=class{sound;trigger;type=E.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 lp(e,t){return e.rules.filter(e=>{let{anchor:n,offsetMs:r}=e.trigger;return n===`start`||r===0||t!==void 0&&r<=t})}let up={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`}]};var dp=class{config;rules=[];fired=new Set;durationMs;constructor(e){this.config=e}onMount(e){let t=Gf(e);return this.durationMs=t?.durationMs,this.rules=lp(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=Gf(e);if(t)return Jf(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 cp(t.sound,i,{atSecond:r/1e3})],{label:`Sound: ${t.sound}`}),e.emitEvent({name:`sound:play`,timestamp:e.clock.currentDate,data:{sound:t.sound,volume:1}})}};let fp=E.Sound;function pp(e,t){let n=mp(e);if(n){let e=hp(t?.profiles,n);if(e)return e}if(t?.noteProfileId){let e=hp(t?.profiles,t.noteProfileId);if(e)return e}return up}function mp(e){for(let t of e){let e=t.metrics.find(e=>e.type===fp);if(!e)continue;let n=e.value;if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function hp(e,t){if(e)return e.find(e=>e.id===t)}let gp=(e,t,n)=>({id:e,kind:`expr`,expression:t,unit:n});_p(),_p(),_p(),vp(),vp();function _p(){return{sRPE:gp(`sRPE`,`rpeSource.rpe`),durationMinutes:gp(`durationMinutes`,`convert(session.duration, min)`),load:gp(`load`,`round(rpeSource.rpe * convert(session.duration, min))`)}}function vp(){return{elapsedMin:gp(`elapsedMin`,`convert(sum(elapsed), min)`),avgMets:gp(`avgMets`,`sum(metMinutes) / elapsedMin`),metMax:gp(`metMax`,`sharedMet.metMax`),metScore:gp(`metScore`,`min(100, avgMets / metMax * 100)`),rpeScore:gp(`rpeScore`,`rpeSource.rpe * 10`),durationScore:gp(`durationScore`,`elapsedMin / 60 * metScore`,`pts`),disciplineFactor:gp(`disciplineFactor`,`lookup("effort", effort, "disciplineFactor")`),tis:gp(`tis`,`round(0.30 * metScore + 0.35 * rpeScore + 0.20 * durationScore + 0.15 * disciplineFactor, 1)`)}}new Nu([]),new Nu([]);var yp=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=D.from(e.flatMap(e=>D.from(e.metrics).toArray()).filter(e=>e.origin!==`runtime`&&e.type!==E.Hint));if(c.length===0)return o;let l=c.find(e=>e.type===E.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&&!id.isStructural(e)).map(e=>e.image).join(` `)||o:m.join(` `).trim().replace(/\s+/g,` `)}static getPrimaryMetric(e){let t=e.find(e=>e.type===E.Rounds);if(t&&t.image)return t.image;let n=e.find(e=>e.type===E.Duration);if(n&&n.image)return n.image}static getLogicKeyword(e,t){if(e.some(e=>zu(e,Pu.LABEL_AMRAP)))return`AMRAP`;if(e.some(e=>zu(e,Pu.LABEL_EMOM)))return`EMOM`;if(e.some(e=>zu(e,Pu.LABEL_TABATA)))return`TABATA`;if(e.some(e=>zu(e,Pu.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===E.Duration||e.type===E.Rounds||e.type===E.Resistance||e.type===E.Distance||e.type===E.Lap||e.type===E.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===E.Resistance||e.type===E.Distance);if(t.length!==0)return t.map(e=>e.image).join(` `).trim()}},bp=class{distribute(e,t){return[e.clone()]}};let xp=e=>e[0];function Sp(e,t){let{statements:n,runtime:r,blockType:i,defaultLabel:a}=t,o=(t.pickStatement??xp)(n),s=t.key??new Te,c=t.context??new Bf(r,s.toString(),o.exerciseId||``),l=yp.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 bp,f=t.filterMetrics,p=n.flatMap(e=>{let t=f?D.from(e.metrics.filter(f)):D.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 Cp=class{priority=90;id=`amrap-logic`;match(e,t){if(!e||e.length===0)return!1;let n=e.some(e=>e.hasMetric(E.Duration)),r=e.some(e=>e.hasMetric(E.Rounds)),i=e.some(e=>e.metrics.some(e=>(e.type===E.Effort||e.type===E.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(E.Duration))||t[0]).metrics.find(e=>e.type===E.Duration)?.value||0,i=Sp(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(E.Duration))||e[0]});e.addBehavior(new tp({mode:`countdown`,label:i}))}},wp=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===E.Duration)),r=e.some(e=>zu(e,Pu.REPEATING_INTERVAL)),i=e.some(e=>e.metrics.some(e=>(e.type===E.Action||e.type===E.Effort)&&typeof e.value==`string`&&e.value.toLowerCase()===`emom`)),a=e.some(e=>zu(e,Pu.LABEL_AMRAP)||e.metrics.some(e=>e.type===E.Rounds&&typeof e.value==`string`&&e.value.toLowerCase()===`amrap`)),o=e.some(e=>zu(e,Pu.LABEL_TABATA)||e.metrics.some(e=>e.type===E.Effort&&typeof e.value==`string`&&e.value.toLowerCase()===`tabata`)),s=i||e.some(e=>e.metrics.some(e=>e.type===E.Rounds));return n&&(r||i)&&!a&&(!o||s)}apply(e,t,n){let r=(t.find(e=>e.metrics.some(e=>e.type===E.Duration))||t[0]).metrics.find(e=>e.type===E.Duration),i=t.flatMap(e=>D.from(e.metrics).toArray()).find(e=>e.type===E.Rounds),a=r?.value||6e4,o=typeof i?.value==`number`?i.value:10,s=Sp(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(E.Duration))||e[0],metricDistributorType:`EMOM`});e.addBehavior(new tp({mode:`countdown`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===E.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===E.Distance)),u=[...c?[{metricType:E.Resistance,origin:`compiler`}]:[],...l?[{metricType:E.Distance,origin:`compiler`}]:[]];u.length>0&&e.addBehavior(new $f({promotions:u}))}},Tp=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===E.Duration&&e.origin!==`runtime`)),r=e.some(e=>e.metrics.some(e=>e.type===E.Rounds&&e.origin!==`runtime`)),i=e.some(e=>e.children&&e.children.length>0);return!n&&!r&&!i}apply(e,t,n){Sp(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 ep({mode:`immediate`,onNext:!0}))}},Ep=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===E.Duration&&e.origin!==`runtime`)),i=e.some(e=>e.metrics.some(e=>e.type===E.Rounds&&e.origin!==`runtime`));return n&&!r&&!i}apply(e,t,n){if(e.hasTimerBehavior()||e.hasRoundConfig())return;let r=Sp(e,{blockType:`Group`,defaultLabel:`Group`,statements:t,runtime:n});e.addBehavior(new tp({mode:`clock`,label:r}));let i=t.some(e=>e.metrics.some(e=>e.type===E.Resistance)),a=t.some(e=>e.metrics.some(e=>e.type===E.Distance)),o=[...i?[{metricType:E.Resistance,origin:`compiler`}]:[],...a?[{metricType:E.Distance,origin:`compiler`}]:[]];o.length>0&&e.addBehavior(new $f({promotions:o}))}},Dp=class{priority=50;id=`generic-loop`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===E.Rounds))}apply(e,t,n){if(e.hasRoundConfig())return;let r=(t.find(e=>e.metrics.some(e=>e.type===E.Rounds))||t[0]).metrics.find(e=>e.type===E.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===E.Rep&&typeof e.value==`number`)).map(e=>e.value);o.length>0&&(a=o,i<=1&&(i=a.length));let s=Sp(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===E.Rounds))||e[0],filterMetrics:e=>e.type!==E.Rep});e.addBehavior(new tp({mode:`clock`,label:s}));let c=t.some(e=>e.metrics.some(e=>e.type===E.Resistance)),l=t.some(e=>e.metrics.some(e=>e.type===E.Distance)),u=[...c?[{metricType:E.Resistance,origin:`compiler`}]:[],...l?[{metricType:E.Distance,origin:`compiler`}]:[]];e.addBehavior(new $f({repScheme:a,promotions:u})),e.declareExit(`immediate`)}},Op=class{priority=50;id=`generic-timer`;match(e,t){return!e||e.length===0?!1:e.some(e=>e.metrics.some(e=>e.type===E.Duration&&e.origin!==`runtime`))}apply(e,t,n){if(e.hasTimerBehavior())return;let r=(t.find(e=>e.metrics.some(e=>e.type===E.Duration&&e.origin!==`runtime`))||t[0]).metrics.find(e=>e.type===E.Duration&&e.origin!==`runtime`),i=r?.direction||`up`,a=r?.value||void 0,o=t.some(e=>zu(e,Pu.REQUIRED_TIMER)),s=t.some(e=>zu(e,Pu.INJECT_REST)),c=!!(a&&i===`down`),l=Sp(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===E.Duration&&e.origin!==`runtime`))||e[0]});o&&c?e.addBehavior(new ep({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})):e.addBehavior(new ep({mode:`immediate`,onNext:!0})),e.addBehavior(new tp({mode:a?`countdown`:`clock`,label:l}))}},kp=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(Zf),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`)}},Ap=class{priority=15;id=`report-output`;match(e,t){return e&&e.length>0}apply(e,t,n){e.hasBehavior(op)||e.addBehavior(new op)}},jp=class{priority=20;id=`sound`;match(e,t){return e.length>0}apply(e,t,n){if(e.hasBehavior(dp)||!e.hasTimerBehavior())return;let r=pp(t,n.options?.soundOptions);e.addBehavior(new dp({profile:r}))}};new Nu([new Cp,new wp,new Op,new Dp,new Ep,new jp,new Ap,new kp,new Tp]).list();let Mp=/^---\r?\n([\s\S]*?)\r?\n---/;function Np(e){let t=Mp.exec(e);if(!t)return{};let n={},r=t[1].split(/\r?\n/),i;for(let e of r){let t=e.trimEnd(),r=t.match(/^\s+-\s+(.*)$/);if(r&&i){n[i].push(r[1].trim());continue}let a=t.match(/^([^:]+):\s*(.*)$/);if(!a)continue;let o=a[1].trim().toLowerCase(),s=a[2].trim();s===``?(n[o]=[],i=o):s.startsWith(`[`)&&s.endsWith(`]`)?(n[o]=s.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^['"]|['"]$/g,``)).filter(e=>e.length>0),i=void 0):(n[o]=s,i=void 0)}return n}let Pp=e=>Array.isArray(e)?e:typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];function Fp(e,t=Xe){let n=Np(e),r=Pp(n.tags).map(e=>({label:e})),i=Object.keys(n);for(let e of t){if(e===`tags`)continue;let t=i.find(t=>t===e.toLowerCase());if(t)for(let i of Pp(n[t]))r.push({label:i,type:e})}return r.filter(e=>e.label.length>0)}let Ip=[`sessionId`,`noteId`,`blockId`,`blockVersion`,`blockContentId`,`origin`,`status`,`startTime`,`endTime`,`duration`,`completed`,`sessionCreatedAt`,`sessionExtraJson`],Lp=`eventId.grain.outputType.timestamp.pageId.effortSlug.eventBlockId.eventBlockVersion.eventBlockContentId.eventOrigin.timeSpan.sourceBlockKey.sourceStatementId.line.text.dialect.stackLevel.completionReason.representationKind.metricType.metricValue.metricUnit.metricImage.metricOrigin.metricMetadata.metricTemporal.metricJson.eventExtraJson`.split(`.`);[...Ip,...Lp];let Rp=De,zp={core:0,community:1,imported:2,user:3};function Bp(e,t){if(t)return t;if(!e)return`core`;if(e===`user`)return`user`;let n=e.startsWith(`seed:`)?e.slice(5):e;return n===`core`||n===`efforts`||n===`equipment`?`core`:n===`community`||n.startsWith(`community-`)||n===`common`?`community`:`imported`}function Vp(e,t){return zp[Bp(e,t)]}let Hp=`canvas`;function Up(e){return`seed:${e}`}function Wp(e){return e.startsWith(`seed:`)?e.slice(5):e}function Gp(e){return{key:e,schema:9,seedVersion:0,builtAt:``,importedAt:0,chunks:{},claim:null}}function Kp(e){let t=/^notebook\.(.+)$/.exec(e)?.[1];return t&&t!==`_root`?t:void 0}function qp(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e);return t?.[1]&&!/^template:\s*canvas\s*$/m.test(t[1])?null:t?.[1]?.match(/^route:\s*(\S+)\s*$/m)?.[1]?.replace(/^\//,``)||null}function Jp(e,t,n){let r=e.split(`/`),i=(r.at(-1)??``).replace(/\.md$/i,``),a=r.slice(2).map(e=>e.replace(/\.md$/i,``)).join(`/`);if(n===`canvas`)return`guides:${qp(t)??a}`;if(n===`dashboards`)return`dashboards`;if(n===`efforts`)return`efforts`;if(n===`equipment`)return`equipment`;if(n.startsWith(`notebook.`)){let e=Kp(n);return e?i.toLowerCase()===`readme`?`notebook:${e}`:`notebook:${a}`:`notebook:_root`}}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function Xp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Zp(e){if(!$(e)||e.schema!==9)throw Error(`Incompatible seed schema; rebuild seed artifacts`);if(!Xp(e.version)||typeof e.builtAt!=`string`||!Number.isFinite(Date.parse(e.builtAt))||!Array.isArray(e.chunks))throw Error(`seed manifest failed shape validation`);for(let t of[`versionLabel`,`commit`,`name`,`description`])if(e[t]!==void 0&&typeof e[t]!=`string`)throw Error(`invalid seed manifest metadata`);if(e.repositoryUrl!==void 0&&(typeof e.repositoryUrl!=`string`||!/^https:\/\//.test(e.repositoryUrl)||new URL(e.repositoryUrl).username||new URL(e.repositoryUrl).password))throw Error(`invalid seed repository URL`);if(e.dirty!==void 0&&typeof e.dirty!=`boolean`)throw Error(`invalid seed manifest metadata`);let t=new Set,n=new Set;for(let r of e.chunks){if(!$(r)||typeof r.id!=`string`||!r.id||typeof r.path!=`string`||!/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(r.path)||typeof r.sha256!=`string`||!/^[0-9a-f]{64}$/.test(r.sha256)||!Xp(r.bytes)||!Xp(r.count)||r.kind!==void 0&&r.kind!==`notes`||t.has(r.id)||n.has(r.path))throw Error(`seed manifest failed shape validation`);t.add(r.id),n.add(r.path)}if(e.notebooks!==void 0){if(!Array.isArray(e.notebooks))throw Error(`seed manifest failed shape validation`);for(let t of e.notebooks){if(!$(t)||typeof t.notebookId!=`string`||!t.notebookId||typeof t.label!=`string`||!Xp(t.count)||typeof t.indexPath!=`string`||!t.indexPath||!Xp(t.version)||typeof t.commit!=`string`||typeof t.builtAt!=`string`||typeof t.sha256!=`string`||!Xp(t.bytes))throw Error(`seed manifest failed shape validation`);if(`records`in t&&Array.isArray(t.records))throw Error(`seed manifest failed shape validation: manifest.notebooks must not contain inline records`)}}return e}function Qp(e){if(!$(e))throw Error(`notebook index failed shape validation`);if(typeof e.notebookId!=`string`||!e.notebookId||typeof e.label!=`string`||typeof e.indexPath!=`string`||!e.indexPath||!Xp(e.version)||typeof e.commit!=`string`||typeof e.builtAt!=`string`||typeof e.sha256!=`string`||!Xp(e.bytes)||!Xp(e.count)||!Array.isArray(e.records))throw Error(`notebook index failed shape validation: missing required index summary or records`);for(let t of e.records)if(!$(t)||typeof t.uuid!=`string`||typeof t.path!=`string`||typeof t.recordPath!=`string`||typeof t.commit!=`string`||!Xp(t.version)||typeof t.sha256!=`string`)throw Error(`notebook index failed shape validation: invalid record ref`);return e}function $p(e){if(!Array.isArray(e))throw Error(`seed chunk is not an array`);let t=new Set;for(let n of e){if(!$(n)||typeof n.path!=`string`||!n.path||n.path.startsWith(`/`)||n.path.split(`/`).includes(`..`)||t.has(n.path)||typeof n.content!=`string`||!$(n.blocks)||!Array.isArray(n.blockIndex)||!Array.isArray(n.blockEfforts)||!Array.isArray(n.blockEquipment))throw Error(`seed chunk row failed shape validation`);t.add(n.path);for(let[e,t]of Object.entries(n.blocks))if(!$(t)||t.id!==e||!e||t.version!==1||t.sourceRevision!==1||!Xp(t.from)||!Yp(t.to)||t.from>=t.to||t.to>n.content.length||![`wod`,`query`,`widget`,`embed`].includes(String(t.kind))||(t.kind===`wod`?![`time`,`log`].includes(String(t.dialect)):t.dialect!==void 0)||t.sport!==void 0&&typeof t.sport!=`string`)throw Error(`invalid seed block range or revision`);Pe(n.content,n.blocks,1,{registeredWidgets:Rp});let e=new Set,r=je(n.content,{registeredWidgets:Rp});for(let t of n.blockIndex){if(!$(t)||typeof t.blockId!=`string`)throw Error(`invalid seed projection`);let i=n.blocks[t.blockId];if(!$(i)||e.has(t.blockId)||typeof t.id!=`string`||typeof t.noteId!=`string`||t.id!==`${t.noteId}:${t.blockId}`||t.blockVersion!==1||t.sourceRevision!==1||t.from!==i.from||t.to!==i.to||t.dataType!==i.kind||t.rawContent!==n.content.slice(Number(i.from),Number(i.to))||typeof t.noteTitle!=`string`||typeof t.createdAt!=`number`||!Number.isFinite(t.createdAt)||t.sourcePath!==n.path||t.isStatic!==!0)throw Error(`orphan or incompatible seed projection`);if(`segmentId`in t||`segmentVersion`in t)throw Error(`incompatible seed projection`);for(let e of[`sourceId`,`routeId`,`blockContentId`])if(t[e]!==void 0&&typeof t[e]!=`string`)throw Error(`invalid seed projection metadata`);if(t.position!==void 0&&!Xp(t.position))throw Error(`invalid seed projection position`);if(i.kind===`wod`){let e=r.find(e=>e.from===i.from&&e.to===i.to);if(t.blockContentId!==Ee(e?.scriptBlock?.content??n.content.slice(Number(i.from),Number(i.to))))throw Error(`invalid seed workout fingerprint`)}else if(t.blockContentId!==void 0)throw Error(`non-workout seed fingerprint`);e.add(t.blockId)}if(e.size!==Object.keys(n.blocks).length)throw Error(`missing actionable seed projection`);let i=new Set;for(let t of n.blockEfforts){if(!$(t)||typeof t.blockId!=`string`||typeof t.noteId!=`string`||typeof t.effortSlug!=`string`||!t.effortSlug)throw Error(`invalid seed effort identity`);let r=n.blocks[t.blockId];if(t.id!==`${t.noteId}:${t.blockId}:${t.effortSlug}`||i.has(String(t.id))||!$(r)||r.kind!==`wod`||!e.has(t.blockId)||t.sourcePath!==n.path||t.isStatic!==!0||typeof t.createdAt!=`number`)throw Error(`orphan or incompatible seed effort link`);let a=n.blockIndex.find(e=>$(e)&&e.blockId===t.blockId);if(!$(a)||t.noteId!==a.noteId||t.blockContentId!==a.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed effort metadata`);i.add(String(t.id))}let a=new Set;for(let t of n.blockEquipment){if(!$(t)||typeof t.blockId!=`string`||typeof t.noteId!=`string`||typeof t.equipmentSlug!=`string`||!t.equipmentSlug)throw Error(`invalid seed equipment identity`);let r=n.blocks[t.blockId];if(t.id!==`${t.noteId}:${t.blockId}:${t.equipmentSlug}`||a.has(String(t.id))||!$(r)||r.kind!==`wod`||!e.has(t.blockId)||t.sourcePath!==n.path||t.isStatic!==!0||typeof t.createdAt!=`number`)throw Error(`orphan or incompatible seed equipment link`);let i=n.blockIndex.find(e=>$(e)&&e.blockId===t.blockId);if(!$(i)||t.noteId!==i.noteId||t.blockContentId!==i.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed equipment metadata`);a.add(String(t.id))}}return e}function em(e){return $p([e])[0]}async function tm(e){let t=await crypto.subtle.digest(`SHA-1`,new TextEncoder().encode(`1b671a64-40d5-491e-99b0-da01ff1f3341:${e}`)),n=new Uint8Array(t.slice(0,16));n[6]=n[6]&15|80,n[8]=n[8]&63|128;let r=Array.from(n,e=>e.toString(16).padStart(2,`0`)).join(``);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function nm(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!=`object`||typeof t!=`object`)return!1;let n=Object.keys(e).filter(t=>Reflect.get(e,t)!==void 0),r=Object.keys(t).filter(e=>Reflect.get(t,e)!==void 0);return n.length===r.length&&n.every(n=>n in t&&nm(Reflect.get(e,n),Reflect.get(t,n)))}function rm(e){return(e.split(`/`).at(-1)??e).replace(/\.md$/,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}function im(e,t,n){let r=e.rawContent,i=0,a=r.length,o=t.length;for(;i<a&&i<o&&r[i]===t[i];)i++;for(;a>i&&o>i&&r[a-1]===t[o-1];)a--,o--;let s=Object.values(e.blocks).filter(e=>i<e.to&&a>e.from),c=Fe(s.length<=1?e.blocks:Object.fromEntries(Object.entries(e.blocks).filter(([,e])=>!s.includes(e))),[{from:i,to:a,insert:t.slice(i,o)}]),l=0;return Ne(t,{sourceRevision:n,blocks:c,registeredWidgets:Rp,createId:()=>`seed:${e.id}:r${n}:${l++}`})}async function am(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=new Set(s),m=e=>{let t=-1;for(let n of o)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},h=[],g=i;for(let[e,t]of c.entries()){if(!u.has(l[e]))continue;let r=n(t.content);r&&h.push({...r,registrySource:`bundled`,ownerNoteId:l[e],sourceId:g,sourcePath:t.path})}let _=await e.getMany(h.map(e=>e.slug)),v=h.filter((e,t)=>{let n=_[t];if(!n)return!0;if(n.registrySource!==`bundled`)return!1;let r;if(n.ownerNoteId===e.ownerNoteId||n.ownerNoteId&&p.has(n.ownerNoteId)&&m(n.ownerNoteId)<a)r=a;else{let e=n.ownerNoteId?m(n.ownerNoteId):-1;r=e>=0?e:Vp(n.sourceId)}return a>=r&&!nm(e,n)});v.length&&await e.putMany(v);let y=new Set(h.map(e=>e.slug)),b=new Map;for(let e of f){let t=d.get(e);if(!t||t.seedOrigin!==`seed`)continue;let r=n(t.rawContent)?.slug;r&&!y.has(r)&&b.set(r,e)}let x=[...b.keys()];if(x.length){let a=await e.getMany(x);for(let[s,c]of a.entries()){let a=x[s];if(!c||c.registrySource!==`bundled`)continue;let l=b.get(a);if(!(c.ownerNoteId===l&&(!c.sourceId||c.sourceId===i||c.sourceId===r)))continue;let u=!1;for(let i of o){let o=i.meta.chunks?.[r]?.noteIds??[];if(!o.length)continue;let s=await t.getMany(o);for(let t of s){if(!t||t.seedOrigin!==`seed`)continue;let r=n(t.rawContent);if(r&&r.slug===a){await e.put({...r,registrySource:`bundled`,ownerNoteId:t.id,sourceId:i.sourceId,sourcePath:t.sourcePath??``}),u=!0;break}}if(u)break}u||await e.delete(a)}}return v.length}async function om(e,t,n){if(!t.length)return;let r=await e.getMany(n),i=t.filter((e,t)=>!nm(e,r[t]));i.length&&await e.putMany(i)}async function sm(e,t){Zp(t.manifest),$p(t.rows);let n={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,addedNotes:0,updatedNotes:0},r=await Promise.all(t.rows.map(e=>tm(e.path))),i=new Map,a=new Map,o=new Map;for(let[e,n]of t.rows.entries()){let t=Np(n.content).slug;typeof t==`string`&&t.trim()&&(i.set(t,await tm(`page:${t}`)),a.set(r[e],await tm(`pagenote:${t}:${n.path}`)));for(let{label:e}of Fp(n.content))o.has(e)||o.set(e,await tm(`tag:${e}`))}return e.transaction([`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`tags`,`note_tags`,`efforts`,`equipment`,`meta`],`readwrite`,async e=>{let s=e.readwrite(`meta`),c=new Set;for(let e of await s.getAll()){let t=Ue(e?.key);t!==void 0&&c.add(t)}if(!nm(await s.get(t.meta.key),t.expectedMeta))throw Error(`Seed checkpoint changed during import`);if(t.meta.schema!==9||t.manifest.schema!==9)throw Error(`Incompatible seed schema; recreate artifacts`);let l=e.readwrite(`notes`),u=t.chunkId?t.expectedMeta?.chunks[t.chunkId]?.noteIds??[]:[],d=new Set((t.chunkId?t.meta.chunks[t.chunkId]?.noteIds:void 0)??r),f=u.filter(e=>!d.has(e)),p=[...new Set([...r,...f])],m=await l.getMany(p),h=new Map(p.map((e,t)=>[e,m[t]])),g=t.meta.key.startsWith(`seed:`)?t.meta.key.slice(5):t.meta.key,_=Wp(t.meta.key),v=Vp(t.meta.key,t.meta.tier),y=[];for(let e of await s.getAll()){let n=e;if(!n||typeof n.key!=`string`||!n.key.startsWith(`seed:`)||n.key===t.meta.key)continue;let r=new Set;for(let e of Object.values(n.chunks??{}))for(let t of e.noteIds??[])r.add(t);y.push({key:n.key,sourceId:n.key.slice(5),rank:Vp(n.key,n.tier),meta:n,noteIds:r})}y.sort((e,t)=>t.rank-e.rank);let b=e=>{let t=-1;for(let n of y)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},x=p.filter(e=>{if(c.has(e))return!1;let n=h.get(e);if(!n)return d.has(e);if(n.seedOrigin!==`seed`)return!1;let r=b(e);return d.has(e)?v>=r:r<0&&n.seedChunkId===t.chunkId}),S=new Set(x),C=e.readwrite(`block_revisions`),ee=r.filter((e,n)=>S.has(e)&&h.get(e)?.rawContent!==t.rows[n].content),te=await C.getAllFromIndexMany(`by-note`,ee),ne=new Map(ee.map((e,t)=>[e,te[t]])),re=e.readwrite(`block_index`),w=e.readwrite(`block_efforts`),T=e.readwrite(`block_equipment`),ie=e.readwrite(`note_tags`),ae=e.readwrite(`page_notes`),oe=await re.getAllFromIndexMany(`by-note`,x),se=await w.getAllFromIndexMany(`by-note`,x),ce=await T.getAllFromIndexMany(`by-note`,x),le=await ie.getAllFromIndexMany(`by-note`,x),ue=await ae.getAllFromIndexMany(`by-note`,x),E=new Map(x.map((e,t)=>[e,t])),de=e.readwrite(`tags`),fe=[...o.keys()],pe=await de.getAllFromIndexMany(`by-label`,fe),me=new Map(fe.map((e,t)=>[e,pe[t][0]])),he=[],ge=[],_e=[],ve=[],ye=[],be=[],xe=[],Se=[],Ce=[];for(let[e,s]of t.rows.entries()){let c=r[e],l=h.get(c);if(!S.has(c)){l&&l.seedOrigin!==`seed`&&n.skippedUserOwned++;continue}l?l.rawContent!==s.content&&n.updatedNotes++:n.addedNotes++,Pe(s.content,s.blocks,1,{registeredWidgets:Rp});let u=l?l.sourceRevision+(l.rawContent===s.content?0:1):1,d=0,f=ne.get(c)??[],p=l?l.rawContent===s.content?structuredClone(l.blocks):im(l,s.content,u):f.length?Ne(s.content,{sourceRevision:u,registeredWidgets:Rp,createId:()=>`seed:${c}:new${f.length}:${d++}`}):structuredClone(s.blocks);for(let e of Object.values(p)){let n=(ne.get(c)??[]).filter(t=>t.blockId===e.id).sort((e,t)=>t.version-e.version)[0],r=s.content.slice(e.from,e.to);if(l?.rawContent===s.content)continue;let i=n&&n.kind===e.kind&&n.rawContent===r&&n.dialect===e.dialect&&n.sport===e.sport;e.version=l?i?n.version:(n?.version??0)+1:1,(!l||!i)&&_e.push({noteId:c,blockId:e.id,version:e.version,kind:e.kind,rawContent:r,savedAt:t.meta.importedAt,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}})}Pe(s.content,p,u,{registeredWidgets:Rp});let m=Np(s.content),g=typeof m.title==`string`&&m.title.trim()?m.title.trim():rm(s.path),v=t.chunkId?Jp(s.path,s.content,t.chunkId):void 0;if(!v)throw Error(`Unknown seed source family ${t.chunkId}`);let y=typeof m.date==`string`?m.date.match(/^(\d{4})-(\d{2})-(\d{2})$/):null,b;if(y){let e=Date.parse(`${m.date}T12:00:00Z`);if(!(Number.isFinite(e)&&new Date(e).getUTCMonth()===Number(y[2])-1&&new Date(e).getUTCDate()===Number(y[3])))throw Error(`invalid frontmatter date '${m.date}' in '${s.path}' — expected a real calendar day (YYYY-MM-DD)`);b=e}let x=s.commit??t.manifest.commit,C={...l,id:c,title:g,rawContent:s.content,sourceRevision:u,blocks:p,createdAt:t.manifest.version,...b===void 0?{}:{date:b},type:t.chunkId===`dashboards`?`dashboard`:`note`,sourceId:v,seedOrigin:`seed`,seedVersion:t.manifest.version,seedChunkId:t.chunkId??void 0,feedOrigin:`feed`,feedSourceId:_,sourcePath:s.path,...x?{seedCommit:x}:{}};b===void 0&&delete C.date,nm(C,l)||ge.push(C);let ee=new Map(Object.values(p).map(e=>[`${e.from}:${e.to}`,e])),te=new Map(s.blockIndex.map(e=>[e.blockId,e])),re=new Map;for(let e of s.blockIndex){let t=ee.get(`${e.from}:${e.to}`);if(!t||t.kind!==e.dataType)throw Error(`Orphan seed projection`);re.set(e.blockId,t.id);let n={...e,id:`${c}:${t.id}`,noteId:c,blockId:t.id,blockVersion:t.version,sourceRevision:u,noteTitle:g,sourceId:v,sourcePath:s.path,rawContent:s.content.slice(t.from,t.to)},r=oe[E.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&xe.push(n)}for(let e of s.blockEfforts){let t=re.get(e.blockId);if(!t||te.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed effort link`);let n={...e,id:`${c}:${t}:${e.effortSlug}`,noteId:c,blockId:t,sourcePath:s.path},r=se[E.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&Se.push(r?{...n,createdAt:r.createdAt}:n)}for(let e of s.blockEquipment){let t=re.get(e.blockId);if(!t||te.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed equipment link`);let n={...e,id:`${c}:${t}:${e.equipmentSlug}`,noteId:c,blockId:t,sourcePath:s.path},r=ce[E.get(c)].find(e=>e.id===n.id);(!r||r.isStatic===!0)&&Ce.push(r?{...n,createdAt:r.createdAt}:n)}let w=E.get(c),T=new Set;for(let e of Fp(s.content)){let n=me.get(e.label);n?e.type&&!n.type&&(n={...n,type:e.type},he.push(n),me.set(e.label,n)):(n={id:o.get(e.label),label:e.label,type:e.type,createdAt:t.meta.importedAt},he.push(n),me.set(e.label,n)),!T.has(n.id)&&(T.add(n.id),le[w].find(e=>e.tagId===n.id)||be.push({id:`${c}:${n.id}`,noteId:c,tagId:n.id}))}for(let e of le[w])T.has(e.tagId)||await ie.delete(e.id);let ae=m.slug;if(typeof ae==`string`&&i.has(ae)){let e=i.get(ae);ve.push({id:e,slug:ae,title:rm(s.path),createdAt:t.manifest.version}),ye.push({id:a.get(c),pageId:e,noteId:c,createdAt:t.manifest.version})}n.totalNotes++,n.totalBlocks+=Object.keys(p).length}let we=new Set(xe.map(e=>e.id)),D=new Set(Se.map(e=>e.id)),Te=new Set(Ce.map(e=>e.id));for(let e of oe)for(let t of e)t.isStatic===!0&&!we.has(t.id)&&await re.delete(t.id);for(let e of se)for(let t of e)t.isStatic===!0&&!D.has(t.id)&&await w.delete(t.id);for(let e of ce)for(let t of e)t.isStatic===!0&&!Te.has(t.id)&&await T.delete(t.id);for(let e of f){if(!S.has(e)||!h.get(e))continue;let t=E.get(e);await l.delete(e);for(let e of le[t])await ie.delete(e.id);for(let e of ue[t])await ae.delete(e.id);n.deleted++}return t.chunkId===`efforts`&&(n.totalEfforts=await am(e.readwrite(`efforts`),l,gf,`efforts`,g,v,y,u,t.rows,r,S,h,p)),t.chunkId===`equipment`&&(n.totalEquipment=await am(e.readwrite(`equipment`),l,_f,`equipment`,g,v,y,u,t.rows,r,S,h,p)),ge.length&&await l.putMany(ge),_e.length&&await C.putMany(_e),await om(re,xe,xe.map(e=>e.id)),await om(w,Se,Se.map(e=>e.id)),await om(T,Ce,Ce.map(e=>e.id)),he.length&&await de.putMany([...new Map(he.map(e=>[e.id,e])).values()]),be.length&&await ie.putMany(be),await om(e.readwrite(`page`),ve,ve.map(e=>e.id)),await om(ae,ye,ye.map(e=>e.id)),await s.put(t.meta),n})}function cm(e,t){let n=t.seedChunkId?e.filter(e=>e.chunkId===t.seedChunkId):[];return[...n.length>0?n:e].sort((e,t)=>t.rank-e.rank||(e.key<t.key?-1:+(e.key>t.key)))[0]}async function lm(e){return await e.transaction([`meta`,`notes`,`block_index`],`readwrite`,async e=>{let t=e.readwrite(`meta`),n=new Map;for(let e of await t.getAll()){let t=e;if(!t||typeof t.key!=`string`||!t.key.startsWith(`seed:`))continue;let r=t.key.slice(5),i=Vp(t.key,t.tier);for(let[e,a]of Object.entries(t.chunks??{}))for(let o of a.noteIds??[]){let a=n.get(o)??[];a.push({sourceId:r,chunkId:e,rank:i,key:t.key}),n.set(o,a)}}if(n.size===0)return 0;let r=e.readwrite(`notes`),i=e.readwrite(`block_index`),a=[...n.keys()],o=await r.getMany(a),s=[];for(let e=0;e<a.length;e++){let t=a[e],i=o[e];if(!i||i.seedOrigin!==`seed`||i.feedSourceId)continue;let c=cm(n.get(t),i),l=i.sourceRevision+1,u=Object.fromEntries(Object.entries(i.blocks).map(([e,t])=>[e,{...t,sourceRevision:l}]));await r.put({...i,blocks:u,sourceRevision:l,feedOrigin:`feed`,feedSourceId:c.sourceId}),s.push({id:t,sourceRevision:l})}if(s.length>0){let e=new Map(s.map(e=>[e.id,e.sourceRevision])),t=(await i.getAllFromIndexMany(`by-note`,s.map(e=>e.id))).flatMap(t=>t.flatMap(t=>{let n=e.get(t.noteId);return n!==void 0&&t.sourceRevision!==n?[{...t,sourceRevision:n}]:[]}));t.length>0&&await i.putMany(t)}return s.length})}async function um(e){return await e.transaction([`meta`,`notes`,`block_index`,`block_efforts`,`block_equipment`],`readwrite`,async e=>{let t=0,n=e.readwrite(`meta`);for(let e of await n.getAll()){let r=e;if(!r||typeof r.key!=`string`||!r.key.startsWith(`seed:`))continue;let i=r.chunks??{},a=!1,o={};for(let[e,t]of Object.entries(i)){let n=su(e);n!==e&&(a=!0),o[n]=o[n]&&o[n]!==t?{...o[n],noteIds:[...new Set([...o[n].noteIds??[],...t.noteIds??[]])]}:t}a&&(await n.put({...r,chunks:o}),t++)}for(let n of[`notes`,`block_index`,`block_efforts`,`block_equipment`]){let r=e.readwrite(n);for(let e of await r.getAll()){let n=e;fu(n)&&(await r.put(du(n)),t++)}}return t})}var dm=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},fm=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 dm(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return Zp(await e.json())}async fetchChunk(e){let t=await this.fetchImpl(`${this.baseUrl}${e}`);if(!t.ok)throw new dm(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}},pm=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 sm(this.storageInstance,e)}backfillFeedProvenance(){return lm(this.storageInstance)}migrateNotebookVocabulary(){return um(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:Vp(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:gf},{storeName:`equipment`,familyPathPrefix:`markdown/equipment/`,parse:_f}];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})}},mm=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=Zp(e.manifest??await this.source.fetchManifest()),n=Up(this.sourceId),r=e.stored===void 0?await this.storage.getSeedMeta(n):e.stored,i=r?.schema===9?r:void 0,a=i??Gp(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===Hp)-Number(e.id===Hp));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=Qp(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=$p(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)?$p(a):[em(a)];e.push(...o),t++}r=e}}else if(d(`fetching`,n.id),r=$p(await this.source.fetchChunk(n.path)),r.length!==n.count)throw Error(`Seed chunk count mismatch`)}else if(d(`fetching`,n.id),r=$p(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=>tm(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}};function hm(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function gm(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}function _m(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 vm(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function ym(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=Up(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&&gm(c,e.embeddedVersion))return s.outcome=`current`,s;if(vm(c,i,a()))return s.outcome=`busy`,s;let l=Zp(await e.source.fetchManifest());s.manifestChecked=!0;let u=t.force?`import`:hm(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??Gp(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(d,c??null);try{let i=await new mm(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=_m(t),s}}let bm=self;bm.onmessage=e=>{if(e.data.type!==`run`)return;let t=e.data;(async()=>{let e=new pm(new Ou({dbName:t.dbName,...t.userId?{getUserId:()=>t.userId}:{}})),n=[];for(let r of t.sources){let i=await ym({id:r.id,label:r.label,source:new fm(r.url),embeddedVersion:r.embeddedVersion,autoSyncOn:r.autoSyncOn,...r.tier?{tier:r.tier}:{},notebookIds:r.notebookIds,granularRecords:r.granularRecords??!0},{storage:e,owner:t.owner,now:Date.now,force:t.force,probeManifests:t.probeManifests,background:t.background},{onProgress:e=>bm.postMessage({type:`progress`,sourceId:r.id,progress:e}),onFirstPaint:()=>bm.postMessage({type:`first-paint`,sourceId:r.id})});bm.postMessage({type:`source-result`,sourceId:r.id,result:i}),n.push(i.outcome)}bm.postMessage({type:`done`,outcomes:n})})()}})();
16
+ //# sourceMappingURL=feedSync.worker-BKsDG4P0.js.map