@trainheroic-unofficial/cli 4.2.0 → 4.3.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
@@ -56,8 +56,10 @@ program's URL in the TrainHeroic web app, or run `trainheroic coach programs`).
56
56
  library id; get one with `coach exercise resolve`. `reps` and `weight` take a scalar or a
57
57
  per-set array (`"reps": [5, 5, 3]`). `reps` is the primary value slot and `weight` is the
58
58
  secondary slot, so either can represent distance or time on an exercise configured that way.
59
- State `primaryUnit` for `reps` and `secondaryUnit` for `weight` using the fixed units returned
60
- by `coach exercise resolve`. The build stops before writing if a unit differs. The full schema
59
+ State `primaryUnit` for `reps` and `secondaryUnit` for `weight`. `coach exercise resolve` returns
60
+ each exercise's default units; a different stated unit, such as `%max` on Back Squat, is set on
61
+ that session. The build stops before writing if a unit is unknown or conflicts with an explicit
62
+ `param_1_type`/`param_2_type`. The full schema
61
63
  is `WorkoutSpec` in [`@trainheroic-unofficial/dto`](../dto).
62
64
 
63
65
  ```jsonc
package/dist/cli.mjs CHANGED
@@ -5,7 +5,7 @@ import { dirname, join } from "node:path";
5
5
  import process from "node:process";
6
6
  import { parseArgs } from "node:util";
7
7
  import { z } from "zod";
8
- //#region ../dto/src/common.ts
8
+ // ../dto/src/common.ts
9
9
  /** An entity id as it arrives over the wire — a number or a numeric string. */
10
10
  const idSchema = z.union([z.string(), z.number()]);
11
11
  /**
@@ -14,8 +14,7 @@ const idSchema = z.union([z.string(), z.number()]);
14
14
  * a bad argument fails validation instead of becoming NaN in a URL or a query.
15
15
  */
16
16
  const idArgSchema = z.union([z.number().int(), z.string().regex(/^\d+$/u)]);
17
- //#endregion
18
- //#region ../dto/src/athlete.ts
17
+ // ../dto/src/athlete.ts
19
18
  const intLike$1 = z.union([z.number(), z.string()]);
20
19
  const intLikeOrNull$1 = z.union([
21
20
  z.number(),
@@ -415,8 +414,7 @@ const presentedExerciseHistorySchema = z.object({
415
414
  sessions: z.array(presentedExerciseSessionSchema)
416
415
  });
417
416
  z.union([presentedExerciseHistorySchema, exerciseHistoryDetailSchema]);
418
- //#endregion
419
- //#region ../dto/src/exercise.ts
417
+ // ../dto/src/exercise.ts
420
418
  /**
421
419
  * A row presented for display. The raw param-type codes are dropped and the fixed
422
420
  * measurement units are surfaced positionally in `units`, ordered by entry slot
@@ -477,8 +475,7 @@ z.object({
477
475
  text: z.string().min(1),
478
476
  replyTo: idSchema.optional()
479
477
  });
480
- //#endregion
481
- //#region ../dto/src/responses.ts
478
+ // ../dto/src/responses.ts
482
479
  const intLike = z.union([z.number(), z.string()]);
483
480
  const intLikeOrNull = z.union([
484
481
  z.number(),
@@ -524,8 +521,7 @@ const teamPublishPatchSchema = z.object({
524
521
  pub_time: z.unknown().optional(),
525
522
  pub_timezone: z.string().optional()
526
523
  }).refine((v) => v.pub_enabled !== void 0 || v.pub_days !== void 0 || v.pub_time !== void 0 || v.pub_timezone !== void 0, { message: "Provide at least one pub_* field" });
527
- //#endregion
528
- //#region ../dto/src/tool-output.ts
524
+ // ../dto/src/tool-output.ts
529
525
  const nullableNumber = z.number().nullable();
530
526
  const nullableString = z.string().nullable();
531
527
  const truncationMarkerSchema = z.looseObject({
@@ -660,6 +656,7 @@ const workoutReadBlockOutputSchema = z.object({
660
656
  });
661
657
  const workoutReadOutputSchema = z.object({
662
658
  pwId: z.number(),
659
+ workoutId: z.number().nullable(),
663
660
  date: z.string(),
664
661
  published: z.json().optional(),
665
662
  instruction: z.string(),
@@ -727,8 +724,7 @@ z.object({
727
724
  programId: z.number(),
728
725
  containerId: nullableNumber
729
726
  });
730
- //#endregion
731
- //#region ../dto/src/workout.ts
727
+ // ../dto/src/workout.ts
732
728
  /** A single exercise prescription inside a block. */
733
729
  const exerciseSpecSchema = z.object({
734
730
  id: z.union([z.number(), z.string()]),
@@ -740,8 +736,8 @@ const exerciseSpecSchema = z.object({
740
736
  ]).optional().describe("Primary slot values; may be reps, distance, or time. State primaryUnit."),
741
737
  sets: z.number().optional(),
742
738
  weight: z.union([z.number(), z.array(z.number())]).optional().describe("Secondary slot values; may be weight or time. State secondaryUnit."),
743
- primaryUnit: z.string().trim().min(1).optional().describe("Intended primary unit from exercise_resolve, such as reps, m, mi, or sec."),
744
- secondaryUnit: z.string().trim().min(1).optional().describe("Intended secondary unit from exercise_resolve, such as lb or sec."),
739
+ primaryUnit: z.string().trim().min(1).optional().describe("Unit of the primary values, such as reps, m, mi, or sec. A unit other than the exercise's default from exercise_resolve is set on this session."),
740
+ secondaryUnit: z.string().trim().min(1).optional().describe("Unit of the secondary values, such as lb, %max, RPE, or sec. A unit other than the exercise's default from exercise_resolve is set on this session."),
745
741
  rpe: z.union([z.number(), z.string()]).optional(),
746
742
  instr: z.string().optional(),
747
743
  param_1_type: z.number().optional(),
@@ -821,8 +817,12 @@ const sessionTemplateCreateSchema = z.object({
821
817
  title: z.string().min(1),
822
818
  instruction: z.string().optional()
823
819
  });
824
- //#endregion
825
- //#region ../js/src/date-window.ts
820
+ z.object({
821
+ workoutId: z.number().int().describe("The session's workout_id (workout_build returns it as workoutId)."),
822
+ pwId: z.number().int().describe("The session's programWorkout id (workout_build returns it as pwId)."),
823
+ title: z.string().trim().min(1).describe("Title of the new library template.")
824
+ });
825
+ // ../js/src/date-window.ts
826
826
  const DAY_MS = 864e5;
827
827
  const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
828
828
  const MAX_DATE_WINDOWS = 100;
@@ -855,8 +855,7 @@ function splitDateRange(start, end, maxDays) {
855
855
  });
856
856
  return windows;
857
857
  }
858
- //#endregion
859
- //#region ../js/src/http-error.ts
858
+ // ../js/src/http-error.ts
860
859
  const MAX_REQUEST_KEYS = 50;
861
860
  const MAX_RESPONSE_DEPTH = 4;
862
861
  const MAX_RESPONSE_KEYS = 20;
@@ -1092,11 +1091,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1092
1091
  Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
1093
1092
  } catch {}
1094
1093
  }
1095
- //#endregion
1096
- //#region ../js/src/transport.ts
1094
+ // ../js/src/transport.ts
1097
1095
  const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
1098
- //#endregion
1099
- //#region ../js/src/auth.ts
1096
+ // ../js/src/auth.ts
1100
1097
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
1101
1098
  /**
1102
1099
  * The login endpoint, allowing an env override so a test harness can authenticate against a local
@@ -1147,8 +1144,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1147
1144
  role: data.role ?? ""
1148
1145
  };
1149
1146
  }
1150
- //#endregion
1151
- //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/chunk.mjs
1147
+ // ../../node_modules/.pnpm/es-toolkit@1.53.2/node_modules/es-toolkit/dist/array/chunk.mjs
1152
1148
  /**
1153
1149
  * Splits an array into smaller arrays of a specified length.
1154
1150
  *
@@ -1183,8 +1179,7 @@ function chunk(arr, size) {
1183
1179
  }
1184
1180
  return result;
1185
1181
  }
1186
- //#endregion
1187
- //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
1182
+ // ../../node_modules/.pnpm/es-toolkit@1.53.2/node_modules/es-toolkit/dist/array/uniq.mjs
1188
1183
  /**
1189
1184
  * Creates a duplicate-free version of an array.
1190
1185
  *
@@ -1203,13 +1198,12 @@ function chunk(arr, size) {
1203
1198
  function uniq(arr) {
1204
1199
  return [...new Set(arr)];
1205
1200
  }
1206
- //#endregion
1207
- //#region ../js/src/exercise-util.ts
1201
+ // ../js/src/exercise-util.ts
1208
1202
  /**
1209
- * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
1210
- * (the API forces param_1_type/param_2_type back to the library default on save), so
1211
- * resolve/search surface it to stop callers picking, say, the miles "Run" for a
1212
- * metric workout. Keep in sync with the workout builder's unit table.
1203
+ * Display labels for TrainHeroic parameter types. Each library exercise has a default type per
1204
+ * slot, which resolve/search surface so callers know, say, that stock "Run" defaults to miles.
1205
+ * A session can set a different type on an exercise; the workout builder maps a stated unit
1206
+ * back to its type code through this table, so keep it in sync with the builder's unit aliases.
1213
1207
  */
1214
1208
  const PARAM_UNIT = {
1215
1209
  0: null,
@@ -1250,7 +1244,7 @@ function unitLabel(paramType) {
1250
1244
  return PARAM_UNIT[t] ?? null;
1251
1245
  }
1252
1246
  /**
1253
- * Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
1247
+ * Default measurement units for an exercise, ordered by entry slot (param 1, then param 2).
1254
1248
  * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
1255
1249
  * by role. A null entry is an unset slot.
1256
1250
  */
@@ -1447,8 +1441,7 @@ function createLimiter(max) {
1447
1441
  function assertPositiveInteger(value, label) {
1448
1442
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1449
1443
  }
1450
- //#endregion
1451
- //#region ../js/src/client.ts
1444
+ // ../js/src/client.ts
1452
1445
  const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
1453
1446
  const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
1454
1447
  const MAX_REQUEST_CONCURRENCY = 4;
@@ -1568,8 +1561,7 @@ var TrainHeroicClient = class {
1568
1561
  return this.#transport(url, init);
1569
1562
  }
1570
1563
  };
1571
- //#endregion
1572
- //#region ../js/src/response-check.ts
1564
+ // ../js/src/response-check.ts
1573
1565
  /**
1574
1566
  * Validate an API response against its (loose) expected shape and warn once on drift.
1575
1567
  * Never throws: callers keep working via defensive coercion. This only surfaces a signal
@@ -1582,8 +1574,7 @@ function checkResponse(schema, data, label) {
1582
1574
  const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
1583
1575
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1584
1576
  }
1585
- //#endregion
1586
- //#region ../js/src/athlete.ts
1577
+ // ../js/src/athlete.ts
1587
1578
  async function getJson(client, path, label) {
1588
1579
  const res = await client.request("GET", path);
1589
1580
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2319,8 +2310,7 @@ function presentExerciseHistory(detail) {
2319
2310
  }))
2320
2311
  };
2321
2312
  }
2322
- //#endregion
2323
- //#region ../js/src/exercise-history.ts
2313
+ // ../js/src/exercise-history.ts
2324
2314
  /**
2325
2315
  * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
2326
2316
  * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
@@ -2341,8 +2331,7 @@ function historyInRange(presented, since, until) {
2341
2331
  sessions
2342
2332
  };
2343
2333
  }
2344
- //#endregion
2345
- //#region ../js/src/coach-athlete-calendar.ts
2334
+ // ../js/src/coach-athlete-calendar.ts
2346
2335
  async function getArray(client, path, label) {
2347
2336
  const res = await client.request("GET", path);
2348
2337
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2357,14 +2346,34 @@ async function getArray(client, path, label) {
2357
2346
  function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
2358
2347
  return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
2359
2348
  }
2349
+ /** A failed coach month-summary read; `status` is TrainHeroic's HTTP status. */
2350
+ var CoachMonthSummaryError = class extends Error {
2351
+ name = "CoachMonthSummaryError";
2352
+ status;
2353
+ constructor(message, status) {
2354
+ super(message);
2355
+ this.status = status;
2356
+ }
2357
+ };
2360
2358
  /**
2361
2359
  * A coach's month view of a roster athlete's logged sessions
2362
2360
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
2363
2361
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
2364
2362
  * `userId` in each row is the roster athlete, not the calling coach.
2363
+ *
2364
+ * TrainHeroic answers this endpoint with HTTP 500 for some athlete-months while the date-range
2365
+ * read (`fetchCoachAthleteWorkouts`) still works for the same athlete, so an HTTP 500 says so.
2365
2366
  */
2366
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
2367
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
2367
+ async function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
2368
+ const res = await client.request("GET", `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`);
2369
+ const label = `Coach athlete calendar summary for athlete ${athleteId} in ${year}-${String(month).padStart(2, "0")}`;
2370
+ if (res.ok) {
2371
+ if (Array.isArray(res.data)) return res.data;
2372
+ throw new Error(`${label} returned an unexpected response shape.`);
2373
+ }
2374
+ const message = trainHeroicApiErrorMessage(label, res.status, res.data);
2375
+ if (res.status === 500) throw new CoachMonthSummaryError(`${message.endsWith(".") ? message : `${message}.`} TrainHeroic's month summary fails for some athletes whose date-range workout read still answers; read the same dates through the date-range read.`, res.status);
2376
+ throw new CoachMonthSummaryError(message, res.status);
2368
2377
  }
