@trainheroic-unofficial/js 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +116 -4
- package/dist/index.mjs +303 -9
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -189,7 +189,11 @@ declare function presentAthleteWorkouts(list: readonly ProgramWorkout[]): Athlet
|
|
|
189
189
|
/** The minimal id scaffold `log-set` / `logForAthlete` needs for one saved workout set. */
|
|
190
190
|
type LogSetTarget = {
|
|
191
191
|
date: string;
|
|
192
|
-
workoutTitle: string; /** The
|
|
192
|
+
workoutTitle: string; /** The program this saved workout belongs to — lets a caller pick the right one of several. */
|
|
193
|
+
program: string | null;
|
|
194
|
+
programId: number | null;
|
|
195
|
+
team: string | null;
|
|
196
|
+
teamId: number | null; /** The id for `--set` (logAthleteSet/logForAthlete `savedWorkoutSetId`). */
|
|
193
197
|
savedWorkoutSetId: number;
|
|
194
198
|
setTitle: string | null;
|
|
195
199
|
exercises: Array<{
|
|
@@ -200,13 +204,27 @@ type LogSetTarget = {
|
|
|
200
204
|
performed: string[];
|
|
201
205
|
}>;
|
|
202
206
|
};
|
|
207
|
+
/**
|
|
208
|
+
* Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
|
|
209
|
+
* every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
|
|
210
|
+
* workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
|
|
211
|
+
* (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
|
|
212
|
+
* `program_title`/`team_title`) — the title match lets a caller target a program by name without
|
|
213
|
+
* first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
|
|
214
|
+
*/
|
|
215
|
+
declare function selectWorkoutsByProgram(list: readonly ProgramWorkout[], filter: {
|
|
216
|
+
programId?: number;
|
|
217
|
+
teamId?: number;
|
|
218
|
+
programTitle?: string;
|
|
219
|
+
}): ProgramWorkout[];
|
|
203
220
|
/**
|
|
204
221
|
* Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
|
|
205
222
|
* location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
|
|
206
223
|
* This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
|
|
207
224
|
* which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
|
|
208
|
-
* `savedWorkoutSetExerciseId` straight off these rows.
|
|
209
|
-
*
|
|
225
|
+
* `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
|
|
226
|
+
* so a caller can pick the right session when the athlete is on several. One row per saved set,
|
|
227
|
+
* dropping any set with no resolvable id.
|
|
210
228
|
*/
|
|
211
229
|
declare function presentLogTargets(list: readonly ProgramWorkout[]): LogSetTarget[];
|
|
212
230
|
/**
|
|
@@ -483,8 +501,102 @@ declare function logSessionForAthlete(client: TrainHeroicClient, args: {
|
|
|
483
501
|
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
484
502
|
declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
|
|
485
503
|
//#endregion
|
|
504
|
+
//#region src/main-lifts.d.ts
|
|
505
|
+
type MainLiftFamilyKey = "cleanjerk" | "snatch" | "deadlift" | "squat" | "bench" | "overhead";
|
|
506
|
+
type MainLiftFamily = {
|
|
507
|
+
key: MainLiftFamilyKey;
|
|
508
|
+
label: string; /** True when a lowercased exercise title belongs to this family. */
|
|
509
|
+
matches: (titleLower: string) => boolean;
|
|
510
|
+
};
|
|
511
|
+
/**
|
|
512
|
+
* The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
|
|
513
|
+
* first family that matches, so the more specific / easily-confused families come before the broad
|
|
514
|
+
* overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
|
|
515
|
+
* swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
|
|
516
|
+
* This is the single place to edit the lift set.
|
|
517
|
+
*/
|
|
518
|
+
declare const MAIN_LIFT_FAMILIES: readonly MainLiftFamily[];
|
|
519
|
+
/** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
|
|
520
|
+
declare function classifyMainLift(title: string): MainLiftFamilyKey | null;
|
|
521
|
+
/** The main-lift variant an athlete actually logs (the most-used exercise in that family). */
|
|
522
|
+
type ResolvedLift = {
|
|
523
|
+
family: MainLiftFamilyKey;
|
|
524
|
+
label: string;
|
|
525
|
+
exerciseId: number;
|
|
526
|
+
title: string;
|
|
527
|
+
};
|
|
528
|
+
type MainLiftResolution = {
|
|
529
|
+
athleteId: number;
|
|
530
|
+
athleteName: string | null;
|
|
531
|
+
lifts: ResolvedLift[];
|
|
532
|
+
};
|
|
533
|
+
/**
|
|
534
|
+
* Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
|
|
535
|
+
* logged workouts over the last `months` (default 12) — the program-workout range, the reliable
|
|
536
|
+
* record of performed sets — buckets every performed exercise into a lift family, and for each
|
|
537
|
+
* family picks the variant logged most often. Returns one entry per family the athlete has logged;
|
|
538
|
+
* families they never trained are simply absent. (The monthly calendar summary is not used: it
|
|
539
|
+
* comes back empty for some accounts that have logged sets in the range endpoint.)
|
|
540
|
+
*/
|
|
541
|
+
declare function resolveAthleteMainLifts(client: TrainHeroicClient, athleteId: number, opts?: {
|
|
542
|
+
months?: number;
|
|
543
|
+
now?: Date;
|
|
544
|
+
}): Promise<MainLiftResolution>;
|
|
545
|
+
/** One main lift's best PR for an athlete. A family the athlete has not logged has a null body. */
|
|
546
|
+
type MainLiftPR = {
|
|
547
|
+
family: MainLiftFamilyKey;
|
|
548
|
+
label: string;
|
|
549
|
+
exerciseId: number | null;
|
|
550
|
+
title: string | null;
|
|
551
|
+
weight: number | null;
|
|
552
|
+
reps: number | null;
|
|
553
|
+
units: string | null;
|
|
554
|
+
date: string | null;
|
|
555
|
+
};
|
|
556
|
+
type AthleteMainLiftPRs = {
|
|
557
|
+
athleteId: number;
|
|
558
|
+
athleteName: string | null;
|
|
559
|
+
prs: MainLiftPR[];
|
|
560
|
+
};
|
|
561
|
+
/**
|
|
562
|
+
* A roster athlete's best PR for each main lift. Discovers the lift variants they log
|
|
563
|
+
* ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
|
|
564
|
+
* The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
|
|
565
|
+
* athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
|
|
566
|
+
* render a stable row of columns.
|
|
567
|
+
*/
|
|
568
|
+
declare function fetchAthleteMainLiftPRs(client: TrainHeroicClient, athleteId: number, opts?: {
|
|
569
|
+
months?: number;
|
|
570
|
+
now?: Date;
|
|
571
|
+
}): Promise<AthleteMainLiftPRs>;
|
|
572
|
+
/**
|
|
573
|
+
* Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
|
|
574
|
+
* resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
|
|
575
|
+
* `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
|
|
576
|
+
* to the roster name when the per-athlete read can't supply one. This is the single roster-level
|
|
577
|
+
* primitive the CLI, the MCP tool, and the warehouse store all build on.
|
|
578
|
+
*/
|
|
579
|
+
declare function fetchRosterMainLiftPRs(client: TrainHeroicClient, opts?: {
|
|
580
|
+
athleteIds?: readonly number[];
|
|
581
|
+
months?: number;
|
|
582
|
+
now?: Date;
|
|
583
|
+
concurrency?: number;
|
|
584
|
+
}): Promise<AthleteMainLiftPRs[]>;
|
|
585
|
+
//#endregion
|
|
486
586
|
//#region src/coach.d.ts
|
|
487
587
|
declare const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
588
|
+
/** A roster member as id + display name. */
|
|
589
|
+
type CoachRosterAthlete = {
|
|
590
|
+
id: number;
|
|
591
|
+
name: string | null;
|
|
592
|
+
};
|
|
593
|
+
/**
|
|
594
|
+
* The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
|
|
595
|
+
* name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
|
|
596
|
+
* and the warehouse store map the roster identically. Includes the account owner and
|
|
597
|
+
* demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
|
|
598
|
+
*/
|
|
599
|
+
declare function fetchCoachRoster(client: TrainHeroicClient, ids?: readonly number[]): Promise<CoachRosterAthlete[]>;
|
|
488
600
|
/**
|
|
489
601
|
* Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
|
|
490
602
|
* addresses (`POST /v5/emails/validate`), then invite the validated ones
|
|
@@ -663,4 +775,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
663
775
|
stats(): Promise<Record<string, unknown>>;
|
|
664
776
|
}
|
|
665
777
|
//#endregion
|
|
666
|
-
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, BuildOptions, ClientResult, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, 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, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
778
|
+
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BuildOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
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
|
-
const
|
|
4
|
+
const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
5
|
+
/**
|
|
6
|
+
* The login endpoint, allowing an env override so a test harness can authenticate against a local
|
|
7
|
+
* fake backend. Precedence: an explicit `TH_AUTH_URL`, else `${TH_APIS_BASE}/auth` (login lives on
|
|
8
|
+
* the apis host, so it follows that base), else the real endpoint. Read via `globalThis.process`
|
|
9
|
+
* (no `import process`) to keep this module workerd-safe, and per call so a child-env override wins.
|
|
10
|
+
*/
|
|
11
|
+
function authUrl() {
|
|
12
|
+
const env = globalThis.process?.env;
|
|
13
|
+
if (env?.TH_AUTH_URL && env.TH_AUTH_URL.length > 0) return env.TH_AUTH_URL;
|
|
14
|
+
const apis = env?.TH_APIS_BASE;
|
|
15
|
+
if (apis && apis.length > 0) return `${apis.replace(/\/$/, "")}/auth`;
|
|
16
|
+
return DEFAULT_AUTH_URL;
|
|
17
|
+
}
|
|
5
18
|
/**
|
|
6
19
|
* Authenticate against TrainHeroic. Returns the session bundle, or null on bad
|
|
7
20
|
* credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
|
|
@@ -9,7 +22,7 @@ const AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
|
9
22
|
* is sent as the `session-token` header and works against both API hosts.
|
|
10
23
|
*/
|
|
11
24
|
async function loginTrainHeroic(email, password) {
|
|
12
|
-
const res = await fetch(
|
|
25
|
+
const res = await fetch(authUrl(), {
|
|
13
26
|
method: "POST",
|
|
14
27
|
headers: {
|
|
15
28
|
"content-type": "application/x-www-form-urlencoded",
|
|
@@ -32,8 +45,19 @@ async function loginTrainHeroic(email, password) {
|
|
|
32
45
|
}
|
|
33
46
|
//#endregion
|
|
34
47
|
//#region src/client.ts
|
|
35
|
-
const
|
|
36
|
-
const
|
|
48
|
+
const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
|
|
49
|
+
const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
|
|
50
|
+
/**
|
|
51
|
+
* Resolve an API host, allowing an env override. The override exists so a test harness can point
|
|
52
|
+
* the client at a local fake backend (and it doubles as a staging knob); production leaves these
|
|
53
|
+
* unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
|
|
54
|
+
* — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
|
|
55
|
+
* read per request (not at module load) so a value the harness sets in the child env always wins.
|
|
56
|
+
*/
|
|
57
|
+
function envBase(key, fallback) {
|
|
58
|
+
const v = (globalThis.process?.env)?.[key];
|
|
59
|
+
return v && v.length > 0 ? v : fallback;
|
|
60
|
+
}
|
|
37
61
|
var TrainHeroicAuthError = class extends Error {
|
|
38
62
|
name = "TrainHeroicAuthError";
|
|
39
63
|
};
|
|
@@ -72,7 +96,7 @@ var TrainHeroicClient = class {
|
|
|
72
96
|
return this.#sessionId;
|
|
73
97
|
}
|
|
74
98
|
async request(method, path, options = {}) {
|
|
75
|
-
const url = `${options.base === "apis" ?
|
|
99
|
+
const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
|
|
76
100
|
let session = await this.#ensureSession();
|
|
77
101
|
let res = await this.#send(method, url, session, options.body);
|
|
78
102
|
if (res.status === 401 || res.status === 403) {
|
|
@@ -596,12 +620,35 @@ function presentAthleteWorkouts(list) {
|
|
|
596
620
|
return list.map(presentAthleteWorkout);
|
|
597
621
|
}
|
|
598
622
|
/**
|
|
623
|
+
* Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
|
|
624
|
+
* every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
|
|
625
|
+
* workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
|
|
626
|
+
* (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
|
|
627
|
+
* `program_title`/`team_title`) — the title match lets a caller target a program by name without
|
|
628
|
+
* first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
|
|
629
|
+
*/
|
|
630
|
+
function selectWorkoutsByProgram(list, filter) {
|
|
631
|
+
const { programId, teamId, programTitle } = filter;
|
|
632
|
+
const needle = programTitle?.trim().toLowerCase();
|
|
633
|
+
if (programId === void 0 && teamId === void 0 && !needle) return [...list];
|
|
634
|
+
return list.filter((pw) => {
|
|
635
|
+
const rec = pw;
|
|
636
|
+
if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
|
|
637
|
+
if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
|
|
638
|
+
if (needle) {
|
|
639
|
+
if (`${str$1(rec.program_title) ?? ""} ${str$1(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
|
|
640
|
+
}
|
|
641
|
+
return false;
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
599
645
|
* Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
|
|
600
646
|
* location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
|
|
601
647
|
* This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
|
|
602
648
|
* which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
|
|
603
|
-
* `savedWorkoutSetExerciseId` straight off these rows.
|
|
604
|
-
*
|
|
649
|
+
* `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
|
|
650
|
+
* so a caller can pick the right session when the athlete is on several. One row per saved set,
|
|
651
|
+
* dropping any set with no resolvable id.
|
|
605
652
|
*/
|
|
606
653
|
function presentLogTargets(list) {
|
|
607
654
|
const targets = [];
|
|
@@ -612,6 +659,10 @@ function presentLogTargets(list) {
|
|
|
612
659
|
if (!saved) continue;
|
|
613
660
|
const date = str$1(rec.date) ?? "";
|
|
614
661
|
const workoutTitle = str$1(rec.workout_title) ?? "";
|
|
662
|
+
const program = str$1(rec.program_title);
|
|
663
|
+
const programId = coerceInt(rec.program_id);
|
|
664
|
+
const team = str$1(rec.team_title);
|
|
665
|
+
const teamId = coerceInt(rec.team_id);
|
|
615
666
|
const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
|
|
616
667
|
for (const s of sets) {
|
|
617
668
|
if (!isRecord(s)) continue;
|
|
@@ -631,6 +682,10 @@ function presentLogTargets(list) {
|
|
|
631
682
|
targets.push({
|
|
632
683
|
date,
|
|
633
684
|
workoutTitle,
|
|
685
|
+
program,
|
|
686
|
+
programId,
|
|
687
|
+
team,
|
|
688
|
+
teamId,
|
|
634
689
|
savedWorkoutSetId,
|
|
635
690
|
setTitle: str$1(s.title),
|
|
636
691
|
exercises
|
|
@@ -992,7 +1047,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
992
1047
|
throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
|
|
993
1048
|
}
|
|
994
1049
|
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
995
|
-
if (!workoutSetExerciseId) throw new Error(`
|
|
1050
|
+
if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
|
|
996
1051
|
const body = {
|
|
997
1052
|
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
|
|
998
1053
|
...extra
|
|
@@ -1256,6 +1311,7 @@ function presentExerciseHistory(detail) {
|
|
|
1256
1311
|
description: p.description ?? null,
|
|
1257
1312
|
reps: p.reps ?? null,
|
|
1258
1313
|
weight: p.weight ?? null,
|
|
1314
|
+
units: p.units ?? null,
|
|
1259
1315
|
date: p.dateCompleted ?? null
|
|
1260
1316
|
})),
|
|
1261
1317
|
sessions: (detail.history ?? []).map((h) => ({
|
|
@@ -1276,6 +1332,37 @@ const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and read
|
|
|
1276
1332
|
function emailList(emails) {
|
|
1277
1333
|
return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
|
|
1278
1334
|
}
|
|
1335
|
+
/** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
|
|
1336
|
+
function rosterName(rec) {
|
|
1337
|
+
const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
|
|
1338
|
+
if (full !== "") return full;
|
|
1339
|
+
const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
|
|
1340
|
+
return combined !== "" ? combined : null;
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
|
|
1344
|
+
* name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
|
|
1345
|
+
* and the warehouse store map the roster identically. Includes the account owner and
|
|
1346
|
+
* demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
|
|
1347
|
+
*/
|
|
1348
|
+
async function fetchCoachRoster(client, ids) {
|
|
1349
|
+
const res = await client.request("GET", "/v5/athletes");
|
|
1350
|
+
if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
|
|
1351
|
+
const keep = ids && ids.length > 0 ? new Set(ids) : null;
|
|
1352
|
+
const out = [];
|
|
1353
|
+
for (const row of res.data) {
|
|
1354
|
+
if (typeof row !== "object" || row === null) continue;
|
|
1355
|
+
const rec = row;
|
|
1356
|
+
const id = coerceInt(rec.id);
|
|
1357
|
+
if (id === null || id <= 0) continue;
|
|
1358
|
+
if (keep && !keep.has(id)) continue;
|
|
1359
|
+
out.push({
|
|
1360
|
+
id,
|
|
1361
|
+
name: rosterName(rec)
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
return out;
|
|
1365
|
+
}
|
|
1279
1366
|
/**
|
|
1280
1367
|
* Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
|
|
1281
1368
|
* addresses (`POST /v5/emails/validate`), then invite the validated ones
|
|
@@ -1555,6 +1642,213 @@ async function teamVolume(client, args) {
|
|
|
1555
1642
|
};
|
|
1556
1643
|
}
|
|
1557
1644
|
//#endregion
|
|
1645
|
+
//#region src/main-lifts.ts
|
|
1646
|
+
/**
|
|
1647
|
+
* The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
|
|
1648
|
+
* first family that matches, so the more specific / easily-confused families come before the broad
|
|
1649
|
+
* overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
|
|
1650
|
+
* swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
|
|
1651
|
+
* This is the single place to edit the lift set.
|
|
1652
|
+
*/
|
|
1653
|
+
const MAIN_LIFT_FAMILIES = [
|
|
1654
|
+
{
|
|
1655
|
+
key: "cleanjerk",
|
|
1656
|
+
label: "Clean & Jerk",
|
|
1657
|
+
matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
|
|
1658
|
+
},
|
|
1659
|
+
{
|
|
1660
|
+
key: "snatch",
|
|
1661
|
+
label: "Snatch",
|
|
1662
|
+
matches: (t) => t.includes("snatch")
|
|
1663
|
+
},
|
|
1664
|
+
{
|
|
1665
|
+
key: "deadlift",
|
|
1666
|
+
label: "Deadlift",
|
|
1667
|
+
matches: (t) => t.includes("deadlift")
|
|
1668
|
+
},
|
|
1669
|
+
{
|
|
1670
|
+
key: "squat",
|
|
1671
|
+
label: "Squat",
|
|
1672
|
+
matches: (t) => t.includes("squat")
|
|
1673
|
+
},
|
|
1674
|
+
{
|
|
1675
|
+
key: "bench",
|
|
1676
|
+
label: "Bench Press",
|
|
1677
|
+
matches: (t) => t.includes("bench")
|
|
1678
|
+
},
|
|
1679
|
+
{
|
|
1680
|
+
key: "overhead",
|
|
1681
|
+
label: "Overhead Press",
|
|
1682
|
+
matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
|
|
1683
|
+
}
|
|
1684
|
+
];
|
|
1685
|
+
/** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
|
|
1686
|
+
function classifyMainLift(title) {
|
|
1687
|
+
const t = title.toLowerCase();
|
|
1688
|
+
for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
|
|
1689
|
+
return null;
|
|
1690
|
+
}
|
|
1691
|
+
const DEFAULT_MONTHS = 12;
|
|
1692
|
+
function pad2(n) {
|
|
1693
|
+
return String(n).padStart(2, "0");
|
|
1694
|
+
}
|
|
1695
|
+
/** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
|
|
1696
|
+
function isoDay(d) {
|
|
1697
|
+
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
|
|
1701
|
+
* logged workouts over the last `months` (default 12) — the program-workout range, the reliable
|
|
1702
|
+
* record of performed sets — buckets every performed exercise into a lift family, and for each
|
|
1703
|
+
* family picks the variant logged most often. Returns one entry per family the athlete has logged;
|
|
1704
|
+
* families they never trained are simply absent. (The monthly calendar summary is not used: it
|
|
1705
|
+
* comes back empty for some accounts that have logged sets in the range endpoint.)
|
|
1706
|
+
*/
|
|
1707
|
+
async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
1708
|
+
const months = opts.months ?? DEFAULT_MONTHS;
|
|
1709
|
+
const now = opts.now ?? /* @__PURE__ */ new Date();
|
|
1710
|
+
const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
|
|
1711
|
+
const tally = /* @__PURE__ */ new Map();
|
|
1712
|
+
let workouts = [];
|
|
1713
|
+
try {
|
|
1714
|
+
workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
|
|
1715
|
+
} catch {
|
|
1716
|
+
workouts = [];
|
|
1717
|
+
}
|
|
1718
|
+
for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
|
|
1719
|
+
if (ex.performed.length === 0 || ex.exerciseId === null) continue;
|
|
1720
|
+
const family = classifyMainLift(ex.title);
|
|
1721
|
+
if (family === null) continue;
|
|
1722
|
+
const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
|
|
1723
|
+
const prev = byId.get(ex.exerciseId);
|
|
1724
|
+
byId.set(ex.exerciseId, {
|
|
1725
|
+
count: (prev?.count ?? 0) + 1,
|
|
1726
|
+
title: prev?.title ?? ex.title
|
|
1727
|
+
});
|
|
1728
|
+
tally.set(family, byId);
|
|
1729
|
+
}
|
|
1730
|
+
const lifts = [];
|
|
1731
|
+
for (const family of MAIN_LIFT_FAMILIES) {
|
|
1732
|
+
const byId = tally.get(family.key);
|
|
1733
|
+
if (!byId || byId.size === 0) continue;
|
|
1734
|
+
let best = null;
|
|
1735
|
+
for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
|
|
1736
|
+
exerciseId,
|
|
1737
|
+
count,
|
|
1738
|
+
title
|
|
1739
|
+
};
|
|
1740
|
+
if (best) lifts.push({
|
|
1741
|
+
family: family.key,
|
|
1742
|
+
label: family.label,
|
|
1743
|
+
exerciseId: best.exerciseId,
|
|
1744
|
+
title: best.title
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
return {
|
|
1748
|
+
athleteId,
|
|
1749
|
+
athleteName: null,
|
|
1750
|
+
lifts
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
const PR_CONCURRENCY = 5;
|
|
1754
|
+
/** The heaviest PR on an exercise's board (ties broken by more reps). */
|
|
1755
|
+
function bestPr(liftPRs) {
|
|
1756
|
+
let best = null;
|
|
1757
|
+
for (const pr of liftPRs) {
|
|
1758
|
+
const weight = coerceNum(pr.weight);
|
|
1759
|
+
if (weight === null) continue;
|
|
1760
|
+
const reps = coerceInt(pr.reps);
|
|
1761
|
+
if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
|
|
1762
|
+
weight,
|
|
1763
|
+
reps,
|
|
1764
|
+
units: pr.units,
|
|
1765
|
+
date: pr.date
|
|
1766
|
+
};
|
|
1767
|
+
}
|
|
1768
|
+
return best;
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* A roster athlete's best PR for each main lift. Discovers the lift variants they log
|
|
1772
|
+
* ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
|
|
1773
|
+
* The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
|
|
1774
|
+
* athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
|
|
1775
|
+
* render a stable row of columns.
|
|
1776
|
+
*/
|
|
1777
|
+
async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
|
|
1778
|
+
const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
|
|
1779
|
+
const byFamily = new Map(lifts.map((l) => [l.family, l]));
|
|
1780
|
+
return {
|
|
1781
|
+
athleteId,
|
|
1782
|
+
athleteName,
|
|
1783
|
+
prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
|
|
1784
|
+
const lift = byFamily.get(family.key);
|
|
1785
|
+
const base = {
|
|
1786
|
+
family: family.key,
|
|
1787
|
+
label: family.label
|
|
1788
|
+
};
|
|
1789
|
+
const empty = {
|
|
1790
|
+
exerciseId: null,
|
|
1791
|
+
title: null,
|
|
1792
|
+
weight: null,
|
|
1793
|
+
reps: null,
|
|
1794
|
+
units: null,
|
|
1795
|
+
date: null
|
|
1796
|
+
};
|
|
1797
|
+
if (!lift) return {
|
|
1798
|
+
...base,
|
|
1799
|
+
...empty
|
|
1800
|
+
};
|
|
1801
|
+
const known = {
|
|
1802
|
+
exerciseId: lift.exerciseId,
|
|
1803
|
+
title: lift.title
|
|
1804
|
+
};
|
|
1805
|
+
try {
|
|
1806
|
+
const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
|
|
1807
|
+
return {
|
|
1808
|
+
...base,
|
|
1809
|
+
...known,
|
|
1810
|
+
weight: best?.weight ?? null,
|
|
1811
|
+
reps: best?.reps ?? null,
|
|
1812
|
+
units: best?.units ?? null,
|
|
1813
|
+
date: best?.date ?? null
|
|
1814
|
+
};
|
|
1815
|
+
} catch {
|
|
1816
|
+
return {
|
|
1817
|
+
...base,
|
|
1818
|
+
...known,
|
|
1819
|
+
weight: null,
|
|
1820
|
+
reps: null,
|
|
1821
|
+
units: null,
|
|
1822
|
+
date: null
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
})
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1828
|
+
const ROSTER_CONCURRENCY = 4;
|
|
1829
|
+
/**
|
|
1830
|
+
* Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
|
|
1831
|
+
* resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
|
|
1832
|
+
* `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
|
|
1833
|
+
* to the roster name when the per-athlete read can't supply one. This is the single roster-level
|
|
1834
|
+
* primitive the CLI, the MCP tool, and the warehouse store all build on.
|
|
1835
|
+
*/
|
|
1836
|
+
async function fetchRosterMainLiftPRs(client, opts = {}) {
|
|
1837
|
+
const roster = await fetchCoachRoster(client, opts.athleteIds);
|
|
1838
|
+
const inner = {
|
|
1839
|
+
...opts.months !== void 0 ? { months: opts.months } : {},
|
|
1840
|
+
...opts.now !== void 0 ? { now: opts.now } : {}
|
|
1841
|
+
};
|
|
1842
|
+
return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
|
|
1843
|
+
const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
|
|
1844
|
+
return {
|
|
1845
|
+
athleteId: athlete.id,
|
|
1846
|
+
athleteName: result.athleteName ?? athlete.name,
|
|
1847
|
+
prs: result.prs
|
|
1848
|
+
};
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
//#endregion
|
|
1558
1852
|
//#region src/util.ts
|
|
1559
1853
|
/**
|
|
1560
1854
|
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
@@ -2137,4 +2431,4 @@ var ExerciseLibrary = class {
|
|
|
2137
2431
|
}
|
|
2138
2432
|
};
|
|
2139
2433
|
//#endregion
|
|
2140
|
-
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, buildExerciseSetPayload, 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, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
2434
|
+
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
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": "1.
|
|
30
|
+
"@trainheroic-unofficial/dto": "1.4.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^26.0.0",
|