@bitcobblers/wod-wiki-lang 0.54.2205 → 0.56.2208

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.
@@ -0,0 +1,1172 @@
1
+ import { MetricType, MetricContainer, getTagReference } from '@bitcobblers/wod-wiki-core';
2
+
3
+ // src/metrics/hints.ts
4
+ var CONSUMED_HINTS = {
5
+ /** IntervalLogicStrategy: treats the block as an EMOM-style repeating interval. */
6
+ REPEATING_INTERVAL: "behavior.repeating_interval",
7
+ /** GenericTimerStrategy: block cannot be skipped past until timer:complete fires. */
8
+ REQUIRED_TIMER: "behavior.required_timer",
9
+ /** GenericTimerStrategy: injects a rest block between repeating intervals. */
10
+ INJECT_REST: "behavior.inject_rest",
11
+ /** LabelComposer: overrides the generated label with a workout-type name. */
12
+ LABEL_AMRAP: "workout.amrap",
13
+ LABEL_EMOM: "workout.emom",
14
+ LABEL_TABATA: "workout.tabata",
15
+ LABEL_FOR_TIME: "workout.for_time"
16
+ };
17
+ var CONSUMED_HINT_KEYS = Object.values(CONSUMED_HINTS);
18
+ function metricsOf(source) {
19
+ if (!source) return [];
20
+ if (Array.isArray(source.rawMetrics)) return source.rawMetrics;
21
+ const m = source.metrics;
22
+ if (!m) return [];
23
+ if (Array.isArray(m)) return m;
24
+ return m.rawMetrics ?? [];
25
+ }
26
+ function hintMetric(hint, origin = "dialect", icon) {
27
+ return { type: MetricType.Hint, value: hint, image: hint, origin, ...icon ? { icon } : {} };
28
+ }
29
+ function hintsToContainer(hints, existing, origin = "dialect") {
30
+ const container = existing ?? MetricContainer.empty("dialect");
31
+ const seen = new Set(getHints(container));
32
+ for (const hint of hints) {
33
+ if (seen.has(hint)) continue;
34
+ seen.add(hint);
35
+ container.add(hintMetric(hint, origin));
36
+ }
37
+ return container;
38
+ }
39
+ function getHints(source) {
40
+ return metricsOf(source).filter((m) => m.type === MetricType.Hint && typeof m.value === "string").map((m) => m.value);
41
+ }
42
+ function hasHint(source, hint) {
43
+ return metricsOf(source).some((m) => m.type === MetricType.Hint && m.value === hint);
44
+ }
45
+
46
+ // src/metrics/units/UnitRegistry.ts
47
+ var LEADING_WORD = /^([a-zA-Z]+)([\s\S]*)$/;
48
+ var UnitSet = class _UnitSet {
49
+ /** Definitions in priority order (later entries override earlier on token collision). */
50
+ defs;
51
+ byToken;
52
+ constructor(defs = []) {
53
+ this.defs = defs;
54
+ this.byToken = /* @__PURE__ */ new Map();
55
+ for (const def of defs) {
56
+ this.byToken.set(def.canonical.toLowerCase(), def);
57
+ for (const alias of def.aliases) {
58
+ this.byToken.set(alias.toLowerCase(), def);
59
+ }
60
+ }
61
+ }
62
+ /** Look up a unit by canonical spelling or alias (case-insensitive). */
63
+ get(token) {
64
+ return this.byToken.get(token.trim().toLowerCase());
65
+ }
66
+ /** Whether the token is a recognized unit (canonical or alias). */
67
+ has(token) {
68
+ return this.byToken.has(token.trim().toLowerCase());
69
+ }
70
+ /**
71
+ * Peel a leading unit token off the front of `text`.
72
+ *
73
+ * Returns `null` when the first whitespace/letter-delimited word is not a
74
+ * recognized unit — this is what keeps `5 Burpees` from ever fusing while
75
+ * `4 mile Run` → `{ unit: mile, rest: "Run" }`.
76
+ */
77
+ consumeLeading(text) {
78
+ const m = LEADING_WORD.exec(text.trimStart());
79
+ if (!m) return null;
80
+ const token = m[1];
81
+ const unit = this.get(token);
82
+ if (!unit) return null;
83
+ return { unit, token, rest: m[2].trim() };
84
+ }
85
+ /**
86
+ * Compose into a new set. Later units override earlier ones on token
87
+ * collision — the mechanism a Dialect uses to add or redefine units.
88
+ */
89
+ extend(...units) {
90
+ return new _UnitSet([...this.defs, ...units]);
91
+ }
92
+ /** All definitions in priority order. */
93
+ toArray() {
94
+ return [...this.defs];
95
+ }
96
+ };
97
+ var STANDARD_UNITS = [
98
+ // length
99
+ { canonical: "m", dimension: "length", aliases: ["meter", "meters", "metre", "metres"] },
100
+ { canonical: "km", dimension: "length", aliases: ["kilometer", "kilometers", "kilometre", "kilometres"] },
101
+ { canonical: "cm", dimension: "length", aliases: ["centimeter", "centimeters", "centimetre", "centimetres"] },
102
+ { canonical: "mm", dimension: "length", aliases: ["millimeter", "millimeters", "millimetre", "millimetres"] },
103
+ { canonical: "ft", dimension: "length", aliases: ["foot", "feet"] },
104
+ { canonical: "in", dimension: "length", aliases: ["inch", "inches"] },
105
+ { canonical: "yd", dimension: "length", aliases: ["yard", "yards"] },
106
+ { canonical: "mi", dimension: "length", aliases: ["mile", "miles"] },
107
+ // mass
108
+ { canonical: "kg", dimension: "mass", aliases: ["kilo", "kilos", "kilogram", "kilograms"] },
109
+ { canonical: "g", dimension: "mass", aliases: ["gram", "grams"] },
110
+ { canonical: "lb", dimension: "mass", aliases: ["lbs", "pound", "pounds"] },
111
+ { canonical: "bw", dimension: "mass", aliases: ["bodyweight"] },
112
+ // energy
113
+ { canonical: "cal", dimension: "energy", aliases: ["cals", "calorie", "calories"] },
114
+ { canonical: "kcal", dimension: "energy", aliases: ["kcals", "kilocalorie", "kilocalories"] }
115
+ ];
116
+ var UnitRegistry = {
117
+ /** The base catalog used by the base Units Dialect. */
118
+ standard() {
119
+ return new UnitSet(STANDARD_UNITS);
120
+ },
121
+ /** Build a set from arbitrary definitions. */
122
+ of(units) {
123
+ return new UnitSet(units);
124
+ }
125
+ };
126
+
127
+ // src/utils/formatTime.ts
128
+ var formatTimeMMSS = (ms) => {
129
+ if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
130
+ return "--:--";
131
+ }
132
+ const isNegative = ms < 0;
133
+ const absMs = Math.abs(ms);
134
+ const totalSeconds = Math.floor(absMs / 1e3);
135
+ const minutes = Math.floor(totalSeconds / 60);
136
+ const seconds = totalSeconds % 60;
137
+ const sign = isNegative ? "-" : "";
138
+ return `${sign}${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
139
+ };
140
+ var formatTimeHHMMSS = (ms) => {
141
+ if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
142
+ return "--:--:--";
143
+ }
144
+ const isNegative = ms < 0;
145
+ const absMs = Math.abs(ms);
146
+ const totalSeconds = Math.floor(absMs / 1e3);
147
+ const hours = Math.floor(totalSeconds / 3600);
148
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
149
+ const seconds = totalSeconds % 60;
150
+ const sign = isNegative ? "-" : "";
151
+ return `${sign}${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
152
+ };
153
+ var formatTimePrecise = (ms) => {
154
+ if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
155
+ return "--:--.--";
156
+ }
157
+ const isNegative = ms < 0;
158
+ const absMs = Math.abs(ms);
159
+ const totalSeconds = Math.floor(absMs / 1e3);
160
+ const minutes = Math.floor(totalSeconds / 60);
161
+ const seconds = totalSeconds % 60;
162
+ const centiseconds = Math.floor(absMs % 1e3 / 10);
163
+ const sign = isNegative ? "-" : "";
164
+ return `${sign}${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}.${centiseconds.toString().padStart(2, "0")}`;
165
+ };
166
+ var formatSecondsMMSS = (seconds) => {
167
+ if (seconds === void 0 || seconds === null || !Number.isFinite(seconds)) {
168
+ return "--:--";
169
+ }
170
+ const isNegative = seconds < 0;
171
+ const absSeconds = Math.abs(seconds);
172
+ const mins = Math.floor(absSeconds / 60);
173
+ const secs = Math.floor(absSeconds % 60);
174
+ const sign = isNegative ? "-" : "";
175
+ return `${sign}${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
176
+ };
177
+ var formatSecondsHHMMSS = (seconds) => {
178
+ if (seconds === void 0 || seconds === null || !Number.isFinite(seconds)) {
179
+ return "--:--:--";
180
+ }
181
+ const isNegative = seconds < 0;
182
+ const absSeconds = Math.abs(seconds);
183
+ const hours = Math.floor(absSeconds / 3600);
184
+ const mins = Math.floor(absSeconds % 3600 / 60);
185
+ const secs = Math.floor(absSeconds % 60);
186
+ const sign = isNegative ? "-" : "";
187
+ return `${sign}${hours.toString().padStart(2, "0")}:${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
188
+ };
189
+ var formatDurationSmart = (ms) => {
190
+ if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
191
+ return "--:--";
192
+ }
193
+ const absMs = Math.abs(ms);
194
+ const totalSeconds = Math.floor(absMs / 1e3);
195
+ if (totalSeconds >= 3600) {
196
+ return formatTimeHHMMSS(ms);
197
+ }
198
+ return formatTimeMMSS(ms);
199
+ };
200
+ var formatDurationCompact = (ms) => {
201
+ if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
202
+ return "--:--";
203
+ }
204
+ const absMs = Math.abs(ms);
205
+ const totalSeconds = Math.floor(absMs / 1e3);
206
+ const minutes = Math.floor(totalSeconds / 60);
207
+ const seconds = totalSeconds % 60;
208
+ if (minutes < 10) {
209
+ return `${minutes}:${seconds.toString().padStart(2, "0")}`;
210
+ }
211
+ return formatTimeMMSS(ms);
212
+ };
213
+ var formatTimestamp = (date) => {
214
+ if (!date) return "running";
215
+ const dateObj = typeof date === "number" ? new Date(date) : date;
216
+ return dateObj.toLocaleTimeString("en-US", {
217
+ hour12: false,
218
+ hour: "2-digit",
219
+ minute: "2-digit",
220
+ second: "2-digit"
221
+ });
222
+ };
223
+ var TIME_LIKE_TYPES = /* @__PURE__ */ new Set([
224
+ MetricType.Duration,
225
+ MetricType.Time,
226
+ MetricType.Elapsed,
227
+ MetricType.Total
228
+ ]);
229
+ function isTimeLikeMetric(type) {
230
+ return TIME_LIKE_TYPES.has(type);
231
+ }
232
+ function baseText(metric) {
233
+ if (metric.image) return metric.image;
234
+ if (metric.value === void 0 || metric.value === null) return metric.type;
235
+ if (typeof metric.value === "object") {
236
+ const v = metric.value;
237
+ if ("text" in v) return String(v.text);
238
+ if ("current" in v) return `Round ${v.current}`;
239
+ return JSON.stringify(metric.value);
240
+ }
241
+ return String(metric.value);
242
+ }
243
+ function computeLabel(metric, _surface) {
244
+ if (isTimeLikeMetric(metric.type) && typeof metric.value === "number") {
245
+ return formatDurationSmart(metric.value);
246
+ }
247
+ const base = baseText(metric);
248
+ if (metric.type === MetricType.Rounds || metric.type === "rounds") {
249
+ const trimmed = base.trim();
250
+ if (/^\d+$/.test(trimmed)) {
251
+ const n = Number(trimmed);
252
+ return `${base} ${n === 1 ? "Round" : "Rounds"}`;
253
+ }
254
+ }
255
+ return base;
256
+ }
257
+ function buildTooltip(metric) {
258
+ const parts = [];
259
+ parts.push(`Type: ${metric.type}`);
260
+ if (metric.value !== void 0) parts.push(`Value: ${metric.value}`);
261
+ if (metric.origin) parts.push(`Origin: ${metric.origin}`);
262
+ if (metric.sourceBlockKey) parts.push(`Block: ${metric.sourceBlockKey}`);
263
+ if (metric.timestamp) parts.push(`Time: ${metric.timestamp.toISOString()}`);
264
+ return parts.join("\n");
265
+ }
266
+ var COLUMN_LABEL_MAP = {
267
+ duration: "Duration",
268
+ rep: "Reps",
269
+ effort: "Effort",
270
+ distance: "Distance",
271
+ rounds: "Rounds",
272
+ resistance: "Resistance",
273
+ action: "Action",
274
+ increment: "Increment",
275
+ metric: "Metric",
276
+ label: "Label",
277
+ text: "Text",
278
+ custom: "Custom",
279
+ calculated: "Calculated",
280
+ "current-round": "Current Round",
281
+ volume: "Volume",
282
+ intensity: "Intensity",
283
+ load: "Load",
284
+ work: "Work",
285
+ lap: "Lap",
286
+ group: "Group",
287
+ time: "Time",
288
+ elapsed: "Elapsed",
289
+ total: "Total",
290
+ "system-time": "System Time",
291
+ spans: "Spans",
292
+ system: "System",
293
+ rir: "RIR",
294
+ "session-rpe": "Session RPE",
295
+ "session-load": "Session Load",
296
+ "met-score": "MET Score",
297
+ tis: "TIS",
298
+ sound: "Sound"
299
+ };
300
+ function humanizeMetricKey(value) {
301
+ const spaced = value.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").trim();
302
+ if (spaced.length === 0) return "";
303
+ return spaced.split(/\s+/).map((word) => {
304
+ if (word === word.toUpperCase()) return word;
305
+ if (/^[A-Z]{2,}$/.test(word)) return word;
306
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
307
+ }).join(" ");
308
+ }
309
+ function computeColumnLabel(type) {
310
+ const key = String(type).trim();
311
+ const normalized = key.toLowerCase();
312
+ return COLUMN_LABEL_MAP[normalized] ?? humanizeMetricKey(key);
313
+ }
314
+ function tagReferenceFor(tagIndex, slug) {
315
+ const resolved = resolveTagContributions(tagIndex, slug);
316
+ const sound = resolved.metrics.find(
317
+ (contribution) => contribution.type === MetricType.Sound && typeof contribution.value === "string"
318
+ );
319
+ return {
320
+ slug,
321
+ label: slug,
322
+ ...resolved.functions.length > 0 ? { functions: [...resolved.functions] } : {},
323
+ ...sound ? { soundProfileId: sound.value } : {}
324
+ };
325
+ }
326
+ function collectTagReferences(metrics, into = []) {
327
+ for (const metric of metrics) {
328
+ const reference = getTagReference(metric.metadata);
329
+ if (!reference) continue;
330
+ if (into.some((existing) => existing.slug === reference.slug)) continue;
331
+ into.push(reference);
332
+ }
333
+ return into;
334
+ }
335
+ var TAG_MARKER_PREFIX = "tag.";
336
+ var MAX_TAG_CONTRIBUTION_DEPTH = 8;
337
+ var EMPTY = { metrics: [], functions: [], tags: [] };
338
+ function resolveTagContributions(tagIndex, slug) {
339
+ if (!tagIndex) return EMPTY;
340
+ const metrics = [];
341
+ const functions = [];
342
+ const tags = [];
343
+ const seenFunctions = /* @__PURE__ */ new Set();
344
+ const visited = /* @__PURE__ */ new Set();
345
+ const walk = (currentSlug, depth) => {
346
+ if (depth > MAX_TAG_CONTRIBUTION_DEPTH) return;
347
+ if (visited.has(currentSlug)) return;
348
+ const definition = tagIndex.resolve(currentSlug);
349
+ if (!definition) return;
350
+ visited.add(currentSlug);
351
+ tags.push(currentSlug);
352
+ for (const contribution of definition.contributions) {
353
+ if (contribution.kind === "metric") metrics.push(contribution);
354
+ else if (contribution.kind === "function") {
355
+ if (!seenFunctions.has(contribution.name)) {
356
+ seenFunctions.add(contribution.name);
357
+ functions.push(contribution.name);
358
+ }
359
+ }
360
+ }
361
+ for (const contribution of definition.contributions) {
362
+ if (contribution.kind === "tag") walk(contribution.slug, depth + 1);
363
+ }
364
+ };
365
+ walk(slug, 0);
366
+ return { metrics, functions, tags };
367
+ }
368
+ function findTagContributionCycles(tagIndex) {
369
+ if (!tagIndex) return [];
370
+ const cycles = [];
371
+ const seen = /* @__PURE__ */ new Set();
372
+ const walk = (slug, path, onPath) => {
373
+ if (onPath.has(slug)) {
374
+ const start = path.indexOf(slug);
375
+ if (start >= 0) {
376
+ const cycle = [...path.slice(start), slug];
377
+ const key = cycleKey(cycle);
378
+ if (!seen.has(key)) {
379
+ seen.add(key);
380
+ cycles.push(cycle);
381
+ }
382
+ }
383
+ return;
384
+ }
385
+ const definition = tagIndex.resolve(slug);
386
+ if (!definition) return;
387
+ const nextPath = [...path, slug];
388
+ const nextOnPath = new Set(onPath);
389
+ nextOnPath.add(slug);
390
+ for (const contribution of definition.contributions) {
391
+ if (contribution.kind === "tag") walk(contribution.slug, nextPath, nextOnPath);
392
+ }
393
+ };
394
+ for (const definition of tagIndex.list()) {
395
+ walk(definition.slug, [], /* @__PURE__ */ new Set());
396
+ }
397
+ return cycles;
398
+ }
399
+ function cycleKey(cycle) {
400
+ const nodes = cycle.slice(0, -1);
401
+ if (nodes.length === 0) return "";
402
+ let smallest = 0;
403
+ for (let index = 1; index < nodes.length; index++) {
404
+ if (nodes[index] < nodes[smallest]) smallest = index;
405
+ }
406
+ return [...nodes.slice(smallest), ...nodes.slice(0, smallest)].join(">");
407
+ }
408
+ function tagMarkerType(slug) {
409
+ return `${TAG_MARKER_PREFIX}${slug}`;
410
+ }
411
+ function tagMarkerSlug(type) {
412
+ if (!type.startsWith(TAG_MARKER_PREFIX)) return void 0;
413
+ const slug = type.slice(TAG_MARKER_PREFIX.length);
414
+ return slug.length > 0 ? slug : void 0;
415
+ }
416
+ function tagMarkerSlugs(metrics) {
417
+ const slugs = [];
418
+ for (const metric of metrics) {
419
+ const slug = tagMarkerSlug(metric.type);
420
+ if (slug !== void 0 && !slugs.includes(slug)) slugs.push(slug);
421
+ }
422
+ return slugs;
423
+ }
424
+ function isEquationMetricValue(value) {
425
+ if (typeof value !== "string") return false;
426
+ const trimmed = value.trim();
427
+ if (!trimmed) return false;
428
+ if (/^[+-]?\d+(?:\.\d+)?(?:\s*[A-Za-z%/][\w%/.-]*)?$/.test(trimmed)) return false;
429
+ if (/^[a-zA-Z0-9_]+(?:-[a-zA-Z0-9_]+)*$/.test(trimmed)) return false;
430
+ return /[*/+()]|\s-\s|->|\b(?:convert|sum|avg|min|max|count|last|round|floor|ceil|abs|clamp|lookup|when|and|or)\b/.test(trimmed);
431
+ }
432
+ function tagContributionMetrics(contributions, origin = "parser") {
433
+ return contributions.filter((c) => !c.type.trim().startsWith("summaries.") && !isEquationMetricValue(c.value)).map((contribution) => ({
434
+ type: contribution.type,
435
+ value: contribution.value,
436
+ origin,
437
+ image: contribution.unit ? `${String(contribution.value)} ${contribution.unit}` : String(contribution.value),
438
+ ...contribution.unit ? { unit: contribution.unit } : {}
439
+ }));
440
+ }
441
+ function isRestMetric(metric) {
442
+ const t = metric.type.toLowerCase();
443
+ if (t !== "effort") return false;
444
+ const v = metric.value ?? metric.image ?? "";
445
+ return v.trim().toLowerCase() === "rest";
446
+ }
447
+ function computeTone(metric, rest) {
448
+ if (rest) return "rest";
449
+ const t = metric.type.toLowerCase();
450
+ const toneMap = {
451
+ time: "time",
452
+ duration: "time",
453
+ elapsed: "time",
454
+ total: "time",
455
+ spans: "time",
456
+ rep: "rep",
457
+ effort: "effort",
458
+ distance: "distance",
459
+ rounds: "rounds",
460
+ increment: "rounds",
461
+ "current-round": "rounds",
462
+ action: "action",
463
+ resistance: "resistance",
464
+ text: "muted",
465
+ label: "muted",
466
+ group: "muted",
467
+ lap: "muted",
468
+ system: "system",
469
+ "system-time": "system",
470
+ volume: "rep",
471
+ intensity: "effort",
472
+ load: "resistance",
473
+ work: "effort",
474
+ rir: "effort",
475
+ "session-rpe": "effort",
476
+ "session-load": "resistance",
477
+ "met-score": "distance",
478
+ tis: "action",
479
+ sound: "system",
480
+ metric: "effort",
481
+ custom: "muted",
482
+ calculated: "effort"
483
+ };
484
+ return toneMap[t] ?? "unknown";
485
+ }
486
+ function createPolicy() {
487
+ const policy = {
488
+ isStructural(metric) {
489
+ const t = metric.type;
490
+ if (t === MetricType.Group || t === "group") {
491
+ const img = metric.image ?? "";
492
+ return img === "+" || img === "-";
493
+ }
494
+ return t === MetricType.Lap || t === "lap";
495
+ },
496
+ isHidden(metric, surface) {
497
+ if (this.isStructural(metric)) {
498
+ return surface !== "debug";
499
+ }
500
+ const t = metric.type;
501
+ if ((t === MetricType.Sound || t === "sound") && surface !== "debug") return true;
502
+ if (t.startsWith(TAG_MARKER_PREFIX) && surface !== "debug") return true;
503
+ if (surface === "review-grid-column") {
504
+ if (t === MetricType.Elapsed || t === "elapsed" || t === MetricType.Total || t === "total") return true;
505
+ if (t === MetricType.System || t === "system") return true;
506
+ }
507
+ return false;
508
+ },
509
+ present(metric, surface) {
510
+ const structural = this.isStructural(metric);
511
+ const hidden = this.isHidden(metric, surface);
512
+ const rest = isRestMetric(metric);
513
+ const comment = (metric.type === MetricType.Text || metric.type === "text") && metric.origin === "parser";
514
+ const userEntered = metric.origin === "user";
515
+ let renderKind;
516
+ if (hidden) {
517
+ renderKind = "hidden";
518
+ } else if (comment) {
519
+ renderKind = "comment";
520
+ } else if (surface === "timer-subtitle" || surface === "history-label" || surface === "label-composer") {
521
+ renderKind = "plain-text";
522
+ } else if (surface === "review-grid-column") {
523
+ renderKind = "column-heading";
524
+ } else {
525
+ renderKind = "badge";
526
+ }
527
+ return {
528
+ metric,
529
+ label: computeLabel(metric),
530
+ tooltip: buildTooltip(metric),
531
+ renderKind,
532
+ tone: computeTone(metric, rest),
533
+ iconKey: rest ? "rest" : metric.type,
534
+ visible: !hidden,
535
+ structural,
536
+ rest,
537
+ comment,
538
+ userEntered,
539
+ columnLabel: computeColumnLabel(metric.type)
540
+ };
541
+ },
542
+ presentGroup(metrics, surface) {
543
+ return metrics.map((m) => this.present(m, surface));
544
+ },
545
+ columnLabel(type) {
546
+ return computeColumnLabel(type);
547
+ }
548
+ };
549
+ return policy;
550
+ }
551
+ var metricPresentation = createPolicy();
552
+
553
+ // src/runtime/INowProvider.ts
554
+ var wallClockNow = {
555
+ now: () => /* @__PURE__ */ new Date(),
556
+ nowMs: () => Date.now()
557
+ };
558
+ function frozenNow(at) {
559
+ return { now: () => at, nowMs: () => at.getTime() };
560
+ }
561
+
562
+ // src/runtime/models/TimeSpan.ts
563
+ var TimeSpan = class _TimeSpan {
564
+ constructor(started, ended) {
565
+ this.started = started;
566
+ this.ended = ended;
567
+ }
568
+ started;
569
+ ended;
570
+ static fromJSON(json) {
571
+ return new _TimeSpan(json.started, json.ended);
572
+ }
573
+ /**
574
+ * Create a TimeSpan from Date objects (legacy support/compatibility)
575
+ */
576
+ static fromDates(start, end) {
577
+ return new _TimeSpan(start.getTime(), end?.getTime());
578
+ }
579
+ /**
580
+ * Length of this individual span in milliseconds.
581
+ * Uses current time if the span is still open.
582
+ *
583
+ * Note: Not to be confused with the glossary term "Duration" which
584
+ * refers to the parser-defined planned target (DurationMetric).
585
+ */
586
+ get duration() {
587
+ const end = this.ended ?? Date.now();
588
+ return Math.max(0, end - this.started);
589
+ }
590
+ /**
591
+ * Whether the span is currently open (no end time).
592
+ */
593
+ get isOpen() {
594
+ return this.ended === void 0;
595
+ }
596
+ get startDate() {
597
+ return new Date(this.started);
598
+ }
599
+ get endDate() {
600
+ return this.ended ? new Date(this.ended) : void 0;
601
+ }
602
+ };
603
+
604
+ // src/runtime/browserRuntimeNow.ts
605
+ function getRuntimeNowMs() {
606
+ if (typeof window !== "undefined") {
607
+ const senderClock = window.__chromecast_senderClockTimeMs;
608
+ if (typeof senderClock === "function") {
609
+ try {
610
+ const value = senderClock();
611
+ if (Number.isFinite(value)) {
612
+ return value;
613
+ }
614
+ } catch {
615
+ }
616
+ }
617
+ }
618
+ return Date.now();
619
+ }
620
+ function createBrowserRuntimeNow() {
621
+ return {
622
+ now: () => new Date(getRuntimeNowMs()),
623
+ nowMs: () => getRuntimeNowMs()
624
+ };
625
+ }
626
+
627
+ // src/utils/timeUtils.ts
628
+ var formatTime = (ms) => {
629
+ if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
630
+ return "--:--.--";
631
+ }
632
+ const isNegative = ms < 0;
633
+ const absMs = Math.abs(ms);
634
+ const totalSeconds = Math.floor(absMs / 1e3);
635
+ const minutes = Math.floor(totalSeconds / 60);
636
+ const seconds = totalSeconds % 60;
637
+ const milliseconds = Math.floor(absMs % 1e3 / 10);
638
+ const sign = isNegative ? "-" : "";
639
+ return `${sign}${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
640
+ };
641
+ var calculateDuration = (spans, now) => {
642
+ if (!spans || !Array.isArray(spans)) return 0;
643
+ return spans.reduce((total, span) => {
644
+ if ("started" in span) {
645
+ const start2 = span.started;
646
+ const end = span.ended ?? now;
647
+ return total + Math.max(0, end - start2);
648
+ }
649
+ const start = span.start instanceof Date ? span.start.getTime() : span.start || 0;
650
+ const stop = span.stop ? span.stop instanceof Date ? span.stop.getTime() : span.stop : now;
651
+ return total + Math.max(0, stop - start);
652
+ }, 0);
653
+ };
654
+ var roundToTenth = (seconds) => {
655
+ if (!Number.isFinite(seconds)) return 0;
656
+ return Math.round(seconds * 10) / 10;
657
+ };
658
+ var EXCLUDED_REP_BLOCK_TYPES = {
659
+ Rounds: true,
660
+ Group: true,
661
+ AMRAP: true,
662
+ EMOM: true,
663
+ SessionRoot: true,
664
+ Root: true,
665
+ Timer: true,
666
+ Rest: true
667
+ };
668
+ function toSpans(spans) {
669
+ return spans.map((s) => new TimeSpan(s.started, s.ended));
670
+ }
671
+ function serializeSpans(spans) {
672
+ return spans.map(
673
+ (s) => s.ended !== void 0 ? { started: s.started, ended: s.ended } : { started: s.started }
674
+ );
675
+ }
676
+ function resolveVisualPolarity(params) {
677
+ if (params.isPaused) return "paused";
678
+ if (params.direction === "down" && params.durationMs !== void 0 && params.durationMs > 0) {
679
+ if (params.displayMs <= 0) return "overrun";
680
+ if (params.displayMs <= 5e3) return "final5";
681
+ }
682
+ return params.basePolarity === "rest" ? "rest" : "work";
683
+ }
684
+ function isRequiredCountdownLocked(params) {
685
+ return !params.isPaused && params.required && params.direction === "down" && params.durationMs !== void 0 && params.displayMs > 0;
686
+ }
687
+ var WATCHED_CLOCK_MEMORY_TAGS = [
688
+ "time",
689
+ "round",
690
+ "display",
691
+ "metric:display",
692
+ "metric:result",
693
+ "metric:next"
694
+ ];
695
+ function observeSessionClockInputs(runtime, onChange) {
696
+ let skipFlash = false;
697
+ let skipFlashKey = 0;
698
+ let skipTimer;
699
+ let memoryUnsubs = [];
700
+ const emit = () => onChange({ skipFlash, skipFlashKey });
701
+ const rebindBlockMemory = () => {
702
+ memoryUnsubs.forEach((fn) => fn());
703
+ memoryUnsubs = [];
704
+ for (const block of runtime.stack.blocks) {
705
+ for (const tag of WATCHED_CLOCK_MEMORY_TAGS) {
706
+ for (const loc of block.getMemoryByTag(tag)) {
707
+ memoryUnsubs.push(loc.subscribe(emit));
708
+ }
709
+ }
710
+ }
711
+ };
712
+ rebindBlockMemory();
713
+ const unsubStack = runtime.subscribeToStack(() => {
714
+ rebindBlockMemory();
715
+ emit();
716
+ });
717
+ const unsubSkip = runtime.eventBus.on(
718
+ "timer:skip-attempt",
719
+ () => {
720
+ skipFlashKey += 1;
721
+ skipFlash = true;
722
+ clearTimeout(skipTimer);
723
+ emit();
724
+ skipTimer = setTimeout(() => {
725
+ skipFlash = false;
726
+ emit();
727
+ }, 3e3);
728
+ },
729
+ "session-clock-inputs-flash"
730
+ );
731
+ return () => {
732
+ clearTimeout(skipTimer);
733
+ unsubStack();
734
+ unsubSkip();
735
+ memoryUnsubs.forEach((fn) => fn());
736
+ memoryUnsubs = [];
737
+ };
738
+ }
739
+ function interpolateSessionClockFrame(frame, nowMs) {
740
+ const activeElapsed = calculateDuration(toSpans(frame.activeSpans), nowMs);
741
+ const displayMs = frame.direction === "down" && frame.durationMs !== void 0 ? Math.max(0, frame.durationMs - activeElapsed) : activeElapsed;
742
+ const sessionElapsedMs = frame.sessionSpans.length > 0 ? calculateDuration(toSpans(frame.sessionSpans), nowMs) : frame.sessionElapsedMs;
743
+ const secondaryTimers = frame.secondaryTimers.map((st) => {
744
+ const elapsed = calculateDuration(toSpans(st.spans), nowMs);
745
+ return {
746
+ ...st,
747
+ displayMs: st.direction === "down" && st.durationMs !== void 0 ? Math.max(0, st.durationMs - elapsed) : elapsed
748
+ };
749
+ });
750
+ const polarity = resolveVisualPolarity({
751
+ isPaused: frame.isPaused,
752
+ basePolarity: frame.basePolarity,
753
+ direction: frame.direction,
754
+ durationMs: frame.durationMs,
755
+ displayMs
756
+ });
757
+ const isRequiredLockActive = isRequiredCountdownLocked({
758
+ isPaused: frame.isPaused,
759
+ required: frame.required,
760
+ direction: frame.direction,
761
+ durationMs: frame.durationMs,
762
+ displayMs
763
+ });
764
+ return {
765
+ ...frame,
766
+ displayMs,
767
+ sessionElapsedMs,
768
+ secondaryTimers,
769
+ polarity,
770
+ isRequiredLockActive
771
+ };
772
+ }
773
+ function readBlockRound(block) {
774
+ if (!block) return void 0;
775
+ const round = block.getMemoryByTag("round")[0]?.metrics[0];
776
+ if (!round || typeof round.current !== "number") return void 0;
777
+ const display = block.getMemoryByTag("display")[0]?.metrics[0]?.value;
778
+ const label = display?.roundDisplay ?? (round.total !== void 0 ? `Round ${round.current} of ${round.total}` : `Round ${round.current}`);
779
+ return { current: round.current, total: round.total, label };
780
+ }
781
+ function readNextPreviewText(blocks) {
782
+ for (const block of blocks) {
783
+ const nextLocs = block.getMemoryByTag("metric:next");
784
+ if (nextLocs.length === 0) continue;
785
+ const merged = MetricContainer.empty(block.key.toString());
786
+ for (const loc of nextLocs) merged.merge(loc.metrics);
787
+ if (merged.length > 0) {
788
+ return metricPresentation.presentGroup([...merged], "timer-subtitle").filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim() || null;
789
+ }
790
+ }
791
+ return null;
792
+ }
793
+ function extractRepTargets(blocks) {
794
+ const targets = [];
795
+ for (const block of blocks) {
796
+ const blockType = block.blockType ?? "";
797
+ if (EXCLUDED_REP_BLOCK_TYPES[blockType]) {
798
+ continue;
799
+ }
800
+ if (block.getMemoryByTag("children:status").length > 0) continue;
801
+ const displayLocs = block.getMemoryByTag("metric:display");
802
+ const resultLocs = block.getMemoryByTag("metric:result");
803
+ const blockKey = block.key.toString();
804
+ const grouped = displayLocs.length > 1;
805
+ for (let idx = 0; idx < displayLocs.length; idx++) {
806
+ const loc = displayLocs[idx];
807
+ let plannedTarget = null;
808
+ let movementText;
809
+ for (const m of loc.metrics) {
810
+ if (m.type === MetricType.Rep && m.origin !== "user" && typeof m.value === "number") {
811
+ plannedTarget = m.value;
812
+ }
813
+ if ((m.type === MetricType.Effort || m.type === MetricType.Action) && typeof m.value === "string" && m.value) {
814
+ movementText ??= m.value;
815
+ }
816
+ }
817
+ const hasMovementIdentity = plannedTarget !== null || loc.metrics.some(
818
+ (m) => (m.type === MetricType.Effort || m.type === MetricType.Action) && (typeof m.value === "string" || typeof m.image === "string")
819
+ );
820
+ if (!hasMovementIdentity) continue;
821
+ let actual = null;
822
+ if (resultLocs.length > 0) {
823
+ const resLoc = resultLocs[Math.min(idx, resultLocs.length - 1)];
824
+ if (resLoc) {
825
+ const userHits = [];
826
+ for (const m of resLoc.metrics) {
827
+ if (m.origin === "user" && m.type === MetricType.Rep && typeof m.value === "number") {
828
+ userHits.push(m);
829
+ }
830
+ }
831
+ const last = userHits[userHits.length - 1];
832
+ if (last) actual = last.value;
833
+ }
834
+ }
835
+ const sourceId = block.sourceIds[idx] ?? idx;
836
+ targets.push({
837
+ occurrenceId: grouped ? `${blockKey}:${sourceId}` : blockKey,
838
+ blockKey,
839
+ ...grouped ? { sourceId } : {},
840
+ label: grouped && movementText ? movementText : block.label,
841
+ target: plannedTarget,
842
+ actual
843
+ });
844
+ }
845
+ }
846
+ return targets;
847
+ }
848
+ function projectSessionClock(runtime, options = {}) {
849
+ const status = options.executionStatus ?? "idle";
850
+ const isPaused = status === "paused";
851
+ const skipFlash = options.skipFlash ?? false;
852
+ const skipFlashKey = options.skipFlashKey ?? 0;
853
+ if (!runtime) {
854
+ return {
855
+ mainLabel: "Timer",
856
+ displayMs: 0,
857
+ direction: "up",
858
+ activeSpans: [],
859
+ basePolarity: "work",
860
+ required: false,
861
+ sessionElapsedMs: 0,
862
+ sessionSpans: [],
863
+ polarity: isPaused ? "paused" : "work",
864
+ isRequiredLockActive: false,
865
+ secondaryTimers: [],
866
+ upNext: null,
867
+ repTargets: [],
868
+ isRunning: status === "running",
869
+ isPaused,
870
+ isNextDisabled: isPaused || options.canNextOverride === false,
871
+ skipFlash,
872
+ skipFlashKey
873
+ };
874
+ }
875
+ const nowMs = options.nowMs ?? runtime.nowProvider.nowMs();
876
+ const blocks = runtime.stack.blocks;
877
+ const orderedRootToLeaf = [...blocks].reverse();
878
+ const displayEntries = [];
879
+ orderedRootToLeaf.forEach((block, index) => {
880
+ if (block.blockType === "Root" && !block.label) return;
881
+ const displayRows = block.getMemoryByTag("metric:display").map((loc) => loc.metrics);
882
+ if (displayRows.length === 0 && !block.label) return;
883
+ displayEntries.push({
884
+ block,
885
+ displayRows,
886
+ label: block.label,
887
+ isLeaf: index === orderedRootToLeaf.length - 1
888
+ });
889
+ });
890
+ const leafEntry = displayEntries.find((e) => e.isLeaf);
891
+ const roundsEntry = displayEntries.find((e) => e.block.blockType === "Rounds") ?? displayEntries.find((e) => e.block.getMemoryByTag("round").length > 0 && e.block.blockType !== "SessionRoot");
892
+ const roundInfo = readBlockRound(roundsEntry?.block);
893
+ const roundsLabel = roundInfo?.label ?? roundsEntry?.label;
894
+ const allTimers = [];
895
+ for (const block of blocks) {
896
+ const timer = block.getMemoryByTag("time")[0]?.metrics[0]?.value;
897
+ if (!timer) continue;
898
+ allTimers.push({
899
+ block,
900
+ timer,
901
+ isPinned: timer.role === "primary"
902
+ });
903
+ }
904
+ const isAnyTimerRunning = allTimers.some(
905
+ (t) => t.timer.spans.some((s) => s.ended === void 0)
906
+ );
907
+ const topTimer = allTimers[0];
908
+ const primaryTimer = topTimer && (topTimer.block.blockType === "Rest" || topTimer.timer.polarity === "rest") ? topTimer : [...allTimers].reverse().find((t) => t.isPinned) ?? topTimer;
909
+ const leafTimer = leafEntry ? allTimers.find((t) => t.block.key.toString() === leafEntry.block.key.toString()) : void 0;
910
+ const isRestHero = primaryTimer?.block.blockType === "Rest" || primaryTimer?.timer.polarity === "rest";
911
+ const active = isRestHero || primaryTimer?.isPinned ? primaryTimer : leafTimer ?? primaryTimer;
912
+ const leafLabel = leafEntry?.label;
913
+ const mainLabel = (isRestHero ? primaryTimer?.block.label || primaryTimer?.timer.label : primaryTimer?.isPinned ? roundsLabel || primaryTimer.timer.label : roundsLabel && roundsLabel !== leafLabel ? roundsLabel : leafLabel || primaryTimer?.timer.label) || "Timer";
914
+ const subLabel = isRestHero && roundsLabel && roundsLabel !== mainLabel ? roundsLabel : mainLabel === leafLabel ? void 0 : leafLabel;
915
+ let subLabels;
916
+ if (!isRestHero && leafEntry && leafEntry.displayRows.length > 1) {
917
+ const lines = leafEntry.displayRows.map(
918
+ (row) => metricPresentation.presentGroup([...row], "timer-subtitle").filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim()
919
+ ).filter(Boolean);
920
+ if (lines.length > 0) subLabels = lines;
921
+ }
922
+ if (!subLabels) subLabels = subLabel ? [subLabel] : void 0;
923
+ const activeDirection = active?.timer.direction ?? "up";
924
+ const activeDurationMs = active?.timer.durationMs;
925
+ const activeSpans = active ? serializeSpans(active.timer.spans) : [];
926
+ let displayMs = 0;
927
+ if (active) {
928
+ const elapsed = calculateDuration(active.timer.spans, nowMs);
929
+ displayMs = activeDirection === "down" && activeDurationMs !== void 0 ? Math.max(0, activeDurationMs - elapsed) : elapsed;
930
+ }
931
+ const withElapsed = allTimers.map((entry) => ({
932
+ entry,
933
+ elapsed: calculateDuration(entry.timer.spans, nowMs)
934
+ }));
935
+ const sessionHolder = withElapsed.find((e) => e.entry.block.blockType === "SessionRoot") ?? withElapsed.reduce(
936
+ (best, cur) => cur.elapsed > (best?.elapsed ?? -1) ? cur : best,
937
+ withElapsed[withElapsed.length - 1]
938
+ );
939
+ const sessionElapsedMs = sessionHolder?.elapsed ?? 0;
940
+ const sessionSpans = sessionHolder ? serializeSpans(sessionHolder.entry.timer.spans) : [];
941
+ const activeKey = active?.block.key.toString();
942
+ const sessionKey = sessionHolder?.entry.block.key.toString();
943
+ const secondaryTimers = allTimers.filter((t) => {
944
+ if (t.timer.role === "hidden") return false;
945
+ const key = t.block.key.toString();
946
+ return key !== activeKey && key !== sessionKey;
947
+ }).map((t) => {
948
+ const elapsed = calculateDuration(t.timer.spans, nowMs);
949
+ return {
950
+ id: t.block.key.toString(),
951
+ label: t.timer.label || t.block.label || "Timer",
952
+ displayMs: t.timer.direction === "down" && t.timer.durationMs !== void 0 ? Math.max(0, t.timer.durationMs - elapsed) : elapsed,
953
+ direction: t.timer.direction,
954
+ durationMs: t.timer.durationMs,
955
+ spans: serializeSpans(t.timer.spans)
956
+ };
957
+ });
958
+ const basePolarity = active?.block.blockType === "Rest" || active?.timer.polarity === "rest" ? "rest" : "work";
959
+ const required = Boolean(active?.timer.required);
960
+ const polarity = resolveVisualPolarity({
961
+ isPaused,
962
+ basePolarity,
963
+ direction: activeDirection,
964
+ durationMs: activeDurationMs,
965
+ displayMs
966
+ });
967
+ const isRequiredLockActive = isRequiredCountdownLocked({
968
+ isPaused,
969
+ required,
970
+ direction: activeDirection,
971
+ durationMs: activeDurationMs,
972
+ displayMs
973
+ });
974
+ return {
975
+ mainLabel,
976
+ subLabels,
977
+ displayMs,
978
+ direction: activeDirection,
979
+ durationMs: activeDurationMs,
980
+ activeSpans,
981
+ basePolarity,
982
+ required,
983
+ sessionElapsedMs,
984
+ sessionSpans,
985
+ polarity,
986
+ isRequiredLockActive,
987
+ roundCurrent: roundInfo?.current,
988
+ roundTotal: roundInfo?.total,
989
+ roundLabel: roundInfo?.label,
990
+ secondaryTimers,
991
+ upNext: readNextPreviewText(blocks),
992
+ repTargets: extractRepTargets(blocks),
993
+ isRunning: isAnyTimerRunning || status === "running",
994
+ isPaused,
995
+ isNextDisabled: isPaused || options.canNextOverride === false,
996
+ skipFlash,
997
+ skipFlashKey
998
+ };
999
+ }
1000
+ var NON_LABEL_SEGMENT_METRIC_TYPES = {
1001
+ [MetricType.Elapsed]: true,
1002
+ [MetricType.Total]: true,
1003
+ [MetricType.Spans]: true,
1004
+ [MetricType.SystemTime]: true,
1005
+ [MetricType.CurrentRound]: true,
1006
+ [MetricType.System]: true
1007
+ };
1008
+ function projectionsToUniqueSummaries(projections) {
1009
+ const byName = /* @__PURE__ */ new Map();
1010
+ for (const proj of projections) {
1011
+ byName.set(proj.name, {
1012
+ key: proj.name,
1013
+ label: computeColumnLabel(proj.name),
1014
+ value: proj.value,
1015
+ unit: proj.unit,
1016
+ metricType: proj.metricType ?? MetricType.Metric,
1017
+ origin: proj.origin
1018
+ });
1019
+ }
1020
+ return [...byName.values()];
1021
+ }
1022
+ function fallbackSummariesFromOutputs(outputs) {
1023
+ const byName = /* @__PURE__ */ new Map();
1024
+ for (const output of outputs) {
1025
+ const metrics = output.metrics;
1026
+ for (let j = 0; j + 1 < metrics.length; j += 2) {
1027
+ const labelMetric = metrics[j];
1028
+ const valueMetric = metrics[j + 1];
1029
+ if (!labelMetric || !valueMetric || typeof valueMetric.value !== "number") continue;
1030
+ const name = labelMetric.image ?? String(labelMetric.value);
1031
+ byName.set(name, {
1032
+ key: name,
1033
+ label: computeColumnLabel(name),
1034
+ value: valueMetric.value,
1035
+ unit: valueMetric.unit ?? "",
1036
+ metricType: valueMetric.type || MetricType.Metric,
1037
+ origin: valueMetric.origin
1038
+ });
1039
+ }
1040
+ }
1041
+ return [...byName.values()];
1042
+ }
1043
+ function formatSplitDeltaLabel(deltaMs) {
1044
+ const deltaSec = Math.round(deltaMs / 1e3);
1045
+ if (deltaSec === 0) return "even";
1046
+ return deltaSec > 0 ? `+${deltaSec}s` : `${deltaSec}s`;
1047
+ }
1048
+ function readRoundFromOutput(output) {
1049
+ const metric = output.getMetric(MetricType.CurrentRound);
1050
+ if (!metric) return {};
1051
+ const round = typeof metric.value === "number" ? metric.value : void 0;
1052
+ let totalRounds;
1053
+ if ("total" in metric && typeof metric.total === "number") {
1054
+ totalRounds = metric.total;
1055
+ }
1056
+ return { round, totalRounds };
1057
+ }
1058
+ function deriveRoundSplits(outputs) {
1059
+ const previousElapsedByKey = /* @__PURE__ */ new Map();
1060
+ const rows = [];
1061
+ for (let idx = 0; idx < outputs.length; idx++) {
1062
+ const out = outputs[idx];
1063
+ if (out.outputType !== "segment") continue;
1064
+ if (out.sourceBlockKey.startsWith("session-root")) continue;
1065
+ if (out.completionReason === "rounds-complete") continue;
1066
+ if (out.sourceStatementId === void 0 && !out.sourceBlockKey.startsWith("rest")) continue;
1067
+ const elapsedVal = out.getMetric(MetricType.Elapsed)?.value;
1068
+ const fallbackSpanElapsed = out.timeSpan.ended !== void 0 ? Math.max(0, out.timeSpan.ended - out.timeSpan.started) : 0;
1069
+ const elapsedMs = typeof elapsedVal === "number" ? elapsedVal : fallbackSpanElapsed;
1070
+ if (!Number.isFinite(elapsedMs)) continue;
1071
+ const displayTokens = metricPresentation.presentGroup(
1072
+ out.metrics.filter((m) => !NON_LABEL_SEGMENT_METRIC_TYPES[m.type]),
1073
+ "timer-subtitle"
1074
+ ).filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim();
1075
+ const label = displayTokens || out.text?.trim() || (out.sourceBlockKey.startsWith("rest") ? "Rest" : "Segment");
1076
+ const comparisonKey = out.sourceStatementId !== void 0 ? `stmt:${out.sourceStatementId}` : `key:${label.toLowerCase()}`;
1077
+ const prevElapsed = previousElapsedByKey.get(comparisonKey);
1078
+ const deltaMs = prevElapsed !== void 0 ? elapsedMs - prevElapsed : void 0;
1079
+ previousElapsedByKey.set(comparisonKey, elapsedMs);
1080
+ const { round, totalRounds } = readRoundFromOutput(out);
1081
+ rows.push({
1082
+ id: `${out.sourceBlockKey}:${idx}`,
1083
+ comparisonKey,
1084
+ label,
1085
+ elapsedMs,
1086
+ ...round !== void 0 ? { round } : {},
1087
+ ...totalRounds !== void 0 ? { totalRounds } : {},
1088
+ ...deltaMs !== void 0 ? { deltaMs, deltaLabel: formatSplitDeltaLabel(deltaMs) } : {}
1089
+ });
1090
+ }
1091
+ return rows;
1092
+ }
1093
+ function projectLiveSessionTelemetry(runtime) {
1094
+ if (!runtime) {
1095
+ return { summaries: [], splits: [] };
1096
+ }
1097
+ const typedProjections = runtime.getLiveProjections?.();
1098
+ const summaries = typedProjections && typedProjections.length > 0 ? projectionsToUniqueSummaries(typedProjections) : fallbackSummariesFromOutputs(runtime.getLiveAnalytics?.() ?? []);
1099
+ const splits = deriveRoundSplits(runtime.getOutputStatements());
1100
+ return { summaries, splits };
1101
+ }
1102
+ function formatStatementLabel(statement) {
1103
+ const presented = metricPresentation.presentGroup(
1104
+ [...statement.metrics].filter((m) => m.type !== MetricType.Hint),
1105
+ "timer-subtitle"
1106
+ ).filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim();
1107
+ return presented || statement.text?.trim() || "Step";
1108
+ }
1109
+ function synthesizeWorkoutFormat(script) {
1110
+ const statements = script?.statements;
1111
+ if (!statements || statements.length === 0) return void 0;
1112
+ const roots = statements.filter((s) => s.parent === void 0);
1113
+ const primaryRoot = roots[0] ?? statements[0];
1114
+ if (!primaryRoot) return void 0;
1115
+ const hasChildren = (primaryRoot.children?.length ?? 0) > 0;
1116
+ const hasProtocolHint = hasHint(primaryRoot, CONSUMED_HINTS.LABEL_AMRAP) || hasHint(primaryRoot, CONSUMED_HINTS.LABEL_EMOM) || hasHint(primaryRoot, CONSUMED_HINTS.LABEL_TABATA) || hasHint(primaryRoot, CONSUMED_HINTS.LABEL_FOR_TIME);
1117
+ const hasStructuralMetric = primaryRoot.metrics.some(
1118
+ (m) => m.type === MetricType.Rounds || m.type === MetricType.Duration
1119
+ );
1120
+ if (!hasChildren && !hasProtocolHint && !hasStructuralMetric) {
1121
+ return void 0;
1122
+ }
1123
+ return formatStatementLabel(primaryRoot);
1124
+ }
1125
+ function projectScriptOutline(runtime) {
1126
+ const statements = runtime?.script?.statements;
1127
+ if (!runtime || !statements || statements.length === 0) return [];
1128
+ const activeIds = /* @__PURE__ */ new Set();
1129
+ for (const block of runtime.stack.blocks) {
1130
+ if (block.blockType === "SessionRoot" || block.blockType === "WaitingToStart") continue;
1131
+ for (const id of block.sourceIds) {
1132
+ if (typeof id === "number") activeIds.add(id);
1133
+ }
1134
+ }
1135
+ const completedIds = /* @__PURE__ */ new Set();
1136
+ for (const out of runtime.getOutputStatements()) {
1137
+ if (out.outputType === "segment" && typeof out.sourceStatementId === "number") {
1138
+ completedIds.add(out.sourceStatementId);
1139
+ }
1140
+ }
1141
+ const depthOf = (stmt) => {
1142
+ let depth = 0;
1143
+ let cur = stmt.parent;
1144
+ const seen = /* @__PURE__ */ new Set();
1145
+ while (cur !== void 0 && !seen.has(cur)) {
1146
+ seen.add(cur);
1147
+ const parentStmt = runtime.script.getId(cur);
1148
+ if (!parentStmt) break;
1149
+ depth += 1;
1150
+ cur = parentStmt.parent;
1151
+ }
1152
+ return depth;
1153
+ };
1154
+ const nodes = [];
1155
+ for (const stmt of statements) {
1156
+ if (typeof stmt.id !== "number") continue;
1157
+ const label = formatStatementLabel(stmt);
1158
+ if (!label) continue;
1159
+ const status = activeIds.has(stmt.id) ? "active" : completedIds.has(stmt.id) ? "completed" : "upcoming";
1160
+ nodes.push({
1161
+ statementId: stmt.id,
1162
+ depth: depthOf(stmt),
1163
+ label,
1164
+ status
1165
+ });
1166
+ }
1167
+ return nodes;
1168
+ }
1169
+
1170
+ export { CONSUMED_HINTS, CONSUMED_HINT_KEYS, MAX_TAG_CONTRIBUTION_DEPTH, STANDARD_UNITS, TAG_MARKER_PREFIX, TimeSpan, UnitRegistry, UnitSet, buildTooltip, calculateDuration, collectTagReferences, computeColumnLabel, computeLabel, createBrowserRuntimeNow, createPolicy, findTagContributionCycles, formatDurationCompact, formatDurationSmart, formatSecondsHHMMSS, formatSecondsMMSS, formatTime, formatTimeHHMMSS, formatTimeMMSS, formatTimePrecise, formatTimestamp, frozenNow, getHints, getRuntimeNowMs, hasHint, hintMetric, hintsToContainer, interpolateSessionClockFrame, isRequiredCountdownLocked, isTimeLikeMetric, metricPresentation, observeSessionClockInputs, projectLiveSessionTelemetry, projectScriptOutline, projectSessionClock, resolveTagContributions, resolveVisualPolarity, roundToTenth, synthesizeWorkoutFormat, tagContributionMetrics, tagMarkerSlug, tagMarkerSlugs, tagMarkerType, tagReferenceFor, wallClockNow };
1171
+ //# sourceMappingURL=chunk-XDMS3U3W.mjs.map
1172
+ //# sourceMappingURL=chunk-XDMS3U3W.mjs.map