2369
2378
  /**
2370
2379
  * Resolve a roster athlete's coach-writable calendar program id
@@ -2405,8 +2414,7 @@ async function resolveBuildProgramId(client, args) {
2405
2414
  const [y, m] = parseWorkoutDate(args.date);
2406
2415
  return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
2407
2416
  }
2408
- //#endregion
2409
- //#region ../js/src/exercise-set-payload.ts
2417
+ // ../js/src/exercise-set-payload.ts
2410
2418
  function slotData(exercise, key) {
2411
2419
  const value = exercise?.[key];
2412
2420
  return value === void 0 || value === null ? "" : String(value);
@@ -2474,8 +2482,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
2474
2482
  body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
2475
2483
  return body;
2476
2484
  }
2477
- //#endregion
2478
- //#region ../js/src/athlete-set-write.ts
2485
+ // ../js/src/athlete-set-write.ts
2479
2486
  const WRITE_CONCURRENCY = 4;
2480
2487
  /**
2481
2488
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
@@ -3107,8 +3114,7 @@ async function logSessionForAthlete(client, args) {
3107
3114
  sets
3108
3115
  };
3109
3116
  }
3110
- //#endregion
3111
- //#region ../js/src/util.ts
3117
+ // ../js/src/util.ts
3112
3118
  /**
3113
3119
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
3114
3120
  * spread into an object under `exactOptionalPropertyTypes` without the per-key
@@ -3123,8 +3129,7 @@ function definedProps(obj) {
3123
3129
  for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
3124
3130
  return result;
3125
3131
  }
3126
- //#endregion
3127
- //#region ../js/src/athlete-workout-note.ts
3132
+ // ../js/src/athlete-workout-note.ts
3128
3133
  /**
3129
3134
  * PUT /1.0/athlete/savedworkout/{id} — set the athlete's session note (the free-text box on the
3130
3135
  * workout screen) and/or session RPE. The date + programWorkoutId (`athlete_workouts` `id`) locate
@@ -3154,8 +3159,7 @@ async function setAthleteWorkoutNote(client, args) {
3154
3159
  rpe: coerceInt(data.rpe) ?? (args.rpe !== void 0 ? args.rpe : null)
3155
3160
  };
3156
3161
  }
3157
- //#endregion
3158
- //#region ../js/src/athlete-exercise-note.ts
3162
+ // ../js/src/athlete-exercise-note.ts
3159
3163
  /**
3160
3164
  * PUT /1.0/athlete/savedworkoutsetexercise/{id} — set the athlete's per-exercise note (the
3161
3165
  * "Add exercise note" box on the exercise screen). A notes-only body leaves logged reps/weight
@@ -3176,8 +3180,7 @@ async function setAthleteExerciseNote(client, args) {
3176
3180
  notes: typeof data.notes === "string" ? data.notes : args.notes
3177
3181
  };
3178
3182
  }
3179
- //#endregion
3180
- //#region ../js/src/workout-export.ts
3183
+ // ../js/src/workout-export.ts
3181
3184
  const DEFAULT_FILENAME_BASE = "trainheroic-workout-history";
3182
3185
  /** Pretty-printed JSON of the structured workouts, exactly as `presentAthleteWorkoutsExport` yields. */
