@trainheroic-unofficial/cli 4.1.1 → 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;
@@ -1063,6 +1062,28 @@ var TrainHeroicHttpError = class extends Error {
1063
1062
  this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
1064
1063
  }
1065
1064
  };
1065
+ /**
1066
+ * True for statuses that mean TrainHeroic's servers could not be reached or did not answer: a
1067
+ * gateway failure (502, 503, 504) or a Cloudflare edge error (520-530). TrainHeroic sits behind
1068
+ * Cloudflare, so a 522 means the edge timed out connecting to TrainHeroic's origin. These describe
1069
+ * an upstream outage, so the same request can succeed when retried later.
1070
+ */
1071
+ function isTrainHeroicUnavailableStatus(status) {
1072
+ return status === 502 || status === 503 || status === 504 || status >= 520 && status <= 530;
1073
+ }
1074
+ /**
1075
+ * Thrown when TrainHeroic answers with an outage status (see `isTrainHeroicUnavailableStatus`).
1076
+ * The message tells the reader to retry later, so a model relaying it does not ask the user to
1077
+ * re-check credentials that are fine.
1078
+ */
1079
+ var TrainHeroicUnavailableError = class extends Error {
1080
+ name = "TrainHeroicUnavailableError";
1081
+ status;
1082
+ constructor(status) {
1083
+ super(`TrainHeroic is not responding right now (HTTP ${status}). Try again in a few minutes.`);
1084
+ this.status = status;
1085
+ }
1086
+ };
1066
1087
  /** Call observability hooks without allowing them to change SDK behavior. */
1067
1088
  function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1068
1089
  if (!handler) return;
@@ -1070,11 +1091,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1070
1091
  Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
1071
1092
  } catch {}
1072
1093
  }
1073
- //#endregion
1074
- //#region ../js/src/transport.ts
1094
+ // ../js/src/transport.ts
1075
1095
  const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
1076
- //#endregion
1077
- //#region ../js/src/auth.ts
1096
+ // ../js/src/auth.ts
1078
1097
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
1079
1098
  /**
1080
1099
  * The login endpoint, allowing an env override so a test harness can authenticate against a local
@@ -1090,8 +1109,10 @@ function authUrl() {
1090
1109
  return DEFAULT_AUTH_URL;
1091
1110
  }
1092
1111
  /**
1093
- * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
1094
- * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
1112
+ * Authenticate against TrainHeroic. Returns the session bundle, or null when TrainHeroic
1113
+ * rejects the login. Throws `TrainHeroicUnavailableError` when TrainHeroic is unreachable (an
1114
+ * outage status such as a Cloudflare 522), so callers can tell the user to retry later.
1115
+ * TrainHeroic returns only { id, scope, role, session_id } (verified in
1095
1116
  * the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
1096
1117
  * is sent as the `session-token` header and works against both API hosts.
1097
1118
  */
@@ -1111,6 +1132,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1111
1132
  if (!res.ok) {
1112
1133
  await res.body?.cancel().catch(() => {});
1113
1134
  notifyHttpError(options.onHttpError, "POST", url, res.status);
1135
+ if (isTrainHeroicUnavailableStatus(res.status)) throw new TrainHeroicUnavailableError(res.status);
1114
1136
  return null;
1115
1137
  }
1116
1138
  const data = await res.json().catch(() => null);
@@ -1122,8 +1144,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1122
1144
  role: data.role ?? ""
1123
1145
  };
1124
1146
  }
1125
- //#endregion
1126
- //#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
1127
1148
  /**
1128
1149
  * Splits an array into smaller arrays of a specified length.
1129
1150
  *
@@ -1158,8 +1179,7 @@ function chunk(arr, size) {
1158
1179
  }
1159
1180
  return result;
1160
1181
  }
1161
- //#endregion
1162
- //#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
1163
1183
  /**
1164
1184
  * Creates a duplicate-free version of an array.
1165
1185
  *
@@ -1178,13 +1198,12 @@ function chunk(arr, size) {
1178
1198
  function uniq(arr) {
1179
1199
  return [...new Set(arr)];
1180
1200
  }
1181
- //#endregion
1182
- //#region ../js/src/exercise-util.ts
1201
+ // ../js/src/exercise-util.ts
1183
1202
  /**
1184
- * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
1185
- * (the API forces param_1_type/param_2_type back to the library default on save), so
1186
- * resolve/search surface it to stop callers picking, say, the miles "Run" for a
1187
- * 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.
1188
1207
  */
