@trainheroic-unofficial/js 0.6.2 → 0.6.4

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, AthleteWorkoutView, BlockSpec, 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 month view of a roster athlete's logged sessions
163
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
164
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
165
+ * `userId` in each row is the roster athlete, not the calling coach.
166
+ */
167
+ declare function fetchCoachAthleteCalendarSummary(client: TrainHeroicClient, athleteId: number, year: number, month: number): Promise<unknown[]>;
147
168
  declare function fetchLeaderboard(client: TrainHeroicClient, workoutId: number, opts?: {
148
169
  page?: number;
149
170
  pageSize?: number;
@@ -168,6 +189,21 @@ declare function selectWorkouts(list: readonly AthleteWorkoutView[], opts?: {
168
189
  loggedOnly?: boolean;
169
190
  limit?: number;
170
191
  }): AthleteWorkoutView[];
192
+ /**
193
+ * Project presented workouts to compact headers (date/title/program + logged flag + exercise
194
+ * counts), dropping the per-set block detail. A dense multi-program week of full views can be
195
+ * tens of KB; this keeps an overview question to one small row per session, with a drill-in
196
+ * (narrow the date range) when the detail is actually needed.
197
+ */
198
+ declare function summarizeAthleteWorkouts(list: readonly AthleteWorkoutView[]): AthleteWorkoutSummary[];
199
+ /**
200
+ * Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
201
+ * flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
202
+ * the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
203
+ * the discovery handle a coach otherwise lacks: read what the athlete actually did, then pull the
204
+ * specific lift's PRs.
205
+ */
206
+ declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId: number, year: number, month: number): CoachAthleteTraining;
171
207
  /**
172
208
  * One set of entered values for a single exercise within a saved workout set.
173
209
  * `param1` and `param2` correspond to the exercise's first and second parameter types
@@ -364,4 +400,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
364
400
  stats(): Promise<Record<string, unknown>>;
365
401
  }
366
402
  //#endregion
367
- 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, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, isRecord, logAthleteSet, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentExercise, presentExerciseHistory, publishSession, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
403
+ 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, fetchRosterActivity, 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, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/dist/index.mjs CHANGED
@@ -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
  }
@@ -348,6 +404,15 @@ function fetchExerciseStats(client, exerciseId, userId, date) {
348
404
  function fetchAthleteWorkouts(client, startDate, endDate) {
349
405
  return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
350
406
  }
407
+ /**
408
+ * A coach's month view of a roster athlete's logged sessions
409
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
410
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
411
+ * `userId` in each row is the roster athlete, not the calling coach.
412
+ */
413
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
414
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
415
+ }
351
416
  function fetchLeaderboard(client, workoutId, opts = {}) {
352
417
  const qs = new URLSearchParams();
353
418
  if (opts.page !== void 0) qs.set("page", String(opts.page));
@@ -532,6 +597,76 @@ function selectWorkouts(list, opts = {}) {
532
597
  if (opts.limit !== void 0) out = [...out].sort((a, b) => a.date < b.date ? 1 : a.date > b.date ? -1 : 0).slice(0, opts.limit);
533
598
  return out;
534
599
  }
600
+ /**
601
+ * Project presented workouts to compact headers (date/title/program + logged flag + exercise
602
+ * counts), dropping the per-set block detail. A dense multi-program week of full views can be
603
+ * tens of KB; this keeps an overview question to one small row per session, with a drill-in
604
+ * (narrow the date range) when the detail is actually needed.
605
+ */
606
+ function summarizeAthleteWorkouts(list) {
607
+ return list.map((w) => {
608
+ const exerciseCount = w.blocks.reduce((n, b) => n + b.exercises.length, 0);
609
+ const performedCount = w.blocks.reduce((n, b) => n + b.exercises.filter((e) => e.performed.length > 0).length, 0);
610
+ return {
611
+ id: w.id,
612
+ date: w.date,
613
+ title: w.title,
614
+ program: w.program,
615
+ team: w.team,
616
+ logged: w.logged,
617
+ exerciseCount,
618
+ performedCount
619
+ };
620
+ });
621
+ }
622
+ /**
623
+ * Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
624
+ * flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
625
+ * the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
626
+ * the discovery handle a coach otherwise lacks: read what the athlete actually did, then pull the
627
+ * specific lift's PRs.
628
+ */
629
+ function presentCoachAthleteTraining(raw, athleteId, year, month) {
630
+ const sessions = [];
631
+ let athleteName = null;
632
+ for (const item of raw) {
633
+ if (!isRecord(item)) continue;
634
+ if (athleteName === null && typeof item.athleteName === "string") athleteName = item.athleteName;
635
+ const exercises = [];
636
+ const sets = Array.isArray(item.sets) ? item.sets : [];
637
+ for (const set of sets) {
638
+ if (!isRecord(set)) continue;
639
+ const exs = Array.isArray(set.exercises) ? set.exercises : [];
640
+ for (const ex of exs) {
641
+ if (!isRecord(ex)) continue;
642
+ exercises.push({
643
+ exerciseId: coerceInt(ex.exercise_id),
644
+ title: typeof ex.title === "string" ? ex.title : "",
645
+ summary: typeof ex.abr === "string" && ex.abr !== "" ? ex.abr : null,
646
+ completed: coerceInt(ex.completed) === 1
647
+ });
648
+ }
649
+ }
650
+ sessions.push({
651
+ workoutId: coerceInt(item.workout_id),
652
+ savedWorkoutId: coerceInt(item.saved_workout_id),
653
+ title: typeof item.workout_title === "string" ? item.workout_title : "",
654
+ logged: coerceInt(item.logged) === 1,
655
+ completed: coerceInt(item.completed) === 1,
656
+ rpe: coerceInt(item.rpe),
657
+ durationMin: coerceInt(item.session_duration),
658
+ notes: typeof item.notes === "string" && item.notes !== "" ? item.notes : null,
659
+ exercises
660
+ });
661
+ }
662
+ return {
663
+ athleteId,
664
+ athleteName,
665
+ year,
666
+ month,
667
+ sessions
668
+ };
669
+ }
535
670
  const MAX_PARAM_SLOTS = 10;
536
671
  /**
537
672
  * Build the body for `PUT /1.0/athlete/savedworkoutsetexercise/{id}`. The body uses
@@ -1291,4 +1426,4 @@ var ExerciseLibrary = class {
1291
1426
  }
1292
1427
  };
1293
1428
  //#endregion
1294
- 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, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, isRecord, logAthleteSet, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentExercise, presentExerciseHistory, publishSession, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
1429
+ 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, fetchRosterActivity, 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, 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.2",
3
+ "version": "0.6.4",
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.2"
30
+ "@trainheroic-unofficial/dto": "0.6.4"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.0.0",