3183
3186
  function workoutsToJson(workouts) {
@@ -3302,8 +3305,7 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
3302
3305
  filename: `${base}.${meta.extension}`
3303
3306
  };
3304
3307
  }
3305
- //#endregion
3306
- //#region ../js/src/workout-encode.ts
3308
+ // ../js/src/workout-encode.ts
3307
3309
  const LEADERBOARD_TYPE = {
3308
3310
  completion: 0,
3309
3311
  "for completion": 0,
@@ -3477,7 +3479,7 @@ function makeExercise(ex, workoutSetId, order, key) {
3477
3479
  param2Type = ex.param_2_type ?? 1;
3478
3480
  param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
3479
3481
  } else {
3480
- param2Type = 0;
3482
+ param2Type = ex.param_2_type ?? 0;
3481
3483
  param2Values = null;
3482
3484
  }
3483
3485
  const entry = {
@@ -3536,9 +3538,6 @@ function buildBlockPayload(blocks, workoutId) {
3536
3538
  };
3537
3539
  });
3538
3540
  }
3539
- function unitOr(t) {
3540
- return unitLabel(t) ?? "?";
3541
- }
3542
3541
  const UNIT_ALIASES = {
3543
3542
  rep: "reps",
3544
3543
  reps: "reps",
@@ -3576,74 +3575,171 @@ function statedUnit(value, label) {
3576
3575
  if (normalized === void 0) throw new Error(`${label}: unknown unit '${value}'. Use a concrete exercise unit such as reps, lb, sec, m, or mi.`);
3577
3576
  return normalized;
3578
3577
  }
3579
- function validateSlotUnit(label, field, stated, paramType, fixedType, allowAddedWeight = false) {
3578
+ /** TrainHeroic param type codes keyed by their unit label (`sec` and `in` each name two). */
3579
+ const TYPES_BY_UNIT = (() => {
3580
+ const map = /* @__PURE__ */ new Map();
3581
+ for (const [code, unit] of Object.entries(PARAM_UNIT)) if (unit !== null) map.set(unit, [...map.get(unit) ?? [], Number(code)]);
3582
+ return map;
3583
+ })();
3584
+ /**
3585
+ * Pick the param type a populated slot is written with. An explicit `param_N_type` wins and
3586
+ * must agree with the stated unit. Otherwise the exercise's library default is kept when it
3587
+ * already has the stated unit, and any other unit maps to its own type code.
3588
+ */
3589
+ function resolveSlotType(label, slot, stated, explicit, libraryDefault) {
3590
+ const field = slot === 1 ? "primaryUnit" : "secondaryUnit";
3580
3591
  if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
3581
3592
  const intended = statedUnit(stated, `${label} / ${field}`);
3582
- const fixed = unitLabel(fixedType);
3583
- if (intended !== fixed && !(allowAddedWeight && (fixedType === 0 || fixedType === null) && intended === "lb")) throw new Error(`${label}: ${field} ${intended} does not match the exercise's fixed ${fixed ?? "unset"} unit. Choose an exercise with the requested unit before building.`);
3584
- if (paramType !== void 0 && unitLabel(paramType) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param type ${paramType} (${unitLabel(paramType) ?? "unset"}).`);
3585
- }
3586
- /** Validate both populated slots against the library before any workout write. */
3587
- function validateExerciseUnits(blockTitle, ex, defaults) {
3588
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3589
- if (ex.reps !== void 0) validateSlotUnit(label, "primaryUnit", ex.primaryUnit, ex.param_1_type, defaults.param1);
3590
- if (ex.weight !== void 0) validateSlotUnit(label, "secondaryUnit", ex.secondaryUnit, ex.param_2_type, defaults.param2, true);
3591
- }
3592
- /** Flag spec params the API will silently override to the exercise's fixed units. */
3593
- function unitAdvisory(blockTitle, ex, defaults) {
3593
+ if (explicit !== void 0) {
3594
+ if (unitLabel(explicit) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param_${slot}_type ${explicit} (${unitLabel(explicit) ?? "unset"}).`);
3595
+ return explicit;
3596
+ }
3597
+ if (libraryDefault !== null && unitLabel(libraryDefault) === intended) return libraryDefault;
3598
+ const [only, ...others] = TYPES_BY_UNIT.get(intended) ?? [];
3599
+ if (only === void 0) throw new Error(`${label}: ${field} ${intended} has no TrainHeroic param type.`);
3600
+ if (others.length === 0) return only;
3601
+ throw new Error(`${label}: ${field} ${intended} matches TrainHeroic param types ${[only, ...others].join(" and ")}; set param_${slot}_type to choose one.`);
3602
+ }
3603
+ /**
3604
+ * Return a copy of `ex` with `param_1_type` and `param_2_type` set to the types the encoder
3605
+ * writes. A slot without values always gets the library default (an explicit type there is
3606
+ * ignored, and `resolveExerciseUnits` warns about it), so only a slot with values can carry a
3607
+ * type that differs from the library.
3608
+ */
3609
+ function withResolvedParamTypes(label, ex, defaults) {
3610
+ const param1 = ex.reps === void 0 ? defaults.param1 ?? 3 : resolveSlotType(label, 1, ex.primaryUnit, ex.param_1_type, defaults.param1);
3611
+ const param2 = ex.weight === void 0 ? defaults.param2 ?? 0 : resolveSlotType(label, 2, ex.secondaryUnit, ex.param_2_type, defaults.param2);
3612
+ return {
3613
+ ...ex,
3614
+ param_1_type: param1,
3615
+ param_2_type: param2
3616
+ };
3617
+ }
3618
+ /**
3619
+ * The slots (1 = primary, 2 = secondary) of a resolved exercise that hold values in a type
3620
+ * other than the library default. This is the one definition of a unit override: the advisory
3621
+ * notes describe these slots, and `buildSession` re-saves a row until TrainHeroic stores
3622
+ * exactly these types.
3623
+ */
3624
+ function overriddenSlots(ex, defaults) {
3625
+ const overridden = [];
3626
+ if (ex.reps !== void 0 && ex.param_1_type !== defaults.param1) overridden.push(1);
3627
+ if (ex.weight !== void 0 && ex.param_2_type !== defaults.param2) overridden.push(2);
3628
+ return overridden;
3629
+ }
3630
+ /** A param type's unit label for advisory text; "unset" for a slot without a type. */
3631
+ function unitName(type) {
3632
+ return unitLabel(type) ?? "unset";
3633
+ }
3634
+ /**
3635
+ * Describe how a resolved exercise's units relate to its library defaults, and flag spec
3636
+ * fields the encoder ignores. `ex` carries the resolved `param_1_type` and `param_2_type`
3637
+ * (from `resolveExerciseUnits`).
3638
+ */
3639
+ function unitAdvisory(label, ex, defaults) {
3594
3640
  const notes = [];
3595
3641
  const warnings = [];
3596
- const u = unitOr;
3597
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3642
+ const u = unitName;
3598
3643
  if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
3599
- const sentP1 = ex.param_1_type;
3600
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
3601
- const sp1 = Math.trunc(Number(sentP1));
3602
- warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
3603
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
3604
- if (ex.weight !== void 0 && ex.weight !== null) {
3605
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
3606
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
3607
- if (sentP2 !== effP2) {
3608
- if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
3609
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
3610
- }
3611
- }
3644
+ const overrides = overriddenSlots(ex, defaults);
3645
+ if (overrides.includes(1)) notes.push(`${label}: primary values are in ${u(ex.param_1_type)}, set on this session in place of the exercise's default ${u(defaults.param1)}.`);
3646
+ else if (ex.reps !== void 0 && ex.param_1_type !== 3) notes.push(`${label}: values are in ${u(ex.param_1_type)} (the exercise's default primary unit).`);
3647
+ const addedLoad = ex.param_2_type === 1 && (defaults.param2 === 0 || defaults.param2 === null);
3648
+ if (overrides.includes(2) && !addedLoad) notes.push(`${label}: secondary values are in ${u(ex.param_2_type)}, set on this session in place of the exercise's default ${u(defaults.param2)}.`);
3612
3649
  return {
3613
3650
  notes,
3614
3651
  warnings
3615
3652
  };
3616
3653
  }
3654
+ /** Warn about explicit param types on slots without values, which the encoder ignores. */
3655
+ function ignoredTypeWarnings(label, ex) {
3656
+ const warnings = [];
3657
+ if (ex.reps === void 0 && ex.param_1_type !== void 0) warnings.push(`${label}: param_1_type ${ex.param_1_type} is ignored because reps has no values; the slot keeps the exercise's default.`);
3658
+ if (ex.weight === void 0 && ex.param_2_type !== void 0) warnings.push(`${label}: param_2_type ${ex.param_2_type} is ignored because weight has no values; the slot keeps the exercise's default.`);
3659
+ return warnings;
3660
+ }
3617
3661
  /**
3618
- * Validate every populated value's stated unit against current TrainHeroic exercise data,
3619
- * then collect non-blocking advisories. The write path calls this before creating a workout;
3620
- * TrainHeroic silently replaces mismatched types.
3662
+ * Resolve every exercise's param types against current TrainHeroic exercise data and collect
3663
+ * non-blocking advisories. Throws, before anything is written, when a populated slot has no
3664
+ * stated unit, an unknown unit, or a unit that disagrees with an explicit param type. The
3665
+ * returned blocks carry the resolved `param_1_type` and `param_2_type` on every exercise.
3621
3666
  */
3622
- async function collectAdvisories(blocks, index) {
3623
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
3624
- block: b,
3625
- ex
3626
- })));
3627
- const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
3667
+ async function resolveExerciseUnits(blocks, index) {
3668
+ const ids = [...new Set(blocks.flatMap((b) => b.exercises.map((ex) => Number(ex.id))).filter(Number.isFinite))];
3628
3669
  const defaultsById = await index.currentDefaultsMany(ids);
3629
3670
  const notes = [];
3630
3671
  const warnings = [];
3631
- pairs.forEach((p) => {
3632
- const def = defaultsById.get(Number(p.ex.id));
3633
- if (!def) throw new Error(`${p.block.title} / ${p.ex.title ?? p.ex.id}: exercise id ${p.ex.id} was not found in the library.`);
3634
- validateExerciseUnits(p.block.title, p.ex, def);
3635
- const advisory = unitAdvisory(p.block.title, p.ex, def);
3636
- notes.push(...advisory.notes);
3637
- warnings.push(...advisory.warnings);
3638
- });
3639
3672
  return {
3640
- notes,
3641
- warnings
3673
+ blocks: blocks.map((block) => ({
3674
+ ...block,
3675
+ exercises: block.exercises.map((ex) => {
3676
+ const label = `${block.title} / ${ex.title ?? ex.id}`;
3677
+ const def = defaultsById.get(Number(ex.id));
3678
+ if (!def) throw new Error(`${label}: exercise id ${ex.id} was not found in the library.`);
3679
+ const typed = withResolvedParamTypes(label, ex, def);
3680
+ const advisory = unitAdvisory(label, typed, def);
3681
+ notes.push(...advisory.notes);
3682
+ warnings.push(...ignoredTypeWarnings(label, ex), ...advisory.warnings);
3683
+ return typed;
3684
+ })
3685
+ })),
3686
+ defaultsById,
3687
+ advisories: {
3688
+ notes,
3689
+ warnings
3690
+ }
3642
3691
  };
3643
3692
  }