1189
1208
  const PARAM_UNIT = {
1190
1209
  0: null,
@@ -1225,7 +1244,7 @@ function unitLabel(paramType) {
1225
1244
  return PARAM_UNIT[t] ?? null;
1226
1245
  }
1227
1246
  /**
1228
- * 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).
1229
1248
  * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
1230
1249
  * by role. A null entry is an unset slot.
1231
1250
  */
@@ -1422,8 +1441,7 @@ function createLimiter(max) {
1422
1441
  function assertPositiveInteger(value, label) {
1423
1442
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1424
1443
  }
1425
- //#endregion
1426
- //#region ../js/src/client.ts
1444
+ // ../js/src/client.ts
1427
1445
  const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
1428
1446
  const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
1429
1447
  const MAX_REQUEST_CONCURRENCY = 4;
@@ -1543,8 +1561,7 @@ var TrainHeroicClient = class {
1543
1561
  return this.#transport(url, init);
1544
1562
  }
1545
1563
  };
1546
- //#endregion
1547
- //#region ../js/src/response-check.ts
1564
+ // ../js/src/response-check.ts
1548
1565
  /**
1549
1566
  * Validate an API response against its (loose) expected shape and warn once on drift.
1550
1567
  * Never throws: callers keep working via defensive coercion. This only surfaces a signal
@@ -1557,8 +1574,7 @@ function checkResponse(schema, data, label) {
1557
1574
  const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
1558
1575
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1559
1576
  }
1560
- //#endregion
1561
- //#region ../js/src/athlete.ts
1577
+ // ../js/src/athlete.ts
1562
1578
  async function getJson(client, path, label) {
1563
1579
  const res = await client.request("GET", path);
1564
1580
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2294,8 +2310,7 @@ function presentExerciseHistory(detail) {
2294
2310
  }))
2295
2311
  };
2296
2312
  }
2297
- //#endregion
2298
- //#region ../js/src/exercise-history.ts
2313
+ // ../js/src/exercise-history.ts
2299
2314
  /**
2300
2315
  * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
2301
2316
  * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
@@ -2316,8 +2331,7 @@ function historyInRange(presented, since, until) {
2316
2331
  sessions
2317
2332
  };
2318
2333
  }
2319
- //#endregion
2320
- //#region ../js/src/coach-athlete-calendar.ts
2334
+ // ../js/src/coach-athlete-calendar.ts
2321
2335
  async function getArray(client, path, label) {
2322
2336
  const res = await client.request("GET", path);
2323
2337
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -2332,14 +2346,34 @@ async function getArray(client, path, label) {
2332
2346
  function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
2333
2347
  return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
2334
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
+ };
2335
2358
  /**
2336
2359
  * A coach's month view of a roster athlete's logged sessions
2337
2360
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
2338
2361
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
2339
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.
2340
2366
  */
2341
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
2342
- 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);
2343
2377
  }
