@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.
package/dist/index.cjs CHANGED
@@ -991,9 +991,15 @@ var UnitsDialect = class {
991
991
  return {};
992
992
  }
993
993
  };
994
+ var CROSSFIT_UNITS = UnitRegistry.of([
995
+ { canonical: "pood", dimension: "mass", aliases: ["poods", "pd"] }
996
+ ]);
994
997
  var CrossFitDialect = class {
995
998
  id = "crossfit";
996
999
  name = "CrossFit Dialect";
1000
+ transform(statement) {
1001
+ fuseUnits(statement, CROSSFIT_UNITS);
1002
+ }
997
1003
  /**
998
1004
  * Check if any Action or Effort metrics contains a keyword (case-insensitive)
999
1005
  */
@@ -1042,9 +1048,15 @@ var CrossFitDialect = class {
1042
1048
  return { metrics: hintsToContainer(hints) };
1043
1049
  }
1044
1050
  };
1051
+ var WOD_UNITS = UnitRegistry.of([
1052
+ { canonical: "pood", dimension: "mass", aliases: ["poods", "pd"] }
1053
+ ]);
1045
1054
  var WodDialect = class {
1046
1055
  id = "wod";
1047
1056
  name = "WOD Dialect";
1057
+ transform(statement) {
1058
+ fuseUnits(statement, WOD_UNITS);
1059
+ }
1048
1060
  /** Case-insensitive keyword check on Action/Effort metrics */
1049
1061
  hasKeyword(metrics, keyword2) {
1050
1062
  return metrics.some(
@@ -1749,6 +1761,36 @@ var PROPERTY_KEY_TO_METRIC_TYPE = {
1749
1761
  };
1750
1762
  var STRUCTURAL_EFFORT_WORDS = /* @__PURE__ */ new Set(["rest", "amrap", "emom", "tabata", "for time"]);
1751
1763
  var STANDARD_UNITS2 = UnitRegistry.standard();
1764
+ var DIALECT_UNIT_WORDS = /* @__PURE__ */ new Set(["pood", "poods", "pd"]);
1765
+ var ROUNDS_LABEL_WORDS = /^(rounds?|rds?|sets?|laps?|cycles?|intervals?)$/i;
1766
+ var TIME_UNIT_SECONDS = {
1767
+ s: 1,
1768
+ sec: 1,
1769
+ secs: 1,
1770
+ second: 1,
1771
+ seconds: 1,
1772
+ min: 60,
1773
+ mins: 60,
1774
+ minute: 60,
1775
+ minutes: 60,
1776
+ hr: 3600,
1777
+ hrs: 3600,
1778
+ hour: 3600,
1779
+ hours: 3600
1780
+ };
1781
+ function formatSecondsAsTimer(totalSeconds) {
1782
+ const hours = Math.floor(totalSeconds / 3600);
1783
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
1784
+ const seconds = totalSeconds % 60;
1785
+ const pad22 = (n) => String(n).padStart(2, "0");
1786
+ if (hours > 0) {
1787
+ return `${hours}:${pad22(minutes)}:${pad22(seconds)}`;
1788
+ }
1789
+ if (minutes > 0) {
1790
+ return `${minutes}:${pad22(seconds)}`;
1791
+ }
1792
+ return `:${pad22(seconds)}`;
1793
+ }
1752
1794
  var REFERENCE_PAIR_KEYS = /* @__PURE__ */ new Set(["effort", "equipment"]);
1753
1795
  function referenceMetadata(resolution) {
1754
1796
  return {
@@ -1891,7 +1933,7 @@ function applyReferenceResolution(pairs, fact, references) {
1891
1933
  if (metric.type === wodWikiCore.MetricType.Effort) {
1892
1934
  const authored = metric instanceof EffortMetric ? metric.effort : String(metric.value ?? "");
1893
1935
  const normalized = authored.trim().toLowerCase();
1894
- if (STRUCTURAL_EFFORT_WORDS.has(normalized) || STANDARD_UNITS2.has(normalized)) {
1936
+ if (STRUCTURAL_EFFORT_WORDS.has(normalized) || STANDARD_UNITS2.has(normalized) || DIALECT_UNIT_WORDS.has(normalized)) {
1895
1937
  result.push(pair);
1896
1938
  continue;
1897
1939
  }
@@ -1995,14 +2037,49 @@ function classifyPrimitive(primitive) {
1995
2037
  case "rounds": {
1996
2038
  if (primitive.sequence) {
1997
2039
  if (primitive.sequence.length === 1) {
1998
- return [{ metrics: new RoundsMetric(primitive.sequence[0]), meta: primitive.meta }];
2040
+ const amount = primitive.sequence[0];
2041
+ const trimmedLabel2 = primitive.label?.trim();
2042
+ if (!trimmedLabel2 || ROUNDS_LABEL_WORDS.test(trimmedLabel2)) {
2043
+ return [{ metrics: new RoundsMetric(amount), meta: primitive.meta }];
2044
+ }
2045
+ const lowerLabel2 = trimmedLabel2.toLowerCase();
2046
+ const unitSeconds = TIME_UNIT_SECONDS[lowerLabel2];
2047
+ if (unitSeconds !== void 0) {
2048
+ const totalSeconds = Math.max(0, Math.round(amount * unitSeconds));
2049
+ return [{ metrics: new DurationMetric(formatSecondsAsTimer(totalSeconds)), meta: primitive.meta }];
2050
+ }
2051
+ if (/^(reps?)$/i.test(trimmedLabel2)) {
2052
+ return [{ metrics: new RepMetric(amount), meta: primitive.meta }];
2053
+ }
2054
+ return [
2055
+ { metrics: new RepMetric(amount), meta: primitive.sequenceMeta ?? primitive.meta },
2056
+ { metrics: new EffortMetric(trimmedLabel2), meta: primitive.labelMeta ?? primitive.meta }
2057
+ ];
1999
2058
  }
2000
2059
  return [
2001
2060
  { metrics: new RoundsMetric(primitive.sequence.length), meta: primitive.meta },
2002
2061
  ...primitive.sequence.map((value) => ({ metrics: new RepMetric(value), meta: primitive.meta }))
2003
2062
  ];
2004
2063
  }
2005
- return primitive.label ? [{ metrics: new RoundsMetric(primitive.label), meta: primitive.meta }] : [];
2064
+ if (!primitive.label) {
2065
+ return [];
2066
+ }
2067
+ const trimmedLabel = primitive.label.trim();
2068
+ const lowerLabel = trimmedLabel.toLowerCase();
2069
+ if (/^(reps?)$/i.test(trimmedLabel)) {
2070
+ return [{ metrics: new RepMetric(void 0), meta: primitive.meta }];
2071
+ }
2072
+ const stdUnit = STANDARD_UNITS2.get(lowerLabel);
2073
+ if (stdUnit) {
2074
+ return [{ metrics: metricForDimension(void 0, trimmedLabel, stdUnit.dimension), meta: primitive.meta }];
2075
+ }
2076
+ if (DIALECT_UNIT_WORDS.has(lowerLabel)) {
2077
+ return [{ metrics: new ResistanceMetric(void 0, trimmedLabel), meta: primitive.meta }];
2078
+ }
2079
+ if (TIME_UNIT_SECONDS[lowerLabel] !== void 0) {
2080
+ return [{ metrics: new DurationMetric(":?"), meta: primitive.meta }];
2081
+ }
2082
+ return [{ metrics: new RoundsMetric(primitive.label), meta: primitive.meta }];
2006
2083
  }
2007
2084
  case "round_scheme": {
2008
2085
  return [
@@ -2398,13 +2475,17 @@ function mapFragmentToPrimitive(locator, source, node) {
2398
2475
  }
2399
2476
  case Rounds: {
2400
2477
  const sequence = node.getChild("Sequence");
2401
- const label = node.getChild("Identifier");
2478
+ const identifiers = node.getChildren("Identifier");
2479
+ const firstId = identifiers[0];
2480
+ const lastId = identifiers[identifiers.length - 1];
2402
2481
  const primitive = {
2403
2482
  kind: "rounds",
2404
2483
  raw,
2405
2484
  meta: meta2,
2406
- sequence: sequence ? source.slice(sequence.from, sequence.to).split("-").map((n) => parseInt(n.trim(), 10)) : void 0,
2407
- label: label ? source.slice(label.from, label.to) : void 0
2485
+ sequence: sequence ? source.slice(sequence.from, sequence.to).split("-").map((n) => Number(n.trim())) : void 0,
2486
+ label: identifiers.length > 0 ? identifiers.map((id) => source.slice(id.from, id.to)).join(" ") : void 0,
2487
+ sequenceMeta: sequence ? createMeta(locator, sequence.from, sequence.to, source.slice(sequence.from, sequence.to)) : void 0,
2488
+ labelMeta: firstId && lastId ? createMeta(locator, firstId.from, lastId.to, source.slice(firstId.from, lastId.to)) : void 0
2408
2489
  };
2409
2490
  return primitive;
2410
2491
  }
@@ -5336,6 +5417,15 @@ var DEFAULT_RUNTIME_OPTIONS = {
5336
5417
  maxActionDepth: 20
5337
5418
  };
5338
5419
 
5420
+ // src/runtime/INowProvider.ts
5421
+ var wallClockNow = {
5422
+ now: () => /* @__PURE__ */ new Date(),
5423
+ nowMs: () => Date.now()
5424
+ };
5425
+ function frozenNow(at) {
5426
+ return { now: () => at, nowMs: () => at.getTime() };
5427
+ }
5428
+
5339
5429
  // src/runtime/models/TimeSpan.ts
5340
5430
  var TimeSpan = class _TimeSpan {
5341
5431
  constructor(started, ended) {
@@ -5432,12 +5522,16 @@ var SnapshotClock = class _SnapshotClock {
5432
5522
  }
5433
5523
  };
5434
5524
  var RuntimeClock = class {
5525
+ constructor(_now = wallClockNow) {
5526
+ this._now = _now;
5527
+ }
5528
+ _now;
5435
5529
  _spans = [];
5436
5530
  /**
5437
- * Current wall-clock time as a Date.
5531
+ * Current clock time as a Date (from injected `INowProvider`, defaulting to wall clock).
5438
5532
  */
5439
5533
  get currentDate() {
5440
- return /* @__PURE__ */ new Date();
5534
+ return this._now.now();
5441
5535
  }
5442
5536
  now() {
5443
5537
  return this.currentDate;
@@ -5463,7 +5557,8 @@ var RuntimeClock = class {
5463
5557
  * Sums all completed spans plus the current running span (if any).
5464
5558
  */
5465
5559
  get elapsed() {
5466
- return this._spans.reduce((total, span) => total + span.duration, 0);
5560
+ const currentMs = this._now.nowMs();
5561
+ return this._spans.reduce((total, span) => total + ((span.ended ?? currentMs) - span.started), 0);
5467
5562
  }
5468
5563
  /**
5469
5564
  * Start the clock. Creates a new span with the current time.
@@ -5472,7 +5567,7 @@ var RuntimeClock = class {
5472
5567
  * If the clock is already running, returns the current span's start time.
5473
5568
  */
5474
5569
  start() {
5475
- const now = /* @__PURE__ */ new Date();
5570
+ const now = this._now.now();
5476
5571
  if (this.isRunning) {
5477
5572
  return this._spans[this._spans.length - 1].startDate;
5478
5573
  }
@@ -5486,7 +5581,7 @@ var RuntimeClock = class {
5486
5581
  * If the clock is not running, returns the current time.
5487
5582
  */
5488
5583
  stop() {
5489
- const now = /* @__PURE__ */ new Date();
5584
+ const now = this._now.now();
5490
5585
  if (!this.isRunning) {
5491
5586
  return now;
5492
5587
  }
@@ -5547,15 +5642,6 @@ function createMockClock(initialTime = /* @__PURE__ */ new Date()) {
5547
5642
  };
5548
5643
  }
5549
5644
 
5550
- // src/runtime/INowProvider.ts
5551
- var wallClockNow = {
5552
- now: () => /* @__PURE__ */ new Date(),
5553
- nowMs: () => Date.now()
5554
- };
5555
- function frozenNow(at) {
5556
- return { now: () => at, nowMs: () => at.getTime() };
5557
- }
5558
-
5559
5645
  // src/runtime/actions/stack/NextAction.ts
5560
5646
  var NextAction = class {
5561
5647
  /**
@@ -6181,6 +6267,31 @@ var RuntimeLogger = new RuntimeLoggerImpl();
6181
6267
  if (typeof window !== "undefined") {
6182
6268
  window.RuntimeLogger = RuntimeLogger;
6183
6269
  }
6270
+ var CurrentRoundMetric = class {
6271
+ /**
6272
+ * @param current The current round number (1-based)
6273
+ * @param total Total number of planned rounds (undefined for unbounded)
6274
+ * @param sourceBlockKey Block that owns this round counter
6275
+ * @param timestamp When this metrics was created
6276
+ * @param customImage Optional custom image string (e.g., "Completed 3 Round(s)")
6277
+ */
6278
+ constructor(current, total, sourceBlockKey, timestamp, customImage) {
6279
+ this.current = current;
6280
+ this.total = total;
6281
+ this.sourceBlockKey = sourceBlockKey;
6282
+ this.timestamp = timestamp;
6283
+ this.value = current;
6284
+ this.image = customImage ?? (total !== void 0 ? `Round ${current} of ${total}` : `Round ${current}`);
6285
+ }
6286
+ current;
6287
+ total;
6288
+ sourceBlockKey;
6289
+ timestamp;
6290
+ type = wodWikiCore.MetricType.CurrentRound;
6291
+ origin = "tracked";
6292
+ value;
6293
+ image;
6294
+ };
6184
6295
  var OutputEmitter = class {
6185
6296
  _outputStatements = [];
6186
6297
  _outputListeners = /* @__PURE__ */ new Set();
@@ -6210,6 +6321,17 @@ var OutputEmitter = class {
6210
6321
  this._clock = deps.clock;
6211
6322
  this._stack = deps.stack;
6212
6323
  this._script = deps.script;
6324
+ if (this._analyticsEngine) {
6325
+ this._bindEngineClock(this._analyticsEngine);
6326
+ }
6327
+ }
6328
+ _bindEngineClock(engine) {
6329
+ if (!this._clock || !engine.setNowProvider) return;
6330
+ const clock = this._clock;
6331
+ engine.setNowProvider({
6332
+ now: () => clock.currentDate,
6333
+ nowMs: () => clock.currentDate.getTime()
6334
+ });
6213
6335
  }
6214
6336
  _requireClock() {
6215
6337
  if (!this._clock) {
@@ -6274,6 +6396,7 @@ var OutputEmitter = class {
6274
6396
  }
6275
6397
  setAnalyticsEngine(engine) {
6276
6398
  this._analyticsEngine = engine;
6399
+ this._bindEngineClock(engine);
6277
6400
  engine.setLiveOutputEmitter((outputs) => this.emitLiveAnalytics(outputs));
6278
6401
  }
6279
6402
  /**
@@ -6326,6 +6449,11 @@ var OutputEmitter = class {
6326
6449
  getLiveAnalytics() {
6327
6450
  return [...this._liveAnalytics];
6328
6451
  }
6452
+ /** Typed live Summary Metric projections directly from AnalyticsEngine. */
6453
+ getLiveProjections() {
6454
+ if (this._analyticsFinalized) return [];
6455
+ return this._analyticsEngine?.getLiveProjections?.() ?? [];
6456
+ }
6329
6457
  dispose() {
6330
6458
  this._outputStatements = [];
6331
6459
  this._outputListeners.clear();
@@ -6432,6 +6560,22 @@ var OutputEmitter = class {
6432
6560
  const sourceFragments = wodWikiCore.MetricContainer.from(displayLocs[i]?.metrics, block.key.toString());
6433
6561
  const metrics = wodWikiCore.MetricContainer.empty(block.key.toString()).add(...sourceFragments.toArray()).add(...resultFragments.toArray());
6434
6562
  if (metrics.length === 0) continue;
6563
+ if (!metrics.some((m) => m.type === wodWikiCore.MetricType.CurrentRound) && block.getMemoryByTag("children:status").length === 0 && block.blockType !== "SessionRoot" && block.blockType !== "Rounds") {
6564
+ const enclosingRoundBlock = (this._stack?.blocks ?? []).find(
6565
+ (ancestor2) => ancestor2.blockType !== "SessionRoot" && ancestor2.getMemoryByTag("round").length > 0
6566
+ );
6567
+ const roundState = enclosingRoundBlock?.getMemoryByTag("round")[0]?.metrics[0];
6568
+ if (roundState && typeof roundState.current === "number") {
6569
+ metrics.add(
6570
+ new CurrentRoundMetric(
6571
+ roundState.current,
6572
+ roundState.total,
6573
+ enclosingRoundBlock?.key.toString(),
6574
+ new Date(fallbackEndMs)
6575
+ )
6576
+ );
6577
+ }
6578
+ }
6435
6579
  const fallbackStartMs = block.executionTiming?.startTime?.getTime() ?? fallbackEndMs;
6436
6580
  const timeSpan = new TimeSpan(fallbackStartMs, fallbackEndMs);
6437
6581
  this.add(new wodWikiCore.OutputStatement({
@@ -6811,6 +6955,9 @@ var ScriptRuntime = class {
6811
6955
  getLiveAnalytics() {
6812
6956
  return this._output.getLiveAnalytics();
6813
6957
  }
6958
+ getLiveProjections() {
6959
+ return this._output.getLiveProjections();
6960
+ }
6814
6961
  /**
6815
6962
  * Add an output statement to the collection and notify subscribers.
6816
6963
  * Used by BehaviorContext to emit outputs at any lifecycle point.
@@ -8050,7 +8197,9 @@ var CountupTimerBehavior = class {
8050
8197
  direction: "up",
8051
8198
  durationMs: void 0,
8052
8199
  label,
8053
- role
8200
+ role,
8201
+ required: false,
8202
+ polarity: this.config.polarity ?? "work"
8054
8203
  })]);
8055
8204
  this.subscriptions.push(
8056
8205
  ctx.subscribe("timer:pause", (_event, pCtx) => {
@@ -8152,31 +8301,6 @@ function formatDuration(ms) {
8152
8301
  const secs = totalSeconds % 60;
8153
8302
  return `${mins}:${secs.toString().padStart(2, "0")}`;
8154
8303
  }
8155
- var CurrentRoundMetric = class {
8156
- /**
8157
- * @param current The current round number (1-based)
8158
- * @param total Total number of planned rounds (undefined for unbounded)
8159
- * @param sourceBlockKey Block that owns this round counter
8160
- * @param timestamp When this metrics was created
8161
- * @param customImage Optional custom image string (e.g., "Completed 3 Round(s)")
8162
- */
8163
- constructor(current, total, sourceBlockKey, timestamp, customImage) {
8164
- this.current = current;
8165
- this.total = total;
8166
- this.sourceBlockKey = sourceBlockKey;
8167
- this.timestamp = timestamp;
8168
- this.value = current;
8169
- this.image = customImage ?? (total !== void 0 ? `Round ${current} of ${total}` : `Round ${current}`);
8170
- }
8171
- current;
8172
- total;
8173
- sourceBlockKey;
8174
- timestamp;
8175
- type = wodWikiCore.MetricType.CurrentRound;
8176
- origin = "tracked";
8177
- value;
8178
- image;
8179
- };
8180
8304
 
8181
8305
  // src/runtime/behaviors/CountdownTimerBehavior.ts
8182
8306
  var CountdownTimerBehavior = class {
@@ -8196,7 +8320,9 @@ var CountdownTimerBehavior = class {
8196
8320
  direction: "down",
8197
8321
  durationMs: this.config.durationMs,
8198
8322
  label,
8199
- role
8323
+ role,
8324
+ required: Boolean(this.config.required),
8325
+ polarity: this.config.polarity ?? "work"
8200
8326
  })]);
8201
8327
  if (this.config.durationMs <= 0) {
8202
8328
  this.handleExpiry(ctx, mode);
@@ -11620,7 +11746,9 @@ var RestBlock = class _RestBlock extends RuntimeBlock {
11620
11746
  durationMs: config.durationMs,
11621
11747
  label: restLabel,
11622
11748
  role: "primary",
11623
- mode: "complete-block"
11749
+ mode: "complete-block",
11750
+ required: true,
11751
+ polarity: "rest"
11624
11752
  }));
11625
11753
  behaviors.push(new ExitBehavior({
11626
11754
  mode: "immediate",
@@ -11810,6 +11938,7 @@ var BlockBuilder = class {
11810
11938
  role: config.role,
11811
11939
  mode,
11812
11940
  required: config.required,
11941
+ polarity: config.polarity,
11813
11942
  restBlockFactory: config.injectRest ? (durationMs, label) => {
11814
11943
  const restBlock = new RestBlock(this.runtime, { durationMs, label });
11815
11944
  return [new PushBlockAction(restBlock)];
@@ -11818,7 +11947,8 @@ var BlockBuilder = class {
11818
11947
  } else {
11819
11948
  this.addBehavior(new CountupTimerBehavior({
11820
11949
  label: config.label,
11821
- role: config.role
11950
+ role: config.role,
11951
+ polarity: config.polarity
11822
11952
  }));
11823
11953
  }
11824
11954
  return this;
@@ -12328,11 +12458,22 @@ var AnalyticsEngine = class {
12328
12458
  outputHistory = [];
12329
12459
  /** Emits a live 'analytics' snapshot per segment so the UI updates in real time. */
12330
12460
  _onLiveOutput;
12461
+ _liveProjections = [];
12331
12462
  /**
12332
12463
  * Signature of the last live projection emission. Used by finalize() to avoid
12333
12464
  * re-emitting the same projections at session end. Timestamps are ignored.
12334
12465
  */
12335
12466
  _lastLiveProjectionSignature;
12467
+ _now;
12468
+ constructor(now = wallClockNow) {
12469
+ this._now = now;
12470
+ }
12471
+ setNowProvider(now) {
12472
+ this._now = now;
12473
+ }
12474
+ getLiveProjections() {
12475
+ return [...this._liveProjections];
12476
+ }
12336
12477
  /**
12337
12478
  * Wire a sink for live analytics outputs. The sink receives the FULL
12338
12479
  * projection snapshot (a replaceable, ephemeral set) each time projections
@@ -12360,8 +12501,9 @@ var AnalyticsEngine = class {
12360
12501
  if (current.outputType === "segment") {
12361
12502
  this.outputHistory.push(current);
12362
12503
  if (this._onLiveOutput) {
12363
- const now = Date.now();
12364
12504
  const projections = this._runSummaries();
12505
+ this._liveProjections = projections;
12506
+ const now = this._now.nowMs();
12365
12507
  const signature = this._projectionSignature(projections);
12366
12508
  if (signature !== this._lastLiveProjectionSignature) {
12367
12509
  this._lastLiveProjectionSignature = signature;
@@ -12374,7 +12516,8 @@ var AnalyticsEngine = class {
12374
12516
  }
12375
12517
  finalize() {
12376
12518
  const projections = this._runSummaries();
12377
- const outputs = this._buildProjectionOutputs(projections, Date.now());
12519
+ this._liveProjections = [];
12520
+ const outputs = this._buildProjectionOutputs(projections, this._now.nowMs());
12378
12521
  const signature = this._projectionSignature(projections);
12379
12522
  if (this._lastLiveProjectionSignature !== void 0 && this._lastLiveProjectionSignature === signature) {
12380
12523
  return [];
@@ -14306,7 +14449,7 @@ var RuntimeFactory = class {
14306
14449
  const script = new WhiteboardScript(block.content, block.statements);
14307
14450
  collapseUnresolvedChoices(script.statements);
14308
14451
  const stack = new RuntimeStack();
14309
- const clock = new RuntimeClock();
14452
+ const clock = new RuntimeClock(this.nowProvider);
14310
14453
  const eventBus = new EventBus();
14311
14454
  const dependencies = {
14312
14455
  stack,
@@ -14541,6 +14684,7 @@ function compose(builder, template) {
14541
14684
  completionConfig,
14542
14685
  injectRest: t2.injectRest,
14543
14686
  required: t2.required,
14687
+ polarity: t2.polarity,
14544
14688
  ...template.countdownTimerConfig ?? {}
14545
14689
  });
14546
14690
  }
@@ -14833,6 +14977,14 @@ var GenericTimerStrategy = class {
14833
14977
  const isRequired = statements.some((s) => hasHint(s, CONSUMED_HINTS.REQUIRED_TIMER));
14834
14978
  const injectRest = statements.some((s) => hasHint(s, CONSUMED_HINTS.INJECT_REST));
14835
14979
  const isCountdown = !!(durationMs && direction === "down");
14980
+ const allMetrics = statements.flatMap((s) => [...s.metrics]);
14981
+ const hasRestKeyword = allMetrics.some(
14982
+ (m) => (m.type === wodWikiCore.MetricType.Effort || m.type === wodWikiCore.MetricType.Action) && typeof m.value === "string" && m.value.trim().toLowerCase() === "rest"
14983
+ );
14984
+ const hasNonRestMovement = allMetrics.some(
14985
+ (m) => m.type === wodWikiCore.MetricType.Effort && typeof m.value === "string" && m.value.trim().toLowerCase() !== "rest"
14986
+ );
14987
+ const polarity = hasRestKeyword && !hasNonRestMovement ? "rest" : "work";
14836
14988
  const template = {
14837
14989
  blockType: "Timer",
14838
14990
  defaultLabel: direction === "down" ? "Countdown" : "For Time",
@@ -14845,7 +14997,8 @@ var GenericTimerStrategy = class {
14845
14997
  role: "primary",
14846
14998
  mode: isCountdown ? "complete-block" : "complete-block",
14847
14999
  injectRest,
14848
- required: isRequired
15000
+ required: isRequired,
15001
+ polarity
14849
15002
  },
14850
15003
  pickStatement: (stmts) => stmts.find(
14851
15004
  (s) => s.metrics.some((f) => f.type === wodWikiCore.MetricType.Duration && f.origin !== "runtime")
@@ -15745,6 +15898,551 @@ var SubscriptionManager = class {
15745
15898
  this.subscriptions.clear();
15746
15899
  }
15747
15900
  };
15901
+
15902
+ // src/utils/timeUtils.ts
15903
+ var formatTime = (ms) => {
15904
+ if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
15905
+ return "--:--.--";
15906
+ }
15907
+ const isNegative = ms < 0;
15908
+ const absMs = Math.abs(ms);
15909
+ const totalSeconds = Math.floor(absMs / 1e3);
15910
+ const minutes = Math.floor(totalSeconds / 60);
15911
+ const seconds = totalSeconds % 60;
15912
+ const milliseconds = Math.floor(absMs % 1e3 / 10);
15913
+ const sign = isNegative ? "-" : "";
15914
+ return `${sign}${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
15915
+ };
15916
+ var calculateDuration = (spans, now) => {
15917
+ if (!spans || !Array.isArray(spans)) return 0;
15918
+ return spans.reduce((total, span) => {
15919
+ if ("started" in span) {
15920
+ const start2 = span.started;
15921
+ const end = span.ended ?? now;
15922
+ return total + Math.max(0, end - start2);
15923
+ }
15924
+ const start = span.start instanceof Date ? span.start.getTime() : span.start || 0;
15925
+ const stop = span.stop ? span.stop instanceof Date ? span.stop.getTime() : span.stop : now;
15926
+ return total + Math.max(0, stop - start);
15927
+ }, 0);
15928
+ };
15929
+ var roundToTenth = (seconds) => {
15930
+ if (!Number.isFinite(seconds)) return 0;
15931
+ return Math.round(seconds * 10) / 10;
15932
+ };
15933
+
15934
+ // src/runtime/projection/SessionClockProjection.ts
15935
+ var EXCLUDED_REP_BLOCK_TYPES = {
15936
+ Rounds: true,
15937
+ Group: true,
15938
+ AMRAP: true,
15939
+ EMOM: true,
15940
+ SessionRoot: true,
15941
+ Root: true,
15942
+ Timer: true,
15943
+ Rest: true
15944
+ };
15945
+ function toSpans(spans) {
15946
+ return spans.map((s) => new TimeSpan(s.started, s.ended));
15947
+ }
15948
+ function serializeSpans(spans) {
15949
+ return spans.map(
15950
+ (s) => s.ended !== void 0 ? { started: s.started, ended: s.ended } : { started: s.started }
15951
+ );
15952
+ }
15953
+ function resolveVisualPolarity(params) {
15954
+ if (params.isPaused) return "paused";
15955
+ if (params.direction === "down" && params.durationMs !== void 0 && params.durationMs > 0) {
15956
+ if (params.displayMs <= 0) return "overrun";
15957
+ if (params.displayMs <= 5e3) return "final5";
15958
+ }
15959
+ return params.basePolarity === "rest" ? "rest" : "work";
15960
+ }
15961
+ function isRequiredCountdownLocked(params) {
15962
+ return !params.isPaused && params.required && params.direction === "down" && params.durationMs !== void 0 && params.displayMs > 0;
15963
+ }
15964
+ var WATCHED_CLOCK_MEMORY_TAGS = [
15965
+ "time",
15966
+ "round",
15967
+ "display",
15968
+ "metric:display",
15969
+ "metric:result",
15970
+ "metric:next"
15971
+ ];
15972
+ function observeSessionClockInputs(runtime, onChange) {
15973
+ let skipFlash = false;
15974
+ let skipFlashKey = 0;
15975
+ let skipTimer;
15976
+ let memoryUnsubs = [];
15977
+ const emit = () => onChange({ skipFlash, skipFlashKey });
15978
+ const rebindBlockMemory = () => {
15979
+ memoryUnsubs.forEach((fn) => fn());
15980
+ memoryUnsubs = [];
15981
+ for (const block of runtime.stack.blocks) {
15982
+ for (const tag of WATCHED_CLOCK_MEMORY_TAGS) {
15983
+ for (const loc of block.getMemoryByTag(tag)) {
15984
+ memoryUnsubs.push(loc.subscribe(emit));
15985
+ }
15986
+ }
15987
+ }
15988
+ };
15989
+ rebindBlockMemory();
15990
+ const unsubStack = runtime.subscribeToStack(() => {
15991
+ rebindBlockMemory();
15992
+ emit();
15993
+ });
15994
+ const unsubSkip = runtime.eventBus.on(
15995
+ "timer:skip-attempt",
15996
+ () => {
15997
+ skipFlashKey += 1;
15998
+ skipFlash = true;
15999
+ clearTimeout(skipTimer);
16000
+ emit();
16001
+ skipTimer = setTimeout(() => {
16002
+ skipFlash = false;
16003
+ emit();
16004
+ }, 3e3);
16005
+ },
16006
+ "session-clock-inputs-flash"
16007
+ );
16008
+ return () => {
16009
+ clearTimeout(skipTimer);
16010
+ unsubStack();
16011
+ unsubSkip();
16012
+ memoryUnsubs.forEach((fn) => fn());
16013
+ memoryUnsubs = [];
16014
+ };
16015
+ }
16016
+ function interpolateSessionClockFrame(frame, nowMs) {
16017
+ const activeElapsed = calculateDuration(toSpans(frame.activeSpans), nowMs);
16018
+ const displayMs = frame.direction === "down" && frame.durationMs !== void 0 ? Math.max(0, frame.durationMs - activeElapsed) : activeElapsed;
16019
+ const sessionElapsedMs = frame.sessionSpans.length > 0 ? calculateDuration(toSpans(frame.sessionSpans), nowMs) : frame.sessionElapsedMs;
16020
+ const secondaryTimers = frame.secondaryTimers.map((st) => {
16021
+ const elapsed = calculateDuration(toSpans(st.spans), nowMs);
16022
+ return {
16023
+ ...st,
16024
+ displayMs: st.direction === "down" && st.durationMs !== void 0 ? Math.max(0, st.durationMs - elapsed) : elapsed
16025
+ };
16026
+ });
16027
+ const polarity = resolveVisualPolarity({
16028
+ isPaused: frame.isPaused,
16029
+ basePolarity: frame.basePolarity,
16030
+ direction: frame.direction,
16031
+ durationMs: frame.durationMs,
16032
+ displayMs
16033
+ });
16034
+ const isRequiredLockActive = isRequiredCountdownLocked({
16035
+ isPaused: frame.isPaused,
16036
+ required: frame.required,
16037
+ direction: frame.direction,
16038
+ durationMs: frame.durationMs,
16039
+ displayMs
16040
+ });
16041
+ return {
16042
+ ...frame,
16043
+ displayMs,
16044
+ sessionElapsedMs,
16045
+ secondaryTimers,
16046
+ polarity,
16047
+ isRequiredLockActive
16048
+ };
16049
+ }
16050
+ function readBlockRound(block) {
16051
+ if (!block) return void 0;
16052
+ const round = block.getMemoryByTag("round")[0]?.metrics[0];
16053
+ if (!round || typeof round.current !== "number") return void 0;
16054
+ const display = block.getMemoryByTag("display")[0]?.metrics[0]?.value;
16055
+ const label = display?.roundDisplay ?? (round.total !== void 0 ? `Round ${round.current} of ${round.total}` : `Round ${round.current}`);
16056
+ return { current: round.current, total: round.total, label };
16057
+ }
16058
+ function readNextPreviewText(blocks) {
16059
+ for (const block of blocks) {
16060
+ const nextLocs = block.getMemoryByTag("metric:next");
16061
+ if (nextLocs.length === 0) continue;
16062
+ const merged = wodWikiCore.MetricContainer.empty(block.key.toString());
16063
+ for (const loc of nextLocs) merged.merge(loc.metrics);
16064
+ if (merged.length > 0) {
16065
+ return metricPresentation.presentGroup([...merged], "timer-subtitle").filter((t2) => t2.visible).map((t2) => t2.label).filter(Boolean).join(" ").trim() || null;
16066
+ }
16067
+ }
16068
+ return null;
16069
+ }
16070
+ function extractRepTargets(blocks) {
16071
+ const targets = [];
16072
+ for (const block of blocks) {
16073
+ const blockType = block.blockType ?? "";
16074
+ if (EXCLUDED_REP_BLOCK_TYPES[blockType]) {
16075
+ continue;
16076
+ }
16077
+ if (block.getMemoryByTag("children:status").length > 0) continue;
16078
+ const displayLocs = block.getMemoryByTag("metric:display");
16079
+ const resultLocs = block.getMemoryByTag("metric:result");
16080
+ const blockKey = block.key.toString();
16081
+ const grouped = displayLocs.length > 1;
16082
+ for (let idx = 0; idx < displayLocs.length; idx++) {
16083
+ const loc = displayLocs[idx];
16084
+ let plannedTarget = null;
16085
+ let movementText;
16086
+ for (const m of loc.metrics) {
16087
+ if (m.type === wodWikiCore.MetricType.Rep && m.origin !== "user" && typeof m.value === "number") {
16088
+ plannedTarget = m.value;
16089
+ }
16090
+ if ((m.type === wodWikiCore.MetricType.Effort || m.type === wodWikiCore.MetricType.Action) && typeof m.value === "string" && m.value) {
16091
+ movementText ??= m.value;
16092
+ }
16093
+ }
16094
+ const hasMovementIdentity = plannedTarget !== null || loc.metrics.some(
16095
+ (m) => (m.type === wodWikiCore.MetricType.Effort || m.type === wodWikiCore.MetricType.Action) && (typeof m.value === "string" || typeof m.image === "string")
16096
+ );
16097
+ if (!hasMovementIdentity) continue;
16098
+ let actual = null;
16099
+ if (resultLocs.length > 0) {
16100
+ const resLoc = resultLocs[Math.min(idx, resultLocs.length - 1)];
16101
+ if (resLoc) {
16102
+ const userHits = [];
16103
+ for (const m of resLoc.metrics) {
16104
+ if (m.origin === "user" && m.type === wodWikiCore.MetricType.Rep && typeof m.value === "number") {
16105
+ userHits.push(m);
16106
+ }
16107
+ }
16108
+ const last = userHits[userHits.length - 1];
16109
+ if (last) actual = last.value;
16110
+ }
16111
+ }
16112
+ const sourceId = block.sourceIds[idx] ?? idx;
16113
+ targets.push({
16114
+ occurrenceId: grouped ? `${blockKey}:${sourceId}` : blockKey,
16115
+ blockKey,
16116
+ ...grouped ? { sourceId } : {},
16117
+ label: grouped && movementText ? movementText : block.label,
16118
+ target: plannedTarget,
16119
+ actual
16120
+ });
16121
+ }
16122
+ }
16123
+ return targets;
16124
+ }
16125
+ function projectSessionClock(runtime, options = {}) {
16126
+ const status = options.executionStatus ?? "idle";
16127
+ const isPaused = status === "paused";
16128
+ const skipFlash = options.skipFlash ?? false;
16129
+ const skipFlashKey = options.skipFlashKey ?? 0;
16130
+ if (!runtime) {
16131
+ return {
16132
+ mainLabel: "Timer",
16133
+ displayMs: 0,
16134
+ direction: "up",
16135
+ activeSpans: [],
16136
+ basePolarity: "work",
16137
+ required: false,
16138
+ sessionElapsedMs: 0,
16139
+ sessionSpans: [],
16140
+ polarity: isPaused ? "paused" : "work",
16141
+ isRequiredLockActive: false,
16142
+ secondaryTimers: [],
16143
+ upNext: null,
16144
+ repTargets: [],
16145
+ isRunning: status === "running",
16146
+ isPaused,
16147
+ isNextDisabled: isPaused || options.canNextOverride === false,
16148
+ skipFlash,
16149
+ skipFlashKey
16150
+ };
16151
+ }
16152
+ const nowMs = options.nowMs ?? runtime.nowProvider.nowMs();
16153
+ const blocks = runtime.stack.blocks;
16154
+ const orderedRootToLeaf = [...blocks].reverse();
16155
+ const displayEntries = [];
16156
+ orderedRootToLeaf.forEach((block, index) => {
16157
+ if (block.blockType === "Root" && !block.label) return;
16158
+ const displayRows = block.getMemoryByTag("metric:display").map((loc) => loc.metrics);
16159
+ if (displayRows.length === 0 && !block.label) return;
16160
+ displayEntries.push({
16161
+ block,
16162
+ displayRows,
16163
+ label: block.label,
16164
+ isLeaf: index === orderedRootToLeaf.length - 1
16165
+ });
16166
+ });
16167
+ const leafEntry = displayEntries.find((e) => e.isLeaf);
16168
+ const roundsEntry = displayEntries.find((e) => e.block.blockType === "Rounds") ?? displayEntries.find((e) => e.block.getMemoryByTag("round").length > 0 && e.block.blockType !== "SessionRoot");
16169
+ const roundInfo = readBlockRound(roundsEntry?.block);
16170
+ const roundsLabel = roundInfo?.label ?? roundsEntry?.label;
16171
+ const allTimers = [];
16172
+ for (const block of blocks) {
16173
+ const timer = block.getMemoryByTag("time")[0]?.metrics[0]?.value;
16174
+ if (!timer) continue;
16175
+ allTimers.push({
16176
+ block,
16177
+ timer,
16178
+ isPinned: timer.role === "primary"
16179
+ });
16180
+ }
16181
+ const isAnyTimerRunning = allTimers.some(
16182
+ (t2) => t2.timer.spans.some((s) => s.ended === void 0)
16183
+ );
16184
+ const topTimer = allTimers[0];
16185
+ const primaryTimer = topTimer && (topTimer.block.blockType === "Rest" || topTimer.timer.polarity === "rest") ? topTimer : [...allTimers].reverse().find((t2) => t2.isPinned) ?? topTimer;
16186
+ const leafTimer = leafEntry ? allTimers.find((t2) => t2.block.key.toString() === leafEntry.block.key.toString()) : void 0;
16187
+ const isRestHero = primaryTimer?.block.blockType === "Rest" || primaryTimer?.timer.polarity === "rest";
16188
+ const active = isRestHero || primaryTimer?.isPinned ? primaryTimer : leafTimer ?? primaryTimer;
16189
+ const leafLabel = leafEntry?.label;
16190
+ const mainLabel = (isRestHero ? primaryTimer?.block.label || primaryTimer?.timer.label : primaryTimer?.isPinned ? roundsLabel || primaryTimer.timer.label : roundsLabel && roundsLabel !== leafLabel ? roundsLabel : leafLabel || primaryTimer?.timer.label) || "Timer";
16191
+ const subLabel = isRestHero && roundsLabel && roundsLabel !== mainLabel ? roundsLabel : mainLabel === leafLabel ? void 0 : leafLabel;
16192
+ let subLabels;
16193
+ if (!isRestHero && leafEntry && leafEntry.displayRows.length > 1) {
16194
+ const lines = leafEntry.displayRows.map(
16195
+ (row) => metricPresentation.presentGroup([...row], "timer-subtitle").filter((t2) => t2.visible).map((t2) => t2.label).filter(Boolean).join(" ").trim()
16196
+ ).filter(Boolean);
16197
+ if (lines.length > 0) subLabels = lines;
16198
+ }
16199
+ if (!subLabels) subLabels = subLabel ? [subLabel] : void 0;
16200
+ const activeDirection = active?.timer.direction ?? "up";
16201
+ const activeDurationMs = active?.timer.durationMs;
16202
+ const activeSpans = active ? serializeSpans(active.timer.spans) : [];
16203
+ let displayMs = 0;
16204
+ if (active) {
16205
+ const elapsed = calculateDuration(active.timer.spans, nowMs);
16206
+ displayMs = activeDirection === "down" && activeDurationMs !== void 0 ? Math.max(0, activeDurationMs - elapsed) : elapsed;
16207
+ }
16208
+ const withElapsed = allTimers.map((entry) => ({
16209
+ entry,
16210
+ elapsed: calculateDuration(entry.timer.spans, nowMs)
16211
+ }));
16212
+ const sessionHolder = withElapsed.find((e) => e.entry.block.blockType === "SessionRoot") ?? withElapsed.reduce(
16213
+ (best, cur) => cur.elapsed > (best?.elapsed ?? -1) ? cur : best,
16214
+ withElapsed[withElapsed.length - 1]
16215
+ );
16216
+ const sessionElapsedMs = sessionHolder?.elapsed ?? 0;
16217
+ const sessionSpans = sessionHolder ? serializeSpans(sessionHolder.entry.timer.spans) : [];
16218
+ const activeKey = active?.block.key.toString();
16219
+ const sessionKey = sessionHolder?.entry.block.key.toString();
16220
+ const secondaryTimers = allTimers.filter((t2) => {
16221
+ if (t2.timer.role === "hidden") return false;
16222
+ const key = t2.block.key.toString();
16223
+ return key !== activeKey && key !== sessionKey;
16224
+ }).map((t2) => {
16225
+ const elapsed = calculateDuration(t2.timer.spans, nowMs);
16226
+ return {
16227
+ id: t2.block.key.toString(),
16228
+ label: t2.timer.label || t2.block.label || "Timer",
16229
+ displayMs: t2.timer.direction === "down" && t2.timer.durationMs !== void 0 ? Math.max(0, t2.timer.durationMs - elapsed) : elapsed,
16230
+ direction: t2.timer.direction,
16231
+ durationMs: t2.timer.durationMs,
16232
+ spans: serializeSpans(t2.timer.spans)
16233
+ };
16234
+ });
16235
+ const basePolarity = active?.block.blockType === "Rest" || active?.timer.polarity === "rest" ? "rest" : "work";
16236
+ const required = Boolean(active?.timer.required);
16237
+ const polarity = resolveVisualPolarity({
16238
+ isPaused,
16239
+ basePolarity,
16240
+ direction: activeDirection,
16241
+ durationMs: activeDurationMs,
16242
+ displayMs
16243
+ });
16244
+ const isRequiredLockActive = isRequiredCountdownLocked({
16245
+ isPaused,
16246
+ required,
16247
+ direction: activeDirection,
16248
+ durationMs: activeDurationMs,
16249
+ displayMs
16250
+ });
16251
+ return {
16252
+ mainLabel,
16253
+ subLabels,
16254
+ displayMs,
16255
+ direction: activeDirection,
16256
+ durationMs: activeDurationMs,
16257
+ activeSpans,
16258
+ basePolarity,
16259
+ required,
16260
+ sessionElapsedMs,
16261
+ sessionSpans,
16262
+ polarity,
16263
+ isRequiredLockActive,
16264
+ roundCurrent: roundInfo?.current,
16265
+ roundTotal: roundInfo?.total,
16266
+ roundLabel: roundInfo?.label,
16267
+ secondaryTimers,
16268
+ upNext: readNextPreviewText(blocks),
16269
+ repTargets: extractRepTargets(blocks),
16270
+ isRunning: isAnyTimerRunning || status === "running",
16271
+ isPaused,
16272
+ isNextDisabled: isPaused || options.canNextOverride === false,
16273
+ skipFlash,
16274
+ skipFlashKey
16275
+ };
16276
+ }
16277
+ var NON_LABEL_SEGMENT_METRIC_TYPES = {
16278
+ [wodWikiCore.MetricType.Elapsed]: true,
16279
+ [wodWikiCore.MetricType.Total]: true,
16280
+ [wodWikiCore.MetricType.Spans]: true,
16281
+ [wodWikiCore.MetricType.SystemTime]: true,
16282
+ [wodWikiCore.MetricType.CurrentRound]: true,
16283
+ [wodWikiCore.MetricType.System]: true
16284
+ };
16285
+ function projectionsToUniqueSummaries(projections) {
16286
+ const byName = /* @__PURE__ */ new Map();
16287
+ for (const proj of projections) {
16288
+ byName.set(proj.name, {
16289
+ key: proj.name,
16290
+ label: computeColumnLabel(proj.name),
16291
+ value: proj.value,
16292
+ unit: proj.unit,
16293
+ metricType: proj.metricType ?? wodWikiCore.MetricType.Metric,
16294
+ origin: proj.origin
16295
+ });
16296
+ }
16297
+ return [...byName.values()];
16298
+ }
16299
+ function fallbackSummariesFromOutputs(outputs) {
16300
+ const byName = /* @__PURE__ */ new Map();
16301
+ for (const output of outputs) {
16302
+ const metrics = output.metrics;
16303
+ for (let j = 0; j + 1 < metrics.length; j += 2) {
16304
+ const labelMetric = metrics[j];
16305
+ const valueMetric = metrics[j + 1];
16306
+ if (!labelMetric || !valueMetric || typeof valueMetric.value !== "number") continue;
16307
+ const name2 = labelMetric.image ?? String(labelMetric.value);
16308
+ byName.set(name2, {
16309
+ key: name2,
16310
+ label: computeColumnLabel(name2),
16311
+ value: valueMetric.value,
16312
+ unit: valueMetric.unit ?? "",
16313
+ metricType: valueMetric.type || wodWikiCore.MetricType.Metric,
16314
+ origin: valueMetric.origin
16315
+ });
16316
+ }
16317
+ }
16318
+ return [...byName.values()];
16319
+ }
16320
+ function formatSplitDeltaLabel(deltaMs) {
16321
+ const deltaSec = Math.round(deltaMs / 1e3);
16322
+ if (deltaSec === 0) return "even";
16323
+ return deltaSec > 0 ? `+${deltaSec}s` : `${deltaSec}s`;
16324
+ }
16325
+ function readRoundFromOutput(output) {
16326
+ const metric = output.getMetric(wodWikiCore.MetricType.CurrentRound);
16327
+ if (!metric) return {};
16328
+ const round = typeof metric.value === "number" ? metric.value : void 0;
16329
+ let totalRounds;
16330
+ if ("total" in metric && typeof metric.total === "number") {
16331
+ totalRounds = metric.total;
16332
+ }
16333
+ return { round, totalRounds };
16334
+ }
16335
+ function deriveRoundSplits(outputs) {
16336
+ const previousElapsedByKey = /* @__PURE__ */ new Map();
16337
+ const rows = [];
16338
+ for (let idx = 0; idx < outputs.length; idx++) {
16339
+ const out = outputs[idx];
16340
+ if (out.outputType !== "segment") continue;
16341
+ if (out.sourceBlockKey.startsWith("session-root")) continue;
16342
+ if (out.completionReason === "rounds-complete") continue;
16343
+ if (out.sourceStatementId === void 0 && !out.sourceBlockKey.startsWith("rest")) continue;
16344
+ const elapsedVal = out.getMetric(wodWikiCore.MetricType.Elapsed)?.value;
16345
+ const fallbackSpanElapsed = out.timeSpan.ended !== void 0 ? Math.max(0, out.timeSpan.ended - out.timeSpan.started) : 0;
16346
+ const elapsedMs = typeof elapsedVal === "number" ? elapsedVal : fallbackSpanElapsed;
16347
+ if (!Number.isFinite(elapsedMs)) continue;
16348
+ const displayTokens = metricPresentation.presentGroup(
16349
+ out.metrics.filter((m) => !NON_LABEL_SEGMENT_METRIC_TYPES[m.type]),
16350
+ "timer-subtitle"
16351
+ ).filter((t2) => t2.visible).map((t2) => t2.label).filter(Boolean).join(" ").trim();
16352
+ const label = displayTokens || out.text?.trim() || (out.sourceBlockKey.startsWith("rest") ? "Rest" : "Segment");
16353
+ const comparisonKey = out.sourceStatementId !== void 0 ? `stmt:${out.sourceStatementId}` : `key:${label.toLowerCase()}`;
16354
+ const prevElapsed = previousElapsedByKey.get(comparisonKey);
16355
+ const deltaMs = prevElapsed !== void 0 ? elapsedMs - prevElapsed : void 0;
16356
+ previousElapsedByKey.set(comparisonKey, elapsedMs);
16357
+ const { round, totalRounds } = readRoundFromOutput(out);
16358
+ rows.push({
16359
+ id: `${out.sourceBlockKey}:${idx}`,
16360
+ comparisonKey,
16361
+ label,
16362
+ elapsedMs,
16363
+ ...round !== void 0 ? { round } : {},
16364
+ ...totalRounds !== void 0 ? { totalRounds } : {},
16365
+ ...deltaMs !== void 0 ? { deltaMs, deltaLabel: formatSplitDeltaLabel(deltaMs) } : {}
16366
+ });
16367
+ }
16368
+ return rows;
16369
+ }
16370
+ function projectLiveSessionTelemetry(runtime) {
16371
+ if (!runtime) {
16372
+ return { summaries: [], splits: [] };
16373
+ }
16374
+ const typedProjections = runtime.getLiveProjections?.();
16375
+ const summaries = typedProjections && typedProjections.length > 0 ? projectionsToUniqueSummaries(typedProjections) : fallbackSummariesFromOutputs(runtime.getLiveAnalytics?.() ?? []);
16376
+ const splits = deriveRoundSplits(runtime.getOutputStatements());
16377
+ return { summaries, splits };
16378
+ }
16379
+ function formatStatementLabel(statement) {
16380
+ const presented = metricPresentation.presentGroup(
16381
+ [...statement.metrics].filter((m) => m.type !== wodWikiCore.MetricType.Hint),
16382
+ "timer-subtitle"
16383
+ ).filter((t2) => t2.visible).map((t2) => t2.label).filter(Boolean).join(" ").trim();
16384
+ return presented || statement.text?.trim() || "Step";
16385
+ }
16386
+ function synthesizeWorkoutFormat(script) {
16387
+ const statements = script?.statements;
16388
+ if (!statements || statements.length === 0) return void 0;
16389
+ const roots = statements.filter((s) => s.parent === void 0);
16390
+ const primaryRoot = roots[0] ?? statements[0];
16391
+ if (!primaryRoot) return void 0;
16392
+ const hasChildren = (primaryRoot.children?.length ?? 0) > 0;
16393
+ 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);
16394
+ const hasStructuralMetric = primaryRoot.metrics.some(
16395
+ (m) => m.type === wodWikiCore.MetricType.Rounds || m.type === wodWikiCore.MetricType.Duration
16396
+ );
16397
+ if (!hasChildren && !hasProtocolHint && !hasStructuralMetric) {
16398
+ return void 0;
16399
+ }
16400
+ return formatStatementLabel(primaryRoot);
16401
+ }
16402
+ function projectScriptOutline(runtime) {
16403
+ const statements = runtime?.script?.statements;
16404
+ if (!runtime || !statements || statements.length === 0) return [];
16405
+ const activeIds = /* @__PURE__ */ new Set();
16406
+ for (const block of runtime.stack.blocks) {
16407
+ if (block.blockType === "SessionRoot" || block.blockType === "WaitingToStart") continue;
16408
+ for (const id of block.sourceIds) {
16409
+ if (typeof id === "number") activeIds.add(id);
16410
+ }
16411
+ }
16412
+ const completedIds = /* @__PURE__ */ new Set();
16413
+ for (const out of runtime.getOutputStatements()) {
16414
+ if (out.outputType === "segment" && typeof out.sourceStatementId === "number") {
16415
+ completedIds.add(out.sourceStatementId);
16416
+ }
16417
+ }
16418
+ const depthOf = (stmt) => {
16419
+ let depth = 0;
16420
+ let cur = stmt.parent;
16421
+ const seen = /* @__PURE__ */ new Set();
16422
+ while (cur !== void 0 && !seen.has(cur)) {
16423
+ seen.add(cur);
16424
+ const parentStmt = runtime.script.getId(cur);
16425
+ if (!parentStmt) break;
16426
+ depth += 1;
16427
+ cur = parentStmt.parent;
16428
+ }
16429
+ return depth;
16430
+ };
16431
+ const nodes = [];
16432
+ for (const stmt of statements) {
16433
+ if (typeof stmt.id !== "number") continue;
16434
+ const label = formatStatementLabel(stmt);
16435
+ if (!label) continue;
16436
+ const status = activeIds.has(stmt.id) ? "active" : completedIds.has(stmt.id) ? "completed" : "upcoming";
16437
+ nodes.push({
16438
+ statementId: stmt.id,
16439
+ depth: depthOf(stmt),
16440
+ label,
16441
+ status
16442
+ });
16443
+ }
16444
+ return nodes;
16445
+ }
15748
16446
  function formatMetricLabel(key) {
15749
16447
  return key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, " ");
15750
16448
  }
@@ -16061,38 +16759,6 @@ function toStoredOutputStatement(output) {
16061
16759
  };
16062
16760
  }
16063
16761
 
16064
- // src/utils/timeUtils.ts
16065
- var formatTime = (ms) => {
16066
- if (ms === void 0 || ms === null || !Number.isFinite(ms)) {
16067
- return "--:--.--";
16068
- }
16069
- const isNegative = ms < 0;
16070
- const absMs = Math.abs(ms);
16071
- const totalSeconds = Math.floor(absMs / 1e3);
16072
- const minutes = Math.floor(totalSeconds / 60);
16073
- const seconds = totalSeconds % 60;
16074
- const milliseconds = Math.floor(absMs % 1e3 / 10);
16075
- const sign = isNegative ? "-" : "";
16076
- return `${sign}${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
16077
- };
16078
- var calculateDuration = (spans, now) => {
16079
- if (!spans || !Array.isArray(spans)) return 0;
16080
- return spans.reduce((total, span) => {
16081
- if ("started" in span) {
16082
- const start2 = span.started;
16083
- const end = span.ended ?? now;
16084
- return total + Math.max(0, end - start2);
16085
- }
16086
- const start = span.start instanceof Date ? span.start.getTime() : span.start || 0;
16087
- const stop = span.stop ? span.stop instanceof Date ? span.stop.getTime() : span.stop : now;
16088
- return total + Math.max(0, stop - start);
16089
- }, 0);
16090
- };
16091
- var roundToTenth = (seconds) => {
16092
- if (!Number.isFinite(seconds)) return 0;
16093
- return Math.round(seconds * 10) / 10;
16094
- };
16095
-
16096
16762
  // src/parser-fixture/metricLine.ts
16097
16763
  var TAIL_TOKEN_RE = /[\w-]+:(?:"(?:[^"\\]|\\.)*"|[^ ]+)/g;
16098
16764
  var FixtureSyntaxError = class extends Error {
@@ -16532,11 +17198,13 @@ exports.hasHint = hasHint;
16532
17198
  exports.hintMetric = hintMetric;
16533
17199
  exports.hintsToContainer = hintsToContainer;
16534
17200
  exports.inferDim = inferDim;
17201
+ exports.interpolateSessionClockFrame = interpolateSessionClockFrame;
16535
17202
  exports.isCastSubscription = isCastSubscription;
16536
17203
  exports.isChoiceResolved = isChoiceResolved;
16537
17204
  exports.isDimensionless = isDimensionless;
16538
17205
  exports.isEffortDiscipline = isEffortDiscipline;
16539
17206
  exports.isFragmentTag = isFragmentTag;
17207
+ exports.isRequiredCountdownLocked = isRequiredCountdownLocked;
16540
17208
  exports.isTimeLikeMetric = isTimeLikeMetric;
16541
17209
  exports.isWithinThreshold = isWithinThreshold;
16542
17210
  exports.levenshteinDistance = levenshteinDistance;
@@ -16544,6 +17212,7 @@ exports.metricPresentation = metricPresentation;
16544
17212
  exports.mutateTimerSpans = mutateTimerSpans;
16545
17213
  exports.normalizeForFuzzy = normalizeForFuzzy;
16546
17214
  exports.num = num;
17215
+ exports.observeSessionClockInputs = observeSessionClockInputs;
16547
17216
  exports.openSpan = openSpan;
16548
17217
  exports.outputNodeId = outputNodeId;
16549
17218
  exports.outputNodeIds = outputNodeIds;
@@ -16557,6 +17226,9 @@ exports.parseMetricLine = parseMetricLine;
16557
17226
  exports.parseScript = parseScript;
16558
17227
  exports.parseSoundTrigger = parseSoundTrigger;
16559
17228
  exports.printCalculation = printCalculation;
17229
+ exports.projectLiveSessionTelemetry = projectLiveSessionTelemetry;
17230
+ exports.projectScriptOutline = projectScriptOutline;
17231
+ exports.projectSessionClock = projectSessionClock;
16560
17232
  exports.readNestedSection = readNestedSection;
16561
17233
  exports.readTimer = readTimer;
16562
17234
  exports.realtimeProcessorRegistry = realtimeProcessorRegistry;
@@ -16571,6 +17243,7 @@ exports.resolveSoundProfile = resolveSoundProfile;
16571
17243
  exports.resolveSourceRank = resolveSourceRank;
16572
17244
  exports.resolveSourceTier = resolveSourceTier;
16573
17245
  exports.resolveTagContributions = resolveTagContributions;
17246
+ exports.resolveVisualPolarity = resolveVisualPolarity;
16574
17247
  exports.roundToTenth = roundToTenth;
16575
17248
  exports.runMetricShakeOutQueue = runMetricShakeOutQueue;
16576
17249
  exports.slugifyRefLabel = slugifyRefLabel;
@@ -16580,6 +17253,7 @@ exports.str = str;
16580
17253
  exports.strategyRegistry = strategyRegistry;
16581
17254
  exports.subDim = subDim;
16582
17255
  exports.summaryProcessorRegistry = summaryProcessorRegistry;
17256
+ exports.synthesizeWorkoutFormat = synthesizeWorkoutFormat;
16583
17257
  exports.tagCategoryRecordToDocument = tagCategoryRecordToDocument;
16584
17258
  exports.tagCategoryToDocument = tagCategoryToDocument;
16585
17259
  exports.tagContributionMetrics = tagContributionMetrics;