@trainheroic-unofficial/js 0.6.3 → 0.6.5

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/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
2
- import { Advisory, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, WorkoutDate } from "@trainheroic-unofficial/dto";
2
+ import { Advisory, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, WorkoutDate } from "@trainheroic-unofficial/dto";
3
3
  import { ZodType } from "zod";
4
4
  export * from "@trainheroic-unofficial/dto";
5
5
 
@@ -133,6 +133,20 @@ declare function resolveAthleteUserId(client: TrainHeroicClient): Promise<number
133
133
  /** Lifetime training totals. `use_metric` is required by the API (omitting it 400s). */
134
134
  declare function fetchAthleteProfileSummary(client: TrainHeroicClient, userId: number, useMetric?: boolean): Promise<AthleteProfileSummary>;
135
135
  declare function fetchAthleteUser(client: TrainHeroicClient, userId: number): Promise<AthleteUser>;
136
+ /**
137
+ * Sort a roster-activity list most-recently-active first; never-logged rows (null date) last.
138
+ * Athletes tied on lastLoggedDate break by session count (more sessions first), so a tie is not
139
+ * left to arbitrary input order.
140
+ */
141
+ declare function sortRosterByRecency(rows: readonly RosterActivityRow[]): RosterActivityRow[];
142
+ /**
143
+ * A coach's roster-activity ranking: each athlete's all-time training snapshot (session count,
144
+ * first/last logged date, total reps/volume), sorted most-recently-active first. There is no
145
+ * single roster-activity endpoint, so this fans out `/v5/athleteProfile/summary` per athlete with
146
+ * a small concurrency cap; pass the subset you care about for a large org. A failed or missing
147
+ * summary becomes a null-data row (sorted last), not an error.
148
+ */
149
+ declare function fetchRosterActivity(client: TrainHeroicClient, athleteIds: readonly number[], useMetric?: boolean): Promise<RosterActivityRow[]>;
136
150
  declare function fetchAthletePrefs(client: TrainHeroicClient): Promise<AthletePrefs>;
137
151
  declare function fetchWorkingMaxes(client: TrainHeroicClient): Promise<AthleteWorkingMax[]>;
138
152
  declare function fetchExerciseHistoryList(client: TrainHeroicClient): Promise<ExerciseHistoryListItem[]>;
