@trainheroic-unofficial/cli 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.mjs +442 -407
  2. package/package.json +3 -3
package/dist/cli.mjs CHANGED
@@ -336,13 +336,24 @@ const leaderboardSpecSchema = z.union([
336
336
  instruction: z.string().optional()
337
337
  })
338
338
  ]);
339
- /** A block (group of exercises); two exercises render as a superset. */
339
+ /**
340
+ * A block (group of exercises); two exercises render as a superset.
341
+ * Empty `exercises` is allowed only with a non-empty `instruction` — that is TrainHeroic's
342
+ * free-text Circuit / Conditioning block (type 1): title + instruction blurb, no linked lifts.
343
+ */
340
344
  const blockSpecSchema = z.object({
341
345
  title: z.string(),
342
346
  type: z.number().optional(),
343
347
  instruction: z.string().optional(),
344
348
  leaderboard: leaderboardSpecSchema.optional(),
345
349
  exercises: z.array(exerciseSpecSchema)
350
+ }).superRefine((block, ctx) => {
351
+ if (block.exercises.length > 0) return;
352
+ if ((block.instruction?.trim() ?? "") === "") ctx.addIssue({
353
+ code: "custom",
354
+ message: "A block with no exercises needs a non-empty instruction (text-only Circuit / Conditioning block). Otherwise provide at least one exercise.",
355
+ path: ["exercises"]
356
+ });
346
357
  });
347
358
  /** A full session spec: the blocks plus an optional session note (Coach Instructions). */
348
359
  const workoutSpecSchema = z.object({
@@ -2120,95 +2131,453 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
2120
2131
  filename: `${base}.${meta.extension}`
2121
2132
  };
2122
2133
  }
