@trainheroic-unofficial/cli 3.5.1 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.mjs +586 -144
  2. package/package.json +3 -3
package/dist/cli.mjs CHANGED
@@ -763,15 +763,19 @@ const workoutSpecSchema = z.object({
763
763
  /**
764
764
  * Parse a `YYYY-M-D` string into the `WorkoutDate` tuple. The single home for this
765
765
  * conversion, shared by the MCP tools and the CLI so they cannot drift on what counts
766
- * as a valid date. Each part must be an integer.
766
+ * as a valid date. Each part must be a run of digits (`Number("")` is 0, so a blank part such as
767
+ * the trailing one in "2026-9-" must be rejected explicitly), and month/day must be in range so
768
+ * a typo cannot land a session on a date the calendar does not have.
767
769
  */
768
770
  function parseWorkoutDate(s) {
769
- const parts = s.split("-").map((p) => Number(p));
770
- if (parts.length !== 3 || parts.some((n) => !Number.isInteger(n))) throw new Error(`date must be YYYY-M-D, got "${s}".`);
771
+ const parts = s.split("-");
772
+ if (parts.length !== 3 || parts.some((p) => !/^\d+$/u.test(p))) throw new Error(`date must be YYYY-M-D, got "${s}".`);
773
+ const [year, month, day] = parts.map(Number);
774
+ if (month < 1 || month > 12 || day < 1 || day > 31) throw new Error(`date must be YYYY-M-D with a real month and day, got "${s}".`);
771
775
  return [
772
- parts[0],
773
- parts[1],
774
- parts[2]
776
+ year,
777
+ month,
778
+ day
775
779
  ];
776
780
  }
777
781
  /** Body for `POST /v5/sessions/template` (library create, not save-from-session). */
@@ -781,30 +785,200 @@ const sessionTemplateCreateSchema = z.object({
781
785
  });
782
786
  //#endregion
783
787
  //#region ../js/src/http-error.ts
784
- /**
785
- * A final non-2xx response from TrainHeroic. The error deliberately carries only request
786
- * metadata that is safe to send to telemetry: never the path, query string, request body,
787
- * response body, credentials, or session token.
788
- */
788
+ const MAX_REQUEST_KEYS = 50;
789
+ const MAX_RESPONSE_DEPTH = 4;
790
+ const MAX_RESPONSE_KEYS = 20;
791
+ const MAX_RESPONSE_ITEMS = 10;
792
+ const MAX_RESPONSE_NODES = 50;
793
+ const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
794
+ "code",
795
+ "detail",
796
+ "details",
797
+ "error",
798
+ "error_code",
799
+ "errors",
800
+ "message",
801
+ "reason",
802
+ "status",
803
+ "status_code",
804
+ "success"
805
+ ]);
806
+ const RESPONSE_CONTAINER_KEYS = /* @__PURE__ */ new Set([
807
+ "data",
808
+ "received",
809
+ "response",
810
+ "result"
811
+ ]);
812
+ const RESPONSE_STATUS_KEYS = /* @__PURE__ */ new Set(["status", "status_code"]);
813
+ const RESPONSE_BOOLEAN_KEYS = /* @__PURE__ */ new Set(["success"]);
814
+ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
815
+ 0,
816
+ 1,
817
+ 2,
818
+ 3,
819
+ 4,
820
+ 5,
821
+ 6,
822
+ 7,
823
+ 10,
824
+ 11,
825
+ 12,
826
+ 13,
827
+ 14,
828
+ 18
829
+ ]);
830
+ function safeFieldName(key) {
831
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
832
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
833
+ return key;
834
+ }
835
+ function boundedEntries(object, limit) {
836
+ const entries = [];
837
+ for (const key of Object.keys(object)) {
838
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
839
+ entries.push([key, descriptor && "value" in descriptor ? descriptor.value : void 0]);
840
+ if (entries.length >= limit) break;
841
+ }
842
+ return entries;
843
+ }
844
+ function safeRequestValue(key, value) {
845
+ if (key === "is_circuit" && typeof value === "boolean") return value;
846
+ if (["param_1_type", "param_2_type"].includes(key) && typeof value === "number" && PARAMETER_TYPES.has(value)) return value;
847
+ }
848
+ function requestBodySummary(body) {
849
+ if (Array.isArray(body)) return {
850
+ type: "array",
851
+ length: body.length
852
+ };
853
+ if (body && typeof body === "object") {
854
+ const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
855
+ const keys = entries.map(([key]) => safeFieldName(key));
856
+ const values = {};
857
+ for (const [key, value] of entries) {
858
+ const safeValue = safeRequestValue(key, value);
859
+ if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
860
+ }
861
+ return Object.keys(values).length > 0 ? {
862
+ type: "object",
863
+ keys,
864
+ values
865
+ } : {
866
+ type: "object",
867
+ keys
868
+ };
869
+ }
870
+ const primitive = typeof body;
871
+ return primitive === "boolean" || primitive === "number" || primitive === "string" ? { type: primitive } : { type: "other" };
872
+ }
873
+ function sanitizedDiagnosticValue(value, depth, budget, field) {
874
+ if (budget.nodes <= 0) return "[Truncated]";
875
+ budget.nodes -= 1;
876
+ if (value === null) return null;
877
+ if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
878
+ if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
879
+ if (typeof value === "string") return "[Redacted]";
880
+ if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
881
+ if (Array.isArray(value)) {
882
+ const result = [];
883
+ for (const item of value.slice(0, MAX_RESPONSE_ITEMS)) {
884
+ if (budget.nodes <= 0) {
885
+ result.push("[Truncated]");
886
+ break;
887
+ }
888
+ result.push(sanitizedDiagnosticValue(item, depth + 1, budget));
889
+ }
890
+ return result;
891
+ }
892
+ if (value && typeof value === "object") {
893
+ const result = {};
894
+ for (const [key, item] of boundedEntries(value, MAX_RESPONSE_KEYS)) {
895
+ if (budget.nodes <= 0) {
896
+ result.truncated = "[Truncated]";
897
+ break;
898
+ }
899
+ const safeKey = safeFieldName(key);
900
+ const safeValue = safeRequestValue(key, item);
901
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget, key);
902
+ else if (RESPONSE_CONTAINER_KEYS.has(key) && item && typeof item === "object") result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget);
903
+ else if (safeValue !== void 0) {
904
+ budget.nodes -= 1;
905
+ result[safeKey] = safeValue;
906
+ }
907
+ }
908
+ return result;
909
+ }
910
+ return `[${typeof value}]`;
911
+ }
912
+ function responseBodyDiagnostics(body, budget, depth = 0) {
913
+ const activeBudget = budget ?? { nodes: MAX_RESPONSE_NODES };
914
+ if (activeBudget.nodes <= 0 || depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
915
+ if (!body || typeof body !== "object" || Array.isArray(body)) return sanitizedDiagnosticValue(body, depth, activeBudget);
916
+ const object = body;
917
+ const result = {};
918
+ for (const [key, value] of boundedEntries(object, MAX_RESPONSE_KEYS)) {
919
+ if (activeBudget.nodes <= 0) {
920
+ result.truncated = "[Truncated]";
921
+ break;
922
+ }
923
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) {
924
+ result[safeFieldName(key)] = sanitizedDiagnosticValue(value, depth + 1, activeBudget, key);
925
+ continue;
926
+ }
927
+ if (RESPONSE_CONTAINER_KEYS.has(key) && value && typeof value === "object") {
928
+ activeBudget.nodes -= 1;
929
+ const nested = responseBodyDiagnostics(value, activeBudget, depth + 1);
930
+ if (nested === "[Truncated]" || nested && typeof nested === "object" && Object.keys(nested).length > 0) result[safeFieldName(key)] = nested;
931
+ }
932
+ }
933
+ if (Object.keys(result).length > 0) return result;
934
+ return { type: "object" };
935
+ }
936
+ function parseResponseText(text) {
937
+ if (text.length === 0) return text;
938
+ try {
939
+ return JSON.parse(text);
940
+ } catch {
941
+ return text;
942
+ }
943
+ }
944
+ function safeRequestBodySummary(body) {
945
+ try {
946
+ return requestBodySummary(body);
947
+ } catch {
948
+ return { type: "other" };
949
+ }
950
+ }
951
+ function safeResponseBodyDiagnostics(body) {
952
+ try {
953
+ return responseBodyDiagnostics(body);
954
+ } catch {
955
+ return "[Unavailable]";
956
+ }
957
+ }
958
+ /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
789
959
  var TrainHeroicHttpError = class extends Error {
790
960
  name = "TrainHeroicHttpError";
791
961
  method;
792
962
  status;
793
963
  host;
794
- constructor(method, url, status) {
964
+ requestBody;
965
+ responseBody;
966
+ constructor(method, url, status, diagnostics = {}) {
795
967
  const parsed = new URL(url);
796
968
  const normalizedMethod = method.toUpperCase();
797
969
  super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
798
970
  this.method = normalizedMethod;
799
971
  this.status = status;
800
972
  this.host = parsed.host;
973
+ this.requestBody = diagnostics.requestBody === void 0 ? void 0 : safeRequestBodySummary(diagnostics.requestBody);
974
+ this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
801
975
  }
802
976
  };
803
977
  /** Call observability hooks without allowing them to change SDK behavior. */
804
- function notifyHttpError(handler, method, url, status) {
978
+ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
805
979
  if (!handler) return;
806
980
  try {
807
- Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
981
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
808
982
  } catch {}
809
983
  }
810
984
  //#endregion
@@ -928,14 +1102,19 @@ var TrainHeroicClient = class {
928
1102
  session = await this.#ensureSession();
929
1103
  res = await this.#send(method, url, session, options.body);
930
1104
  }
931
- if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
932
- const text = await res.text();
933
- let data = text;
934
- if (text.length > 0) try {
935
- data = JSON.parse(text);
936
- } catch {
937
- data = text;
1105
+ const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
1106
+ let text;
1107
+ try {
1108
+ text = await res.text();
1109
+ } catch (error) {
1110
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
1111
+ throw error;
938
1112
  }
1113
+ const data = parseResponseText(text);
1114
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
1115
+ requestBody: options.body,
1116
+ responseBody: data
1117
+ });
939
1118
  return {
940
1119
  status: res.status,
941
1120
  ok: res.ok,
@@ -974,6 +1153,26 @@ function checkResponse(schema, data, label) {
974
1153
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
975
1154
  }
976
1155
  //#endregion
1156
+ //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
1157
+ /**
1158
+ * Creates a duplicate-free version of an array.
1159
+ *
1160
+ * This function takes an array and returns a new array containing only the unique values
1161
+ * from the original array, preserving the order of first occurrence.
1162
+ *
1163
+ * @template T - The type of elements in the array.
1164
+ * @param arr - The array to process.
1165
+ * @returns A new array with only unique values from the original array.
1166
+ *
1167
+ * @example
1168
+ * const array = [1, 2, 2, 3, 4, 4, 5];
1169
+ * const result = uniq(array);
1170
+ * // result will be [1, 2, 3, 4, 5]
1171
+ */
1172
+ function uniq(arr) {
1173
+ return [...new Set(arr)];
1174
+ }
1175
+ //#endregion
977
1176
  //#region ../js/src/exercise-util.ts
978
1177
  /**
979
1178
  * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
@@ -1147,18 +1346,76 @@ function rankSearch(rows, query, limit) {
1147
1346
  * on workerd, blowing the subrequest budget.
1148
1347
  */
1149
1348
  async function mapPool(items, limit, fn) {
1349
+ assertPositiveInteger(limit, "Concurrency limit");
1150
1350
  const out = Array.from({ length: items.length });
1151
1351
  let next = 0;
1352
+ const state = { failure: null };
1152
1353
  const worker = async () => {
1153
- while (next < items.length) {
1354
+ while (next < items.length && state.failure === null) {
1154
1355
  const i = next;
1155
1356
  next += 1;
1156
- out[i] = await fn(items[i], i);
1357
+ try {
1358
+ out[i] = await fn(items[i], i);
1359
+ } catch (error) {
1360
+ state.failure ??= { error };
1361
+ }
1157
1362
  }
1158
1363
  };
1159
1364
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
1365
+ if (state.failure !== null) throw state.failure.error;
1160
1366
  return out;
1161
1367
  }
1368
+ function createLimiter(max) {
1369
+ assertPositiveInteger(max, "Maximum concurrency");
1370
+ let active = 0;
1371
+ let cancelled = null;
1372
+ const waiting = [];
1373
+ const acquire = (finalizer) => new Promise((resolve, reject) => {
1374
+ if (cancelled !== null && !finalizer) reject(cancelled.error);
1375
+ else if (active < max) {
1376
+ active += 1;
1377
+ resolve();
1378
+ } else waiting.push({
1379
+ start: () => {
1380
+ active += 1;
1381
+ resolve();
1382
+ },
1383
+ abort: reject,
1384
+ finalizer
1385
+ });
1386
+ });
1387
+ const release = () => {
1388
+ active -= 1;
1389
+ waiting.shift()?.start();
1390
+ };
1391
+ return {
1392
+ async run(task) {
1393
+ await acquire(false);
1394
+ try {
1395
+ return await task();
1396
+ } finally {
1397
+ release();
1398
+ }
1399
+ },
1400
+ async runFinalizer(task) {
1401
+ await acquire(true);
1402
+ try {
1403
+ return await task();
1404
+ } finally {
1405
+ release();
1406
+ }
1407
+ },
1408
+ cancel(error) {
1409
+ cancelled ??= { error };
1410
+ const queued = waiting.splice(0);
1411
+ for (const entry of queued) if (entry.finalizer) waiting.push(entry);
1412
+ else entry.abort(error);
1413
+ }
1414
+ };
1415
+ }
1416
+ function assertPositiveInteger(value, label) {
1417
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1418
+ }
1162
1419
  //#endregion
1163
1420
  //#region ../js/src/athlete.ts
1164
1421
  async function getJson(client, path, label) {
@@ -1212,39 +1469,25 @@ function sortRosterByRecency(rows) {
1212
1469
  * summary becomes a null-data row (sorted last), not an error.
1213
1470
  */
1214
1471
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
1215
- const rows = [];
1216
- const concurrency = 6;
1217
- const uniqueAthleteIds = [...new Set(athleteIds)];
1218
- for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
1219
- const chunk = uniqueAthleteIds.slice(i, i + concurrency);
1220
- const settled = await Promise.all(chunk.map(async (id) => {
1221
- try {
1222
- return {
1223
- id,
1224
- summary: await fetchAthleteProfileSummary(client, id, useMetric)
1225
- };
1226
- } catch {
1227
- return {
1228
- id,
1229
- summary: null
1230
- };
1231
- }
1232
- }));
1233
- for (const { id, summary } of settled) {
1234
- const count = summary?.sessions_count ?? null;
1235
- const hasSessions = count !== null && count > 0;
1236
- const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1237
- rows.push({
1238
- athleteId: id,
1239
- sessionsCount: count,
1240
- firstLoggedDate: normDate(summary?.first_logged_date),
1241
- lastLoggedDate: normDate(summary?.last_logged_date),
1242
- totalReps: summary?.reps_sum ?? null,
1243
- totalVolume: summary?.volume_sum ?? null
1244
- });
1472
+ return sortRosterByRecency(await mapPool(uniq(athleteIds), 6, async (id) => {
1473
+ let summary;
1474
+ try {
1475
+ summary = await fetchAthleteProfileSummary(client, id, useMetric);
1476
+ } catch {
1477
+ summary = null;
1245
1478
  }
1246
- }
1247
- return sortRosterByRecency(rows);
1479
+ const count = summary?.sessions_count ?? null;
1480
+ const hasSessions = count !== null && count > 0;
1481
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1482
+ return {
1483
+ athleteId: id,
1484
+ sessionsCount: count,
1485
+ firstLoggedDate: normDate(summary?.first_logged_date),
1486
+ lastLoggedDate: normDate(summary?.last_logged_date),
1487
+ totalReps: summary?.reps_sum ?? null,
1488
+ totalVolume: summary?.volume_sum ?? null
1489
+ };
1490
+ }));
1248
1491
  }
1249
1492
  function fetchAthletePrefs(client) {
1250
1493
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
@@ -1264,9 +1507,19 @@ function fetchAthleteCircuits(client, kind = "recent") {
1264
1507
  function fetchAthleteProgrammingPrograms(client) {
1265
1508
  return getArray$1(client, "/1.0/athlete/programming/programs", "athlete programming programs");
1266
1509
  }
1267
- /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
1510
+ /**
1511
+ * Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). Only
1512
+ * rows whose title carries every query token are candidates; rankSearch scores but never drops a
1513
+ * row, so ranking the whole catalog would pad a no-match query with the shortest titles up to
1514
+ * `limit`. Mirrors the coach `ExerciseLibrary.search` filter, and a blank query returns nothing.
1515
+ */
1268
1516
  async function searchExerciseHistory(client, query, limit = 20) {
1269
- return rankSearch(await fetchExerciseHistoryList(client), query, limit);
1517
+ const tokens = buildSearchText(query).split(/\s+/u).filter((t) => t.length > 0);
1518
+ if (tokens.length === 0) return [];
1519
+ return rankSearch((await fetchExerciseHistoryList(client)).filter((row) => {
1520
+ const text = buildSearchText(row.title);
1521
+ return tokens.every((t) => text.includes(t));
1522
+ }), query, limit);
1270
1523
  }
1271
1524
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
1272
1525
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
@@ -1381,6 +1634,28 @@ function slotValues(ex, requireMade) {
1381
1634
  }
1382
1635
  return map;
1383
1636
  }
1637
+ /**
1638
+ * The slots carrying data that the athlete has NOT marked performed (`param_i_made !== 1`). On a
1639
+ * saved-copy row these are the row's own targets: the pre-filled prescription, an athlete- or
1640
+ * coach-level override written with `made = 0` (`prescribeAthleteSet`), or a personal session's
1641
+ * only prescription, since personal work has no template tree at all.
1642
+ */
1643
+ function unmadeSlotValues(ex) {
1644
+ const map = slotValues(ex, false);
1645
+ for (const i of map.keys()) if (coerceInt(ex[`param_${i}_made`]) === 1) map.delete(i);
1646
+ return map;
1647
+ }
1648
+ /**
1649
+ * The prescription for one exercise: the template row's slots, with any target the saved copy
1650
+ * still holds unperformed taking precedence per set index (that is what the athlete's app shows,
1651
+ * and where a per-athlete override lives). Without a template row the saved copy's unperformed
1652
+ * slots are the whole prescription.
1653
+ */
1654
+ function prescriptionSlots(template, saved) {
1655
+ const map = template ? slotValues(template, false) : /* @__PURE__ */ new Map();
1656
+ if (saved) for (const [i, v] of unmadeSlotValues(saved)) map.set(i, v);
1657
+ return map;
1658
+ }
1384
1659
  /** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
1385
1660
  function fmtSlot(slot) {
1386
1661
  const has1 = slot.p1 !== null;
@@ -1390,10 +1665,6 @@ function fmtSlot(slot) {
1390
1665
  if (has2) return `@ ${slot.p2}`;
1391
1666
  return "";
1392
1667
  }
1393
- /** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
1394
- function prescribedStrings(ex) {
1395
- return [...slotValues(ex, false).values()].map(fmtSlot);
1396
- }
1397
1668
  /** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
1398
1669
  function performedStrings(ex) {
1399
1670
  return [...slotValues(ex, true).values()].map(fmtSlot);
@@ -1415,6 +1686,46 @@ function savedSets(saved) {
1415
1686
  return out;
1416
1687
  }
1417
1688
  /**
1689
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
1690
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
1691
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
1692
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
1693
+ */
1694
+ function performedExercises(workouts) {
1695
+ const out = [];
1696
+ for (const pw of workouts) {
1697
+ const rec = pw;
1698
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1699
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1700
+ const templates = /* @__PURE__ */ new Map();
1701
+ for (const set of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1702
+ if (!isRecord(set)) continue;
1703
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1704
+ for (const ex of exercises) {
1705
+ if (!isRecord(ex)) continue;
1706
+ const id = coerceInt(ex.id);
1707
+ if (id !== null) templates.set(id, {
1708
+ exerciseId: coerceInt(ex.exercise_id),
1709
+ title: exerciseTitle(ex)
1710
+ });
1711
+ }
1712
+ }
1713
+ const saved = savedWorkoutOf(pw);
1714
+ if (!saved) continue;
1715
+ for (const { exercises } of savedSets(saved)) for (const ex of exercises) {
1716
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1717
+ const template = templateId === null ? void 0 : templates.get(templateId);
1718
+ const exerciseId = coerceInt(ex.exercise_id) ?? template?.exerciseId ?? null;
1719
+ if (exerciseId === null || slotValues(ex, true).size === 0) continue;
1720
+ out.push({
1721
+ exerciseId,
1722
+ title: exerciseTitle(ex, template?.title)
1723
+ });
1724
+ }
1725
+ }
1726
+ return out;
1727
+ }
1728
+ /**
1418
1729
  * Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
1419
1730
  * the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
1420
1731
  * entered values live in the same `param_N_data` slots as a prescription.
@@ -1429,6 +1740,15 @@ function performedSlotsByExerciseId(sets) {
1429
1740
  }
1430
1741
  return map;
1431
1742
  }
1743
+ /** Each saved-copy row keyed by the prescription exercise id it was copied from. */
1744
+ function savedRowsByTemplateId(sets) {
1745
+ const map = /* @__PURE__ */ new Map();
1746
+ for (const { exercises } of sets) for (const ex of exercises) {
1747
+ const id = coerceInt(ex.workout_set_exercise_id);
1748
+ if (id !== null && !map.has(id)) map.set(id, ex);
1749
+ }
1750
+ return map;
1751
+ }
1432
1752
  /** Per-exercise athlete notes keyed by the prescription template id (`workout_set_exercise_id`). */
1433
1753
  function notesByTemplateId(sets) {
1434
1754
  const map = /* @__PURE__ */ new Map();
@@ -1452,7 +1772,7 @@ function mergeExercise(prescribed, performed, meta) {
1452
1772
  };
1453
1773
  }
1454
1774
  /** A prescription block, each exercise aligned with the slots the athlete logged against it. */
1455
- function mergePrescriptionBlock(set, performedById, notesById) {
1775
+ function mergePrescriptionBlock(set, performedById, savedById, notesById) {
1456
1776
  const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1457
1777
  return {
1458
1778
  order: coerceInt(set.order) ?? 0,
@@ -1462,7 +1782,7 @@ function mergePrescriptionBlock(set, performedById, notesById) {
1462
1782
  exercises: exercises.filter(isRecord).map((ex) => {
1463
1783
  const id = coerceInt(ex.id);
1464
1784
  const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
1465
- return mergeExercise(slotValues(ex, false), performed, {
1785
+ return mergeExercise(prescriptionSlots(ex, id !== null ? savedById.get(id) : void 0), performed, {
1466
1786
  exerciseId: coerceInt(ex.exercise_id),
1467
1787
  title: typeof ex.title === "string" ? ex.title : "",
1468
1788
  instruction: str$1(ex.instruction),
@@ -1472,14 +1792,18 @@ function mergePrescriptionBlock(set, performedById, notesById) {
1472
1792
  })
1473
1793
  };
1474
1794
  }
1475
- /** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
1795
+ /**
1796
+ * A block straight from the saved copy (athlete-added or personal work; no template row). Its
1797
+ * unperformed slots are the prescription — a personal session's targets live only here — and its
1798
+ * performed slots are what was logged.
1799
+ */
1476
1800
  function mergeSavedBlock(set, exercises) {
1477
1801
  return {
1478
1802
  order: coerceInt(set.order) ?? 0,
1479
1803
  title: str$1(set.title),
1480
1804
  instruction: str$1(set.instruction),
1481
1805
  isTest: coerceInt(set.is_test) === 1,
1482
- exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
1806
+ exercises: exercises.map((ex) => mergeExercise(prescriptionSlots(void 0, ex), slotValues(ex, true), {
1483
1807
  exerciseId: coerceInt(ex.exercise_id),
1484
1808
  title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
1485
1809
  instruction: str$1(ex.instruction),
@@ -1502,8 +1826,9 @@ function mergeAthleteWorkout(raw) {
1502
1826
  const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
1503
1827
  const logged = savedSets(saved);
1504
1828
  const performedById = performedSlotsByExerciseId(logged);
1829
+ const savedById = savedRowsByTemplateId(logged);
1505
1830
  const notesById = notesByTemplateId(logged);
1506
- const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, notesById)).sort((a, b) => a.order - b.order);
1831
+ const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, savedById, notesById)).sort((a, b) => a.order - b.order);
1507
1832
  const prescribedIds = /* @__PURE__ */ new Set();
1508
1833
  for (const s of prescriptionSets) {
1509
1834
  const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
@@ -1515,7 +1840,7 @@ function mergeAthleteWorkout(raw) {
1515
1840
  }
1516
1841
  for (const { set, exercises } of logged) {
1517
1842
  const extra = exercises.filter((ex) => {
1518
- if (slotValues(ex, true).size === 0) return false;
1843
+ if (slotValues(ex, false).size === 0) return false;
1519
1844
  const id = coerceInt(ex.workout_set_exercise_id);
1520
1845
  return id === null || !prescribedIds.has(id);
1521
1846
  });
@@ -1691,6 +2016,16 @@ function presentLogTargets(list) {
1691
2016
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1692
2017
  const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1693
2018
  if (!saved) continue;
2019
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
2020
+ const templatesById = /* @__PURE__ */ new Map();
2021
+ for (const tSet of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
2022
+ if (!isRecord(tSet)) continue;
2023
+ const tExs = Array.isArray(tSet.workoutSetExercises) ? tSet.workoutSetExercises : [];
2024
+ for (const tEx of tExs) {
2025
+ const tId = isRecord(tEx) ? coerceInt(tEx.id) : null;
2026
+ if (tId !== null && isRecord(tEx)) templatesById.set(tId, tEx);
2027
+ }
2028
+ }
1694
2029
  const date = str$1(rec.date) ?? "";
1695
2030
  const workoutTitle = str$1(rec.workout_title) ?? "";
1696
2031
  const program = str$1(rec.program_title);
@@ -1705,12 +2040,14 @@ function presentLogTargets(list) {
1705
2040
  const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
1706
2041
  const id = coerceInt(ex.id);
1707
2042
  if (id === null) return null;
2043
+ const templateId = coerceInt(ex.workout_set_exercise_id);
2044
+ const template = templateId === null ? void 0 : templatesById.get(templateId);
1708
2045
  return {
1709
2046
  savedWorkoutSetExerciseId: id,
1710
2047
  title: exerciseTitle(ex),
1711
2048
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1712
2049
  notes: str$1(ex.notes),
1713
- prescribed: prescribedStrings(ex),
2050
+ prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
1714
2051
  performed: performedStrings(ex)
1715
2052
  };
1716
2053
  }).filter((e) => e !== null);
@@ -1835,6 +2172,28 @@ function presentExerciseHistory(detail) {
1835
2172
  };
1836
2173
  }
1837
2174
  //#endregion
2175
+ //#region ../js/src/exercise-history.ts
2176
+ /**
2177
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
2178
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
2179
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
2180
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
2181
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
2182
+ */
2183
+ function historyInRange(presented, since, until) {
2184
+ if (since === void 0 && until === void 0) return presented;
2185
+ const sessions = presented.sessions.filter((s) => {
2186
+ const d = (s.date ?? "").slice(0, 10);
2187
+ if (since !== void 0 && d < since) return false;
2188
+ if (until !== void 0 && d > until) return false;
2189
+ return true;
2190
+ });
2191
+ return {
2192
+ ...presented,
2193
+ sessions
2194
+ };
2195
+ }
2196
+ //#endregion
1838
2197
  //#region ../js/src/coach-athlete-calendar.ts
1839
2198
  async function getArray(client, path, label) {
1840
2199
  const res = await client.request("GET", path);
@@ -1969,6 +2328,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
1969
2328
  }
1970
2329
  //#endregion
1971
2330
  //#region ../js/src/athlete-set-write.ts
2331
+ const WRITE_CONCURRENCY = 4;
1972
2332
  /**
1973
2333
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1974
2334
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -2210,6 +2570,41 @@ async function swapAthleteExercise(client, args) {
2210
2570
  originalTeamExerciseId: coerceInt(template.exercise_id)
2211
2571
  };
2212
2572
  }
2573
+ function prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode) {
2574
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2575
+ assertUniqueExerciseResults(results);
2576
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2577
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2578
+ return {
2579
+ savedWorkoutSetId,
2580
+ exercises,
2581
+ rawSet,
2582
+ suffix,
2583
+ extra,
2584
+ writes: results.map((result) => {
2585
+ const ex = exercises.find((candidate) => coerceInt(candidate.id) === result.savedWorkoutSetExerciseId);
2586
+ if (!ex) {
2587
+ const valid = exercises.map((candidate) => {
2588
+ const id = coerceInt(candidate.id);
2589
+ return id === null ? null : `${id} (${exerciseTitle(candidate, "exercise")})`;
2590
+ }).filter((label) => label !== null);
2591
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2592
+ }
2593
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2594
+ if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
2595
+ return {
2596
+ id: result.savedWorkoutSetExerciseId,
2597
+ body: {
2598
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2599
+ ...extra
2600
+ }
2601
+ };
2602
+ })
2603
+ };
2604
+ }
2605
+ function errorMessage(error) {
2606
+ return error instanceof Error ? error.message : String(error);
2607
+ }
2213
2608
  /**
2214
2609
  * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
2215
2610
  * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
@@ -2223,36 +2618,40 @@ async function swapAthleteExercise(client, args) {
2223
2618
  * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
2224
2619
  * open.
2225
2620
  */
2226
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
2227
- const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2228
- assertUniqueExerciseResults(results);
2229
- const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2230
- const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2231
- let exercisesWritten = 0;
2232
- const projectedCompletion = /* @__PURE__ */ new Map();
2233
- for (const result of results) {
2234
- const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
2235
- if (!ex) {
2236
- const valid = exercises.map((e) => {
2237
- const id = coerceInt(e.id);
2238
- return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
2239
- }).filter((x) => x !== null);
2240
- throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2241
- }
2242
- const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2243
- if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
2244
- const body = {
2245
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2246
- ...extra
2621
+ async function executeSetWrite(client, target, prepared, mode, limit, sessionProgress) {
2622
+ const { savedWorkoutSetId, exercises, rawSet, suffix, extra, writes } = prepared;
2623
+ const put = (path, body, failureMessage, finalizer = false) => {
2624
+ const request = async () => {
2625
+ try {
2626
+ const res = await client.request("PUT", path, { body });
2627
+ if (!res.ok) throw new Error(failureMessage(res.status));
2628
+ } catch (error) {
2629
+ limit.cancel(error);
2630
+ throw error;
2631
+ }
2247
2632
  };
2248
- const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
2249
- if (!res.ok) {
2250
- const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
2251
- throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
2252
- }
2253
- projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
2254
- exercisesWritten += 1;
2633
+ return finalizer ? limit.runFinalizer(request) : limit.run(request);
2634
+ };
2635
+ const confirmed = [];
2636
+ try {
2637
+ await mapPool(writes, WRITE_CONCURRENCY, async ({ id, body }) => {
2638
+ await put(`/1.0/${target.role}/savedworkoutsetexercise/${id}${suffix}`, body, (status) => {
2639
+ return `Failed to write exercise ${id} (HTTP ${status}).${target.role === "coach" && (status === 401 || status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${status} here; writes only persist for real (invited) athletes.` : ""}`;
2640
+ });
2641
+ confirmed.push(id);
2642
+ if (sessionProgress) {
2643
+ const sessionConfirmed = sessionProgress.get(savedWorkoutSetId) ?? [];
2644
+ sessionConfirmed.push(id);
2645
+ sessionProgress.set(savedWorkoutSetId, sessionConfirmed);
2646
+ }
2647
+ });
2648
+ } catch (error) {
2649
+ if (sessionProgress || confirmed.length === 0) throw error;
2650
+ confirmed.sort((a, b) => a - b);
2651
+ throw new Error(`${errorMessage(error)} Confirmed exercise writes before the failure: ${confirmed.join(", ")}. The set was not marked complete; retry the same request to reconcile it.`, { cause: error });
2255
2652
  }
2653
+ const exercisesWritten = writes.length;
2654
+ const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
2256
2655
  let setCompleted = false;
2257
2656
  if (mode === "log") {
2258
2657
  if (isSetFullyLogged(exercises, projectedCompletion)) {
@@ -2260,8 +2659,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2260
2659
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
2261
2660
  ...extra
2262
2661
  };
2263
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
2264
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
2662
+ try {
2663
+ await put(`/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, setBody, (status) => `Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${status}).`, true);
2664
+ } catch (error) {
2665
+ throw new Error(`${errorMessage(error)} Exercise values were written successfully; retry the same request to complete the set.`, { cause: error });
2666
+ }
2265
2667
  setCompleted = true;
2266
2668
  }
2267
2669
  }
@@ -2271,6 +2673,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2271
2673
  setCompleted
2272
2674
  };
2273
2675
  }
2676
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode, limit = createLimiter(WRITE_CONCURRENCY)) {
2677
+ return executeSetWrite(client, target, prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode), mode, limit);
2678
+ }
2274
2679
  /**
2275
2680
  * POST /v5/programWorkouts/personal — create a personal workout session for a given date.
2276
2681
  * Returns the key ids: workoutId (needed for addExercisesToWorkout), programWorkoutId,
@@ -2443,7 +2848,7 @@ function prescribedExerciseLabels(workouts) {
2443
2848
  return labels;
2444
2849
  }
2445
2850
  /** Group resolved exercises by saved set and write each set via the given log target. */
2446
- async function logResolvedExercises(client, target, workouts, resolved) {
2851
+ async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
2447
2852
  const bySet = /* @__PURE__ */ new Map();
2448
2853
  for (const r of resolved) {
2449
2854
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -2453,15 +2858,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
2453
2858
  });
2454
2859
  bySet.set(r.savedWorkoutSetId, list);
2455
2860
  }
2456
- const out = [];
2457
- for (const [savedWorkoutSetId, results] of bySet) {
2458
- const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
2459
- out.push({
2460
- savedWorkoutSetId: written.savedWorkoutSetId,
2461
- exercisesLogged: written.exercisesWritten
2861
+ const prepared = [...bySet].map(([savedWorkoutSetId, results]) => prepareSetWrite(target, workouts, savedWorkoutSetId, results, "log"));
2862
+ const limit = createLimiter(WRITE_CONCURRENCY);
2863
+ const confirmedBySet = /* @__PURE__ */ new Map();
2864
+ const succeeded = [];
2865
+ try {
2866
+ return await mapPool(prepared, WRITE_CONCURRENCY, async (set) => {
2867
+ const written = await executeSetWrite(client, target, set, "log", limit, confirmedBySet);
2868
+ succeeded.push(written.savedWorkoutSetId);
2869
+ return {
2870
+ savedWorkoutSetId: written.savedWorkoutSetId,
2871
+ exercisesLogged: written.exercisesWritten
2872
+ };
2462
2873
  });
2874
+ } catch (error) {
2875
+ const completed = new Set(succeeded);
2876
+ const incomplete = [...confirmedBySet].filter(([savedWorkoutSetId]) => !completed.has(savedWorkoutSetId)).sort(([a], [b]) => a - b).map(([savedWorkoutSetId, ids]) => `set ${savedWorkoutSetId}: ${ids.toSorted((a, b) => a - b).join(", ")}`);
2877
+ if (incomplete.length === 0 && succeeded.length === 0) throw error;
2878
+ succeeded.sort((a, b) => a - b);
2879
+ const partial = incomplete.length === 0 ? "" : ` Confirmed exercise writes in incomplete sets before the failure: ${incomplete.join("; ")}.${retryGuidance ? ` ${retryGuidance}` : ""}`;
2880
+ const complete = succeeded.length === 0 ? "" : ` Set writes confirmed before the failure: ${succeeded.join(", ")}.`;
2881
+ throw new Error(`${errorMessage(error)}${partial}${complete}`, { cause: error });
2463
2882
  }
2464
- return out;
2465
2883
  }
2466
2884
  /**
2467
2885
  * Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
@@ -2534,7 +2952,7 @@ async function logSessionForAthlete(client, args) {
2534
2952
  const sets = await logResolvedExercises(client, {
2535
2953
  role: "coach",
2536
2954
  athleteId: args.athleteId
2537
- }, day, resolved);
2955
+ }, day, resolved, "Retry the same request to reconcile them.");
2538
2956
  return {
2539
2957
  date: args.date,
2540
2958
  created: false,
@@ -3120,7 +3538,7 @@ async function readSession(client, programId, date, pwId) {
3120
3538
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
3121
3539
  return {
3122
3540
  pwId,
3123
- date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
3541
+ date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
3124
3542
  published: pw.published,
3125
3543
  instruction: str(pw.instruction),
3126
3544
  blocks
@@ -3140,14 +3558,13 @@ function readBlock(b) {
3140
3558
  };
3141
3559
  }
3142
3560
  function readExercise(ex) {
3143
- const reps = [];
3144
- const load = [];
3145
- for (let i = 1; i <= 10; i += 1) {
3146
- const r = str(ex[`param_1_data_${i}`]);
3147
- if (r !== "") reps.push(r);
3148
- const w = str(ex[`param_2_data_${i}`]);
3149
- if (w !== "") load.push(w);
3150
- }
3561
+ let last = 0;
3562
+ for (let i = 1; i <= 10; i += 1) if (str(ex[`param_1_data_${i}`]) !== "" || str(ex[`param_2_data_${i}`]) !== "") last = i;
3563
+ const slots = Array.from({ length: last }, (_, k) => k + 1);
3564
+ const repsRaw = slots.map((i) => str(ex[`param_1_data_${i}`]));
3565
+ const loadRaw = slots.map((i) => str(ex[`param_2_data_${i}`]));
3566
+ const reps = repsRaw.some((r) => r !== "") ? repsRaw : [];
3567
+ const load = loadRaw.some((w) => w !== "") ? loadRaw : [];
3151
3568
  return {
3152
3569
  order: Number(ex.order),
3153
3570
  title: str(ex.title),
@@ -3721,8 +4138,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3721
4138
  } catch {
3722
4139
  workouts = [];
3723
4140
  }
3724
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
3725
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
4141
+ for (const ex of performedExercises(workouts)) {
3726
4142
  const family = classifyMainLift(ex.title);
3727
4143
  if (family === null) continue;
3728
4144
  const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
@@ -3967,6 +4383,7 @@ var ExerciseLibrary = class {
3967
4383
  #byId = /* @__PURE__ */ new Map();
3968
4384
  #loaded = false;
3969
4385
  #fetchedAt = 0;
4386
+ #loading = null;
3970
4387
  constructor(client, cache = new MemoryLibraryCache()) {
3971
4388
  this.#client = client;
3972
4389
  this.#cache = cache;
@@ -3994,8 +4411,11 @@ var ExerciseLibrary = class {
3994
4411
  });
3995
4412
  }
3996
4413
  async ensureFresh() {
3997
- if (!this.#loaded) await this.#ensureLoaded();
3998
- else if (Date.now() - this.#fetchedAt > TTL_MS$1) await this.refresh();
4414
+ if (this.#loaded && Date.now() - this.#fetchedAt <= TTL_MS$1) return;
4415
+ this.#loading ??= (this.#loaded ? this.refresh() : this.#ensureLoaded()).finally(() => {
4416
+ this.#loading = null;
4417
+ });
4418
+ await this.#loading;
3999
4419
  }
4000
4420
  async refresh() {
4001
4421
  const res = await this.#client.request("GET", LIBRARY_PATH);
@@ -4014,6 +4434,7 @@ var ExerciseLibrary = class {
4014
4434
  return presentExercise(s.raw);
4015
4435
  }
4016
4436
  async defaultsMany(ids) {
4437
+ await this.ensureFresh();
4017
4438
  const result = /* @__PURE__ */ new Map();
4018
4439
  for (const id of ids) {
4019
4440
  const s = this.#byId.get(id);
@@ -4134,6 +4555,26 @@ function looksLikeJson(s) {
4134
4555
  function requireTeamCalendarReassignmentConfirmation(teamId, groupProgram, confirmed) {
4135
4556
  if (groupProgram !== void 0 && !confirmed) throw new Error(`reassigning team ${teamId}'s calendar changes live athlete programming; add --yes.`);
4136
4557
  }
4558
+ /**
4559
+ * An integer argument. `Number("")` is 0 and `Number("1.5")` is finite, so a bare `Number` check
4560
+ * let a trailing comma in an id list become id 0 and a fractional --limit slip through; every
4561
+ * integer-valued flag and positional (ids, counts, pages) goes through here instead.
4562
+ */
4563
+ function parseIntArg(value, label) {
4564
+ const s = value.trim();
4565
+ if (!/^-?\d+$/u.test(s)) throw new Error(`${label} must be an integer, got "${value}".`);
4566
+ return Number(s);
4567
+ }
4568
+ /** A positive integer argument (a --limit, a page size): 0 and negatives are rejected. */
4569
+ function parseCountArg(value, label) {
4570
+ const n = parseIntArg(value, label);
4571
+ if (n < 1) throw new Error(`${label} must be a positive integer, got "${value}".`);
4572
+ return n;
4573
+ }
4574
+ /** A comma-separated list of integer ids; a blank entry (e.g. a trailing comma) is an error. */
4575
+ function parseIdList(value, label) {
4576
+ return value.split(",").map((s) => parseIntArg(s, label));
4577
+ }
4137
4578
  //#endregion
4138
4579
  //#region src/session-cache.ts
4139
4580
  const TTL_MS = 216e5;
@@ -4179,7 +4620,7 @@ Coach — manage a roster (needs a coach account):
4179
4620
  coach program <id> | team <id> | team-codes <id>
4180
4621
 
4181
4622
  roster athlete reads (three lenses — pick by the question):
4182
- coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency; --metric adds session count + training volume. All-time snapshot, NO date range — for a windowed total use 'coach team-volume'. Get the full id list from 'coach athletes'.
4623
+ coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency with each athlete's session count + training volume; --metric reports the totals in kg instead of lb. All-time snapshot, NO date range — for a windowed total use 'coach team-volume'. Get the full id list from 'coach athletes'.
4183
4624
  coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D team training volume scoped to a date window: per-athlete rows (only those who logged in range) + rolled-up totals (volume in lb). --team resolves the roster; --athletes passes ids directly.
4184
4625
  coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --program (title substring) / --program-id / --team targets one program when the athlete is on several; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
4185
4626
  coach athlete-training --athlete <id> --year <YYYY> --month <1-12> sessions the athlete LOGGED in one month (empty = nothing logged that month, not an error)
@@ -4235,7 +4676,7 @@ Coach — manage a roster (needs a coach account):
4235
4676
  coach session-template-create --title "..." [--instruction "..."]
4236
4677
  coach session-template-delete --id <id> --yes
4237
4678
 
4238
- analytics (curated metrics; for team training volume/recency use roster-activity --metric instead):
4679
+ analytics (curated metrics; for team training volume/recency use roster-activity instead):
4239
4680
  coach analytics-query [--metric <key>] [--team <id>] [--users id,id] [--exercise <id>] [--date|--start|--end Y-M-D] [--use-metric]
4240
4681
  run with no --metric to list the valid keys + each one's scope and required params
4241
4682
  (these keys are curated and differ from the raw 'coach analytics' categories)
@@ -4312,9 +4753,12 @@ function need(value, usage) {
4312
4753
  return value;
4313
4754
  }
4314
4755
  function toInt(value, label) {
4315
- const n = Number(value);
4316
- if (!Number.isFinite(n)) fail(`${label} must be a number, got "${value}".`);
4317
- return n;
4756
+ return parseIntArg(value, label);
4757
+ }
4758
+ /** A --limit style count: a positive integer, so 0 / negatives fail instead of emptying or
4759
+ * tail-slicing the result. Matches the MCP tools' `positive()` limit schemas. */
4760
+ function toCount(value, label) {
4761
+ return parseCountArg(value, label);
4318
4762
  }
4319
4763
  /** Validate input against a dto schema, failing with a readable message on mismatch. */
4320
4764
  function validate(schema, value, label, hint) {
@@ -4367,7 +4811,7 @@ async function mutate(client, method, path, body) {
4367
4811
  }
4368
4812
  /** Parse a comma-separated id list ("1,2,3") into numbers. */
4369
4813
  function idList(value, label) {
4370
- return value.split(",").map((s) => toInt(s.trim(), label));
4814
+ return parseIdList(value, label);
4371
4815
  }
4372
4816
  function library(client) {
4373
4817
  return new ExerciseLibrary(client, new JsonFileLibraryCache());
@@ -4380,7 +4824,7 @@ async function cmdExercise(client, rest) {
4380
4824
  case "search": {
4381
4825
  const { values, positionals } = parse(a, { limit: { type: "string" } });
4382
4826
  const query = need(positionals.join(" ").trim() || void 0, "coach exercise search <query>");
4383
- const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
4827
+ const limit = values.limit !== void 0 ? toCount(values.limit, "--limit") : 20;
4384
4828
  return out(await lib.search(query, limit));
4385
4829
  }
4386
4830
  case "get": return out(await lib.get(toInt(need(a[0], "coach exercise get <id>"), "id")));
@@ -4523,7 +4967,7 @@ async function cmdMessage(client, rest) {
4523
4967
  limit: { type: "string" },
4524
4968
  after: { type: "string" }
4525
4969
  });
4526
- return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N] [--after <commentId>]"), "streamId"), values.limit !== void 0 ? toInt(values.limit, "--limit") : 20, values.after !== void 0 ? toInt(values.after, "--after") : void 0));
4970
+ return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N] [--after <commentId>]"), "streamId"), values.limit !== void 0 ? toCount(values.limit, "--limit") : 20, values.after !== void 0 ? toInt(values.after, "--after") : void 0));
4527
4971
  }
4528
4972
  case "draft": {
4529
4973
  const { values, positionals } = parse(a, { "reply-to": { type: "string" } });
@@ -4823,11 +5267,7 @@ async function cmdAthleteWorkouts(client, a) {
4823
5267
  if (format !== void 0 && (values.raw === true || values["log-ids"] === true || values.summary === true)) fail("--format cannot be combined with --raw, --log-ids, or --summary.");
4824
5268
  const opts = {};
4825
5269
  if (values["logged-only"] === true) opts.loggedOnly = true;
4826
- if (values.limit !== void 0) {
4827
- const limit = toInt(values.limit, "--limit");
4828
- if (!Number.isInteger(limit) || limit < 0) fail(`--limit must be a non-negative integer.`);
4829
- opts.limit = limit;
4830
- }
5270
+ if (values.limit !== void 0) opts.limit = toCount(values.limit, "--limit");
4831
5271
  const workouts = await fetchAthleteWorkoutsChunked(client, start, end);
4832
5272
  if (format !== void 0) return outRaw(serializeWorkoutHistory(selectWorkouts(presentAthleteWorkoutsExport(workouts), opts), format).content);
4833
5273
  if (values["log-ids"] === true) return out(presentLogTargets(workouts));
@@ -4855,9 +5295,15 @@ async function cmdAthlete(client, rest) {
4855
5295
  q: { type: "string" },
4856
5296
  limit: { type: "string" }
4857
5297
  });
4858
- const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
5298
+ const limit = values.limit !== void 0 ? toCount(values.limit, "--limit") : void 0;
4859
5299
  const q = values.q;
4860
- return out(q !== void 0 ? await searchExerciseHistory(client, q, limit) : await fetchExerciseHistoryList(client));
5300
+ if (q !== void 0) return out(await searchExerciseHistory(client, q, limit ?? 20));
5301
+ const rows = await fetchExerciseHistoryList(client);
5302
+ if (limit !== void 0 && rows.length > limit) {
5303
+ logErr(`showing ${limit} of ${rows.length} exercises; drop --limit for the full catalog`);
5304
+ return out(rows.slice(0, limit));
5305
+ }
5306
+ return out(rows);
4861
5307
  }
4862
5308
  case "recent-exercises": return out(await fetchRecentExercises(client));
4863
5309
  case "circuits": {
@@ -5086,7 +5532,7 @@ async function cmdCoachAthleteWorkouts(client, a) {
5086
5532
  if (values.raw === true) return out(workouts);
5087
5533
  const opts = {};
5088
5534
  if (values["logged-only"] === true) opts.loggedOnly = true;
5089
- if (values.limit !== void 0) opts.limit = toInt(values.limit, "--limit");
5535
+ if (values.limit !== void 0) opts.limit = toCount(values.limit, "--limit");
5090
5536
  const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
5091
5537
  return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
5092
5538
  }
@@ -5347,16 +5793,12 @@ async function cmdCoachAthleteLiftHistory(client, a) {
5347
5793
  const presented = presentExerciseHistory(detail);
5348
5794
  const since = values.since !== void 0 ? isoDate(values.since, "--since") : void 0;
5349
5795
  const until = values.until !== void 0 ? isoDate(values.until, "--until") : void 0;
5350
- const sessions = presented.sessions.filter((s) => (since === void 0 || s.date >= since) && (until === void 0 || s.date <= until));
5351
- if (sessions.length === 0 && presented.liftPRs.length === 0) return out({
5352
- ...presented,
5353
- sessions,
5796
+ const windowed = historyInRange(presented, since, until);
5797
+ if (windowed.sessions.length === 0 && windowed.liftPRs.length === 0) return out({
5798
+ ...windowed,
5354
5799
  note: `No logged history for exercise ${exerciseId} for athlete ${athleteId}${since !== void 0 || until !== void 0 ? " in this date window" : ""}. This view only shows sessions where the athlete logged this exact exercise — an empty result means none were logged, not an error. Confirm the exercise id (via 'coach exercise resolve <name>') and widen --since/--until.`
5355
5800
  });
5356
- return out({
5357
- ...presented,
5358
- sessions
5359
- });
5801
+ return out(windowed);
5360
5802
  }
5361
5803
  async function cmdCoachMainLiftPrs(client, a) {
5362
5804
  const { values } = parse(a, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "3.5.1",
3
+ "version": "3.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "3.5.1",
25
- "@trainheroic-unofficial/js": "3.5.1"
24
+ "@trainheroic-unofficial/dto": "3.6.0",
25
+ "@trainheroic-unofficial/js": "3.6.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.3.0",