3644
- //#endregion
3645
- //#region ../js/src/workout-session.ts
3693
+ // ../js/src/workout-session.ts
3646
3694
  const EXERCISE_SAVE_CONCURRENCY = 4;
3695
+ const SAVE_EXERCISES_PATH = "/2.0/coach/calendar/saveWorkoutSetExercises";
3696
+ /**
3697
+ * Pair each sent entry with the row TrainHeroic returned for it. A block's rows are matched on
3698
+ * `order` (unique within one block's payload) and must carry the same `exercise_id` and an id.
3699
+ * Throws when the response is not a row array or a row is missing, because the caller cannot
3700
+ * then confirm which units TrainHeroic stored.
3701
+ */
3702
+ function matchSavedRows(saves, response, pwId) {
3703
+ if (!Array.isArray(response)) throw new Error(`saveWorkoutSetExercises returned an unexpected response shape for draft session ${pwId}.`);
3704
+ const rows = response.filter((row) => typeof row === "object" && row !== null);
3705
+ return saves.map((save) => {
3706
+ const row = rows.find((r) => coerceInt(r.order) === coerceInt(save.entry.order) && coerceInt(r.exercise_id) === coerceInt(save.entry.exercise_id));
3707
+ const id = coerceInt(row?.id);
3708
+ if (row === void 0 || id === null) throw new Error(`saveWorkoutSetExercises returned no row for exercise ${String(save.entry.exercise_id)} (order ${String(save.entry.order)}) on draft session ${pwId}.`);
3709
+ return {
3710
+ save,
3711
+ row,
3712
+ id
3713
+ };
3714
+ });
3715
+ }
3716
+ /** True when the stored row holds the requested type in every overridden slot. */
3717
+ function keepsOverrides(save, row) {
3718
+ return save.overrides.every((slot) => coerceInt(row[`param_${slot}_type`]) === coerceInt(save.entry[`param_${slot}_type`]));
3719
+ }
3720
+ /**
3721
+ * Save one block's exercises. TrainHeroic stores a newly inserted row with the exercise's
3722
+ * library param types whatever the request says, and keeps the requested types when the same
3723
+ * row is saved again with its `id`; the coach web app's unit picker saves single rows by id
3724
+ * the same way. So each row with an overridden slot (say %max load on a pounds lift) that the
3725
+ * insert stored in the library type is saved a second time by id. Throws when the second save
3726
+ * still does not hold the requested types, because the values would render in the wrong unit.
3727
+ */
3728
+ async function saveBlockExercises(client, pwId, saves) {
3729
+ const corrections = matchSavedRows(saves, await req(client, "POST", SAVE_EXERCISES_PATH, saves.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row)).map(({ save, id }) => ({
3730
+ entry: {
3731
+ ...save.entry,
3732
+ id
3733
+ },
3734
+ overrides: save.overrides
3735
+ }));
3736
+ if (corrections.length === 0) return;
3737
+ const unkept = matchSavedRows(corrections, await req(client, "POST", SAVE_EXERCISES_PATH, corrections.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row));
3738
+ if (unkept.length > 0) {
3739
+ const names = unkept.map(({ save, row }) => typeof row.title === "string" && row.title !== "" ? row.title : `exercise ${String(save.entry.exercise_id)}`).join(", ");
3740
+ throw new Error(`TrainHeroic did not keep the requested units for ${names} on draft session ${pwId}. Remove the draft or correct those exercises in the coach app.`);
3741
+ }
3742
+ }
3647
3743
  /**
3648
3744
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
3649
3745
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -3672,8 +3768,9 @@ async function buildSession(client, opts) {
3672
3768
  const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
3673
3769
  const splitSummary = setSplitSummary(validatedBlocks);
3674
3770
  if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
3675
- const advisories = await collectAdvisories(validatedBlocks, opts.index);
3676
- const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
3771
+ const resolved = await resolveExerciseUnits(validatedBlocks, opts.index);
3772
+ const advisories = resolved.advisories;
3773
+ const blocks = splitSummary === null ? resolved.blocks : splitOversizedBlocks(resolved.blocks);
3677
3774
  const sess = await req(client, "POST", createPath(opts), {});
3678
3775
  checkResponse(sessionCreateResponseSchema, sess, "session create");
3679
3776
  const workoutId = Number(sess.workout_id);
@@ -3686,9 +3783,13 @@ async function buildSession(client, opts) {
3686
3783
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
3687
3784
  return block.exercises.map((ex, j) => {
3688
3785
  counter += 1;
3689
- return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
3786
+ const defaults = resolved.defaultsById.get(Number(ex.id));
3787
+ return {
3788
+ entry: makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`),
3789
+ overrides: defaults === void 0 ? [] : overriddenSlots(ex, defaults)
3790
+ };
3690
3791
  });
3691
- }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (payload) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", payload));
3792
+ }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (saves) => saveBlockExercises(client, pwId, saves));
3692
3793
  if (opts.instruction !== void 0 && opts.instruction !== "") {
3693
3794
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
3694
3795
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -3737,6 +3838,7 @@ async function readSession(client, programId, date, pwId) {
3737
3838
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
3738
3839
  return {
3739
3840
  pwId,
3841
+ workoutId: coerceInt(pw.workout_id),
3740
3842
  date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
3741
3843
  published: pw.published,
3742
3844
  instruction: str(pw.instruction),
@@ -4158,9 +4260,26 @@ async function requestAnalytics(client, args) {
4158
4260
  body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
4159
4261
  }
4160
4262
  const res = await client.request("POST", spec.path, { body });
4161
- if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
4263
+ if (!res.ok) {
4264
+ const message = trainHeroicApiErrorMessage(`Analytics ${args.metric}`, res.status, res.data);
4265
+ throw new Error(withHint(message, analyticsErrorHint(res.data)));
4266
+ }
4162
4267
  return res.data;
4163
4268
  }
4269
+ /**
4270
+ * Explain TrainHeroic's terse analytics rejections so the caller can fix its input.
4271
+ * lift-1rm-history answers "Invalid exercise id" for any exercise that is not a weighted lift
4272
+ * (verified with Run, Push-Up, and an unknown id; Back Squat succeeds).
4273
+ */
4274
+ function analyticsErrorHint(responseBody) {
4275
+ if (typeof responseBody === "string" && responseBody.includes("Invalid exercise id")) return "exerciseId must be a weighted lift such as Back Squat (id 1); bodyweight, distance, and unknown exercises are rejected.";
4276
+ return null;
4277
+ }
4278
+ /** Append a sentence of guidance to an error message that may or may not end in a period. */
4279
+ function withHint(message, hint) {
4280
+ if (hint === null) return message;
4281
+ return `${message.endsWith(".") ? message : `${message}.`} ${hint}`;
4282
+ }
4164
4283
  function reportRows(report) {
4165
4284
  if (report === null || typeof report !== "object") return null;
4166
4285
  const rows = report.rows;
@@ -4300,10 +4419,31 @@ async function createSessionTemplate(client, args) {
4300
4419
  if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
4301
4420
  return res.data;
4302
4421
  }
4422
+ /**
4423
+ * Copy an existing calendar session, with its blocks and exercises, into the coach's session
4424
+ * library as a new template
4425
+ * (`POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`). The path takes
4426
+ * the session's workout id and the body's `id` takes its programWorkout id (pwId), which is what
4427
+ * the coach web app sends. TrainHeroic answers HTTP 500 when the body is missing, when the body
4428
+ * has no `id`, or when the two ids are swapped.
4429
+ */
4430
+ async function saveSessionAsTemplate(client, args) {
4431
+ const title = args.title.trim();
4432
+ if (title === "") throw new Error("Session template title must not be blank.");
4433
+ const res = await client.request("POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${args.workoutId}`, { body: {
4434
+ id: args.pwId,
4435
+ title
4436
+ } });
4437
+ if (!res.ok) {
4438
+ const message = trainHeroicApiErrorMessage(`Saving session ${args.pwId} (workout ${args.workoutId}) as a template`, res.status, res.data);
4439
+ throw new Error(withHint(message, "Check that workoutId and pwId belong to the same session; a session read-back returns both."));
4440
+ }
4441
+ if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template save response is missing an id.");
4442
+ return res.data;
4443
+ }
4303
4444
  /** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
4304
4445
  const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
4305
- //#endregion
4306
- //#region ../js/src/main-lifts.ts
4446
+ // ../js/src/main-lifts.ts
4307
4447
  /**
4308
4448
  * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
4309
4449
  * first family that matches, so the more specific / easily-confused families come before the broad
@@ -4515,8 +4655,7 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
4515
4655
  };
4516
4656
  });
4517
4657
  }
4518
- //#endregion
4519
- //#region ../js/src/messaging.ts
4658
+ // ../js/src/messaging.ts
4520
4659
  const BUCKETS = [
4521
4660
  ["team", "teams"],
4522
4661
  ["athlete", "athletes"],
@@ -4571,8 +4710,7 @@ async function readLive(client, streamId, limit, afterCommentId) {
4571
4710
  if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
4572
4711
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
4573
4712
  }
4574
- //#endregion
4575
- //#region ../js/src/library-cache.ts
4713
+ // ../js/src/library-cache.ts
4576
4714
  /** In-memory cache (no persistence). The default when none is supplied. */