2344
2378
  /**
2345
2379
  * Resolve a roster athlete's coach-writable calendar program id
@@ -2380,8 +2414,7 @@ async function resolveBuildProgramId(client, args) {
2380
2414
  const [y, m] = parseWorkoutDate(args.date);
2381
2415
  return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
2382
2416
  }
2383
- //#endregion
2384
- //#region ../js/src/exercise-set-payload.ts
2417
+ // ../js/src/exercise-set-payload.ts
2385
2418
  function slotData(exercise, key) {
2386
2419
  const value = exercise?.[key];
2387
2420
  return value === void 0 || value === null ? "" : String(value);
@@ -2449,8 +2482,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
2449
2482
  body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
2450
2483
  return body;
2451
2484
  }
2452
- //#endregion
2453
- //#region ../js/src/athlete-set-write.ts
2485
+ // ../js/src/athlete-set-write.ts
2454
2486
  const WRITE_CONCURRENCY = 4;
2455
2487
  /**
2456
2488
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
@@ -3082,8 +3114,7 @@ async function logSessionForAthlete(client, args) {
3082
3114
  sets
3083
3115
  };
3084
3116
  }
3085
- //#endregion
3086
- //#region ../js/src/util.ts
3117
+ // ../js/src/util.ts
3087
3118
  /**
3088
3119
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
3089
3120
  * spread into an object under `exactOptionalPropertyTypes` without the per-key
@@ -3098,8 +3129,7 @@ function definedProps(obj) {
3098
3129
  for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
3099
3130
  return result;
3100
3131
  }
3101
- //#endregion
3102
- //#region ../js/src/athlete-workout-note.ts
3132
+ // ../js/src/athlete-workout-note.ts
3103
3133
  /**
3104
3134
  * PUT /1.0/athlete/savedworkout/{id} — set the athlete's session note (the free-text box on the
3105
3135
  * workout screen) and/or session RPE. The date + programWorkoutId (`athlete_workouts` `id`) locate
@@ -3129,8 +3159,7 @@ async function setAthleteWorkoutNote(client, args) {
3129
3159
  rpe: coerceInt(data.rpe) ?? (args.rpe !== void 0 ? args.rpe : null)
3130
3160
  };
3131
3161
  }
3132
- //#endregion
3133
- //#region ../js/src/athlete-exercise-note.ts
3162
+ // ../js/src/athlete-exercise-note.ts
3134
3163
  /**
3135
3164
  * PUT /1.0/athlete/savedworkoutsetexercise/{id} — set the athlete's per-exercise note (the
3136
3165
  * "Add exercise note" box on the exercise screen). A notes-only body leaves logged reps/weight
@@ -3151,8 +3180,7 @@ async function setAthleteExerciseNote(client, args) {
3151
3180
  notes: typeof data.notes === "string" ? data.notes : args.notes
3152
3181
  };
3153
3182
  }
3154
- //#endregion
3155
- //#region ../js/src/workout-export.ts
3183
+ // ../js/src/workout-export.ts
3156
3184
  const DEFAULT_FILENAME_BASE = "trainheroic-workout-history";
3157
3185
  /** Pretty-printed JSON of the structured workouts, exactly as `presentAthleteWorkoutsExport` yields. */
3158
3186
  function workoutsToJson(workouts) {
@@ -3277,8 +3305,7 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
3277
3305
  filename: `${base}.${meta.extension}`
3278
3306
  };
3279
3307
  }
3280
- //#endregion
3281
- //#region ../js/src/workout-encode.ts
3308
+ // ../js/src/workout-encode.ts
3282
3309
  const LEADERBOARD_TYPE = {
3283
3310
  completion: 0,
3284
3311
  "for completion": 0,
@@ -3452,7 +3479,7 @@ function makeExercise(ex, workoutSetId, order, key) {
3452
3479
  param2Type = ex.param_2_type ?? 1;
3453
3480
  param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
3454
3481
  } else {
3455
- param2Type = 0;
3482
+ param2Type = ex.param_2_type ?? 0;
3456
3483
  param2Values = null;
3457
3484
  }
3458
3485
  const entry = {
@@ -3511,9 +3538,6 @@ function buildBlockPayload(blocks, workoutId) {
3511
3538
  };
3512
3539
  });
3513
3540
  }
3514
- function unitOr(t) {
3515
- return unitLabel(t) ?? "?";
3516
- }
3517
3541
  const UNIT_ALIASES = {
3518
3542
  rep: "reps",
3519
3543
  reps: "reps",
@@ -3551,74 +3575,171 @@ function statedUnit(value, label) {
3551
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.`);
3552
3576
  return normalized;
3553
3577
  }
3554
- 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";
3555
3591
  if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
3556
3592
  const intended = statedUnit(stated, `${label} / ${field}`);
3557
- const fixed = unitLabel(fixedType);
3558
- 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.`);
3559
- if (paramType !== void 0 && unitLabel(paramType) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param type ${paramType} (${unitLabel(paramType) ?? "unset"}).`);
3560
- }
3561
- /** Validate both populated slots against the library before any workout write. */
3562
- function validateExerciseUnits(blockTitle, ex, defaults) {
3563
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3564
- if (ex.reps !== void 0) validateSlotUnit(label, "primaryUnit", ex.primaryUnit, ex.param_1_type, defaults.param1);
3565
- if (ex.weight !== void 0) validateSlotUnit(label, "secondaryUnit", ex.secondaryUnit, ex.param_2_type, defaults.param2, true);
3566
- }
3567
- /** Flag spec params the API will silently override to the exercise's fixed units. */
3568
- 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) {
3569
3640
  const notes = [];
3570
3641
  const warnings = [];
3571
- const u = unitOr;
3572
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3642
+ const u = unitName;
3573
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).`);
3574
- const sentP1 = ex.param_1_type;
3575
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
3576
- const sp1 = Math.trunc(Number(sentP1));
3577
- 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)}.`);
3578
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
3579
- if (ex.weight !== void 0 && ex.weight !== null) {
3580
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
3581
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
3582
- if (sentP2 !== effP2) {
3583
- 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.`);
3584
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
3585
- }
3586
- }
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)}.`);
3587
3649
  return {
3588
3650
  notes,
3589
3651
  warnings
3590
3652
  };
3591
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
+ }
3592
3661
  /**
3593
- * Validate every populated value's stated unit against current TrainHeroic exercise data,
3594
- * then collect non-blocking advisories. The write path calls this before creating a workout;
3595
- * 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.
3596
3666
  */
3597
- async function collectAdvisories(blocks, index) {
3598
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
3599
- block: b,
3600
- ex
3601
- })));
3602
- 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))];
3603
3669
  const defaultsById = await index.currentDefaultsMany(ids);
3604
3670
  const notes = [];
3605
3671
  const warnings = [];
3606
- pairs.forEach((p) => {
3607
- const def = defaultsById.get(Number(p.ex.id));
3608
- 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.`);
3609
- validateExerciseUnits(p.block.title, p.ex, def);
3610
- const advisory = unitAdvisory(p.block.title, p.ex, def);
3611
- notes.push(...advisory.notes);
3612
- warnings.push(...advisory.warnings);
3613
- });
3614
3672
  return {
3615
- notes,
3616
- 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
+ }
3617
3691
  };
