@trainheroic-unofficial/cli 3.0.0 → 3.1.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
@@ -84,7 +84,7 @@ trainheroic coach workout build --program 988 --date 2026-6-22 --file day.json -
84
84
  validation path on bad input.
85
85
  - Actions that touch an athlete or delete data require an explicit `--yes`:
86
86
  `coach workout publish`, `coach workout remove`, `coach exercise forget`,
87
- `coach message send`, `coach message delete`, `athlete log-set`, and
87
+ `coach message send`, `coach message delete`, `athlete log-set`, `athlete prescribe-set`, and
88
88
  `coach workout build --publish`. (`coach workout build` alone creates a draft; `--publish`
89
89
  makes it visible to athletes, which is why that combination needs `--yes`.)
90
90
  - JSON input can be passed inline, with `--file <path>`, or piped on stdin. Inputs are
package/dist/cli.mjs CHANGED
@@ -211,20 +211,18 @@ const logSetArgsSchema = z.object({
211
211
  */
212
212
  const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
213
213
  /**
214
- * Args for the coach prescription-override write. Like {@link coachLogSetArgsSchema}
215
- * (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but the values are prescribed
216
- * targets (param1 = reps, param2 = weight) written to the athlete's plan without marking the set
217
- * performed. The write replaces this athlete's whole prescription for the set, so its sets are
218
- * positional and sequential by definition: it deliberately omits the log path's `slot` field (a
219
- * sparse, slot-targeted prescription has no meaning here) by building its results off
220
- * {@link loggedSetSchema} rather than {@link loggedSetWithSlotSchema}.
214
+ * Args for changing the logged-in athlete's prescribed targets without marking the set performed.
215
+ * The write replaces the exercise's whole prescription, so its sets are positional and sequential
216
+ * by definition: it deliberately omits the log path's `slot` field because a sparse prescription
217
+ * has no meaning here.
221
218
  */
222
- const coachPrescribeSetArgsSchema = z.object({
219
+ const athletePrescribeSetArgsSchema = z.object({
223
220
  date: dateString,
224
221
  savedWorkoutSetId: idArgSchema,
225
- athleteId: idArgSchema,
226
222
  results: prescribedExerciseResultsSchema
227
223
  });
224
+ /** Coach variant of {@link athletePrescribeSetArgsSchema}, with the roster athlete to update. */
225
+ const coachPrescribeSetArgsSchema = athletePrescribeSetArgsSchema.extend({ athleteId: idArgSchema });
228
226
  /**
229
227
  * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
230
228
  * roster athlete's saved-workout slots with a different exercise, the API equivalent of the
@@ -800,8 +798,9 @@ function sortRosterByRecency(rows) {
800
798
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
801
799
  const rows = [];
802
800
  const concurrency = 6;
803
- for (let i = 0; i < athleteIds.length; i += concurrency) {
804
- const chunk = athleteIds.slice(i, i + concurrency);
801
+ const uniqueAthleteIds = [...new Set(athleteIds)];
802
+ for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
803
+ const chunk = uniqueAthleteIds.slice(i, i + concurrency);
805
804
  const settled = await Promise.all(chunk.map(async (id) => {
806
805
  try {
807
806
  return {
@@ -1661,6 +1660,21 @@ async function logAthleteSet(client, args) {
1661
1660
  };
1662
1661
  }
1663
1662
  /**
1663
+ * Set the logged-in athlete's prescribed reps/weight for one saved workout set WITHOUT marking it
1664
+ * performed. This is the athlete-side equivalent of editing target values in the app: it writes
1665
+ * `param_N_data_M` with every made/completed flag cleared and skips the set-completion PUT.
1666
+ *
1667
+ * The write replaces the selected exercise's whole prescription, so callers must pass every set
1668
+ * they want to keep. An omitted param is cleared rather than preserved.
1669
+ */
1670
+ async function prescribeAthleteSet(client, args) {
1671
+ const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "prescribe");
1672
+ return {
1673
+ savedWorkoutSetId: r.savedWorkoutSetId,
1674
+ exercisesPrescribed: r.exercisesWritten
1675
+ };
1676
+ }
1677
+ /**
1664
1678
  * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
1665
1679
  * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
1666
1680
  * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
@@ -1745,9 +1759,10 @@ async function swapAthleteExercise(client, args) {
1745
1759
  };
1746
1760
  }
1747
1761
  /**
1748
- * Shared set-write behind {@link logAthleteSet}, {@link logForAthlete}, and
1749
- * {@link prescribeForAthlete}. `target` selects the surface: `athlete` writes `/1.0/athlete/...`;
1750
- * `coach` writes `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body.
1762
+ * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
1763
+ * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
1764
+ * writes `/1.0/athlete/...`; `coach` writes `/1.0/coach/...{athleteId}` and stamps `athleteId` into
1765
+ * each body.
1751
1766
  *
1752
1767
  * Step 1 PUTs each exercise's per-set values to its own endpoint (the only path that actually
1753
1768
  * stores reps and weight). `mode` decides what those values mean: `"log"` records them as a
@@ -1979,7 +1994,7 @@ function prescribedExerciseLabels(workouts) {
1979
1994
  return labels;
1980
1995
  }
1981
1996
  /** Group resolved exercises by saved set and write each set via the given log target. */
1982
- async function logResolvedExercises(client, target, date, resolved) {
1997
+ async function logResolvedExercises(client, target, workouts, resolved) {
1983
1998
  const bySet = /* @__PURE__ */ new Map();
1984
1999
  for (const r of resolved) {
1985
2000
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -1991,19 +2006,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1991
2006
  }
1992
2007
  const out = [];
1993
2008
  for (const [savedWorkoutSetId, results] of bySet) {
1994
- const written = target.role === "coach" ? await logForAthlete(client, {
1995
- athleteId: target.athleteId,
1996
- date,
1997
- savedWorkoutSetId,
1998
- results
1999
- }) : await logAthleteSet(client, {
2000
- date,
2001
- savedWorkoutSetId,
2002
- results
2003
- });
2009
+ const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
2004
2010
  out.push({
2005
2011
  savedWorkoutSetId: written.savedWorkoutSetId,
2006
- exercisesLogged: written.exercisesLogged
2012
+ exercisesLogged: written.exercisesWritten
2007
2013
  });
2008
2014
  }
2009
2015
  return out;
@@ -2041,7 +2047,7 @@ async function logAdHocSession(client, args) {
2041
2047
  sets: e.sets
2042
2048
  };
2043
2049
  });
2044
- const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
2050
+ const sets = await logResolvedExercises(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), resolved);
2045
2051
  const result = {
2046
2052
  date: args.date,
2047
2053
  created,
@@ -2079,7 +2085,7 @@ async function logSessionForAthlete(client, args) {
2079
2085
  const sets = await logResolvedExercises(client, {
2080
2086
  role: "coach",
2081
2087
  athleteId: args.athleteId
2082
- }, args.date, resolved);
2088
+ }, day, resolved);
2083
2089
  return {
2084
2090
  date: args.date,
2085
2091
  created: false,
@@ -2439,6 +2445,7 @@ async function collectAdvisories(blocks, index) {
2439
2445
  }
2440
2446
  //#endregion
2441
2447
  //#region ../js/src/workout-session.ts
2448
+ const EXERCISE_SAVE_CONCURRENCY = 4;
2442
2449
  /**
2443
2450
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2444
2451
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -2472,15 +2479,14 @@ async function buildSession(client, opts) {
2472
2479
  const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2473
2480
  const byOrder = new Map(created.map((b) => [b.order, b.id]));
2474
2481
  let counter = 0;
2475
- const payloads = blocks.map((block, i) => {
2482
+ await mapPool(blocks.map((block, i) => {
2476
2483
  const wsid = byOrder.get(i + 1);
2477
2484
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2478
2485
  return block.exercises.map((ex, j) => {
2479
2486
  counter += 1;
2480
2487
  return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2481
2488
  });
2482
- });
2483
- await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2489
+ }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (payload) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", payload));
2484
2490
  if (opts.instruction !== void 0 && opts.instruction !== "") {
2485
2491
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2486
2492
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -3186,9 +3192,11 @@ async function deleteComment(client, streamId, commentId) {
3186
3192
  if (!res.ok) throw new Error(`Message delete failed (HTTP ${res.status}).`);
3187
3193
  return res.data;
3188
3194
  }
3189
- async function readLive(client, streamId, limit) {
3190
- const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=`);
3195
+ async function readLive(client, streamId, limit, afterCommentId) {
3196
+ const cursor = afterCommentId === void 0 ? "" : String(afterCommentId);
3197
+ const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=${cursor}`);
3191
3198
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`Message read failed (HTTP ${res.status}).`);
3199
+ if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
3192
3200
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
3193
3201
  }
3194
3202
  //#endregion
@@ -3319,21 +3327,12 @@ var ExerciseLibrary = class {
3319
3327
  }
3320
3328
  async resolve(name) {
3321
3329
  await this.ensureFresh();
3322
- let hit = this.#exact(name);
3330
+ const hit = this.#exact(name);
3323
3331
  if (hit) return {
3324
3332
  match: hit,
3325
3333
  candidates: [hit]
3326
3334
  };
3327
- let candidates = this.#searchOnly(name, 20);
3328
- if (candidates.length === 0) {
3329
- await this.refresh();
3330
- hit = this.#exact(name);
3331
- if (hit) return {
3332
- match: hit,
3333
- candidates: [hit]
3334
- };
3335
- candidates = this.#searchOnly(name, 20);
3336
- }
3335
+ const candidates = this.#searchOnly(name, 20);
3337
3336
  if (candidates.length === 1) return {
3338
3337
  match: candidates[0] ?? null,
3339
3338
  candidates
@@ -3521,7 +3520,7 @@ Coach — manage a roster (needs a coach account):
3521
3520
 
3522
3521
  messaging:
3523
3522
  coach message list
3524
- coach message read <streamId> [--limit N]
3523
+ coach message read <streamId> [--limit N] [--after <commentId>]
3525
3524
  coach message draft <streamId> <text> [--reply-to <id>]
3526
3525
  coach message send <streamId> <text> [--reply-to <id>] --yes
3527
3526
  coach message delete <streamId> <commentId> --yes
@@ -3537,6 +3536,7 @@ Athlete — the logged-in user's own training (a coach account works too):
3537
3536
  athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
3538
3537
  athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
3539
3538
  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)
3539
+ athlete prescribe-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (sets your PLANNED reps/weight without logging completion; replaces the selected exercise's whole prescription, so pass every set/value to keep)
3540
3540
  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')
3541
3541
  athlete session-remove --id <programWorkoutId> --date Y-M-D --yes (delete a stray PERSONAL session; the id is the session 'id' from 'athlete workouts')
3542
3542
  athlete swap-exercise --set-exercise <savedWorkoutSetExerciseId> --exercise <exerciseId> --yes (substitute one prescribed exercise in a COACH-SCHEDULED slot for a different one — your copy only; slot id from 'athlete log-targets', exerciseId from 'athlete exercises')
@@ -3756,8 +3756,11 @@ async function cmdMessage(client, rest) {
3756
3756
  userId: stream.userId
3757
3757
  })));
3758
3758
  case "read": {
3759
- const { values, positionals } = parse(a, { limit: { type: "string" } });
3760
- return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N]"), "streamId"), values.limit !== void 0 ? toInt(values.limit, "--limit") : 20));
3759
+ const { values, positionals } = parse(a, {
3760
+ limit: { type: "string" },
3761
+ after: { type: "string" }
3762
+ });
3763
+ 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));
3761
3764
  }
3762
3765
  case "draft": {
3763
3766
  const { values, positionals } = parse(a, { "reply-to": { type: "string" } });
@@ -3881,6 +3884,29 @@ async function cmdAthleteLogSet(client, a) {
3881
3884
  results: toSetResults(args.results)
3882
3885
  }));
3883
3886
  }
3887
+ const ATHLETE_PRESCRIBE_SET_USAGE = "athlete prescribe-set --date Y-M-D --set <id> <resultsJson> --yes";
3888
+ async function cmdAthletePrescribeSet(client, a) {
3889
+ const { values, positionals } = parse(a, {
3890
+ date: { type: "string" },
3891
+ set: { type: "string" },
3892
+ file: { type: "string" },
3893
+ yes: { type: "boolean" }
3894
+ });
3895
+ const date = isoDate(need(values.date, ATHLETE_PRESCRIBE_SET_USAGE), "--date");
3896
+ const savedWorkoutSetId = toInt(need(values.set, ATHLETE_PRESCRIBE_SET_USAGE), "--set");
3897
+ const results = await jsonInput(positionals[0], values.file);
3898
+ const args = validate(athletePrescribeSetArgsSchema, {
3899
+ date,
3900
+ savedWorkoutSetId,
3901
+ results
3902
+ }, "athlete prescribe-set args");
3903
+ if (values.yes !== true) fail(`changing the prescribed values for set ${savedWorkoutSetId} requires --yes.`);
3904
+ return out(await prescribeAthleteSet(client, {
3905
+ date: args.date,
3906
+ savedWorkoutSetId,
3907
+ results: toSetResults(args.results)
3908
+ }));
3909
+ }
3884
3910
  const LOG_SESSION_USAGE = "athlete log-session --date Y-M-D <exercisesJson>|--file f --yes";
3885
3911
  /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
3886
3912
  function toSessionExercises(exercises) {
@@ -4065,10 +4091,11 @@ async function cmdAthlete(client, rest) {
4065
4091
  case "export": return cmdAthleteExport(client, a);
4066
4092
  case "log-targets": return cmdAthleteLogTargets(client, a);
4067
4093
  case "log-set": return cmdAthleteLogSet(client, a);
4094
+ case "prescribe-set": return cmdAthletePrescribeSet(client, a);
4068
4095
  case "log-session": return cmdAthleteLogSession(client, a);
4069
4096
  case "session-remove": return cmdAthleteSessionRemove(client, a);
4070
4097
  case "swap-exercise": return cmdAthleteSwapExercise(client, a);
4071
- 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|swap-exercise>");
4098
+ default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|log-targets|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set|prescribe-set|log-session|session-remove|swap-exercise>");
4072
4099
  }
4073
4100
  }
4074
4101
  async function cmdSkill(rest) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "3.0.0",
3
+ "version": "3.1.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.0.0",
25
- "@trainheroic-unofficial/js": "3.0.0"
24
+ "@trainheroic-unofficial/dto": "3.1.0",
25
+ "@trainheroic-unofficial/js": "3.1.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.2.0",
@@ -65,6 +65,7 @@ on a 401/403. Start with `$TH athlete whoami` to confirm auth and get your `id`.
65
65
  | Download all historicals to JSON | `$TH athlete export [--out dir] [--full]` |
66
66
  | Log ids for a scheduled workout | `$TH athlete log-targets --start Y-M-D --end Y-M-D [--program <title>]` |
67
67
  | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
68
+ | Set planned reps/weight (gated) | `$TH athlete prescribe-set --date Y-M-D --set <id> ... --yes` |
68
69
  | Log an off-plan session (gated) | `$TH athlete log-session --date Y-M-D '[{"exerciseId":N,"sets":[...]}]' --yes` |
69
70
  | Swap a prescribed exercise (gated) | `$TH athlete swap-exercise --set-exercise <sweId> --exercise <exerciseId> --yes` |
70
71
  | Remove a stray personal session | `$TH athlete session-remove --id <programWorkoutId> --date Y-M-D --yes` |
@@ -131,6 +132,21 @@ $TH athlete log-set --date 2026-06-01 --set 1593305783 --yes \
131
132
  check the result landed as intended. `param1`/`param2` are the entered values by entry slot
132
133
  (check the exercise's positional units first).
133
134
 
135
+ ### Setting planned weight without logging
136
+
137
+ Use `$TH athlete prescribe-set` when you know the target reps or weight but have not performed the
138
+ set. It writes the prescription with every completion flag clear, so the workout remains open and
139
+ nothing is added to exercise history:
140
+
141
+ ```bash
142
+ $TH athlete prescribe-set --date 2026-06-01 --set 1593305783 --yes \
143
+ '[{"savedWorkoutSetExerciseId": 2712369448, "sets": [{"param1": 5, "param2": 225}]}]'
144
+ ```
145
+
146
+ The write replaces that exercise's whole prescription. Include every planned set and every value
147
+ you want to keep; an omitted parameter is cleared. Get both ids from `athlete log-targets`, just as
148
+ for `log-set`.
149
+
134
150
  ### Logging an off-plan session
135
151
 
136
152
  When you trained something a coach never scheduled (accessory work, a makeup lift, an
@@ -87,7 +87,8 @@ account) expose:
87
87
  - Live reads: `athlete_whoami`, `athlete_profile`, `athlete_prefs`, `athlete_workouts`,
88
88
  `athlete_exercises`, `athlete_exercise_history`, `athlete_personal_records`,
89
89
  `athlete_exercise_stats`, `athlete_working_maxes`, `athlete_leaderboard`.
90
- - Gated write: `athlete_log_set` (elicitation or `confirm:true`).
90
+ - Gated writes include `athlete_log_set` for performed results and `athlete_prescribe_set` for
91
+ planned reps/weight that must not mark a set completed (elicitation or `confirm:true`).
91
92
 
92
93
  ## Warehouse tools (hosted worker only, D1-backed)
93
94