2123
- /** Normalize one-or-many emails into a deduped, trimmed list. */
2124
- function emailList(emails) {
2125
- return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
2126
- }
2127
- /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
2128
- function rosterName(rec) {
2129
- const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
2130
- if (full !== "") return full;
2131
- const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
2132
- return combined !== "" ? combined : null;
2134
+ //#endregion
2135
+ //#region ../js/src/workout-encode.ts
2136
+ const LEADERBOARD_TYPE = {
2137
+ completion: 0,
2138
+ "for completion": 0,
2139
+ weight: 1,
2140
+ lb: 1,
2141
+ load: 1,
2142
+ reps: 2,
2143
+ rep: 2,
2144
+ rounds: 3,
2145
+ round: 3,
2146
+ time: 4,
2147
+ yards: 5,
2148
+ yd: 5,
2149
+ meters: 6,
2150
+ m: 6,
2151
+ feet: 7,
2152
+ ft: 7,
2153
+ calories: 8,
2154
+ cal: 8,
2155
+ cals: 8,
2156
+ miles: 10,
2157
+ mi: 10,
2158
+ inches: 12,
2159
+ in: 12,
2160
+ watts: 15,
2161
+ w: 15,
2162
+ velocity: 17,
2163
+ "m/s": 17,
2164
+ seconds: 18,
2165
+ sec: 18,
2166
+ s: 18
2167
+ };
2168
+ const LEADERBOARD_LABEL = {
2169
+ 0: "For Completion",
2170
+ 1: "Weight",
2171
+ 2: "Reps",
2172
+ 3: "Rounds",
2173
+ 4: "Time",
2174
+ 5: "Yards",
2175
+ 6: "Meters",
2176
+ 7: "Feet",
2177
+ 8: "Calories",
2178
+ 10: "Miles",
2179
+ 12: "Inches",
2180
+ 13: "Other",
2181
+ 15: "Watts",
2182
+ 16: "Percent",
2183
+ 17: "Velocity",
2184
+ 18: "Seconds"
2185
+ };
2186
+ function resolveLeaderboard(block) {
2187
+ const lb = block.leaderboard;
2188
+ if (lb === void 0 || lb === null) return {
2189
+ isRedzone: null,
2190
+ redzoneType: 0,
2191
+ smallerIsBetter: null,
2192
+ redzoneInstruction: ""
2193
+ };
2194
+ let unit;
2195
+ let instruction = "";
2196
+ let lowest;
2197
+ if (typeof lb === "object") {
2198
+ unit = lb.unit ?? lb.type;
2199
+ instruction = lb.instruction ?? "";
2200
+ lowest = lb.lowest_wins;
2201
+ } else unit = lb;
2202
+ let rz;
2203
+ if (typeof unit === "string") {
2204
+ const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
2205
+ if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
2206
+ rz = found;
2207
+ } else if (typeof unit === "number") rz = Math.trunc(unit);
2208
+ else throw new Error("Leaderboard requires a unit.");
2209
+ if (lowest === void 0) lowest = rz === 4 || rz === 18;
2210
+ return {
2211
+ isRedzone: 1,
2212
+ redzoneType: rz,
2213
+ smallerIsBetter: lowest ? 1 : 0,
2214
+ redzoneInstruction: instruction
2215
+ };
2133
2216
  }
2134
- /**
2135
- * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
2136
- * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
2137
- * and the warehouse store map the roster identically. Includes the account owner and
2138
- * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
2139
- */
2140
- async function fetchCoachRoster(client, ids) {
2141
- const res = await client.request("GET", "/v5/athletes");
2142
- if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2143
- const keep = ids && ids.length > 0 ? new Set(ids) : null;
2217
+ function slots(values, n = 10) {
2144
2218
  const out = [];
2145
- for (const row of res.data) {
2146
- if (typeof row !== "object" || row === null) continue;
2147
- const rec = row;
2148
- const id = coerceInt(rec.id);
2149
- if (id === null || id <= 0) continue;
2150
- if (keep && !keep.has(id)) continue;
2151
- out.push({
2152
- id,
2153
- name: rosterName(rec)
2154
- });
2155
- }
2219
+ for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
2156
2220
  return out;
2157
2221
  }
2222
+ function repsList(ex) {
2223
+ const reps = ex.reps;
2224
+ if (Array.isArray(reps)) return reps.map((r) => String(r));
2225
+ if (reps === void 0 || reps === null) return [];
2226
+ const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2227
+ return Array.from({ length: sets }, () => String(reps));
2228
+ }
2229
+ /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2230
+ function makeExercise(ex, workoutSetId, order, key) {
2231
+ const reps = repsList(ex);
2232
+ let instruction = ex.instr ?? "";
2233
+ if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2234
+ const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2235
+ const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2236
+ let count = reps.length;
2237
+ if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2238
+ let param2Type;
2239
+ let param2Values;
2240
+ if (hasWeight) {
2241
+ param2Type = ex.param_2_type ?? 1;
2242
+ param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2243
+ } else {
2244
+ param2Type = 0;
2245
+ param2Values = null;
2246
+ }
2247
+ const entry = {
2248
+ exercise_id: ex.id,
2249
+ workout_set_id: workoutSetId,
2250
+ set_id: workoutSetId,
2251
+ setKey: workoutSetId,
2252
+ title: ex.title ?? "",
2253
+ instruction,
2254
+ order,
2255
+ param_1_type: ex.param_1_type ?? 3,
2256
+ param_2_type: param2Type,
2257
+ workout_set_exercise_template_id: null,
2258
+ no_sets: 0,
2259
+ param_count: count,
2260
+ set_num: count,
2261
+ key,
2262
+ video_url: "",
2263
+ thumbnail_url: "",
2264
+ tags: [],
2265
+ eType: "e",
2266
+ use_count: 0
2267
+ };
2268
+ const p1 = slots(reps);
2269
+ const p2 = slots(param2Values);
2270
+ for (let i = 0; i < 10; i += 1) {
2271
+ entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2272
+ entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
2273
+ }
2274
+ return entry;
2275
+ }
2158
2276
  /**
2159
- * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
2160
- * addresses (`POST /v5/emails/validate`), then invite the validated ones
2161
- * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
2277
+ * Default block type: text-only (empty exercises) blocks are Conditioning / Circuit (type 1);
2278
+ * structured exercise blocks default to Hypertrophy (type 2). An explicit `type` always wins.
2162
2279
  */
2163
- async function inviteAthletes(client, args) {
2164
- const list = emailList(args.emails);
2165
- if (list.length === 0) throw new Error("Provide at least one email address to invite.");
2166
- const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
2167
- if (!validation.ok) {
2168
- const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
2169
- throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
2170
- }
2171
- const valid = Array.isArray(validation.data) ? validation.data : list;
2172
- if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
2173
- const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
2174
- teamType: 0,
2175
- teamId: args.teamId,
2176
- orgId: null,
2177
- emails: valid,
2178
- message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
2179
- } });
2180
- if (!invite.ok) {
2181
- const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
2182
- throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
2280
+ function defaultBlockType(block) {
2281
+ if (block.type !== void 0) return block.type;
2282
+ return block.exercises.length === 0 ? 1 : 2;
2283
+ }
2284
+ function buildBlockPayload(blocks, workoutId) {
2285
+ return blocks.map((b, i) => {
2286
+ const lb = resolveLeaderboard(b);
2287
+ return {
2288
+ workout_id: workoutId,
2289
+ order: i + 1,
2290
+ type: defaultBlockType(b),
2291
+ instruction: b.instruction ?? "",
2292
+ is_redzone: lb.isRedzone,
2293
+ redzone_type: lb.redzoneType,
2294
+ smaller_is_better: lb.smallerIsBetter,
2295
+ redzone_instruction: lb.redzoneInstruction,
2296
+ exercises: [],
2297
+ exerciseKeys: [],
2298
+ key: `k::${workoutId}${i + 1}`,
2299
+ title: b.title
2300
+ };
2301
+ });
2302
+ }
2303
+ function unitOr(t) {
2304
+ return unitLabel(t) ?? "?";
2305
+ }
2306
+ /** Flag spec params the API will silently override to the exercise's fixed units. */
2307
+ function unitAdvisory(blockTitle, ex, defaults) {
2308
+ const notes = [];
2309
+ const warnings = [];
2310
+ const u = unitOr;
2311
+ const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2312
+ 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).`);
2313
+ const sentP1 = ex.param_1_type;
2314
+ if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2315
+ const sp1 = Math.trunc(Number(sentP1));
2316
+ 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)}.`);
2317
+ } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2318
+ if (ex.weight !== void 0 && ex.weight !== null) {
2319
+ const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2320
+ const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2321
+ if (sentP2 !== effP2) 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.`);
2322
+ else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2183
2323
  }
2184
2324
  return {
2185
- teamId: args.teamId,
2186
- invited: valid,
2187
- result: invite.data
2325
+ notes,
2326
+ warnings
2188
2327
  };
2189
2328
  }
2190
2329
  /**
2191
- * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2192
- * The API wants the target date as a structured object (with weekday and an isToday flag),
2193
- * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
2330
+ * Run unit advisories across a whole block list against an exercise index. Shared by the
2331
+ * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2332
+ * index is loaded first, otherwise `defaults` returns null on a cold index and every
2333
+ * advisory is silently dropped.
2194
2334
  */
2195
- async function copySession(client, args) {
2196
- const [year, month, day] = parseWorkoutDate(args.toDate);
2197
- const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
2198
- const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
2199
- const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
2200
- toProgramId: args.toProgramId,
2201
- pwId: args.pwId,
2202
- toDate: {
2203
- date: iso,
2204
- day,
2205
- month,
2335
+ async function collectAdvisories(blocks, index) {
2336
+ await index.ensureFresh();
2337
+ const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2338
+ block: b,
2339
+ ex
2340
+ })));
2341
+ const defaults = await Promise.all(pairs.map((p) => {
2342
+ const id = Number(p.ex.id);
2343
+ return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2344
+ }));
2345
+ const notes = [];
2346
+ const warnings = [];
2347
+ pairs.forEach((p, i) => {
2348
+ const def = defaults[i];
2349
+ if (!def) return;
2350
+ const advisory = unitAdvisory(p.block.title, p.ex, def);
2351
+ notes.push(...advisory.notes);
2352
+ warnings.push(...advisory.warnings);
2353
+ });
2354
+ return {
2355
+ notes,
2356
+ warnings
2357
+ };
2358
+ }
2359
+ //#endregion
2360
+ //#region ../js/src/workout-session.ts
2361
+ /**
2362
+ * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2363
+ * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
2364
+ * `copySession` so the hint stays in one place.
2365
+ */
2366
+ function calendarWriteError(method, path, status, detail) {
2367
+ const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
2368
+ if (!(path.includes("/createWorkoutForDay/") || path.includes("/createWorkoutForTimelineDay/") || path.includes("/copyProgramWorkout")) || status !== 500 && status !== 401) return new Error(base);
2369
+ return /* @__PURE__ */ new Error(`${base}. This often means the program is another athlete's Coach Plan / personal calendar (personal_cal), which the coach calendar write endpoints do not support — workout_build and session_copy work on team/group programs (and the coach's own personal calendar), but there is currently no coach-facing tool to create sessions on another athlete's personal calendar.`);
2370
+ }
2371
+ async function req(client, method, path, body) {
2372
+ const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2373
+ if (!res.ok) {
2374
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2375
+ throw calendarWriteError(method, path, res.status, detail);
2376
+ }
2377
+ return res.data;
2378
+ }
2379
+ function createPath(opts) {
2380
+ if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2381
+ if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2382
+ const [y, m, d] = opts.date;
2383
+ return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2384
+ }
2385
+ async function buildSession(client, opts) {
2386
+ const blocks = z.array(blockSpecSchema).parse(opts.blocks);
2387
+ const sess = await req(client, "POST", createPath(opts), {});
2388
+ checkResponse(sessionCreateResponseSchema, sess, "session create");
2389
+ const workoutId = Number(sess.workout_id);
2390
+ const pwId = Number(sess.id);
2391
+ const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2392
+ const byOrder = new Map(created.map((b) => [b.order, b.id]));
2393
+ let counter = 0;
2394
+ const payloads = blocks.map((block, i) => {
2395
+ const wsid = byOrder.get(i + 1);
2396
+ if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2397
+ return block.exercises.map((ex, j) => {
2398
+ counter += 1;
2399
+ return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2400
+ });
2401
+ });
2402
+ await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2403
+ if (opts.instruction !== void 0 && opts.instruction !== "") {
2404
+ const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2405
+ await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2406
+ }
2407
+ if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2408
+ return {
2409
+ pwId,
2410
+ workoutId
2411
+ };
2412
+ }
2413
+ /**
2414
+ * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2415
+ * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2416
+ * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2417
+ * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
2418
+ */
2419
+ async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2420
+ const body = {
2421
+ ...pw,
2422
+ instruction,
2423
+ sets: blockIds,
2424
+ setKeys: blockIds
2425
+ };
2426
+ await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2427
+ }
2428
+ async function removeSession(client, programId, pwId) {
2429
+ await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2430
+ programId,
2431
+ pwId
2432
+ });
2433
+ }
2434
+ async function publishSession(client, pwId) {
2435
+ await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2436
+ }
2437
+ function str(value) {
2438
+ return value === void 0 || value === null ? "" : String(value);
2439
+ }
2440
+ async function readSession(client, programId, date, pwId) {
2441
+ const [y, m, d] = date;
2442
+ const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2443
+ checkResponse(programsEditResponseSchema, data, "programs edit");
2444
+ const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2445
+ if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2446
+ const setsObj = pw.sets ?? {};
2447
+ const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2448
+ return {
2449
+ pwId,
2450
+ date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2451
+ published: pw.published,
2452
+ instruction: str(pw.instruction),
2453
+ blocks
2454
+ };
2455
+ }
2456
+ function readBlock(b) {
2457
+ const rz = coerceInt(b.redzone_type);
2458
+ let leaderboard = null;
2459
+ if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2460
+ const exercises = (Array.isArray(b.exercises) ? b.exercises : []).filter((ex) => coerceInt(ex.id) !== null || str(ex.title) !== "").sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2461
+ return {
2462
+ order: Number(b.order),
2463
+ title: str(b.title),
2464
+ instruction: str(b.instruction),
2465
+ leaderboard,
2466
+ exercises
2467
+ };
2468
+ }
2469
+ function readExercise(ex) {
2470
+ const reps = [];
2471
+ const load = [];
2472
+ for (let i = 1; i <= 10; i += 1) {
2473
+ const r = str(ex[`param_1_data_${i}`]);
2474
+ if (r !== "") reps.push(r);
2475
+ const w = str(ex[`param_2_data_${i}`]);
2476
+ if (w !== "") load.push(w);
2477
+ }
2478
+ return {
2479
+ order: Number(ex.order),
2480
+ title: str(ex.title),
2481
+ reps,
2482
+ primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2483
+ load,
2484
+ loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2485
+ instruction: str(ex.instruction)
2486
+ };
2487
+ }
2488
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
2489
+ function emailList(emails) {
2490
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
2491
+ }
2492
+ /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
2493
+ function rosterName(rec) {
2494
+ const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
2495
+ if (full !== "") return full;
2496
+ const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
2497
+ return combined !== "" ? combined : null;
2498
+ }
2499
+ /**
2500
+ * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
2501
+ * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
2502
+ * and the warehouse store map the roster identically. Includes the account owner and
2503
+ * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
2504
+ */
2505
+ async function fetchCoachRoster(client, ids) {
2506
+ const res = await client.request("GET", "/v5/athletes");
2507
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2508
+ const keep = ids && ids.length > 0 ? new Set(ids) : null;
2509
+ const out = [];
2510
+ for (const row of res.data) {
2511
+ if (typeof row !== "object" || row === null) continue;
2512
+ const rec = row;
2513
+ const id = coerceInt(rec.id);
2514
+ if (id === null || id <= 0) continue;
2515
+ if (keep && !keep.has(id)) continue;
2516
+ out.push({
2517
+ id,
2518
+ name: rosterName(rec)
2519
+ });
2520
+ }
2521
+ return out;
2522
+ }
2523
+ /**
2524
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
2525
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
2526
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
2527
+ */
2528
+ async function inviteAthletes(client, args) {
2529
+ const list = emailList(args.emails);
2530
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
2531
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
2532
+ if (!validation.ok) {
2533
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
2534
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
2535
+ }
2536
+ const valid = Array.isArray(validation.data) ? validation.data : list;
2537
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
2538
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
2539
+ teamType: 0,
2540
+ teamId: args.teamId,
2541
+ orgId: null,
2542
+ emails: valid,
2543
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
2544
+ } });
2545
+ if (!invite.ok) {
2546
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
2547
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
2548
+ }
2549
+ return {
2550
+ teamId: args.teamId,
2551
+ invited: valid,
2552
+ result: invite.data
2553
+ };
2554
+ }
2555
+ /**
2556
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2557
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
2558
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
2559
+ */
2560
+ async function copySession(client, args) {
2561
+ const [year, month, day] = parseWorkoutDate(args.toDate);
2562
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
2563
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
2564
+ const path = "/2.0/coach/calendar/copyProgramWorkout";
2565
+ const res = await client.request("POST", path, { body: {
2566
+ toProgramId: args.toProgramId,
2567
+ pwId: args.pwId,
2568
+ toDate: {
2569
+ date: iso,
2570
+ day,
2571
+ month,
2206
2572
  year,
2207
2573
  dayOfWeek,
2208
2574
  isToday: false
2209
2575
  }
2210
2576
  } });
2211
- if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
2577
+ if (!res.ok) {
2578
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2579
+ throw calendarWriteError("POST", path, res.status, detail);
2580
+ }
2212
2581
  return res.data;
2213
2582
  }