3618
3692
  }
3619
- //#endregion
3620
- //#region ../js/src/workout-session.ts
3693
+ // ../js/src/workout-session.ts
3621
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
+ }
3622
3743
  /**
3623
3744
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
3624
3745
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -3647,8 +3768,9 @@ async function buildSession(client, opts) {
3647
3768
  const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
3648
3769
  const splitSummary = setSplitSummary(validatedBlocks);
3649
3770
  if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
3650
- const advisories = await collectAdvisories(validatedBlocks, opts.index);
3651
- 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);
3652
3774
  const sess = await req(client, "POST", createPath(opts), {});
3653
3775
  checkResponse(sessionCreateResponseSchema, sess, "session create");
3654
3776
  const workoutId = Number(sess.workout_id);
@@ -3661,9 +3783,13 @@ async function buildSession(client, opts) {
3661
3783
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
3662
3784
  return block.exercises.map((ex, j) => {
3663
3785
  counter += 1;
3664
- 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
+ };
3665
3791
  });
3666
- }).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));
3667
3793
  if (opts.instruction !== void 0 && opts.instruction !== "") {
3668
3794
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
3669
3795
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -3712,6 +3838,7 @@ async function readSession(client, programId, date, pwId) {
3712
3838
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
3713
3839
  return {
3714
3840
  pwId,
3841
+ workoutId: coerceInt(pw.workout_id),
3715
3842
  date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
3716
3843
  published: pw.published,
3717
3844
  instruction: str(pw.instruction),
@@ -4133,9 +4260,26 @@ async function requestAnalytics(client, args) {
4133
4260
  body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
4134
4261
  }
4135
4262
  const res = await client.request("POST", spec.path, { body });
4136
- 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
+ }
4137
4267
  return res.data;
4138
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
+ }
4139
4283
  function reportRows(report) {
4140
4284
  if (report === null || typeof report !== "object") return null;
4141
4285
  const rows = report.rows;
@@ -4275,10 +4419,31 @@ async function createSessionTemplate(client, args) {
4275
4419
  if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
4276
4420
  return res.data;
4277
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
+ }
4278
4444
  /** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
4279
4445
  const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
4280
- //#endregion
4281
- //#region ../js/src/main-lifts.ts
4446
+ // ../js/src/main-lifts.ts
4282
4447
  /**
4283
4448
  * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
4284
4449
  * first family that matches, so the more specific / easily-confused families come before the broad
@@ -4490,8 +4655,7 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
4490
4655
  };
4491
4656
  });
4492
4657
  }
4493
- //#endregion
4494
- //#region ../js/src/messaging.ts
4658
+ // ../js/src/messaging.ts
4495
4659
  const BUCKETS = [
4496
4660
  ["team", "teams"],
4497
4661
  ["athlete", "athletes"],
@@ -4546,8 +4710,7 @@ async function readLive(client, streamId, limit, afterCommentId) {
4546
4710
  if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
4547
4711
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
4548
4712
  }
4549
- //#endregion
4550
- //#region ../js/src/library-cache.ts
4713
+ // ../js/src/library-cache.ts
4551
4714
  /** In-memory cache (no persistence). The default when none is supplied. */
