@trainheroic-unofficial/cli 1.4.0 → 1.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @trainheroic-unofficial/cli
2
2
 
3
- A command-line tool for the TrainHeroic coaching API. Takes credentials from the environment, prints JSON.
3
+ A command-line tool for the TrainHeroic API. Takes credentials from the environment, prints JSON.
4
4
 
5
5
  Part of the [trainheroic-unofficial](../../README.md) workspace.
6
6
 
package/dist/cli.mjs CHANGED
@@ -163,16 +163,29 @@ const loggedSetSchema = z.object({
163
163
  param2: z.union([z.number(), z.string()]).optional()
164
164
  });
165
165
  /**
166
+ * A logged set that can name the prescribed position it fills. `slot` is the 1-based set
167
+ * index in the prescription (10 max) the result should land in; omit it to fill the next
168
+ * sequential position (the first entry is set 1, the second set 2, and so on). Targeting a
169
+ * slot lets a partial log land in the right positions of a multi-set prescription — e.g.
170
+ * three top singles into the 4th/5th/6th positions of an `8,5,3,1,1,1` ramp. Used by the
171
+ * by-set logging write (not the by-exercise session log, where each exercise's sets are
172
+ * always sequential).
173
+ */
174
+ const loggedSetWithSlotSchema = loggedSetSchema.extend({ slot: z.number().int().min(1).max(10).optional() });
175
+ /**
166
176
  * Args for the set-logging write. `date` (the workout's day) locates the saved
167
177
  * workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
168
- * gives, per exercise in it, the entered value of each set (param 1 / param 2 by entry slot).
178
+ * gives, per exercise in it, the entered value of each set. Each set fills the next position by
179
+ * default, or names its `slot` (1-based) to place a partial log at specific positions. A partial
180
+ * log keeps positions already logged in an earlier call and leaves the positions it does not
181
+ * write empty.
169
182
  */
170
183
  const logSetArgsSchema = z.object({
171
184
  date: dateString,
172
185
  savedWorkoutSetId: idArgSchema,
173
186
  results: z.array(z.object({
174
187
  savedWorkoutSetExerciseId: idArgSchema,
175
- sets: z.array(loggedSetSchema).min(1)
188
+ sets: z.array(loggedSetWithSlotSchema).min(1)
176
189
  })).min(1)
177
190
  });
178
191
  /**
@@ -181,14 +194,23 @@ const logSetArgsSchema = z.object({
181
194
  */
182
195
  const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
183
196
  /**
184
- * Args for the coach prescription-override write. Structurally the same as
185
- * {@link coachLogSetArgsSchema} (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but
186
- * the values are prescribed targets (param1 = reps, param2 = weight) written to the athlete's
187
- * plan without marking the set performed. It is a separate schema (not an alias) so a future
188
- * prescribe-only constraint can be added here without changing the log args, and the write
189
- * replaces the slot's prescribed values for this athlete only.
197
+ * Args for the coach prescription-override write. Like {@link coachLogSetArgsSchema}
198
+ * (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but the values are prescribed
199
+ * targets (param1 = reps, param2 = weight) written to the athlete's plan without marking the set
200
+ * performed. The write replaces this athlete's whole prescription for the set, so its sets are
201
+ * positional and sequential by definition: it deliberately omits the log path's `slot` field (a
202
+ * sparse, slot-targeted prescription has no meaning here) by building its results off
203
+ * {@link loggedSetSchema} rather than {@link loggedSetWithSlotSchema}.
190
204
  */
191
- const coachPrescribeSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
205
+ const coachPrescribeSetArgsSchema = z.object({
206
+ date: dateString,
207
+ savedWorkoutSetId: idArgSchema,
208
+ athleteId: idArgSchema,
209
+ results: z.array(z.object({
210
+ savedWorkoutSetExerciseId: idArgSchema,
211
+ sets: z.array(loggedSetSchema).min(1)
212
+ })).min(1)
213
+ });
192
214
  /**
193
215
  * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
194
216
  * roster athlete's saved-workout slots with a different exercise, the API equivalent of the
@@ -219,6 +241,16 @@ const logSessionArgsSchema = z.object({
219
241
  * `athleteId` whose session is being logged on their behalf.
220
242
  */
221
243
  const coachLogSessionArgsSchema = logSessionArgsSchema.extend({ athleteId: idArgSchema });
244
+ /**
245
+ * Args for removing a personal (athlete-created) workout session. `programWorkoutId` is the
246
+ * range item's top-level `id`; `date` is that session's day, used to look the item back up so the
247
+ * write can confirm it is a personal session (`personal_cal === true`) before deleting. A
248
+ * coach-scheduled workout is never removed this way.
249
+ */
250
+ const athleteSessionRemoveArgsSchema = z.object({
251
+ programWorkoutId: idArgSchema,
252
+ date: dateString
253
+ });
222
254
  //#endregion