4577
4715
  var MemoryLibraryCache = class {
4578
4716
  #snapshot = null;
@@ -4583,8 +4721,7 @@ var MemoryLibraryCache = class {
4583
4721
  this.#snapshot = snapshot;
4584
4722
  }
4585
4723
  };
4586
- //#endregion
4587
- //#region ../js/src/exercise-index.ts
4724
+ // ../js/src/exercise-index.ts
4588
4725
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
4589
4726
  const CREATE_PATH = "/2.0/coach/exercise/create";
4590
4727
  const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
@@ -4790,8 +4927,7 @@ var ExerciseLibrary = class {
4790
4927
  };
4791
4928
  }
4792
4929
  };
4793
- //#endregion
4794
- //#region ../js/src/node.ts
4930
+ // ../js/src/node.ts
4795
4931
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
4796
4932
  function defaultCachePath() {
4797
4933
  return process.env.TRAINHEROIC_CACHE_FILE ?? join(homedir(), ".trainheroic", "library.json");
@@ -4814,8 +4950,7 @@ var JsonFileLibraryCache = class {
4814
4950
  await writeFile(this.#path, JSON.stringify(snapshot), { mode: 384 });
4815
4951
  }
4816
4952
  };
4817
- //#endregion
4818
- //#region src/parse.ts
4953
+ // src/parse.ts
4819
4954
  /** True when a string looks like inline JSON (starts with { or [) rather than a path. */
4820
4955
  function looksLikeJson(s) {
4821
4956
  return /^\s*[[{]/u.test(s);
@@ -4844,8 +4979,7 @@ function parseCountArg(value, label) {
4844
4979
  function parseIdList(value, label) {
4845
4980
  return value.split(",").map((s) => parseIntArg(s, label));
4846
4981
  }
4847
- //#endregion
4848
- //#region src/session-cache.ts
4982
+ // src/session-cache.ts
4849
4983
  const TTL_MS = 216e5;
4850
4984
  function sessionPath() {
4851
4985
  return process.env.TRAINHEROIC_SESSION_FILE ?? join(homedir(), ".trainheroic", "session.json");
@@ -4866,8 +5000,7 @@ async function saveSession(sessionId) {
4866
5000
  savedAt: Date.now()
4867
5001
  }), { mode: 384 });
4868
5002
  }
4869
- //#endregion
4870
- //#region src/cli.ts
5003
+ // src/cli.ts
4871
5004
  const HELP = `trainheroic — command-line tool for the TrainHeroic API
4872
5005
 
4873
5006
  Credentials come from TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD. Output is JSON.
@@ -4940,7 +5073,7 @@ Coach — manage a roster (needs a coach account):
4940
5073
  session lifecycle:
4941
5074
  coach session-copy --to-program <id> --pw <id> --to-date Y-M-D
4942
5075
  coach session-unpublish --pw <id> --yes
4943
- coach session-save-template --workout <id>
5076
+ coach session-save-template --workout <id> --pw <id> --title "..."
4944
5077
  coach session-templates
4945
5078
  coach session-template-create --title "..." [--instruction "..."]
4946
5079
  coach session-template-delete --id <id> --yes
@@ -5944,9 +6077,17 @@ async function cmdCoachSessionUnpublish(client, a) {
5944
6077
  return out(await mutate(client, "POST", `/2.0/coach/calendar/programWorkout/unPublish/${pwId}`));
5945
6078
  }
5946
6079
  async function cmdCoachSessionSaveTemplate(client, a) {
5947
- const usage = "coach session-save-template --workout <id>";
5948
- const { values } = parse(a, { workout: { type: "string" } });
5949
- return out(await mutate(client, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${toInt(need(values.workout, usage), "--workout")}`));
6080
+ const usage = "coach session-save-template --workout <id> --pw <id> --title \"...\"";
6081
+ const { values } = parse(a, {
6082
+ workout: { type: "string" },
6083
+ pw: { type: "string" },
6084
+ title: { type: "string" }
6085
+ });
6086
+ return out(await saveSessionAsTemplate(client, {
6087
+ workoutId: toInt(need(values.workout, usage), "--workout"),
6088
+ pwId: toInt(need(values.pw, usage), "--pw"),
6089
+ title: need(values.title, usage)
6090
+ }));
5950
6091
  }
