@trainheroic-unofficial/cli 2.0.2 → 2.1.1

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/dist/cli.mjs CHANGED
@@ -375,6 +375,34 @@ function parseWorkoutDate(s) {
375
375
  ];
376
376
  }
377
377
  //#endregion
378
+ //#region ../js/src/http-error.ts
379
+ /**
380
+ * A final non-2xx response from TrainHeroic. The error deliberately carries only request
381
+ * metadata that is safe to send to telemetry: never the path, query string, request body,
382
+ * response body, credentials, or session token.
383
+ */
384
+ var TrainHeroicHttpError = class extends Error {
385
+ name = "TrainHeroicHttpError";
386
+ method;
387
+ status;
388
+ host;
389
+ constructor(method, url, status) {
390
+ const parsed = new URL(url);
391
+ const normalizedMethod = method.toUpperCase();
392
+ super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
393
+ this.method = normalizedMethod;
394
+ this.status = status;
395
+ this.host = parsed.host;
396
+ }
397
+ };
398
+ /** Call observability hooks without allowing them to change SDK behavior. */
399
+ function notifyHttpError(handler, method, url, status) {
400
+ if (!handler) return;
401
+ try {
402
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
403
+ } catch {}
404
+ }
405
+ //#endregion
378
406
  //#region ../js/src/auth.ts
379
407
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
380
408
  /**
@@ -396,8 +424,9 @@ function authUrl() {
396
424
  * the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
397
425
  * is sent as the `session-token` header and works against both API hosts.
398
426
  */