@@ -144,6 +158,13 @@ declare function fetchPersonalRecords(client: TrainHeroicClient, exerciseId: num
144
158
  declare function fetchExerciseStats(client: TrainHeroicClient, exerciseId: number, userId: number, date: string): Promise<ExerciseStats>;
145
159
  /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
146
160
  declare function fetchAthleteWorkouts(client: TrainHeroicClient, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
161
+ /**
162
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
163
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
164
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
165
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
166
+ */
167
+ declare function fetchCoachAthleteWorkouts(client: TrainHeroicClient, athleteId: number, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
147
168
  /**
148
169
  * A coach's month view of a roster athlete's logged sessions
149
170
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
@@ -165,6 +186,29 @@ declare function fetchLeaderboard(client: TrainHeroicClient, workoutId: number,
165
186
  */
166
187
  declare function presentAthleteWorkout(raw: ProgramWorkout): AthleteWorkoutView;
167
188
  declare function presentAthleteWorkouts(list: readonly ProgramWorkout[]): AthleteWorkoutView[];
189
+ /** The minimal id scaffold `log-set` / `logForAthlete` needs for one saved workout set. */
190
+ type LogSetTarget = {
191
+ date: string;
192
+ workoutTitle: string; /** The id for `--set` (logAthleteSet/logForAthlete `savedWorkoutSetId`). */
193
+ savedWorkoutSetId: number;
194
+ setTitle: string | null;
195
+ exercises: Array<{
196
+ /** The id for each result's `savedWorkoutSetExerciseId`. */savedWorkoutSetExerciseId: number;
197
+ title: string;
198
+ units: ReturnType<typeof exerciseUnits>;
199
+ prescribed: string[];
200
+ performed: string[];
201
+ }>;
202
+ };
203
+ /**
204
+ * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
205
+ * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
206
+ * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
207
+ * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
208
+ * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
209
+ * with no resolvable id.
210
+ */
211
+ declare function presentLogTargets(list: readonly ProgramWorkout[]): LogSetTarget[];
168
212
  /**
169
213
  * Narrow a presented workout list for the common "what did I actually do" reads. `loggedOnly`
170
214
  * keeps only workouts the athlete logged a set on (the reliable signal, not the API's
@@ -269,6 +313,25 @@ declare function logAthleteSet(client: TrainHeroicClient, args: {
269
313
  savedWorkoutSetId: number;
270
314
  exercisesLogged: number;
271
315
  }>;
316
+ /**
317
+ * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
318
+ * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
319
+ * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
320
+ * contract as {@link logAthleteSet}; the bodies are identical except each is stamped with
321
+ * `athleteId`. The day is located through the coach range endpoint for that athlete.
322
+ *
323
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only for results and return 401 on the
324
+ * data-write step; real (invited) athletes accept it.
325
+ */
326
+ declare function logForAthlete(client: TrainHeroicClient, args: {
327
+ athleteId: number;
328
+ date: string;
329
+ savedWorkoutSetId: number;
330
+ results: readonly SetResult[];
331
+ }): Promise<{
332
+ savedWorkoutSetId: number;
333
+ exercisesLogged: number;
334
+ }>;
272
335
  type PersonalWorkoutCreated = {
273
336
  programWorkoutId: number;
274
337
  workoutId: number;
@@ -297,6 +360,77 @@ declare function addExercisesToWorkout(client: TrainHeroicClient, workoutId: num
297
360
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
298
361
  declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
299
362
  //#endregion
363
+ //#region src/coach.d.ts
364
+ declare const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
365
+ /**
366
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
367
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
368
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
369
+ */
370
+ declare function inviteAthletes(client: TrainHeroicClient, args: {
371
+ teamId: number;
372
+ emails: readonly string[];
373
+ message?: string;
374
+ }): Promise<{
375
+ teamId: number;
376
+ invited: string[];
377
+ result: unknown;
378
+ }>;
379
+ /**
380
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
381
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
382
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
383
+ */
384
+ declare function copySession(client: TrainHeroicClient, args: {
385
+ toProgramId: number;
386
+ pwId: number;
387
+ toDate: string;
388
+ }): Promise<unknown>;
389
+ declare const ANALYTICS_METRIC_KEYS: readonly ["readiness-team", "readiness-athlete", "lift-1rm-history", "training-summary-athlete", "compliance-team", "lift-progress-team", "working-max-history"];
390
+ type AnalyticsMetric = (typeof ANALYTICS_METRIC_KEYS)[number];
391
+ /**
392
+ * A serializable description of every analytics metric: its scope (does it need a `teamId` or
393
+ * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
394
+ * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
395
+ * shape by trial and error. These curated keys are deliberately NOT the raw category names from
396
+ * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
397
+ */
398
+ declare function analyticsMetricCatalog(): Array<{
399
+ metric: AnalyticsMetric;
400
+ scope: "team" | "user";
401
+ scopeParam: "teamId" | "userIds";
402
+ requires: string[];
403
+ optional: string[];
404
+ }>;
405
+ type AnalyticsQueryArgs = {
406
+ metric: AnalyticsMetric;
407
+ teamId?: number;
408
+ userIds?: readonly number[];
409
+ exerciseId?: number;
410
+ date?: string;
411
+ dateStart?: string;
412
+ dateEnd?: string;
413
+ useMetric?: boolean;
414
+ };
415
+ /**
416
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
417
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
418
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
419
+ */
420
+ declare function queryAnalytics(client: TrainHeroicClient, args: AnalyticsQueryArgs): Promise<unknown>;
421
+ //#endregion
422
+ //#region src/util.d.ts
423
+ /**
424
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
425
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
426
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
427
+ * optional ones lose `undefined` from their value type.
428
+ *
429
+ * Example:
430
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
431
+ */
432
+ declare function definedProps<T extends object>(obj: T): { [K in keyof T]: Exclude<T[K], undefined> };
433
+ //#endregion
300
434
  //#region src/workout-encode.d.ts
301
435
  declare const LEADERBOARD_TYPE: Readonly<Record<string, number>>;
302
436
  declare const LEADERBOARD_LABEL: Readonly<Record<number, string>>;
@@ -386,4 +520,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
386
520
  stats(): Promise<Record<string, unknown>>;
387
521
  }
388
522
  //#endregion
389
- export { AddedExercise, ApiBase, BuildOptions, ClientResult, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SetResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, createPersonalWorkout, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, isRecord, logAthleteSet, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, publishSession, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
523
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, BuildOptions, ClientResult, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSetTarget, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SetResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAthleteSet, logForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { exerciseLibraryResponseSchema, exerciseResponseSchema, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
1
+ import { exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
2
  export * from "@trainheroic-unofficial/dto";
3
3
  //#region src/auth.ts
4
4
  const AUTH_URL = "https://apis.trainheroic.com/auth";
@@ -321,6 +321,62 @@ function fetchAthleteProfileSummary(client, userId, useMetric = false) {
321
321
  function fetchAthleteUser(client, userId) {
322
322
  return getJson(client, `/v5/users/${userId}`, "athlete user");
323
323
  }
324
+ /**
325
+ * Sort a roster-activity list most-recently-active first; never-logged rows (null date) last.
326
+ * Athletes tied on lastLoggedDate break by session count (more sessions first), so a tie is not
327
+ * left to arbitrary input order.
328
+ */
329
+ function sortRosterByRecency(rows) {
330
+ return [...rows].sort((a, b) => {
331
+ if (a.lastLoggedDate !== b.lastLoggedDate) {
332
+ if (a.lastLoggedDate === null) return 1;
333
+ if (b.lastLoggedDate === null) return -1;
334
+ return a.lastLoggedDate < b.lastLoggedDate ? 1 : -1;
335
+ }
336
+ return (b.sessionsCount ?? 0) - (a.sessionsCount ?? 0);
337
+ });
338
+ }
339
+ /**
340
+ * A coach's roster-activity ranking: each athlete's all-time training snapshot (session count,
341
+ * first/last logged date, total reps/volume), sorted most-recently-active first. There is no
342
+ * single roster-activity endpoint, so this fans out `/v5/athleteProfile/summary` per athlete with
343
+ * a small concurrency cap; pass the subset you care about for a large org. A failed or missing
344
+ * summary becomes a null-data row (sorted last), not an error.
345
+ */
346
+ async function fetchRosterActivity(client, athleteIds, useMetric = false) {
347
+ const rows = [];
348
+ const concurrency = 6;
349
+ for (let i = 0; i < athleteIds.length; i += concurrency) {
350
+ const chunk = athleteIds.slice(i, i + concurrency);
351
+ const settled = await Promise.all(chunk.map(async (id) => {
352
+ try {
353
+ return {
354
+ id,
355
+ summary: await fetchAthleteProfileSummary(client, id, useMetric)
356
+ };
357
+ } catch {
358
+ return {
359
+ id,
360
+ summary: null
361
+ };
362
+ }
363
+ }));
364
+ for (const { id, summary } of settled) {
365
+ const count = summary?.sessions_count ?? null;
366
+ const hasSessions = count !== null && count > 0;
367
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
368
+ rows.push({
369
+ athleteId: id,
370
+ sessionsCount: count,
371
+ firstLoggedDate: normDate(summary?.first_logged_date),
372
+ lastLoggedDate: normDate(summary?.last_logged_date),
373
+ totalReps: summary?.reps_sum ?? null,
374
+ totalVolume: summary?.volume_sum ?? null
375
+ });
376
+ }
377
+ }
378
+ return sortRosterByRecency(rows);
379
+ }
324
380
  function fetchAthletePrefs(client) {
325
381
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
326
382
  }
@@ -349,6 +405,15 @@ function fetchAthleteWorkouts(client, startDate, endDate) {
349
405
  return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
350
406
  }
351
407
  /**
408
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
409
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
410
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
411
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
412
+ */
413
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
414
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
415
+ }
416
+ /**
352
417
  * A coach's month view of a roster athlete's logged sessions
353
418
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
354
419
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
@@ -531,6 +596,50 @@ function presentAthleteWorkouts(list) {
531
596
  return list.map(presentAthleteWorkout);
532
597
  }
533
598
  /**
599
+ * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
600
+ * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
601
+ * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
602
+ * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
603
+ * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
604
+ * with no resolvable id.
605
+ */
606
+ function presentLogTargets(list) {
607
+ const targets = [];
608
+ for (const pw of list) {
609
+ const rec = pw;
610
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
611
+ const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
612
+ if (!saved) continue;
613
+ const date = str$1(rec.date) ?? "";
614
+ const workoutTitle = str$1(rec.workout_title) ?? "";
615
+ const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
616
+ for (const s of sets) {
617
+ if (!isRecord(s)) continue;
618
+ const savedWorkoutSetId = coerceInt(s.id);
619
+ if (savedWorkoutSetId === null) continue;
620
+ const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
621
+ const id = coerceInt(ex.id);
622
+ if (id === null) return null;
623
+ return {
624
+ savedWorkoutSetExerciseId: id,
625
+ title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
626
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
627
+ prescribed: prescribedSets(ex),
628
+ performed: performedSets(ex)
629
+ };
630
+ }).filter((e) => e !== null);
631
+ targets.push({
632
+ date,
633
+ workoutTitle,
634
+ savedWorkoutSetId,
635
+ setTitle: str$1(s.title),
636
+ exercises
637
+ });
638
+ }
639
+ }
640
+ return targets;
641
+ }
642
+ /**
534
643
  * Narrow a presented workout list for the common "what did I actually do" reads. `loggedOnly`
535
644
  * keeps only workouts the athlete logged a set on (the reliable signal, not the API's
536
645
  * completion flag). `limit` keeps the most recent N by date (newest first). Both are pure
@@ -648,6 +757,7 @@ function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
648
757
  * record so callers can build the set-completion PUT body via `buildSetCompletePayload`.
649
758
  */
650
759
  function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
760
+ const available = [];
651
761
  for (const pw of workouts) {
652
762
  const rec = pw;
653
763
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
@@ -656,18 +766,29 @@ function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
656
766
  const sets = Array.isArray(sw.workoutSets) ? sw.workoutSets : [];
657
767
  for (const s of sets) {
658
768
  if (!isRecord(s)) continue;
769
+ const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises.filter(isRecord) : [];
659
770
  if (coerceInt(s.id) === savedWorkoutSetId) {
660
771
  const savedWorkoutId = coerceInt(sw.id);
661
772
  if (!savedWorkoutId) continue;
662
773
  return {
663
774
  savedWorkoutId,
664
- exercises: Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises.filter(isRecord) : [],
775
+ exercises,
665
776
  rawSet: s
666
777
  };
667
778
  }
779
+ const setId = coerceInt(s.id);
780
+ if (setId !== null) {
781
+ const exLabels = exercises.map((ex) => {
782
+ const exId = coerceInt(ex.id);
783
+ const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
784
+ return exId === null ? null : `${exId} (${title})`;
785
+ }).filter((x) => x !== null);
786
+ available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
787
+ }
668
788
  }
669
789
  }
670
- throw new Error(`Saved workout set ${savedWorkoutSetId} not found on this date.`);
790
+ const hint = available.length > 0 ? ` Saved workout sets present on this date: ${available.join("; ")}. Pass a "set N" id to --set (the savedWorkoutSetId), and the matching "exercise id" as savedWorkoutSetExerciseId in the results.` : " No saved workout is scheduled on this date — log against a date that has a workout (find it via athlete-workouts / coach athlete-workouts).";
791
+ throw new Error(`Saved workout set ${savedWorkoutSetId} not found on this date.${hint}`);
671
792
  }
672
793
  /**
673
794
  * Build the body for `PUT /1.0/athlete/savedworkoutset/{id}` that marks the set completed.
@@ -724,23 +845,69 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
724
845
  * by the respective PUT bodies.
725
846
  */
726
847
  async function logAthleteSet(client, args) {
727
- const { exercises, rawSet } = findSavedWorkoutSet(await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId);
848
+ return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
849
+ }
850
+ /**
851
+ * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
852
+ * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
853
+ * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
854
+ * contract as {@link logAthleteSet}; the bodies are identical except each is stamped with
855
+ * `athleteId`. The day is located through the coach range endpoint for that athlete.
856
+ *
857
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only for results and return 401 on the
858
+ * data-write step; real (invited) athletes accept it.
859
+ */
860
+ async function logForAthlete(client, args) {
861
+ const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
862
+ return writeSetResults(client, {
863
+ role: "coach",
864
+ athleteId: args.athleteId
865
+ }, workouts, args.savedWorkoutSetId, args.results);
866
+ }
867
+ /**
868
+ * Shared two-step set-log write behind {@link logAthleteSet} and {@link logForAthlete}.
869
+ * `target` selects the surface: `athlete` writes `/1.0/athlete/...`; `coach` writes
870
+ * `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body. Step 1 PUTs each
871
+ * exercise's entered data to its own endpoint (the only path that actually stores reps and
872
+ * weight). Step 2 marks the set completed; that body needs the app's camelCase in-memory
873
+ * shape and the full list of savedWorkoutSetExercise IDs in the set (not only the logged ones).
874
+ */
875
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
876
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
877
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
878
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
728
879
  let exercisesLogged = 0;
729
- for (const result of args.results) {
880
+ for (const result of results) {
730
881
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
731
- if (!ex) throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${args.savedWorkoutSetId}.`);
882
+ if (!ex) {
883
+ const valid = exercises.map((e) => {
884
+ const id = coerceInt(e.id);
885
+ const title = typeof e.exercise_title === "string" && e.exercise_title || typeof e.title === "string" && e.title || "exercise";
886
+ return id === null ? null : `${id} (${title})`;
887
+ }).filter((x) => x !== null);
888
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
889
+ }
732
890
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
733
891
  if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
734
- const body = buildExerciseLogPayload(result.savedWorkoutSetExerciseId, args.savedWorkoutSetId, workoutSetExerciseId, result.sets);
735
- const res = await client.request("PUT", `/1.0/athlete/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}`, { body });
736
- if (!res.ok) throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).`);
892
+ const body = {
893
+ ...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
894
+ ...extra
895
+ };
896
+ const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
897
+ if (!res.ok) {
898
+ const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for results — TrainHeroic's seeded demo/sample athletes return ${res.status} here; results only persist for real (invited) athletes.` : "";
899
+ throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
900
+ }
737
901
  exercisesLogged += 1;
738
902
  }
739
- const setBody = buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true);
740
- const setRes = await client.request("PUT", `/1.0/athlete/savedworkoutset/${args.savedWorkoutSetId}`, { body: setBody });
741
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${args.savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
903
+ const setBody = {
904
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
905
+ ...extra
906
+ };
907
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
908
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
742
909
  return {
743
- savedWorkoutSetId: args.savedWorkoutSetId,
910
+ savedWorkoutSetId,
744
911
  exercisesLogged
745
912
  };
746
913
  }
@@ -804,6 +971,219 @@ function presentExerciseHistory(detail) {
804
971
  };
805
972
  }
806
973
  //#endregion
974
+ //#region src/coach.ts
975
+ const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
976
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
977
+ function emailList(emails) {
978
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
979
+ }
980
+ /**
981
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
982
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
983
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
984
+ */
985
+ async function inviteAthletes(client, args) {
986
+ const list = emailList(args.emails);
987
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
988
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
989
+ if (!validation.ok) {
990
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
991
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
992
+ }
993
+ const valid = Array.isArray(validation.data) ? validation.data : list;
994
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
995
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
996
+ teamType: 0,
997
+ teamId: args.teamId,
998
+ orgId: null,
999
+ emails: valid,
1000
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
1001
+ } });
1002
+ if (!invite.ok) {
1003
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1004
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
1005
+ }
1006
+ return {
1007
+ teamId: args.teamId,
1008
+ invited: valid,
1009
+ result: invite.data
1010
+ };
1011
+ }
1012
+ /**
1013
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
1014
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
1015
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
1016
+ */
1017
+ async function copySession(client, args) {
1018
+ const [year, month, day] = parseWorkoutDate(args.toDate);
1019
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1020
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1021
+ const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1022
+ toProgramId: args.toProgramId,
1023
+ pwId: args.pwId,
1024
+ toDate: {
1025
+ date: iso,
1026
+ day,
1027
+ month,
1028
+ year,
1029
+ dayOfWeek,
1030
+ isToday: false
1031
+ }
1032
+ } });
1033
+ if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
1034
+ return res.data;
1035
+ }
1036
+ const ANALYTICS_METRIC_KEYS = [
1037
+ "readiness-team",
1038
+ "readiness-athlete",
1039
+ "lift-1rm-history",
1040
+ "training-summary-athlete",
1041
+ "compliance-team",
1042
+ "lift-progress-team",
1043
+ "working-max-history"
1044
+ ];
1045
+ const ANALYTICS_METRICS = {
1046
+ "readiness-team": {
1047
+ path: "/v5/analytics/readiness/teams",
1048
+ scope: "team",
1049
+ inputs: ["date"],
1050
+ requires: ["date"]
1051
+ },
1052
+ "readiness-athlete": {
1053
+ path: "/v5/analytics/readiness/users",
1054
+ scope: "user",
1055
+ inputs: ["dateStart", "dateEnd"],
1056
+ requires: ["dateStart", "dateEnd"]
1057
+ },
1058
+ "lift-1rm-history": {
1059
+ path: "/v5/analytics/lift-one-rep-max-history/users",
1060
+ scope: "user",
1061
+ inputs: [
1062
+ "dateStart",
1063
+ "dateEnd",
1064
+ "exerciseId",
1065
+ "useMetric"
1066
+ ],
1067
+ requires: [
1068
+ "dateStart",
1069
+ "dateEnd",
1070
+ "exerciseId"
1071
+ ]
1072
+ },
1073
+ "training-summary-athlete": {
1074
+ path: "/v5/analytics/training-summary/users",
1075
+ scope: "user",
1076
+ inputs: ["dateStart", "dateEnd"],
1077
+ requires: ["dateStart", "dateEnd"]
1078
+ },
1079
+ "compliance-team": {
1080
+ path: "/v5/analytics/compliance",
1081
+ scope: "team",
1082
+ inputs: ["dateStart", "dateEnd"],
1083
+ requires: ["dateStart", "dateEnd"]
1084
+ },
1085
+ "lift-progress-team": {
1086
+ path: "/v5/analytics/lift-progress/teams",
1087
+ scope: "team",
1088
+ inputs: [
1089
+ "exerciseId",
1090
+ "dateStart",
1091
+ "dateEnd"
1092
+ ],
1093
+ requires: [
1094
+ "exerciseId",
1095
+ "dateStart",
1096
+ "dateEnd"
1097
+ ]
1098
+ },
1099
+ "working-max-history": {
1100
+ path: "/v5/analytics/working-max-history/users",
1101
+ scope: "user",
1102
+ inputs: [
1103
+ "exerciseId",
1104
+ "dateStart",
1105
+ "dateEnd",
1106
+ "useMetric"
1107
+ ],
1108
+ requires: ["exerciseId"]
1109
+ }
1110
+ };
1111
+ /**
1112
+ * A serializable description of every analytics metric: its scope (does it need a `teamId` or
1113
+ * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
1114
+ * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
1115
+ * shape by trial and error. These curated keys are deliberately NOT the raw category names from
1116
+ * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
1117
+ */
1118
+ function analyticsMetricCatalog() {
1119
+ return ANALYTICS_METRIC_KEYS.map((metric) => {
1120
+ const spec = ANALYTICS_METRICS[metric];
1121
+ return {
1122
+ metric,
1123
+ scope: spec.scope,
1124
+ scopeParam: spec.scope === "team" ? "teamId" : "userIds",
1125
+ requires: [...spec.requires],
1126
+ optional: spec.inputs.filter((i) => !spec.requires.includes(i))
1127
+ };
1128
+ });
1129
+ }
1130
+ const ANALYTICS_BODY_KEY = {
1131
+ date: "date",
1132
+ dateStart: "date_start",
1133
+ dateEnd: "date_end",
1134
+ exerciseId: "exercise_id",
1135
+ useMetric: "use_metric"
1136
+ };
1137
+ /**
1138
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
1139
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
1140
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
1141
+ */
1142
+ async function queryAnalytics(client, args) {
1143
+ const spec = ANALYTICS_METRICS[args.metric];
1144
+ const body = {};
1145
+ if (spec.scope === "team") {
1146
+ if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
1147
+ body.teamId = args.teamId;
1148
+ } else {
1149
+ if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
1150
+ body.user_ids = args.userIds.map((u) => String(u));
1151
+ }
1152
+ const inputs = {
1153
+ date: args.date,
1154
+ dateStart: args.dateStart,
1155
+ dateEnd: args.dateEnd,
1156
+ exerciseId: args.exerciseId,
1157
+ useMetric: args.useMetric
1158
+ };
1159
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
1160
+ if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
1161
+ for (const k of spec.inputs) {
1162
+ const v = inputs[k];
1163
+ if (v === void 0) continue;
1164
+ body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
1165
+ }
1166
+ const res = await client.request("POST", spec.path, { body });
1167
+ if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
1168
+ return res.data;
1169
+ }
1170
+ //#endregion
1171
+ //#region src/util.ts
1172
+ /**
1173
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
1174
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
1175
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
1176
+ * optional ones lose `undefined` from their value type.
1177
+ *
1178
+ * Example:
1179
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
1180
+ */
1181
+ function definedProps(obj) {
1182
+ const result = {};
1183
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
1184
+ return result;
1185
+ }
1186
+ //#endregion
807
1187
  //#region src/workout-encode.ts
808
1188
  const LEADERBOARD_TYPE = {
809
1189
  completion: 0,
@@ -1370,4 +1750,4 @@ var ExerciseLibrary = class {
1370
1750
  }
1371
1751
  };
1372
1752
  //#endregion
1373
- export { ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, createPersonalWorkout, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, isRecord, logAthleteSet, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, publishSession, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
1753
+ export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAthleteSet, logForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "zod": "^4.4.3",
30
- "@trainheroic-unofficial/dto": "0.6.3"
30
+ "@trainheroic-unofficial/dto": "0.6.5"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.0.0",