5951
6092
  async function cmdCoachSessionTemplateCreate(client, a) {
5952
6093
  const usage = "coach session-template-create --title \"...\" [--instruction \"...\"]";
@@ -6177,5 +6318,4 @@ async function main() {
6177
6318
  }
6178
6319
  }
6179
6320
  await main();
6180
- //#endregion
6181
6321
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,16 +20,16 @@
20
20
  "skill"
21
21
  ],
22
22
  "dependencies": {
23
- "zod": "^4.6.5",
24
- "@trainheroic-unofficial/dto": "4.2.0",
25
- "@trainheroic-unofficial/js": "4.2.0"
23
+ "zod": "^4.6.7",
24
+ "@trainheroic-unofficial/dto": "4.3.0",
25
+ "@trainheroic-unofficial/js": "4.3.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.6.4",
29
- "tsdown": "^0.23.0",
28
+ "@types/node": "^26.6.6",
29
+ "tsdown": "^0.23.7",
30
30
  "tsx": "^4.23.15",
31
31
  "typescript": "^7.0.2",
32
- "vitest": "^5.0.3"
32
+ "vitest": "^5.1.0"
33
33
  },
34
34
  "scripts": {
35
35
  "start": "tsx src/cli.ts",
@@ -210,8 +210,9 @@ $TH athlete exercise-note --set-exercise 2712369448 --notes "green band" --yes
210
210
 
211
211
  - `profile` must send `use_metric` and `stats` must send `date`, or the API returns 400.
212
212
  The CLI fills `use_metric` (toggle with `--metric`); pass `--date` to `stats`.
213
- - Units are **fixed per exercise** and surfaced positionally as `[param 1, param 2]` (e.g.
214
- `["reps", "lb"]`). They are not labelled by role: some exercises reverse the slots.
213
+ - Each exercise has **default units**, surfaced positionally as `[param 1, param 2]` (e.g.
214
+ `["reps", "lb"]`). They are not labelled by role: some exercises reverse the slots. A coach
215
+ can set other units on one session, such as % of max on Back Squat.
215
216
  - `log-set`, `workout-note`, and `exercise-note` write to your coach-visible log. Gate them
216
217
  behind explicit user confirmation, never run them autonomously, and verify the result.
217
218
  `log-set`'s request shape was reverse-engineered from the mobile app (a two-step write:
@@ -238,17 +238,17 @@ Environment-specific facts that defy reasonable assumptions:
238
238
  repeated. `{"content": "..."}` returns `400 Invalid parameters`; so does trimming any
239
239
  field. The CLI sends the full body. There is **no draft state**: a POST is delivered
240
240
  immediately, so gate sends behind explicit user confirmation (`--yes`).
241
- - **Units are fixed per exercise — you can't set them at prescribe time.** On save the API
242
- discards the `param_1_type`/`param_2_type` you send and restores the exercise's library
243
- defaults (the _values_ are kept). So the stock `Run` (miles) can't be made metric; a
244
- "200 m run" on it shows as 200 _miles_. And `param_2_type` `2` (% of max) and `14` (RPE)
245
- coerce to weight on a weight lift, rendering as pounds — put % or RPE in the
246
- `instruction` (the builder does this from `rpe`). You _can_ add weight (`1`) to a
247
- no-secondary-param lift (weighted Pull-Ups). Check units with `$TH coach exercise resolve`
248
- (the `units` array, ordered by entry slot `[param 1, param 2]`). Include
249
- `primaryUnit` with every `reps` value and `secondaryUnit` with every `weight` value;
250
- these fields name the intended unit for each positional slot. The builder rejects
251
- mismatches before creating a draft. "Max"/"AMRAP" reps work as free text in the
241
+ - **Each exercise has default units, and a session can override them.** An insert through
242
+ `saveWorkoutSetExercises` stores the exercise's library `param_1_type`/`param_2_type`
243
+ whatever you send (the _values_ are kept). Saving the same row again with its `id` keeps the
244
+ types you send, which is how the coach app's unit picker sets Weight (%) on any lift. The
245
+ builder does both saves for you. `$TH coach exercise resolve` shows the default units (the
246
+ `units` array, ordered by entry slot `[param 1, param 2]`). Include `primaryUnit` with
247
+ every `reps` value and `secondaryUnit` with every `weight` value. A unit other than the
248
+ default is set on that session: `"secondaryUnit": "%max"` prescribes % of max on Back
249
+ Squat, `"RPE"` prescribes RPE as load, and `"primaryUnit": "m"` makes the stock `Run`
250
+ (miles) metric. `sec` and `in` each name two TrainHeroic types, so pair them with
251
+ `param_N_type` when they are not the default. "Max"/"AMRAP" reps work as free text in the
252
252
  rep slots.
253
253
  - **`saveWorkoutSetExercises` returns HTTP 500** unless every field is present: all ten
254
254
  `param_1_data_N`/`param_2_data_N` slots (empty string for unused), `set_num`, `key`,
@@ -260,8 +260,8 @@ Environment-specific facts that defy reasonable assumptions:
260
260
  - **A created session exposes two IDs**: `workout_id` (for adding blocks) and `id` (the
261
261
  programWorkout id, used to publish and to delete; the CLI calls it `pw`).
262
262
  - **The API ignores the exercise `title` you send** and uses the real title for
263
- `exercise_id`; it also overrides both `param_1_type` and `param_2_type` to the exercise
264
- default (see the units gotcha above).
263
+ `exercise_id`; an insert also stores the exercise's default `param_1_type` and
264
+ `param_2_type` until the row is saved again by id (see the units gotcha above).
265
265
  - **Response envelopes vary.** `2.0/coach/*` tag/exercise endpoints wrap data as
266
266
  `{"success": 1, "data": {...}}`; most others return bare objects/arrays.
267
267
  - **This API is undocumented and can change.** `references/api-reference.md` has a "Still
@@ -564,25 +564,21 @@ This creates A1: Back Squat, A2: Front Squat displayed as a superset.
564
564
  | 14 | RPE | rating |
565
565
  | 18 | Time (seconds, alt) | `0:30` |
566
566
 
567
- > **The unit is fixed per exercise — you cannot set it at prescribe time (verified).**
568
- > On save the API discards the `param_1_type`/`param_2_type` you send and restores
569
- > the exercise's library defaults. The `param_*_data_N` _values_ are kept, so a
570
- > value sent under the wrong assumed unit renders under the exercise's real unit.
567
+ > **Insert stores the exercise's default units; a save by id overrides them (verified).**
568
+ > Inserting a row (no `id`) through `saveWorkoutSetExercises` discards the
569
+ > `param_1_type`/`param_2_type` you send and stores the exercise's library defaults. The
570
+ > `param_*_data_N` _values_ are kept, so a value sent under another unit renders under the
571
+ > default unit. Posting the same row again with the `id` the insert returned keeps the
572
+ > types you send. The coach web app works this way: it inserts the exercise, then saves the
573
+ > row again when the coach picks a unit such as Weight (%).
571
574
  >
572
- > - **`param_1_type` (primary) is always forced to the exercise default.** e.g. stock
573
- > `Run` (id 82) is `10` (miles); sending `6` (meters) is ignored and `200` shows as
574
- > _200 miles_. To program meters, pick a meters-native exercise (`Sprint` 127,
575
- > `Rowing` 101, `Shuttle Sprint` 42523) or a custom exercise — there is no metric
576
- > "Run". `$TH coach exercise resolve` now prints a `units` array (ordered by entry slot,
577
- > `[param 1, param 2]`); check it.
578
- > - **`param_2_type` (secondary) is forced to the default too, with one exception:**
579
- > if the exercise has no secondary param (default `0`/none) you may add weight
580
- > (`1`) — this is how weighted Pull-Ups/Dips work. You cannot swap an exercise's
581
- > existing secondary unit, and **`2` (% of max) and `14` (RPE) never stick on a
582
- > weight-default lift — both coerce to weight, so the numbers render as pounds.**
583
- > Put % or RPE in the `instruction` text instead.
584
- > - the workout builder reads the local exercise cache and prints a `WARNING` when a
585
- > sent param type will be overridden.
575
+ > - Verified on 2026-11-14: stock `Back Squat` (id 1, default `3`/`1`) keeps `2` (% of max)
576
+ > and `14` (RPE) in `param_2_type`, and stock `Run` (id 82, default `10` miles) keeps `6`
577
+ > (meters) in `param_1_type`, after the save by id.
578
+ > - `$TH coach exercise resolve` prints a `units` array (ordered by entry slot,
579
+ > `[param 1, param 2]`) with the defaults.
580
+ > - The workout builder maps each stated `primaryUnit`/`secondaryUnit` to a type and does
581
+ > the second save for every row whose stored types differ from the requested ones.
586
582
 
587
583
  **Common param type combos (from 2067 exercises):**
588
584
 
@@ -604,7 +600,7 @@ This creates A1: Back Squat, A2: Front Squat displayed as a superset.
604
600
  - `no_sets` = 0 (normal), non-zero may indicate special handling
605
601
  - `instruction` = Per-exercise coach notes
606
602
 
607
- **Note:** The API ignores the `title` field and uses the exercise's real title from `exercise_id`. It also overrides **both** `param_1_type` and `param_2_type` to the exercise's library defaults (see the fixed-unit note above) — the data values you send are kept, but the unit is the exercise's, not the one you requested.
603
+ **Note:** The API ignores the `title` field and uses the exercise's real title from `exercise_id`. An insert also stores the exercise's library `param_1_type` and `param_2_type`; save the row again with its `id` to keep other types (see the units note above).
608
604
 
609
605
  #### Step 5: Publish Session
610
606
 
@@ -1332,7 +1328,17 @@ causes this legacy endpoint to return HTTP 500.
1332
1328
 
1333
1329
  #### `POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`
1334
1330
 
1335
- Saves an existing session as a reusable template in the session library. No request body needed — uses the workout ID in the URL path.
1331
+ Copies an existing session, with its blocks and exercises, into the session library as a new
1332
+ template. The path takes the session's `workout_id`, and the body takes the session's
1333
+ programWorkout id (pwId) as `id`, plus the template `title`:
1334
+
1335
+ ```json
1336
+ { "id": 163487882, "title": "Lower body A" }
1337
+ ```
1338
+
1339
+ Verified 2026-11-14: a missing body, a body without `id`, and swapped ids (pwId in the path)
1340
+ all return HTTP 500. Without `title` the template is saved untitled. The coach web app sends
1341
+ the whole programWorkout object as the body; `id` is the only field TrainHeroic needs.
1336
1342
 
1337
1343
  ---
1338
1344
 
@@ -13,10 +13,10 @@ All calls use the coach base (`https://api.trainheroic.com`) with the
13
13
  > correctly. Reach for the manual steps below only when debugging or doing
14
14
  > something the builder does not cover.
15
15
  >
16
- > **RPE rule (verified the hard way):** never prescribe RPE as a structured param.
17
- > `param_2_type: 14` is silently overridden to weight on any lift whose library
18
- > default param is weight, so the RPE values render as pounds. Put RPE in the
19
- > exercise `instruction` ("RPE 8"), prescribe reps, and leave load blank.
16
+ > **Units rule:** an insert stores the exercise's library param types, so RPE
17
+ > (`param_2_type: 14`) or % of max (`2`) on a pounds lift renders as pounds until the
18
+ > row is saved again with its `id`. The builder does that second save; in manual calls,
19
+ > repeat the `saveWorkoutSetExercises` POST with the returned row `id`.
20
20
 
21
21
  ## Step 1 — Get a program/calendar to write to
22
22
 
@@ -144,7 +144,9 @@ Fields that cause a 500 when missing:
144
144
  - `workout_set_exercise_template_id` — `null`
145
145
 
146
146
  The API ignores the `title` you send and substitutes the real title for
147
- `exercise_id`. It may also override `param_2_type` from the exercise's defaults.
147
+ `exercise_id`. An insert also stores the exercise's default `param_1_type` and
148
+ `param_2_type`. To keep other types, POST the same entry again with the `id` from the
149
+ insert response.
148
150
 
149
151
  ## Step 5 — Publish
150
152
 
@@ -215,25 +217,23 @@ Most common combos: `p1=3,p2=1` (reps @ weight, e.g. Back Squat), `p1=3,p2=0`
215
217
  `param_1_data_N` is the value for param 1 in set N; `param_2_data_N` likewise for
216
218
  param 2. `param_count` is the number of sets (max 10).
217
219
 
218
- ### The unit is fixed per exercise (verified)
219
-
220
- On save the API **discards the `param_1_type`/`param_2_type` you send and restores
221
- the exercise's library defaults.** Your `param_*_data_N` values are kept, so a value
222
- sent under the wrong assumed unit silently renders under the exercise's real unit.
223
-
224
- - **`param_1_type` (primary): always forced to the exercise default.** You cannot
225
- change the primary unit at prescribe time. Stock `Run` (id 82) is miles, so a
226
- "200 m run" written on `Run` renders as _200 miles_. For meters use a meters-native
227
- exercise (`Sprint` 127, `Rowing` 101, `Shuttle Sprint` 42523) or a custom exercise.
228
- - **`param_2_type` (secondary): forced to the default too, except** you may add weight
229
- (`1`) to an exercise that has no secondary param (default `0`/none) — that is how
230
- weighted Pull-Ups/Dips work. `2` (% of max) and `14` (RPE) do **not** stick on a
231
- weight-default lift; both coerce to weight and render as pounds.
232
- - Check an exercise's real units first: `$TH coach exercise resolve "<name>"` prints a
233
- `units` array, ordered by entry slot (`[param 1, param 2]`). In the workout spec,
234
- include `primaryUnit` when `reps` contains a value and `secondaryUnit` when `weight`
235
- contains a value. The builder checks both units before creating a draft, and its
236
- read-back labels the stored units.
220
+ ### Default units and session overrides (verified)
221
+
222
+ An insert (an entry without `id`) **stores the exercise's library `param_1_type`/`param_2_type`
223
+ whatever you send.** Your `param_*_data_N` values are kept, so a value sent under another unit
224
+ renders under the default unit. Posting the same entry again with the row `id` from the insert
225
+ response keeps the types you send. The coach web app's unit picker (for example Weight (%))
226
+ uses this second save.
227
+
228
+ - Verified live on 2026-11-14: stock `Back Squat` (id 1) keeps `param_2_type` `2` (% of max)
229
+ and `14` (RPE), and stock `Run` (id 82, miles) keeps `param_1_type` `6` (meters).
230
+ - Check an exercise's default units with `$TH coach exercise resolve "<name>"`, which prints a
231
+ `units` array ordered by entry slot (`[param 1, param 2]`).
232
+ - In the workout spec, include `primaryUnit` when `reps` contains a value and `secondaryUnit`
233
+ when `weight` contains a value. The builder keeps the default when it has the stated unit,
234
+ maps any other unit to its own type, and does the second save. `sec` and `in` each name two
235
+ types, so set `param_N_type` with them when they differ from the default. The read-back
236
+ labels the stored units.
237
237
 
238
238
  ## Prescription patterns
239
239
 
@@ -245,18 +245,18 @@ sent under the wrong assumed unit silently renders under the exercise's real uni
245
245
  (e.g. reps `5,3,1,3,5` at weight `185,225,275,225,185`).
246
246
  - **Bodyweight**: `param_2_type: 0` and leave every `param_2_data_N` empty.
247
247
  - **Weighted bodyweight** (weighted Pull-Up/Dip): add `param_2_type: 1` with loads.
248
- Adding weight sticks _only_ on exercises whose default secondary is none (`0`).
248
+ An insert keeps the added weight only when the exercise's default secondary is none
249
+ (`0`); for any other default, save the row again by `id` (the builder does this).
249
250
  - **Max / AMRAP reps (verified)**: the rep slots are free text — put the literal
250
251
  string `"Max"` (or `"AMRAP"`, `"ME"`) in `param_1_data_N`; it round-trips verbatim
251
252
  and you can mix it with numbers (e.g. last set `"Max"`). The builder accepts
252
253
  `"reps": ["Max", "Max"]` or `"reps": [5, 5, "Max"]`.
253
- - **RPE and % of max (verified caveat)**: `param_2_type: 14` (RPE) and `2` (% of max)
254
- do **not** stick on exercises whose library default param is weight — the API
255
- overrides them back to weight, so the numbers render as pounds. Reliable approach:
256
- prescribe reps with `param_2_type: 0` (load left blank for athlete autoregulation)
257
- and put the target in the exercise `instruction` (e.g. `"RPE 8"` or `"75% of max"`).
258
- The `instruction` field round-trips intact. (This is one case of the fixed-unit
259
- rule above.)
254
+ - **RPE and % of max (verified)**: with the builder, put the values in `weight` and set
255
+ `"secondaryUnit": "%max"` or `"secondaryUnit": "RPE"`; this works on built-in pounds
256
+ lifts such as Back Squat. In manual calls, the insert stores pounds, so repeat the
257
+ `saveWorkoutSetExercises` POST with the row `id` and `param_2_type` `2` or `14` (see the
258
+ units section above). The builder's `rpe` field instead writes `"RPE 8"` into the exercise
259
+ `instruction`, which round-trips intact.
260
260
 
261
261
  ## Common exercise IDs
262
262
 
@@ -309,3 +309,4 @@ athlete's round count (e.g. ~5–6 rounds for a ~10–12 min triplet) and confir
309
309
  - Delete: `POST /2.0/coach/calendar/removeProgramWorkout` `{ "programId", "pwId" }`
310
310
  - Copy/repeat to a date: `POST /2.0/coach/calendar/copyProgramWorkout`
311
311
  - Save as template: `POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`
312
+ with body `{ "id": <pwId>, "title": "..." }` (`$TH coach session-save-template`)