399
- async function loginTrainHeroic(email, password) {
400
- const res = await fetch(authUrl(), {
427
+ async function loginTrainHeroic(email, password, options = {}) {
428
+ const url = authUrl();
429
+ const res = await fetch(url, {
401
430
  method: "POST",
402
431
  headers: {
403
432
  "content-type": "application/x-www-form-urlencoded",
@@ -408,7 +437,10 @@ async function loginTrainHeroic(email, password) {
408
437
  password
409
438
  }).toString()
410
439
  });
411
- if (!res.ok) return null;
440
+ if (!res.ok) {
441
+ notifyHttpError(options.onHttpError, "POST", url, res.status);
442
+ return null;
443
+ }
412
444
  const data = await res.json().catch(() => null);
413
445
  if (!data || typeof data.id !== "number" || !data.session_id) return null;
414
446
  return {
@@ -451,6 +483,7 @@ var TrainHeroicClient = class {
451
483
  #email;
452
484
  #password;
453
485
  #onSession;
486
+ #onHttpError;
454
487
  #sessionId;
455
488
  #loginInFlight = null;
456
489
  constructor(email, password, sessionId = null, options = {}) {
@@ -458,6 +491,7 @@ var TrainHeroicClient = class {
458
491
  this.#password = password;
459
492
  this.#sessionId = sessionId;
460
493
  this.#onSession = options.onSession;
494
+ this.#onHttpError = options.onHttpError;
461
495
  }
462
496
  get sessionId() {
463
497
  return this.#sessionId;
@@ -472,7 +506,7 @@ var TrainHeroicClient = class {
472
506
  }
473
507
  }
474
508
  async #login() {
475
- const session = await loginTrainHeroic(this.#email, this.#password);
509
+ const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
476
510
  if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
477
511
  this.#sessionId = session.sessionId;
478
512
  try {
@@ -489,6 +523,7 @@ var TrainHeroicClient = class {
489
523
  session = await this.#ensureSession();
490
524
  res = await this.#send(method, url, session, options.body);
491
525
  }
526
+ if (!res.ok) notifyHttpError(this.#onHttpError, method, url, res.status);
492
527
  const text = await res.text();
493
528
  let data = text;
494
529
  if (text.length > 0) try {
@@ -717,7 +752,7 @@ async function getJson(client, path, label) {
717
752
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
718
753
  return res.data;
719
754
  }
720
- async function getArray(client, path, label) {
755
+ async function getArray$1(client, path, label) {
721
756
  const res = await client.request("GET", path);
722
757
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
723
758
  return res.data;
@@ -800,10 +835,10 @@ function fetchAthletePrefs(client) {
800
835
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
801
836
  }
802
837
  function fetchWorkingMaxes(client) {
803
- return getArray(client, "/2.0/athlete/workingMax", "athlete working maxes");
838
+ return getArray$1(client, "/2.0/athlete/workingMax", "athlete working maxes");
804
839
  }
805
840
  function fetchExerciseHistoryList(client) {
806
- return getArray(client, "/v5/users/exercises/history", "athlete exercise history list");
841
+ return getArray$1(client, "/v5/users/exercises/history", "athlete exercise history list");
807
842
  }
808
843
  /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
809
844
  async function searchExerciseHistory(client, query, limit = 20) {
@@ -813,7 +848,7 @@ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
813
848
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
814
849
  }
815
850
  function fetchPersonalRecords(client, exerciseId) {
816
- return getArray(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
851
+ return getArray$1(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
817
852
  }
818
853
  /** Last performance + PR for an exercise. `date` (YYYY-MM-DD) is required by the API. */
819
854
  function fetchExerciseStats(client, exerciseId, userId, date) {
@@ -821,7 +856,7 @@ function fetchExerciseStats(client, exerciseId, userId, date) {
821
856
  }
822
857
  /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
823
858
  function fetchAthleteWorkouts(client, startDate, endDate) {
824
- return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
859
+ return getArray$1(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
825
860
  }
826
861
  /** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
827
862
  function shiftDate(iso, days) {
@@ -883,24 +918,6 @@ async function fetchAthleteWorkoutsChunked(client, startDate, endDate, opts = {}
883
918
  return page;
884
919
  }));
885
920
  }
886
- /**
887
- * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
888
- * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
889
- * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
890
- * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
891
- */
892
- function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
893
- return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
894
- }
895
- /**
896
- * A coach's month view of a roster athlete's logged sessions
897
- * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
898
- * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
899
- * `userId` in each row is the roster athlete, not the calling coach.
900
- */
901
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
902
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
903
- }
904
921
  function fetchLeaderboard(client, workoutId, opts = {}) {
905
922
  const qs = new URLSearchParams();
906
923
  if (opts.page !== void 0) qs.set("page", String(opts.page));
@@ -1365,6 +1382,70 @@ function presentExerciseHistory(detail) {
1365
1382
  };
1366
1383
  }
1367
1384
  //#endregion
1385
+ //#region ../js/src/coach-athlete-calendar.ts
1386
+ async function getArray(client, path, label) {
1387
+ const res = await client.request("GET", path);
1388
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
1389
+ return res.data;
1390
+ }
1391
+ /**
1392
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
1393
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
1394
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
1395
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
1396
+ */
1397
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
1398
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
1399
+ }
1400
+ /**
1401
+ * A coach's month view of a roster athlete's logged sessions
1402
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1403
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1404
+ * `userId` in each row is the roster athlete, not the calling coach.
1405
+ */
1406
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1407
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
1408
+ }
1409
+ /**
1410
+ * Resolve a roster athlete's coach-writable calendar program id
1411
+ * (`GET /v5/calendars/athletes/{athleteId}?year=&month=`).
1412
+ *
1413
+ * Year and month are required by the API (HTTP 400 without them); the returned `programId` is
1414
+ * stable for the athlete, so any month works. This is the calendar the coach web app writes
1415
+ * with `createWorkoutForDay` when you open an athlete from My Athletes → calendar — distinct
1416
+ * from athlete-created `personal_cal` ad-hoc sessions.
1417
+ */
1418
+ async function fetchCoachAthleteCalendar(client, athleteId, year, month) {
1419
+ const path = `/v5/calendars/athletes/${athleteId}?year=${year}&month=${month}`;
1420
+ const res = await client.request("GET", path);
1421
+ if (!res.ok) {
1422
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
1423
+ throw new Error(`GET ${path} failed (HTTP ${res.status}): ${detail}`);
1424
+ }
1425
+ if (!isRecord(res.data)) throw new Error("Unexpected athlete calendar response.");
1426
+ const programId = coerceInt(res.data.id);
1427
+ if (programId === null || programId <= 0) throw new Error(`Athlete calendar for ${athleteId} did not include a program id.`);
1428
+ return {
1429
+ programId,
1430
+ title: str$1(res.data.title) ?? "",
1431
+ type: coerceInt(res.data.type),
1432
+ groupId: coerceInt(res.data.group_id)
1433
+ };
1434
+ }
1435
+ /**
1436
+ * Resolve the calendar program id for `workout_build` / `coach workout build`: either an
1437
+ * explicit team/group `programId`, or a roster `athleteId` (+ date) via
1438
+ * `fetchCoachAthleteCalendar`. Exactly one of programId / athleteId is required.
1439
+ */
1440
+ async function resolveBuildProgramId(client, args) {
1441
+ if (args.programId !== void 0 && args.athleteId !== void 0) throw new Error("Pass programId or athleteId, not both.");
1442
+ if (args.programId !== void 0) return args.programId;
1443
+ if (args.athleteId === void 0) throw new Error("Provide programId (team calendar) or athleteId (athlete calendar).");
1444
+ if (args.date === void 0) throw new Error("athleteId requires date (YYYY-M-D) to resolve the athlete calendar.");
1445
+ const [y, m] = parseWorkoutDate(args.date);
1446
+ return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
1447
+ }
1448
+ //#endregion
1368
1449
  //#region ../js/src/exercise-set-payload.ts
1369
1450
  function slotData(exercise, key) {
1370
1451
  const value = exercise?.[key];
@@ -2318,8 +2399,10 @@ function unitAdvisory(blockTitle, ex, defaults) {
2318
2399
  if (ex.weight !== void 0 && ex.weight !== null) {
2319
2400
  const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2320
2401
  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).`);
2402
+ if (sentP2 !== effP2) {
2403
+ 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.`);
2404
+ else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2405
+ }
2323
2406
  }
2324
2407
  return {
2325
2408
  notes,
@@ -2366,7 +2449,7 @@ async function collectAdvisories(blocks, index) {
2366
2449
  function calendarWriteError(method, path, status, detail) {
2367
2450
  const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
2368
2451
  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.`);
2452
+ return /* @__PURE__ */ new Error(`${base}. This often means the programId is not a coach-writable calendar — use a team/group programId (list_teams → group_program) or resolve a roster athlete's calendar via GET /v5/calendars/athletes/{athleteId}?year=&month= (workout_build athleteId). Athlete-created personal_cal ad-hoc sessions are a different surface.`);
2370
2453
  }
2371
2454
  async function req(client, method, path, body) {
2372
2455
  const res = await client.request(method, path, body === void 0 ? void 0 : { body });
@@ -2553,6 +2636,36 @@ async function inviteAthletes(client, args) {
2553
2636
  };
2554
2637
  }
2555
2638
  /**
2639
+ * Update a team's title and/or reassign its calendar (`PUT /v5/teams/{teamId}`).
2640
+ *
2641
+ * The live API accepts `group_program` to point the team at an existing parent program /
2642
+ * calendar (e.g. another team's `group_program` from `list_teams`), but rejects a body that
2643
+ * has only `group_program` (HTTP 400 "Invalid parameters"). When `title` is omitted we read
2644
+ * the current title first so callers can re-link without renaming.
2645
+ */
2646
+ async function updateTeam(client, args) {
2647
+ if (args.title === void 0 && args.groupProgram === void 0) throw new Error("Provide title and/or groupProgram.");
2648
+ let title = args.title;
2649
+ if (title === void 0) {
2650
+ const existing = await client.request("GET", `/v5/teams/${args.teamId}`);
2651
+ if (!existing.ok) {
2652
+ const detail = typeof existing.data === "string" ? existing.data : JSON.stringify(existing.data);
2653
+ throw new Error(`GET /v5/teams/${args.teamId} failed (HTTP ${existing.status}): ${detail}`);
2654
+ }
2655
+ const rec = existing.data && typeof existing.data === "object" ? existing.data : null;
2656
+ title = typeof rec?.title === "string" ? rec.title : "";
2657
+ if (title.trim() === "") throw new Error(`Could not read current title for team ${args.teamId}; pass title explicitly.`);
2658
+ }
2659
+ const body = { title };
2660
+ if (args.groupProgram !== void 0) body.group_program = args.groupProgram;
2661
+ const res = await client.request("PUT", `/v5/teams/${args.teamId}`, { body });
2662
+ if (!res.ok) {
2663
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2664
+ throw new Error(`PUT /v5/teams/${args.teamId} failed (HTTP ${res.status}): ${detail}`);
2665
+ }
2666
+ return res.data;
2667
+ }
2668
+ /**
2556
2669
  * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2557
2670
  * The API wants the target date as a structured object (with weekday and an isToday flag),
2558
2671
  * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
@@ -3372,7 +3485,7 @@ Coach — manage a roster (needs a coach account):
3372
3485
 
3373
3486
  teams & join codes:
3374
3487
  coach team-create --title "..."
3375
- coach team-update --team <id> --title "..."
3488
+ coach team-update --team <id> [--title "..."] [--group-program <id>]
3376
3489
  coach team-delete --team <id> --yes
3377
3490
  coach team-code-create --team <id> [--type N]
3378
3491
  coach team-code-delete --code <id> --yes (--code is the id from team-code-create, not the join-code number)
@@ -3398,7 +3511,7 @@ Coach — manage a roster (needs a coach account):
3398
3511
 
3399
3512
  workouts (spec: {"blocks":[{"title","exercises":[{"id","sets"?,"reps"?,"weight"?,"rpe"?}]}],"instruction"?};
3400
3513
  reps/weight may be a scalar or per-set array; omit --publish to leave a draft):
3401
- coach workout build --program <id> (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
3514
+ coach workout build (--program <id> | --athlete <id>) (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
3402
3515
  coach workout read --program <id> --date Y-M-D --pw <id>
3403
3516
  coach workout publish --pw <id> --yes
3404
3517
  coach workout remove --program <id> --pw <id> --yes
@@ -3545,42 +3658,57 @@ async function cmdExercise(client, rest) {
3545
3658
  default: return fail("usage: trainheroic coach exercise <resolve|search|get|sync|create|forget|stats>");
3546
3659
  }
3547
3660
  }
3661
+ async function cmdWorkoutBuild(client, a) {
3662
+ const { values, positionals } = parse(a, {
3663
+ program: { type: "string" },
3664
+ athlete: { type: "string" },
3665
+ date: { type: "string" },
3666
+ "timeline-day": { type: "string" },
3667
+ publish: { type: "boolean" },
3668
+ yes: { type: "boolean" },
3669
+ file: { type: "string" }
3670
+ });
3671
+ const usage = "coach workout build (--program <id> | --athlete <id>) (--date Y-M-D | --timeline-day <n>) ...";
3672
+ const programRaw = values.program;
3673
+ const athleteRaw = values.athlete;
3674
+ if (values.date === void 0 && values["timeline-day"] === void 0) fail("provide --date YYYY-M-D or --timeline-day <n>.");
3675
+ let programId;
3676
+ try {
3677
+ programId = await resolveBuildProgramId(client, {
3678
+ ...programRaw !== void 0 ? { programId: toInt(programRaw, "--program") } : {},
3679
+ ...athleteRaw !== void 0 ? { athleteId: toInt(athleteRaw, "--athlete") } : {},
3680
+ ...values.date !== void 0 ? { date: values.date } : {}
3681
+ });
3682
+ } catch (err) {
3683
+ fail(err instanceof Error ? `${usage}: ${err.message}` : String(err));
3684
+ }
3685
+ const parsed = await jsonInput(positionals[0], values.file);
3686
+ const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec", "run 'trainheroic skill' for the workout spec format and copy-paste examples.");
3687
+ const publish = values.publish === true;
3688
+ if (publish && values.yes !== true) fail("publishing is athlete-facing; add --yes to build and publish.");
3689
+ const opts = {
3690
+ programId,
3691
+ blocks: spec.blocks,
3692
+ publish
3693
+ };
3694
+ if (values.date !== void 0) opts.date = parseWorkoutDate(values.date);
3695
+ if (values["timeline-day"] !== void 0) opts.timelineDay = toInt(values["timeline-day"], "--timeline-day");
3696
+ if (spec.instruction !== void 0) opts.instruction = spec.instruction;
3697
+ const advice = await collectAdvisories(spec.blocks, library(client));
3698
+ const built = await buildSession(client, opts);
3699
+ const readback = opts.date ? await readSession(client, programId, opts.date, built.pwId) : null;
3700
+ return out({
3701
+ ...built,
3702
+ programId,
3703
+ published: publish,
3704
+ advisories: advice,
3705
+ readback
3706
+ });
3707
+ }
3548
3708
  async function cmdWorkout(client, rest) {
3549
3709
  const [sub, ...a] = rest;
3550
3710
  switch (sub) {
3551
- case "build": {
3552
- const { values, positionals } = parse(a, {
3553
- program: { type: "string" },
3554
- date: { type: "string" },
3555
- "timeline-day": { type: "string" },
3556
- publish: { type: "boolean" },
3557
- yes: { type: "boolean" },
3558
- file: { type: "string" }
3559
- });
3560
- const programId = toInt(need(values.program, "coach workout build --program <id> ..."), "--program");
3561
- if (values.date === void 0 && values["timeline-day"] === void 0) fail("provide --date YYYY-M-D or --timeline-day <n>.");
3562
- const parsed = await jsonInput(positionals[0], values.file);
3563
- const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec", "run 'trainheroic skill' for the workout spec format and copy-paste examples.");
3564
- const publish = values.publish === true;
3565
- if (publish && values.yes !== true) fail("publishing is athlete-facing; add --yes to build and publish.");
3566
- const opts = {
3567
- programId,
3568
- blocks: spec.blocks,
3569
- publish
3570
- };
3571
- if (values.date !== void 0) opts.date = parseWorkoutDate(values.date);
3572
- if (values["timeline-day"] !== void 0) opts.timelineDay = toInt(values["timeline-day"], "--timeline-day");
3573
- if (spec.instruction !== void 0) opts.instruction = spec.instruction;
3574
- const advice = await collectAdvisories(spec.blocks, library(client));
3575
- const built = await buildSession(client, opts);
3576
- const readback = opts.date ? await readSession(client, programId, opts.date, built.pwId) : null;
3577
- return out({
3578
- ...built,
3579
- published: publish,
3580
- advisories: advice,
3581
- readback
3582
- });
3583
- }
3711
+ case "build": return cmdWorkoutBuild(client, a);
3584
3712
  case "read": {
3585
3713
  const { values } = parse(a, {
3586
3714
  program: { type: "string" },
@@ -4170,14 +4298,20 @@ async function cmdCoachTeamCreate(client, a) {
4170
4298
  return out(await mutate(client, "POST", "/1.0/coach/team/createWithTitleAndCode", { title: need(values.title, "coach team-create --title \"...\"") }));
4171
4299
  }
4172
4300
  async function cmdCoachTeamUpdate(client, a) {
4173
- const usage = "coach team-update --team <id> --title \"...\"";
4301
+ const usage = "coach team-update --team <id> [--title \"...\"] [--group-program <id>] (at least one of --title / --group-program)";
4174
4302
  const { values } = parse(a, {
4175
4303
  team: { type: "string" },
4176
- title: { type: "string" }
4304
+ title: { type: "string" },
4305
+ "group-program": { type: "string" }
4177
4306
  });
4178
4307
  const teamId = toInt(need(values.team, usage), "--team");
4179
- const title = need(values.title, usage);
4180
- return out(await mutate(client, "PUT", `/v5/teams/${teamId}`, { title }));
4308
+ const title = values.title;
4309
+ const groupProgramRaw = values["group-program"];
4310
+ if (title === void 0 && groupProgramRaw === void 0) fail(usage);
4311
+ const args = { teamId };
4312
+ if (title !== void 0) args.title = title;
4313
+ if (groupProgramRaw !== void 0) args.groupProgram = toInt(groupProgramRaw, "--group-program");
4314
+ return out(await updateTeam(client, args));
4181
4315
  }
4182
4316
  async function cmdCoachTeamDelete(client, a) {
4183
4317
  const usage = "coach team-delete --team <id> --yes";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "2.0.2",
3
+ "version": "2.1.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,13 +21,13 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/js": "2.0.2",
25
- "@trainheroic-unofficial/dto": "2.0.2"
24
+ "@trainheroic-unofficial/dto": "2.1.1",
25
+ "@trainheroic-unofficial/js": "2.1.1"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.1.2",
28
+ "@types/node": "^26.2.0",
29
29
  "tsdown": "^0.22.14",
30
- "tsx": "^4.23.4",
30
+ "tsx": "^4.23.11",
31
31
  "typescript": "^7.0.2",
32
32
  "vitest": "^4.1.10"
33
33
  },
@@ -373,7 +373,7 @@ Deletes a custom exercise. No request body needed. Only works on exercises where
373
373
  | POST | `/v5/sessions/template` | **Create session template** (library) |
374
374
  | DELETE | `/v5/sessions/template/{sessionId}` | **Delete session template** |
375
375
  | POST | `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/{programId}/{day}/null` | **Create session in program** (timeline) |
376
- | POST | `/2.0/coach/calendar/workout/createWorkoutForDay/{calendarId}/{year}/{month}/{day}/0` | **Create session on team calendar date** |
376
+ | POST | `/2.0/coach/calendar/workout/createWorkoutForDay/{calendarId}/{year}/{month}/{day}/0` | **Create session on calendar date** (team or athlete calendar) |
377
377
  | POST | `/2.0/coach/calendar/saveProgramWorkoutSets` | **Add block to session** |
378
378
  | POST | `/2.0/coach/calendar/saveWorkoutSetExercises` | **Add exercise to block** (with prescription) |
379
379
  | POST | `/2.0/coach/calendar/programWorkout/publish` | **Publish session** |
@@ -993,32 +993,33 @@ Returns all available analytics categories and their instances:
993
993
 
994
994
  These are used by the mobile app / athlete-facing client (documented in `train-heroic-schema.yml`):
995
995
 
996
- | Method | Endpoint | Description |
997
- | ------ | ------------------------------------------------------- | ---------------------------------------------- |
998
- | POST | `/auth` | Login |
999
- | GET | `/v5/users/exercises/history` | All exercise history |
1000
- | GET | `/v5/users/exercises/recent` | Recent exercises |
1001
- | GET | `/v5/exercises/{id}/history` | Single exercise history |
1002
- | GET | `/v5/exercises/{id}` | Exercise details |
1003
- | GET | `/v5/exercises/{id}/personalRecords` | Exercise PRs |
1004
- | GET | `/v5/exercises/{id}/stats` | Exercise stats |
1005
- | GET | `/v5/exercises/{id}/stackUp/isSupportedExercise` | Stack-up support check |
1006
- | GET | `/v5/users/circuits/recent` | Recent circuits |
1007
- | GET | `/v5/users/circuits/history` | Circuit history |
1008
- | GET | `/3.0/athlete/programworkout/range?startDate=&endDate=` | Workouts by date range |
1009
- | GET | `/1.0/athlete/programming/programs` | Athlete programs |
1010
- | GET | `/v5/users/{id}` | User profile |
1011
- | GET | `/1.0/athlete/prefs` | Athlete preferences |
1012
- | GET | `/2.0/athlete/workingMax` | Working maxes (all exercises with WM tracking) |
1013
- | GET | `/1.0/athlete/savedworkoutset/{id}` | Saved workout set |
1014
- | GET | `/1.0/athlete/savedworkout/{id}` | Saved workout |
1015
- | GET | `/1.0/user/userInfo` | User info |
1016
- | GET | `/v5/calendars/athletes/{id}/coachAthleteTeam` | Coach-athlete team calendar |
1017
- | GET | `/v5/users/{id}/workingMaxes/{id1}` | Specific working max |
1018
- | GET | `/v5/programs/new` | New programs |
1019
- | GET | `/v5/programs/free` | Free programs |
1020
- | GET | `/v5/athleteProfile/summary` | Athlete profile summary |
1021
- | GET | `/3.0/athlete/leaderboard/{id}` | Leaderboard |
996
+ | Method | Endpoint | Description |
997
+ | ------ | ------------------------------------------------------- | ---------------------------------------------------------- |
998
+ | POST | `/auth` | Login |
999
+ | GET | `/v5/users/exercises/history` | All exercise history |
1000
+ | GET | `/v5/users/exercises/recent` | Recent exercises |
1001
+ | GET | `/v5/exercises/{id}/history` | Single exercise history |
1002
+ | GET | `/v5/exercises/{id}` | Exercise details |
1003
+ | GET | `/v5/exercises/{id}/personalRecords` | Exercise PRs |
1004
+ | GET | `/v5/exercises/{id}/stats` | Exercise stats |
1005
+ | GET | `/v5/exercises/{id}/stackUp/isSupportedExercise` | Stack-up support check |
1006
+ | GET | `/v5/users/circuits/recent` | Recent circuits |
1007
+ | GET | `/v5/users/circuits/history` | Circuit history |
1008
+ | GET | `/3.0/athlete/programworkout/range?startDate=&endDate=` | Workouts by date range |
1009
+ | GET | `/1.0/athlete/programming/programs` | Athlete programs |
1010
+ | GET | `/v5/users/{id}` | User profile |
1011
+ | GET | `/1.0/athlete/prefs` | Athlete preferences |
1012
+ | GET | `/2.0/athlete/workingMax` | Working maxes (all exercises with WM tracking) |
1013
+ | GET | `/1.0/athlete/savedworkoutset/{id}` | Saved workout set |
1014
+ | GET | `/1.0/athlete/savedworkout/{id}` | Saved workout |
1015
+ | GET | `/1.0/user/userInfo` | User info |
1016
+ | GET | `/v5/calendars/athletes/{id}?year=&month=` | **Athlete coach calendar** (program id for CREATE SESSION) |
1017
+ | GET | `/v5/calendars/athletes/{id}/coachAthleteTeam` | Coach-athlete team calendar |
1018
+ | GET | `/v5/users/{id}/workingMaxes/{id1}` | Specific working max |
1019
+ | GET | `/v5/programs/new` | New programs |
1020
+ | GET | `/v5/programs/free` | Free programs |
1021
+ | GET | `/v5/athleteProfile/summary` | Athlete profile summary |
1022
+ | GET | `/3.0/athlete/leaderboard/{id}` | Leaderboard |
1022
1023
 
1023
1024
  ---
1024
1025
 
@@ -1320,16 +1321,22 @@ Saves an existing session as a reusable template in the session library. No requ
1320
1321
 
1321
1322
  #### `PUT /v5/teams/{teamId}`
1322
1323
 
1323
- Updates team properties like title.
1324
+ Updates team properties. `title` is required by the API (HTTP 400 without it). Optional
1325
+ `group_program` re-points the team at an existing parent program/calendar (e.g. another
1326
+ team's `group_program` from `GET /1.0/coach/teams`).
1324
1327
 
1325
1328
  **Request body:**
1326
1329
 
1327
1330
  ```json
1328
1331
  {
1329
- "title": "New Team Name"
1332
+ "title": "New Team Name",
1333
+ "group_program": 4713234
1330
1334
  }
1331
1335
  ```
1332
1336
 
1337
+ `team_create` always auto-creates a calendar; to attach a new team to an existing calendar,
1338
+ create the team then `team_update` / `coach team-update --group-program <id>`.
1339
+
1333
1340
  #### `POST /1.0/coach/team/updatePublishSettings`
1334
1341
 
1335
1342
  Updates the auto-publish settings for a team's program. Takes the full program object with `pub_*` fields controlling auto-publish behavior.