@bitcobblers/wod-wiki-tools 0.63.2275 → 0.63.2277
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.
- package/dist/{agentCommands-EMSQQULU.mjs → agentCommands-2JG7EWTL.mjs} +3 -3
- package/dist/{agentCommands-EMSQQULU.mjs.map → agentCommands-2JG7EWTL.mjs.map} +1 -1
- package/dist/bin/wod.cjs +1 -1
- package/dist/bin/wod.cjs.map +1 -1
- package/dist/bin/wod.mjs +2 -2
- package/dist/{chunk-P765CSYD.mjs → chunk-5HNRARXN.mjs} +3 -3
- package/dist/{chunk-P765CSYD.mjs.map → chunk-5HNRARXN.mjs.map} +1 -1
- package/dist/{chunk-WNLCOTKS.mjs → chunk-CAKQ4DZC.mjs} +3 -3
- package/dist/{chunk-WNLCOTKS.mjs.map → chunk-CAKQ4DZC.mjs.map} +1 -1
- package/dist/{chunk-J3SUKZI6.mjs → chunk-GLQVAJMR.mjs} +3 -3
- package/dist/{chunk-J3SUKZI6.mjs.map → chunk-GLQVAJMR.mjs.map} +1 -1
- package/dist/{chunk-KWVIU4IE.mjs → chunk-VXLBLOXM.mjs} +3 -3
- package/dist/chunk-VXLBLOXM.mjs.map +1 -0
- package/dist/{chunk-FJUWZBQU.mjs → chunk-WB34CDVO.mjs} +8 -8
- package/dist/{chunk-FJUWZBQU.mjs.map → chunk-WB34CDVO.mjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +5 -5
- package/dist/{mcp-OTUKTKAA.mjs → mcp-7LEKXDGR.mjs} +4 -4
- package/dist/{mcp-OTUKTKAA.mjs.map → mcp-7LEKXDGR.mjs.map} +1 -1
- package/dist/{scaffoldFeed-22UZWHLD.mjs → scaffoldFeed-2PTNJTIB.mjs} +3 -3
- package/dist/{scaffoldFeed-22UZWHLD.mjs.map → scaffoldFeed-2PTNJTIB.mjs.map} +1 -1
- package/dist/server/app.cjs +1 -1
- package/dist/server/app.cjs.map +1 -1
- package/dist/server/app.mjs +3 -3
- package/dist/server-BUFFB2I3.mjs +13 -0
- package/dist/{server-LV3E5FC2.mjs.map → server-BUFFB2I3.mjs.map} +1 -1
- package/dist/web/playground/.well-known/agent-capabilities.json +1 -10
- package/dist/web/playground/assets/{feedSync.worker-Bzf6IjsN.js → feedSync.worker-XrQNJWMM.js} +3 -3
- package/dist/web/playground/assets/main-BbBJifvS.css +2 -0
- package/dist/web/playground/assets/main-CWJqmVUJ.js +1204 -0
- package/dist/web/playground/assets/{vendor-DK-J-_E6.js → vendor-BtQ07Y_z.js} +66 -66
- package/dist/web/{server/assets/vendor-codemirror-BTCBSa_I.js → playground/assets/vendor-codemirror-CycrjLPB.js} +2 -2
- package/dist/web/playground/index.html +4 -4
- package/dist/web/playground/llms-full.txt +15 -15
- package/dist/web/playground/seed/core/chunks/{canvas.cd2e2017.json → canvas.f0c53604.json} +1 -1
- package/dist/web/{server/seed/core/chunks/dashboards.17370a55.json → playground/seed/core/chunks/dashboards.3e8ed107.json} +1 -1
- package/dist/web/{server/seed/core/chunks/efforts.6c05c2a7.json → playground/seed/core/chunks/efforts.05ff5169.json} +1 -1
- package/dist/web/playground/seed/core/chunks/{equipment.ff91b932.json → equipment.4c7ee2ec.json} +1 -1
- package/dist/web/playground/seed/core/indexes/notebooks/canvas.json +180 -180
- package/dist/web/playground/seed/core/indexes/notebooks/dashboards.json +16 -16
- package/dist/web/playground/seed/core/indexes/notebooks/efforts.json +326 -326
- package/dist/web/playground/seed/core/indexes/notebooks/equipment.json +50 -50
- package/dist/web/playground/seed/core/manifest.json +27 -27
- package/dist/web/playground/seed/core/markdown/canvas/ai-first/README.json +1 -1
- package/dist/web/playground/seed/core/markdown/canvas/guide/README.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/guide/clock.json +1 -1
- package/dist/web/playground/seed/core/markdown/canvas/guide/dashboards.json +1 -1
- package/dist/web/playground/seed/core/markdown/canvas/guide/metrics-summaries.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/guide/metrics.json +12 -12
- package/dist/web/playground/seed/core/markdown/canvas/guide/protocols.json +20 -20
- package/dist/web/playground/seed/core/markdown/canvas/guide/sessions.json +33 -33
- package/dist/web/playground/seed/core/markdown/canvas/guide/start.json +11 -11
- package/dist/web/playground/seed/core/markdown/canvas/guide/structure.json +25 -25
- package/dist/web/playground/seed/core/markdown/canvas/guide/wql.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/home/sample-script.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/home/welcome-1.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-full-session.json +10 -10
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/complex-swimming.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-3.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
- package/dist/web/playground/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-1.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-2.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-3.json +10 -10
- package/dist/web/playground/seed/core/markdown/canvas/syntax/document-4.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/effort-notes.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/frontmatter-summaries.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/measurements.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-4.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-sections.json +10 -10
- package/dist/web/playground/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
- package/dist/web/playground/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/named-groups.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-3.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
- package/dist/web/playground/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
- package/dist/web/playground/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
- package/dist/web/playground/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
- package/dist/web/playground/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
- package/dist/web/playground/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
- package/dist/web/playground/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
- package/dist/web/playground/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
- package/dist/web/playground/seed/core/markdown/dashboards/training-block-review.json +11 -11
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/air-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/box-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/broad-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/burpee.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/ground-kong.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/jumping-jack.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/kong-walk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/lunge.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/overhead-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-roll.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/parkour-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/pistol-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/plank.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-burpee.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/precision-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/russian-twist.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/sit-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-hold.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/squat-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/tuck-jump.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/bodyweight/wall-burpee.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/cycling/assault-bike.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-moderate.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/cycling/cycling-vigorous.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/dip.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/double-under.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-hold.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/handstand-walk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jump-rope.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/muscle-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/pull-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/push-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/rope-climb.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/recovery/rest.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/recovery/stretching.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/rowing/rowing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/rowing/ski-erg.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/backward-running.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/running-6-mph.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/running-8-mph.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/running/running-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/snatch.json +4 -4
- package/dist/web/playground/seed/core/markdown/efforts/strength/back-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/bench-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/box-step-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/carioca.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/clean-and-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/cluster.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dead-hang.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/devils-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-fly.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-row.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/dumbbell-thruster.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/elbows-to-knees.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/farmer-carry.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/frog-stand.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/front-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/good-morning.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/hanging-leg-raise.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/hollow-rock.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/knees-to-elbows.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/l-sit.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/man-maker.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/medicine-ball-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/overhead-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/parkour-vault.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/pig-flip.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/power-clean.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/power-snatch.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/push-jerk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/push-press.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/romanian-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/single-leg-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/skull-crusher.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/slam-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/sled-pull.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/sled-push.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/sumo-deadlift.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/thruster.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/triceps-extension.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/v-sit-hold.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/wall-walk.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-backstroke.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-butterfly.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dive-start.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-drafting.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-freestyle.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-kick.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-pull.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-sighting.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming-vigorous.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/swimming/swimming.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-circles.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-mill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-flow.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +1 -1
- package/dist/web/playground/seed/core/markdown/efforts/walking/walking-3-mph.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/air-bike.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/barbell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/bench.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/bike-erg.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/climbing-rope.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/clubs.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/dumbbell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/ghd.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/jump-rope.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/kettlebell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/macebell.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/medicine-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/parallettes.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/plyo-box.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/pull-up-bar.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/rower.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/sandbag.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/ski-erg.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/slam-ball.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/sled.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/sledgehammer.json +1 -1
- package/dist/web/playground/seed/core/markdown/equipment/weight-vest.json +1 -1
- package/dist/web/playground/seed/core/report.html +13 -13
- package/dist/web/playground/version.json +3 -3
- package/dist/web/server/.well-known/agent-capabilities.json +1 -10
- package/dist/web/server/assets/{feedSync.worker-Bzf6IjsN.js → feedSync.worker-XrQNJWMM.js} +3 -3
- package/dist/web/server/assets/main-BbBJifvS.css +2 -0
- package/dist/web/server/assets/main-NHcmzdAC.js +1204 -0
- package/dist/web/server/assets/{vendor-DK-J-_E6.js → vendor-BtQ07Y_z.js} +66 -66
- package/dist/web/{playground/assets/vendor-codemirror-BTCBSa_I.js → server/assets/vendor-codemirror-CycrjLPB.js} +2 -2
- package/dist/web/server/index.html +4 -4
- package/dist/web/server/llms-full.txt +15 -15
- package/dist/web/server/seed/core/chunks/{canvas.cd2e2017.json → canvas.f0c53604.json} +1 -1
- package/dist/web/{playground/seed/core/chunks/dashboards.17370a55.json → server/seed/core/chunks/dashboards.3e8ed107.json} +1 -1
- package/dist/web/{playground/seed/core/chunks/efforts.6c05c2a7.json → server/seed/core/chunks/efforts.05ff5169.json} +1 -1
- package/dist/web/server/seed/core/chunks/{equipment.ff91b932.json → equipment.4c7ee2ec.json} +1 -1
- package/dist/web/server/seed/core/indexes/notebooks/canvas.json +180 -180
- package/dist/web/server/seed/core/indexes/notebooks/dashboards.json +16 -16
- package/dist/web/server/seed/core/indexes/notebooks/efforts.json +326 -326
- package/dist/web/server/seed/core/indexes/notebooks/equipment.json +50 -50
- package/dist/web/server/seed/core/manifest.json +27 -27
- package/dist/web/server/seed/core/markdown/canvas/ai-first/README.json +1 -1
- package/dist/web/server/seed/core/markdown/canvas/guide/README.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/guide/clock.json +1 -1
- package/dist/web/server/seed/core/markdown/canvas/guide/dashboards.json +1 -1
- package/dist/web/server/seed/core/markdown/canvas/guide/metrics-summaries.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/guide/metrics.json +12 -12
- package/dist/web/server/seed/core/markdown/canvas/guide/protocols.json +20 -20
- package/dist/web/server/seed/core/markdown/canvas/guide/sessions.json +33 -33
- package/dist/web/server/seed/core/markdown/canvas/guide/start.json +11 -11
- package/dist/web/server/seed/core/markdown/canvas/guide/structure.json +25 -25
- package/dist/web/server/seed/core/markdown/canvas/guide/wql.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/home/sample-script.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/home/welcome-1.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/actions-comments.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/alternating-emom.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/basic-emom.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/calculated-metrics.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/classic-amrap.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-barbell-cycling.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-full-session.json +10 -10
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-nested-protocols.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-partner-workout.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/complex-swimming.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/core-rules.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-and-calculated-metrics.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-intervals.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-1.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-2.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-3.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-4.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/custom-metrics-5.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-bouldering.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-hangboard.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-climb-sport.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-log.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-plan.json +8 -8
- package/dist/web/server/seed/core/markdown/canvas/syntax/dialect-wod.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/distance-intervals.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-1.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-2.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-3.json +10 -10
- package/dist/web/server/seed/core/markdown/canvas/syntax/document-4.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/effort-notes.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/frontmatter-summaries.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-1.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-2.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-3.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/groups-4.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/longer-duration.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/longer-intervals.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/measurements.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-1.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-2.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-3.json +8 -8
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-4.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/metrics-5.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-sections.json +10 -10
- package/dist/web/server/seed/core/markdown/canvas/syntax/mixed-timers.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-amrap-windows.json +7 -7
- package/dist/web/server/seed/core/markdown/canvas/syntax/multiple-sets.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/named-groups.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-1.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-2.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-3.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-4.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/protocols-5.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/single-movement.json +3 -3
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-1.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-2.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-3.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/supplemental-4.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/time-cap.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/timer-modifiers.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-1.json +6 -6
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-2.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-3.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-4.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-5.json +5 -5
- package/dist/web/server/seed/core/markdown/canvas/syntax/timers-rest.json +4 -4
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-effort.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/aggregate-by-week.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/content-fran.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/filter-combos.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/pipes-limit.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/session-rpe.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/source-journal.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/tis-trend.json +2 -2
- package/dist/web/server/seed/core/markdown/canvas/wql-presets/where-join.json +2 -2
- package/dist/web/server/seed/core/markdown/dashboards/benchmark-pr-board.json +6 -6
- package/dist/web/server/seed/core/markdown/dashboards/finger-strength-v8.json +5 -5
- package/dist/web/server/seed/core/markdown/dashboards/polarized-base-marathon.json +9 -9
- package/dist/web/server/seed/core/markdown/dashboards/recovery-readiness.json +7 -7
- package/dist/web/server/seed/core/markdown/dashboards/road-to-560-total.json +9 -9
- package/dist/web/server/seed/core/markdown/dashboards/training-block-review.json +11 -11
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/air-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/box-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/broad-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-box-jump-over.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee-over-dumbbell.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/burpee.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/dumbbell-squat-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/ghd-sit-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/ground-kong.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/jumping-jack.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/kong-walk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/lunge.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/overhead-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-roll.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/parkour-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/pistol-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/plank.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-burpee.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/precision-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/quadrupedal-movement.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/russian-twist.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/sit-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-hold.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/squat-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/tuck-jump.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/bodyweight/wall-burpee.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/cycling/assault-bike.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-moderate.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/cycling/cycling-vigorous.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/assisted-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/burpee-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/chest-to-bar-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/dip.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/double-under.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-hold.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-push-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/handstand-walk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/jump-rope.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/jumping-push-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/l-sit-pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/muscle-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/pull-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/push-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/reverse-wall-dip.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/rope-climb.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/gymnastics/toes-to-bar.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-arm-bar.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-around-the-world.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-bent-over-row.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean-and-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-floor-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-front-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-goblet-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-gorilla-row.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-halo.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-overhead-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-swing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/kettlebell-windmill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/kettlebell/turkish-get-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/recovery/rest.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/recovery/stretching.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/rowing/rowing-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/rowing/rowing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/rowing/ski-erg.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/backward-running.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/running-6-mph.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/running-8-mph.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/running/running-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/snatch.json +4 -4
- package/dist/web/server/seed/core/markdown/efforts/strength/back-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/bench-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/box-step-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/carioca.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/clean-and-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/cluster.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dead-hang.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/devils-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-box-step-up.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-fly.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-row.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/dumbbell-thruster.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/elbows-to-knees.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/farmer-carry.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/frog-stand.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/front-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/good-morning.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/hanging-leg-raise.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/hollow-rock.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/knees-to-elbows.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/l-sit.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/man-maker.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/medicine-ball-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/overhead-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/parkour-vault.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/pig-flip.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/power-clean.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/power-snatch.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/push-jerk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/push-press.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/romanian-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/single-leg-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/skull-crusher.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/slam-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/sled-pull.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/sled-push.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/sumo-deadlift.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/thruster.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/triceps-extension.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/v-sit-hold.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/wall-walk.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/strength/yoga-sun-salutation.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-assisted-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-backstroke.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke-kick.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-breaststroke.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-butterfly.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-catch-up-drill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-choice-stroke.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dive-start.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-dolphin-kick.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-drafting.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-fingertip-drag.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-freestyle.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-individual-medley.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-kick.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-pull.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-resisted-sprint.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-rotation-drill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-sighting.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-single-arm-drill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-stroke-transition.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-two-kick-one-pull.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming-vigorous.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/swimming/swimming.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-arm-cast.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-circles.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-mill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-reverse-mill.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/clubbell-shield-cast.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-10-to-2-swing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-360-swing.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-barbarian-squat.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-flow.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-gravedigger.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/macebell-touchdown.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-carry.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-bear-hug-extension.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/unconventional/sandbag-over-shoulder.json +1 -1
- package/dist/web/server/seed/core/markdown/efforts/walking/walking-3-mph.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/air-bike.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/barbell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/bench.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/bike-erg.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/climbing-rope.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/clubs.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/dumbbell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/ghd.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/gymnastic-rings.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/jump-rope.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/kettlebell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/macebell.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/medicine-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/parallettes.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/plyo-box.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/pull-up-bar.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/rower.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/sandbag.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/ski-erg.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/slam-ball.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/sled.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/sledgehammer.json +1 -1
- package/dist/web/server/seed/core/markdown/equipment/weight-vest.json +1 -1
- package/dist/web/server/seed/core/report.html +13 -13
- package/dist/web/server/version.json +3 -3
- package/package.json +6 -6
- package/dist/chunk-KWVIU4IE.mjs.map +0 -1
- package/dist/server-LV3E5FC2.mjs +0 -13
- package/dist/web/playground/assets/main-B4OBzYQ9.js +0 -1204
- package/dist/web/playground/assets/main-Bm77yCnC.css +0 -2
- package/dist/web/server/assets/main-Bm77yCnC.css +0 -2
- package/dist/web/server/assets/main-G7P2C7Vn.js +0 -1204
|
@@ -1,7 +1,7 @@
|
|
|
1
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,w=new WeakMap,ee={get(e,t){if(!x.includes(t))return e[t];let n=S[t];return n||=S[t]=function(...e){C.set(this,w.get(this)[t](...e))},n}};async function*te(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let n=new Proxy(t,ee);for(w.set(n,t),s.set(n,h(t));t;)yield n,t=await(C.get(n)||t.continue()),C.delete(n)}function ne(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 ne(t,n)?te:e.get(t,n,r)},has(t,n){return ne(t,n)||e.has(t,n)}}));let T=[{name:`notes`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-created`,keyPath:[`createdAt`]},{name:`by-type`,keyPath:[`type`]},{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:`note_revisions`,keyPath:[`noteId`,`version`],indexes:[{name:`by-note`,keyPath:[`noteId`]}]},{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-session-date`,keyPath:[`sessionDate`]},{name:`by-schedule-item`,keyPath:[`scheduleItemId`]},{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:`notebook_links`,keyPath:[`id`],indexes:[{name:`by-notebook`,keyPath:[`notebookId`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-target`,keyPath:[`targetKind`,`targetId`]},{name:`by-notebook-target`,keyPath:[`notebookId`,`targetKind`,`targetId`],unique:!0},{name:`by-user`,keyPath:[`userId`]}]},{name:`property_overrides`,keyPath:[`id`],indexes:[{name:`by-notebook`,keyPath:[`notebookId`]},{name:`by-kind-slug`,keyPath:[`kind`,`slug`]},{name:`by-owner-note`,keyPath:[`ownerNoteId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`schedule_items`,keyPath:[`id`],indexes:[{name:`by-date`,keyPath:[`date`]},{name:`by-note`,keyPath:[`noteId`]},{name:`by-page`,keyPath:[`pageId`]},{name:`by-date-note`,keyPath:[`date`,`noteId`]},{name:`by-user`,keyPath:[`userId`]}]},{name:`meta`,keyPath:[`key`],indexes:[]},{name:`memberships`,keyPath:[`id`],indexes:[],system:!0}],re=[`notes`,`page`,`page_notes`,`tags`,`tag_types`,`note_tags`,`sessions`,`attachments`,`events`,`efforts`,`block_index`,`block_efforts`,`equipment`,`block_equipment`,`notebook_links`,`property_overrides`,`schedule_items`],ie=Object.fromEntries(re.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){let t=e.split(/[\s_\-\u2010-\u2015]+/).filter(Boolean),n=[];for(let e of t){let t=e.replace(/([\p{Ll}\p{Nd}])(\p{Lu})/gu,`$1\0$2`).replace(/(\p{Lu})(\p{Lu}\p{Ll})/gu,`$1\0$2`);for(let e of t.split(`\0`))e&&n.push(e)}return n}function we(e){let t=Ce(e);return t.length===0?``:t.map((e,t)=>{let n=e.toLowerCase();return t===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join(``)}function Te(e){return e.split(`.`).map(we).filter(e=>e.length>0).join(`.`)}function Ee(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(Array.isArray(e))return`array`;switch(typeof e){case`number`:return`number`;case`string`:return`string`;case`boolean`:return`boolean`;case`object`:return`object`;default:return`undefined`}}function De(e){return JSON.stringify([e.path,e.kind,e.dimension??null])}let Oe=[{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 Oe){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});let ke=`references`,Ae=[`explicit`,`split`,`whole`,`default`,`none`];function je(e){if(!e||typeof e!=`object`)return!1;let t=e;return(t.kind===`effort`||t.kind===`equipment`)&&typeof t.slug==`string`&&!!t.slug&&typeof t.label==`string`}function Me(e){return!e||typeof e!=`object`?!1:typeof e.reason==`string`}function Ne(e){let t=e?.[ke];if(!t||typeof t!=`object`)return;let n=t;if(!(typeof n.matched!=`string`||!Ae.includes(n.matched))&&typeof n.source==`string`&&!(n.refs!==void 0&&(!Array.isArray(n.refs)||!n.refs.every(je)))&&!(n.diagnostics!==void 0&&(!Array.isArray(n.diagnostics)||!n.diagnostics.every(Me))))return t}var Pe=class{line;startOffset;endOffset;length;columnStart;columnEnd;raw;constructor(e,t,n,r,i=0,a=0,o=``){this.line=e,this.startOffset=t,this.endOffset=n,this.length=r,this.columnStart=i,this.columnEnd=a,this.raw=o}},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(`, `)}]`}},Fe=class{exerciseId;line;text;raw;dialect;hasMetric(e){return this.metricContainer.hasMetric(e)}getDisplayMetrics(e){return this.metricContainer.getDisplayMetrics(e)}getMetric(e){return this.metricContainer.getMetric(e)}getAllMetricsByType(e){return this.metricContainer.getAllMetricsByType(e)}get rawMetrics(){return this.metricContainer.rawMetrics}get metricContainer(){return this.metrics instanceof D?this.metrics:D.from(this.metrics,this.id)}},Ie=class extends Fe{id=0;parent;children=[];meta=new Pe(0,0,0,0);_metrics=D.empty();metricMeta=new Map;isLeaf;get metrics(){return this._metrics}set metrics(e){this._metrics=D.from(e,this.id)}constructor(e){super(),e&&(Object.assign(this,e),e.metrics&&(this.metrics=D.from(e.metrics,this.id)),this.metricMeta||=new Map)}},Le=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 Re(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 ze=[{slug:`journal`,notebookId:`notebook/journal`,name:`Journal`,description:`Private training log tracking all created notes and sessions across journal and playground.`,icon:`J`,href:`/journal`,readOnly:!1,publishable:!1},{slug:`playground`,notebookId:`notebook/playground`,name:`Playground`,description:`Scratchpad workouts and timer experiments.`,icon:`P`,href:`/playgrounds`,readOnly:!1,publishable:!1},{slug:`defaults`,notebookId:`notebook/defaults`,name:`Defaults`,description:`Read-only base primitives: Tags, Efforts, Equipment, and shared dynamic properties.`,icon:`D`,href:`/notebook/defaults`,readOnly:!0,publishable:!1},{slug:`custom`,notebookId:`notebook/custom`,name:`Custom`,description:`User overrides and custom Tags, Efforts, Equipment, and starter workouts.`,icon:`C`,href:`/notebook/custom`,readOnly:!1,publishable:!1},{slug:`guides`,notebookId:`notebook/guides`,name:`Guides`,description:`Pre-subscribed read-only Whiteboard Language and WQL guides.`,icon:`G`,href:`/notebook/guides`,readOnly:!0,publishable:!1,feedEntryId:`core`,seedChunkId:`canvas`},{slug:`efforts`,notebookId:`notebook/efforts`,name:`Efforts`,description:`The effort library — every effort the parser and analytics resolve, across the canonical disciplines.`,icon:`🏋️`,href:`/efforts`,feedEntryId:`core`,seedChunkId:`efforts`},{slug:`equipment`,notebookId:`notebook/equipment`,name:`Equipment`,description:`The equipment library — gear definitions the language resolves.`,icon:`🔧`,href:`/equipment`,feedEntryId:`core`,seedChunkId:`equipment`},{slug:`dashboards`,notebookId:`notebook/dashboards`,name:`Dashboards`,description:`Prebuilt WQL dashboards — query compositions ready to open.`,icon:`📊`,href:`/dashboards`,feedEntryId:`core`,seedChunkId:`dashboards`}],Be=[`playground-run-tip`,`attention`,`code-example`,`syntax-group`],Ve={table:!0,list:!0,value:!0,timeseries:!0,bar:!0,donut:!0,toplist:!0,"stacked-bar":!0,"goal-rings":!0,"zone-distribution":!0},He={time:`time`,wod:`time`,whiteboard:`time`,log:`log`};function Ue(e){let t=e.match(/^`{3,}(time|wod|whiteboard|log)(?::([\w-]+))?\s*$/i);return t?{dialect:He[t[1].toLowerCase()],...t[2]?{sport:t[2]}:{}}:null}function We(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 Ge(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 Ke(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
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]==="`"?Ue(`\`\`\`${h}`):null,_=a[0]==="`"?h.match(/^widget:([\w-]+)$/):null,v=t.registeredWidgets??Be,y=_&&(`has`in v?v.has(_[1]):v.includes(_[1])),b=a[0]==="`"&&!y?h.match(/^widget:([a-z-]+)(?:-(?:full|\d+))?(?:\s+.*)?$/i):null,x=!!(b&&Ve[b[1].toLowerCase()]),S=a[0]==="`"?h.match(/^query(?:[:\s](.*))?$/i)??(x?h.match(/^widget:?(.*)$/i):null):null,C=p&&g?g.dialect:p&&y?`widget`:p&&S?`query`:`code`,w=u(C,l,m);w.contentFrom=r[l]+n[l].length+i[l].length,w.contentTo=p?r[c]:w.to,w.displayContent=e.slice(w.contentFrom,w.contentTo),g&&p&&(w.sport=g.sport,w.contentId=Re(w.displayContent),w.scriptBlock={id:w.id,contentId:w.contentId,dialect:g.dialect,sport:g.sport,startLine:l,endLine:m,content:w.displayContent,state:`idle`,version:1,createdAt:s}),C===`widget`&&_&&(w.widgetName=_[1]),C===`query`&&S&&(w.querySuffix=(S[1]??``).trim()),o.push(w),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=We(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=Ge(m.displayContent.trim()),a&&(c=!1),o.push(m),l=p+1}return o}function qe(e){return e.type===`time`||e.type===`log`?`wod`:e.type===`query`||e.type===`widget`||e.type===`embed`?e.type:null}function Je(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 Ke(e,t)){let e=qe(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 Ye(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=Je(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 Xe(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}let Ze=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;function Qe(e){return e.replace(/^(['"])(.*)\1$/,(e,t,n)=>t===`"`?n.replace(/\\(["\\nrt])/g,(e,t)=>t===`n`?`
|
|
4
|
-
`:t===`r`?`\r`:t===`t`?` `:t):n)}function $e(e){let t={};for(let n=0;n<e.length;n++){let r=e[n].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);if(!r)continue;let i=r[1],a=r[2].trim();if(a===``){let r=[];for(;n+1<e.length;){let t=e[n+1].match(/^\s+-\s+(.+)$/);if(!t)break;r.push(Qe(t[1].trim())),n++}if(r.length>0)t[i]=r;else if(i===`metrics`||i===`summaries`||i===`widgets`||i===`baseAttributes`)for(;n+1<e.length;){let r=e[n+1];if(/^\s*(?:#.*)?$/.test(r)){n++;continue}let a=r.match(/^\s{2,}([A-Za-z][\w.-]*)\s*:(.*)$/);if(!a)break;n++;let o=a[1],s=i===`baseAttributes`?o===`met`||o===`disciplineFactor`?`metrics.${o}`:o:`${i}.${o}`,c=a[2].trim();if(c===``){let r=[];for(;n+1<e.length;){let t=e[n+1].match(/^\s{4,}-\s+(.+)$/);if(!t)break;r.push(Qe(t[1].trim())),n++}t[s]=r.length>0?r:``}else{let e=/^(['"])(.*)\1$/.test(c),n=Qe(c),r=Number(n);t[s]=!e&&n!==``&&!isNaN(r)?r:n}}else t[i]=``}else{let e=/^(['"])(.*)\1$/.test(a),n=Qe(a),r=Number(n);t[i]=!e&&n!==``&&!isNaN(r)?r:n}}return t}function et(e){let t=e.match(Ze);return t?{meta:$e(t[1].split(/\r?\n/)),body:e.slice(t[0].length)}:{meta:{},body:e}}function tt(e,t){let n=e[t];return typeof n==`string`||typeof n==`number`?n:void 0}var nt=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n,this.name=`StorageError`}};function rt(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)=>rt(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)&&rt(Reflect.get(e,n),Reflect.get(t,n)))}function it(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new nt(400,`storage row must be an object`);return e}function at(e,t){if(e!==`notes`&&e!==`block_revisions`&&e!==`note_revisions`&&e!==`sessions`&&e!==`block_index`&&e!==`schedule_items`)return;let n=it(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`))||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.provenance!==void 0&&(typeof n.provenance!=`object`||n.provenance===null||Array.isArray(n.provenance)||typeof n.provenance.sourceNoteId!=`string`)||[`type`,`sourceId`,`sourcePath`,`notebookId`,`seedChunkId`,`feedSourceId`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new nt(400,`invalid whole Note`,`invalid_note_blocks`);try{Ye(n.rawContent,it(n.blocks),n.sourceRevision)}catch(e){throw new nt(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 nt(400,`invalid block revision`,`invalid_note_blocks`);try{Ye(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 nt(400,e instanceof Error?e.message:`invalid revision source`,`invalid_note_blocks`)}}else if(e===`note_revisions`){if(!i(`noteId`)||!r(`version`)||typeof n.title!=`string`||typeof n.rawContent!=`string`||typeof n.savedAt!=`number`||!Number.isFinite(n.savedAt)||n.tags!==void 0&&(!Array.isArray(n.tags)||!n.tags.every(e=>typeof e==`string`))||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.type!==void 0&&typeof n.type!=`string`)throw new nt(400,`invalid note revision`,`invalid_note_blocks`);try{Ye(n.rawContent,it(n.blocks),n.version)}catch(e){throw new nt(400,e instanceof Error?e.message:`invalid note revision blocks`,`invalid_note_blocks`)}}else if(e===`schedule_items`){if(!i(`id`)||!i(`date`)||!i(`noteId`)||typeof n.position!=`number`||!Number.isFinite(n.position)||![`planned`,`completed`,`skipped`,`moved`].includes(String(n.status))||typeof n.createdAt!=`number`||!Number.isFinite(n.createdAt)||typeof n.updatedAt!=`number`||!Number.isFinite(n.updatedAt)||[`pageId`,`sourceNotebookId`,`fallbackTitle`,`blockId`,`slot`,`notes`,`movedFromDate`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new nt(400,`invalid schedule item`,`invalid_schedule_item`)}else if(e===`sessions`){if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||n.noteSourceRevision!==void 0&&!r(`noteSourceRevision`)||n.sessionDate!==void 0&&typeof n.sessionDate!=`string`||n.scheduleItemId!==void 0&&typeof n.scheduleItemId!=`string`||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||[`segmentId`,`segmentVersion`,`version`,`rawContent`,`script`,`serializedScript`,`source`,`data`,`logs`].some(e=>e in n))throw new nt(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 nt(400,`invalid actionable block projection`,`invalid_note_blocks`)}function ot(e,t){if(e===void 0||rt(e,t))return;let n=it(e),r=it(t);if(typeof n.sourceRevision!=`number`||typeof r.sourceRevision!=`number`||r.sourceRevision<n.sourceRevision||(!rt(n.blocks,r.blocks)||n.rawContent!==r.rawContent)&&r.sourceRevision<=n.sourceRevision)throw new nt(409,`stale Note source revision`,`transaction_conflict`)}function st(e,t){if(e===void 0)return;let n=it(e),r=it(t);if(n.noteId!==r.noteId||n.blockId!==r.blockId||n.blockVersion!==r.blockVersion)throw new nt(409,`Session pin is immutable`,`invalid_session_pin`)}async function ct(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 nt(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 nt(409,`Session pin must reference a saved workout revision`,`invalid_session_pin`)}}function lt(e){if(!(typeof e!=`string`||!e.startsWith(`user-deleted-seed:`)))return e.slice(18)||void 0}function ut(e){return typeof e==`string`&&e.startsWith(`seed:`)}function dt(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 ft(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`property_overrides`:return!(`seedOrigin`in t&&t.seedOrigin===`seed`);case`meta`:return!ut(`key`in t?t.key:void 0);default:return!0}}Object.fromEntries(T.map(e=>[e.name,!0]));let pt=[`reps`,`distance`,`resistance`,`elapsed`,`power`,`pace`],mt=[`totalVolume`,`totalDistance`,`tis`,`sessionLoad`],ht=[`sum`,`avg`,`min`,`max`,`count`,`last`,`delta`],gt=[`domain`,`format`,`equipment`,`quality`,`intent`],_t=[...gt,`effort`,`discipline`,`intensity`,`grade`,`note`,`notebook`,`page`,`origin`,`grain`,`metric`,`block`,`result`,`tags`],vt=[`effort`,`discipline`,`intensity`,`origin`,`text`],yt=[`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`],bt=[`note`,`block`,`effort`,`session`,`segment`,`event`,`notebook`,`page`,`tag`,`equipment`,`feed`],xt=[`note`,`notes`,`block`,`effort`,`session`,`segment`,`event`,`journal`,`notebook`,`notebooks`,`playground`,`page`,`tag`,`equipment`,`feed`,`feeds`,`dashboard`],St=ht,Ct=[`summary`,`timeseries`,`bar`,`stacked-bar`,`table`,`list`,`donut`,`toplist`,`value`,`goal-rings`,`zone-distribution`],wt=[`@session`,`@today`,`@note`,`@block`,`@notebook`];[..._t];let Tt=[`kg`,`lb`],Et={time:!0,groupby:!0,rollup:!0,unit:!0,where:!0,agg:!0},Dt=_t.filter(e=>e!==`metric`),Ot=_t.filter(e=>e!==`tags`);[...Dt.map(e=>e===`tags`?`tag`:e)];let kt={notebook:new Set([`text`,`notebook`,`tag`,`effort`,...gt,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`]),note:new Set([`text`,`notebook`,`tag`,`effort`,...gt,`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([...vt,`groupby`]),session:new Set([`result`,`block`,`note`,`plane`,...Dt.map(e=>e===`tags`?`tag`:e),`time`,`groupby`]),segment:new Set([...Ot,`tag`,`time`,`groupby`,`unit`]),event:new Set([...Ot,`tag`,`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`]),feed:new Set([`feed`,`tag`,`text`,`subscribed`,`groupby`])},At=[`metric`,..._t.filter(e=>e!==`metric`)],jt=Object.fromEntries(Object.entries(kt).map(([e,t])=>[e,[...t].filter(e=>!Et[e]).map(e=>e===`tag`?`tags`:e)]));[..._t],[...pt,...mt,...yt];function Mt(e,t){return t===`aggregate`?At:jt[e]??[]}let Nt=1024,Pt=0;var Ft=class{constructor(e,t){this.from=e,this.to=t}},O=class{constructor(e={}){this.id=Pt++,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=Rt.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 It=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 Lt=Object.create(null);var Rt=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):Lt,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}}}};Rt.none=new Rt(``,Object.create(null),0,8);var zt=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 Rt(e.name,r,e.id,e.flags):e)}return new e(n)}};let Bt=new WeakMap,Vt=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=It.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 tn(this.topNode,e)}cursorAt(e,t=0,n=0){let r=new tn(Bt.get(this)||this.topNode);return r.moveTo(e,t),Bt.set(this,r._tree),r}get topNode(){return new qt(this,0,0,null)}resolve(e,t=0){let n=Gt(Bt.get(this)||this.topNode,e,t,!1);return Bt.set(this,n),n}resolveInner(e,t=0){let n=Gt(Vt.get(this)||this.topNode,e,t,!0);return Vt.set(this,n),n}resolveStack(e,t=0){return en(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:sn(Rt.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(Rt.none,t,n,r)))}static build(e){return rn(e)}};A.empty=new A(Rt.none,[],[],0);var Ht=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)}},Ut=class e{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return Rt.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 Gt(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 qt&&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 qt&&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 Kt=class{cursor(e=0){return new tn(this,e)}getChild(e,t=null,n=null){let r=Jt(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return Jt(this,e,t,n)}resolve(e,t=0){return Gt(this,e,t,!1)}resolveInner(e,t=0){return Gt(this,e,t,!0)}matchContext(e){return Yt(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}},qt=class e extends Kt{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=It.get(l))&&!d.overlay&&d.bracketed&&r>=u&&r<=u+l.length)&&!Wt(i,r,u,u+l.length))){if(l instanceof Ut){if(a&k.ExcludeBuffers)continue;let e=l.findChild(0,l.buffer.length,n,r-u,i);if(e>-1)return new Zt(new Xt(o,l,t,u),null,e)}else if(a&k.IncludeAnonymous||!l.type.isAnonymous||nn(l)){let s;if(!(a&k.IgnoreMounts)&&(s=It.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=It.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 Jt(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 Yt(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 Xt=class{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}},Zt=class e extends Kt{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 Qt(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 qt&&n.index<0?null:n.parent,i=e.slice();return r?i[t]=r:i.splice(t,1),new $t(i,n)}var $t=class{constructor(e,t){this.heads=e,this.node=t}get next(){return Qt(this.heads)}};function en(e,t,n){let r=e.resolveInner(t,n),i=null;for(let e=r instanceof qt?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=It.get(e.tree);if(a&&a.overlay&&a.overlay[0].from<=t&&a.overlay[a.overlay.length-1].to>=t){let o=new qt(a.tree,a.overlay[0].from+e.from,-1,e);(i||=[r]).push(Gt(o,t,n,!1))}}return i?Qt(i):r}var tn=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 qt)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 qt?(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 Ut||!e.type.isAnonymous||nn(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 Zt(this.buffer,t,this.stack[e]);return this.bufferNode=new Zt(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 Yt(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 Yt(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 nn(e){return e.children.some(e=>e instanceof Ut||!e.type.isAnonymous||nn(e))}function rn(e){let{buffer:t,nodeSet:n,maxBufferLength:r=Nt,reused:i=[],minRepeatType:a=n.types.length}=e,o=Array.isArray(t)?new Ht(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:w}=o,ee=l,te=c;if(w<0){if(o.next(),w==-1){let t=i[x];_.push(t),v.push(S-e);return}if(w==-3){c=x;return}if(w==-4){l=x;return}throw RangeError(`Unrecognized record size: ${w}`)}let ne=s[x],T,re,ie=S-e;if(C-S<=r&&(re=h(o.pos-t,y))){let t=new Uint16Array(re.size-re.skip),r=o.pos-re.size,i=t.length;for(;o.pos>r;)i=g(re.start,t,i);T=new Ut(t,C-re.start,n),ie=re.start-e}else{let e=o.pos-w;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,ee,te),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,ee,te),t.reverse(),n.reverse(),i>-1&&s>0){let e=f(ne,te);T=sn(ne,t,n,0,t.length,0,C-S,e,e)}else T=m(ne,t,n,C-S,ee-C,te)}_.push(T),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 Ut(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 an=new WeakMap;function on(e,t){if(!e.isAnonymous||t instanceof Ut||t.type!=e)return 1;let n=an.get(t);if(n==null){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof A)){n=1;break}n+=on(e,r)}an.set(t,n)}return n}function sn(e,t,n,r,i,a,o,s,c){let l=0;for(let n=r;n<i;n++)l+=on(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=on(e,t[s]);for(s++;s<i;s++){let n=on(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(sn(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 cn=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}},ln=class{startParse(e,t,n){return typeof e==`string`&&(e=new un(e)),n=n?n.length?n.map(e=>new Ft(e.from,e.to)):[new Ft(0,0)]:[new Ft(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}}},un=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 dn=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 fn(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 pn(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 fn(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()}},fn=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},pn=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}},mn=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 hn(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 gn=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};let _n=new gn;var vn=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=_n,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=_n,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}},yn=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:n}=t.p;xn(this.data,e,t,this.id,n.data,n.tokenPrecTable)}};yn.prototype.contextual=yn.prototype.fallback=yn.prototype.extend=!1;var bn=class{constructor(e,t,n){this.precTable=t,this.elseToken=n,this.data=typeof e==`string`?hn(e):e}token(e,t){let n=e.pos,r=0;for(;;){let n=e.next<0,i=e.resolveOffset(1,1);if(xn(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))}};bn.prototype.contextual=yn.prototype.fallback=yn.prototype.extend=!1;function xn(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||Cn(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 Sn(e,t,n){for(let r=t,i;(i=e[r])!=65535;r++)if(i==n)return r-t;return-1}function Cn(e,t,n,r){let i=Sn(n,r,t);return i<0||Sn(n,r,e)<i}let wn=typeof process<`u`&&/\bparse\b/.test({}.LOG),Tn=null;function En(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 Dn=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?En(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?En(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}}},On=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(e=>new gn)}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 gn,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 gn,{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=Nn(o,s+2);else{r==0&&o[s+1]==2&&(r=this.putAction(Nn(o,s+2),t,n,r));break}}o[s]==t&&(r=this.putAction(Nn(o,s+1),t,n,r))}return r}},kn=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 vn(t,r),this.tokens=new On(e,this.stream),this.topTerm=e.top[1];let{from:i}=r[0];this.stacks=[dn.start(this,e.top[0],i)],this.fragments=n.length&&this.stream.end-i>e.bufferLength*4?new Dn(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 wn&&console.log(`Finish with `+this.stackID(e)),this.stackToTree(e);if(this.parser.strict)throw wn&&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 wn&&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=wn?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),wn&&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),wn&&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),wn&&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 An(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=wn?this.stackID(o)+` -> `:``;if(o.deadEnd&&(i||(i=!0,o.restart(),wn&&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()&&(wn&&console.log(d+this.stackID(u)+` (via force-reduce)`),!this.advanceFully(u,n));e++)wn&&(d=this.stackID(u)+` -> `);for(let e of o.recoverByInsert(s))wn&&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),wn&&console.log(l+this.stackID(o)+` (via recover-delete ${this.parser.getName(s)})`),An(o,n)):(!r||r.score<u.score)&&(r=u)}return r}stackToTree(e){return e.close(),A.build({buffer:mn.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=(Tn||=new WeakMap).get(e);return t||Tn.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function An(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 jn=class{constructor(e,t,n){this.source=e,this.flags=t,this.disabled=n}allows(e){return!this.disabled||this.disabled[e]==0}},Mn=class e extends ln{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 zt(t.map((t,i)=>Rt.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=Nt;let a=hn(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(Fn),this.states=hn(e.states,Uint32Array),this.data=hn(e.stateData),this.goto=hn(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(e=>typeof e==`number`?new yn(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 kn(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=Nn(n,i+2)];else if(n[i+1]==2)return Nn(n,i+2);else break}if(a==t||a==0)return Nn(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=Nn(this.data,n+2);else break}r=t(Nn(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=Nn(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]=Fn(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 jn(e,n,r)}static deserialize(t){return new e(t)}};function Nn(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 Fn(e){if(e.external){let t=+!!e.extend;return(n,r)=>e.external(n,r)<<1|t}return e.get}let In=Mn.deserialize({version:14,states:"+|OVQPOOOOQO'#Cb'#CbObQPO'#C`OgQPO'#C`OlQPO'#CnOqQQO'#C_OOQO'#C_'#C_O!SQQO'#CpQOQPOOOOQO,58z,58zO!bQPO,58zOOQO,59Y,59YO!jQPO'#CfOOQO,58y,58yOVQPO,58xO!xQPO'#CqO!}QPO'#CtOOQO,59[,59[O#SQPO,59[O#[QPO'#CdO#aQQO'#CcOOQO'#Cc'#CcOOQO1G.f1G.fOOQO'#Ci'#CiO#uQPO'#CgO#zQPO'#CgOOQO'#Cg'#CgOOQO,59Q,59QO$PQPO,59QO$XQPO'#C_O$dQPO1G.dO$lQPO,59]O$tQQO,59`OOQO1G.v1G.vOOQO,59O,59OO$yQPO'#CwO%OQQO,58}O%dQPO,59RO%rQPO,59RO%wQPO'#CzO&SQPO1G.lOOQO1G.l1G.lOVQPO'#C{O&[QPO7+$OOOQO'#Cs'#CsOOQO1G.w1G.wO&dQPO1G.wO&lQPO1G.zOOQO,59c,59cOOQO-E6u-E6uOOQO'#Ck'#CkO&qQPO'#CkO'VQPO'#CkO'eQPO'#CjOOQO1G.m1G.mO%dQPO1G.mOOQO,59f,59fOOQO-E6x-E6xOOQO7+$W7+$WO'pQPO'#CcOOQO,59g,59gOOQO-E6y-E6yO(OQPO'#C|O(TQPO7+$cOOQO7+$c7+$cO(]QPO7+$fO(bQPO'#CxO(gQPO,59VOOQO,59V,59VO%dQPO'#CyO({QPO,59UOOQO7+$X7+$XO)WQPO,58}OOQO,59h,59hOOQO-E6z-E6zOOQO<<G}<<G}OOQO<<HQ<<HQOOQO,59d,59dOOQO-E6v-E6vOOQO1G.q1G.qOOQO,59e,59eOOQO-E6w-E6wO)fQPO,58zO)nQPO'#C`",stateData:")s~OsOS~OTPOcSOtQO~OTXO~OtYO~OTZO~Ov[OfRXiRXqRXwRX~Of_Oi`Ow^OqdX~OTdOXcO~OTgOXcO[iOykO~OvoO~OzpO~Oi`Oqda~OTrO~OusOfVXiVXqVXvVXwVX~OtuO~OTgO~OxwOyyO~Ov[OqRXwRX~OwzOqQi~OT|Oy}O~Oj!PO~OT!QO~OusOfVaiVaqVavVawVa~OT!TOXcO`!SOa!UO~Ot!XO~OTgOXcO[iO~OxwOy![O~OwzOqQq~Ox!`Oy!bO~OT!cO~O`!fOt!dOu!dOw_Xx_Xy_X~O`!fOw_Xx_Xy_X~Ow!gOx^Xy^X~OusOqVXvVXwVX~OT|O~Ox!`Oy!mO~O{!nO~OT!oO~O`!qOt!dOu!dOw_ax_ay_a~Ow!gOx^ay^a~OusOqVavVawVa~OT!]OXcO~Ot!tO~O",goto:"$mqPPru!OP!V!^!bP!o!sP!y#Q#WPP#_Pr#dP#g#mPP#s#}$T$Z$a$gRWOQVOQn^R!^zQTOTm^zQROT!u^zTfY!tSeY!tSj[wV!Su!X!gT]TmQl[R!YwSh[wRviQ!WuR!i!XS!Vu!XR!r!gVUO^zRbVQ!OoR!k!`QaVRqbQtdS!Rt!jR!j!]Q!e!TR!p!eQ!h!VR!s!hQxlR!ZxQ{nR!_{Q!a!OR!l!a",nodeNames:`⚠ Query Pipeline Stage Head Word Aggregator Metric ParamRef Dollar Filters Filter Negate TagKey TagValue Value Star Quoted DatasetReference At Single GroupBy By Dimension Rollup RollupDot Int`,maxTerm:43,skippedNodes:[0],repeatNodeCount:6,tokenData:"'q~RhXY!mYZ!m]^!mpq!mqr#Ors#Ttu#rxy#wyz#|z{$R|}$W}!O$]!O!P$q!Q![%n![!]&U!b!c&Z!c!}$]#R#S$]#T#U$]#U#V&`#V#o$]#o#p'b#p#q'g#q#r'l~!rSs~XY!mYZ!m]^!mpq!m~#TO[~~#WTOr#Trs#gs;'S#T;'S;=`#l<%lO#T~#lOa~~#oP;=`<%l#T~#wOX~~#|Oz~~$RO{~~$WO`~~$]Ox~P$bTTP}!O$]!Q![$]!c!}$]#R#S$]#T#o$]~$vPu~#f#g$y~$|P#c#d%P~%SP#`#a%V~%YP#`#a%]~%`P#i#j%c~%fP#d#e%i~%nOi~R%uTjQTP}!O$]!Q![%n!c!}$]#R#S$]#T#o$]~&ZOt~~&`Oc~R&eVTP}!O$]!Q![$]!c!}$]#R#S$]#T#m$]#m#n&z#n#o$]R'RTfQTP}!O$]!Q![$]!c!}$]#R#S$]#T#o$]~'gOv~~'lOw~~'qOy~",tokenizers:[0,1],topRules:{Query:[0,1]},tokenPrec:0}),Ln=[],Rn=[];(()=>{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?Rn:Ln).push(n+=e[t])})();function zn(e){if(e<768)return!1;for(let t=0,n=Ln.length;;){let r=t+n>>1;if(e<Ln[r])n=r;else if(e>=Rn[r])t=r+1;else return!0;if(t==n)return!1}}function Bn(e){return e>=127462&&e<=127487}let Vn=8205;function Hn(e,t,n=!0,r=!0){return(n?Un:Wn)(e,t,r)}function Un(e,t,n){if(t==e.length)return t;t&&Kn(e.charCodeAt(t))&&qn(e.charCodeAt(t-1))&&t--;let r=Gn(e,t);for(t+=Jn(r);t<e.length;){let i=Gn(e,t);if(r==Vn||i==Vn||n&&zn(i))t+=Jn(i),r=i;else if(Bn(i)){let n=0,r=t-2;for(;r>=0&&Bn(Gn(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function Wn(e,t,n){for(;t>0;){let r=Un(e,t-2,n);if(r<t)return r;t--}return 0}function Gn(e,t){let n=e.charCodeAt(t);if(!qn(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return Kn(r)?(n-55296<<10)+(r-56320)+65536:n}function Kn(e){return e>=56320&&e<57344}function qn(e){return e>=55296&&e<56320}function Jn(e){return e<65536?1:2}var j=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]=ir(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),Xn.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]=ir(this,e,t);let n=[];return this.decompose(e,t,n,0),Xn.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 er(this),i=new er(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 er(this,e)}iterRange(e,t=this.length){return new tr(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 nr(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 Yn(t):Xn.from(Yn.split(t,[]))}},Yn=class e extends j{constructor(e,t=Zn(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 rr(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e($n(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=Qn(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]=ir(this,t,n);let i=Qn(this.text,Qn(r.text,$n(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):Xn.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
|
|
4
|
+
`:t===`r`?`\r`:t===`t`?` `:t):n)}function $e(e){let t={};for(let n=0;n<e.length;n++){let r=e[n].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);if(!r)continue;let i=r[1],a=r[2].trim();if(a===``){let r=[];for(;n+1<e.length;){let t=e[n+1].match(/^\s+-\s+(.+)$/);if(!t)break;r.push(Qe(t[1].trim())),n++}if(r.length>0)t[i]=r;else if(i===`metrics`||i===`summaries`||i===`widgets`||i===`baseAttributes`)for(;n+1<e.length;){let r=e[n+1];if(/^\s*(?:#.*)?$/.test(r)){n++;continue}let a=r.match(/^\s{2,}([A-Za-z][\w.-]*)\s*:(.*)$/);if(!a)break;n++;let o=a[1],s=i===`baseAttributes`?o===`met`||o===`disciplineFactor`?`metrics.${o}`:o:`${i}.${o}`,c=a[2].trim();if(c===``){let r=[];for(;n+1<e.length;){let t=e[n+1].match(/^\s{4,}-\s+(.+)$/);if(!t)break;r.push(Qe(t[1].trim())),n++}t[s]=r.length>0?r:``}else{let e=/^(['"])(.*)\1$/.test(c),n=Qe(c),r=Number(n);t[s]=!e&&n!==``&&!isNaN(r)?r:n}}else t[i]=``}else{let e=/^(['"])(.*)\1$/.test(a),n=Qe(a),r=Number(n);t[i]=!e&&n!==``&&!isNaN(r)?r:n}}return t}function et(e){let t=e.match(Ze);return t?{meta:$e(t[1].split(/\r?\n/)),body:e.slice(t[0].length)}:{meta:{},body:e}}function tt(e,t){let n=e[t];return typeof n==`string`||typeof n==`number`?n:void 0}var nt=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n,this.name=`StorageError`}};function rt(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)=>rt(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)&&rt(Reflect.get(e,n),Reflect.get(t,n)))}function it(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new nt(400,`storage row must be an object`);return e}function at(e,t){if(e!==`notes`&&e!==`block_revisions`&&e!==`note_revisions`&&e!==`sessions`&&e!==`block_index`&&e!==`schedule_items`)return;let n=it(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`))||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.provenance!==void 0&&(typeof n.provenance!=`object`||n.provenance===null||Array.isArray(n.provenance)||typeof n.provenance.sourceNoteId!=`string`)||[`type`,`sourceId`,`sourcePath`,`notebookId`,`seedChunkId`,`feedSourceId`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new nt(400,`invalid whole Note`,`invalid_note_blocks`);try{Ye(n.rawContent,it(n.blocks),n.sourceRevision)}catch(e){throw new nt(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 nt(400,`invalid block revision`,`invalid_note_blocks`);try{Ye(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 nt(400,e instanceof Error?e.message:`invalid revision source`,`invalid_note_blocks`)}}else if(e===`note_revisions`){if(!i(`noteId`)||!r(`version`)||typeof n.title!=`string`||typeof n.rawContent!=`string`||typeof n.savedAt!=`number`||!Number.isFinite(n.savedAt)||n.tags!==void 0&&(!Array.isArray(n.tags)||!n.tags.every(e=>typeof e==`string`))||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||n.type!==void 0&&typeof n.type!=`string`)throw new nt(400,`invalid note revision`,`invalid_note_blocks`);try{Ye(n.rawContent,it(n.blocks),n.version)}catch(e){throw new nt(400,e instanceof Error?e.message:`invalid note revision blocks`,`invalid_note_blocks`)}}else if(e===`schedule_items`){if(!i(`id`)||!i(`date`)||!i(`noteId`)||typeof n.position!=`number`||!Number.isFinite(n.position)||![`planned`,`completed`,`skipped`,`moved`].includes(String(n.status))||typeof n.createdAt!=`number`||!Number.isFinite(n.createdAt)||typeof n.updatedAt!=`number`||!Number.isFinite(n.updatedAt)||[`pageId`,`sourceNotebookId`,`fallbackTitle`,`blockId`,`slot`,`notes`,`movedFromDate`].some(e=>n[e]!==void 0&&typeof n[e]!=`string`))throw new nt(400,`invalid schedule item`,`invalid_schedule_item`)}else if(e===`sessions`){if(!i(`noteId`)||!i(`blockId`)||!r(`blockVersion`)||n.noteSourceRevision!==void 0&&!r(`noteSourceRevision`)||n.sessionDate!==void 0&&typeof n.sessionDate!=`string`||n.scheduleItemId!==void 0&&typeof n.scheduleItemId!=`string`||n.public!==void 0&&typeof n.public!=`boolean`||n.notebookIds!==void 0&&(!Array.isArray(n.notebookIds)||!n.notebookIds.every(e=>typeof e==`string`))||[`segmentId`,`segmentVersion`,`version`,`rawContent`,`script`,`serializedScript`,`source`,`data`,`logs`].some(e=>e in n))throw new nt(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 nt(400,`invalid actionable block projection`,`invalid_note_blocks`)}function ot(e,t){if(e===void 0||rt(e,t))return;let n=it(e),r=it(t);if(typeof n.sourceRevision!=`number`||typeof r.sourceRevision!=`number`||r.sourceRevision<n.sourceRevision||(!rt(n.blocks,r.blocks)||n.rawContent!==r.rawContent)&&r.sourceRevision<=n.sourceRevision)throw new nt(409,`stale Note source revision`,`transaction_conflict`)}function st(e,t){if(e===void 0)return;let n=it(e),r=it(t);if(n.noteId!==r.noteId||n.blockId!==r.blockId||n.blockVersion!==r.blockVersion)throw new nt(409,`Session pin is immutable`,`invalid_session_pin`)}async function ct(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 nt(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 nt(409,`Session pin must reference a saved workout revision`,`invalid_session_pin`)}}function lt(e){if(!(typeof e!=`string`||!e.startsWith(`user-deleted-seed:`)))return e.slice(18)||void 0}function ut(e){return typeof e==`string`&&e.startsWith(`seed:`)}function dt(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 ft(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`property_overrides`:return!(`seedOrigin`in t&&t.seedOrigin===`seed`);case`meta`:return!ut(`key`in t?t.key:void 0);default:return!0}}Object.fromEntries(T.map(e=>[e.name,!0]));let pt=[`reps`,`distance`,`resistance`,`elapsed`,`power`,`pace`],mt=[`totalVolume`,`totalDistance`,`tis`,`sessionLoad`],ht=[`sum`,`avg`,`min`,`max`,`count`,`last`,`delta`],gt=[`domain`,`format`,`equipment`,`quality`,`intent`],_t=[...gt,`effort`,`discipline`,`intensity`,`grade`,`note`,`notebook`,`page`,`origin`,`grain`,`metric`,`block`,`result`,`tags`],vt=[`effort`,`discipline`,`intensity`,`origin`,`text`,`has`],yt=[`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`],bt=[`note`,`block`,`effort`,`session`,`segment`,`event`,`notebook`,`page`,`tag`,`equipment`,`feed`],xt=[`note`,`notes`,`block`,`effort`,`session`,`segment`,`event`,`journal`,`notebook`,`notebooks`,`playground`,`page`,`tag`,`equipment`,`feed`,`feeds`,`dashboard`],St=ht,Ct=[`summary`,`timeseries`,`bar`,`stacked-bar`,`table`,`list`,`donut`,`toplist`,`value`,`goal-rings`,`zone-distribution`],wt=[`@session`,`@today`,`@note`,`@block`,`@notebook`];[..._t];let Tt=[`kg`,`lb`],Et={time:!0,groupby:!0,rollup:!0,unit:!0,where:!0,agg:!0},Dt=_t.filter(e=>e!==`metric`),Ot=_t.filter(e=>e!==`tags`);[...Dt.map(e=>e===`tags`?`tag`:e)];let kt={notebook:new Set([`text`,`notebook`,`tag`,`effort`,...gt,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`,`owner`,`published`]),note:new Set([`text`,`notebook`,`tag`,`effort`,...gt,`type`,`page`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`,`owner`,`has`]),block:new Set([`text`,`notebook`,`tag`,`effort`,`type`,`source`,`note`,`time`,`groupby`,`where`,`feed`,`subscribed`]),effort:new Set([...vt,`groupby`]),session:new Set([`result`,`block`,`note`,`plane`,...Dt.map(e=>e===`tags`?`tag`:e),`time`,`groupby`]),segment:new Set([...Ot,`tag`,`time`,`groupby`,`unit`]),event:new Set([...Ot,`tag`,`time`,`groupby`,`unit`]),page:new Set([`page`,`notebook`,`text`,`note`,`owner`,`type`,`time`,`groupby`]),tag:new Set([`tag`,`type`,`text`,`contributes`,`time`]),equipment:new Set([`equipment`,`tags`,`text`,`notebook`,`has`,`time`,`groupby`]),feed:new Set([`feed`,`tag`,`text`,`subscribed`,`groupby`])},At=[`metric`,..._t.filter(e=>e!==`metric`)],jt=Object.fromEntries(Object.entries(kt).map(([e,t])=>[e,[...t].filter(e=>!Et[e]).map(e=>e===`tag`?`tags`:e)]));[..._t],[...pt,...mt,...yt];function Mt(e,t){return t===`aggregate`?At:jt[e]??[]}let Nt=1024,Pt=0;var Ft=class{constructor(e,t){this.from=e,this.to=t}},O=class{constructor(e={}){this.id=Pt++,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=Rt.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 It=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 Lt=Object.create(null);var Rt=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):Lt,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}}}};Rt.none=new Rt(``,Object.create(null),0,8);var zt=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 Rt(e.name,r,e.id,e.flags):e)}return new e(n)}};let Bt=new WeakMap,Vt=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=It.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 tn(this.topNode,e)}cursorAt(e,t=0,n=0){let r=new tn(Bt.get(this)||this.topNode);return r.moveTo(e,t),Bt.set(this,r._tree),r}get topNode(){return new qt(this,0,0,null)}resolve(e,t=0){let n=Gt(Bt.get(this)||this.topNode,e,t,!1);return Bt.set(this,n),n}resolveInner(e,t=0){let n=Gt(Vt.get(this)||this.topNode,e,t,!0);return Vt.set(this,n),n}resolveStack(e,t=0){return en(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:sn(Rt.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(Rt.none,t,n,r)))}static build(e){return rn(e)}};A.empty=new A(Rt.none,[],[],0);var Ht=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)}},Ut=class e{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return Rt.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 Gt(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 qt&&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 qt&&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 Kt=class{cursor(e=0){return new tn(this,e)}getChild(e,t=null,n=null){let r=Jt(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return Jt(this,e,t,n)}resolve(e,t=0){return Gt(this,e,t,!1)}resolveInner(e,t=0){return Gt(this,e,t,!0)}matchContext(e){return Yt(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}},qt=class e extends Kt{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=It.get(l))&&!d.overlay&&d.bracketed&&r>=u&&r<=u+l.length)&&!Wt(i,r,u,u+l.length))){if(l instanceof Ut){if(a&k.ExcludeBuffers)continue;let e=l.findChild(0,l.buffer.length,n,r-u,i);if(e>-1)return new Zt(new Xt(o,l,t,u),null,e)}else if(a&k.IncludeAnonymous||!l.type.isAnonymous||nn(l)){let s;if(!(a&k.IgnoreMounts)&&(s=It.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=It.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 Jt(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 Yt(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 Xt=class{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}},Zt=class e extends Kt{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 Qt(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 qt&&n.index<0?null:n.parent,i=e.slice();return r?i[t]=r:i.splice(t,1),new $t(i,n)}var $t=class{constructor(e,t){this.heads=e,this.node=t}get next(){return Qt(this.heads)}};function en(e,t,n){let r=e.resolveInner(t,n),i=null;for(let e=r instanceof qt?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=It.get(e.tree);if(a&&a.overlay&&a.overlay[0].from<=t&&a.overlay[a.overlay.length-1].to>=t){let o=new qt(a.tree,a.overlay[0].from+e.from,-1,e);(i||=[r]).push(Gt(o,t,n,!1))}}return i?Qt(i):r}var tn=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 qt)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 qt?(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 Ut||!e.type.isAnonymous||nn(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 Zt(this.buffer,t,this.stack[e]);return this.bufferNode=new Zt(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 Yt(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 Yt(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 nn(e){return e.children.some(e=>e instanceof Ut||!e.type.isAnonymous||nn(e))}function rn(e){let{buffer:t,nodeSet:n,maxBufferLength:r=Nt,reused:i=[],minRepeatType:a=n.types.length}=e,o=Array.isArray(t)?new Ht(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:w}=o,ee=l,te=c;if(w<0){if(o.next(),w==-1){let t=i[x];_.push(t),v.push(S-e);return}if(w==-3){c=x;return}if(w==-4){l=x;return}throw RangeError(`Unrecognized record size: ${w}`)}let ne=s[x],T,re,ie=S-e;if(C-S<=r&&(re=h(o.pos-t,y))){let t=new Uint16Array(re.size-re.skip),r=o.pos-re.size,i=t.length;for(;o.pos>r;)i=g(re.start,t,i);T=new Ut(t,C-re.start,n),ie=re.start-e}else{let e=o.pos-w;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,ee,te),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,ee,te),t.reverse(),n.reverse(),i>-1&&s>0){let e=f(ne,te);T=sn(ne,t,n,0,t.length,0,C-S,e,e)}else T=m(ne,t,n,C-S,ee-C,te)}_.push(T),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 Ut(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 an=new WeakMap;function on(e,t){if(!e.isAnonymous||t instanceof Ut||t.type!=e)return 1;let n=an.get(t);if(n==null){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof A)){n=1;break}n+=on(e,r)}an.set(t,n)}return n}function sn(e,t,n,r,i,a,o,s,c){let l=0;for(let n=r;n<i;n++)l+=on(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=on(e,t[s]);for(s++;s<i;s++){let n=on(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(sn(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 cn=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}},ln=class{startParse(e,t,n){return typeof e==`string`&&(e=new un(e)),n=n?n.length?n.map(e=>new Ft(e.from,e.to)):[new Ft(0,0)]:[new Ft(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}}},un=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 dn=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 fn(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 pn(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 fn(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()}},fn=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},pn=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}},mn=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 hn(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 gn=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}};let _n=new gn;var vn=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=_n,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=_n,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}},yn=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:n}=t.p;xn(this.data,e,t,this.id,n.data,n.tokenPrecTable)}};yn.prototype.contextual=yn.prototype.fallback=yn.prototype.extend=!1;var bn=class{constructor(e,t,n){this.precTable=t,this.elseToken=n,this.data=typeof e==`string`?hn(e):e}token(e,t){let n=e.pos,r=0;for(;;){let n=e.next<0,i=e.resolveOffset(1,1);if(xn(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))}};bn.prototype.contextual=yn.prototype.fallback=yn.prototype.extend=!1;function xn(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||Cn(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 Sn(e,t,n){for(let r=t,i;(i=e[r])!=65535;r++)if(i==n)return r-t;return-1}function Cn(e,t,n,r){let i=Sn(n,r,t);return i<0||Sn(n,r,e)<i}let wn=typeof process<`u`&&/\bparse\b/.test({}.LOG),Tn=null;function En(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 Dn=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?En(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?En(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}}},On=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(e=>new gn)}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 gn,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 gn,{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=Nn(o,s+2);else{r==0&&o[s+1]==2&&(r=this.putAction(Nn(o,s+2),t,n,r));break}}o[s]==t&&(r=this.putAction(Nn(o,s+1),t,n,r))}return r}},kn=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 vn(t,r),this.tokens=new On(e,this.stream),this.topTerm=e.top[1];let{from:i}=r[0];this.stacks=[dn.start(this,e.top[0],i)],this.fragments=n.length&&this.stream.end-i>e.bufferLength*4?new Dn(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 wn&&console.log(`Finish with `+this.stackID(e)),this.stackToTree(e);if(this.parser.strict)throw wn&&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 wn&&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=wn?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),wn&&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),wn&&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),wn&&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 An(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=wn?this.stackID(o)+` -> `:``;if(o.deadEnd&&(i||(i=!0,o.restart(),wn&&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()&&(wn&&console.log(d+this.stackID(u)+` (via force-reduce)`),!this.advanceFully(u,n));e++)wn&&(d=this.stackID(u)+` -> `);for(let e of o.recoverByInsert(s))wn&&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),wn&&console.log(l+this.stackID(o)+` (via recover-delete ${this.parser.getName(s)})`),An(o,n)):(!r||r.score<u.score)&&(r=u)}return r}stackToTree(e){return e.close(),A.build({buffer:mn.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=(Tn||=new WeakMap).get(e);return t||Tn.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function An(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 jn=class{constructor(e,t,n){this.source=e,this.flags=t,this.disabled=n}allows(e){return!this.disabled||this.disabled[e]==0}},Mn=class e extends ln{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 zt(t.map((t,i)=>Rt.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=Nt;let a=hn(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(Fn),this.states=hn(e.states,Uint32Array),this.data=hn(e.stateData),this.goto=hn(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(e=>typeof e==`number`?new yn(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 kn(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=Nn(n,i+2)];else if(n[i+1]==2)return Nn(n,i+2);else break}if(a==t||a==0)return Nn(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=Nn(this.data,n+2);else break}r=t(Nn(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=Nn(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]=Fn(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 jn(e,n,r)}static deserialize(t){return new e(t)}};function Nn(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 Fn(e){if(e.external){let t=+!!e.extend;return(n,r)=>e.external(n,r)<<1|t}return e.get}let In=Mn.deserialize({version:14,states:"-OOVQPOOOOQO'#Cb'#CbObQPO'#C`OgQPO'#C`OlQPO'#CnOqQQO'#C_OOQO'#C_'#C_O!SQQO'#CpQOQPOOOOQO,58z,58zO!bQPO,58zOOQO,59Y,59YO!jQPO'#CfOOQO,58y,58yOVQPO,58xO!xQPO'#CqO!}QPO'#CtOOQO,59[,59[O#SQPO,59[O#[QPO'#CdO#aQQO'#CcOOQO'#Cc'#CcOOQO1G.f1G.fOOQO'#Ci'#CiO#uQPO'#CgO#zQPO'#CgOOQO'#Cg'#CgOOQO,59Q,59QO$PQPO,59QO$XQPO'#C_O$dQPO1G.dO$lQPO,59]O$tQQO,59`OOQO1G.v1G.vOOQO,59O,59OO$yQPO'#CwO%OQQO,58}O%dQPO,59RO%uQPO,59RO%zQPO'#C{O&VQPO1G.lOOQO1G.l1G.lOVQPO'#C|O&_QPO7+$OOOQO'#Cs'#CsOOQO1G.w1G.wO&gQPO1G.wO&oQPO1G.zOOQO,59c,59cOOQO-E6u-E6uOOQO'#Cx'#CxO%dQPO'#CjOOQO'#Ck'#CkO&tQPO'#CkO'YQPO'#CkO'hQPO'#CjOOQO1G.m1G.mO%dQPO1G.mOOQO,59g,59gOOQO-E6y-E6yOOQO7+$W7+$WO'sQPO'#CcOOQO,59h,59hOOQO-E6z-E6zO(RQPO'#C}O(WQPO7+$cOOQO7+$c7+$cO(`QPO7+$fOOQO-E6v-E6vO(eQPO,59UO(pQPO'#CyO(uQPO,59VOOQO,59V,59VO)ZQPO,59UO(eQPO,59UOOQO7+$X7+$XO)eQPO,58}OOQO,59i,59iOOQO-E6{-E6{OOQO<<G}<<G}OOQO<<HQ<<HQO)sQPO1G.pO)}QPO1G.pOOQO,59e,59eOOQO-E6w-E6wOOQO1G.q1G.qOOQO,59f,59fOOQO-E6x-E6xO*YQPO7+$[P%dQPO'#CxO*dQPO,58zO*lQPO'#C`",stateData:"*q~OtOS~OTPOcSOuQO~OTXO~OuYO~OTZO~Ow[OfRXiRXrRXxRX~Of_Oi`Ox^OrdX~OTdOXcO~OTgOXcO[iOzkO~OwoO~O{pO~Oi`Orda~OTrO~OvsOfVXiVXrVXwVXxVX~OuuO~OTgO~OywOzyO~Ow[OrRXxRX~OxzOrQi~OT|Oz}O~Oj!PO~OT!QO~OvsOfVaiVarVawVaxVa~OT!VOXcO`!UOa!WOx!SO~Ou!ZO~OTgOXcO[iO~OywOz!^O~OxzOrQq~Oy!bOz!dO~OT!eO~O`!jOu!hOv!hOx_Xy_Xz_X~O`!jOx_Xy_Xz_X~Ox!SOy^Xz^X~OvsOrVXwVXxVX~OT|O~Oy!bOz!qO~O|!rO~Ox!SOy^az^a~OT!uO~O`!wOu!hOv!hOx_ay_az_a~Oy^az^a~P%dOvsOrVawVaxVa~Oy^iz^i~P%dOx!SOy^iz^i~Oy^qz^q~P%dOT!_OXcO~Ou!|O~O",goto:"%crPPsv!PP!W!_!cP!t!xP#O#V#]PP#jPs#oP#r#xPP$O$Y$o$u%P%V%]RWOQVOQn^R!`zQTOTm^zQROT!}^zTfY!|SeY!|Sj[w_!Uu!T!Z!k!s!z!{T]TmQl[R![wSh[wRviQ!YuR!m!ZS!Xu!ZQ!g!TX!x!k!s!z!{VUO^zRbVQ!OoR!o!bQaVRqbQtdS!Rt!nR!n!_S!Tu!ZY!f!T!k!s!z!{Q!k!XS!s!g!lR!z!tQ!i!VR!v!iQ!l!XQ!t!gT!y!l!tQxlR!]xQ{nR!a{Q!c!OR!p!c",nodeNames:`⚠ Query Pipeline Stage Head Word Aggregator Metric ParamRef Dollar Filters Filter Negate TagKey TagValue Value Star Quoted DatasetReference At Single GroupBy By Dimension Rollup RollupDot Int`,maxTerm:44,skippedNodes:[0],repeatNodeCount:7,tokenData:"'q~RhXY!mYZ!m]^!mpq!mqr#Ors#Ttu#rxy#wyz#|z{$R|}$W}!O$]!O!P$q!Q![%n![!]&U!b!c&Z!c!}$]#R#S$]#T#U$]#U#V&`#V#o$]#o#p'b#p#q'g#q#r'l~!rSt~XY!mYZ!m]^!mpq!m~#TO[~~#WTOr#Trs#gs;'S#T;'S;=`#l<%lO#T~#lOa~~#oP;=`<%l#T~#wOX~~#|O{~~$RO|~~$WO`~~$]Oy~P$bTTP}!O$]!Q![$]!c!}$]#R#S$]#T#o$]~$vPv~#f#g$y~$|P#c#d%P~%SP#`#a%V~%YP#`#a%]~%`P#i#j%c~%fP#d#e%i~%nOi~R%uTjQTP}!O$]!Q![%n!c!}$]#R#S$]#T#o$]~&ZOu~~&`Oc~R&eVTP}!O$]!Q![$]!c!}$]#R#S$]#T#m$]#m#n&z#n#o$]R'RTfQTP}!O$]!Q![$]!c!}$]#R#S$]#T#o$]~'gOw~~'lOx~~'qOz~",tokenizers:[0,1],topRules:{Query:[0,1]},tokenPrec:0}),Ln=[],Rn=[];(()=>{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?Rn:Ln).push(n+=e[t])})();function zn(e){if(e<768)return!1;for(let t=0,n=Ln.length;;){let r=t+n>>1;if(e<Ln[r])n=r;else if(e>=Rn[r])t=r+1;else return!0;if(t==n)return!1}}function Bn(e){return e>=127462&&e<=127487}let Vn=8205;function Hn(e,t,n=!0,r=!0){return(n?Un:Wn)(e,t,r)}function Un(e,t,n){if(t==e.length)return t;t&&Kn(e.charCodeAt(t))&&qn(e.charCodeAt(t-1))&&t--;let r=Gn(e,t);for(t+=Jn(r);t<e.length;){let i=Gn(e,t);if(r==Vn||i==Vn||n&&zn(i))t+=Jn(i),r=i;else if(Bn(i)){let n=0,r=t-2;for(;r>=0&&Bn(Gn(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function Wn(e,t,n){for(;t>0;){let r=Un(e,t-2,n);if(r<t)return r;t--}return 0}function Gn(e,t){let n=e.charCodeAt(t);if(!qn(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return Kn(r)?(n-55296<<10)+(r-56320)+65536:n}function Kn(e){return e>=56320&&e<57344}function qn(e){return e>=55296&&e<56320}function Jn(e){return e<65536?1:2}var j=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]=ir(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),Xn.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]=ir(this,e,t);let n=[];return this.decompose(e,t,n,0),Xn.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 er(this),i=new er(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 er(this,e)}iterRange(e,t=this.length){return new tr(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 nr(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 Yn(t):Xn.from(Yn.split(t,[]))}},Yn=class e extends j{constructor(e,t=Zn(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 rr(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e($n(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=Qn(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]=ir(this,t,n);let i=Qn(this.text,Qn(r.text,$n(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):Xn.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
|
|
5
5
|
`){[e,t]=ir(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}},Xn=class e extends j{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]=ir(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=`
|
|
6
6
|
`){[e,t]=ir(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 Yn(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 Yn&&c&&(n=u[u.length-1])instanceof Yn&&t.lines+n.lines<=32?(c+=t.lines,l+=t.length+1,u[u.length-1]=new Yn(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)}};j.empty=new Yn([``],0);function Zn(e){let t=-1;for(let n of e)t+=n.length+1;return t}function Qn(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 $n(e,t,n){return Qn(e,[``],t,n)}var er=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 Yn?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 Yn?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=`
|
|
7
7
|
`,this;e--}else if(r instanceof Yn){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 Yn?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)}},tr=class{constructor(e,t,n){this.value=``,this.done=!1,this.cursor=new er(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!=``}},nr=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`&&(j.prototype[Symbol.iterator]=function(){return this.iter()},er.prototype[Symbol.iterator]=tr.prototype[Symbol.iterator]=nr.prototype[Symbol.iterator]=function(){return this});var rr=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 ir(e,t,n){return t=Math.max(0,Math.min(e.length,t)),[t,Math.max(t,Math.min(e.length,n))]}function ar(e,t,n=!0,r=!0){return Hn(e,t,n,r)}let or=/\r\n?|\n/;var sr=(function(e){return e[e.Simple=0]=`Simple`,e[e.TrackDel=1]=`TrackDel`,e[e.TrackBefore=2]=`TrackBefore`,e[e.TrackAfter=3]=`TrackAfter`,e})(sr||={}),cr=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){dr(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:pr(this,e)}mapDesc(e,t=!1){return e.empty?this:fr(this,e,t)}mapPos(e,t=-1,n=sr.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!=sr.Simple&&c>=e&&(n==sr.TrackDel&&r<e&&c>e||n==sr.TrackBefore&&r<e||n==sr.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)}},lr=class e extends cr{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 dr(this,(t,n,r,i,a)=>e=e.replace(r,r+(n-t),a),!1),e}mapDesc(e,t=!1){return fr(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(j.empty);r.push(a?t.slice(i,i+a):j.empty)}i+=a}return new e(n,r)}compose(e){return this.empty?e:e.empty?this:pr(this,e,!0)}map(e,t=!1){return e.empty?this:fr(this,e,t,!0)}iterChanges(e,t=!1){dr(this,e,t)}get desc(){return cr.create(this.sections)}filter(t){let n=[],r=[],i=[],a=new mr(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);M(i,e,-1);let t=a.ins==-1?-1:a.off==0?a.ins:0;M(n,e,t),t>0&&ur(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);M(n,e,-1),M(i,e,a.ins==-1?-1:a.off==0?a.ins:0),a.forward(e),o+=e}}return{changes:new e(n,r),filtered:cr.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&&M(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`?j.of(l.split(r||or)):l:j.empty,d=u.length;if(e==s&&d==0)return;e<o&&c(),e>o&&M(i,e-o,-1),M(i,s-e,d),ur(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(j.empty);r[e]=j.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 M(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 ur(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(j.empty);e.push(n)}}function dr(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=j.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 fr(e,t,n,r=!1){let i=[],a=r?[]:null,o=new mr(e),s=new mr(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);M(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(M(i,s.ins,-1);t;){let n=Math.min(o.len,t);o.ins>=0&&e<o.i&&o.len<=n&&(M(i,0,o.ins),a&&ur(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;M(i,t,e<o.i?o.ins:0),a&&e<o.i&&ur(a,i,o.text),e=o.i,o.forward(o.len-n)}else if(o.done&&s.done)return a?lr.createSet(i,a):cr.create(i);else throw Error(`Mismatched change set lengths`)}function pr(e,t,n=!1){let r=[],i=n?[]:null,a=new mr(e),o=new mr(t);for(let e=!1;;)if(a.done&&o.done)return i?lr.createSet(r,i):cr.create(r);else if(a.ins==0)M(r,a.len,0,e),a.next();else if(o.len==0&&!o.done)M(r,0,o.ins,e),i&&ur(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;M(r,t,n,e),i&&n&&ur(i,r,o.text)}else o.ins==-1?(M(r,a.off?0:a.len,t,e),i&&ur(i,r,a.textBit(t))):(M(r,a.off?0:a.len,o.off?0:o.ins,e),i&&!o.off&&ur(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 mr=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?j.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?j.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)}},hr=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 N.range(e,t,void 0,void 0,n);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return N.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 N.range(e.anchor,e.head)}static create(t,n,r,i){return new e(t,n,r,i)}},N=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=>hr.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 hr.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?hr.create(t,e,a|32,n):hr.create(e,t,a,n)}static undirectionalRange(e,t){return hr.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 gr(e,t){for(let n of e.ranges)if(n.to>t)throw RangeError(`Selection points outside of document`)}let _r=0;var P=class e{constructor(e,t,n,r,i){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=r,this.id=_r++,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:vr),!!t.static,t.enables)}of(e){return new yr([],this,0,e)}compute(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new yr(e,this,1,t)}computeN(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new yr(e,this,2,t)}from(e,t){return t||=e=>e,this.compute([e],n=>t(n.field(e)))}};function vr(e,t){return e==t||e.length==t.length&&e.every((e,n)=>e===t[n])}var yr=class{constructor(e,t,n,r){this.dependencies=e,this.facet=t,this.type=n,this.value=r,this.id=_r++}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)||xr(e,c)){let r=t(e);if(a?!br(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 P?o.facet(t)===e.facet(t):t instanceof wr?o.field(t,!1)==e.field(t,!1):!0)||(a?br(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 br(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 xr(e,t){let n=!1;for(let r of t)Nr(e,r)&1&&(n=!0);return n}function Sr(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)Nr(e,t);return e.values[o]=s(e),1},update(e,n){if(!xr(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=xr(e,r),c=i.config.facets[t.id],l=i.facet(t);if(c&&!a&&vr(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 Cr=P.define({static:!0});var wr=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(_r++,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(Cr).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(Cr),i=n.facet(Cr),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,Cr.of({field:this,create:e})]}get extension(){return this}};let Tr={lowest:4,low:3,default:2,high:1,highest:0};function Er(e){return t=>new Or(t,e)}let Dr={highest:Er(Tr.highest),high:Er(Tr.high),default:Er(Tr.default),low:Er(Tr.low),lowest:Er(Tr.lowest)};var Or=class{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}},kr=class e{of(e){return new Ar(this,e)}reconfigure(t){return e.reconfigure.of({compartment:this,extension:t})}get(e){return e.config.compartments.get(this)}},Ar=class{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}},jr=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 Mr(t,n,o))e instanceof wr?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,vr(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=>Sr(e,n,t))}}let d=l.map(e=>e(s));return new e(t,o,d,s,c,a)}};function Mr(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 Ar&&n.delete(e.compartment)}if(i.set(e,o),Array.isArray(e))for(let t of e)a(t,o);else if(e instanceof Ar){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 Or)a(e.inner,e.prec);else if(e instanceof wr)r[o].push(e),e.provides&&a(e.provides,o);else if(e instanceof yr)r[o].push(e),e.facet.extensions&&a(e.facet.extensions,Tr.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,Tr.default),r.reduce((e,t)=>e.concat(t))}function Nr(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 Fr=P.define(),Ir=P.define({combine:e=>e.some(e=>e),static:!0}),Lr=P.define({combine:e=>e.length?e[0]:void 0,static:!0}),Rr=P.define(),zr=P.define(),Br=P.define(),Vr=P.define({combine:e=>e.length?e[0]:!1});var Hr=class{constructor(e,t){this.type=e,this.value=t}static define(){return new Ur}},Ur=class{of(e){return new Hr(this,e)}},Wr=class{constructor(e){this.map=e}of(e){return new F(this,e)}},F=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 Wr(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}};F.reconfigure=F.define(),F.appendConfig=F.define();var Gr=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&&gr(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]==`.`))}};Gr.time=Hr.define(),Gr.userEvent=Hr.define(),Gr.addToHistory=Hr.define(),Gr.remote=Hr.define();function Kr(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 qr(e,t,n){let r,i,a;return n?(r=t.changes,i=lr.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:F.mapEffects(e.effects,r).concat(F.mapEffects(t.effects,i)),annotations:e.annotations.length?e.annotations.concat(t.annotations):t.annotations,scrollIntoView:e.scrollIntoView||t.scrollIntoView}}function Jr(e,t,n){let r=t.selection,i=$r(t.annotations);return t.userEvent&&(i=i.concat(Gr.userEvent.of(t.userEvent))),{changes:t.changes instanceof lr?t.changes:lr.of(t.changes||[],n,e.facet(Lr)),selection:r&&(r instanceof N?r:N.single(r.anchor,r.head)),effects:$r(t.effects),annotations:i,scrollIntoView:!!t.scrollIntoView}}function Yr(e,t,n){let r=Jr(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=qr(r,Jr(e,t[i],a?r.changes.newLength:e.doc.length),a)}let i=Gr.create(e,r.changes,r.selection,r.effects,r.annotations,r.scrollIntoView);return Zr(n?Xr(i):i)}function Xr(e){let t=e.startState,n=!0;for(let r of t.facet(Rr)){let t=r(e);if(t===!1){n=!1;break}Array.isArray(t)&&(n=n===!0?t:Kr(n,t))}if(n!==!0){let r,i;if(n===!1)i=e.changes.invertedDesc,r=lr.empty(t.doc.length);else{let t=e.changes.filter(n);r=t.changes,i=t.filtered.mapDesc(t.changes).invertedDesc}e=Gr.create(t,r,e.selection&&e.selection.map(i),F.mapEffects(e.effects,i),e.annotations,e.scrollIntoView)}let r=t.facet(zr);for(let n=r.length-1;n>=0;n--){let i=r[n](e);e=i instanceof Gr?i:Array.isArray(i)&&i.length==1&&i[0]instanceof Gr?i[0]:Yr(t,$r(i),!1)}return e}function Zr(e){let t=e.startState,n=t.facet(Br),r=e;for(let i=n.length-1;i>=0;i--){let a=n[i](e);a&&Object.keys(a).length&&(r=qr(r,Jr(t,a,e.changes.newLength),!0))}return r==e?e:Gr.create(t,e.changes,e.selection,r.effects,r.annotations,r.scrollIntoView)}let Qr=[];function $r(e){return e==null?Qr:Array.isArray(e)?e:[e]}var ei=(function(e){return e[e.Word=0]=`Word`,e[e.Space=1]=`Space`,e[e.Other=2]=`Other`,e})(ei||={});let ti=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ni;try{ni=RegExp(`[\\p{Alphabetic}\\p{Number}_]`,`u`)}catch{}function ri(e){if(ni)return ni.test(e);for(let t=0;t<e.length;t++){let n=e[t];if(/\w/.test(n)||n>``&&(n.toUpperCase()!=n.toLowerCase()||ti.test(n)))return!0}return!1}function ii(e){return t=>{if(!/\S/.test(t))return ei.Space;if(ri(t))return ei.Word;for(let n=0;n<e.length;n++)if(t.indexOf(e[n])>-1)return ei.Word;return ei.Other}}var I=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++)Nr(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 Nr(this,n),Pr(this,n)}update(...e){return Yr(this,e,!0)}applyTransaction(t){let n=this.config,{base:r,compartments:i}=n;for(let e of t.effects)e.is(kr.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(F.reconfigure)?(n=null,r=e.value):e.is(F.appendConfig)&&(n=null,r=$r(r).concat(e.value));let a;n?a=t.startState.values.slice():(n=jr.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(Ir)?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:N.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=$r(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=F.mapEffects(a,c).concat(F.mapEffects($r(o.effects),l))}return{changes:r,selection:N.create(i,t.mainIndex),effects:a}}changes(t=[]){return t instanceof lr?t:lr.of(t,this.doc.length,this.facet(e.lineSeparator))}toText(t){return j.of(t.split(this.facet(e.lineSeparator)||or))}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:(Nr(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 wr&&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:N.fromJSON(t.selection),extensions:n.extensions?i.concat([n.extensions]):i})}static create(t={}){let n=jr.resolve(t.extensions||[],new Map),r=t.doc instanceof j?t.doc:j.of((t.doc||``).split(n.staticFacet(e.lineSeparator)||or)),i=t.selection?t.selection instanceof N?t.selection:N.single(t.selection.anchor,t.selection.head):N.single(0);return gr(i,r.length),n.staticFacet(Ir)||(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)||`
|
|
@@ -18,5 +18,5 @@
|
|
|
18
18
|
`,i=t??ip.parse(r),a=ap(n),o=[],s=null;return i.iterate({enter(e){if(e.name===`⚠`){s&&s.to===e.from&&o.splice(s.index,1),s=null;return}if(e.name===`Property`){let t=sp(a,n,e.from,e.to);if(t){let n=t.meta;o.push({id:o.length,line:n.line,meta:n,primitives:[t],children:[],isLeaf:!0}),s={to:e.to,index:o.length-1}}return}if(e.name!==`Block`)return;s=null;let t=pp(a,e.from,e.to,n.slice(e.from,e.to)),r={id:o.length,line:t.line,meta:t,primitives:[],children:[],isLeaf:!0},i=e.node.cursor();if(i.firstChild())do{let e=i.node,t=n.slice(e.from,e.to);if(e.type.id===8){let n={kind:`lap`,raw:t,meta:pp(a,e.from,e.to,t),lapType:t===`+`?`compose`:`round`};r.primitives.push(n);continue}if(e.type.id!==9||!e.firstChild)continue;let o=e.firstChild,s=up(a,n,o);s&&r.primitives.push(s)}while(i.nextSibling());o.push(r)}}),dp(o),{statements:o}}function sp(e,t,n,r){let i=t.slice(n,r),a=pp(e,n,r,i),o=i.match(/^\s*([A-Za-z][A-Za-z0-9]*)\s*:\s*(.*?)\s*$/);if(!o)return null;let[,s,c]=o,l=cp(c);return{kind:`property`,raw:i,meta:a,key:s,valueRaw:c,value:l===void 0?lp(c):c.trim(),...l===void 0?{}:{tagRefs:l}}}function cp(e){let t=e.trim().split(/\s+/).filter(e=>e.length>0);if(t.length===0)return;let n=[];for(let e of t){let t=e.match(/^#([a-zA-Z0-9][a-zA-Z0-9-]*)$/);if(!t)return;n.push(t[1])}return n}function lp(e){let t=e.trim();return/^"(?:[^"\\]|\\.)*"$/.test(t)?t.slice(1,-1).replace(/\\(["\\/bfnrt])/g,`$1`):/^-?(?:\d+\.\d+|\d+)$/.test(t)?Number(t):t===`true`?!0:t===`false`?!1:t===`null`?null:t}function up(e,t,n){let r=t.slice(n.from,n.to),i=pp(e,n.from,n.to,r);switch(n.type.id){case 10:{let e=n.getChild(`Trend`),a=n.getChild(`Timer`)||n.getChild(`CollectibleTimer`);return{kind:`duration`,raw:r,meta:i,timerRaw:a?t.slice(a.from,a.to):void 0,hasTrend:!!e,isRequired:r.includes(`*`)}}case 14:{let a=n.getChild(`Sequence`),o=n.getChildren(`Identifier`),s=o[0],c=o[o.length-1];return{kind:`rounds`,raw:r,meta:i,sequence:a?t.slice(a.from,a.to).split(`-`).map(e=>Number(e.trim())):void 0,label:o.length>0?o.map(e=>t.slice(e.from,e.to)).join(` `):void 0,sequenceMeta:a?pp(e,a.from,a.to,t.slice(a.from,a.to)):void 0,labelMeta:s&&c?pp(e,s.from,c.to,t.slice(s.from,c.to)):void 0}}case 16:{let e=r.match(/^(\d+)\s*[xX]\s*(\d+)$/);return e?{kind:`round_scheme`,raw:r,meta:i,rounds:parseInt(e[1],10),reps:parseInt(e[2],10)}:null}case 17:return{kind:`action`,raw:r,meta:i,hasColonPrefix:r.startsWith(`[:`)};case 18:return{kind:`text`,raw:r,meta:i};case 19:return{kind:`heading`,raw:r,meta:i};case 20:{let e=!!n.getChild(`AtSign`),a=n.getChild(`Number`);return{kind:`quantity`,raw:r,meta:i,value:a?parseFloat(t.slice(a.from,a.to)):void 0,hasAtSign:e}}case 25:return{kind:`effort`,raw:r,meta:i};case 6:{let e=r.match(/^#([a-zA-Z0-9][a-zA-Z0-9-]*)$/);return e?{kind:`tag_ref`,raw:r,meta:i,slug:e[1]}:null}case 23:return{kind:`effort`,raw:r,meta:i};case 24:return{kind:`effort`,raw:r,meta:i};case 26:{let e=[];try{let t=JSON.parse(r);t&&typeof t==`object`&&!Array.isArray(t)&&(e=Object.entries(t).map(([e,t])=>({key:e,value:t})))}catch{}return{kind:`metric_object`,raw:r,meta:i,pairs:e}}default:return null}}function dp(e){let t=new Map,n=[];for(let r of e){if(n=n.filter(e=>e.columnStart<r.meta.columnStart),n.length>0)for(let e of n)t.has(e.statement.id)||t.set(e.statement.id,[]),t.get(e.statement.id).push(r.id),r.parentId=e.statement.id;n.push({columnStart:r.meta.columnStart,statement:r})}for(let n of e)n.children=fp(t.get(n.id)??[],e),n.isLeaf=n.children.length===0}function fp(e,t){if(e.length===0)return[];let n=new Map(t.map(e=>[e.id,e])),r=[];for(let t of e)n.get(t)?.primitives.find(e=>e.kind===`lap`)?.lapType===`compose`&&r.length>0?r[r.length-1].push(t):r.push([t]);return r}function pp(e,t,n,r){let{lineNumber:i,lineStart:a}=e(t);return{line:i,startOffset:t,endOffset:n,columnStart:t-a,columnEnd:n-a,length:n-t,raw:r}}function mp(e,t){return typeof e==`string`?{source:e,tree:t}:`source`in e?{source:e.source,tree:t??e.tree}:`doc`in e?{source:e.doc.toString(),tree:t}:{source:``}}function hp(e,t,n){let{source:r,tree:i}=mp(e,t);return yp(Gf(op(r,i),n))}function gp(e,t,n,r){let i,a;typeof t==`string`?i=t:t&&typeof t==`object`&&(a=t,i=n);let o=mp(e,a),s=Gf(op(o.source,o.tree),r);return Ef.processAll(s,i),Jf(s,r),yp(s)}function _p(e){return e.children.length>0?!1:e.metrics.some(e=>e.type===E.Rounds)&&e.metrics.some(e=>e.type===E.Rep)&&!e.metrics.some(e=>e.type===E.Duration)}function vp(e){let t=Object.create(Object.getPrototypeOf(e));return Object.assign(t,e),t}function yp(e){if(!e.some(_p))return e;let t=[],n=new Map,r=new Map,i=new Map,a=new Map;for(let o of e){if(!_p(o)){n.set(o.id,t.length),t.push(o);continue}o.parent!==void 0&&r.set(o.id,o.parent);let e=vp(o),s=vp(o),c=e=>e.type===E.Rounds||e.type===E.Rep;e.metrics=D.from(o.metrics.filter(c),e.id),s.metrics=D.from(o.metrics.filter(e=>!c(e)),s.id),e.metricMeta=new Map([...o.metricMeta].filter(([e])=>c(e))),s.metricMeta=new Map([...o.metricMeta].filter(([e])=>!c(e))),e.isLeaf=!1,s.isLeaf=!0,e.children=[],s.children=[],i.set(s,e),a.set(e,o.id),n.set(o.id,t.length),t.push(e,s)}return t.map((e,t)=>{let o=e.id;if(e.id=t,e.metrics=D.from(e.metrics,e.id),i.get(e))return e.parent=t-1,e;if(a.has(e)){e.children=[[t+1]];let i=r.get(a.get(e));return e.parent=i===void 0?void 0:n.get(i),e}return e.parent=e.parent===void 0?void 0:n.get(e.parent),e.children=e.children.map(e=>e.filter(e=>!r.has(e)||r.get(e)===o).map(e=>n.get(e)??e)).filter(e=>e.length>0),e})}var bp=class{source;statements;errors;_idMap;constructor(e,t,n=[]){this.source=e,this.statements=t,this.errors=n}getIdMap(){return this._idMap||=new Map(this.statements.map(e=>[e.id,e])),this._idMap}getIds(e){let t=this.getIdMap();return e.map(e=>t.get(e)).filter(Boolean)}getId(e){return this.getIdMap().get(e)}getAt(e){return this.statements[e]}getFlatChildren(e){return this.getIds(e.flat())}getChildGroups(e){return e.map(e=>this.getIds(e))}};function xp(e,t={}){if(!e||!e.trim())return new bp(e,[],[]);try{let n=e.endsWith(`
|
|
19
19
|
`)?e:e+`
|
|
20
20
|
`,r=ip.parse(n),i=t.sport??t.dialect,a=t.references||t.tags?{...t.references?{index:t.references}:{},defaults:t.defaults,tags:t.tags}:void 0;return new bp(e,t.withoutDialects?hp(e,r,a):gp(e,r,i,a),[])}catch(t){return new bp(e,[],[{message:t instanceof Error?t.message:`Unknown parse error`}])}}function Sp(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,` `).replace(/[-_]+/g,` `).trim().replace(/\s+/g,` `)}let Cp={units:{name:`Units`,rank:1},inNotebook:{name:`In this notebook`,rank:2},templates:{name:`Templates`,rank:3},actionCues:{name:`Action Cues`,rank:4},structure:{name:`Structure`,rank:5},movements:{name:`Movements`,rank:6},tags:{name:`Tags`,rank:7},equipment:{name:`Equipment`,rank:8},sounds:{name:`Sounds`,rank:9},dialect:{name:`Dialect`,rank:10},blockProperties:{name:`Block Properties`,rank:20},unitAliases:{name:`Unit Aliases`,rank:50},create:{name:`Create`,rank:90}};Object.fromEntries(Object.values(Cp).map(e=>[e.name.toLowerCase(),e])),[...Object.keys(If)],Cp.actionCues,Cp.actionCues,Cp.actionCues,Cp.actionCues,Cp.movements,Cp.equipment,Cp.sounds,Cp.tags,tu.define({parser:ip.configure({props:[Ml({Identifier:Y.variableName,String:Y.string,Number:Y.number,"schemeNumber schemeSpaced":Y.number,Timer:Y.keyword,collectibleTimer:Y.keyword,textComment:Y.lineComment,heading:Y.heading,minus:Y.operator,plus:Y.operator,trend:Y.operator,atSign:Y.operator,"Slash/slash":Y.operator,question:Y.keyword,actionOpen:Y.bracket,actionClose:Y.bracket,groupOpen:Y.bracket,groupClose:Y.bracket,colon:Y.punctuation,Property:Y.propertyName,"Block/Lap":Y.keyword})]}),languageData:{commentTokens:{line:`//`},closeBrackets:{brackets:[`(`,`[`,`'`,`"`]}}});let wp={core:0,community:1,imported:2,user:3};function Tp(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 Ep(e){return e.registrySource===`user`?`user`:Tp(e.sourceId)}function Dp(e){return wp[Ep(e)]}function Op(e){let t=new Map;for(let n of e){let e=n.slug.toLowerCase(),r=t.get(e);(!r||Dp(n)>=Dp(r))&&t.set(e,n)}return Array.from(t.values())}let kp={defaultMet:5,defaultThreshold:2},Ap=[`bodyweight`,`cycling`,`gymnastics`,`kettlebell`,`recovery`,`rowing`,`running`,`strength`,`swimming`,`walking`];function jp(e){return typeof e==`string`&&Ap.includes(e.toLowerCase())}let Z=[];for(let e=0;e<256;++e)Z.push((e+256).toString(16).slice(1));function Mp(e,t=0){return(Z[e[t+0]]+Z[e[t+1]]+Z[e[t+2]]+Z[e[t+3]]+`-`+Z[e[t+4]]+Z[e[t+5]]+`-`+Z[e[t+6]]+Z[e[t+7]]+`-`+Z[e[t+8]]+Z[e[t+9]]+`-`+Z[e[t+10]]+Z[e[t+11]]+Z[e[t+12]]+Z[e[t+13]]+Z[e[t+14]]+Z[e[t+15]]).toLowerCase()}let Np,Pp=new Uint8Array(16);function Fp(){if(!Np){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);Np=crypto.getRandomValues.bind(crypto)}return Np(Pp)}let Ip={};function Lp(e,t,n){let r;if(e)r=zp(e.random??e.rng?.()??Fp(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=Fp();Rp(Ip,e,i),r=zp(i,Ip.msecs,Ip.seq,t,n)}return t??Mp(r)}function Rp(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 zp(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 Bp=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Vp(e){return e.replace(/^(['"])(.*)\1$/,(e,t,n)=>t===`"`?n.replace(/\\(["\\nrt])/g,(e,t)=>t===`n`?`
|
|
21
|
-
`:t===`r`?`\r`:t===`t`?` `:t):n)}function Hp(e,t){let n=e[t];return n===void 0||typeof n==`string`&&n===`[]`?[]:Array.isArray(n)?n:void 0}function Up(e){return e===`true`?!0:e===`false`?!1:e!==``&&!Number.isNaN(Number(e))?Number(e):Vp(e)}function Wp(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]=Up(l)):o>=4&&i!==null&&(r[i][c]=Up(l))}return Object.keys(r).length>0?r:void 0}function Gp(e){if(!e)return;let t=Vp(e.trim()).toLowerCase();if(jp(t))return t;console.warn(`[definition-markdown] unknown discipline '${e}' — expected one of the canonical values; treating as unset`)}function Kp(e,t){let n=[],r=e===void 0?``:String(e);return r?Bp.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 qp(e,t){let n=[];for(let r of e)r.trim()?t===`equipment`&&!Bp.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 Jp(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 Yp(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}=et(e),a=tt(r,`type`);if(a!==void 0&&a!==`effort`)return null;let o=tt(r,`id`),s=tt(r,`slug`),c=tt(r,`label`),l=Hp(r,`aliases`),u=Hp(r,`equipment`);if(l===void 0||u===void 0||Kp(s,c).length>0||qp(l,`aliases`).length>0||u.length>0&&qp(u,`equipment`).length>0)return null;let d=Wp(n,`baseAttributes`)??{},f=Wp(n,`metrics`)??{},p=r[`metrics.met`]??f.met??d.met;if(Jp(p)!==null)return null;let m=Number(p),h=tt(r,`discipline`),g=Gp(typeof h==`string`?h:typeof d.discipline==`string`?d.discipline:void 0),_=tt(r,`intensityTier`)??tt(r,`intensity`)??d.intensityTier,v=r[`metrics.disciplineFactor`]??f.disciplineFactor??d.disciplineFactor,y=typeof v==`number`&&Number.isFinite(v)?v:void 0,b=Wp(n,`hints`),x=Wp(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 Xp(e){let{meta:t,body:n}=et(e);if(tt(t,`type`)!==`equipment`)return null;let r=tt(t,`id`),i=tt(t,`slug`),a=tt(t,`label`),o=Hp(t,`aliases`);if(r===void 0||o===void 0||Kp(i,a).length>0||qp(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 Zp=[{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`}];[...Zp];let Qp=Zp;Qp.length;function $p(e){let t=Op(e),n=new Map,r=(e,t)=>{if(!e)return;let r=n.get(e);r?r.includes(t)||r.push(t):n.set(e,[t])};for(let e of t){r(e.slug.toLowerCase(),e),r(Sp(e.label),e);for(let t of e.aliases)r(Sp(t),e)}return{byKey:n,lookup(e){let t=n.get(e)??n.get(Sp(e));if(!t||t.length===0)return{entity:null,ambiguous:[]};if(t.length===1)return{entity:t[0],ambiguous:[]};let r=-1;for(let e of t){let t=Dp(e);t>r&&(r=t)}let i=t.filter(e=>Dp(e)===r);if(i.length===1)return{entity:i[0],ambiguous:[]};let a=e.trim().toLowerCase(),o=Sp(e).replace(/\s+/g,`-`),s=i.filter(e=>e.slug.toLowerCase()===a||e.slug.toLowerCase()===o);return s.length===1?{entity:s[0],ambiguous:[]}:{entity:null,ambiguous:i}}}}function em(e){return{kind:`equipment`,slug:e.slug,label:e.label}}function tm(e){let t=new Set,n=[];for(let r of e){let e=`${r.kind}:${r.slug}`;t.has(e)||(t.add(e),n.push(r))}return n}function nm(e,t){let n=Op(e.equipment??[]),r=$p(e.efforts??[]),i=$p(n),a=n.flatMap(e=>[e.label,...e.aliases].filter(e=>!!e&&!!e.trim()).map(t=>({lower:t.trim().toLowerCase(),entity:e}))).sort((e,t)=>t.lower.length-e.lower.length),o=t??(e=>({effort:e,definition:e,slug:e.slug,label:e.label,met:e.baseAttributes.met,baseAttributes:e.baseAttributes,discipline:e.baseAttributes.discipline,disciplineFactor:e.baseAttributes.disciplineFactor??1,intensityTier:e.baseAttributes.intensityTier,modifiers:{},registrySource:e.registrySource,resolvedFrom:e.registrySource===`user`?`user`:e.registrySource===`bundled`?`bundled`:`default`,isEstimated:!1})),s=e=>{let t=r.lookup(e.trim());return t.entity?{entity:t.entity}:t.ambiguous.length>0?{entity:null,diagnostic:{reason:`ambiguous-effort`,message:`"${e}" matches multiple efforts.`,token:e,candidates:t.ambiguous.map(e=>e.slug)}}:{entity:null,diagnostic:{reason:`unknown-effort`,message:`Unknown effort "${e}".`,token:e}}},c=e=>{let t=[],n=[];for(let r of e){if(typeof r!=`string`||!r.trim()){n.push({reason:`invalid-explicit`,message:`Equipment reference must be a slug string, got ${JSON.stringify(r)??`null`}.`,token:String(r)});continue}let e=i.lookup(r.trim());e.entity?t.push(em(e.entity)):e.ambiguous.length>0?n.push({reason:`ambiguous-equipment`,message:`"${r}" matches multiple equipment entries.`,token:r,candidates:e.ambiguous.map(e=>e.slug)}):n.push({reason:`invalid-explicit`,message:`Unknown equipment "${r}".`,token:r})}return{refs:tm(t),diagnostics:n}};return{resolveEffort(e){return r.lookup(e).entity},resolveEquipment(e){return i.lookup(e).entity},materialize(e){return o(e)},resolve(e,t){let n=(e??``).trim(),r=[],l=e=>{e&&r.push(e)},u=`none`,d=null,f=``,p=[],m=!1,h,g=()=>{if(!(p.length>0||m)&&d!==null){if(t?.equipment?.length){let e=c(t.equipment);p=e.refs;for(let t of e.diagnostics)l({...t,reason:`unknown-equipment`});if(p.length>0)return}if(d.equipment?.length){let e=c(d.equipment);p=e.refs;for(let t of e.diagnostics)l({...t,reason:`unknown-equipment`})}}};if(!n){if(t?.effort){let e=s(t.effort);e.entity?(d=e.entity,u=`default`):l({reason:e.diagnostic?.reason===`ambiguous-effort`?`ambiguous-effort`:`unknown-effort`,message:`Default effort "${t.effort}" is not in the catalog.`,token:t.effort,candidates:e.diagnostic?.candidates})}return g(),{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label}:null,equipment:p,remaining:``,diagnostics:r}}if(n.startsWith(`{`)){let e;try{e=JSON.parse(n)}catch{return{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:[{reason:`malformed-json`,message:`Reference object is not valid JSON.`,token:n}]}}if(e&&typeof e==`object`&&!Array.isArray(e)&&(`effort`in e||`equipment`in e)){u=`explicit`;let t=e;if(t.effort!==void 0){if(typeof t.effort==`string`&&t.effort.trim()){let e=s(t.effort);d=e.entity,e.diagnostic&&l(e.diagnostic.reason===`ambiguous-effort`?e.diagnostic:{...e.diagnostic,reason:`invalid-explicit`,message:`Explicit effort "${t.effort}" is not in the catalog.`})}else l({reason:`invalid-explicit`,message:`Explicit "effort" must be a slug string.`,token:String(t.effort)})}if(t.equipment!==void 0){m=!0;let e=Array.isArray(t.equipment)?t.equipment:[t.equipment],i=c(e);if(p=i.refs,r.push(...i.diagnostics),d&&d.equipment?.length){let e=new Set(d.equipment),t=p.map(e=>e.slug);t.length>0&&t.some(t=>!e.has(t))&&l({reason:`conflict`,message:`Explicit equipment [${t.join(`, `)}] contradicts effort "${d.slug}" definition equipment [${d.equipment.join(`, `)}].`,token:n})}}return g(),{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label}:null,equipment:p,remaining:``,diagnostics:r}}}let _=s(n),v=n.toLowerCase();for(let e of a){if(!v.startsWith(e.lower))continue;let t=n.slice(e.lower.length);if(t&&!/^\s/.test(t))continue;let a=t.trim();if(!a)continue;let o=i.lookup(e.lower);if(o.ambiguous.length>0)return l({reason:`ambiguous-equipment`,message:`"${e.lower}" matches multiple equipment entries.`,token:n,candidates:o.ambiguous.map(e=>e.slug)}),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};if(!o.entity)continue;let c=s(a);if(_.entity&&_.entity.equipment?.includes(o.entity.slug)&&(c.entity||c.diagnostic?.reason===`ambiguous-effort`)){u=`whole`,d=_.entity;break}if(c.entity){u=`split`,d=c.entity;let t=n.slice(0,e.lower.length).trim();p=[{...em(o.entity),...t.toLowerCase()===o.entity.label.toLowerCase()?{}:{matchedAlias:t}}],m=!0,f=a,h={start:0,end:t.length};break}if(c.diagnostic?.reason===`ambiguous-effort`&&!_.entity)return l(c.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r}}if(u===`none`){if(_.entity)d=_.entity,u=`whole`;else if(_.diagnostic?.reason===`ambiguous-effort`)return l(_.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};else _.diagnostic&&l(_.diagnostic)}if(u===`none`)for(let e of a){if(!v.endsWith(e.lower))continue;let t=n.length-e.lower.length;if(t<=0||!/\s$/.test(n.slice(0,t)))continue;let a=n.slice(0,t).trim();if(!a)continue;let o=i.lookup(e.lower);if(o.ambiguous.length>0)return r.length=0,l({reason:`ambiguous-equipment`,message:`"${e.lower}" matches multiple equipment entries.`,token:n,candidates:o.ambiguous.map(e=>e.slug)}),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};if(!o.entity)continue;let c=s(a);if(c.entity){r.length=0,u=`split`,d=c.entity;let e=n.slice(t);p=[{...em(o.entity),...e.toLowerCase()===o.entity.label.toLowerCase()?{}:{matchedAlias:e}}],m=!0,f=a,h={start:t,end:n.length};break}if(c.diagnostic?.reason===`ambiguous-effort`)return r.length=0,l(c.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r}}g();let y=u===`split`?f:n;return{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label,...y&&y.toLowerCase()!==d.label.toLowerCase()?{matchedAlias:y}:{}}:null,equipment:p,remaining:f,...h?{equipmentSpan:h}:{},diagnostics:r}}}}function rm(e){let t=[],n=[],r=new Set,i=new Set,a=(e,t,n)=>{n&&(t.has(n)||(t.add(n),e.push(n)))};for(let o of e??[]){let e=Array.isArray(o.metrics)?o.metrics:o.metrics?.toArray?.()??[];for(let o of e){let e=Ne(o.metadata)?.refs;if(e)for(let o of e)o.kind===`effort`&&a(t,r,o.slug),o.kind===`equipment`&&a(n,i,o.slug)}}return{efforts:t,equipment:n}}let im={now:()=>new Date,nowMs:()=>Date.now()};var am=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}},om=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)}},sm=class{options;now;type=`next`;constructor(e,t=im){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:om.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 cm=e=>String(e).padStart(2,`0`),lm=e=>String(e).padStart(3,`0`);function um(e){return`${cm(e.getHours())}:${cm(e.getMinutes())}:${cm(e.getSeconds())}.${lm(e.getMilliseconds())}`}function dm(e){return(e+` `).slice(0,5)}function fm(e){return(e+` `.repeat(24)).slice(0,24)}function pm(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 mm=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)}] ${hm(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${pm(e)}`,`color: #94a3b8`)}writeLine(e,t,n){let r=um(new Date);this._console.log(`${r} %c${dm(e)}%c ${fm(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 hm(e){try{return JSON.stringify(e)??``}catch{return String(e)}}let gm=new mm;typeof window<`u`&&(window.RuntimeLogger=gm);var _m=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}`)}};function vm(e,t){let n=0;for(let r of e.spans){let e=r.ended??t;n+=e-r.started}return n}function ym(e){let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}var bm=class{value;sourceBlockKey;timestamp;type=E.Elapsed;origin=`analyzed`;unit=`ms`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return ym(this.value)}},xm=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`),gm.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`&&gm.logPop(a,a.completionReason,e.stack.blocks.length+1),e.stack.current?[...i,new sm(r,e.nowProvider)]:i):[]}},Sm=class{_memory;ownerId;type;visibility;_logger;id=Lp();_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=Lp(),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)}}},Cm=class{_references=[];allocate(e,t,n,r=`private`){let i=new Sm(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 Sm&&r.hasSubscribers()&&r.notifySubscribers(void 0,n),this._references.splice(t,1)}}};let wm=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 Tm=class{timestamp;constructor(e=im){this.timestamp=e.now()}},Em=class extends Tm{name=`memory:allocate`;data;constructor(e,t,n=im){super(n),this.data={ref:e,value:t}}},Dm=class extends Tm{name=`memory:set`;data;constructor(e,t,n,r=im){super(r),this.data={ref:e,value:t,oldValue:n}}},Om=class extends Tm{name=`memory:release`;data;constructor(e,t,n=im){super(n),this.data={ref:e,lastValue:t}}},km=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 Cm}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 Em(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 Dm(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 Om(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===wm.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(wm.ANCHOR,this.ownerId,void 0,`public`);return n.id=e,this._references.push(n),n}};let Am=`time`;function jm(e){return[new am(e)]}function Mm(e,t){return e.map((n,r)=>r===e.length-1&&n.ended===void 0?new am(n.started,t):n)}function Nm(e,t){return[...e,new am(t)]}function Pm(e){return e.getMemoryByTag(Am)[0]?.metrics[0]?.value}function Fm(e,t){let n=e.getMemoryByTag(Am)[0]?.metrics[0],r=n?.value;if(!r||!n)return!1;let i=t(r.spans,e.clock.currentDate.getTime());return e.updateMemory(Am,[{...n,value:{...r,spans:i}}]),!0}var Im=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 xm().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 sm(void 0,e.nowProvider)),t}},Lm=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:jm(t),direction:`down`,durationMs:this.config.durationMs,label:n,role:r,required:!!this.config.required,polarity:this.config.polarity??`work`})]),this.config.durationMs<=0?(this.handleExpiry(e,i),[new Im(e.block.key.toString())]):(this.subscriptions.push(e.subscribe(`tick`,(e,t)=>i===`complete-block`&&t.block.isComplete||!this.hasExpired(t)?[]:(this.handleExpiry(t,i),[new Im(t.block.key.toString())]),{scope:`bubble`})),this.subscriptions.push(e.subscribe(`timer:reset`,(e,t)=>(i===`reset-interval`&&Fm(t,(e,t)=>jm(t)),[]))),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||Fm(t,Mm)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&Fm(t,Nm)&&(this.isPaused=!1),[]))),[])}onNext(e){if((this.config.mode??`complete-block`)===`complete-block`&&!e.block.isComplete&&this.hasExpired(e))return e.markComplete(`timer-expired`),[new xm,new Im(e.block.key.toString())];if(this.config.required&&!e.block.isComplete)return e.emitEvent({name:`timer:skip-attempt`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),[];if(e.hasCapability(`childSelection`)||!this.config.restBlockFactory)return[];let t=Pm(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 Fm(e,Mm),[]}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(Fm(e,(e,t)=>jm(t)),e.hasCapability(`childSelection`))return;let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t){let n=new _m(t.current+1,t.total,e.block.key.toString(),e.clock.currentDate);e.updateMemory(`round`,[n])}let n=e.getMemoryByTag(`children:status`)[0],r={childIndex:0,totalChildren:n?.metrics[0]?.value?.totalChildren??0,allExecuted:!1,allCompleted:!1};n?.metrics[0]?e.updateMemory(`children:status`,[{...n.metrics[0],value:r}]):e.pushMemory(`children:status`,[{type:`status`,image:``,origin:`runtime`,value:r}])}}hasExpired(e){let t=Pm(e);return!t||t.direction!==`down`||t.durationMs===void 0?!1:vm(t,e.nowProvider.nowMs())>=t.durationMs}getRemainingCountdownMs(e){let t=Pm(e);if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=vm(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}createFragment(e,t){return{type:E.Time,image:Rm(t.durationMs),origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}};function Rm(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 zm=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])}},Bm=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 xm]));this.unsubscribers.push(n)}return[]}onNext(e){return this.config.mode===`deferred`?e.block.isComplete?[new xm]:[]:this.config.onNext?(e.block.isComplete||e.markComplete(`user-advance`),[new xm]):[]}onUnmount(e){return[]}onDispose(e){for(let e of this.unsubscribers)e();this.unsubscribers=[]}},Vm=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`}};kp.defaultMet;var Hm=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 ym(this.value)}},Um=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`)}`}},Wm=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()}},Gm=class{config;_now;lastEmittedRound;constructor(e={},t=im){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=Pm(e),n=e.getMemoryByTag(`round`)[0]?.metrics[0],r=this.config.computeTimeResults??!0,i=e.block.completionReason,a=i===`user-abort`||i===`forced-pop`||i===`timer-expired`,o=n?a?{current:Math.max(0,n.current-1),total:n.total}:n:void 0,s=this.config.label??`Completed`;if(this.config.label||(e.block.blockType===`SessionRoot`?s=`Session Completed`:o&&!a&&o.total!==void 0&&o.total>1?s=`Completed ${o.total} Round(s)`:o&&o.current>0?s=`Completed ${o.current} Round(s)`:a&&n&&(s=`Completed 0 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),s,o,a);return this.writeResultGroups(e,r),[]}}let c=r?this.computeTimeResults(e,t,s,o,a):D.from([new Wm(this._now.now(),e.block.key.toString())],e.block.key.toString());return this.writeResultMemory(e,c),[]}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 _m(t.current,t.total,e.block.key.toString(),e.clock.currentDate)),r=Pm(e);if(r){let t=vm(r,e.clock.currentDate.getTime());n.add(new bm(t,e.block.key.toString(),e.clock.currentDate)),r.spans.length>0&&n.add(new Um([...r.spans],e.block.key.toString(),e.clock.currentDate))}return n}resolveFallbackTiming(e,t){if(e.block.blockType===`WaitingToStart`)return null;let n=e.block.executionTiming?.startTime?.getTime();return n===void 0||!Number.isFinite(n)||n>t?null:{started:n,ended:t,elapsedMs:Math.max(0,t-n)}}computeTimeResults(e,t,n,r,i=!1){let a=e.clock.currentDate,o=a.getTime(),s=e.block.key.toString(),c=r!==void 0&&(r.current>0||i);if(t&&t.spans.length>0){let e=vm(t,o),i=t.spans.map(e=>e.ended===void 0?new am(e.started,o):e),l=i[0].started,u=i[i.length-1].ended??o,d=Math.max(0,u-l),f=D.empty(s).add(new bm(e,s,a),new Hm(d,s,a),new Um(i,s,a),new Wm(this._now.now(),s));return c&&f.add(new _m(r.current,r.total,s,a,n)),f}let l=this.resolveFallbackTiming(e,o),u=l?new am(l.started,l.ended):new am(o,o),d=l?.elapsedMs??0,f=D.empty(s).add(new bm(d,s,a),new Hm(d,s,a),new Um([u],s,a),new Wm(this._now.now(),s));return c&&f.add(new _m(r.current,r.total,s,a,n)),f}buildWeightedSplitGroups(e,t,n,r,i,a,o,s,c=!1){let l=o.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}),u=l.reduce((e,t)=>e+t,0),d=a!==void 0&&(a.current>0||c),f=0;return o.map((o,c)=>{let p=l[c]/u,m=Math.round(t*p),h=Math.round(n*p),g=e+f,_=g+h;f+=h;let v=o.clone().add(new bm(m,i,r),new Hm(h,i,r),new Um([new am(g,_)],i,r),new Wm(this._now.now(),i));return d&&v.add(new _m(a.current,a.total,i,r,s)),v})}computeSplitTimeResults(e,t,n,r,i,a=!1){let o=e.clock.currentDate,s=o.getTime(),c=e.block.key.toString(),l=i!==void 0&&(i.current>0||a);if(!t||t.spans.length===0){let t=this.resolveFallbackTiming(e,s);return t?this.buildWeightedSplitGroups(t.started,t.elapsedMs,t.elapsedMs,o,c,i,n,r,a):n.map(e=>{let t=e.clone().add(new bm(0,c,o),new Hm(0,c,o),new Um([new am(s,s)],c,o),new Wm(this._now.now(),c));return l&&t.add(new _m(i.current,i.total,c,o,r)),t})}let u=vm(t,s),d=t.spans[0].started,f=(t.spans[t.spans.length-1].ended??s)-d;return this.buildWeightedSplitGroups(d,u,f,o,c,i,n,r,a)}writeResultMemory(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length>0){let r=Km(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?Km([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 Km(e){let t=[];for(let n of e)for(let e of n.metrics)e.origin===`user`&&t.push(e);return t}var qm=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 Jm(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 Ym={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 Xm=class{config;rules=[];fired=new Set;durationMs;constructor(e){this.config=e}onMount(e){let t=Pm(e);return this.durationMs=t?.durationMs,this.rules=Jm(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=Pm(e);if(t)return vm(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 qm(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 Zm=E.Sound;function Qm(e,t){let n=$m(e);if(n){let e=eh(t?.profiles,n);if(e)return e}if(t?.noteProfileId){let e=eh(t?.profiles,t.noteProfileId);if(e)return e}return Ym}function $m(e){for(let t of e){let e=t.metrics.find(e=>e.type===Zm);if(!e)continue;let n=e.value;if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function eh(e,t){if(e)return e.find(e=>e.id===t)}let th=(e,t,n)=>({id:e,kind:`expr`,expression:t,unit:n});nh(),nh(),nh(),rh(),rh();function nh(){return{sRPE:th(`sRPE`,`rpeSource.rpe`),durationMinutes:th(`durationMinutes`,`convert(session.duration, min)`),load:th(`load`,`round(rpeSource.rpe * convert(session.duration, min))`)}}function rh(){return{elapsedMin:th(`elapsedMin`,`convert(sum(elapsed), min)`),avgMets:th(`avgMets`,`sum(metMinutes) / elapsedMin`),metMax:th(`metMax`,`sharedMet.metMax`),metScore:th(`metScore`,`min(100, avgMets / metMax * 100)`),rpeScore:th(`rpeScore`,`rpeSource.rpe * 10`),durationScore:th(`durationScore`,`elapsedMin / 60 * metScore`,`pts`),disciplineFactor:th(`disciplineFactor`,`lookup("effort", effort, "disciplineFactor")`),tis:th(`tis`,`round(0.30 * metScore + 0.35 * rpeScore + 0.20 * durationScore + 0.15 * disciplineFactor, 1)`)}}new ad([]),new ad([]);var ih=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&&!Rd.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=>dd(e,od.LABEL_AMRAP)))return`AMRAP`;if(e.some(e=>dd(e,od.LABEL_EMOM)))return`EMOM`;if(e.some(e=>dd(e,od.LABEL_TABATA)))return`TABATA`;if(e.some(e=>dd(e,od.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||e.type===E.Equipment)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()}},ah=class{distribute(e,t){return[e.clone()]}};let oh=e=>e[0];function sh(e,t){let{statements:n,runtime:r,blockType:i,defaultLabel:a}=t,o=(t.pickStatement??oh)(n),s=t.key??new Le,c=t.context??new km(r,s.toString(),o.exerciseId||``),l=ih.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 ah,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,polarity:n.polarity,...t.countdownTimerConfig??{}})}if(t.repeater){let n=t.repeater;e.asRepeater({totalRounds:n.totalRounds,startRound:n.startRound??1,addCompletion:n.addCompletion})}return l}var ch=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=sh(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 Vm({mode:`countdown`,label:i})),e.declareExit(`immediate`)}},lh=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=>dd(e,od.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=>dd(e,od.LABEL_AMRAP)||e.metrics.some(e=>e.type===E.Rounds&&typeof e.value==`string`&&e.value.toLowerCase()===`amrap`)),o=e.some(e=>dd(e,od.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=sh(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 Vm({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 zm({promotions:u}))}},uh=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){sh(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 Bm({mode:`immediate`,onNext:!0}))}},dh=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=sh(e,{blockType:`Group`,defaultLabel:`Group`,statements:t,runtime:n});e.addBehavior(new Vm({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 zm({promotions:o}))}},fh=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=sh(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 Vm({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 zm({repScheme:a,promotions:u})),e.declareExit(`immediate`)}},ph=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=>dd(e,od.REQUIRED_TIMER)),s=t.some(e=>dd(e,od.INJECT_REST)),c=!!(a&&i===`down`),l=t.flatMap(e=>[...e.metrics]),u=l.some(e=>(e.type===E.Effort||e.type===E.Action)&&typeof e.value==`string`&&e.value.trim().toLowerCase()===`rest`),d=l.some(e=>e.type===E.Effort&&typeof e.value==`string`&&e.value.trim().toLowerCase()!==`rest`),f=sh(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,polarity:u&&!d?`rest`:`work`},pickStatement:e=>e.find(e=>e.metrics.some(e=>e.type===E.Duration&&e.origin!==`runtime`))||e[0]});o&&c?e.addBehavior(new Bm({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})):e.addBehavior(new Bm({mode:`immediate`,onNext:!0})),e.addBehavior(new Vm({mode:a?`countdown`:`clock`,label:f}))}},mh=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(Lm),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`)}},hh=class{priority=15;id=`report-output`;match(e,t){return e&&e.length>0}apply(e,t,n){e.hasBehavior(Gm)||e.addBehavior(new Gm)}},gh=class{priority=20;id=`sound`;match(e,t){return e.length>0}apply(e,t,n){if(e.hasBehavior(Xm)||!e.hasTimerBehavior())return;let r=Qm(t,n.options?.soundOptions);e.addBehavior(new Xm({profile:r}))}};new ad([new ch,new lh,new ph,new fh,new dh,new gh,new hh,new mh,new uh]).list(),E.Elapsed,E.Total,E.Spans,E.SystemTime,E.CurrentRound,E.System;function _h(e){let t=e.trim();if(t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)){try{if(t.startsWith(`"`))return JSON.parse(t)}catch{}return t.slice(1,-1)}return t}function vh(e){if(!e)return;let t=_h(e),n=t.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(n){let e=Date.parse(`${t}T12:00:00Z`),r=new Date(e);return Number.isFinite(e)&&r.getUTCMonth()===Number(n[2])-1&&r.getUTCDate()===Number(n[3])?e:void 0}let r=Date.parse(t);return Number.isFinite(r)?r:void 0}let yh=/^---\r?\n([\s\S]*?)\r?\n---/;function bh(e){let t=yh.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 xh=e=>Array.isArray(e)?e:typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];function Sh(e,t=gt){let n=bh(e),r=xh(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 xh(n[t]))r.push({label:i,type:e})}return r.filter(e=>e.label.length>0)}let Ch=[`sessionId`,`noteId`,`blockId`,`blockVersion`,`blockContentId`,`origin`,`status`,`startTime`,`endTime`,`duration`,`completed`,`sessionCreatedAt`,`sessionExtraJson`],wh=`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(`.`),Th=[...Ch,...wh],Eh=[`revisionKind`,`revisionRawContent`,`revisionSavedAt`,`revisionDialect`,`revisionSport`,`parseId`,`parseStage`,`parseStatus`,`parseDiagnosticsJson`,`parseMetricsJson`];[...Th,...Eh];let Dh=Be,Oh={core:0,community:1,imported:2,user:3};function kh(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 Ah(e,t){return Oh[kh(e,t)]}let jh=`feed:index:`;function Mh(e,t){return`${jh}${e}:${t}`}let Nh=`canvas`;function Ph(e){return`seed:${e}`}function Fh(e){return e.startsWith(`seed:`)?e.slice(5):e}function Ih(e){return{key:e,schema:9,seedVersion:0,builtAt:``,importedAt:0,chunks:{},claim:null}}function Lh(e){let t=/^notebook\.(.+)$/.exec(e)?.[1];return t&&t!==`_root`?t:void 0}function Rh(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 zh(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:${Rh(t)??a}`;if(n===`dashboards`)return`dashboards`;if(n===`efforts`)return`efforts`;if(n===`equipment`)return`equipment`;if(n.startsWith(`notebook.`)){let e=Lh(n);return e?i.toLowerCase()===`readme`?`notebook:${e}`:`notebook:${a}`:`notebook:_root`}}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bh(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function $(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Vh(e){return typeof e==`number`&&Number.isFinite(e)}function Hh(e){return typeof e==`string`&&e.length>0&&!e.startsWith(`/`)&&!e.split(`/`).includes(`..`)}function Uh(e){if(typeof e!=`string`||!e.trim())return!1;if(/^https?:\/\//i.test(e))try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password}catch{return!1}return Hh(e)}function Wh(e){if(!Q(e))throw Error(`Incompatible seed schema; rebuild seed artifacts`);let t=Array.isArray(e.notebooks);if(e.schema===void 0){if(!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`)}else if(!Bh(e.schema)||e.schema!==9&&!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`);let n=e.schema===void 0?9:e.schema,r=e.version===void 0&&t?1:e.version,i=e.builtAt===void 0&&t?new Date(0).toISOString():e.builtAt,a=e.chunks===void 0&&t?[]:e.chunks;if(!$(r)||typeof i!=`string`||!Number.isFinite(Date.parse(i))||!Array.isArray(a))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`);for(let t of[`indexBytes`,`chunkBytes`])if(e[t]!==void 0&&!$(e[t]))throw Error(`invalid seed manifest metadata`);let o=new Set,s=new Set;for(let e of a){if(!Q(e)||typeof e.id!=`string`||!e.id||typeof e.path!=`string`||!/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(e.path)||typeof e.sha256!=`string`||!/^[0-9a-f]{64}$/.test(e.sha256)||!$(e.bytes)||!$(e.count)||e.kind!==void 0&&e.kind!==`notes`||o.has(e.id)||s.has(e.path))throw Error(`seed manifest failed shape validation`);o.add(e.id),s.add(e.path)}let c;if(e.notebooks!==void 0){if(!Array.isArray(e.notebooks))throw Error(`seed manifest failed shape validation`);c=[];for(let t of e.notebooks){if(!Q(t)||typeof t.notebookId!=`string`||!t.notebookId||typeof t.label!=`string`||!$(t.count)||!Uh(t.indexPath))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`);if(t.version!==void 0&&!$(t.version)||t.commit!==void 0&&typeof t.commit!=`string`||t.builtAt!==void 0&&typeof t.builtAt!=`string`||t.sha256!==void 0&&typeof t.sha256!=`string`||t.bytes!==void 0&&!$(t.bytes)||t.indexBytes!==void 0&&!$(t.indexBytes)||t.chunkBytes!==void 0&&!$(t.chunkBytes))throw Error(`seed manifest failed shape validation`);c.push({...t,version:t.version??r,commit:t.commit??``,builtAt:t.builtAt??i,sha256:t.sha256??``,bytes:t.bytes??t.indexBytes??0})}}return{...e,schema:n,version:r,builtAt:i,chunks:a,...c===void 0?{}:{notebooks:c}}}function Gh(e){if(!Q(e))throw Error(`notebook index failed shape validation`);if(typeof e.notebookId!=`string`||!e.notebookId||typeof e.label!=`string`||!e.label||!Uh(e.indexPath)||!$(e.count)||!Array.isArray(e.records)||e.version!==void 0&&!$(e.version)||e.commit!==void 0&&typeof e.commit!=`string`||e.builtAt!==void 0&&typeof e.builtAt!=`string`||e.sha256!==void 0&&typeof e.sha256!=`string`||e.bytes!==void 0&&!$(e.bytes))throw Error(`notebook index failed shape validation: missing required index summary or records`);let t=[];for(let n of e.records){if(!Q(n)||typeof n.uuid!=`string`||!n.uuid||!Hh(n.path))throw Error(`notebook index failed shape validation: invalid record ref`);let e=n.recordPath!==void 0,r=n.rawUrl!==void 0,i=/\.md$/i.test(n.path);if(e&&!Hh(n.recordPath)||r&&!Uh(n.rawUrl)||!e&&!r&&!i||n.commit!==void 0&&typeof n.commit!=`string`||n.version!==void 0&&!$(n.version)||n.sha256!==void 0&&typeof n.sha256!=`string`||n.title!==void 0&&typeof n.title!=`string`||n.date!==void 0&&!Vh(n.date))throw Error(`notebook index failed shape validation: invalid record ref`);t.push({...n,commit:n.commit??``,version:n.version??1,sha256:n.sha256??``})}return{...e,version:e.version??1,commit:e.commit??``,builtAt:e.builtAt??new Date(0).toISOString(),sha256:e.sha256??``,bytes:e.bytes??0,records:t}}function Kh(e,t){if(e.telemetry===void 0)return;if(!Q(e.telemetry)||!Array.isArray(e.telemetry.sessions)||!Array.isArray(e.telemetry.events))throw Error(`invalid seed telemetry`);let n=new Map;for(let r of e.telemetry.sessions){if(!Q(r)||typeof r.id!=`string`||!r.id||n.has(r.id)||typeof r.noteId!=`string`||!r.noteId||typeof e.uuid==`string`&&r.noteId!==e.uuid||typeof r.blockId!=`string`||!Bh(r.blockVersion)||typeof r.blockContentId!=`string`||!Vh(r.startTime)||!Vh(r.endTime)||!Vh(r.duration)||typeof r.completed!=`boolean`||!Vh(r.createdAt))throw Error(`invalid seed session`);let i=t.find(e=>Q(e)&&e.blockId===r.blockId);if(!Q(i)||i.dataType!==`wod`||i.blockVersion!==r.blockVersion||i.blockContentId!==r.blockContentId)throw Error(`orphan or incompatible seed session pin`);n.set(r.id,r)}let r=new Set;for(let t of e.telemetry.events){if(!Q(t)||typeof t.id!=`string`||!t.id||r.has(t.id)||typeof t.resultId!=`string`||typeof t.noteId!=`string`||!Vh(t.timestamp)||t.grain!==`event`&&t.grain!==`summary`||typeof t.outputType!=`string`||!Array.isArray(t.metrics)||!t.metrics.every(e=>Q(e)&&typeof e.type==`string`)||t.grain===`summary`&&t.metrics.length!==1)throw Error(`invalid seed event`);let e=n.get(t.resultId);if(!e||t.noteId!==e.noteId||t.blockId!==e.blockId||t.blockVersion!==e.blockVersion||t.blockContentId!==e.blockContentId)throw Error(`orphan or incompatible seed event identity`);r.add(t.id)}}function qh(e){if(!Array.isArray(e))throw Error(`seed chunk is not an array`);let t=new Set;for(let n of e){if(!Q(n)||typeof n.path!=`string`||!n.path||n.path.startsWith(`/`)||n.path.split(`/`).includes(`..`)||t.has(n.path)||typeof n.content!=`string`||!Q(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(!Q(t)||t.id!==e||!e||t.version!==1||t.sourceRevision!==1||!$(t.from)||!Bh(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`);Ye(n.content,n.blocks,1,{registeredWidgets:Dh});let e=new Set,r=Ke(n.content,{registeredWidgets:Dh});for(let t of n.blockIndex){if(!Q(t)||typeof t.blockId!=`string`)throw Error(`invalid seed projection`);let i=n.blocks[t.blockId];if(!Q(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&&!$(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!==Re(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(!Q(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))||!Q(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=>Q(e)&&e.blockId===t.blockId);if(!Q(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(!Q(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))||!Q(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=>Q(e)&&e.blockId===t.blockId);if(!Q(i)||t.noteId!==i.noteId||t.blockContentId!==i.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed equipment metadata`);a.add(String(t.id))}Kh(n,n.blockIndex)}return e}function Jh(e){return qh([e])[0]}function Yh(e,t,n){return`${e}:${t}:${n}`}async function Xh(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 Zh(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&&Zh(Reflect.get(e,n),Reflect.get(t,n)))}function Qh(e){return(e.split(`/`).at(-1)??e).replace(/\.md$/,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}function $h(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=Xe(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 Je(t,{sourceRevision:n,blocks:c,registeredWidgets:Dh,createId:()=>`seed:${e.id}:r${n}:${l++}`})}async function eg(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:Ah(n.sourceId)}return a>=r&&!Zh(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 tg(e,t,n){if(!t.length)return;let r=await e.getMany(n),i=t.filter((e,t)=>!Zh(e,r[t]));i.length&&await e.putMany(i)}let ng=[`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`tags`,`note_tags`,`efforts`,`equipment`,`property_overrides`,`meta`,`sessions`,`events`];async function rg(e){Wh(e.manifest),qh(e.rows);let t=await Promise.all(e.rows.map(e=>Xh(e.path))),n=new Map,r=new Map,i=new Map;for(let[a,o]of e.rows.entries()){let e=bh(o.content).slug;typeof e==`string`&&e.trim()&&(n.set(e,await Xh(`page:${e}`)),r.set(t[a],await Xh(`pagenote:${e}:${o.path}`)));for(let{label:e}of Sh(o.content))i.has(e)||i.set(e,await Xh(`tag:${e}`))}return{write:e,ids:t,pagesBySlug:n,linkIds:r,tagIds:i}}async function ig(e,t){let n={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0};if(!t.length)return n;let r=await Promise.all(t.map(rg)),i={...n};for(let t=0;t<r.length;t++){let n=r[t],a=await e.transaction(ng,`readwrite`,e=>og(e,n));i.totalNotes+=a.totalNotes,i.totalEfforts+=a.totalEfforts,i.totalEquipment+=a.totalEquipment,i.totalBlocks+=a.totalBlocks,i.skippedUserOwned+=a.skippedUserOwned,i.deleted+=a.deleted,i.preservedPinned=(i.preservedPinned??0)+(a.preservedPinned??0),i.addedNotes+=a.addedNotes,i.updatedNotes+=a.updatedNotes,t+1<r.length&&await new Promise(e=>setTimeout(e,0))}return i}async function ag(e,t){return ig(e,[t])}async function og(e,t){let{write:n,ids:r,pagesBySlug:i,linkIds:a,tagIds:o}=t,s={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0},c=e.readwrite(`meta`),l=new Set;for(let e of await c.getAll()){let t=lt(e?.key);t!==void 0&&l.add(t)}if(!Zh(await c.get(n.meta.key),n.expectedMeta))throw Error(`Seed checkpoint changed during import`);if(n.meta.schema!==9||n.manifest.schema!==9&&!Array.isArray(n.manifest.notebooks))throw Error(`Incompatible seed schema; recreate artifacts`);let u=e.readwrite(`notes`),d=n.chunkId?n.expectedMeta?.chunks[n.chunkId]?.noteIds??[]:[],f=new Set((n.chunkId?n.meta.chunks[n.chunkId]?.noteIds:void 0)??r),p=d.filter(e=>!f.has(e)),m=[...new Set([...r,...p])],h=await u.getMany(m),g=new Map(m.map((e,t)=>[e,h[t]])),_=n.meta.key.startsWith(`seed:`)?n.meta.key.slice(5):n.meta.key,v=Fh(n.meta.key),y=Ah(n.meta.key,n.meta.tier),b=[];for(let e of await c.getAll()){let t=e;if(!t||typeof t.key!=`string`||!t.key.startsWith(`seed:`)||t.key===n.meta.key)continue;let r=new Set;for(let e of Object.values(t.chunks??{}))for(let t of e.noteIds??[])r.add(t);b.push({key:t.key,sourceId:t.key.slice(5),rank:Ah(t.key,t.tier),meta:t,noteIds:r})}b.sort((e,t)=>t.rank-e.rank);let x=e=>{let t=-1;for(let n of b)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},S=m.filter(e=>{if(l.has(e))return!1;let t=g.get(e);if(!t)return f.has(e);if(t.seedOrigin!==`seed`)return!1;let r=x(e);return f.has(e)?y>=r:r<0&&t.seedChunkId===n.chunkId}),C=new Set(S),w=e.readwrite(`block_revisions`),ee=r.filter((e,t)=>C.has(e)&&g.get(e)?.rawContent!==n.rows[t].content),te=await w.getAllFromIndexMany(`by-note`,ee),ne=new Map(ee.map((e,t)=>[e,te[t]])),T=e.readwrite(`block_index`),re=e.readwrite(`block_efforts`),ie=e.readwrite(`block_equipment`),ae=e.readwrite(`note_tags`),oe=e.readwrite(`page_notes`),se=await T.getAllFromIndexMany(`by-note`,S),ce=await re.getAllFromIndexMany(`by-note`,S),le=await ie.getAllFromIndexMany(`by-note`,S),ue=await ae.getAllFromIndexMany(`by-note`,S),E=await oe.getAllFromIndexMany(`by-note`,S),de=new Map(S.map((e,t)=>[e,t])),fe=e.readwrite(`tags`),pe=[...o.keys()],me=await fe.getAllFromIndexMany(`by-label`,pe),he=new Map(pe.map((e,t)=>[e,me[t][0]])),ge=[],_e=[],ve=[],ye=[],be=[],xe=[],Se=[],Ce=[],we=[],Te=e.readwrite(`sessions`),Ee=e.readwrite(`events`),De=new Set;if(S.length>0){let e;try{e=await Te.getAllFromIndexMany(`by-note`,S)}catch{let t=await Te.getAll();e=S.map(e=>t.filter(t=>t.noteId===e))}for(let t=0;t<S.length;t++){let n=S[t];(g.get(n)?.retention===`session-pinned`||(e[t]?.length??0)>0)&&De.add(n)}}let Oe=n.rows.flatMap(e=>e.telemetry?.sessions.map(e=>e.id)??[]),ke=await Te.getMany(Oe),Ae=new Map(Oe.map((e,t)=>[e,ke[t]])),je=[],Me=[];for(let[e,t]of n.rows.entries()){let c=r[e],l=g.get(c);if(!C.has(c)){l&&l.seedOrigin!==`seed`&&s.skippedUserOwned++;continue}l?l.rawContent!==t.content&&s.updatedNotes++:s.addedNotes++,Ye(t.content,t.blocks,1,{registeredWidgets:Dh});let u=l?l.sourceRevision+(l.rawContent===t.content?0:1):1,d=0,f=ne.get(c)??[],p=l?l.rawContent===t.content?structuredClone(l.blocks):$h(l,t.content,u):f.length?Je(t.content,{sourceRevision:u,registeredWidgets:Dh,createId:()=>`seed:${c}:new${f.length}:${d++}`}):structuredClone(t.blocks);for(let e of Object.values(p)){let r=(ne.get(c)??[]).filter(t=>t.blockId===e.id).sort((e,t)=>t.version-e.version)[0],i=t.content.slice(e.from,e.to);if(l?.rawContent===t.content)continue;let a=r&&r.kind===e.kind&&r.rawContent===i&&r.dialect===e.dialect&&r.sport===e.sport;e.version=l?a?r.version:(r?.version??0)+1:1,(!l||!a)&&ve.push({noteId:c,blockId:e.id,version:e.version,kind:e.kind,rawContent:i,savedAt:n.meta.importedAt,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}})}Ye(t.content,p,u,{registeredWidgets:Dh});let m=bh(t.content),h=typeof m.title==`string`&&m.title.trim()?m.title.trim():Qh(t.path),_=n.chunkId?zh(t.path,t.content,n.chunkId):void 0;if(!_)throw Error(`Unknown seed source family ${n.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 '${t.path}' — expected a real calendar day (YYYY-MM-DD)`);b=e}let x=t.commit??n.manifest.commit,S=l,w=De.has(c)||S?.retention===`session-pinned`?`session-pinned`:S?.retention===`schedule-pinned`?`schedule-pinned`:void 0,ee=typeof n.manifest.builtAt==`string`?Date.parse(n.manifest.builtAt):NaN,te=n.manifest.version===0?0:Number.isFinite(ee)&&ee>=9466848e5?ee:Number.isFinite(n.meta.importedAt)&&n.meta.importedAt>=9466848e5?n.meta.importedAt:Date.now(),T={...l,id:c,title:h,rawContent:t.content,sourceRevision:u,blocks:p,createdAt:te,...b===void 0?{}:{date:b},type:n.chunkId===`dashboards`?`dashboard`:`note`,sourceId:_,seedOrigin:`seed`,seedVersion:n.manifest.version,seedChunkId:n.chunkId??void 0,feedOrigin:`feed`,feedSourceId:v,sourcePath:t.path,...x?{seedCommit:x}:{},...w?{retention:w}:S?.retention?{retention:S.retention}:{},...w||S?.upstreamStatus?{upstreamStatus:`live`}:{}};b===void 0&&delete T.date,Zh(T,l)||_e.push(T);let re=new Map(Object.values(p).map(e=>[`${e.from}:${e.to}`,e])),ie=new Map(t.blockIndex.map(e=>[e.blockId,e])),oe=new Map;for(let e of t.blockIndex){let n=re.get(`${e.from}:${e.to}`);if(!n||n.kind!==e.dataType)throw Error(`Orphan seed projection`);oe.set(e.blockId,n.id);let r={...e,id:`${c}:${n.id}`,noteId:c,blockId:n.id,blockVersion:n.version,sourceRevision:u,noteTitle:h,sourceId:_,sourcePath:t.path,rawContent:t.content.slice(n.from,n.to)},i=se[de.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&Se.push(r)}let E=new Map,fe=new Set;for(let e of t.telemetry?.sessions??[]){if(ie.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed session pin`);let t=Ae.get(e.id);if(t&&t.noteId!==c)throw Error(`Seed session ${e.id} belongs to another note`);if(t&&(t.origin||!t.id.startsWith(`seed:`))){fe.add(e.id);continue}let n=t?.blockId??oe.get(e.blockId);if(!n)throw Error(`Orphan seed session pin`);let r=p[n];if(!t&&!r)throw Error(`Orphan seed session pin`);let i={...e,noteId:c,blockId:n,blockVersion:t?.blockVersion??r.version,blockContentId:t?.blockContentId??ie.get(e.blockId)?.blockContentId};je.push(i),E.set(i.id,i)}for(let e of t.telemetry?.events??[]){if(fe.has(e.resultId))continue;let t=E.get(e.resultId);if(!t)throw Error(`Orphan seed event result`);Me.push({...e,noteId:c,blockId:t.blockId,blockVersion:t.blockVersion,blockContentId:t.blockContentId})}for(let e of t.blockEfforts){let n=oe.get(e.blockId);if(!n||ie.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed effort link`);let r={...e,id:`${c}:${n}:${e.effortSlug}`,noteId:c,blockId:n,sourcePath:t.path},i=ce[de.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&Ce.push(i?{...r,createdAt:i.createdAt}:r)}for(let e of t.blockEquipment){let n=oe.get(e.blockId);if(!n||ie.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed equipment link`);let r={...e,id:`${c}:${n}:${e.equipmentSlug}`,noteId:c,blockId:n,sourcePath:t.path},i=le[de.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&we.push(i?{...r,createdAt:i.createdAt}:r)}let pe=de.get(c),me=new Set;for(let e of Sh(t.content)){let t=he.get(e.label);t?e.type&&!t.type&&(t={...t,type:e.type},ge.push(t),he.set(e.label,t)):(t={id:o.get(e.label),label:e.label,type:e.type,createdAt:n.meta.importedAt},ge.push(t),he.set(e.label,t)),!me.has(t.id)&&(me.add(t.id),ue[pe].find(e=>e.tagId===t.id)||xe.push({id:`${c}:${t.id}`,noteId:c,tagId:t.id}))}for(let e of ue[pe])me.has(e.tagId)||await ae.delete(e.id);let Te=m.slug;if(typeof Te==`string`&&i.has(Te)){let e=i.get(Te);ye.push({id:e,slug:Te,title:Qh(t.path),createdAt:te}),be.push({id:a.get(c),pageId:e,noteId:c,createdAt:te})}s.totalNotes++,s.totalBlocks+=Object.keys(p).length}let Ne=new Set(p.filter(e=>C.has(e)&&(De.has(e)||g.get(e)?.retention===`schedule-pinned`))),Pe=new Set(Se.map(e=>e.id)),D=new Set(Ce.map(e=>e.id)),Fe=new Set(we.map(e=>e.id));for(let e of se)for(let t of e)t.isStatic===!0&&!Pe.has(t.id)&&!Ne.has(t.noteId)&&await T.delete(t.id);for(let e of ce)for(let t of e)t.isStatic===!0&&!D.has(t.id)&&!Ne.has(t.noteId)&&await re.delete(t.id);for(let e of le)for(let t of e)t.isStatic===!0&&!Fe.has(t.id)&&!Ne.has(t.noteId)&&await ie.delete(t.id);for(let e of p){if(!C.has(e))continue;let t=g.get(e);if(!t||t.seedOrigin!==`seed`)continue;let n=De.has(e)||t.retention===`session-pinned`?`session-pinned`:t.retention===`schedule-pinned`?`schedule-pinned`:void 0;if(n){let e={...t,retention:n,upstreamStatus:`removed`};Zh(e,t)||_e.push(e),s.preservedPinned=(s.preservedPinned??0)+1;continue}let r=de.get(e);await u.delete(e);for(let e of ue[r])await ae.delete(e.id);for(let e of E[r])await oe.delete(e.id);s.deleted++}let Ie=async(t,i)=>{let a;try{a=e.readwrite(`property_overrides`)}catch{return}let o=v===`core`?[`notebook/defaults`]:[`feed:${v}`,...n.manifest.chunks.filter(e=>e.id.startsWith(`notebook.`)).map(e=>`notebook/${Lh(e.id)}`)],s=await a.getAll(),c=new Map(s.map(e=>[e.id,e])),l=new Set,u=[];for(let[e,a]of n.rows.entries()){let s=i(a.content);if(s)for(let i of o){let o=Yh(i,t,s.slug);l.add(o);let d=c.get(o);if(d&&d.seedOrigin!==`seed`)continue;let f={id:o,notebookId:i,kind:t,slug:s.slug,label:s.label,ownerNoteId:r[e],rawContent:a.content,payload:s,seedOrigin:`seed`,feedSourceId:v,updatedAt:n.meta.importedAt};(!d||!Zh(d,f))&&u.push(f)}}u.length>0&&await a.putMany(u);for(let e of s)e.seedOrigin===`seed`&&e.feedSourceId===v&&e.kind===t&&!l.has(e.id)&&(!e.ownerNoteId||!f.has(e.ownerNoteId))&&await a.delete(e.id)};return n.chunkId===`efforts`&&(s.totalEfforts=await eg(e.readwrite(`efforts`),u,Yp,`efforts`,_,y,b,d,n.rows,r,C,g,m),await Ie(`effort`,Yp)),n.chunkId===`equipment`&&(s.totalEquipment=await eg(e.readwrite(`equipment`),u,Xp,`equipment`,_,y,b,d,n.rows,r,C,g,m),await Ie(`equipment`,Xp)),_e.length&&await u.putMany(_e),ve.length&&await w.putMany(ve),await tg(T,Se,Se.map(e=>e.id)),await tg(re,Ce,Ce.map(e=>e.id)),await tg(ie,we,we.map(e=>e.id)),await tg(Te,je,je.map(e=>e.id)),await tg(Ee,Me,Me.map(e=>e.id)),ge.length&&await fe.putMany([...new Map(ge.map(e=>[e.id,e])).values()]),xe.length&&await ae.putMany(xe),await tg(e.readwrite(`page`),ye,ye.map(e=>e.id)),await tg(oe,be,be.map(e=>e.id)),await c.put(n.meta),s}function sg(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 cg(e){return 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=Ah(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=sg(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 lg(e){return 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=ku(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;Pu(n)&&(await r.put(Nu(n)),t++)}}return t})}new TextEncoder,new TextDecoder;let ug=null;function dg(){return ug||=nm({efforts:[...Qp],equipment:[]}),ug}function fg(e,t){let n=bh(t);return(typeof n.title==`string`?n.title.trim().replace(/^["']|["']$/g,``):``)||t.match(/^#\s+(.+)$/m)?.[1]?.trim()||(e.split(`/`).at(-1)??e).replace(/\.md$/i,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}async function pg(e){let t=e.path.replace(/^\/+/,``);if(!t||t.split(`/`).includes(`..`))throw Error(`Invalid seed markdown path: '${e.path}'`);let n=e.markdown,r=e.uuid||await Xh(t),i=bh(n),a=e.title?.trim()||fg(t,n),o=vh(typeof i.date==`string`?i.date:void 0),s=e.date??o??e.createdAt??0,c=0,l=Je(n,{sourceRevision:1,registeredWidgets:Dh,createId:()=>`seed:${t}:${c++}`}),u=Ke(n,{registeredWidgets:Dh}),d=Object.values(l).map((i,o)=>{let c=u.find(e=>e.from===i.from&&e.to===i.to),l=i.kind===`wod`?Re(c?.scriptBlock?.content??n.slice(i.from,i.to)):void 0;return{id:`${r}:${i.id}`,noteId:r,blockId:i.id,blockVersion:1,sourceRevision:1,from:i.from,to:i.to,position:o,dataType:i.kind,...l?{blockContentId:l}:{},rawContent:n.slice(i.from,i.to),noteTitle:a,createdAt:s,isStatic:!0,...e.sourceId?{sourceId:e.sourceId}:{},sourcePath:t,...e.routeId?{routeId:e.routeId}:{}}}),f=e.referenceIndex??dg(),p=[],m=[];for(let e of d){if(e.dataType!==`wod`||!e.rawContent)continue;let n=rm(xp(Ke(e.rawContent,{registeredWidgets:Dh}).find(e=>e.scriptBlock)?.scriptBlock?.content??e.rawContent,{references:f}).statements),i=new Set;for(let a of n.efforts){let n=f.resolveEffort(a)?.slug;!n||i.has(n)||(i.add(n),p.push({id:`${e.id}:${n}`,noteId:r,blockId:e.blockId,...e.blockContentId?{blockContentId:e.blockContentId}:{},effortSlug:n,isStatic:!0,sourcePath:t,createdAt:s}))}let a=new Set;for(let i of n.equipment){let n=f.resolveEquipment(i)?.slug;!n||a.has(n)||(a.add(n),m.push({id:`${e.id}:${n}`,noteId:r,blockId:e.blockId,...e.blockContentId?{blockContentId:e.blockContentId}:{},equipmentSlug:n,isStatic:!0,sourcePath:t,createdAt:s}))}}return Jh({path:t,content:n,blocks:l,blockIndex:d,blockEfforts:p,blockEquipment:m,uuid:r,commit:e.commit??``,version:e.version??1})}new TextDecoder;async function mg(e,t){let n=e.readonly(`sessions`);try{return typeof n.countFromIndex==`function`?await n.countFromIndex(`by-note`,t)>0:(await n.getAllFromIndex(`by-note`,t)).length>0}catch{return(await n.getAll()).some(e=>e.noteId===t)}}async function hg(e,t){try{let n=e.readonly(`schedule_items`);return typeof n.countFromIndex==`function`?await n.countFromIndex(`by-note`,t)>0:(await n.getAllFromIndex(`by-note`,t)).length>0}catch{try{return(await e.readonly(`schedule_items`).getAll()).some(e=>e.noteId===t)}catch{return!1}}}async function gg(e,t){return e.transaction([`notes`,`attachments`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`schedule_items`,`efforts`,`equipment`,`property_overrides`,`sessions`,`meta`],`readwrite`,async e=>{let n=t.key.startsWith(`seed:`)?t.key.slice(5):t.key,r=Object.keys(t.chunks),i=r.length===0||Object.values(t.chunks).length>0,a=new Set,o=[];for(let[e,n]of Object.entries(t.chunks))if(n.noteIds?.length)for(let e of n.noteIds)a.add(e);else o.push(e);let s=o.length||i?await e.readwrite(`notes`).getAll():[];if(o.length)for(let e of s)e.seedOrigin===`seed`&&e.seedChunkId&&o.includes(e.seedChunkId)&&a.add(e.id);if(i)for(let e of s){let t=e;e.seedOrigin===`seed`&&e.feedSourceId===n&&(r.length===0||t.retention===`cached`||t.retention===`schedule-pinned`||t.retention===`session-pinned`)&&a.add(e.id)}let c=e.readwrite(`meta`),l=[],u=[],d=`${jh}${n}:`;for(let e of await c.getAll()){let n=e?.key;typeof n==`string`&&n.startsWith(d)&&u.push(n);let r=e;if(!r||typeof r.key!=`string`||!r.key.startsWith(`seed:`)||r.key===t.key)continue;let i=new Set;for(let e of Object.values(r.chunks??{}))for(let t of e.noteIds??[])i.add(t);l.push({key:r.key,sourceId:r.key.slice(5),rank:Ah(r.key,r.tier),meta:r,noteIds:i})}l.sort((e,t)=>t.rank-e.rank);let f=e=>l.some(t=>t.noteIds.has(e)),p=e.readwrite(`notes`),m=0,h=0,g=new Set,_=new Set;for(let i of a){if(f(i))continue;let a=await p.get(i);!a||a.seedOrigin!==`seed`||(a.feedSourceId!==n||r.length!==0&&a.retention!==`cached`&&a.retention!==`schedule-pinned`&&a.retention!==`session-pinned`)&&a.seedChunkId&&!t.chunks[a.seedChunkId]||(await vg(e,a,`unsubscribed`,_,g)===`pinned`?h++:m++)}await _g(e,_);let v=[{storeName:`efforts`,familyPathPrefix:`markdown/efforts/`,parse:Yp},{storeName:`equipment`,familyPathPrefix:`markdown/equipment/`,parse:Xp}];for(let{storeName:t,familyPathPrefix:r,parse:i}of v){let o=e.readwrite(t);for(let e of await o.getAll()){if(e.registrySource!==`bundled`||!(e.sourceId===n||e.ownerNoteId!==void 0&&a.has(e.ownerNoteId)&&(!e.sourceId||e.sourceId===t)||e.sourcePath!==void 0&&e.sourcePath.startsWith(r)&&g.has(e.sourcePath)))continue;let s=!1;for(let n of l){let r=n.meta.chunks?.[t]?.noteIds??[];for(let t of r){let r=await p.get(t);if(!r||r.seedOrigin!==`seed`)continue;let a=i(r.rawContent);if(a&&a.slug===e.slug){await o.put({...a,registrySource:`bundled`,ownerNoteId:r.id,sourceId:n.sourceId,feedSourceId:n.sourceId,sourcePath:r.sourcePath??``}),s=!0;break}}if(s)break}s||await o.delete(e.slug)}}try{let t=e.readwrite(`property_overrides`);for(let e of await t.getAll())e.seedOrigin===`seed`&&e.feedSourceId===n&&await t.delete(e.id)}catch{}for(let e of u)await c.delete(e);return await c.delete(t.key),{deleted:m,preservedPinned:h}})}async function _g(e,t){if(t.size===0)return;let n=e.readwrite(`notes`),r=e.readwrite(`note_tags`),i=e.readwrite(`tags`);for(let e of t){if(await r.countFromIndex(`by-tag`,e)>0)continue;let t=await i.get(e);t&&(t.contributions&&t.contributions.length>0||await n.get(`t/${t.type??`tag`}/${t.label}`)||await i.delete(e))}}async function vg(e,t,n,r,i){let a=e.readwrite(`notes`),o=await mg(e,t.id),s=t.retention===`session-pinned`||o,c=!s&&await hg(e,t.id),l=t.retention===`schedule-pinned`||c;if(s||l)return await a.put({...t,retention:s?`session-pinned`:`schedule-pinned`,upstreamStatus:n}),`pinned`;t.sourcePath&&i&&i.add(t.sourcePath),await a.delete(t.id);let u=e.readwrite(`attachments`);for(let e of await u.getAllFromIndex(`by-note`,t.id))await u.delete(e.id);let d=e.readwrite(`note_tags`);for(let e of await d.getAllFromIndex(`by-note`,t.id))r.add(e.tagId),await d.delete(e.id);let f=e.readwrite(`block_index`);for(let e of await f.getAllFromIndex(`by-note`,t.id))await f.delete(e.id);let p=e.readwrite(`block_efforts`);for(let e of await p.getAllFromIndex(`by-note`,t.id))await p.delete(e.id);let m=e.readwrite(`block_equipment`);for(let e of await m.getAllFromIndex(`by-note`,t.id))await m.delete(e.id);let h=e.readwrite(`page_notes`);for(let e of await h.getAllFromIndex(`by-note`,t.id))await h.delete(e.id);return`deleted`}async function yg(e,t){return gg(e,await e.readonly(`meta`).get(Ph(t))??Ih(Ph(t)))}async function bg(e,t,n){return e.transaction([`notes`,`attachments`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`schedule_items`,`sessions`,`meta`],`readwrite`,async e=>{let r=await e.readwrite(`notes`).getAll(),i=0,a=0,o=new Set;for(let s of r){let r=s;r.seedOrigin===`seed`&&r.feedSourceId===t&&r.seedChunkId===n&&(await vg(e,r,`unsubscribed`,o)===`pinned`?a++:i++)}return await _g(e,o),await e.readwrite(`meta`).delete(`${jh}${t}:${n}`),{deleted:i,preservedPinned:a}})}async function xg(e,t,n,r){return e.transaction([`notes`,`attachments`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`schedule_items`,`sessions`],`readwrite`,async e=>{let i=await e.readwrite(`notes`).getAll(),a=0,o=0,s=new Set;for(let c of i){let i=c;i.seedOrigin===`seed`&&i.feedSourceId===t&&i.seedChunkId===n&&(r.has(i.id)||(await vg(e,i,`removed`,s)===`pinned`?o++:a++))}return await _g(e,s),{deleted:a,preservedPinned:o}})}new Set(ze.map(e=>e.slug));var Sg=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},Cg=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 Sg(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return Wh(await e.json())}resolveTargetUrl(e){if(/^https?:\/\//i.test(e)){let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`||t.username||t.password)throw new Sg(`Disallowed feed resource URL`);return t.toString()}let t=e.replace(/^\/+/,``);return`${this.baseUrl}${t}`}async fetchChunk(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new Sg(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}async fetchText(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new Sg(`feed text fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.text()}},wg=class{storageInstance;constructor(e){this.storageInstance=e}async getSeedMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async getMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async putMeta(e){await this.storageInstance.transaction([`meta`],`readwrite`,async t=>{await t.readwrite(`meta`).put(e)})}async deleteMeta(e){await this.storageInstance.transaction([`meta`],`readwrite`,async t=>{await t.readwrite(`meta`).delete(e)})}async getAllMeta(){return await this.storageInstance.readonly(`meta`).getAll()}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 ag(this.storageInstance,e)}applyChunks(e){return ig(this.storageInstance,e)}backfillFeedProvenance(){return cg(this.storageInstance)}migrateNotebookVocabulary(){return lg(this.storageInstance)}async removeSourceContent(e){return gg(this.storageInstance,e)}async removeSourceContentById(e){return yg(this.storageInstance,e)}async removeNotebookContent(e,t){return bg(this.storageInstance,e,t)}async reconcileRemovedRecords(e,t,n){return xg(this.storageInstance,e,t,n)}},Tg=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=Wh(e.manifest??await this.source.fetchManifest()),n=Ph(this.sourceId),r=e.stored===void 0?await this.storage.getSeedMeta(n):e.stored,i=r?.schema===9?r:void 0,a=i??Ih(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=new Set(t.chunks.map(e=>e.id)),s=[...t.chunks,...(t.notebooks??[]).filter(e=>!o.has(e.notebookId)).map(e=>({id:e.notebookId,path:e.indexPath,sha256:e.sha256,bytes:e.bytes,count:e.count}))],c=s.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))),l=!!(t.notebooks&&t.notebooks.length>0),u=c.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(!l&&(t.version!==a.seedVersion||t.builtAt!==a.builtAt))return!0;return i.sha256!==n.sha256});u.sort((e,t)=>Number(t.id===Nh)-Number(e.id===Nh));let d=Object.keys(a.chunks).filter(e=>!s.some(t=>t.id===e)),f={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0};if(!u.length&&!d.length&&t.version===a.seedVersion&&t.builtAt===a.builtAt)return f;f.status=`imported`;let p=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:f.appliedChunks,totalChunks:u.length,totalNotes:f.totalNotes,totalEfforts:f.totalEfforts,totalEquipment:f.totalEquipment,totalBlocks:f.totalBlocks,skippedUserOwned:f.skippedUserOwned,deleted:f.deleted,preservedPinned:f.preservedPinned,addedNotes:f.addedNotes,updatedNotes:f.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}}),m=e=>{f.totalNotes+=e.totalNotes,f.totalEfforts+=e.totalEfforts,f.totalEquipment+=e.totalEquipment,f.totalBlocks+=e.totalBlocks,f.skippedUserOwned+=e.skippedUserOwned,f.deleted+=e.deleted,f.preservedPinned=(f.preservedPinned??0)+(e.preservedPinned??0),f.addedNotes+=e.addedNotes,f.updatedNotes+=e.updatedNotes},h=(e,n,r)=>({...a,chunks:{...a.chunks,[e.id]:{sha256:e.sha256,version:n?.version,builtAt:n?.builtAt??t.builtAt,importedAt:this.now(),noteIds:r}},importedAt:this.now()}),g=0;if(u[0]?.id===`canvas`){let n=u[0],r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:s,noteIds:c}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id)),l=h(n,r,c);p(`applying`,n.id),m(await this.storage.applyChunk({chunkId:n.id,rows:s,manifest:t,expectedMeta:i,meta:l})),f.appliedChunks++,a=l,i=l,p(`committed`,n.id),e.onFirstPaintApplied?.(),g=1}let _=[];for(let n=g;n<u.length;n+=4){let r=u.slice(n,n+4),i=await Promise.all(r.map(async n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:i,noteIds:s}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id));return{chunk:n,notebook:r,rows:i,noteIds:s}}));_.push(...i)}let v=[];for(let e of _){let n=h(e.chunk,e.notebook,e.noteIds);v.push({chunkId:e.chunk.id,rows:e.rows,manifest:t,expectedMeta:i,meta:n}),a=n,i=n}for(let e of d){let n={...a.chunks};delete n[e];let r={...a,chunks:n,importedAt:this.now()};v.push({chunkId:e,rows:[],manifest:t,expectedMeta:i,meta:r}),a=r,i=r}let y={...a,schema:9,seedVersion:t.version,builtAt:t.builtAt,importedAt:this.now()};if(v.push({chunkId:null,rows:[],manifest:t,expectedMeta:i,meta:y}),v.length>0){if(_.length>0&&p(`applying`,_[0].chunk.id),this.storage.applyChunks){m(await this.storage.applyChunks(v)),f.appliedChunks+=_.length;for(let e of _)p(`committed`,e.chunk.id)}else for(let e of v)m(await this.storage.applyChunk(e)),e.chunkId&&_.some(t=>t.chunk.id===e.chunkId)&&(f.appliedChunks++,p(`committed`,e.chunkId))}return p(`finalizing`,null),f}async fetchSingleRecordRow(e){if(e.recordPath)try{let t=await this.source.fetchChunk(e.recordPath);return Array.isArray(t)?qh(t):[Jh(t)]}catch(t){if(!e.rawUrl&&!/\.md$/i.test(e.path))throw t}let t=e.rawUrl??e.path,n=this.source.fetchText?await this.source.fetchText(t):String(await this.source.fetchChunk(t));return[await pg({path:e.path,markdown:n,uuid:e.uuid,commit:e.commit,version:e.version,title:e.title,date:e.date})]}async fetchChunkData(e,t,n,r,i,a){let o,s=e.records,c=!!(n.chunks[e.id]&&r.granularRecords&&(t?.indexPath||e.records));if(!a||c||r.granularRecords&&e.records&&e.records.length>0){if(t?.indexPath&&(s=Gh(await this.source.fetchChunk(t.indexPath)).records),s&&s.length>0){let t=!r.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(s.map(e=>e.uuid)):void 0,n=t?s.filter(e=>t.get(e.uuid)!==e.commit):s;if(a&&c&&n.length>s.length/2){if(i(`fetching`,e.id),o=qh(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else{let t=[];for(let r=0;r<n.length;r+=8){let a=n.slice(r,r+8);i(`fetching`,e.id,a[0]?.uuid,r,n.length);let o=await Promise.all(a.map(e=>this.fetchSingleRecordRow(e)));for(let e of o)t.push(...e)}o=t}}else if(a){if(i(`fetching`,e.id),o=qh(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else o=[]}else if(i(`fetching`,e.id),o=qh(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`);let l=s&&s.length>0?s.map(e=>e.uuid):await Promise.all(o.map(e=>Xh(e.path)));return{rows:o,noteIds:l}}};function Eg(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function Dg(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}function Og(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 kg(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function Ag(e,t){if(e.offlinePolicy)return e.offlinePolicy;if(e.id===`core`)return`offline-full`;try{let n=(await t.getMeta?.(`feed:subscriptions`))?.entries?.[e.id]?.offlinePolicy;if(n===`index-only`||n===`offline-full`)return n}catch{}return`index-only`}async function jg(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=Ph(e.id),s={outcome:`current`,error:null,manifestChecked:!1,hadCheckpoint:!1};try{let c=await r.getSeedMeta(o);s.hadCheckpoint=(c?.seedVersion??0)>0;let l=await Ag(e,r);if(l===`offline-full`&&!t.force&&!t.probeManifests&&Dg(c,e.embeddedVersion))return s.outcome=`current`,s;if(kg(c,i,a()))return s.outcome=`busy`,s;let u=Wh(await e.source.fetchManifest());if(s.manifestChecked=!0,s.manifest=u,r.putMeta){let t=`catalog:${e.id}`,n=(await r.getMeta(t).catch(()=>void 0))?.manifest;(!n||n.version!==u.version||n.builtAt!==u.builtAt||n.commit!==u.commit||n.schema!==u.schema||(n.notebooks?.length??0)!==(u.notebooks?.length??0)||n.chunks.length!==u.chunks.length)&&await r.putMeta({key:t,feedId:e.id,manifest:u,updatedAt:a()}).catch(()=>void 0)}let d=Array.isArray(u.notebooks)&&u.notebooks.length>0;if(l===`index-only`&&d){let n=u.notebooks.filter(t=>e.notebookIds!==void 0&&e.notebookIds!==null?e.notebookIds.length!==0&&e.notebookIds.includes(t.notebookId):!0),i=await Promise.all(n.map(t=>r.getMeta?.(Mh(e.id,t.notebookId)).catch(()=>void 0)));if(t.background&&!e.autoSyncOn)return s.outcome=n.some((e,t)=>{let n=i[t];return!n?.index||e.version>(n.index.version??0)||!!(e.sha256&&n.index.sha256!==e.sha256)})?`update-pending`:`current`,s;let o=!1,c=0;for(let[s,l]of n.entries()){let n=i[s];if(!(t.force===!0||!n?.index||l.version>(n.index.version??0)||l.sha256&&n.index.sha256!==l.sha256))continue;let u=Gh(await e.source.fetchChunk(l.indexPath));await r.putMeta?.({key:Mh(e.id,l.notebookId),feedId:e.id,notebookId:l.notebookId,index:u,updatedAt:a()});let d=new Set(u.records.map(e=>e.uuid)),f=await r.reconcileRemovedRecords?.(e.id,l.notebookId,d);c+=f?.preservedPinned??0,o=!0}return s.outcome=o?`imported`:`current`,o&&(s.applied=!0,s.importedVersion=u.version,s.added=0,s.updated=0),c>0&&(s.preservedPinned=c),s}let f=t.force?`import`:Eg(c?.seedVersion,u.version);if(f===`server-stale`)return s.outcome=`server-stale`,s;if(c&&c.schema!==9)throw Error(`Incompatible seed checkpoint; recreate storage`);let p=u.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`)));if(t.background&&!e.autoSyncOn)return s.outcome=p.some(e=>{let t=u.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;let m=!!(c&&Object.keys(c.chunks).length>0),h=new Set([...u.chunks.map(e=>e.id),...(u.notebooks??[]).map(e=>e.notebookId)]),g=!m||p.every(e=>c?.chunks[e.id]?.sha256===e.sha256),_=m&&Object.keys(c.chunks).some(e=>!h.has(e));if(!t.force&&f===`current`&&c?.schema===9&&c.builtAt===u.builtAt&&g&&!_)return s.outcome=`current`,s;let v={...c??Ih(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(v,c??null);try{let i=await new Tg(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:!t.force&&!!(e.granularRecords&&m),manifest:u,stored:v});s.outcome=`imported`,i.status===`imported`&&(s.applied=!0,s.importedVersion=u.version,s.added=i.addedNotes,s.updated=i.updatedNotes,i.preservedPinned&&(s.preservedPinned=i.preservedPinned))}finally{try{let e=await r.getSeedMeta(o);e?.claim?.owner===i&&await r.putSeedMeta({...e,claim:null},e)}catch(t){console.warn(`[feedSync] ${e.id} claim release skipped after concurrent update`,t)}}return s}catch(t){return console.warn(`[feedSync] ${e.id} seed sync failed`,t),s.outcome=`error`,s.error=Og(t),s}}let Mg=self;Mg.onmessage=e=>{if(e.data.type!==`run`)return;let t=e.data;(async()=>{let e=new wg(new ed({dbName:t.dbName,...t.userId?{getUserId:()=>t.userId}:{}})),n=[];try{for(let r of t.sources){let i=await jg({id:r.id,label:r.label,source:new Cg(r.url),embeddedVersion:r.embeddedVersion,autoSyncOn:r.autoSyncOn,...r.tier?{tier:r.tier}:{},notebookIds:r.notebookIds,granularRecords:r.granularRecords??!0,...r.offlinePolicy?{offlinePolicy:r.offlinePolicy}:{}},{storage:e,owner:t.owner,now:Date.now,force:t.force,probeManifests:t.probeManifests,background:t.background},{onProgress:e=>Mg.postMessage({type:`progress`,sourceId:r.id,progress:e}),onFirstPaint:()=>Mg.postMessage({type:`first-paint`,sourceId:r.id})});Mg.postMessage({type:`source-result`,sourceId:r.id,result:i}),n.push(i.outcome)}}finally{await e.storageInstance.close().catch(()=>void 0)}Mg.postMessage({type:`done`,outcomes:n})})()}})();
|
|
22
|
-
//# sourceMappingURL=feedSync.worker-
|
|
21
|
+
`:t===`r`?`\r`:t===`t`?` `:t):n)}function Hp(e,t){let n=e[t];return n===void 0||typeof n==`string`&&n===`[]`?[]:Array.isArray(n)?n:void 0}function Up(e){return e===`true`?!0:e===`false`?!1:e!==``&&!Number.isNaN(Number(e))?Number(e):Vp(e)}function Wp(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]=Up(l)):o>=4&&i!==null&&(r[i][c]=Up(l))}return Object.keys(r).length>0?r:void 0}function Gp(e){if(!e)return;let t=Vp(e.trim()).toLowerCase();if(jp(t))return t;console.warn(`[definition-markdown] unknown discipline '${e}' — expected one of the canonical values; treating as unset`)}function Kp(e,t){let n=[],r=e===void 0?``:String(e);return r?Bp.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 qp(e,t){let n=[];for(let r of e)r.trim()?t===`equipment`&&!Bp.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 Jp(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 Yp(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}=et(e),a=tt(r,`type`);if(a!==void 0&&a!==`effort`)return null;let o=tt(r,`id`),s=tt(r,`slug`),c=tt(r,`label`),l=Hp(r,`aliases`),u=Hp(r,`equipment`);if(l===void 0||u===void 0||Kp(s,c).length>0||qp(l,`aliases`).length>0||u.length>0&&qp(u,`equipment`).length>0)return null;let d=Wp(n,`baseAttributes`)??{},f=Wp(n,`metrics`)??{},p=r[`metrics.met`]??f.met??d.met;if(Jp(p)!==null)return null;let m=Number(p),h=tt(r,`discipline`),g=Gp(typeof h==`string`?h:typeof d.discipline==`string`?d.discipline:void 0),_=tt(r,`intensityTier`)??tt(r,`intensity`)??d.intensityTier,v=r[`metrics.disciplineFactor`]??f.disciplineFactor??d.disciplineFactor,y=typeof v==`number`&&Number.isFinite(v)?v:void 0,b=Wp(n,`hints`),x=Wp(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 Xp(e){let{meta:t,body:n}=et(e);if(tt(t,`type`)!==`equipment`)return null;let r=tt(t,`id`),i=tt(t,`slug`),a=tt(t,`label`),o=Hp(t,`aliases`);if(r===void 0||o===void 0||Kp(i,a).length>0||qp(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 Zp=[{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`}];[...Zp];let Qp=Zp;Qp.length;function $p(e){let t=Op(e),n=new Map,r=(e,t)=>{if(!e)return;let r=n.get(e);r?r.includes(t)||r.push(t):n.set(e,[t])};for(let e of t){r(e.slug.toLowerCase(),e),r(Sp(e.label),e);for(let t of e.aliases)r(Sp(t),e)}return{byKey:n,lookup(e){let t=n.get(e)??n.get(Sp(e));if(!t||t.length===0)return{entity:null,ambiguous:[]};if(t.length===1)return{entity:t[0],ambiguous:[]};let r=-1;for(let e of t){let t=Dp(e);t>r&&(r=t)}let i=t.filter(e=>Dp(e)===r);if(i.length===1)return{entity:i[0],ambiguous:[]};let a=e.trim().toLowerCase(),o=Sp(e).replace(/\s+/g,`-`),s=i.filter(e=>e.slug.toLowerCase()===a||e.slug.toLowerCase()===o);return s.length===1?{entity:s[0],ambiguous:[]}:{entity:null,ambiguous:i}}}}function em(e){return{kind:`equipment`,slug:e.slug,label:e.label}}function tm(e){let t=new Set,n=[];for(let r of e){let e=`${r.kind}:${r.slug}`;t.has(e)||(t.add(e),n.push(r))}return n}function nm(e,t){let n=Op(e.equipment??[]),r=$p(e.efforts??[]),i=$p(n),a=n.flatMap(e=>[e.label,...e.aliases].filter(e=>!!e&&!!e.trim()).map(t=>({lower:t.trim().toLowerCase(),entity:e}))).sort((e,t)=>t.lower.length-e.lower.length),o=t??(e=>({effort:e,definition:e,slug:e.slug,label:e.label,met:e.baseAttributes.met,baseAttributes:e.baseAttributes,discipline:e.baseAttributes.discipline,disciplineFactor:e.baseAttributes.disciplineFactor??1,intensityTier:e.baseAttributes.intensityTier,modifiers:{},registrySource:e.registrySource,resolvedFrom:e.registrySource===`user`?`user`:e.registrySource===`bundled`?`bundled`:`default`,isEstimated:!1})),s=e=>{let t=r.lookup(e.trim());return t.entity?{entity:t.entity}:t.ambiguous.length>0?{entity:null,diagnostic:{reason:`ambiguous-effort`,message:`"${e}" matches multiple efforts.`,token:e,candidates:t.ambiguous.map(e=>e.slug)}}:{entity:null,diagnostic:{reason:`unknown-effort`,message:`Unknown effort "${e}".`,token:e}}},c=e=>{let t=[],n=[];for(let r of e){if(typeof r!=`string`||!r.trim()){n.push({reason:`invalid-explicit`,message:`Equipment reference must be a slug string, got ${JSON.stringify(r)??`null`}.`,token:String(r)});continue}let e=i.lookup(r.trim());e.entity?t.push(em(e.entity)):e.ambiguous.length>0?n.push({reason:`ambiguous-equipment`,message:`"${r}" matches multiple equipment entries.`,token:r,candidates:e.ambiguous.map(e=>e.slug)}):n.push({reason:`invalid-explicit`,message:`Unknown equipment "${r}".`,token:r})}return{refs:tm(t),diagnostics:n}};return{resolveEffort(e){return r.lookup(e).entity},resolveEquipment(e){return i.lookup(e).entity},materialize(e){return o(e)},resolve(e,t){let n=(e??``).trim(),r=[],l=e=>{e&&r.push(e)},u=`none`,d=null,f=``,p=[],m=!1,h,g=()=>{if(!(p.length>0||m)&&d!==null){if(t?.equipment?.length){let e=c(t.equipment);p=e.refs;for(let t of e.diagnostics)l({...t,reason:`unknown-equipment`});if(p.length>0)return}if(d.equipment?.length){let e=c(d.equipment);p=e.refs;for(let t of e.diagnostics)l({...t,reason:`unknown-equipment`})}}};if(!n){if(t?.effort){let e=s(t.effort);e.entity?(d=e.entity,u=`default`):l({reason:e.diagnostic?.reason===`ambiguous-effort`?`ambiguous-effort`:`unknown-effort`,message:`Default effort "${t.effort}" is not in the catalog.`,token:t.effort,candidates:e.diagnostic?.candidates})}return g(),{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label}:null,equipment:p,remaining:``,diagnostics:r}}if(n.startsWith(`{`)){let e;try{e=JSON.parse(n)}catch{return{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:[{reason:`malformed-json`,message:`Reference object is not valid JSON.`,token:n}]}}if(e&&typeof e==`object`&&!Array.isArray(e)&&(`effort`in e||`equipment`in e)){u=`explicit`;let t=e;if(t.effort!==void 0){if(typeof t.effort==`string`&&t.effort.trim()){let e=s(t.effort);d=e.entity,e.diagnostic&&l(e.diagnostic.reason===`ambiguous-effort`?e.diagnostic:{...e.diagnostic,reason:`invalid-explicit`,message:`Explicit effort "${t.effort}" is not in the catalog.`})}else l({reason:`invalid-explicit`,message:`Explicit "effort" must be a slug string.`,token:String(t.effort)})}if(t.equipment!==void 0){m=!0;let e=Array.isArray(t.equipment)?t.equipment:[t.equipment],i=c(e);if(p=i.refs,r.push(...i.diagnostics),d&&d.equipment?.length){let e=new Set(d.equipment),t=p.map(e=>e.slug);t.length>0&&t.some(t=>!e.has(t))&&l({reason:`conflict`,message:`Explicit equipment [${t.join(`, `)}] contradicts effort "${d.slug}" definition equipment [${d.equipment.join(`, `)}].`,token:n})}}return g(),{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label}:null,equipment:p,remaining:``,diagnostics:r}}}let _=s(n),v=n.toLowerCase();for(let e of a){if(!v.startsWith(e.lower))continue;let t=n.slice(e.lower.length);if(t&&!/^\s/.test(t))continue;let a=t.trim();if(!a)continue;let o=i.lookup(e.lower);if(o.ambiguous.length>0)return l({reason:`ambiguous-equipment`,message:`"${e.lower}" matches multiple equipment entries.`,token:n,candidates:o.ambiguous.map(e=>e.slug)}),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};if(!o.entity)continue;let c=s(a);if(_.entity&&_.entity.equipment?.includes(o.entity.slug)&&(c.entity||c.diagnostic?.reason===`ambiguous-effort`)){u=`whole`,d=_.entity;break}if(c.entity){u=`split`,d=c.entity;let t=n.slice(0,e.lower.length).trim();p=[{...em(o.entity),...t.toLowerCase()===o.entity.label.toLowerCase()?{}:{matchedAlias:t}}],m=!0,f=a,h={start:0,end:t.length};break}if(c.diagnostic?.reason===`ambiguous-effort`&&!_.entity)return l(c.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r}}if(u===`none`){if(_.entity)d=_.entity,u=`whole`;else if(_.diagnostic?.reason===`ambiguous-effort`)return l(_.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};else _.diagnostic&&l(_.diagnostic)}if(u===`none`)for(let e of a){if(!v.endsWith(e.lower))continue;let t=n.length-e.lower.length;if(t<=0||!/\s$/.test(n.slice(0,t)))continue;let a=n.slice(0,t).trim();if(!a)continue;let o=i.lookup(e.lower);if(o.ambiguous.length>0)return r.length=0,l({reason:`ambiguous-equipment`,message:`"${e.lower}" matches multiple equipment entries.`,token:n,candidates:o.ambiguous.map(e=>e.slug)}),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r};if(!o.entity)continue;let c=s(a);if(c.entity){r.length=0,u=`split`,d=c.entity;let e=n.slice(t);p=[{...em(o.entity),...e.toLowerCase()===o.entity.label.toLowerCase()?{}:{matchedAlias:e}}],m=!0,f=a,h={start:t,end:n.length};break}if(c.diagnostic?.reason===`ambiguous-effort`)return r.length=0,l(c.diagnostic),{matched:`none`,label:n,effort:null,effortRef:null,equipment:[],remaining:``,diagnostics:r}}g();let y=u===`split`?f:n;return{matched:u,label:n,effort:d?o(d):null,effortRef:d?{kind:`effort`,slug:d.slug,label:d.label,...y&&y.toLowerCase()!==d.label.toLowerCase()?{matchedAlias:y}:{}}:null,equipment:p,remaining:f,...h?{equipmentSpan:h}:{},diagnostics:r}}}}function rm(e){let t=[],n=[],r=new Set,i=new Set,a=(e,t,n)=>{n&&(t.has(n)||(t.add(n),e.push(n)))};for(let o of e??[]){let e=Array.isArray(o.metrics)?o.metrics:o.metrics?.toArray?.()??[];for(let o of e){let e=Ne(o.metadata)?.refs;if(e)for(let o of e)o.kind===`effort`&&a(t,r,o.slug),o.kind===`equipment`&&a(n,i,o.slug)}}return{efforts:t,equipment:n}}let im={now:()=>new Date,nowMs:()=>Date.now()};var am=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}},om=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)}},sm=class{options;now;type=`next`;constructor(e,t=im){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:om.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 cm=e=>String(e).padStart(2,`0`),lm=e=>String(e).padStart(3,`0`);function um(e){return`${cm(e.getHours())}:${cm(e.getMinutes())}:${cm(e.getSeconds())}.${lm(e.getMilliseconds())}`}function dm(e){return(e+` `).slice(0,5)}function fm(e){return(e+` `.repeat(24)).slice(0,24)}function pm(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 mm=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)}] ${hm(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${pm(e)}`,`color: #94a3b8`)}writeLine(e,t,n){let r=um(new Date);this._console.log(`${r} %c${dm(e)}%c ${fm(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 hm(e){try{return JSON.stringify(e)??``}catch{return String(e)}}let gm=new mm;typeof window<`u`&&(window.RuntimeLogger=gm);var _m=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}`)}};function vm(e,t){let n=0;for(let r of e.spans){let e=r.ended??t;n+=e-r.started}return n}function ym(e){let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}var bm=class{value;sourceBlockKey;timestamp;type=E.Elapsed;origin=`analyzed`;unit=`ms`;constructor(e,t,n){this.value=e,this.sourceBlockKey=t,this.timestamp=n}get image(){return ym(this.value)}},xm=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`),gm.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`&&gm.logPop(a,a.completionReason,e.stack.blocks.length+1),e.stack.current?[...i,new sm(r,e.nowProvider)]:i):[]}},Sm=class{_memory;ownerId;type;visibility;_logger;id=Lp();_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=Lp(),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)}}},Cm=class{_references=[];allocate(e,t,n,r=`private`){let i=new Sm(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 Sm&&r.hasSubscribers()&&r.notifySubscribers(void 0,n),this._references.splice(t,1)}}};let wm=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 Tm=class{timestamp;constructor(e=im){this.timestamp=e.now()}},Em=class extends Tm{name=`memory:allocate`;data;constructor(e,t,n=im){super(n),this.data={ref:e,value:t}}},Dm=class extends Tm{name=`memory:set`;data;constructor(e,t,n,r=im){super(r),this.data={ref:e,value:t,oldValue:n}}},Om=class extends Tm{name=`memory:release`;data;constructor(e,t,n=im){super(n),this.data={ref:e,lastValue:t}}},km=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 Cm}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 Em(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 Dm(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 Om(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===wm.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(wm.ANCHOR,this.ownerId,void 0,`public`);return n.id=e,this._references.push(n),n}};let Am=`time`;function jm(e){return[new am(e)]}function Mm(e,t){return e.map((n,r)=>r===e.length-1&&n.ended===void 0?new am(n.started,t):n)}function Nm(e,t){return[...e,new am(t)]}function Pm(e){return e.getMemoryByTag(Am)[0]?.metrics[0]?.value}function Fm(e,t){let n=e.getMemoryByTag(Am)[0]?.metrics[0],r=n?.value;if(!r||!n)return!1;let i=t(r.spans,e.clock.currentDate.getTime());return e.updateMemory(Am,[{...n,value:{...r,spans:i}}]),!0}var Im=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 xm().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 sm(void 0,e.nowProvider)),t}},Lm=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:jm(t),direction:`down`,durationMs:this.config.durationMs,label:n,role:r,required:!!this.config.required,polarity:this.config.polarity??`work`})]),this.config.durationMs<=0?(this.handleExpiry(e,i),[new Im(e.block.key.toString())]):(this.subscriptions.push(e.subscribe(`tick`,(e,t)=>i===`complete-block`&&t.block.isComplete||!this.hasExpired(t)?[]:(this.handleExpiry(t,i),[new Im(t.block.key.toString())]),{scope:`bubble`})),this.subscriptions.push(e.subscribe(`timer:reset`,(e,t)=>(i===`reset-interval`&&Fm(t,(e,t)=>jm(t)),[]))),this.subscriptions.push(e.subscribe(`timer:pause`,(e,t)=>(this.isPaused||Fm(t,Mm)&&(this.isPaused=!0),[]))),this.subscriptions.push(e.subscribe(`timer:resume`,(e,t)=>(this.isPaused&&Fm(t,Nm)&&(this.isPaused=!1),[]))),[])}onNext(e){if((this.config.mode??`complete-block`)===`complete-block`&&!e.block.isComplete&&this.hasExpired(e))return e.markComplete(`timer-expired`),[new xm,new Im(e.block.key.toString())];if(this.config.required&&!e.block.isComplete)return e.emitEvent({name:`timer:skip-attempt`,timestamp:e.clock.currentDate,data:{blockKey:e.block.key.toString()}}),[];if(e.hasCapability(`childSelection`)||!this.config.restBlockFactory)return[];let t=Pm(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 Fm(e,Mm),[]}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(Fm(e,(e,t)=>jm(t)),e.hasCapability(`childSelection`))return;let t=e.getMemoryByTag(`round`)[0]?.metrics[0];if(t){let n=new _m(t.current+1,t.total,e.block.key.toString(),e.clock.currentDate);e.updateMemory(`round`,[n])}let n=e.getMemoryByTag(`children:status`)[0],r={childIndex:0,totalChildren:n?.metrics[0]?.value?.totalChildren??0,allExecuted:!1,allCompleted:!1};n?.metrics[0]?e.updateMemory(`children:status`,[{...n.metrics[0],value:r}]):e.pushMemory(`children:status`,[{type:`status`,image:``,origin:`runtime`,value:r}])}}hasExpired(e){let t=Pm(e);return!t||t.direction!==`down`||t.durationMs===void 0?!1:vm(t,e.nowProvider.nowMs())>=t.durationMs}getRemainingCountdownMs(e){let t=Pm(e);if(!t||t.direction!==`down`||!t.durationMs)return 0;let n=vm(t,e.clock.currentDate.getTime());return Math.max(0,t.durationMs-n)}createFragment(e,t){return{type:E.Time,image:Rm(t.durationMs),origin:`runtime`,value:t,sourceBlockKey:e.block.key.toString(),timestamp:e.clock.currentDate}}};function Rm(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 zm=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])}},Bm=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 xm]));this.unsubscribers.push(n)}return[]}onNext(e){return this.config.mode===`deferred`?e.block.isComplete?[new xm]:[]:this.config.onNext?(e.block.isComplete||e.markComplete(`user-advance`),[new xm]):[]}onUnmount(e){return[]}onDispose(e){for(let e of this.unsubscribers)e();this.unsubscribers=[]}},Vm=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`}};kp.defaultMet;var Hm=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 ym(this.value)}},Um=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`)}`}},Wm=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()}},Gm=class{config;_now;lastEmittedRound;constructor(e={},t=im){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=Pm(e),n=e.getMemoryByTag(`round`)[0]?.metrics[0],r=this.config.computeTimeResults??!0,i=e.block.completionReason,a=i===`user-abort`||i===`forced-pop`||i===`timer-expired`,o=n?a?{current:Math.max(0,n.current-1),total:n.total}:n:void 0,s=this.config.label??`Completed`;if(this.config.label||(e.block.blockType===`SessionRoot`?s=`Session Completed`:o&&!a&&o.total!==void 0&&o.total>1?s=`Completed ${o.total} Round(s)`:o&&o.current>0?s=`Completed ${o.current} Round(s)`:a&&n&&(s=`Completed 0 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),s,o,a);return this.writeResultGroups(e,r),[]}}let c=r?this.computeTimeResults(e,t,s,o,a):D.from([new Wm(this._now.now(),e.block.key.toString())],e.block.key.toString());return this.writeResultMemory(e,c),[]}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 _m(t.current,t.total,e.block.key.toString(),e.clock.currentDate)),r=Pm(e);if(r){let t=vm(r,e.clock.currentDate.getTime());n.add(new bm(t,e.block.key.toString(),e.clock.currentDate)),r.spans.length>0&&n.add(new Um([...r.spans],e.block.key.toString(),e.clock.currentDate))}return n}resolveFallbackTiming(e,t){if(e.block.blockType===`WaitingToStart`)return null;let n=e.block.executionTiming?.startTime?.getTime();return n===void 0||!Number.isFinite(n)||n>t?null:{started:n,ended:t,elapsedMs:Math.max(0,t-n)}}computeTimeResults(e,t,n,r,i=!1){let a=e.clock.currentDate,o=a.getTime(),s=e.block.key.toString(),c=r!==void 0&&(r.current>0||i);if(t&&t.spans.length>0){let e=vm(t,o),i=t.spans.map(e=>e.ended===void 0?new am(e.started,o):e),l=i[0].started,u=i[i.length-1].ended??o,d=Math.max(0,u-l),f=D.empty(s).add(new bm(e,s,a),new Hm(d,s,a),new Um(i,s,a),new Wm(this._now.now(),s));return c&&f.add(new _m(r.current,r.total,s,a,n)),f}let l=this.resolveFallbackTiming(e,o),u=l?new am(l.started,l.ended):new am(o,o),d=l?.elapsedMs??0,f=D.empty(s).add(new bm(d,s,a),new Hm(d,s,a),new Um([u],s,a),new Wm(this._now.now(),s));return c&&f.add(new _m(r.current,r.total,s,a,n)),f}buildWeightedSplitGroups(e,t,n,r,i,a,o,s,c=!1){let l=o.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}),u=l.reduce((e,t)=>e+t,0),d=a!==void 0&&(a.current>0||c),f=0;return o.map((o,c)=>{let p=l[c]/u,m=Math.round(t*p),h=Math.round(n*p),g=e+f,_=g+h;f+=h;let v=o.clone().add(new bm(m,i,r),new Hm(h,i,r),new Um([new am(g,_)],i,r),new Wm(this._now.now(),i));return d&&v.add(new _m(a.current,a.total,i,r,s)),v})}computeSplitTimeResults(e,t,n,r,i,a=!1){let o=e.clock.currentDate,s=o.getTime(),c=e.block.key.toString(),l=i!==void 0&&(i.current>0||a);if(!t||t.spans.length===0){let t=this.resolveFallbackTiming(e,s);return t?this.buildWeightedSplitGroups(t.started,t.elapsedMs,t.elapsedMs,o,c,i,n,r,a):n.map(e=>{let t=e.clone().add(new bm(0,c,o),new Hm(0,c,o),new Um([new am(s,s)],c,o),new Wm(this._now.now(),c));return l&&t.add(new _m(i.current,i.total,c,o,r)),t})}let u=vm(t,s),d=t.spans[0].started,f=(t.spans[t.spans.length-1].ended??s)-d;return this.buildWeightedSplitGroups(d,u,f,o,c,i,n,r,a)}writeResultMemory(e,t){let n=e.block.getMemoryByTag(`metric:result`);if(n.length>0){let r=Km(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?Km([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 Km(e){let t=[];for(let n of e)for(let e of n.metrics)e.origin===`user`&&t.push(e);return t}var qm=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 Jm(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 Ym={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 Xm=class{config;rules=[];fired=new Set;durationMs;constructor(e){this.config=e}onMount(e){let t=Pm(e);return this.durationMs=t?.durationMs,this.rules=Jm(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=Pm(e);if(t)return vm(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 qm(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 Zm=E.Sound;function Qm(e,t){let n=$m(e);if(n){let e=eh(t?.profiles,n);if(e)return e}if(t?.noteProfileId){let e=eh(t?.profiles,t.noteProfileId);if(e)return e}return Ym}function $m(e){for(let t of e){let e=t.metrics.find(e=>e.type===Zm);if(!e)continue;let n=e.value;if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function eh(e,t){if(e)return e.find(e=>e.id===t)}let th=(e,t,n)=>({id:e,kind:`expr`,expression:t,unit:n});nh(),nh(),nh(),rh(),rh();function nh(){return{sRPE:th(`sRPE`,`rpeSource.rpe`),durationMinutes:th(`durationMinutes`,`convert(session.duration, min)`),load:th(`load`,`round(rpeSource.rpe * convert(session.duration, min))`)}}function rh(){return{elapsedMin:th(`elapsedMin`,`convert(sum(elapsed), min)`),avgMets:th(`avgMets`,`sum(metMinutes) / elapsedMin`),metMax:th(`metMax`,`sharedMet.metMax`),metScore:th(`metScore`,`min(100, avgMets / metMax * 100)`),rpeScore:th(`rpeScore`,`rpeSource.rpe * 10`),durationScore:th(`durationScore`,`elapsedMin / 60 * metScore`,`pts`),disciplineFactor:th(`disciplineFactor`,`lookup("effort", effort, "disciplineFactor")`),tis:th(`tis`,`round(0.30 * metScore + 0.35 * rpeScore + 0.20 * durationScore + 0.15 * disciplineFactor, 1)`)}}new ad([]),new ad([]);var ih=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&&!Rd.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=>dd(e,od.LABEL_AMRAP)))return`AMRAP`;if(e.some(e=>dd(e,od.LABEL_EMOM)))return`EMOM`;if(e.some(e=>dd(e,od.LABEL_TABATA)))return`TABATA`;if(e.some(e=>dd(e,od.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||e.type===E.Equipment)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()}},ah=class{distribute(e,t){return[e.clone()]}};let oh=e=>e[0];function sh(e,t){let{statements:n,runtime:r,blockType:i,defaultLabel:a}=t,o=(t.pickStatement??oh)(n),s=t.key??new Le,c=t.context??new km(r,s.toString(),o.exerciseId||``),l=ih.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 ah,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,polarity:n.polarity,...t.countdownTimerConfig??{}})}if(t.repeater){let n=t.repeater;e.asRepeater({totalRounds:n.totalRounds,startRound:n.startRound??1,addCompletion:n.addCompletion})}return l}var ch=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=sh(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 Vm({mode:`countdown`,label:i})),e.declareExit(`immediate`)}},lh=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=>dd(e,od.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=>dd(e,od.LABEL_AMRAP)||e.metrics.some(e=>e.type===E.Rounds&&typeof e.value==`string`&&e.value.toLowerCase()===`amrap`)),o=e.some(e=>dd(e,od.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=sh(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 Vm({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 zm({promotions:u}))}},uh=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){sh(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 Bm({mode:`immediate`,onNext:!0}))}},dh=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=sh(e,{blockType:`Group`,defaultLabel:`Group`,statements:t,runtime:n});e.addBehavior(new Vm({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 zm({promotions:o}))}},fh=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=sh(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 Vm({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 zm({repScheme:a,promotions:u})),e.declareExit(`immediate`)}},ph=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=>dd(e,od.REQUIRED_TIMER)),s=t.some(e=>dd(e,od.INJECT_REST)),c=!!(a&&i===`down`),l=t.flatMap(e=>[...e.metrics]),u=l.some(e=>(e.type===E.Effort||e.type===E.Action)&&typeof e.value==`string`&&e.value.trim().toLowerCase()===`rest`),d=l.some(e=>e.type===E.Effort&&typeof e.value==`string`&&e.value.trim().toLowerCase()!==`rest`),f=sh(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,polarity:u&&!d?`rest`:`work`},pickStatement:e=>e.find(e=>e.metrics.some(e=>e.type===E.Duration&&e.origin!==`runtime`))||e[0]});o&&c?e.addBehavior(new Bm({mode:`immediate`,onNext:!1,onEvents:[`timer:complete`]})):e.addBehavior(new Bm({mode:`immediate`,onNext:!0})),e.addBehavior(new Vm({mode:a?`countdown`:`clock`,label:f}))}},mh=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(Lm),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`)}},hh=class{priority=15;id=`report-output`;match(e,t){return e&&e.length>0}apply(e,t,n){e.hasBehavior(Gm)||e.addBehavior(new Gm)}},gh=class{priority=20;id=`sound`;match(e,t){return e.length>0}apply(e,t,n){if(e.hasBehavior(Xm)||!e.hasTimerBehavior())return;let r=Qm(t,n.options?.soundOptions);e.addBehavior(new Xm({profile:r}))}};new ad([new ch,new lh,new ph,new fh,new dh,new gh,new hh,new mh,new uh]).list(),E.Elapsed,E.Total,E.Spans,E.SystemTime,E.CurrentRound,E.System;function _h(e){let t=e.trim();if(t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)){try{if(t.startsWith(`"`))return JSON.parse(t)}catch{}return t.slice(1,-1)}return t}function vh(e){if(!e)return;let t=_h(e),n=t.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(n){let e=Date.parse(`${t}T12:00:00Z`),r=new Date(e);return Number.isFinite(e)&&r.getUTCMonth()===Number(n[2])-1&&r.getUTCDate()===Number(n[3])?e:void 0}let r=Date.parse(t);return Number.isFinite(r)?r:void 0}let yh=/^---\r?\n([\s\S]*?)\r?\n---/;function bh(e){let t=yh.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 xh=e=>Array.isArray(e)?e:typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[];function Sh(e,t=gt){let n=bh(e),r=xh(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 xh(n[t]))r.push({label:i,type:e})}return r.filter(e=>e.label.length>0)}let Ch=[`sessionId`,`noteId`,`blockId`,`blockVersion`,`blockContentId`,`origin`,`status`,`startTime`,`endTime`,`duration`,`completed`,`sessionCreatedAt`,`sessionExtraJson`],wh=`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(`.`),Th=[...Ch,...wh],Eh=[`revisionKind`,`revisionRawContent`,`revisionSavedAt`,`revisionDialect`,`revisionSport`,`parseId`,`parseStage`,`parseStatus`,`parseDiagnosticsJson`,`parseMetricsJson`];[...Th,...Eh];let Dh=Be,Oh={core:0,community:1,imported:2,user:3};function kh(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 Ah(e,t){return Oh[kh(e,t)]}let jh=`feed:index:`;function Mh(e,t){return`${jh}${e}:${t}`}let Nh=`canvas`;function Ph(e){return`seed:${e}`}function Fh(e){return e.startsWith(`seed:`)?e.slice(5):e}function Ih(e){return{key:e,schema:9,seedVersion:0,builtAt:``,importedAt:0,chunks:{},claim:null}}function Lh(e){let t=/^notebook\.(.+)$/.exec(e)?.[1];return t&&t!==`_root`?t:void 0}function Rh(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 zh(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:${Rh(t)??a}`;if(n===`dashboards`)return`dashboards`;if(n===`efforts`)return`efforts`;if(n===`equipment`)return`equipment`;if(n.startsWith(`notebook.`)){let e=Lh(n);return e?i.toLowerCase()===`readme`?`notebook:${e}`:`notebook:${a}`:`notebook:_root`}}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bh(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function $(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Vh(e){return typeof e==`number`&&Number.isFinite(e)}function Hh(e){return typeof e==`string`&&e.length>0&&!e.startsWith(`/`)&&!e.split(`/`).includes(`..`)}function Uh(e){if(typeof e!=`string`||!e.trim())return!1;if(/^https?:\/\//i.test(e))try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password}catch{return!1}return Hh(e)}function Wh(e){if(!Q(e))throw Error(`Incompatible seed schema; rebuild seed artifacts`);let t=Array.isArray(e.notebooks);if(e.schema===void 0){if(!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`)}else if(!Bh(e.schema)||e.schema!==9&&!t)throw Error(`Incompatible seed schema; rebuild seed artifacts`);let n=e.schema===void 0?9:e.schema,r=e.version===void 0&&t?1:e.version,i=e.builtAt===void 0&&t?new Date(0).toISOString():e.builtAt,a=e.chunks===void 0&&t?[]:e.chunks;if(!$(r)||typeof i!=`string`||!Number.isFinite(Date.parse(i))||!Array.isArray(a))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`);for(let t of[`indexBytes`,`chunkBytes`])if(e[t]!==void 0&&!$(e[t]))throw Error(`invalid seed manifest metadata`);let o=new Set,s=new Set;for(let e of a){if(!Q(e)||typeof e.id!=`string`||!e.id||typeof e.path!=`string`||!/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(e.path)||typeof e.sha256!=`string`||!/^[0-9a-f]{64}$/.test(e.sha256)||!$(e.bytes)||!$(e.count)||e.kind!==void 0&&e.kind!==`notes`||o.has(e.id)||s.has(e.path))throw Error(`seed manifest failed shape validation`);o.add(e.id),s.add(e.path)}let c;if(e.notebooks!==void 0){if(!Array.isArray(e.notebooks))throw Error(`seed manifest failed shape validation`);c=[];for(let t of e.notebooks){if(!Q(t)||typeof t.notebookId!=`string`||!t.notebookId||typeof t.label!=`string`||!$(t.count)||!Uh(t.indexPath))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`);if(t.version!==void 0&&!$(t.version)||t.commit!==void 0&&typeof t.commit!=`string`||t.builtAt!==void 0&&typeof t.builtAt!=`string`||t.sha256!==void 0&&typeof t.sha256!=`string`||t.bytes!==void 0&&!$(t.bytes)||t.indexBytes!==void 0&&!$(t.indexBytes)||t.chunkBytes!==void 0&&!$(t.chunkBytes))throw Error(`seed manifest failed shape validation`);c.push({...t,version:t.version??r,commit:t.commit??``,builtAt:t.builtAt??i,sha256:t.sha256??``,bytes:t.bytes??t.indexBytes??0})}}return{...e,schema:n,version:r,builtAt:i,chunks:a,...c===void 0?{}:{notebooks:c}}}function Gh(e){if(!Q(e))throw Error(`notebook index failed shape validation`);if(typeof e.notebookId!=`string`||!e.notebookId||typeof e.label!=`string`||!e.label||!Uh(e.indexPath)||!$(e.count)||!Array.isArray(e.records)||e.version!==void 0&&!$(e.version)||e.commit!==void 0&&typeof e.commit!=`string`||e.builtAt!==void 0&&typeof e.builtAt!=`string`||e.sha256!==void 0&&typeof e.sha256!=`string`||e.bytes!==void 0&&!$(e.bytes))throw Error(`notebook index failed shape validation: missing required index summary or records`);let t=[];for(let n of e.records){if(!Q(n)||typeof n.uuid!=`string`||!n.uuid||!Hh(n.path))throw Error(`notebook index failed shape validation: invalid record ref`);let e=n.recordPath!==void 0,r=n.rawUrl!==void 0,i=/\.md$/i.test(n.path);if(e&&!Hh(n.recordPath)||r&&!Uh(n.rawUrl)||!e&&!r&&!i||n.commit!==void 0&&typeof n.commit!=`string`||n.version!==void 0&&!$(n.version)||n.sha256!==void 0&&typeof n.sha256!=`string`||n.title!==void 0&&typeof n.title!=`string`||n.date!==void 0&&!Vh(n.date))throw Error(`notebook index failed shape validation: invalid record ref`);t.push({...n,commit:n.commit??``,version:n.version??1,sha256:n.sha256??``})}return{...e,version:e.version??1,commit:e.commit??``,builtAt:e.builtAt??new Date(0).toISOString(),sha256:e.sha256??``,bytes:e.bytes??0,records:t}}function Kh(e,t){if(e.telemetry===void 0)return;if(!Q(e.telemetry)||!Array.isArray(e.telemetry.sessions)||!Array.isArray(e.telemetry.events))throw Error(`invalid seed telemetry`);let n=new Map;for(let r of e.telemetry.sessions){if(!Q(r)||typeof r.id!=`string`||!r.id||n.has(r.id)||typeof r.noteId!=`string`||!r.noteId||typeof e.uuid==`string`&&r.noteId!==e.uuid||typeof r.blockId!=`string`||!Bh(r.blockVersion)||typeof r.blockContentId!=`string`||!Vh(r.startTime)||!Vh(r.endTime)||!Vh(r.duration)||typeof r.completed!=`boolean`||!Vh(r.createdAt))throw Error(`invalid seed session`);let i=t.find(e=>Q(e)&&e.blockId===r.blockId);if(!Q(i)||i.dataType!==`wod`||i.blockVersion!==r.blockVersion||i.blockContentId!==r.blockContentId)throw Error(`orphan or incompatible seed session pin`);n.set(r.id,r)}let r=new Set;for(let t of e.telemetry.events){if(!Q(t)||typeof t.id!=`string`||!t.id||r.has(t.id)||typeof t.resultId!=`string`||typeof t.noteId!=`string`||!Vh(t.timestamp)||t.grain!==`event`&&t.grain!==`summary`||typeof t.outputType!=`string`||!Array.isArray(t.metrics)||!t.metrics.every(e=>Q(e)&&typeof e.type==`string`)||t.grain===`summary`&&t.metrics.length!==1)throw Error(`invalid seed event`);let e=n.get(t.resultId);if(!e||t.noteId!==e.noteId||t.blockId!==e.blockId||t.blockVersion!==e.blockVersion||t.blockContentId!==e.blockContentId)throw Error(`orphan or incompatible seed event identity`);r.add(t.id)}}function qh(e){if(!Array.isArray(e))throw Error(`seed chunk is not an array`);let t=new Set;for(let n of e){if(!Q(n)||typeof n.path!=`string`||!n.path||n.path.startsWith(`/`)||n.path.split(`/`).includes(`..`)||t.has(n.path)||typeof n.content!=`string`||!Q(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(!Q(t)||t.id!==e||!e||t.version!==1||t.sourceRevision!==1||!$(t.from)||!Bh(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`);Ye(n.content,n.blocks,1,{registeredWidgets:Dh});let e=new Set,r=Ke(n.content,{registeredWidgets:Dh});for(let t of n.blockIndex){if(!Q(t)||typeof t.blockId!=`string`)throw Error(`invalid seed projection`);let i=n.blocks[t.blockId];if(!Q(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&&!$(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!==Re(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(!Q(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))||!Q(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=>Q(e)&&e.blockId===t.blockId);if(!Q(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(!Q(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))||!Q(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=>Q(e)&&e.blockId===t.blockId);if(!Q(i)||t.noteId!==i.noteId||t.blockContentId!==i.blockContentId||!Number.isFinite(t.createdAt))throw Error(`invalid seed equipment metadata`);a.add(String(t.id))}Kh(n,n.blockIndex)}return e}function Jh(e){return qh([e])[0]}function Yh(e,t,n){return`${e}:${t}:${n}`}async function Xh(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 Zh(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&&Zh(Reflect.get(e,n),Reflect.get(t,n)))}function Qh(e){return(e.split(`/`).at(-1)??e).replace(/\.md$/,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}function $h(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=Xe(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 Je(t,{sourceRevision:n,blocks:c,registeredWidgets:Dh,createId:()=>`seed:${e.id}:r${n}:${l++}`})}async function eg(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:Ah(n.sourceId)}return a>=r&&!Zh(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 tg(e,t,n){if(!t.length)return;let r=await e.getMany(n),i=t.filter((e,t)=>!Zh(e,r[t]));i.length&&await e.putMany(i)}let ng=[`notes`,`block_revisions`,`block_index`,`block_efforts`,`block_equipment`,`page`,`page_notes`,`tags`,`note_tags`,`efforts`,`equipment`,`property_overrides`,`meta`,`sessions`,`events`];async function rg(e){Wh(e.manifest),qh(e.rows);let t=await Promise.all(e.rows.map(e=>Xh(e.path))),n=new Map,r=new Map,i=new Map;for(let[a,o]of e.rows.entries()){let e=bh(o.content).slug;typeof e==`string`&&e.trim()&&(n.set(e,await Xh(`page:${e}`)),r.set(t[a],await Xh(`pagenote:${e}:${o.path}`)));for(let{label:e}of Sh(o.content))i.has(e)||i.set(e,await Xh(`tag:${e}`))}return{write:e,ids:t,pagesBySlug:n,linkIds:r,tagIds:i}}async function ig(e,t){let n={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0};if(!t.length)return n;let r=await Promise.all(t.map(rg)),i={...n};for(let t=0;t<r.length;t++){let n=r[t],a=await e.transaction(ng,`readwrite`,e=>og(e,n));i.totalNotes+=a.totalNotes,i.totalEfforts+=a.totalEfforts,i.totalEquipment+=a.totalEquipment,i.totalBlocks+=a.totalBlocks,i.skippedUserOwned+=a.skippedUserOwned,i.deleted+=a.deleted,i.preservedPinned=(i.preservedPinned??0)+(a.preservedPinned??0),i.addedNotes+=a.addedNotes,i.updatedNotes+=a.updatedNotes,t+1<r.length&&await new Promise(e=>setTimeout(e,0))}return i}async function ag(e,t){return ig(e,[t])}async function og(e,t){let{write:n,ids:r,pagesBySlug:i,linkIds:a,tagIds:o}=t,s={totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0},c=e.readwrite(`meta`),l=new Set;for(let e of await c.getAll()){let t=lt(e?.key);t!==void 0&&l.add(t)}if(!Zh(await c.get(n.meta.key),n.expectedMeta))throw Error(`Seed checkpoint changed during import`);if(n.meta.schema!==9||n.manifest.schema!==9&&!Array.isArray(n.manifest.notebooks))throw Error(`Incompatible seed schema; recreate artifacts`);let u=e.readwrite(`notes`),d=n.chunkId?n.expectedMeta?.chunks[n.chunkId]?.noteIds??[]:[],f=new Set((n.chunkId?n.meta.chunks[n.chunkId]?.noteIds:void 0)??r),p=d.filter(e=>!f.has(e)),m=[...new Set([...r,...p])],h=await u.getMany(m),g=new Map(m.map((e,t)=>[e,h[t]])),_=n.meta.key.startsWith(`seed:`)?n.meta.key.slice(5):n.meta.key,v=Fh(n.meta.key),y=Ah(n.meta.key,n.meta.tier),b=[];for(let e of await c.getAll()){let t=e;if(!t||typeof t.key!=`string`||!t.key.startsWith(`seed:`)||t.key===n.meta.key)continue;let r=new Set;for(let e of Object.values(t.chunks??{}))for(let t of e.noteIds??[])r.add(t);b.push({key:t.key,sourceId:t.key.slice(5),rank:Ah(t.key,t.tier),meta:t,noteIds:r})}b.sort((e,t)=>t.rank-e.rank);let x=e=>{let t=-1;for(let n of b)n.noteIds.has(e)&&n.rank>t&&(t=n.rank);return t},S=m.filter(e=>{if(l.has(e))return!1;let t=g.get(e);if(!t)return f.has(e);if(t.seedOrigin!==`seed`)return!1;let r=x(e);return f.has(e)?y>=r:r<0&&t.seedChunkId===n.chunkId}),C=new Set(S),w=e.readwrite(`block_revisions`),ee=r.filter((e,t)=>C.has(e)&&g.get(e)?.rawContent!==n.rows[t].content),te=await w.getAllFromIndexMany(`by-note`,ee),ne=new Map(ee.map((e,t)=>[e,te[t]])),T=e.readwrite(`block_index`),re=e.readwrite(`block_efforts`),ie=e.readwrite(`block_equipment`),ae=e.readwrite(`note_tags`),oe=e.readwrite(`page_notes`),se=await T.getAllFromIndexMany(`by-note`,S),ce=await re.getAllFromIndexMany(`by-note`,S),le=await ie.getAllFromIndexMany(`by-note`,S),ue=await ae.getAllFromIndexMany(`by-note`,S),E=await oe.getAllFromIndexMany(`by-note`,S),de=new Map(S.map((e,t)=>[e,t])),fe=e.readwrite(`tags`),pe=[...o.keys()],me=await fe.getAllFromIndexMany(`by-label`,pe),he=new Map(pe.map((e,t)=>[e,me[t][0]])),ge=[],_e=[],ve=[],ye=[],be=[],xe=[],Se=[],Ce=[],we=[],Te=e.readwrite(`sessions`),Ee=e.readwrite(`events`),De=new Set;if(S.length>0){let e;try{e=await Te.getAllFromIndexMany(`by-note`,S)}catch{let t=await Te.getAll();e=S.map(e=>t.filter(t=>t.noteId===e))}for(let t=0;t<S.length;t++){let n=S[t];(g.get(n)?.retention===`session-pinned`||(e[t]?.length??0)>0)&&De.add(n)}}let Oe=n.rows.flatMap(e=>e.telemetry?.sessions.map(e=>e.id)??[]),ke=await Te.getMany(Oe),Ae=new Map(Oe.map((e,t)=>[e,ke[t]])),je=[],Me=[];for(let[e,t]of n.rows.entries()){let c=r[e],l=g.get(c);if(!C.has(c)){l&&l.seedOrigin!==`seed`&&s.skippedUserOwned++;continue}l?l.rawContent!==t.content&&s.updatedNotes++:s.addedNotes++,Ye(t.content,t.blocks,1,{registeredWidgets:Dh});let u=l?l.sourceRevision+(l.rawContent===t.content?0:1):1,d=0,f=ne.get(c)??[],p=l?l.rawContent===t.content?structuredClone(l.blocks):$h(l,t.content,u):f.length?Je(t.content,{sourceRevision:u,registeredWidgets:Dh,createId:()=>`seed:${c}:new${f.length}:${d++}`}):structuredClone(t.blocks);for(let e of Object.values(p)){let r=(ne.get(c)??[]).filter(t=>t.blockId===e.id).sort((e,t)=>t.version-e.version)[0],i=t.content.slice(e.from,e.to);if(l?.rawContent===t.content)continue;let a=r&&r.kind===e.kind&&r.rawContent===i&&r.dialect===e.dialect&&r.sport===e.sport;e.version=l?a?r.version:(r?.version??0)+1:1,(!l||!a)&&ve.push({noteId:c,blockId:e.id,version:e.version,kind:e.kind,rawContent:i,savedAt:n.meta.importedAt,...e.dialect?{dialect:e.dialect}:{},...e.sport?{sport:e.sport}:{}})}Ye(t.content,p,u,{registeredWidgets:Dh});let m=bh(t.content),h=typeof m.title==`string`&&m.title.trim()?m.title.trim():Qh(t.path),_=n.chunkId?zh(t.path,t.content,n.chunkId):void 0;if(!_)throw Error(`Unknown seed source family ${n.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 '${t.path}' — expected a real calendar day (YYYY-MM-DD)`);b=e}let x=t.commit??n.manifest.commit,S=l,w=De.has(c)||S?.retention===`session-pinned`?`session-pinned`:S?.retention===`schedule-pinned`?`schedule-pinned`:void 0,ee=typeof n.manifest.builtAt==`string`?Date.parse(n.manifest.builtAt):NaN,te=n.manifest.version===0?0:Number.isFinite(ee)&&ee>=9466848e5?ee:Number.isFinite(n.meta.importedAt)&&n.meta.importedAt>=9466848e5?n.meta.importedAt:Date.now(),T={...l,id:c,title:h,rawContent:t.content,sourceRevision:u,blocks:p,createdAt:te,...b===void 0?{}:{date:b},type:n.chunkId===`dashboards`?`dashboard`:`note`,sourceId:_,seedOrigin:`seed`,seedVersion:n.manifest.version,seedChunkId:n.chunkId??void 0,feedOrigin:`feed`,feedSourceId:v,sourcePath:t.path,...x?{seedCommit:x}:{},...w?{retention:w}:S?.retention?{retention:S.retention}:{},...w||S?.upstreamStatus?{upstreamStatus:`live`}:{}};b===void 0&&delete T.date,Zh(T,l)||_e.push(T);let re=new Map(Object.values(p).map(e=>[`${e.from}:${e.to}`,e])),ie=new Map(t.blockIndex.map(e=>[e.blockId,e])),oe=new Map;for(let e of t.blockIndex){let n=re.get(`${e.from}:${e.to}`);if(!n||n.kind!==e.dataType)throw Error(`Orphan seed projection`);oe.set(e.blockId,n.id);let r={...e,id:`${c}:${n.id}`,noteId:c,blockId:n.id,blockVersion:n.version,sourceRevision:u,noteTitle:h,sourceId:_,sourcePath:t.path,rawContent:t.content.slice(n.from,n.to)},i=se[de.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&Se.push(r)}let E=new Map,fe=new Set;for(let e of t.telemetry?.sessions??[]){if(ie.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed session pin`);let t=Ae.get(e.id);if(t&&t.noteId!==c)throw Error(`Seed session ${e.id} belongs to another note`);if(t&&(t.origin||!t.id.startsWith(`seed:`))){fe.add(e.id);continue}let n=t?.blockId??oe.get(e.blockId);if(!n)throw Error(`Orphan seed session pin`);let r=p[n];if(!t&&!r)throw Error(`Orphan seed session pin`);let i={...e,noteId:c,blockId:n,blockVersion:t?.blockVersion??r.version,blockContentId:t?.blockContentId??ie.get(e.blockId)?.blockContentId};je.push(i),E.set(i.id,i)}for(let e of t.telemetry?.events??[]){if(fe.has(e.resultId))continue;let t=E.get(e.resultId);if(!t)throw Error(`Orphan seed event result`);Me.push({...e,noteId:c,blockId:t.blockId,blockVersion:t.blockVersion,blockContentId:t.blockContentId})}for(let e of t.blockEfforts){let n=oe.get(e.blockId);if(!n||ie.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed effort link`);let r={...e,id:`${c}:${n}:${e.effortSlug}`,noteId:c,blockId:n,sourcePath:t.path},i=ce[de.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&Ce.push(i?{...r,createdAt:i.createdAt}:r)}for(let e of t.blockEquipment){let n=oe.get(e.blockId);if(!n||ie.get(e.blockId)?.dataType!==`wod`)throw Error(`Orphan seed equipment link`);let r={...e,id:`${c}:${n}:${e.equipmentSlug}`,noteId:c,blockId:n,sourcePath:t.path},i=le[de.get(c)].find(e=>e.id===r.id);(!i||i.isStatic===!0)&&we.push(i?{...r,createdAt:i.createdAt}:r)}let pe=de.get(c),me=new Set;for(let e of Sh(t.content)){let t=he.get(e.label);t?e.type&&!t.type&&(t={...t,type:e.type},ge.push(t),he.set(e.label,t)):(t={id:o.get(e.label),label:e.label,type:e.type,createdAt:n.meta.importedAt},ge.push(t),he.set(e.label,t)),!me.has(t.id)&&(me.add(t.id),ue[pe].find(e=>e.tagId===t.id)||xe.push({id:`${c}:${t.id}`,noteId:c,tagId:t.id}))}for(let e of ue[pe])me.has(e.tagId)||await ae.delete(e.id);let Te=m.slug;if(typeof Te==`string`&&i.has(Te)){let e=i.get(Te);ye.push({id:e,slug:Te,title:Qh(t.path),createdAt:te}),be.push({id:a.get(c),pageId:e,noteId:c,createdAt:te})}s.totalNotes++,s.totalBlocks+=Object.keys(p).length}let Ne=new Set(p.filter(e=>C.has(e)&&(De.has(e)||g.get(e)?.retention===`schedule-pinned`))),Pe=new Set(Se.map(e=>e.id)),D=new Set(Ce.map(e=>e.id)),Fe=new Set(we.map(e=>e.id));for(let e of se)for(let t of e)t.isStatic===!0&&!Pe.has(t.id)&&!Ne.has(t.noteId)&&await T.delete(t.id);for(let e of ce)for(let t of e)t.isStatic===!0&&!D.has(t.id)&&!Ne.has(t.noteId)&&await re.delete(t.id);for(let e of le)for(let t of e)t.isStatic===!0&&!Fe.has(t.id)&&!Ne.has(t.noteId)&&await ie.delete(t.id);for(let e of p){if(!C.has(e))continue;let t=g.get(e);if(!t||t.seedOrigin!==`seed`)continue;let n=De.has(e)||t.retention===`session-pinned`?`session-pinned`:t.retention===`schedule-pinned`?`schedule-pinned`:void 0;if(n){let e={...t,retention:n,upstreamStatus:`removed`};Zh(e,t)||_e.push(e),s.preservedPinned=(s.preservedPinned??0)+1;continue}let r=de.get(e);await u.delete(e);for(let e of ue[r])await ae.delete(e.id);for(let e of E[r])await oe.delete(e.id);s.deleted++}let Ie=async(t,i)=>{let a;try{a=e.readwrite(`property_overrides`)}catch{return}let o=v===`core`?[`notebook/defaults`]:[`feed:${v}`,...n.manifest.chunks.filter(e=>e.id.startsWith(`notebook.`)).map(e=>`notebook/${Lh(e.id)}`)],s=await a.getAll(),c=new Map(s.map(e=>[e.id,e])),l=new Set,u=[];for(let[e,a]of n.rows.entries()){let s=i(a.content);if(s)for(let i of o){let o=Yh(i,t,s.slug);l.add(o);let d=c.get(o);if(d&&d.seedOrigin!==`seed`)continue;let f={id:o,notebookId:i,kind:t,slug:s.slug,label:s.label,ownerNoteId:r[e],rawContent:a.content,payload:s,seedOrigin:`seed`,feedSourceId:v,updatedAt:n.meta.importedAt};(!d||!Zh(d,f))&&u.push(f)}}u.length>0&&await a.putMany(u);for(let e of s)e.seedOrigin===`seed`&&e.feedSourceId===v&&e.kind===t&&!l.has(e.id)&&(!e.ownerNoteId||!f.has(e.ownerNoteId))&&await a.delete(e.id)};return n.chunkId===`efforts`&&(s.totalEfforts=await eg(e.readwrite(`efforts`),u,Yp,`efforts`,_,y,b,d,n.rows,r,C,g,m),await Ie(`effort`,Yp)),n.chunkId===`equipment`&&(s.totalEquipment=await eg(e.readwrite(`equipment`),u,Xp,`equipment`,_,y,b,d,n.rows,r,C,g,m),await Ie(`equipment`,Xp)),_e.length&&await u.putMany(_e),ve.length&&await w.putMany(ve),await tg(T,Se,Se.map(e=>e.id)),await tg(re,Ce,Ce.map(e=>e.id)),await tg(ie,we,we.map(e=>e.id)),await tg(Te,je,je.map(e=>e.id)),await tg(Ee,Me,Me.map(e=>e.id)),ge.length&&await fe.putMany([...new Map(ge.map(e=>[e.id,e])).values()]),xe.length&&await ae.putMany(xe),await tg(e.readwrite(`page`),ye,ye.map(e=>e.id)),await tg(oe,be,be.map(e=>e.id)),await c.put(n.meta),s}function sg(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 cg(e){return 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=Ah(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=sg(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 lg(e){return 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=ku(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;Pu(n)&&(await r.put(Nu(n)),t++)}}return t})}new TextEncoder,new TextDecoder,new Set(ze.map(e=>e.slug));let ug=null;function dg(){return ug||=nm({efforts:[...Qp],equipment:[]}),ug}function fg(e,t){let n=bh(t);return(typeof n.title==`string`?n.title.trim().replace(/^["']|["']$/g,``):``)||t.match(/^#\s+(.+)$/m)?.[1]?.trim()||(e.split(`/`).at(-1)??e).replace(/\.md$/i,``).replace(/[-_]+/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}async function pg(e){let t=e.path.replace(/^\/+/,``);if(!t||t.split(`/`).includes(`..`))throw Error(`Invalid seed markdown path: '${e.path}'`);let n=e.markdown,r=e.uuid||await Xh(t),i=bh(n),a=e.title?.trim()||fg(t,n),o=vh(typeof i.date==`string`?i.date:void 0),s=e.date??o??e.createdAt??0,c=0,l=Je(n,{sourceRevision:1,registeredWidgets:Dh,createId:()=>`seed:${t}:${c++}`}),u=Ke(n,{registeredWidgets:Dh}),d=Object.values(l).map((i,o)=>{let c=u.find(e=>e.from===i.from&&e.to===i.to),l=i.kind===`wod`?Re(c?.scriptBlock?.content??n.slice(i.from,i.to)):void 0;return{id:`${r}:${i.id}`,noteId:r,blockId:i.id,blockVersion:1,sourceRevision:1,from:i.from,to:i.to,position:o,dataType:i.kind,...l?{blockContentId:l}:{},rawContent:n.slice(i.from,i.to),noteTitle:a,createdAt:s,isStatic:!0,...e.sourceId?{sourceId:e.sourceId}:{},sourcePath:t,...e.routeId?{routeId:e.routeId}:{}}}),f=e.referenceIndex??dg(),p=[],m=[];for(let e of d){if(e.dataType!==`wod`||!e.rawContent)continue;let n=rm(xp(Ke(e.rawContent,{registeredWidgets:Dh}).find(e=>e.scriptBlock)?.scriptBlock?.content??e.rawContent,{references:f}).statements),i=new Set;for(let a of n.efforts){let n=f.resolveEffort(a)?.slug;!n||i.has(n)||(i.add(n),p.push({id:`${e.id}:${n}`,noteId:r,blockId:e.blockId,...e.blockContentId?{blockContentId:e.blockContentId}:{},effortSlug:n,isStatic:!0,sourcePath:t,createdAt:s}))}let a=new Set;for(let i of n.equipment){let n=f.resolveEquipment(i)?.slug;!n||a.has(n)||(a.add(n),m.push({id:`${e.id}:${n}`,noteId:r,blockId:e.blockId,...e.blockContentId?{blockContentId:e.blockContentId}:{},equipmentSlug:n,isStatic:!0,sourcePath:t,createdAt:s}))}}return Jh({path:t,content:n,blocks:l,blockIndex:d,blockEfforts:p,blockEquipment:m,uuid:r,commit:e.commit??``,version:e.version??1})}new TextDecoder;async function mg(e,t){let n=e.readonly(`sessions`);try{return typeof n.countFromIndex==`function`?await n.countFromIndex(`by-note`,t)>0:(await n.getAllFromIndex(`by-note`,t)).length>0}catch{return(await n.getAll()).some(e=>e.noteId===t)}}async function hg(e,t){try{let n=e.readonly(`schedule_items`);return typeof n.countFromIndex==`function`?await n.countFromIndex(`by-note`,t)>0:(await n.getAllFromIndex(`by-note`,t)).length>0}catch{try{return(await e.readonly(`schedule_items`).getAll()).some(e=>e.noteId===t)}catch{return!1}}}async function gg(e,t){return e.transaction([`notes`,`attachments`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`schedule_items`,`efforts`,`equipment`,`property_overrides`,`sessions`,`meta`],`readwrite`,async e=>{let n=t.key.startsWith(`seed:`)?t.key.slice(5):t.key,r=Object.keys(t.chunks),i=r.length===0||Object.values(t.chunks).length>0,a=new Set,o=[];for(let[e,n]of Object.entries(t.chunks))if(n.noteIds?.length)for(let e of n.noteIds)a.add(e);else o.push(e);let s=o.length||i?await e.readwrite(`notes`).getAll():[];if(o.length)for(let e of s)e.seedOrigin===`seed`&&e.seedChunkId&&o.includes(e.seedChunkId)&&a.add(e.id);if(i)for(let e of s){let t=e;e.seedOrigin===`seed`&&e.feedSourceId===n&&(r.length===0||t.retention===`cached`||t.retention===`schedule-pinned`||t.retention===`session-pinned`)&&a.add(e.id)}let c=e.readwrite(`meta`),l=[],u=[],d=`${jh}${n}:`;for(let e of await c.getAll()){let n=e?.key;typeof n==`string`&&n.startsWith(d)&&u.push(n);let r=e;if(!r||typeof r.key!=`string`||!r.key.startsWith(`seed:`)||r.key===t.key)continue;let i=new Set;for(let e of Object.values(r.chunks??{}))for(let t of e.noteIds??[])i.add(t);l.push({key:r.key,sourceId:r.key.slice(5),rank:Ah(r.key,r.tier),meta:r,noteIds:i})}l.sort((e,t)=>t.rank-e.rank);let f=e=>l.some(t=>t.noteIds.has(e)),p=e.readwrite(`notes`),m=0,h=0,g=new Set,_=new Set;for(let i of a){if(f(i))continue;let a=await p.get(i);!a||a.seedOrigin!==`seed`||(a.feedSourceId!==n||r.length!==0&&a.retention!==`cached`&&a.retention!==`schedule-pinned`&&a.retention!==`session-pinned`)&&a.seedChunkId&&!t.chunks[a.seedChunkId]||(await vg(e,a,`unsubscribed`,_,g)===`pinned`?h++:m++)}await _g(e,_);let v=[{storeName:`efforts`,familyPathPrefix:`markdown/efforts/`,parse:Yp},{storeName:`equipment`,familyPathPrefix:`markdown/equipment/`,parse:Xp}];for(let{storeName:t,familyPathPrefix:r,parse:i}of v){let o=e.readwrite(t);for(let e of await o.getAll()){if(e.registrySource!==`bundled`||!(e.sourceId===n||e.ownerNoteId!==void 0&&a.has(e.ownerNoteId)&&(!e.sourceId||e.sourceId===t)||e.sourcePath!==void 0&&e.sourcePath.startsWith(r)&&g.has(e.sourcePath)))continue;let s=!1;for(let n of l){let r=n.meta.chunks?.[t]?.noteIds??[];for(let t of r){let r=await p.get(t);if(!r||r.seedOrigin!==`seed`)continue;let a=i(r.rawContent);if(a&&a.slug===e.slug){await o.put({...a,registrySource:`bundled`,ownerNoteId:r.id,sourceId:n.sourceId,feedSourceId:n.sourceId,sourcePath:r.sourcePath??``}),s=!0;break}}if(s)break}s||await o.delete(e.slug)}}try{let t=e.readwrite(`property_overrides`);for(let e of await t.getAll())e.seedOrigin===`seed`&&e.feedSourceId===n&&await t.delete(e.id)}catch{}for(let e of u)await c.delete(e);return await c.delete(t.key),{deleted:m,preservedPinned:h}})}async function _g(e,t){if(t.size===0)return;let n=e.readwrite(`notes`),r=e.readwrite(`note_tags`),i=e.readwrite(`tags`);for(let e of t){if(await r.countFromIndex(`by-tag`,e)>0)continue;let t=await i.get(e);t&&(t.contributions&&t.contributions.length>0||await n.get(`t/${t.type??`tag`}/${t.label}`)||await i.delete(e))}}async function vg(e,t,n,r,i){let a=e.readwrite(`notes`),o=await mg(e,t.id),s=t.retention===`session-pinned`||o,c=!s&&await hg(e,t.id),l=t.retention===`schedule-pinned`||c;if(s||l)return await a.put({...t,retention:s?`session-pinned`:`schedule-pinned`,upstreamStatus:n}),`pinned`;t.sourcePath&&i&&i.add(t.sourcePath),await a.delete(t.id);let u=e.readwrite(`attachments`);for(let e of await u.getAllFromIndex(`by-note`,t.id))await u.delete(e.id);let d=e.readwrite(`note_tags`);for(let e of await d.getAllFromIndex(`by-note`,t.id))r.add(e.tagId),await d.delete(e.id);let f=e.readwrite(`block_index`);for(let e of await f.getAllFromIndex(`by-note`,t.id))await f.delete(e.id);let p=e.readwrite(`block_efforts`);for(let e of await p.getAllFromIndex(`by-note`,t.id))await p.delete(e.id);let m=e.readwrite(`block_equipment`);for(let e of await m.getAllFromIndex(`by-note`,t.id))await m.delete(e.id);let h=e.readwrite(`page_notes`);for(let e of await h.getAllFromIndex(`by-note`,t.id))await h.delete(e.id);return`deleted`}async function yg(e,t){return gg(e,await e.readonly(`meta`).get(Ph(t))??Ih(Ph(t)))}async function bg(e,t,n){return e.transaction([`notes`,`attachments`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`schedule_items`,`sessions`,`meta`],`readwrite`,async e=>{let r=await e.readwrite(`notes`).getAll(),i=0,a=0,o=new Set;for(let s of r){let r=s;r.seedOrigin===`seed`&&r.feedSourceId===t&&r.seedChunkId===n&&(await vg(e,r,`unsubscribed`,o)===`pinned`?a++:i++)}return await _g(e,o),await e.readwrite(`meta`).delete(`${jh}${t}:${n}`),{deleted:i,preservedPinned:a}})}async function xg(e,t,n,r){return e.transaction([`notes`,`attachments`,`tags`,`note_tags`,`block_index`,`block_efforts`,`block_equipment`,`page_notes`,`schedule_items`,`sessions`],`readwrite`,async e=>{let i=await e.readwrite(`notes`).getAll(),a=0,o=0,s=new Set;for(let c of i){let i=c;i.seedOrigin===`seed`&&i.feedSourceId===t&&i.seedChunkId===n&&(r.has(i.id)||(await vg(e,i,`removed`,s)===`pinned`?o++:a++))}return await _g(e,s),{deleted:a,preservedPinned:o}})}new Set(ze.map(e=>e.slug));var Sg=class extends Error{status;constructor(e,t){super(e),this.status=t,this.name=`FeedSourceError`}},Cg=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 Sg(`feed manifest fetch failed: HTTP ${e.status}`,e.status);return Wh(await e.json())}resolveTargetUrl(e){if(/^https?:\/\//i.test(e)){let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`||t.username||t.password)throw new Sg(`Disallowed feed resource URL`);return t.toString()}let t=e.replace(/^\/+/,``);return`${this.baseUrl}${t}`}async fetchChunk(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new Sg(`feed chunk fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.json()}async fetchText(e){let t=await this.fetchImpl(this.resolveTargetUrl(e));if(!t.ok)throw new Sg(`feed text fetch failed: HTTP ${t.status} for ${e}`,t.status);return await t.text()}},wg=class{storageInstance;constructor(e){this.storageInstance=e}async getSeedMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async getMeta(e){return await this.storageInstance.readonly(`meta`).get(e)}async putMeta(e){await this.storageInstance.transaction([`meta`],`readwrite`,async t=>{await t.readwrite(`meta`).put(e)})}async deleteMeta(e){await this.storageInstance.transaction([`meta`],`readwrite`,async t=>{await t.readwrite(`meta`).delete(e)})}async getAllMeta(){return await this.storageInstance.readonly(`meta`).getAll()}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 ag(this.storageInstance,e)}applyChunks(e){return ig(this.storageInstance,e)}backfillFeedProvenance(){return cg(this.storageInstance)}migrateNotebookVocabulary(){return lg(this.storageInstance)}async removeSourceContent(e){return gg(this.storageInstance,e)}async removeSourceContentById(e){return yg(this.storageInstance,e)}async removeNotebookContent(e,t){return bg(this.storageInstance,e,t)}async reconcileRemovedRecords(e,t,n){return xg(this.storageInstance,e,t,n)}},Tg=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=Wh(e.manifest??await this.source.fetchManifest()),n=Ph(this.sourceId),r=e.stored===void 0?await this.storage.getSeedMeta(n):e.stored,i=r?.schema===9?r:void 0,a=i??Ih(n);if(t.version<a.seedVersion)throw Error(`Seed manifest is older than the stored checkpoint`);let o=new Set(t.chunks.map(e=>e.id)),s=[...t.chunks,...(t.notebooks??[]).filter(e=>!o.has(e.notebookId)).map(e=>({id:e.notebookId,path:e.indexPath,sha256:e.sha256,bytes:e.bytes,count:e.count}))],c=s.filter(t=>!(e.notebookIds!==void 0&&e.notebookIds!==null&&(e.notebookIds.length===0||!e.notebookIds.includes(t.id)&&t.id!==`efforts`&&t.id!==`equipment`))),l=!!(t.notebooks&&t.notebooks.length>0),u=c.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(!l&&(t.version!==a.seedVersion||t.builtAt!==a.builtAt))return!0;return i.sha256!==n.sha256});u.sort((e,t)=>Number(t.id===Nh)-Number(e.id===Nh));let d=Object.keys(a.chunks).filter(e=>!s.some(t=>t.id===e)),f={status:`current`,appliedChunks:0,totalNotes:0,totalEfforts:0,totalEquipment:0,totalBlocks:0,skippedUserOwned:0,deleted:0,preservedPinned:0,addedNotes:0,updatedNotes:0};if(!u.length&&!d.length&&t.version===a.seedVersion&&t.builtAt===a.builtAt)return f;f.status=`imported`;let p=(t,n,r,i,a)=>e.onProgress?.({phase:t,chunkId:n,completedChunks:f.appliedChunks,totalChunks:u.length,totalNotes:f.totalNotes,totalEfforts:f.totalEfforts,totalEquipment:f.totalEquipment,totalBlocks:f.totalBlocks,skippedUserOwned:f.skippedUserOwned,deleted:f.deleted,preservedPinned:f.preservedPinned,addedNotes:f.addedNotes,updatedNotes:f.updatedNotes,...r===void 0?{}:{recordId:r},...i===void 0?{}:{completedRecords:i},...a===void 0?{}:{totalRecords:a}}),m=e=>{f.totalNotes+=e.totalNotes,f.totalEfforts+=e.totalEfforts,f.totalEquipment+=e.totalEquipment,f.totalBlocks+=e.totalBlocks,f.skippedUserOwned+=e.skippedUserOwned,f.deleted+=e.deleted,f.preservedPinned=(f.preservedPinned??0)+(e.preservedPinned??0),f.addedNotes+=e.addedNotes,f.updatedNotes+=e.updatedNotes},h=(e,n,r)=>({...a,chunks:{...a.chunks,[e.id]:{sha256:e.sha256,version:n?.version,builtAt:n?.builtAt??t.builtAt,importedAt:this.now(),noteIds:r}},importedAt:this.now()}),g=0;if(u[0]?.id===`canvas`){let n=u[0],r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:s,noteIds:c}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id)),l=h(n,r,c);p(`applying`,n.id),m(await this.storage.applyChunk({chunkId:n.id,rows:s,manifest:t,expectedMeta:i,meta:l})),f.appliedChunks++,a=l,i=l,p(`committed`,n.id),e.onFirstPaintApplied?.(),g=1}let _=[];for(let n=g;n<u.length;n+=4){let r=u.slice(n,n+4),i=await Promise.all(r.map(async n=>{let r=t.notebooks?.find(e=>e.notebookId===n.id),{rows:i,noteIds:s}=await this.fetchChunkData(n,r,a,e,p,o.has(n.id));return{chunk:n,notebook:r,rows:i,noteIds:s}}));_.push(...i)}let v=[];for(let e of _){let n=h(e.chunk,e.notebook,e.noteIds);v.push({chunkId:e.chunk.id,rows:e.rows,manifest:t,expectedMeta:i,meta:n}),a=n,i=n}for(let e of d){let n={...a.chunks};delete n[e];let r={...a,chunks:n,importedAt:this.now()};v.push({chunkId:e,rows:[],manifest:t,expectedMeta:i,meta:r}),a=r,i=r}let y={...a,schema:9,seedVersion:t.version,builtAt:t.builtAt,importedAt:this.now()};if(v.push({chunkId:null,rows:[],manifest:t,expectedMeta:i,meta:y}),v.length>0){if(_.length>0&&p(`applying`,_[0].chunk.id),this.storage.applyChunks){m(await this.storage.applyChunks(v)),f.appliedChunks+=_.length;for(let e of _)p(`committed`,e.chunk.id)}else for(let e of v)m(await this.storage.applyChunk(e)),e.chunkId&&_.some(t=>t.chunk.id===e.chunkId)&&(f.appliedChunks++,p(`committed`,e.chunkId))}return p(`finalizing`,null),f}async fetchSingleRecordRow(e){if(e.recordPath)try{let t=await this.source.fetchChunk(e.recordPath);return Array.isArray(t)?qh(t):[Jh(t)]}catch(t){if(!e.rawUrl&&!/\.md$/i.test(e.path))throw t}let t=e.rawUrl??e.path,n=this.source.fetchText?await this.source.fetchText(t):String(await this.source.fetchChunk(t));return[await pg({path:e.path,markdown:n,uuid:e.uuid,commit:e.commit,version:e.version,title:e.title,date:e.date})]}async fetchChunkData(e,t,n,r,i,a){let o,s=e.records,c=!!(n.chunks[e.id]&&r.granularRecords&&(t?.indexPath||e.records));if(!a||c||r.granularRecords&&e.records&&e.records.length>0){if(t?.indexPath&&(s=Gh(await this.source.fetchChunk(t.indexPath)).records),s&&s.length>0){let t=!r.forceAll&&this.storage.getNoteCommits?await this.storage.getNoteCommits(s.map(e=>e.uuid)):void 0,n=t?s.filter(e=>t.get(e.uuid)!==e.commit):s;if(a&&c&&n.length>s.length/2){if(i(`fetching`,e.id),o=qh(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else{let t=[];for(let r=0;r<n.length;r+=8){let a=n.slice(r,r+8);i(`fetching`,e.id,a[0]?.uuid,r,n.length);let o=await Promise.all(a.map(e=>this.fetchSingleRecordRow(e)));for(let e of o)t.push(...e)}o=t}}else if(a){if(i(`fetching`,e.id),o=qh(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`)}else o=[]}else if(i(`fetching`,e.id),o=qh(await this.source.fetchChunk(e.path)),o.length!==e.count)throw Error(`Seed chunk count mismatch`);let l=s&&s.length>0?s.map(e=>e.uuid):await Promise.all(o.map(e=>Xh(e.path)));return{rows:o,noteIds:l}}};function Eg(e,t){return e===void 0||e<=0||t>e?`import`:t===e?`current`:`server-stale`}function Dg(e,t){return e?.schema!==void 0&&e.schema!==9?!1:e?.seedVersion!=null&&e.seedVersion>0&&e.seedVersion===t}function Og(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 kg(e,t,n){let r=e?.claim;return!!r&&r.owner!==t&&n-r.at<45e3}async function Ag(e,t){if(e.offlinePolicy)return e.offlinePolicy;if(e.id===`core`)return`offline-full`;try{let n=(await t.getMeta?.(`feed:subscriptions`))?.entries?.[e.id]?.offlinePolicy;if(n===`index-only`||n===`offline-full`)return n}catch{}return`index-only`}async function jg(e,t,n={}){let{storage:r,owner:i}=t,a=t.now,o=Ph(e.id),s={outcome:`current`,error:null,manifestChecked:!1,hadCheckpoint:!1};try{let c=await r.getSeedMeta(o);s.hadCheckpoint=(c?.seedVersion??0)>0;let l=await Ag(e,r);if(l===`offline-full`&&!t.force&&!t.probeManifests&&Dg(c,e.embeddedVersion))return s.outcome=`current`,s;if(kg(c,i,a()))return s.outcome=`busy`,s;let u=Wh(await e.source.fetchManifest());if(s.manifestChecked=!0,s.manifest=u,r.putMeta){let t=`catalog:${e.id}`,n=(await r.getMeta(t).catch(()=>void 0))?.manifest;(!n||n.version!==u.version||n.builtAt!==u.builtAt||n.commit!==u.commit||n.schema!==u.schema||(n.notebooks?.length??0)!==(u.notebooks?.length??0)||n.chunks.length!==u.chunks.length)&&await r.putMeta({key:t,feedId:e.id,manifest:u,updatedAt:a()}).catch(()=>void 0)}let d=Array.isArray(u.notebooks)&&u.notebooks.length>0;if(l===`index-only`&&d){let n=u.notebooks.filter(t=>e.notebookIds!==void 0&&e.notebookIds!==null?e.notebookIds.length!==0&&e.notebookIds.includes(t.notebookId):!0),i=await Promise.all(n.map(t=>r.getMeta?.(Mh(e.id,t.notebookId)).catch(()=>void 0)));if(t.background&&!e.autoSyncOn)return s.outcome=n.some((e,t)=>{let n=i[t];return!n?.index||e.version>(n.index.version??0)||!!(e.sha256&&n.index.sha256!==e.sha256)})?`update-pending`:`current`,s;let o=!1,c=0;for(let[s,l]of n.entries()){let n=i[s];if(!(t.force===!0||!n?.index||l.version>(n.index.version??0)||l.sha256&&n.index.sha256!==l.sha256))continue;let u=Gh(await e.source.fetchChunk(l.indexPath));await r.putMeta?.({key:Mh(e.id,l.notebookId),feedId:e.id,notebookId:l.notebookId,index:u,updatedAt:a()});let d=new Set(u.records.map(e=>e.uuid)),f=await r.reconcileRemovedRecords?.(e.id,l.notebookId,d);c+=f?.preservedPinned??0,o=!0}return s.outcome=o?`imported`:`current`,o&&(s.applied=!0,s.importedVersion=u.version,s.added=0,s.updated=0),c>0&&(s.preservedPinned=c),s}let f=t.force?`import`:Eg(c?.seedVersion,u.version);if(f===`server-stale`)return s.outcome=`server-stale`,s;if(c&&c.schema!==9)throw Error(`Incompatible seed checkpoint; recreate storage`);let p=u.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`)));if(t.background&&!e.autoSyncOn)return s.outcome=p.some(e=>{let t=u.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;let m=!!(c&&Object.keys(c.chunks).length>0),h=new Set([...u.chunks.map(e=>e.id),...(u.notebooks??[]).map(e=>e.notebookId)]),g=!m||p.every(e=>c?.chunks[e.id]?.sha256===e.sha256),_=m&&Object.keys(c.chunks).some(e=>!h.has(e));if(!t.force&&f===`current`&&c?.schema===9&&c.builtAt===u.builtAt&&g&&!_)return s.outcome=`current`,s;let v={...c??Ih(o),...e.tier?{tier:e.tier}:{},claim:{owner:i,at:a()}};await r.putSeedMeta(v,c??null);try{let i=await new Tg(r,e.source,e.id,a).applyAll({forceAll:t.force===!0,onFirstPaintApplied:()=>n.onFirstPaint?.(),onProgress:n.onProgress,notebookIds:e.notebookIds,granularRecords:!t.force&&!!(e.granularRecords&&m),manifest:u,stored:v});s.outcome=`imported`,i.status===`imported`&&(s.applied=!0,s.importedVersion=u.version,s.added=i.addedNotes,s.updated=i.updatedNotes,i.preservedPinned&&(s.preservedPinned=i.preservedPinned))}finally{try{let e=await r.getSeedMeta(o);e?.claim?.owner===i&&await r.putSeedMeta({...e,claim:null},e)}catch(t){console.warn(`[feedSync] ${e.id} claim release skipped after concurrent update`,t)}}return s}catch(t){return console.warn(`[feedSync] ${e.id} seed sync failed`,t),s.outcome=`error`,s.error=Og(t),s}}let Mg=self;Mg.onmessage=e=>{if(e.data.type!==`run`)return;let t=e.data;(async()=>{let e=new wg(new ed({dbName:t.dbName,...t.userId?{getUserId:()=>t.userId}:{}})),n=[];try{for(let r of t.sources){let i=await jg({id:r.id,label:r.label,source:new Cg(r.url),embeddedVersion:r.embeddedVersion,autoSyncOn:r.autoSyncOn,...r.tier?{tier:r.tier}:{},notebookIds:r.notebookIds,granularRecords:r.granularRecords??!0,...r.offlinePolicy?{offlinePolicy:r.offlinePolicy}:{}},{storage:e,owner:t.owner,now:Date.now,force:t.force,probeManifests:t.probeManifests,background:t.background},{onProgress:e=>Mg.postMessage({type:`progress`,sourceId:r.id,progress:e}),onFirstPaint:()=>Mg.postMessage({type:`first-paint`,sourceId:r.id})});Mg.postMessage({type:`source-result`,sourceId:r.id,result:i}),n.push(i.outcome)}}finally{await e.storageInstance.close().catch(()=>void 0)}Mg.postMessage({type:`done`,outcomes:n})})()}})();
|
|
22
|
+
//# sourceMappingURL=feedSync.worker-XrQNJWMM.js.map
|