2214
2583
  const ANALYTICS_METRIC_KEYS = [
@@ -2657,340 +3026,6 @@ function definedProps(obj) {
2657
3026
  return result;
2658
3027
  }
2659
3028
  //#endregion
2660
- //#region ../js/src/workout-encode.ts
2661
- const LEADERBOARD_TYPE = {
2662
- completion: 0,
2663
- "for completion": 0,
2664
- weight: 1,
2665
- lb: 1,
2666
- load: 1,
2667
- reps: 2,
2668
- rep: 2,
2669
- rounds: 3,
2670
- round: 3,
2671
- time: 4,
2672
- yards: 5,
2673
- yd: 5,
2674
- meters: 6,
2675
- m: 6,
2676
- feet: 7,
2677
- ft: 7,
2678
- calories: 8,
2679
- cal: 8,
2680
- cals: 8,
2681
- miles: 10,
2682
- mi: 10,
2683
- inches: 12,
2684
- in: 12,
2685
- watts: 15,
2686
- w: 15,
2687
- velocity: 17,
2688
- "m/s": 17,
2689
- seconds: 18,
2690
- sec: 18,
2691
- s: 18
2692
- };
2693
- const LEADERBOARD_LABEL = {
2694
- 0: "For Completion",
2695
- 1: "Weight",
2696
- 2: "Reps",
2697
- 3: "Rounds",
2698
- 4: "Time",
2699
- 5: "Yards",
2700
- 6: "Meters",
2701
- 7: "Feet",
2702
- 8: "Calories",
2703
- 10: "Miles",
2704
- 12: "Inches",
2705
- 13: "Other",
2706
- 15: "Watts",
2707
- 16: "Percent",
2708
- 17: "Velocity",
2709
- 18: "Seconds"
2710
- };
2711
- function resolveLeaderboard(block) {
2712
- const lb = block.leaderboard;
2713
- if (lb === void 0 || lb === null) return {
2714
- isRedzone: null,
2715
- redzoneType: 0,
2716
- smallerIsBetter: null,
2717
- redzoneInstruction: ""
2718
- };
2719
- let unit;
2720
- let instruction = "";
2721
- let lowest;
2722
- if (typeof lb === "object") {
2723
- unit = lb.unit ?? lb.type;
2724
- instruction = lb.instruction ?? "";
2725
- lowest = lb.lowest_wins;
2726
- } else unit = lb;
2727
- let rz;
2728
- if (typeof unit === "string") {
2729
- const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
2730
- if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
2731
- rz = found;
2732
- } else if (typeof unit === "number") rz = Math.trunc(unit);
2733
- else throw new Error("Leaderboard requires a unit.");
2734
- if (lowest === void 0) lowest = rz === 4 || rz === 18;
2735
- return {
2736
- isRedzone: 1,
2737
- redzoneType: rz,
2738
- smallerIsBetter: lowest ? 1 : 0,
2739
- redzoneInstruction: instruction
2740
- };
2741
- }
2742
- function slots(values, n = 10) {
2743
- const out = [];
2744
- for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
2745
- return out;
2746
- }
2747
- function repsList(ex) {
2748
- const reps = ex.reps;
2749
- if (Array.isArray(reps)) return reps.map((r) => String(r));
2750
- if (reps === void 0 || reps === null) return [];
2751
- const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2752
- return Array.from({ length: sets }, () => String(reps));
2753
- }
2754
- /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2755
- function makeExercise(ex, workoutSetId, order, key) {
2756
- const reps = repsList(ex);
2757
- let instruction = ex.instr ?? "";
2758
- if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2759
- const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2760
- const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2761
- let count = reps.length;
2762
- if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2763
- let param2Type;
2764
- let param2Values;
2765
- if (hasWeight) {
2766
- param2Type = ex.param_2_type ?? 1;
2767
- param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2768
- } else {
2769
- param2Type = 0;
2770
- param2Values = null;
2771
- }
2772
- const entry = {
2773
- exercise_id: ex.id,
2774
- workout_set_id: workoutSetId,
2775
- set_id: workoutSetId,
2776
- setKey: workoutSetId,
2777
- title: ex.title ?? "",
2778
- instruction,
2779
- order,
2780
- param_1_type: ex.param_1_type ?? 3,
2781
- param_2_type: param2Type,
2782
- workout_set_exercise_template_id: null,
2783
- no_sets: 0,
2784
- param_count: count,
2785
- set_num: count,
2786
- key,
2787
- video_url: "",
2788
- thumbnail_url: "",
2789
- tags: [],
2790
- eType: "e",
2791
- use_count: 0
2792
- };
2793
- const p1 = slots(reps);
2794
- const p2 = slots(param2Values);
2795
- for (let i = 0; i < 10; i += 1) {
2796
- entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2797
- entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
2798
- }
2799
- return entry;
2800
- }
2801
- function buildBlockPayload(blocks, workoutId) {
2802
- return blocks.map((b, i) => {
2803
- const lb = resolveLeaderboard(b);
2804
- return {
2805
- workout_id: workoutId,
2806
- order: i + 1,
2807
- type: b.type ?? 2,
2808
- instruction: b.instruction ?? "",
2809
- is_redzone: lb.isRedzone,
2810
- redzone_type: lb.redzoneType,
2811
- smaller_is_better: lb.smallerIsBetter,
2812
- redzone_instruction: lb.redzoneInstruction,
2813
- exercises: [],
2814
- exerciseKeys: [],
2815
- key: `k::${workoutId}${i + 1}`,
2816
- title: b.title
2817
- };
2818
- });
2819
- }
2820
- function unitOr(t) {
2821
- return unitLabel(t) ?? "?";
2822
- }
2823
- /** Flag spec params the API will silently override to the exercise's fixed units. */
2824
- function unitAdvisory(blockTitle, ex, defaults) {
2825
- const notes = [];
2826
- const warnings = [];
2827
- const u = unitOr;
2828
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2829
- 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).`);
2830
- const sentP1 = ex.param_1_type;
2831
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2832
- const sp1 = Math.trunc(Number(sentP1));
2833
- 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)}.`);
2834
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2835
- if (ex.weight !== void 0 && ex.weight !== null) {
2836
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2837
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2838
- if (sentP2 !== effP2) 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.`);
2839
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2840
- }
2841
- return {
2842
- notes,
2843
- warnings
2844
- };
2845
- }
2846
- /**
2847
- * Run unit advisories across a whole block list against an exercise index. Shared by the
2848
- * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2849
- * index is loaded first, otherwise `defaults` returns null on a cold index and every
2850
- * advisory is silently dropped.
2851
- */
2852
- async function collectAdvisories(blocks, index) {
2853
- await index.ensureFresh();
2854
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2855
- block: b,
2856
- ex
2857
- })));
2858
- const defaults = await Promise.all(pairs.map((p) => {
2859
- const id = Number(p.ex.id);
2860
- return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2861
- }));
2862
- const notes = [];
2863
- const warnings = [];
2864
- pairs.forEach((p, i) => {
2865
- const def = defaults[i];
2866
- if (!def) return;
2867
- const advisory = unitAdvisory(p.block.title, p.ex, def);
2868
- notes.push(...advisory.notes);
2869
- warnings.push(...advisory.warnings);
2870
- });
2871
- return {
2872
- notes,
2873
- warnings
2874
- };
2875
- }
2876
- //#endregion
2877
- //#region ../js/src/workout-session.ts
2878
- async function req(client, method, path, body) {
2879
- const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2880
- if (!res.ok) {
2881
- const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2882
- throw new Error(`${method} ${path} failed (HTTP ${res.status}): ${detail}`);
2883
- }
2884
- return res.data;
2885
- }
2886
- function createPath(opts) {
2887
- if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2888
- if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2889
- const [y, m, d] = opts.date;
2890
- return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2891
- }
2892
- async function buildSession(client, opts) {
2893
- const sess = await req(client, "POST", createPath(opts), {});
2894
- checkResponse(sessionCreateResponseSchema, sess, "session create");
2895
- const workoutId = Number(sess.workout_id);
2896
- const pwId = Number(sess.id);
2897
- const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(opts.blocks, workoutId));
2898
- const byOrder = new Map(created.map((b) => [b.order, b.id]));
2899
- let counter = 0;
2900
- const payloads = opts.blocks.map((block, i) => {
2901
- const wsid = byOrder.get(i + 1);
2902
- if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2903
- return block.exercises.map((ex, j) => {
2904
- counter += 1;
2905
- return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2906
- });
2907
- });
2908
- await Promise.all(payloads.map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2909
- if (opts.instruction !== void 0 && opts.instruction !== "") {
2910
- const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2911
- await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2912
- }
2913
- if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2914
- return {
2915
- pwId,
2916
- workoutId
2917
- };
2918
- }
2919
- /**
2920
- * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2921
- * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2922
- * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2923
- * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
2924
- */
2925
- async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2926
- const body = {
2927
- ...pw,
2928
- instruction,
2929
- sets: blockIds,
2930
- setKeys: blockIds
2931
- };
2932
- await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2933
- }
2934
- async function removeSession(client, programId, pwId) {
2935
- await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2936
- programId,
2937
- pwId
2938
- });
2939
- }
2940
- async function publishSession(client, pwId) {
2941
- await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2942
- }
2943
- function str(value) {
2944
- return value === void 0 || value === null ? "" : String(value);
2945
- }
2946
- async function readSession(client, programId, date, pwId) {
2947
- const [y, m, d] = date;
2948
- const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2949
- checkResponse(programsEditResponseSchema, data, "programs edit");
2950
- const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2951
- if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2952
- const setsObj = pw.sets ?? {};
2953
- const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2954
- return {
2955
- pwId,
2956
- date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2957
- published: pw.published,
2958
- instruction: str(pw.instruction),
2959
- blocks
2960
- };
2961
- }
2962
- function readBlock(b) {
2963
- const rz = coerceInt(b.redzone_type);
2964
- let leaderboard = null;
2965
- if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2966
- const exercises = (Array.isArray(b.exercises) ? b.exercises : []).sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2967
- return {
2968
- order: Number(b.order),
2969
- title: str(b.title),
2970
- leaderboard,
2971
- exercises
2972
- };
2973
- }
2974
- function readExercise(ex) {
2975
- const reps = [];
2976
- const load = [];
2977
- for (let i = 1; i <= 10; i += 1) {
2978
- const r = str(ex[`param_1_data_${i}`]);
2979
- if (r !== "") reps.push(r);
2980
- const w = str(ex[`param_2_data_${i}`]);
2981
- if (w !== "") load.push(w);
2982
- }
2983
- return {
2984
- order: Number(ex.order),
2985
- title: str(ex.title),
2986
- reps,
2987
- primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2988
- load,
2989
- loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2990
- instruction: str(ex.instruction)
2991
- };
2992
- }
2993
- //#endregion
2994
3029
  //#region ../js/src/messaging.ts
2995
3030
  const BUCKETS = [
2996
3031
  ["team", "teams"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "2.0.0",
25
- "@trainheroic-unofficial/js": "2.0.0"
24
+ "@trainheroic-unofficial/js": "2.0.2",
25
+ "@trainheroic-unofficial/dto": "2.0.2"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.1.2",