@trainheroic-unofficial/js 2.0.1 → 2.1.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 +72 -15
- package/dist/index.mjs +921 -817
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
|
|
1
|
+
import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
|
|
2
|
+
import { z } from "zod";
|
|
2
3
|
export * from "@trainheroic-unofficial/dto";
|
|
3
4
|
//#region src/auth.ts
|
|
4
5
|
const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
@@ -355,7 +356,7 @@ async function getJson(client, path, label) {
|
|
|
355
356
|
if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
|
|
356
357
|
return res.data;
|
|
357
358
|
}
|
|
358
|
-
async function getArray(client, path, label) {
|
|
359
|
+
async function getArray$1(client, path, label) {
|
|
359
360
|
const res = await client.request("GET", path);
|
|
360
361
|
if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
|
|
361
362
|
return res.data;
|
|
@@ -438,10 +439,10 @@ function fetchAthletePrefs(client) {
|
|
|
438
439
|
return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
|
|
439
440
|
}
|
|
440
441
|
function fetchWorkingMaxes(client) {
|
|
441
|
-
return getArray(client, "/2.0/athlete/workingMax", "athlete working maxes");
|
|
442
|
+
return getArray$1(client, "/2.0/athlete/workingMax", "athlete working maxes");
|
|
442
443
|
}
|
|
443
444
|
function fetchExerciseHistoryList(client) {
|
|
444
|
-
return getArray(client, "/v5/users/exercises/history", "athlete exercise history list");
|
|
445
|
+
return getArray$1(client, "/v5/users/exercises/history", "athlete exercise history list");
|
|
445
446
|
}
|
|
446
447
|
/** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
|
|
447
448
|
async function searchExerciseHistory(client, query, limit = 20) {
|
|
@@ -451,7 +452,7 @@ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
|
|
|
451
452
|
return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
|
|
452
453
|
}
|
|
453
454
|
function fetchPersonalRecords(client, exerciseId) {
|
|
454
|
-
return getArray(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
|
|
455
|
+
return getArray$1(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
|
|
455
456
|
}
|
|
456
457
|
/** Last performance + PR for an exercise. `date` (YYYY-MM-DD) is required by the API. */
|
|
457
458
|
function fetchExerciseStats(client, exerciseId, userId, date) {
|
|
@@ -459,7 +460,7 @@ function fetchExerciseStats(client, exerciseId, userId, date) {
|
|
|
459
460
|
}
|
|
460
461
|
/** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
|
|
461
462
|
function fetchAthleteWorkouts(client, startDate, endDate) {
|
|
462
|
-
return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
|
|
463
|
+
return getArray$1(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
|
|
463
464
|
}
|
|
464
465
|
/** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
|
|
465
466
|
function shiftDate(iso, days) {
|
|
@@ -521,24 +522,6 @@ async function fetchAthleteWorkoutsChunked(client, startDate, endDate, opts = {}
|
|
|
521
522
|
return page;
|
|
522
523
|
}));
|
|
523
524
|
}
|
|
524
|
-
/**
|
|
525
|
-
* A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
|
|
526
|
-
* YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
|
|
527
|
-
* `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
|
|
528
|
-
* `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
|
|
529
|
-
*/
|
|
530
|
-
function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
|
|
531
|
-
return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* A coach's month view of a roster athlete's logged sessions
|
|
535
|
-
* (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
|
|
536
|
-
* ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
|
|
537
|
-
* `userId` in each row is the roster athlete, not the calling coach.
|
|
538
|
-
*/
|
|
539
|
-
function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
|
|
540
|
-
return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
|
|
541
|
-
}
|
|
542
525
|
function fetchLeaderboard(client, workoutId, opts = {}) {
|
|
543
526
|
const qs = new URLSearchParams();
|
|
544
527
|
if (opts.page !== void 0) qs.set("page", String(opts.page));
|
|
@@ -1003,6 +986,70 @@ function presentExerciseHistory(detail) {
|
|
|
1003
986
|
};
|
|
1004
987
|
}
|
|
1005
988
|
//#endregion
|
|
989
|
+
//#region src/coach-athlete-calendar.ts
|
|
990
|
+
async function getArray(client, path, label) {
|
|
991
|
+
const res = await client.request("GET", path);
|
|
992
|
+
if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
|
|
993
|
+
return res.data;
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
|
|
997
|
+
* YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
|
|
998
|
+
* `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
|
|
999
|
+
* `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
|
|
1000
|
+
*/
|
|
1001
|
+
function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
|
|
1002
|
+
return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* A coach's month view of a roster athlete's logged sessions
|
|
1006
|
+
* (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
|
|
1007
|
+
* ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
|
|
1008
|
+
* `userId` in each row is the roster athlete, not the calling coach.
|
|
1009
|
+
*/
|
|
1010
|
+
function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
|
|
1011
|
+
return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Resolve a roster athlete's coach-writable calendar program id
|
|
1015
|
+
* (`GET /v5/calendars/athletes/{athleteId}?year=&month=`).
|
|
1016
|
+
*
|
|
1017
|
+
* Year and month are required by the API (HTTP 400 without them); the returned `programId` is
|
|
1018
|
+
* stable for the athlete, so any month works. This is the calendar the coach web app writes
|
|
1019
|
+
* with `createWorkoutForDay` when you open an athlete from My Athletes → calendar — distinct
|
|
1020
|
+
* from athlete-created `personal_cal` ad-hoc sessions.
|
|
1021
|
+
*/
|
|
1022
|
+
async function fetchCoachAthleteCalendar(client, athleteId, year, month) {
|
|
1023
|
+
const path = `/v5/calendars/athletes/${athleteId}?year=${year}&month=${month}`;
|
|
1024
|
+
const res = await client.request("GET", path);
|
|
1025
|
+
if (!res.ok) {
|
|
1026
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
1027
|
+
throw new Error(`GET ${path} failed (HTTP ${res.status}): ${detail}`);
|
|
1028
|
+
}
|
|
1029
|
+
if (!isRecord(res.data)) throw new Error("Unexpected athlete calendar response.");
|
|
1030
|
+
const programId = coerceInt(res.data.id);
|
|
1031
|
+
if (programId === null || programId <= 0) throw new Error(`Athlete calendar for ${athleteId} did not include a program id.`);
|
|
1032
|
+
return {
|
|
1033
|
+
programId,
|
|
1034
|
+
title: str(res.data.title) ?? "",
|
|
1035
|
+
type: coerceInt(res.data.type),
|
|
1036
|
+
groupId: coerceInt(res.data.group_id)
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Resolve the calendar program id for `workout_build` / `coach workout build`: either an
|
|
1041
|
+
* explicit team/group `programId`, or a roster `athleteId` (+ date) via
|
|
1042
|
+
* `fetchCoachAthleteCalendar`. Exactly one of programId / athleteId is required.
|
|
1043
|
+
*/
|
|
1044
|
+
async function resolveBuildProgramId(client, args) {
|
|
1045
|
+
if (args.programId !== void 0 && args.athleteId !== void 0) throw new Error("Pass programId or athleteId, not both.");
|
|
1046
|
+
if (args.programId !== void 0) return args.programId;
|
|
1047
|
+
if (args.athleteId === void 0) throw new Error("Provide programId (team calendar) or athleteId (athlete calendar).");
|
|
1048
|
+
if (args.date === void 0) throw new Error("athleteId requires date (YYYY-M-D) to resolve the athlete calendar.");
|
|
1049
|
+
const [y, m] = parseWorkoutDate(args.date);
|
|
1050
|
+
return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
|
|
1051
|
+
}
|
|
1052
|
+
//#endregion
|
|
1006
1053
|
//#region src/exercise-set-payload.ts
|
|
1007
1054
|
function slotData(exercise, key) {
|
|
1008
1055
|
const value = exercise?.[key];
|
|
@@ -1770,877 +1817,934 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
|
|
|
1770
1817
|
};
|
|
1771
1818
|
}
|
|
1772
1819
|
//#endregion
|
|
1773
|
-
//#region src/
|
|
1774
|
-
const
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1820
|
+
//#region src/workout-encode.ts
|
|
1821
|
+
const LEADERBOARD_TYPE = {
|
|
1822
|
+
completion: 0,
|
|
1823
|
+
"for completion": 0,
|
|
1824
|
+
weight: 1,
|
|
1825
|
+
lb: 1,
|
|
1826
|
+
load: 1,
|
|
1827
|
+
reps: 2,
|
|
1828
|
+
rep: 2,
|
|
1829
|
+
rounds: 3,
|
|
1830
|
+
round: 3,
|
|
1831
|
+
time: 4,
|
|
1832
|
+
yards: 5,
|
|
1833
|
+
yd: 5,
|
|
1834
|
+
meters: 6,
|
|
1835
|
+
m: 6,
|
|
1836
|
+
feet: 7,
|
|
1837
|
+
ft: 7,
|
|
1838
|
+
calories: 8,
|
|
1839
|
+
cal: 8,
|
|
1840
|
+
cals: 8,
|
|
1841
|
+
miles: 10,
|
|
1842
|
+
mi: 10,
|
|
1843
|
+
inches: 12,
|
|
1844
|
+
in: 12,
|
|
1845
|
+
watts: 15,
|
|
1846
|
+
w: 15,
|
|
1847
|
+
velocity: 17,
|
|
1848
|
+
"m/s": 17,
|
|
1849
|
+
seconds: 18,
|
|
1850
|
+
sec: 18,
|
|
1851
|
+
s: 18
|
|
1852
|
+
};
|
|
1853
|
+
const LEADERBOARD_LABEL = {
|
|
1854
|
+
0: "For Completion",
|
|
1855
|
+
1: "Weight",
|
|
1856
|
+
2: "Reps",
|
|
1857
|
+
3: "Rounds",
|
|
1858
|
+
4: "Time",
|
|
1859
|
+
5: "Yards",
|
|
1860
|
+
6: "Meters",
|
|
1861
|
+
7: "Feet",
|
|
1862
|
+
8: "Calories",
|
|
1863
|
+
10: "Miles",
|
|
1864
|
+
12: "Inches",
|
|
1865
|
+
13: "Other",
|
|
1866
|
+
15: "Watts",
|
|
1867
|
+
16: "Percent",
|
|
1868
|
+
17: "Velocity",
|
|
1869
|
+
18: "Seconds"
|
|
1870
|
+
};
|
|
1871
|
+
function resolveLeaderboard(block) {
|
|
1872
|
+
const lb = block.leaderboard;
|
|
1873
|
+
if (lb === void 0 || lb === null) return {
|
|
1874
|
+
isRedzone: null,
|
|
1875
|
+
redzoneType: 0,
|
|
1876
|
+
smallerIsBetter: null,
|
|
1877
|
+
redzoneInstruction: ""
|
|
1878
|
+
};
|
|
1879
|
+
let unit;
|
|
1880
|
+
let instruction = "";
|
|
1881
|
+
let lowest;
|
|
1882
|
+
if (typeof lb === "object") {
|
|
1883
|
+
unit = lb.unit ?? lb.type;
|
|
1884
|
+
instruction = lb.instruction ?? "";
|
|
1885
|
+
lowest = lb.lowest_wins;
|
|
1886
|
+
} else unit = lb;
|
|
1887
|
+
let rz;
|
|
1888
|
+
if (typeof unit === "string") {
|
|
1889
|
+
const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
|
|
1890
|
+
if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
|
|
1891
|
+
rz = found;
|
|
1892
|
+
} else if (typeof unit === "number") rz = Math.trunc(unit);
|
|
1893
|
+
else throw new Error("Leaderboard requires a unit.");
|
|
1894
|
+
if (lowest === void 0) lowest = rz === 4 || rz === 18;
|
|
1895
|
+
return {
|
|
1896
|
+
isRedzone: 1,
|
|
1897
|
+
redzoneType: rz,
|
|
1898
|
+
smallerIsBetter: lowest ? 1 : 0,
|
|
1899
|
+
redzoneInstruction: instruction
|
|
1900
|
+
};
|
|
1785
1901
|
}
|
|
1786
|
-
|
|
1787
|
-
* The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
|
|
1788
|
-
* name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
|
|
1789
|
-
* and the warehouse store map the roster identically. Includes the account owner and
|
|
1790
|
-
* demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
|
|
1791
|
-
*/
|
|
1792
|
-
async function fetchCoachRoster(client, ids) {
|
|
1793
|
-
const res = await client.request("GET", "/v5/athletes");
|
|
1794
|
-
if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
|
|
1795
|
-
const keep = ids && ids.length > 0 ? new Set(ids) : null;
|
|
1902
|
+
function slots(values, n = 10) {
|
|
1796
1903
|
const out = [];
|
|
1797
|
-
for (
|
|
1798
|
-
if (typeof row !== "object" || row === null) continue;
|
|
1799
|
-
const rec = row;
|
|
1800
|
-
const id = coerceInt(rec.id);
|
|
1801
|
-
if (id === null || id <= 0) continue;
|
|
1802
|
-
if (keep && !keep.has(id)) continue;
|
|
1803
|
-
out.push({
|
|
1804
|
-
id,
|
|
1805
|
-
name: rosterName(rec)
|
|
1806
|
-
});
|
|
1807
|
-
}
|
|
1904
|
+
for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
|
|
1808
1905
|
return out;
|
|
1809
1906
|
}
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
const
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
}
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
|
|
1907
|
+
function repsList(ex) {
|
|
1908
|
+
const reps = ex.reps;
|
|
1909
|
+
if (Array.isArray(reps)) return reps.map((r) => String(r));
|
|
1910
|
+
if (reps === void 0 || reps === null) return [];
|
|
1911
|
+
const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
|
|
1912
|
+
return Array.from({ length: sets }, () => String(reps));
|
|
1913
|
+
}
|
|
1914
|
+
/** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
|
|
1915
|
+
function makeExercise(ex, workoutSetId, order, key) {
|
|
1916
|
+
const reps = repsList(ex);
|
|
1917
|
+
let instruction = ex.instr ?? "";
|
|
1918
|
+
if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
|
|
1919
|
+
const hasWeight = ex.weight !== void 0 && ex.weight !== null;
|
|
1920
|
+
const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
|
|
1921
|
+
let count = reps.length;
|
|
1922
|
+
if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
|
|
1923
|
+
let param2Type;
|
|
1924
|
+
let param2Values;
|
|
1925
|
+
if (hasWeight) {
|
|
1926
|
+
param2Type = ex.param_2_type ?? 1;
|
|
1927
|
+
param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
|
|
1928
|
+
} else {
|
|
1929
|
+
param2Type = 0;
|
|
1930
|
+
param2Values = null;
|
|
1835
1931
|
}
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1932
|
+
const entry = {
|
|
1933
|
+
exercise_id: ex.id,
|
|
1934
|
+
workout_set_id: workoutSetId,
|
|
1935
|
+
set_id: workoutSetId,
|
|
1936
|
+
setKey: workoutSetId,
|
|
1937
|
+
title: ex.title ?? "",
|
|
1938
|
+
instruction,
|
|
1939
|
+
order,
|
|
1940
|
+
param_1_type: ex.param_1_type ?? 3,
|
|
1941
|
+
param_2_type: param2Type,
|
|
1942
|
+
workout_set_exercise_template_id: null,
|
|
1943
|
+
no_sets: 0,
|
|
1944
|
+
param_count: count,
|
|
1945
|
+
set_num: count,
|
|
1946
|
+
key,
|
|
1947
|
+
video_url: "",
|
|
1948
|
+
thumbnail_url: "",
|
|
1949
|
+
tags: [],
|
|
1950
|
+
eType: "e",
|
|
1951
|
+
use_count: 0
|
|
1840
1952
|
};
|
|
1953
|
+
const p1 = slots(reps);
|
|
1954
|
+
const p2 = slots(param2Values);
|
|
1955
|
+
for (let i = 0; i < 10; i += 1) {
|
|
1956
|
+
entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
|
|
1957
|
+
entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
|
|
1958
|
+
}
|
|
1959
|
+
return entry;
|
|
1841
1960
|
}
|
|
1961
|
+
/** Block `type` values the coach calendar accepts (verified in workout-creation.md). */
|
|
1962
|
+
const BLOCK_TYPE_CONDITIONING = 1;
|
|
1963
|
+
const BLOCK_TYPE_HYPERTROPHY = 2;
|
|
1842
1964
|
/**
|
|
1843
|
-
*
|
|
1844
|
-
*
|
|
1845
|
-
* which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
|
|
1965
|
+
* Default block type: text-only (empty exercises) blocks are Conditioning / Circuit (type 1);
|
|
1966
|
+
* structured exercise blocks default to Hypertrophy (type 2). An explicit `type` always wins.
|
|
1846
1967
|
*/
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
|
|
1851
|
-
const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
|
|
1852
|
-
toProgramId: args.toProgramId,
|
|
1853
|
-
pwId: args.pwId,
|
|
1854
|
-
toDate: {
|
|
1855
|
-
date: iso,
|
|
1856
|
-
day,
|
|
1857
|
-
month,
|
|
1858
|
-
year,
|
|
1859
|
-
dayOfWeek,
|
|
1860
|
-
isToday: false
|
|
1861
|
-
}
|
|
1862
|
-
} });
|
|
1863
|
-
if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
|
|
1864
|
-
return res.data;
|
|
1968
|
+
function defaultBlockType(block) {
|
|
1969
|
+
if (block.type !== void 0) return block.type;
|
|
1970
|
+
return block.exercises.length === 0 ? 1 : 2;
|
|
1865
1971
|
}
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
"lift-1rm-history",
|
|
1870
|
-
"training-summary-athlete",
|
|
1871
|
-
"compliance-team",
|
|
1872
|
-
"lift-progress-team",
|
|
1873
|
-
"working-max-history"
|
|
1874
|
-
];
|
|
1875
|
-
const ANALYTICS_METRICS = {
|
|
1876
|
-
"readiness-team": {
|
|
1877
|
-
path: "/v5/analytics/readiness/teams",
|
|
1878
|
-
scope: "team",
|
|
1879
|
-
inputs: ["date"],
|
|
1880
|
-
requires: ["date"]
|
|
1881
|
-
},
|
|
1882
|
-
"readiness-athlete": {
|
|
1883
|
-
path: "/v5/analytics/readiness/users",
|
|
1884
|
-
scope: "user",
|
|
1885
|
-
inputs: ["dateStart", "dateEnd"],
|
|
1886
|
-
requires: ["dateStart", "dateEnd"]
|
|
1887
|
-
},
|
|
1888
|
-
"lift-1rm-history": {
|
|
1889
|
-
path: "/v5/analytics/lift-one-rep-max-history/users",
|
|
1890
|
-
scope: "user",
|
|
1891
|
-
inputs: [
|
|
1892
|
-
"dateStart",
|
|
1893
|
-
"dateEnd",
|
|
1894
|
-
"exerciseId",
|
|
1895
|
-
"useMetric"
|
|
1896
|
-
],
|
|
1897
|
-
requires: [
|
|
1898
|
-
"dateStart",
|
|
1899
|
-
"dateEnd",
|
|
1900
|
-
"exerciseId"
|
|
1901
|
-
]
|
|
1902
|
-
},
|
|
1903
|
-
"training-summary-athlete": {
|
|
1904
|
-
path: "/v5/analytics/training-summary/users",
|
|
1905
|
-
scope: "user",
|
|
1906
|
-
inputs: ["dateStart", "dateEnd"],
|
|
1907
|
-
requires: ["dateStart", "dateEnd"]
|
|
1908
|
-
},
|
|
1909
|
-
"compliance-team": {
|
|
1910
|
-
path: "/v5/analytics/compliance",
|
|
1911
|
-
scope: "team",
|
|
1912
|
-
inputs: ["dateStart", "dateEnd"],
|
|
1913
|
-
requires: ["dateStart", "dateEnd"]
|
|
1914
|
-
},
|
|
1915
|
-
"lift-progress-team": {
|
|
1916
|
-
path: "/v5/analytics/lift-progress/teams",
|
|
1917
|
-
scope: "team",
|
|
1918
|
-
inputs: [
|
|
1919
|
-
"exerciseId",
|
|
1920
|
-
"dateStart",
|
|
1921
|
-
"dateEnd"
|
|
1922
|
-
],
|
|
1923
|
-
requires: [
|
|
1924
|
-
"exerciseId",
|
|
1925
|
-
"dateStart",
|
|
1926
|
-
"dateEnd"
|
|
1927
|
-
]
|
|
1928
|
-
},
|
|
1929
|
-
"working-max-history": {
|
|
1930
|
-
path: "/v5/analytics/working-max-history/users",
|
|
1931
|
-
scope: "user",
|
|
1932
|
-
inputs: [
|
|
1933
|
-
"exerciseId",
|
|
1934
|
-
"dateStart",
|
|
1935
|
-
"dateEnd",
|
|
1936
|
-
"useMetric"
|
|
1937
|
-
],
|
|
1938
|
-
requires: ["exerciseId"]
|
|
1939
|
-
}
|
|
1940
|
-
};
|
|
1941
|
-
/**
|
|
1942
|
-
* A serializable description of every analytics metric: its scope (does it need a `teamId` or
|
|
1943
|
-
* `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
|
|
1944
|
-
* surface this so an agent picks a valid `metric` + params up front, instead of discovering the
|
|
1945
|
-
* shape by trial and error. These curated keys are deliberately NOT the raw category names from
|
|
1946
|
-
* `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
|
|
1947
|
-
*/
|
|
1948
|
-
function analyticsMetricCatalog() {
|
|
1949
|
-
return ANALYTICS_METRIC_KEYS.map((metric) => {
|
|
1950
|
-
const spec = ANALYTICS_METRICS[metric];
|
|
1972
|
+
function buildBlockPayload(blocks, workoutId) {
|
|
1973
|
+
return blocks.map((b, i) => {
|
|
1974
|
+
const lb = resolveLeaderboard(b);
|
|
1951
1975
|
return {
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1976
|
+
workout_id: workoutId,
|
|
1977
|
+
order: i + 1,
|
|
1978
|
+
type: defaultBlockType(b),
|
|
1979
|
+
instruction: b.instruction ?? "",
|
|
1980
|
+
is_redzone: lb.isRedzone,
|
|
1981
|
+
redzone_type: lb.redzoneType,
|
|
1982
|
+
smaller_is_better: lb.smallerIsBetter,
|
|
1983
|
+
redzone_instruction: lb.redzoneInstruction,
|
|
1984
|
+
exercises: [],
|
|
1985
|
+
exerciseKeys: [],
|
|
1986
|
+
key: `k::${workoutId}${i + 1}`,
|
|
1987
|
+
title: b.title
|
|
1957
1988
|
};
|
|
1958
1989
|
});
|
|
1959
1990
|
}
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1991
|
+
function unitOr(t) {
|
|
1992
|
+
return unitLabel(t) ?? "?";
|
|
1993
|
+
}
|
|
1994
|
+
/** Flag spec params the API will silently override to the exercise's fixed units. */
|
|
1995
|
+
function unitAdvisory(blockTitle, ex, defaults) {
|
|
1996
|
+
const notes = [];
|
|
1997
|
+
const warnings = [];
|
|
1998
|
+
const u = unitOr;
|
|
1999
|
+
const label = `${blockTitle} / ${ex.title ?? ex.id}`;
|
|
2000
|
+
if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
|
|
2001
|
+
const sentP1 = ex.param_1_type;
|
|
2002
|
+
if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
|
|
2003
|
+
const sp1 = Math.trunc(Number(sentP1));
|
|
2004
|
+
warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
|
|
2005
|
+
} else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
|
|
2006
|
+
if (ex.weight !== void 0 && ex.weight !== null) {
|
|
2007
|
+
const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
|
|
2008
|
+
const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
|
|
2009
|
+
if (sentP2 !== effP2) if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
|
|
2010
|
+
else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
|
|
2011
|
+
}
|
|
2012
|
+
return {
|
|
2013
|
+
notes,
|
|
2014
|
+
warnings
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
1967
2017
|
/**
|
|
1968
|
-
*
|
|
1969
|
-
*
|
|
1970
|
-
*
|
|
2018
|
+
* Run unit advisories across a whole block list against an exercise index. Shared by the
|
|
2019
|
+
* MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
|
|
2020
|
+
* index is loaded first, otherwise `defaults` returns null on a cold index and every
|
|
2021
|
+
* advisory is silently dropped.
|
|
1971
2022
|
*/
|
|
1972
|
-
async function
|
|
1973
|
-
|
|
1974
|
-
const
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
}
|
|
1982
|
-
const
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
2023
|
+
async function collectAdvisories(blocks, index) {
|
|
2024
|
+
await index.ensureFresh();
|
|
2025
|
+
const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
|
|
2026
|
+
block: b,
|
|
2027
|
+
ex
|
|
2028
|
+
})));
|
|
2029
|
+
const defaults = await Promise.all(pairs.map((p) => {
|
|
2030
|
+
const id = Number(p.ex.id);
|
|
2031
|
+
return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
|
|
2032
|
+
}));
|
|
2033
|
+
const notes = [];
|
|
2034
|
+
const warnings = [];
|
|
2035
|
+
pairs.forEach((p, i) => {
|
|
2036
|
+
const def = defaults[i];
|
|
2037
|
+
if (!def) return;
|
|
2038
|
+
const advisory = unitAdvisory(p.block.title, p.ex, def);
|
|
2039
|
+
notes.push(...advisory.notes);
|
|
2040
|
+
warnings.push(...advisory.warnings);
|
|
2041
|
+
});
|
|
2042
|
+
return {
|
|
2043
|
+
notes,
|
|
2044
|
+
warnings
|
|
1988
2045
|
};
|
|
1989
|
-
const missing = spec.requires.filter((k) => inputs[k] === void 0);
|
|
1990
|
-
if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
|
|
1991
|
-
for (const k of spec.inputs) {
|
|
1992
|
-
const v = inputs[k];
|
|
1993
|
-
if (v === void 0) continue;
|
|
1994
|
-
body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
|
|
1995
|
-
}
|
|
1996
|
-
const res = await client.request("POST", spec.path, { body });
|
|
1997
|
-
if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
|
|
1998
|
-
return res.data;
|
|
1999
2046
|
}
|
|
2047
|
+
//#endregion
|
|
2048
|
+
//#region src/workout-session.ts
|
|
2000
2049
|
/**
|
|
2001
|
-
*
|
|
2002
|
-
*
|
|
2003
|
-
*
|
|
2004
|
-
* given id, matched as a string. Throws when the roster fetch fails.
|
|
2050
|
+
* Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
|
|
2051
|
+
* on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
|
|
2052
|
+
* `copySession` so the hint stays in one place.
|
|
2005
2053
|
*/
|
|
2006
|
-
|
|
2007
|
-
const
|
|
2008
|
-
if (!
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
const
|
|
2015
|
-
|
|
2016
|
-
const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
|
|
2017
|
-
if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
|
|
2054
|
+
function calendarWriteError(method, path, status, detail) {
|
|
2055
|
+
const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
|
|
2056
|
+
if (!(path.includes("/createWorkoutForDay/") || path.includes("/createWorkoutForTimelineDay/") || path.includes("/copyProgramWorkout")) || status !== 500 && status !== 401) return new Error(base);
|
|
2057
|
+
return /* @__PURE__ */ new Error(`${base}. This often means the programId is not a coach-writable calendar — use a team/group programId (list_teams → group_program) or resolve a roster athlete's calendar via GET /v5/calendars/athletes/{athleteId}?year=&month= (workout_build athleteId). Athlete-created personal_cal ad-hoc sessions are a different surface.`);
|
|
2058
|
+
}
|
|
2059
|
+
async function req(client, method, path, body) {
|
|
2060
|
+
const res = await client.request(method, path, body === void 0 ? void 0 : { body });
|
|
2061
|
+
if (!res.ok) {
|
|
2062
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
2063
|
+
throw calendarWriteError(method, path, res.status, detail);
|
|
2018
2064
|
}
|
|
2019
|
-
return
|
|
2065
|
+
return res.data;
|
|
2020
2066
|
}
|
|
2021
|
-
function
|
|
2022
|
-
|
|
2023
|
-
|
|
2067
|
+
function createPath(opts) {
|
|
2068
|
+
if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
|
|
2069
|
+
if (!opts.date) throw new Error("workout build requires either date or timelineDay");
|
|
2070
|
+
const [y, m, d] = opts.date;
|
|
2071
|
+
return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
|
|
2024
2072
|
}
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
});
|
|
2041
|
-
const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
|
|
2042
|
-
const byAthlete = /* @__PURE__ */ new Map();
|
|
2043
|
-
for (const row of rows) {
|
|
2044
|
-
const athleteId = toNum(row.user_id);
|
|
2045
|
-
if (athleteId === 0) continue;
|
|
2046
|
-
const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
|
|
2047
|
-
const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
|
|
2048
|
-
const existing = byAthlete.get(athleteId);
|
|
2049
|
-
if (existing) {
|
|
2050
|
-
existing.sessions += 1;
|
|
2051
|
-
existing.reps += toNum(row.reps);
|
|
2052
|
-
existing.volume += toNum(row.volume);
|
|
2053
|
-
if (date !== null) {
|
|
2054
|
-
if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
|
|
2055
|
-
if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
|
|
2056
|
-
}
|
|
2057
|
-
} else byAthlete.set(athleteId, {
|
|
2058
|
-
athleteId,
|
|
2059
|
-
name,
|
|
2060
|
-
sessions: 1,
|
|
2061
|
-
reps: toNum(row.reps),
|
|
2062
|
-
volume: toNum(row.volume),
|
|
2063
|
-
firstLoggedDate: date,
|
|
2064
|
-
lastLoggedDate: date
|
|
2073
|
+
async function buildSession(client, opts) {
|
|
2074
|
+
const blocks = z.array(blockSpecSchema).parse(opts.blocks);
|
|
2075
|
+
const sess = await req(client, "POST", createPath(opts), {});
|
|
2076
|
+
checkResponse(sessionCreateResponseSchema, sess, "session create");
|
|
2077
|
+
const workoutId = Number(sess.workout_id);
|
|
2078
|
+
const pwId = Number(sess.id);
|
|
2079
|
+
const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
|
|
2080
|
+
const byOrder = new Map(created.map((b) => [b.order, b.id]));
|
|
2081
|
+
let counter = 0;
|
|
2082
|
+
const payloads = blocks.map((block, i) => {
|
|
2083
|
+
const wsid = byOrder.get(i + 1);
|
|
2084
|
+
if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
|
|
2085
|
+
return block.exercises.map((ex, j) => {
|
|
2086
|
+
counter += 1;
|
|
2087
|
+
return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
|
|
2065
2088
|
});
|
|
2066
|
-
}
|
|
2067
|
-
const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
|
|
2068
|
-
const totals = athletes.reduce((acc, a) => ({
|
|
2069
|
-
athletes: acc.athletes + 1,
|
|
2070
|
-
sessions: acc.sessions + a.sessions,
|
|
2071
|
-
reps: acc.reps + a.reps,
|
|
2072
|
-
volume: acc.volume + a.volume
|
|
2073
|
-
}), {
|
|
2074
|
-
athletes: 0,
|
|
2075
|
-
sessions: 0,
|
|
2076
|
-
reps: 0,
|
|
2077
|
-
volume: 0
|
|
2078
2089
|
});
|
|
2090
|
+
await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
|
|
2091
|
+
if (opts.instruction !== void 0 && opts.instruction !== "") {
|
|
2092
|
+
const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
|
|
2093
|
+
await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
|
|
2094
|
+
}
|
|
2095
|
+
if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
|
|
2079
2096
|
return {
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
end: args.dateEnd
|
|
2083
|
-
},
|
|
2084
|
-
athletes,
|
|
2085
|
-
totals
|
|
2097
|
+
pwId,
|
|
2098
|
+
workoutId
|
|
2086
2099
|
};
|
|
2087
2100
|
}
|
|
2088
|
-
//#endregion
|
|
2089
|
-
//#region src/main-lifts.ts
|
|
2090
2101
|
/**
|
|
2091
|
-
*
|
|
2092
|
-
*
|
|
2093
|
-
*
|
|
2094
|
-
*
|
|
2095
|
-
* This is the single place to edit the lift set.
|
|
2102
|
+
* Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
|
|
2103
|
+
* programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
|
|
2104
|
+
* the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
|
|
2105
|
+
* ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
|
|
2096
2106
|
*/
|
|
2097
|
-
|
|
2098
|
-
{
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
label: "Snatch",
|
|
2106
|
-
matches: (t) => t.includes("snatch")
|
|
2107
|
-
},
|
|
2108
|
-
{
|
|
2109
|
-
key: "deadlift",
|
|
2110
|
-
label: "Deadlift",
|
|
2111
|
-
matches: (t) => t.includes("deadlift")
|
|
2112
|
-
},
|
|
2113
|
-
{
|
|
2114
|
-
key: "squat",
|
|
2115
|
-
label: "Squat",
|
|
2116
|
-
matches: (t) => t.includes("squat")
|
|
2117
|
-
},
|
|
2118
|
-
{
|
|
2119
|
-
key: "bench",
|
|
2120
|
-
label: "Bench Press",
|
|
2121
|
-
matches: (t) => t.includes("bench")
|
|
2122
|
-
},
|
|
2123
|
-
{
|
|
2124
|
-
key: "overhead",
|
|
2125
|
-
label: "Overhead Press",
|
|
2126
|
-
matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
|
|
2127
|
-
}
|
|
2128
|
-
];
|
|
2129
|
-
/** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
|
|
2130
|
-
function classifyMainLift(title) {
|
|
2131
|
-
const t = title.toLowerCase();
|
|
2132
|
-
for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
|
|
2133
|
-
return null;
|
|
2107
|
+
async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
|
|
2108
|
+
const body = {
|
|
2109
|
+
...pw,
|
|
2110
|
+
instruction,
|
|
2111
|
+
sets: blockIds,
|
|
2112
|
+
setKeys: blockIds
|
|
2113
|
+
};
|
|
2114
|
+
await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
|
|
2134
2115
|
}
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2116
|
+
async function removeSession(client, programId, pwId) {
|
|
2117
|
+
await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
|
|
2118
|
+
programId,
|
|
2119
|
+
pwId
|
|
2120
|
+
});
|
|
2138
2121
|
}
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
|
2122
|
+
async function publishSession(client, pwId) {
|
|
2123
|
+
await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
|
|
2142
2124
|
}
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
const
|
|
2153
|
-
const
|
|
2154
|
-
const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
|
|
2155
|
-
const tally = /* @__PURE__ */ new Map();
|
|
2156
|
-
let workouts = [];
|
|
2157
|
-
try {
|
|
2158
|
-
workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
|
|
2159
|
-
} catch {
|
|
2160
|
-
workouts = [];
|
|
2161
|
-
}
|
|
2162
|
-
for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
|
|
2163
|
-
if (ex.performed.length === 0 || ex.exerciseId === null) continue;
|
|
2164
|
-
const family = classifyMainLift(ex.title);
|
|
2165
|
-
if (family === null) continue;
|
|
2166
|
-
const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
|
|
2167
|
-
const prev = byId.get(ex.exerciseId);
|
|
2168
|
-
byId.set(ex.exerciseId, {
|
|
2169
|
-
count: (prev?.count ?? 0) + 1,
|
|
2170
|
-
title: prev?.title ?? ex.title
|
|
2171
|
-
});
|
|
2172
|
-
tally.set(family, byId);
|
|
2173
|
-
}
|
|
2174
|
-
const lifts = [];
|
|
2175
|
-
for (const family of MAIN_LIFT_FAMILIES) {
|
|
2176
|
-
const byId = tally.get(family.key);
|
|
2177
|
-
if (!byId || byId.size === 0) continue;
|
|
2178
|
-
let best = null;
|
|
2179
|
-
for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
|
|
2180
|
-
exerciseId,
|
|
2181
|
-
count,
|
|
2182
|
-
title
|
|
2183
|
-
};
|
|
2184
|
-
if (best) lifts.push({
|
|
2185
|
-
family: family.key,
|
|
2186
|
-
label: family.label,
|
|
2187
|
-
exerciseId: best.exerciseId,
|
|
2188
|
-
title: best.title
|
|
2189
|
-
});
|
|
2190
|
-
}
|
|
2125
|
+
function str$1(value) {
|
|
2126
|
+
return value === void 0 || value === null ? "" : String(value);
|
|
2127
|
+
}
|
|
2128
|
+
async function readSession(client, programId, date, pwId) {
|
|
2129
|
+
const [y, m, d] = date;
|
|
2130
|
+
const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
|
|
2131
|
+
checkResponse(programsEditResponseSchema, data, "programs edit");
|
|
2132
|
+
const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
|
|
2133
|
+
if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
|
|
2134
|
+
const setsObj = pw.sets ?? {};
|
|
2135
|
+
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
2191
2136
|
return {
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2137
|
+
pwId,
|
|
2138
|
+
date: `${str$1(pw.year)}-${str$1(pw.month)}-${str$1(pw.day)}`,
|
|
2139
|
+
published: pw.published,
|
|
2140
|
+
instruction: str$1(pw.instruction),
|
|
2141
|
+
blocks
|
|
2195
2142
|
};
|
|
2196
2143
|
}
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2144
|
+
function readBlock(b) {
|
|
2145
|
+
const rz = coerceInt(b.redzone_type);
|
|
2146
|
+
let leaderboard = null;
|
|
2147
|
+
if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
|
|
2148
|
+
const exercises = (Array.isArray(b.exercises) ? b.exercises : []).filter((ex) => coerceInt(ex.id) !== null || str$1(ex.title) !== "").sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
|
|
2149
|
+
return {
|
|
2150
|
+
order: Number(b.order),
|
|
2151
|
+
title: str$1(b.title),
|
|
2152
|
+
instruction: str$1(b.instruction),
|
|
2153
|
+
leaderboard,
|
|
2154
|
+
exercises
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
function readExercise(ex) {
|
|
2158
|
+
const reps = [];
|
|
2159
|
+
const load = [];
|
|
2160
|
+
for (let i = 1; i <= 10; i += 1) {
|
|
2161
|
+
const r = str$1(ex[`param_1_data_${i}`]);
|
|
2162
|
+
if (r !== "") reps.push(r);
|
|
2163
|
+
const w = str$1(ex[`param_2_data_${i}`]);
|
|
2164
|
+
if (w !== "") load.push(w);
|
|
2211
2165
|
}
|
|
2212
|
-
return
|
|
2166
|
+
return {
|
|
2167
|
+
order: Number(ex.order),
|
|
2168
|
+
title: str$1(ex.title),
|
|
2169
|
+
reps,
|
|
2170
|
+
primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
|
|
2171
|
+
load,
|
|
2172
|
+
loadUnit: unitLabel(coerceInt(ex.param_2_type)),
|
|
2173
|
+
instruction: str$1(ex.instruction)
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
//#endregion
|
|
2177
|
+
//#region src/coach.ts
|
|
2178
|
+
const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
2179
|
+
/** Normalize one-or-many emails into a deduped, trimmed list. */
|
|
2180
|
+
function emailList(emails) {
|
|
2181
|
+
return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
|
|
2182
|
+
}
|
|
2183
|
+
/** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
|
|
2184
|
+
function rosterName(rec) {
|
|
2185
|
+
const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
|
|
2186
|
+
if (full !== "") return full;
|
|
2187
|
+
const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
|
|
2188
|
+
return combined !== "" ? combined : null;
|
|
2213
2189
|
}
|
|
2214
2190
|
/**
|
|
2215
|
-
*
|
|
2216
|
-
* (
|
|
2217
|
-
*
|
|
2218
|
-
*
|
|
2219
|
-
* render a stable row of columns.
|
|
2191
|
+
* The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
|
|
2192
|
+
* name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
|
|
2193
|
+
* and the warehouse store map the roster identically. Includes the account owner and
|
|
2194
|
+
* demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
|
|
2220
2195
|
*/
|
|
2221
|
-
async function
|
|
2222
|
-
const
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
units: null,
|
|
2239
|
-
date: null
|
|
2240
|
-
};
|
|
2241
|
-
if (!lift) return {
|
|
2242
|
-
...base,
|
|
2243
|
-
...empty
|
|
2244
|
-
};
|
|
2245
|
-
const known = {
|
|
2246
|
-
exerciseId: lift.exerciseId,
|
|
2247
|
-
title: lift.title
|
|
2248
|
-
};
|
|
2249
|
-
try {
|
|
2250
|
-
const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
|
|
2251
|
-
return {
|
|
2252
|
-
...base,
|
|
2253
|
-
...known,
|
|
2254
|
-
weight: best?.weight ?? null,
|
|
2255
|
-
reps: best?.reps ?? null,
|
|
2256
|
-
units: best?.units ?? null,
|
|
2257
|
-
date: best?.date ?? null
|
|
2258
|
-
};
|
|
2259
|
-
} catch {
|
|
2260
|
-
return {
|
|
2261
|
-
...base,
|
|
2262
|
-
...known,
|
|
2263
|
-
weight: null,
|
|
2264
|
-
reps: null,
|
|
2265
|
-
units: null,
|
|
2266
|
-
date: null
|
|
2267
|
-
};
|
|
2268
|
-
}
|
|
2269
|
-
})
|
|
2270
|
-
};
|
|
2196
|
+
async function fetchCoachRoster(client, ids) {
|
|
2197
|
+
const res = await client.request("GET", "/v5/athletes");
|
|
2198
|
+
if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
|
|
2199
|
+
const keep = ids && ids.length > 0 ? new Set(ids) : null;
|
|
2200
|
+
const out = [];
|
|
2201
|
+
for (const row of res.data) {
|
|
2202
|
+
if (typeof row !== "object" || row === null) continue;
|
|
2203
|
+
const rec = row;
|
|
2204
|
+
const id = coerceInt(rec.id);
|
|
2205
|
+
if (id === null || id <= 0) continue;
|
|
2206
|
+
if (keep && !keep.has(id)) continue;
|
|
2207
|
+
out.push({
|
|
2208
|
+
id,
|
|
2209
|
+
name: rosterName(rec)
|
|
2210
|
+
});
|
|
2211
|
+
}
|
|
2212
|
+
return out;
|
|
2271
2213
|
}
|
|
2272
|
-
const ROSTER_CONCURRENCY = 4;
|
|
2273
2214
|
/**
|
|
2274
|
-
*
|
|
2275
|
-
*
|
|
2276
|
-
* `
|
|
2277
|
-
* to the roster name when the per-athlete read can't supply one. This is the single roster-level
|
|
2278
|
-
* primitive the CLI, the MCP tool, and the warehouse store all build on.
|
|
2215
|
+
* Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
|
|
2216
|
+
* addresses (`POST /v5/emails/validate`), then invite the validated ones
|
|
2217
|
+
* (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
|
|
2279
2218
|
*/
|
|
2280
|
-
async function
|
|
2281
|
-
const
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2219
|
+
async function inviteAthletes(client, args) {
|
|
2220
|
+
const list = emailList(args.emails);
|
|
2221
|
+
if (list.length === 0) throw new Error("Provide at least one email address to invite.");
|
|
2222
|
+
const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
|
|
2223
|
+
if (!validation.ok) {
|
|
2224
|
+
const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
|
|
2225
|
+
throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
|
|
2226
|
+
}
|
|
2227
|
+
const valid = Array.isArray(validation.data) ? validation.data : list;
|
|
2228
|
+
if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
|
|
2229
|
+
const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
|
|
2230
|
+
teamType: 0,
|
|
2231
|
+
teamId: args.teamId,
|
|
2232
|
+
orgId: null,
|
|
2233
|
+
emails: valid,
|
|
2234
|
+
message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
|
|
2235
|
+
} });
|
|
2236
|
+
if (!invite.ok) {
|
|
2237
|
+
const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
|
|
2238
|
+
throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
|
|
2239
|
+
}
|
|
2240
|
+
return {
|
|
2241
|
+
teamId: args.teamId,
|
|
2242
|
+
invited: valid,
|
|
2243
|
+
result: invite.data
|
|
2285
2244
|
};
|
|
2286
|
-
return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
|
|
2287
|
-
const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
|
|
2288
|
-
return {
|
|
2289
|
-
athleteId: athlete.id,
|
|
2290
|
-
athleteName: result.athleteName ?? athlete.name,
|
|
2291
|
-
prs: result.prs
|
|
2292
|
-
};
|
|
2293
|
-
});
|
|
2294
2245
|
}
|
|
2295
|
-
//#endregion
|
|
2296
|
-
//#region src/util.ts
|
|
2297
2246
|
/**
|
|
2298
|
-
*
|
|
2299
|
-
* spread into an object under `exactOptionalPropertyTypes` without the per-key
|
|
2300
|
-
* `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
|
|
2301
|
-
* optional ones lose `undefined` from their value type.
|
|
2247
|
+
* Update a team's title and/or reassign its calendar (`PUT /v5/teams/{teamId}`).
|
|
2302
2248
|
*
|
|
2303
|
-
*
|
|
2304
|
-
*
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
ft: 7,
|
|
2330
|
-
calories: 8,
|
|
2331
|
-
cal: 8,
|
|
2332
|
-
cals: 8,
|
|
2333
|
-
miles: 10,
|
|
2334
|
-
mi: 10,
|
|
2335
|
-
inches: 12,
|
|
2336
|
-
in: 12,
|
|
2337
|
-
watts: 15,
|
|
2338
|
-
w: 15,
|
|
2339
|
-
velocity: 17,
|
|
2340
|
-
"m/s": 17,
|
|
2341
|
-
seconds: 18,
|
|
2342
|
-
sec: 18,
|
|
2343
|
-
s: 18
|
|
2344
|
-
};
|
|
2345
|
-
const LEADERBOARD_LABEL = {
|
|
2346
|
-
0: "For Completion",
|
|
2347
|
-
1: "Weight",
|
|
2348
|
-
2: "Reps",
|
|
2349
|
-
3: "Rounds",
|
|
2350
|
-
4: "Time",
|
|
2351
|
-
5: "Yards",
|
|
2352
|
-
6: "Meters",
|
|
2353
|
-
7: "Feet",
|
|
2354
|
-
8: "Calories",
|
|
2355
|
-
10: "Miles",
|
|
2356
|
-
12: "Inches",
|
|
2357
|
-
13: "Other",
|
|
2358
|
-
15: "Watts",
|
|
2359
|
-
16: "Percent",
|
|
2360
|
-
17: "Velocity",
|
|
2361
|
-
18: "Seconds"
|
|
2362
|
-
};
|
|
2363
|
-
function resolveLeaderboard(block) {
|
|
2364
|
-
const lb = block.leaderboard;
|
|
2365
|
-
if (lb === void 0 || lb === null) return {
|
|
2366
|
-
isRedzone: null,
|
|
2367
|
-
redzoneType: 0,
|
|
2368
|
-
smallerIsBetter: null,
|
|
2369
|
-
redzoneInstruction: ""
|
|
2370
|
-
};
|
|
2371
|
-
let unit;
|
|
2372
|
-
let instruction = "";
|
|
2373
|
-
let lowest;
|
|
2374
|
-
if (typeof lb === "object") {
|
|
2375
|
-
unit = lb.unit ?? lb.type;
|
|
2376
|
-
instruction = lb.instruction ?? "";
|
|
2377
|
-
lowest = lb.lowest_wins;
|
|
2378
|
-
} else unit = lb;
|
|
2379
|
-
let rz;
|
|
2380
|
-
if (typeof unit === "string") {
|
|
2381
|
-
const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
|
|
2382
|
-
if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
|
|
2383
|
-
rz = found;
|
|
2384
|
-
} else if (typeof unit === "number") rz = Math.trunc(unit);
|
|
2385
|
-
else throw new Error("Leaderboard requires a unit.");
|
|
2386
|
-
if (lowest === void 0) lowest = rz === 4 || rz === 18;
|
|
2387
|
-
return {
|
|
2388
|
-
isRedzone: 1,
|
|
2389
|
-
redzoneType: rz,
|
|
2390
|
-
smallerIsBetter: lowest ? 1 : 0,
|
|
2391
|
-
redzoneInstruction: instruction
|
|
2392
|
-
};
|
|
2393
|
-
}
|
|
2394
|
-
function slots(values, n = 10) {
|
|
2395
|
-
const out = [];
|
|
2396
|
-
for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
|
|
2397
|
-
return out;
|
|
2398
|
-
}
|
|
2399
|
-
function repsList(ex) {
|
|
2400
|
-
const reps = ex.reps;
|
|
2401
|
-
if (Array.isArray(reps)) return reps.map((r) => String(r));
|
|
2402
|
-
if (reps === void 0 || reps === null) return [];
|
|
2403
|
-
const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
|
|
2404
|
-
return Array.from({ length: sets }, () => String(reps));
|
|
2249
|
+
* The live API accepts `group_program` to point the team at an existing parent program /
|
|
2250
|
+
* calendar (e.g. another team's `group_program` from `list_teams`), but rejects a body that
|
|
2251
|
+
* has only `group_program` (HTTP 400 "Invalid parameters"). When `title` is omitted we read
|
|
2252
|
+
* the current title first so callers can re-link without renaming.
|
|
2253
|
+
*/
|
|
2254
|
+
async function updateTeam(client, args) {
|
|
2255
|
+
if (args.title === void 0 && args.groupProgram === void 0) throw new Error("Provide title and/or groupProgram.");
|
|
2256
|
+
let title = args.title;
|
|
2257
|
+
if (title === void 0) {
|
|
2258
|
+
const existing = await client.request("GET", `/v5/teams/${args.teamId}`);
|
|
2259
|
+
if (!existing.ok) {
|
|
2260
|
+
const detail = typeof existing.data === "string" ? existing.data : JSON.stringify(existing.data);
|
|
2261
|
+
throw new Error(`GET /v5/teams/${args.teamId} failed (HTTP ${existing.status}): ${detail}`);
|
|
2262
|
+
}
|
|
2263
|
+
const rec = existing.data && typeof existing.data === "object" ? existing.data : null;
|
|
2264
|
+
title = typeof rec?.title === "string" ? rec.title : "";
|
|
2265
|
+
if (title.trim() === "") throw new Error(`Could not read current title for team ${args.teamId}; pass title explicitly.`);
|
|
2266
|
+
}
|
|
2267
|
+
const body = { title };
|
|
2268
|
+
if (args.groupProgram !== void 0) body.group_program = args.groupProgram;
|
|
2269
|
+
const res = await client.request("PUT", `/v5/teams/${args.teamId}`, { body });
|
|
2270
|
+
if (!res.ok) {
|
|
2271
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
2272
|
+
throw new Error(`PUT /v5/teams/${args.teamId} failed (HTTP ${res.status}): ${detail}`);
|
|
2273
|
+
}
|
|
2274
|
+
return res.data;
|
|
2405
2275
|
}
|
|
2406
|
-
/**
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
const
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2276
|
+
/**
|
|
2277
|
+
* Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
|
|
2278
|
+
* The API wants the target date as a structured object (with weekday and an isToday flag),
|
|
2279
|
+
* which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
|
|
2280
|
+
*/
|
|
2281
|
+
async function copySession(client, args) {
|
|
2282
|
+
const [year, month, day] = parseWorkoutDate(args.toDate);
|
|
2283
|
+
const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
|
|
2284
|
+
const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
|
|
2285
|
+
const path = "/2.0/coach/calendar/copyProgramWorkout";
|
|
2286
|
+
const res = await client.request("POST", path, { body: {
|
|
2287
|
+
toProgramId: args.toProgramId,
|
|
2288
|
+
pwId: args.pwId,
|
|
2289
|
+
toDate: {
|
|
2290
|
+
date: iso,
|
|
2291
|
+
day,
|
|
2292
|
+
month,
|
|
2293
|
+
year,
|
|
2294
|
+
dayOfWeek,
|
|
2295
|
+
isToday: false
|
|
2296
|
+
}
|
|
2297
|
+
} });
|
|
2298
|
+
if (!res.ok) {
|
|
2299
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
2300
|
+
throw calendarWriteError("POST", path, res.status, detail);
|
|
2423
2301
|
}
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2302
|
+
return res.data;
|
|
2303
|
+
}
|
|
2304
|
+
const ANALYTICS_METRIC_KEYS = [
|
|
2305
|
+
"readiness-team",
|
|
2306
|
+
"readiness-athlete",
|
|
2307
|
+
"lift-1rm-history",
|
|
2308
|
+
"training-summary-athlete",
|
|
2309
|
+
"compliance-team",
|
|
2310
|
+
"lift-progress-team",
|
|
2311
|
+
"working-max-history"
|
|
2312
|
+
];
|
|
2313
|
+
const ANALYTICS_METRICS = {
|
|
2314
|
+
"readiness-team": {
|
|
2315
|
+
path: "/v5/analytics/readiness/teams",
|
|
2316
|
+
scope: "team",
|
|
2317
|
+
inputs: ["date"],
|
|
2318
|
+
requires: ["date"]
|
|
2319
|
+
},
|
|
2320
|
+
"readiness-athlete": {
|
|
2321
|
+
path: "/v5/analytics/readiness/users",
|
|
2322
|
+
scope: "user",
|
|
2323
|
+
inputs: ["dateStart", "dateEnd"],
|
|
2324
|
+
requires: ["dateStart", "dateEnd"]
|
|
2325
|
+
},
|
|
2326
|
+
"lift-1rm-history": {
|
|
2327
|
+
path: "/v5/analytics/lift-one-rep-max-history/users",
|
|
2328
|
+
scope: "user",
|
|
2329
|
+
inputs: [
|
|
2330
|
+
"dateStart",
|
|
2331
|
+
"dateEnd",
|
|
2332
|
+
"exerciseId",
|
|
2333
|
+
"useMetric"
|
|
2334
|
+
],
|
|
2335
|
+
requires: [
|
|
2336
|
+
"dateStart",
|
|
2337
|
+
"dateEnd",
|
|
2338
|
+
"exerciseId"
|
|
2339
|
+
]
|
|
2340
|
+
},
|
|
2341
|
+
"training-summary-athlete": {
|
|
2342
|
+
path: "/v5/analytics/training-summary/users",
|
|
2343
|
+
scope: "user",
|
|
2344
|
+
inputs: ["dateStart", "dateEnd"],
|
|
2345
|
+
requires: ["dateStart", "dateEnd"]
|
|
2346
|
+
},
|
|
2347
|
+
"compliance-team": {
|
|
2348
|
+
path: "/v5/analytics/compliance",
|
|
2349
|
+
scope: "team",
|
|
2350
|
+
inputs: ["dateStart", "dateEnd"],
|
|
2351
|
+
requires: ["dateStart", "dateEnd"]
|
|
2352
|
+
},
|
|
2353
|
+
"lift-progress-team": {
|
|
2354
|
+
path: "/v5/analytics/lift-progress/teams",
|
|
2355
|
+
scope: "team",
|
|
2356
|
+
inputs: [
|
|
2357
|
+
"exerciseId",
|
|
2358
|
+
"dateStart",
|
|
2359
|
+
"dateEnd"
|
|
2360
|
+
],
|
|
2361
|
+
requires: [
|
|
2362
|
+
"exerciseId",
|
|
2363
|
+
"dateStart",
|
|
2364
|
+
"dateEnd"
|
|
2365
|
+
]
|
|
2366
|
+
},
|
|
2367
|
+
"working-max-history": {
|
|
2368
|
+
path: "/v5/analytics/working-max-history/users",
|
|
2369
|
+
scope: "user",
|
|
2370
|
+
inputs: [
|
|
2371
|
+
"exerciseId",
|
|
2372
|
+
"dateStart",
|
|
2373
|
+
"dateEnd",
|
|
2374
|
+
"useMetric"
|
|
2375
|
+
],
|
|
2376
|
+
requires: ["exerciseId"]
|
|
2450
2377
|
}
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2378
|
+
};
|
|
2379
|
+
/**
|
|
2380
|
+
* A serializable description of every analytics metric: its scope (does it need a `teamId` or
|
|
2381
|
+
* `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
|
|
2382
|
+
* surface this so an agent picks a valid `metric` + params up front, instead of discovering the
|
|
2383
|
+
* shape by trial and error. These curated keys are deliberately NOT the raw category names from
|
|
2384
|
+
* `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
|
|
2385
|
+
*/
|
|
2386
|
+
function analyticsMetricCatalog() {
|
|
2387
|
+
return ANALYTICS_METRIC_KEYS.map((metric) => {
|
|
2388
|
+
const spec = ANALYTICS_METRICS[metric];
|
|
2456
2389
|
return {
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
redzone_type: lb.redzoneType,
|
|
2463
|
-
smaller_is_better: lb.smallerIsBetter,
|
|
2464
|
-
redzone_instruction: lb.redzoneInstruction,
|
|
2465
|
-
exercises: [],
|
|
2466
|
-
exerciseKeys: [],
|
|
2467
|
-
key: `k::${workoutId}${i + 1}`,
|
|
2468
|
-
title: b.title
|
|
2390
|
+
metric,
|
|
2391
|
+
scope: spec.scope,
|
|
2392
|
+
scopeParam: spec.scope === "team" ? "teamId" : "userIds",
|
|
2393
|
+
requires: [...spec.requires],
|
|
2394
|
+
optional: spec.inputs.filter((i) => !spec.requires.includes(i))
|
|
2469
2395
|
};
|
|
2470
2396
|
});
|
|
2471
2397
|
}
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
if (
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2398
|
+
const ANALYTICS_BODY_KEY = {
|
|
2399
|
+
date: "date",
|
|
2400
|
+
dateStart: "date_start",
|
|
2401
|
+
dateEnd: "date_end",
|
|
2402
|
+
exerciseId: "exercise_id",
|
|
2403
|
+
useMetric: "use_metric"
|
|
2404
|
+
};
|
|
2405
|
+
/**
|
|
2406
|
+
* Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
|
|
2407
|
+
* athlete metrics need one or more `userIds` (passed together — the report returns a row per
|
|
2408
|
+
* athlete). Throws a readable Error when a required input is missing or the call fails.
|
|
2409
|
+
*/
|
|
2410
|
+
async function queryAnalytics(client, args) {
|
|
2411
|
+
const spec = ANALYTICS_METRICS[args.metric];
|
|
2412
|
+
const body = {};
|
|
2413
|
+
if (spec.scope === "team") {
|
|
2414
|
+
if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
|
|
2415
|
+
body.teamId = args.teamId;
|
|
2416
|
+
} else {
|
|
2417
|
+
if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
|
|
2418
|
+
body.user_ids = args.userIds.map((u) => String(u));
|
|
2492
2419
|
}
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2420
|
+
const inputs = {
|
|
2421
|
+
date: args.date,
|
|
2422
|
+
dateStart: args.dateStart,
|
|
2423
|
+
dateEnd: args.dateEnd,
|
|
2424
|
+
exerciseId: args.exerciseId,
|
|
2425
|
+
useMetric: args.useMetric
|
|
2496
2426
|
};
|
|
2427
|
+
const missing = spec.requires.filter((k) => inputs[k] === void 0);
|
|
2428
|
+
if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
|
|
2429
|
+
for (const k of spec.inputs) {
|
|
2430
|
+
const v = inputs[k];
|
|
2431
|
+
if (v === void 0) continue;
|
|
2432
|
+
body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
|
|
2433
|
+
}
|
|
2434
|
+
const res = await client.request("POST", spec.path, { body });
|
|
2435
|
+
if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
|
|
2436
|
+
return res.data;
|
|
2497
2437
|
}
|
|
2498
2438
|
/**
|
|
2499
|
-
*
|
|
2500
|
-
*
|
|
2501
|
-
*
|
|
2502
|
-
*
|
|
2439
|
+
* Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
|
|
2440
|
+
* place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
|
|
2441
|
+
* there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
|
|
2442
|
+
* given id, matched as a string. Throws when the roster fetch fails.
|
|
2503
2443
|
*/
|
|
2504
|
-
async function
|
|
2505
|
-
await
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
const
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2444
|
+
async function fetchTeamAthleteIds(client, teamId) {
|
|
2445
|
+
const res = await client.request("GET", "/v5/athletes");
|
|
2446
|
+
if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
|
|
2447
|
+
const rows = Array.isArray(res.data) ? res.data : [];
|
|
2448
|
+
const want = String(teamId);
|
|
2449
|
+
const ids = [];
|
|
2450
|
+
for (const row of rows) {
|
|
2451
|
+
if (row === null || typeof row !== "object") continue;
|
|
2452
|
+
const rec = row;
|
|
2453
|
+
if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
|
|
2454
|
+
const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
|
|
2455
|
+
if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
|
|
2456
|
+
}
|
|
2457
|
+
return ids;
|
|
2458
|
+
}
|
|
2459
|
+
function toNum(v) {
|
|
2460
|
+
const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
|
|
2461
|
+
return Number.isFinite(n) ? n : 0;
|
|
2462
|
+
}
|
|
2463
|
+
/**
|
|
2464
|
+
* Team-wide training volume over an inclusive date window. The `training-summary-athlete`
|
|
2465
|
+
* analytics report already returns the team in one call — one row per logged session across all
|
|
2466
|
+
* `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
|
|
2467
|
+
* volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
|
|
2468
|
+
* logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
|
|
2469
|
+
* all-time `fetchRosterActivity` snapshot, which has no date range.
|
|
2470
|
+
*/
|
|
2471
|
+
async function teamVolume(client, args) {
|
|
2472
|
+
if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
|
|
2473
|
+
const report = await queryAnalytics(client, {
|
|
2474
|
+
metric: "training-summary-athlete",
|
|
2475
|
+
userIds: args.athleteIds,
|
|
2476
|
+
dateStart: args.dateStart,
|
|
2477
|
+
dateEnd: args.dateEnd
|
|
2478
|
+
});
|
|
2479
|
+
const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
|
|
2480
|
+
const byAthlete = /* @__PURE__ */ new Map();
|
|
2481
|
+
for (const row of rows) {
|
|
2482
|
+
const athleteId = toNum(row.user_id);
|
|
2483
|
+
if (athleteId === 0) continue;
|
|
2484
|
+
const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
|
|
2485
|
+
const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
|
|
2486
|
+
const existing = byAthlete.get(athleteId);
|
|
2487
|
+
if (existing) {
|
|
2488
|
+
existing.sessions += 1;
|
|
2489
|
+
existing.reps += toNum(row.reps);
|
|
2490
|
+
existing.volume += toNum(row.volume);
|
|
2491
|
+
if (date !== null) {
|
|
2492
|
+
if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
|
|
2493
|
+
if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
|
|
2494
|
+
}
|
|
2495
|
+
} else byAthlete.set(athleteId, {
|
|
2496
|
+
athleteId,
|
|
2497
|
+
name,
|
|
2498
|
+
sessions: 1,
|
|
2499
|
+
reps: toNum(row.reps),
|
|
2500
|
+
volume: toNum(row.volume),
|
|
2501
|
+
firstLoggedDate: date,
|
|
2502
|
+
lastLoggedDate: date
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
|
|
2506
|
+
const totals = athletes.reduce((acc, a) => ({
|
|
2507
|
+
athletes: acc.athletes + 1,
|
|
2508
|
+
sessions: acc.sessions + a.sessions,
|
|
2509
|
+
reps: acc.reps + a.reps,
|
|
2510
|
+
volume: acc.volume + a.volume
|
|
2511
|
+
}), {
|
|
2512
|
+
athletes: 0,
|
|
2513
|
+
sessions: 0,
|
|
2514
|
+
reps: 0,
|
|
2515
|
+
volume: 0
|
|
2522
2516
|
});
|
|
2523
2517
|
return {
|
|
2524
|
-
|
|
2525
|
-
|
|
2518
|
+
window: {
|
|
2519
|
+
start: args.dateStart,
|
|
2520
|
+
end: args.dateEnd
|
|
2521
|
+
},
|
|
2522
|
+
athletes,
|
|
2523
|
+
totals
|
|
2526
2524
|
};
|
|
2527
2525
|
}
|
|
2528
2526
|
//#endregion
|
|
2529
|
-
//#region src/
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2527
|
+
//#region src/main-lifts.ts
|
|
2528
|
+
/**
|
|
2529
|
+
* The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
|
|
2530
|
+
* first family that matches, so the more specific / easily-confused families come before the broad
|
|
2531
|
+
* overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
|
|
2532
|
+
* swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
|
|
2533
|
+
* This is the single place to edit the lift set.
|
|
2534
|
+
*/
|
|
2535
|
+
const MAIN_LIFT_FAMILIES = [
|
|
2536
|
+
{
|
|
2537
|
+
key: "cleanjerk",
|
|
2538
|
+
label: "Clean & Jerk",
|
|
2539
|
+
matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
|
|
2540
|
+
},
|
|
2541
|
+
{
|
|
2542
|
+
key: "snatch",
|
|
2543
|
+
label: "Snatch",
|
|
2544
|
+
matches: (t) => t.includes("snatch")
|
|
2545
|
+
},
|
|
2546
|
+
{
|
|
2547
|
+
key: "deadlift",
|
|
2548
|
+
label: "Deadlift",
|
|
2549
|
+
matches: (t) => t.includes("deadlift")
|
|
2550
|
+
},
|
|
2551
|
+
{
|
|
2552
|
+
key: "squat",
|
|
2553
|
+
label: "Squat",
|
|
2554
|
+
matches: (t) => t.includes("squat")
|
|
2555
|
+
},
|
|
2556
|
+
{
|
|
2557
|
+
key: "bench",
|
|
2558
|
+
label: "Bench Press",
|
|
2559
|
+
matches: (t) => t.includes("bench")
|
|
2560
|
+
},
|
|
2561
|
+
{
|
|
2562
|
+
key: "overhead",
|
|
2563
|
+
label: "Overhead Press",
|
|
2564
|
+
matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
|
|
2535
2565
|
}
|
|
2536
|
-
|
|
2566
|
+
];
|
|
2567
|
+
/** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
|
|
2568
|
+
function classifyMainLift(title) {
|
|
2569
|
+
const t = title.toLowerCase();
|
|
2570
|
+
for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
|
|
2571
|
+
return null;
|
|
2537
2572
|
}
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
const [y, m, d] = opts.date;
|
|
2542
|
-
return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
|
|
2573
|
+
const DEFAULT_MONTHS = 12;
|
|
2574
|
+
function pad2(n) {
|
|
2575
|
+
return String(n).padStart(2, "0");
|
|
2543
2576
|
}
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2577
|
+
/** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
|
|
2578
|
+
function isoDay(d) {
|
|
2579
|
+
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
|
2580
|
+
}
|
|
2581
|
+
/**
|
|
2582
|
+
* Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
|
|
2583
|
+
* logged workouts over the last `months` (default 12) — the program-workout range, the reliable
|
|
2584
|
+
* record of performed sets — buckets every performed exercise into a lift family, and for each
|
|
2585
|
+
* family picks the variant logged most often. Returns one entry per family the athlete has logged;
|
|
2586
|
+
* families they never trained are simply absent. (The monthly calendar summary is not used: it
|
|
2587
|
+
* comes back empty for some accounts that have logged sets in the range endpoint.)
|
|
2588
|
+
*/
|
|
2589
|
+
async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
2590
|
+
const months = opts.months ?? DEFAULT_MONTHS;
|
|
2591
|
+
const now = opts.now ?? /* @__PURE__ */ new Date();
|
|
2592
|
+
const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
|
|
2593
|
+
const tally = /* @__PURE__ */ new Map();
|
|
2594
|
+
let workouts = [];
|
|
2595
|
+
try {
|
|
2596
|
+
workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
|
|
2597
|
+
} catch {
|
|
2598
|
+
workouts = [];
|
|
2599
|
+
}
|
|
2600
|
+
for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
|
|
2601
|
+
if (ex.performed.length === 0 || ex.exerciseId === null) continue;
|
|
2602
|
+
const family = classifyMainLift(ex.title);
|
|
2603
|
+
if (family === null) continue;
|
|
2604
|
+
const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
|
|
2605
|
+
const prev = byId.get(ex.exerciseId);
|
|
2606
|
+
byId.set(ex.exerciseId, {
|
|
2607
|
+
count: (prev?.count ?? 0) + 1,
|
|
2608
|
+
title: prev?.title ?? ex.title
|
|
2609
|
+
});
|
|
2610
|
+
tally.set(family, byId);
|
|
2611
|
+
}
|
|
2612
|
+
const lifts = [];
|
|
2613
|
+
for (const family of MAIN_LIFT_FAMILIES) {
|
|
2614
|
+
const byId = tally.get(family.key);
|
|
2615
|
+
if (!byId || byId.size === 0) continue;
|
|
2616
|
+
let best = null;
|
|
2617
|
+
for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
|
|
2618
|
+
exerciseId,
|
|
2619
|
+
count,
|
|
2620
|
+
title
|
|
2621
|
+
};
|
|
2622
|
+
if (best) lifts.push({
|
|
2623
|
+
family: family.key,
|
|
2624
|
+
label: family.label,
|
|
2625
|
+
exerciseId: best.exerciseId,
|
|
2626
|
+
title: best.title
|
|
2558
2627
|
});
|
|
2559
|
-
});
|
|
2560
|
-
await Promise.all(payloads.map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
|
|
2561
|
-
if (opts.instruction !== void 0 && opts.instruction !== "") {
|
|
2562
|
-
const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
|
|
2563
|
-
await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
|
|
2564
2628
|
}
|
|
2565
|
-
if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
|
|
2566
2629
|
return {
|
|
2567
|
-
|
|
2568
|
-
|
|
2630
|
+
athleteId,
|
|
2631
|
+
athleteName: null,
|
|
2632
|
+
lifts
|
|
2569
2633
|
};
|
|
2570
2634
|
}
|
|
2635
|
+
const PR_CONCURRENCY = 5;
|
|
2636
|
+
/** The heaviest PR on an exercise's board (ties broken by more reps). */
|
|
2637
|
+
function bestPr(liftPRs) {
|
|
2638
|
+
let best = null;
|
|
2639
|
+
for (const pr of liftPRs) {
|
|
2640
|
+
const weight = coerceNum(pr.weight);
|
|
2641
|
+
if (weight === null) continue;
|
|
2642
|
+
const reps = coerceInt(pr.reps);
|
|
2643
|
+
if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
|
|
2644
|
+
weight,
|
|
2645
|
+
reps,
|
|
2646
|
+
units: pr.units,
|
|
2647
|
+
date: pr.date
|
|
2648
|
+
};
|
|
2649
|
+
}
|
|
2650
|
+
return best;
|
|
2651
|
+
}
|
|
2571
2652
|
/**
|
|
2572
|
-
*
|
|
2573
|
-
*
|
|
2574
|
-
*
|
|
2575
|
-
*
|
|
2653
|
+
* A roster athlete's best PR for each main lift. Discovers the lift variants they log
|
|
2654
|
+
* ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
|
|
2655
|
+
* The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
|
|
2656
|
+
* athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
|
|
2657
|
+
* render a stable row of columns.
|
|
2576
2658
|
*/
|
|
2577
|
-
async function
|
|
2578
|
-
const
|
|
2579
|
-
|
|
2580
|
-
instruction,
|
|
2581
|
-
sets: blockIds,
|
|
2582
|
-
setKeys: blockIds
|
|
2583
|
-
};
|
|
2584
|
-
await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
|
|
2585
|
-
}
|
|
2586
|
-
async function removeSession(client, programId, pwId) {
|
|
2587
|
-
await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
|
|
2588
|
-
programId,
|
|
2589
|
-
pwId
|
|
2590
|
-
});
|
|
2591
|
-
}
|
|
2592
|
-
async function publishSession(client, pwId) {
|
|
2593
|
-
await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
|
|
2594
|
-
}
|
|
2595
|
-
function str$1(value) {
|
|
2596
|
-
return value === void 0 || value === null ? "" : String(value);
|
|
2597
|
-
}
|
|
2598
|
-
async function readSession(client, programId, date, pwId) {
|
|
2599
|
-
const [y, m, d] = date;
|
|
2600
|
-
const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
|
|
2601
|
-
checkResponse(programsEditResponseSchema, data, "programs edit");
|
|
2602
|
-
const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
|
|
2603
|
-
if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
|
|
2604
|
-
const setsObj = pw.sets ?? {};
|
|
2605
|
-
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
2659
|
+
async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
|
|
2660
|
+
const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
|
|
2661
|
+
const byFamily = new Map(lifts.map((l) => [l.family, l]));
|
|
2606
2662
|
return {
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2663
|
+
athleteId,
|
|
2664
|
+
athleteName,
|
|
2665
|
+
prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
|
|
2666
|
+
const lift = byFamily.get(family.key);
|
|
2667
|
+
const base = {
|
|
2668
|
+
family: family.key,
|
|
2669
|
+
label: family.label
|
|
2670
|
+
};
|
|
2671
|
+
const empty = {
|
|
2672
|
+
exerciseId: null,
|
|
2673
|
+
title: null,
|
|
2674
|
+
weight: null,
|
|
2675
|
+
reps: null,
|
|
2676
|
+
units: null,
|
|
2677
|
+
date: null
|
|
2678
|
+
};
|
|
2679
|
+
if (!lift) return {
|
|
2680
|
+
...base,
|
|
2681
|
+
...empty
|
|
2682
|
+
};
|
|
2683
|
+
const known = {
|
|
2684
|
+
exerciseId: lift.exerciseId,
|
|
2685
|
+
title: lift.title
|
|
2686
|
+
};
|
|
2687
|
+
try {
|
|
2688
|
+
const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
|
|
2689
|
+
return {
|
|
2690
|
+
...base,
|
|
2691
|
+
...known,
|
|
2692
|
+
weight: best?.weight ?? null,
|
|
2693
|
+
reps: best?.reps ?? null,
|
|
2694
|
+
units: best?.units ?? null,
|
|
2695
|
+
date: best?.date ?? null
|
|
2696
|
+
};
|
|
2697
|
+
} catch {
|
|
2698
|
+
return {
|
|
2699
|
+
...base,
|
|
2700
|
+
...known,
|
|
2701
|
+
weight: null,
|
|
2702
|
+
reps: null,
|
|
2703
|
+
units: null,
|
|
2704
|
+
date: null
|
|
2705
|
+
};
|
|
2706
|
+
}
|
|
2707
|
+
})
|
|
2612
2708
|
};
|
|
2613
2709
|
}
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2710
|
+
const ROSTER_CONCURRENCY = 4;
|
|
2711
|
+
/**
|
|
2712
|
+
* Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
|
|
2713
|
+
* resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
|
|
2714
|
+
* `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
|
|
2715
|
+
* to the roster name when the per-athlete read can't supply one. This is the single roster-level
|
|
2716
|
+
* primitive the CLI, the MCP tool, and the warehouse store all build on.
|
|
2717
|
+
*/
|
|
2718
|
+
async function fetchRosterMainLiftPRs(client, opts = {}) {
|
|
2719
|
+
const roster = await fetchCoachRoster(client, opts.athleteIds);
|
|
2720
|
+
const inner = {
|
|
2721
|
+
...opts.months !== void 0 ? { months: opts.months } : {},
|
|
2722
|
+
...opts.now !== void 0 ? { now: opts.now } : {}
|
|
2624
2723
|
};
|
|
2724
|
+
return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
|
|
2725
|
+
const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
|
|
2726
|
+
return {
|
|
2727
|
+
athleteId: athlete.id,
|
|
2728
|
+
athleteName: result.athleteName ?? athlete.name,
|
|
2729
|
+
prs: result.prs
|
|
2730
|
+
};
|
|
2731
|
+
});
|
|
2625
2732
|
}
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
loadUnit: unitLabel(coerceInt(ex.param_2_type)),
|
|
2642
|
-
instruction: str$1(ex.instruction)
|
|
2643
|
-
};
|
|
2733
|
+
//#endregion
|
|
2734
|
+
//#region src/util.ts
|
|
2735
|
+
/**
|
|
2736
|
+
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
2737
|
+
* spread into an object under `exactOptionalPropertyTypes` without the per-key
|
|
2738
|
+
* `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
|
|
2739
|
+
* optional ones lose `undefined` from their value type.
|
|
2740
|
+
*
|
|
2741
|
+
* Example:
|
|
2742
|
+
* definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
|
|
2743
|
+
*/
|
|
2744
|
+
function definedProps(obj) {
|
|
2745
|
+
const result = {};
|
|
2746
|
+
for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
|
|
2747
|
+
return result;
|
|
2644
2748
|
}
|
|
2645
2749
|
//#endregion
|
|
2646
2750
|
//#region src/messaging.ts
|
|
@@ -2875,4 +2979,4 @@ var ExerciseLibrary = class {
|
|
|
2875
2979
|
}
|
|
2876
2980
|
};
|
|
2877
2981
|
//#endregion
|
|
2878
|
-
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, 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, dateWindows, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
|
2982
|
+
export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, 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, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|