223
255
  //#region ../dto/src/exercise.ts
224
256
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
@@ -583,6 +615,26 @@ function asExerciseList(body) {
583
615
  function isRecord(x) {
584
616
  return typeof x === "object" && x !== null && !Array.isArray(x);
585
617
  }
618
+ /** A non-empty string, or null. Narrows a loosely-typed API field to a usable string. */
619
+ function str$1(v) {
620
+ return typeof v === "string" && v !== "" ? v : null;
621
+ }
622
+ /**
623
+ * The display title of a saved-copy exercise row, preferring `exercise_title`, then `title`, then
624
+ * the given fallback. The saved-workout shape carries the title under either key depending on the
625
+ * endpoint, so this is the one place that reconciles them.
626
+ */
627
+ function exerciseTitle(ex, fallback = "") {
628
+ return typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || fallback;
629
+ }
630
+ /**
631
+ * True when a program-workout range item is a personal (athlete-created) session rather than a
632
+ * coach-scheduled one. The API marks these with `personal_cal === true`; this is the single
633
+ * definition every consumer (presenter, find-or-create, the remove guard) reads through.
634
+ */
635
+ function isPersonalSession(pw) {
636
+ return isRecord(pw) && pw.personal_cal === true;
637
+ }
586
638
  /**
587
639
  * Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
588
640
  * exact title, then prefix, then count of matched tokens, with shorter titles and
@@ -762,7 +814,6 @@ function fetchLeaderboard(client, workoutId, opts = {}) {
762
814
  const query = qs.toString();
763
815
  return getJson(client, `/3.0/athlete/leaderboard/${workoutId}${query ? `?${query}` : ""}`, "athlete leaderboard");
764
816
  }
765
- const SLOTS = 10;
766
817
  function nonEmpty(value) {
767
818
  return value !== void 0 && value !== null && String(value).trim() !== "";
768
819
  }
@@ -773,7 +824,7 @@ function nonEmpty(value) {
773
824
  */
774
825
  function prescribedSets(ex) {
775
826
  const out = [];
776
- for (let i = 1; i <= SLOTS; i += 1) {
827
+ for (let i = 1; i <= 10; i += 1) {
777
828
  const p1 = ex[`param_1_data_${i}`];
778
829
  const p2 = ex[`param_2_data_${i}`];
779
830
  const has1 = nonEmpty(p1);
@@ -794,7 +845,7 @@ function prescribedSets(ex) {
794
845
  */
795
846
  function performedSets(ex) {
796
847
  const out = [];
797
- for (let i = 1; i <= SLOTS; i += 1) {
848
+ for (let i = 1; i <= 10; i += 1) {
798
849
  if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
799
850
  const p1 = ex[`param_1_data_${i}`];
800
851
  const p2 = ex[`param_2_data_${i}`];
@@ -828,9 +879,6 @@ function presentBlock(set, performedById) {
828
879
  exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
829
880
  };
830
881
  }
831
- function str$1(v) {
832
- return typeof v === "string" && v !== "" ? v : null;
833
- }
834
882
  /** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
835
883
  function savedSets(saved) {
836
884
  const out = [];
@@ -921,6 +969,7 @@ function presentAthleteWorkout(raw) {
921
969
  team: str$1(rec.team_title),
922
970
  instruction: str$1(workout.instruction),
923
971
  logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
972
+ personal: isPersonalSession(rec),
924
973
  blocks
925
974
  };
926
975
  }
@@ -981,7 +1030,7 @@ function presentLogTargets(list) {
981
1030
  if (id === null) return null;
982
1031
  return {
983
1032
  savedWorkoutSetExerciseId: id,
984
- title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
1033
+ title: exerciseTitle(ex),
985
1034
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
986
1035
  prescribed: prescribedSets(ex),
987
1036
  performed: performedSets(ex)
@@ -1030,6 +1079,7 @@ function summarizeAthleteWorkouts(list) {
1030
1079
  program: w.program,
1031
1080
  team: w.team,
1032
1081
  logged: w.logged,
1082
+ personal: w.personal,
1033
1083
  exerciseCount,
1034
1084
  performedCount
1035
1085
  };
@@ -1083,7 +1133,29 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
1083
1133
  sessions
1084
1134
  };
1085
1135
  }
1086
- const MAX_PARAM_SLOTS = 10;
1136
+ /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1137
+ function presentExerciseHistory(detail) {
1138
+ return {
1139
+ liftPRs: (detail.liftPRs ?? []).map((p) => ({
1140
+ description: p.description ?? null,
1141
+ reps: p.reps ?? null,
1142
+ weight: p.weight ?? null,
1143
+ units: p.units ?? null,
1144
+ date: p.dateCompleted ?? null
1145
+ })),
1146
+ sessions: (detail.history ?? []).map((h) => ({
1147
+ date: h.dateCompleted,
1148
+ abr: h.abr ?? null,
1149
+ estimated1RM: h.bestEstimated1RM ?? null,
1150
+ sets: (h.sets ?? []).map((s) => ({
1151
+ setNumber: s.setNumber,
1152
+ value: s.formattedValue ?? null
1153
+ }))
1154
+ }))
1155
+ };
1156
+ }
1157
+ //#endregion
1158
+ //#region ../js/src/athlete-set-write.ts
1087
1159
  /**
1088
1160
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1089
1161
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -1098,10 +1170,11 @@ function toSetResults(results) {
1098
1170
  return {
1099
1171
  savedWorkoutSetExerciseId: id,
1100
1172
  sets: r.sets.map((s) => {
1101
- const slot = {};
1102
- if (s.param1 !== void 0) slot.param1 = s.param1;
1103
- if (s.param2 !== void 0) slot.param2 = s.param2;
1104
- return slot;
1173
+ const set = {};
1174
+ if (s.param1 !== void 0) set.param1 = s.param1;
1175
+ if (s.param2 !== void 0) set.param2 = s.param2;
1176
+ if (s.slot !== void 0) set.slot = s.slot;
1177
+ return set;
1105
1178
  })
1106
1179
  };
1107
1180
  });
@@ -1113,36 +1186,96 @@ function toSetResults(results) {
1113
1186
  *
1114
1187
  * `mode` selects which write this is — the same endpoint serves both:
1115
1188
  * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
1116
- * and the exercise `completed` flag is 1 when any set has data.
1189
+ * and the exercise `completed` flag is 1 when any set has logged data.
1117
1190
  * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1118
1191
  * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1119
1192
  * coach edits an athlete's prescribed reps/weight.
1120
1193
  *
1194
+ * Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
1195
+ * when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
1196
+ * it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
1197
+ * a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
1198
+ * (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
1199
+ * the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
1200
+ * sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
1201
+ * copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
1202
+ *
1121
1203
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1122
- * required from the live exercise record; everything else is derived from `results`.
1204
+ * required from the live exercise record; everything else is derived from `results` and the
1205
+ * preserved slots of `existing`.
1123
1206
  *
1124
1207
  * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1125
1208
  */
1126
- function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
1127
- if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
1209
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1210
+ if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1211
+ const bySlot = /* @__PURE__ */ new Map();
1212
+ results.forEach((set, i) => {
1213
+ const slot = set.slot ?? i + 1;
1214
+ if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1215
+ if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1216
+ bySlot.set(slot, set);
1217
+ });
1128
1218
  const performed = mode === "log";
1129
- const hasData = results.some((s) => s.param1 !== void 0 || s.param2 !== void 0);
1219
+ const carryOver = performed && existing !== void 0;
1130
1220
  const body = {
1131
1221
  id: savedWorkoutSetExerciseId,
1132
1222
  saved_workout_set_id: savedWorkoutSetId,
1133
- workout_set_exercise_id: workoutSetExerciseId,
1134
- completed: performed && hasData ? 1 : 0
1223
+ workout_set_exercise_id: workoutSetExerciseId
1135
1224
  };
1136
- for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1137
- const slot = results[i - 1];
1138
- const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1139
- const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1140
- body[`param_${i}_made`] = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1225
+ let anyMade = false;
1226
+ for (let i = 1; i <= 10; i += 1) {
1227
+ const target = bySlot.get(i);
1228
+ let p1;
1229
+ let p2;
1230
+ let made;
1231
+ if (target) {
1232
+ p1 = target.param1 !== void 0 ? String(target.param1) : "";
1233
+ p2 = target.param2 !== void 0 ? String(target.param2) : "";
1234
+ made = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1235
+ } else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
1236
+ p1 = existingSlotData(existing, `param_1_data_${i}`);
1237
+ p2 = existingSlotData(existing, `param_2_data_${i}`);
1238
+ made = 1;
1239
+ } else {
1240
+ p1 = "";
1241
+ p2 = "";
1242
+ made = 0;
1243
+ }
1244
+ if (made === 1) anyMade = true;
1245
+ body[`param_${i}_made`] = made;
1141
1246
  body[`param_1_data_${i}`] = p1;
1142
1247
  body[`param_2_data_${i}`] = p2;
1143
1248
  }
1249
+ body.completed = performed && anyMade ? 1 : 0;
1144
1250
  return body;
1145
1251
  }
1252
+ /** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
1253
+ function existingSlotData(existing, key) {
1254
+ const v = existing?.[key];
1255
+ return v === void 0 || v === null ? "" : String(v);
1256
+ }
1257
+ /** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
1258
+ function exerciseHasLoggedData(ex) {
1259
+ for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
1260
+ return false;
1261
+ }
1262
+ /** True when a result carries at least one non-empty param value (so it produces a performed slot). */
1263
+ function resultHasData(result) {
1264
+ return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "" || s.param2 !== void 0 && String(s.param2) !== "");
1265
+ }
1266
+ /**
1267
+ * Whether every exercise in a saved workout set now has logged data — either written with data in
1268
+ * this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
1269
+ * superset/circuit stays open until the last exercise is logged, so completing it on a partial log
1270
+ * does not flip its still-empty siblings to "done". An exercise written with only empty values does
1271
+ * not count (it would not be marked performed), so an all-empty log never completes the set.
1272
+ */
1273
+ function isSetFullyLogged(exercises, loggedIds) {
1274
+ return exercises.every((ex) => {
1275
+ const id = coerceInt(ex.id);
1276
+ return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
1277
+ });
1278
+ }
1146
1279
  /**
1147
1280
  * Locate the target saved workout set across all program workouts on the given day.
1148
1281
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -1173,8 +1306,7 @@ function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
1173
1306
  if (setId !== null) {
1174
1307
  const exLabels = exercises.map((ex) => {
1175
1308
  const exId = coerceInt(ex.id);
1176
- const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1177
- return exId === null ? null : `${exId} (${title})`;
1309
+ return exId === null ? null : `${exId} (${exerciseTitle(ex, "exercise")})`;
1178
1310
  }).filter((x) => x !== null);
1179
1311
  available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
1180
1312
  }
@@ -1241,7 +1373,8 @@ async function logAthleteSet(client, args) {
1241
1373
  const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
1242
1374
  return {
1243
1375
  savedWorkoutSetId: r.savedWorkoutSetId,
1244
- exercisesLogged: r.exercisesWritten
1376
+ exercisesLogged: r.exercisesWritten,
1377
+ setCompleted: r.setCompleted
1245
1378
  };
1246
1379
  }
1247
1380
  /**
@@ -1262,7 +1395,8 @@ async function logForAthlete(client, args) {
1262
1395
  }, workouts, args.savedWorkoutSetId, args.results, "log");
1263
1396
  return {
1264
1397
  savedWorkoutSetId: r.savedWorkoutSetId,
1265
- exercisesLogged: r.exercisesWritten
1398
+ exercisesLogged: r.exercisesWritten,
1399
+ setCompleted: r.setCompleted
1266
1400
  };
1267
1401
  }
1268
1402
  /**
@@ -1349,15 +1483,14 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1349
1483
  if (!ex) {
1350
1484
  const valid = exercises.map((e) => {
1351
1485
  const id = coerceInt(e.id);
1352
- const title = typeof e.exercise_title === "string" && e.exercise_title || typeof e.title === "string" && e.title || "exercise";
1353
- return id === null ? null : `${id} (${title})`;
1486
+ return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
1354
1487
  }).filter((x) => x !== null);
1355
1488
  throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1356
1489
  }
1357
1490
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1358
1491
  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.`);
1359
1492
  const body = {
1360
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1493
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1361
1494
  ...extra
1362
1495
  };
1363
1496
  const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
@@ -1367,17 +1500,22 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1367
1500
  }
1368
1501
  exercisesWritten += 1;
1369
1502
  }
1503
+ let setCompleted = false;
1370
1504
  if (mode === "log") {
1371
- const setBody = {
1372
- ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1373
- ...extra
1374
- };
1375
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1376
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1505
+ if (isSetFullyLogged(exercises, new Set(results.filter(resultHasData).map((r) => r.savedWorkoutSetExerciseId)))) {
1506
+ const setBody = {
1507
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1508
+ ...extra
1509
+ };
1510
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1511
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1512
+ setCompleted = true;
1513
+ }
1377
1514
  }
1378
1515
  return {
1379
1516
  savedWorkoutSetId,
1380
- exercisesWritten
1517
+ exercisesWritten,
1518
+ setCompleted
1381
1519
  };
1382
1520
  }
1383
1521
  /**
@@ -1420,17 +1558,30 @@ async function addExercisesToWorkout(client, workoutId, exercises) {
1420
1558
  return res.data;
1421
1559
  }
1422
1560
  /**
1561
+ * DELETE /v5/programWorkouts/{programWorkoutId} — remove a personal (athlete-created) workout
1562
+ * session from the athlete's own calendar. Re-reads the day and removes ONLY a personal session
1563
+ * (`personal_cal`): it throws if no workout with that id is on the date, or if the target is a
1564
+ * coach-scheduled workout (which is not the athlete's to delete). This guard lives here, at the
1565
+ * delete itself, so no caller can issue the DELETE against a coach workout by skipping a check.
1566
+ * Throws on a non-ok response.
1567
+ */
1568
+ async function removePersonalWorkout(client, args) {
1569
+ const target = (await fetchAthleteWorkouts(client, args.date, args.date)).find((pw) => coerceInt(pw.id) === args.programWorkoutId);
1570
+ if (target === void 0) throw new Error(`No workout with id ${args.programWorkoutId} on ${args.date}. Get the id and date from athlete_workouts.`);
1571
+ if (!isPersonalSession(target)) throw new Error(`Workout ${args.programWorkoutId} on ${args.date} is a coach-scheduled workout, not a personal session, so it can't be removed. To change logged results on a scheduled workout, use athlete_log_set.`);
1572
+ const res = await client.request("DELETE", `/v5/programWorkouts/${args.programWorkoutId}`);
1573
+ if (!res.ok) throw new Error(`Remove personal workout failed (HTTP ${res.status}).`);
1574
+ }
1575
+ /**
1423
1576
  * Find a personal-calendar session already on the given day. The range marks these with
1424
1577
  * `personal_cal === true`; the addable id is the program workout's `workout_id`. Returns the
1425
1578
  * first one's workoutId, or null when the day has no personal session.
1426
1579
  */
1427
1580
  function findPersonalSessionWorkoutId(workouts) {
1428
1581
  for (const pw of workouts) {
1429
- const rec = pw;
1430
- if (rec.personal_cal === true) {
1431
- const workoutId = coerceInt(rec.workout_id);
1432
- if (workoutId !== null) return workoutId;
1433
- }
1582
+ if (!isPersonalSession(pw)) continue;
1583
+ const workoutId = coerceInt(pw.workout_id);
1584
+ if (workoutId !== null) return workoutId;
1434
1585
  }
1435
1586
  return null;
1436
1587
  }
@@ -1461,7 +1612,11 @@ function indexAddedExercises(added) {
1461
1612
  }
1462
1613
  return out;
1463
1614
  }
1464
- /** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
1615
+ /**
1616
+ * Flatten a day's saved sets into `{ pw, savedWorkoutSetId, ex }` rows (both saved-set keys),
1617
+ * carrying the parent program-workout so a caller can read its identity (`personal_cal`, program
1618
+ * title) without re-walking. The one saved-copy traversal the by-exercise paths share.
1619
+ */
1465
1620
  function eachPrescribedExercise(workouts) {
1466
1621
  const rows = [];
1467
1622
  for (const pw of workouts) {
@@ -1476,6 +1631,7 @@ function eachPrescribedExercise(workouts) {
1476
1631
  if (savedWorkoutSetId === null) continue;
1477
1632
  const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
1478
1633
  for (const ex of exercises) if (isRecord(ex)) rows.push({
1634
+ pw: rec,
1479
1635
  savedWorkoutSetId,
1480
1636
  ex
1481
1637
  });
@@ -1500,14 +1656,39 @@ function findPrescribedExercise(workouts, exerciseId, used) {
1500
1656
  }
1501
1657
  return null;
1502
1658
  }
1659
+ /**
1660
+ * Find prescribed exercises on coach-scheduled (non-personal) workouts that day matching any of the
1661
+ * given exercise ids. Used to warn after an ad-hoc log that the same lift was already on the
1662
+ * athlete's scheduled workout — a caller can then point at {@link logAthleteSet}. Personal sessions
1663
+ * (`personal_cal === true`) are skipped: the ad-hoc log itself lands there, so they are not an
1664
+ * alternative. One row per matching saved-set exercise, dropping any with an unresolvable id.
1665
+ */
1666
+ function findScheduledMatches(workouts, exerciseIds) {
1667
+ const out = [];
1668
+ for (const { pw, savedWorkoutSetId, ex } of eachPrescribedExercise(workouts)) {
1669
+ if (isPersonalSession(pw)) continue;
1670
+ const exerciseId = coerceInt(ex.exercise_id);
1671
+ const savedWorkoutSetExerciseId = coerceInt(ex.id);
1672
+ if (exerciseId === null || savedWorkoutSetExerciseId === null) continue;
1673
+ if (!exerciseIds.has(exerciseId)) continue;
1674
+ out.push({
1675
+ exerciseId,
1676
+ title: exerciseTitle(ex),
1677
+ program: str$1(pw.program_title),
1678
+ workoutTitle: str$1(pw.workout_title) ?? "",
1679
+ savedWorkoutSetId,
1680
+ savedWorkoutSetExerciseId
1681
+ });
1682
+ }
1683
+ return out;
1684
+ }
1503
1685
  /** List the prescribed exercises on a day as `id (title)` labels, for not-found errors. */
1504
1686
  function prescribedExerciseLabels(workouts) {
1505
1687
  const labels = [];
1506
1688
  for (const { ex } of eachPrescribedExercise(workouts)) {
1507
1689
  const id = coerceInt(ex.exercise_id);
1508
1690
  if (id === null) continue;
1509
- const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1510
- labels.push(`${id} (${title})`);
1691
+ labels.push(`${id} (${exerciseTitle(ex, "exercise")})`);
1511
1692
  }
1512
1693
  return labels;
1513
1694
  }
@@ -1534,7 +1715,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1534
1715
  savedWorkoutSetId,
1535
1716
  results
1536
1717
  });
1537
- out.push(written);
1718
+ out.push({
1719
+ savedWorkoutSetId: written.savedWorkoutSetId,
1720
+ exercisesLogged: written.exercisesLogged
1721
+ });
1538
1722
  }
1539
1723
  return out;
1540
1724
  }
@@ -1547,7 +1731,8 @@ async function logResolvedExercises(client, target, date, resolved) {
1547
1731
  */
1548
1732
  async function logAdHocSession(client, args) {
1549
1733
  if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
1550
- const existing = findPersonalSessionWorkoutId(await fetchAthleteWorkouts(client, args.date, args.date));
1734
+ const day = await fetchAthleteWorkouts(client, args.date, args.date);
1735
+ const existing = findPersonalSessionWorkoutId(day);
1551
1736
  const created = existing === null;
1552
1737
  const workoutId = existing ?? (await createPersonalWorkout(client, args.date)).workoutId;
1553
1738
  const withOrder = args.exercises.map((e, i) => ({
@@ -1571,11 +1756,14 @@ async function logAdHocSession(client, args) {
1571
1756
  };
1572
1757
  });
1573
1758
  const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
1574
- return {
1759
+ const result = {
1575
1760
  date: args.date,
1576
1761
  created,
1577
1762
  sets
1578
1763
  };
1764
+ const scheduledAlternatives = findScheduledMatches(day, new Set(args.exercises.map((e) => e.exerciseId)));
1765
+ if (scheduledAlternatives.length > 0) result.scheduledAlternatives = scheduledAlternatives;
1766
+ return result;
1579
1767
  }
1580
1768
  /**
1581
1769
  * Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
@@ -1612,27 +1800,6 @@ async function logSessionForAthlete(client, args) {
1612
1800
  sets
1613
1801
  };
1614
1802
  }
1615
- /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1616
- function presentExerciseHistory(detail) {
1617
- return {
1618
- liftPRs: (detail.liftPRs ?? []).map((p) => ({
1619
- description: p.description ?? null,
1620
- reps: p.reps ?? null,
1621
- weight: p.weight ?? null,
1622
- units: p.units ?? null,
1623
- date: p.dateCompleted ?? null
1624
- })),
1625
- sessions: (detail.history ?? []).map((h) => ({
1626
- date: h.dateCompleted,
1627
- abr: h.abr ?? null,
1628
- estimated1RM: h.bestEstimated1RM ?? null,
1629
- sets: (h.sets ?? []).map((s) => ({
1630
- setNumber: s.setNumber,
1631
- value: s.formattedValue ?? null
1632
- }))
1633
- }))
1634
- };
1635
- }
1636
1803
  /** Normalize one-or-many emails into a deduped, trimmed list. */
1637
1804
  function emailList(emails) {
1638
1805
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -2789,7 +2956,7 @@ async function saveSession(sessionId) {
2789
2956
  }
2790
2957
  //#endregion
2791
2958
  //#region src/cli.ts
2792
- const HELP = `trainheroic — command-line tool for the TrainHeroic coaching API
2959
+ const HELP = `trainheroic — command-line tool for the TrainHeroic API
2793
2960
 
2794
2961
  Credentials come from TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD. Output is JSON.
2795
2962
  Coaching commands live under 'coach'; your own training lives under 'athlete'.
@@ -2823,6 +2990,9 @@ Coach — manage a roster (needs a coach account):
2823
2990
  --date is the workout's SCHEDULED date (not necessarily today); get --set (savedWorkoutSetId)
2824
2991
  and each result's savedWorkoutSetExerciseId from 'coach athlete-workouts ... --log-ids'
2825
2992
  resultsJson: [{"savedWorkoutSetExerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2993
+ each set fills the next position; add "slot":K to place it at the K-th prescribed set. A
2994
+ partial log records only the positions you send (plus any logged earlier); a superset block
2995
+ completes only once all its exercises are logged.
2826
2996
  coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes
2827
2997
  log by exercise instead of by set id: each exercise (exerciseId + sets) is matched to a set
2828
2998
  already on the athlete's calendar that day. The API can't put an off-plan session on an
@@ -2888,15 +3058,17 @@ Coach — manage a roster (needs a coach account):
2888
3058
 
2889
3059
  Athlete — the logged-in user's own training (a coach account works too):
2890
3060
  athlete whoami | profile [--metric] | prefs | working-maxes
2891
- athlete workouts --start Y-M-D --end Y-M-D [--raw] [--log-ids] [--logged-only] [--limit N] [--summary] (--log-ids: the savedWorkoutSetId + savedWorkoutSetExerciseId log-set needs)
3061
+ athlete workouts --start Y-M-D --end Y-M-D [--raw] [--logged-only] [--limit N] [--summary] (reads what you did; for the log ids use 'athlete log-targets')
3062
+ athlete log-targets --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--raw] (the savedWorkoutSetId + savedWorkoutSetExerciseId log-set needs; --program narrows when several workouts share a date)
2892
3063
  athlete exercises [--q <text>] [--limit N]
2893
3064
  athlete history <exerciseId> [--raw]
2894
3065
  athlete prs <exerciseId>
2895
3066
  athlete stats <exerciseId> --date Y-M-D
2896
3067
  athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
2897
3068
  athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
2898
- athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date; ids from 'athlete workouts ... --log-ids')
3069
+ athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date; ids from 'athlete log-targets'; each set fills the next position, add "slot":K to target the K-th; a partial log records only what you send)
2899
3070
  athlete log-session --date Y-M-D <exercisesJson>|--file f --yes (log OFF-PLAN work with no prescription — creates/reuses a personal session for the date, then logs it; exerciseIds from 'athlete exercises')
3071
+ athlete session-remove --id <programWorkoutId> --date Y-M-D --yes (delete a stray PERSONAL session; the id is the session 'id' from 'athlete workouts')
2900
3072
  JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2901
3073
  `;
2902
3074
  function out(value) {
@@ -3260,10 +3432,57 @@ async function cmdAthleteLogSession(client, a) {
3260
3432
  exercises: await jsonInput(positionals[0], values.file)
3261
3433
  }, "log-session args");
3262
3434
  if (values.yes !== true) fail(`logging a session on ${date} writes to your coach-visible log; add --yes.`);
3263
- return out(await logAdHocSession(client, {
3435
+ const result = await logAdHocSession(client, {
3264
3436
  date: args.date,
3265
3437
  exercises: toSessionExercises(args.exercises)
3266
- }));
3438
+ });
3439
+ const scheduled = result.scheduledAlternatives ?? [];
3440
+ if (scheduled.length > 0) {
3441
+ const names = scheduled.map((s) => s.title).join(", ");
3442
+ process.stderr.write(`note: ${names} ${scheduled.length === 1 ? "was" : "were"} already on a coach-scheduled workout today; this logged a SEPARATE personal session. To log into the scheduled workout instead, use 'athlete log-set' with the savedWorkoutSetId/savedWorkoutSetExerciseId in scheduledAlternatives, or 'athlete session-remove' to delete this personal session.\n`);
3443
+ }
3444
+ return out(result);
3445
+ }
3446
+ async function cmdAthleteLogTargets(client, a) {
3447
+ const usage = "athlete log-targets --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--raw]";
3448
+ const { values } = parse(a, {
3449
+ start: { type: "string" },
3450
+ end: { type: "string" },
3451
+ program: { type: "string" },
3452
+ "program-id": { type: "string" },
3453
+ team: { type: "string" },
3454
+ raw: { type: "boolean" }
3455
+ });
3456
+ const all = await fetchAthleteWorkouts(client, isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
3457
+ const filter = {};
3458
+ if (values.program !== void 0) filter.programTitle = values.program;
3459
+ if (values["program-id"] !== void 0) filter.programId = toInt(values["program-id"], "--program-id");
3460
+ if (values.team !== void 0) filter.teamId = toInt(values.team, "--team");
3461
+ const workouts = selectWorkoutsByProgram(all, filter);
3462
+ return out(values.raw === true ? workouts : presentLogTargets(workouts));
3463
+ }
3464
+ const SESSION_REMOVE_USAGE = "athlete session-remove --id <programWorkoutId> --date Y-M-D --yes";
3465
+ async function cmdAthleteSessionRemove(client, a) {
3466
+ const { values } = parse(a, {
3467
+ id: { type: "string" },
3468
+ date: { type: "string" },
3469
+ yes: { type: "boolean" }
3470
+ });
3471
+ const args = validate(athleteSessionRemoveArgsSchema, {
3472
+ programWorkoutId: need(values.id, SESSION_REMOVE_USAGE),
3473
+ date: isoDate(need(values.date, SESSION_REMOVE_USAGE), "--date")
3474
+ }, "session-remove args");
3475
+ const id = toInt(String(args.programWorkoutId), "--id");
3476
+ if (values.yes !== true) fail(`removing personal session ${id} deletes its logged work; add --yes.`);
3477
+ await removePersonalWorkout(client, {
3478
+ programWorkoutId: id,
3479
+ date: args.date
3480
+ });
3481
+ return out({
3482
+ removed: true,
3483
+ programWorkoutId: id,
3484
+ date: args.date
3485
+ });
3267
3486
  }
3268
3487
  async function cmdAthlete(client, rest) {
3269
3488
  const [sub, ...a] = rest;
@@ -3334,9 +3553,11 @@ async function cmdAthlete(client, rest) {
3334
3553
  return out(await fetchLeaderboard(client, workoutId, opts));
3335
3554
  }
3336
3555
  case "export": return cmdAthleteExport(client, a);
3556
+ case "log-targets": return cmdAthleteLogTargets(client, a);
3337
3557
  case "log-set": return cmdAthleteLogSet(client, a);
3338
3558
  case "log-session": return cmdAthleteLogSession(client, a);
3339
- default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set|log-session>");
3559
+ case "session-remove": return cmdAthleteSessionRemove(client, a);
3560
+ default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|log-targets|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set|log-session|session-remove>");
3340
3561
  }
3341
3562
  }
3342
3563
  async function cmdSkill(rest) {
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/alandotcom/trainheroic-unofficial.git",
8
8
  "directory": "packages/cli"
9
9
  },
10
- "description": "Command-line tool for the TrainHeroic coaching API.",
10
+ "description": "Command-line tool for the TrainHeroic API.",
11
11
  "type": "module",
12
12
  "bin": {
13
13
  "trainheroic": "./dist/cli.mjs"
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "1.4.0",
25
- "@trainheroic-unofficial/js": "1.4.0"
24
+ "@trainheroic-unofficial/dto": "1.6.0",
25
+ "@trainheroic-unofficial/js": "1.6.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",
@@ -63,8 +63,10 @@ on a 401/403. Start with `$TH athlete whoami` to confirm auth and get your `id`.
63
63
  | Working maxes (drive % prescriptions) | `$TH athlete working-maxes` |
64
64
  | Benchmark leaderboard | `$TH athlete leaderboard <workoutId>` |
65
65
  | Download all historicals to JSON | `$TH athlete export [--out dir] [--full]` |
66
+ | Log ids for a scheduled workout | `$TH athlete log-targets --start Y-M-D --end Y-M-D [--program <title>]` |
66
67
  | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
67
68
  | Log an off-plan session (gated) | `$TH athlete log-session --date Y-M-D '[{"exerciseId":N,"sets":[...]}]' --yes` |
69
+ | Remove a stray personal session | `$TH athlete session-remove --id <programWorkoutId> --date Y-M-D --yes` |
68
70
 
69
71
  ## Reading training
70
72
 
@@ -114,11 +116,12 @@ marks the set completed, and the result shows up in your exercise history. **It
114
116
  athlete-facing**: it mutates your training log, which your coach can see, so confirm before
115
117
  running and re-read the workout to check the result landed.
116
118
 
117
- Get the `savedWorkoutSetId` and each `savedWorkoutSetExerciseId` from the raw workout
118
- (`$TH athlete workouts --start <day> --end <day> --raw`, under
119
- `summarizedSavedWorkout.saved_workout.workoutSets`). Then:
119
+ Get the `savedWorkoutSetId` and each `savedWorkoutSetExerciseId` from `$TH athlete log-targets`
120
+ — a compact one-row-per-set view, no raw blob to dig through. When several workouts fall on the
121
+ same day (you're on more than one program), narrow with `--program <title-substring>`:
120
122
 
121
123
  ```bash
124
+ $TH athlete log-targets --start 2026-06-01 --end 2026-06-01 --program "Bodybuilding"
122
125
  $TH athlete log-set --date 2026-06-01 --set 1593305783 --yes \
123
126
  '[{"savedWorkoutSetExerciseId": 2712369448, "sets": [{"param1": 3, "param2": 225}]}]'
124
127
  ```
@@ -8,7 +8,7 @@ metadata:
8
8
 
9
9
  # TrainHeroic API
10
10
 
11
- Authenticated access to the TrainHeroic coaching API through the `trainheroic`
11
+ Authenticated access to the TrainHeroic API through the `trainheroic`
12
12
  command-line tool (`@trainheroic-unofficial/cli`), which wraps the `@trainheroic-unofficial/js`
13
13
  SDK: a spec-driven workout builder, an on-disk exercise cache, and gated messaging.
14
14