4552
4715
  var MemoryLibraryCache = class {
4553
4716
  #snapshot = null;
@@ -4558,8 +4721,7 @@ var MemoryLibraryCache = class {
4558
4721
  this.#snapshot = snapshot;
4559
4722
  }
4560
4723
  };
4561
- //#endregion
4562
- //#region ../js/src/exercise-index.ts
4724
+ // ../js/src/exercise-index.ts
4563
4725
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
4564
4726
  const CREATE_PATH = "/2.0/coach/exercise/create";
4565
4727
  const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
@@ -4765,8 +4927,7 @@ var ExerciseLibrary = class {
4765
4927
  };
4766
4928
  }
4767
4929
  };
4768
- //#endregion
4769
- //#region ../js/src/node.ts
4930
+ // ../js/src/node.ts
4770
4931
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
4771
4932
  function defaultCachePath() {
4772
4933
  return process.env.TRAINHEROIC_CACHE_FILE ?? join(homedir(), ".trainheroic", "library.json");
@@ -4789,8 +4950,7 @@ var JsonFileLibraryCache = class {
4789
4950
  await writeFile(this.#path, JSON.stringify(snapshot), { mode: 384 });
4790
4951
  }
4791
4952
  };
4792
- //#endregion
4793
- //#region src/parse.ts
4953
+ // src/parse.ts
4794
4954
  /** True when a string looks like inline JSON (starts with { or [) rather than a path. */
4795
4955
  function looksLikeJson(s) {
4796
4956
  return /^\s*[[{]/u.test(s);
@@ -4819,8 +4979,7 @@ function parseCountArg(value, label) {
4819
4979
  function parseIdList(value, label) {
4820
4980
  return value.split(",").map((s) => parseIntArg(s, label));
4821
4981
  }
4822
- //#endregion
4823
- //#region src/session-cache.ts
4982
+ // src/session-cache.ts
4824
4983
  const TTL_MS = 216e5;
4825
4984
  function sessionPath() {
4826
4985
  return process.env.TRAINHEROIC_SESSION_FILE ?? join(homedir(), ".trainheroic", "session.json");
@@ -4841,8 +5000,7 @@ async function saveSession(sessionId) {
4841
5000
  savedAt: Date.now()
4842
5001
  }), { mode: 384 });
4843
5002
  }
4844
- //#endregion
4845
- //#region src/cli.ts
5003
+ // src/cli.ts
4846
5004
  const HELP = `trainheroic — command-line tool for the TrainHeroic API
4847
5005
 
4848
5006
  Credentials come from TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD. Output is JSON.
@@ -4915,7 +5073,7 @@ Coach — manage a roster (needs a coach account):
4915
5073
  session lifecycle:
4916
5074
  coach session-copy --to-program <id> --pw <id> --to-date Y-M-D
4917
5075
  coach session-unpublish --pw <id> --yes
4918
- coach session-save-template --workout <id>
5076
+ coach session-save-template --workout <id> --pw <id> --title "..."
4919
5077
  coach session-templates
4920
5078
  coach session-template-create --title "..." [--instruction "..."]
4921
5079
  coach session-template-delete --id <id> --yes
@@ -5919,9 +6077,17 @@ async function cmdCoachSessionUnpublish(client, a) {
5919
6077
  return out(await mutate(client, "POST", `/2.0/coach/calendar/programWorkout/unPublish/${pwId}`));
5920
6078
  }
5921
6079
  async function cmdCoachSessionSaveTemplate(client, a) {
5922
- const usage = "coach session-save-template --workout <id>";
5923
- const { values } = parse(a, { workout: { type: "string" } });
5924
- 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
+ }));
5925
6091
  }
5926
6092
  async function cmdCoachSessionTemplateCreate(client, a) {
5927
6093
  const usage = "coach session-template-create --title \"...\" [--instruction \"...\"]";
@@ -6152,5 +6318,4 @@ async function main() {
6152
6318
  }
6153
6319
  }
6154
6320
  await main();
6155
- //#endregion
6156
6321
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "4.1.1",
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.1.1",
25
- "@trainheroic-unofficial/js": "4.1.1"
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`)