@trainheroic-unofficial/js 2.1.1 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -163,16 +163,17 @@ declare function mapPool<T, R>(items: readonly T[], limit: number, fn: (item: T,
163
163
  * The exercise-library surface the tools depend on, so the tools work over either a
164
164
  * D1-backed mirror (hosted, multi-tenant) or an in-memory cache (local, single-user).
165
165
  */
166
+ type ExerciseDefaults = {
167
+ param1: number | null;
168
+ param2: number | null;
169
+ };
166
170
  interface ExerciseIndex {
167
171
  ensureFresh(): Promise<void>;
168
172
  refresh(): Promise<Record<string, unknown>>;
169
173
  resolve(name: string): Promise<ResolveResult>;
170
174
  search(query: string, limit?: number): Promise<ExerciseView[]>;
171
175
  get(id: number): Promise<Record<string, unknown> | null>;
172
- defaults(id: number): Promise<{
173
- param1: number | null;
174
- param2: number | null;
175
- } | null>;
176
+ defaultsMany(ids: readonly number[]): Promise<Map<number, ExerciseDefaults>>;
176
177
  create(body: Record<string, unknown>): Promise<Record<string, unknown>>;
177
178
  recordDelete(id: number): Promise<void>;
178
179
  stats(): Promise<Record<string, unknown>>;
@@ -878,6 +879,7 @@ declare function teamVolume(client: TrainHeroicClient, args: {
878
879
  declare function definedProps<T extends object>(obj: T): { [K in keyof T]: Exclude<T[K], undefined>; };
879
880
  //#endregion
880
881
  //#region src/workout-encode.d.ts
882
+ type AdvisoryIndex = Pick<ExerciseIndex, "defaultsMany" | "ensureFresh">;
881
883
  declare const LEADERBOARD_TYPE: Readonly<Record<string, number>>;
882
884
  declare const LEADERBOARD_LABEL: Readonly<Record<number, string>>;
883
885
  type Leaderboard = {
@@ -907,10 +909,10 @@ declare function unitAdvisory(blockTitle: string, ex: ExerciseSpec, defaults: {
907
909
  /**
908
910
  * Run unit advisories across a whole block list against an exercise index. Shared by the
909
911
  * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
910
- * index is loaded first, otherwise `defaults` returns null on a cold index and every
912
+ * index is loaded first, otherwise the defaults map is empty on a cold index and every
911
913
  * advisory is silently dropped.
912
914
  */
913
- declare function collectAdvisories(blocks: readonly BlockSpec[], index: ExerciseIndex): Promise<Advisory>;
915
+ declare function collectAdvisories(blocks: readonly BlockSpec[], index: AdvisoryIndex): Promise<Advisory>;
914
916
  //#endregion
915
917
  //#region src/workout-session.d.ts
916
918
  type BuildOptions = {
@@ -956,7 +958,7 @@ declare function fetchStreams(client: TrainHeroicClient): Promise<Array<{
956
958
  declare function buildCommentPayload(streamId: number, text: string, replyTo?: number | null): Record<string, unknown>;
957
959
  declare function sendComment(client: TrainHeroicClient, streamId: number, text: string, replyTo?: number | null): Promise<Record<string, unknown>>;
958
960
  declare function deleteComment(client: TrainHeroicClient, streamId: number, commentId: number): Promise<unknown>;
959
- declare function readLive(client: TrainHeroicClient, streamId: number, limit?: number): Promise<unknown[]>;
961
+ declare function readLive(client: TrainHeroicClient, streamId: number, limit?: number, afterCommentId?: number): Promise<unknown[]>;
960
962
  //#endregion
961
963
  //#region src/exercise-index.d.ts
962
964
  /**
@@ -970,10 +972,7 @@ declare class ExerciseLibrary implements ExerciseIndex {
970
972
  ensureFresh(): Promise<void>;
971
973
  refresh(): Promise<Record<string, unknown>>;
972
974
  get(id: number): Promise<Record<string, unknown> | null>;
973
- defaults(id: number): Promise<{
974
- param1: number | null;
975
- param2: number | null;
976
- } | null>;
975
+ defaultsMany(ids: readonly number[]): Promise<Map<number, ExerciseDefaults>>;
977
976
  search(query: string, limit?: number): Promise<ExerciseView[]>;
978
977
  resolve(name: string): Promise<ResolveResult>;
979
978
  create(body: Record<string, unknown>): Promise<Record<string, unknown>>;
@@ -981,4 +980,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
981
980
  stats(): Promise<Record<string, unknown>>;
982
981
  }
983
982
  //#endregion
984
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, 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 };
983
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseDefaults, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, 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 };
package/dist/index.mjs CHANGED
@@ -439,8 +439,9 @@ function sortRosterByRecency(rows) {
439
439
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
440
440
  const rows = [];
441
441
  const concurrency = 6;
442
- for (let i = 0; i < athleteIds.length; i += concurrency) {
443
- const chunk = athleteIds.slice(i, i + concurrency);
442
+ const uniqueAthleteIds = [...new Set(athleteIds)];
443
+ for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
444
+ const chunk = uniqueAthleteIds.slice(i, i + concurrency);
444
445
  const settled = await Promise.all(chunk.map(async (id) => {
445
446
  try {
446
447
  return {
@@ -1618,7 +1619,7 @@ function prescribedExerciseLabels(workouts) {
1618
1619
  return labels;
1619
1620
  }
1620
1621
  /** Group resolved exercises by saved set and write each set via the given log target. */
1621
- async function logResolvedExercises(client, target, date, resolved) {
1622
+ async function logResolvedExercises(client, target, workouts, resolved) {
1622
1623
  const bySet = /* @__PURE__ */ new Map();
1623
1624
  for (const r of resolved) {
1624
1625
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -1630,19 +1631,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1630
1631
  }
1631
1632
  const out = [];
1632
1633
  for (const [savedWorkoutSetId, results] of bySet) {
1633
- const written = target.role === "coach" ? await logForAthlete(client, {
1634
- athleteId: target.athleteId,
1635
- date,
1636
- savedWorkoutSetId,
1637
- results
1638
- }) : await logAthleteSet(client, {
1639
- date,
1640
- savedWorkoutSetId,
1641
- results
1642
- });
1634
+ const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
1643
1635
  out.push({
1644
1636
  savedWorkoutSetId: written.savedWorkoutSetId,
1645
- exercisesLogged: written.exercisesLogged
1637
+ exercisesLogged: written.exercisesWritten
1646
1638
  });
1647
1639
  }
1648
1640
  return out;
@@ -1680,7 +1672,7 @@ async function logAdHocSession(client, args) {
1680
1672
  sets: e.sets
1681
1673
  };
1682
1674
  });
1683
- const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
1675
+ const sets = await logResolvedExercises(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), resolved);
1684
1676
  const result = {
1685
1677
  date: args.date,
1686
1678
  created,
@@ -1718,7 +1710,7 @@ async function logSessionForAthlete(client, args) {
1718
1710
  const sets = await logResolvedExercises(client, {
1719
1711
  role: "coach",
1720
1712
  athleteId: args.athleteId
1721
- }, args.date, resolved);
1713
+ }, day, resolved);
1722
1714
  return {
1723
1715
  date: args.date,
1724
1716
  created: false,
@@ -2054,7 +2046,7 @@ function unitAdvisory(blockTitle, ex, defaults) {
2054
2046
  /**
2055
2047
  * Run unit advisories across a whole block list against an exercise index. Shared by the
2056
2048
  * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2057
- * index is loaded first, otherwise `defaults` returns null on a cold index and every
2049
+ * index is loaded first, otherwise the defaults map is empty on a cold index and every
2058
2050
  * advisory is silently dropped.
2059
2051
  */
2060
2052
  async function collectAdvisories(blocks, index) {
@@ -2063,14 +2055,12 @@ async function collectAdvisories(blocks, index) {
2063
2055
  block: b,
2064
2056
  ex
2065
2057
  })));
2066
- const defaults = await Promise.all(pairs.map((p) => {
2067
- const id = Number(p.ex.id);
2068
- return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2069
- }));
2058
+ const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
2059
+ const defaultsById = await index.defaultsMany(ids);
2070
2060
  const notes = [];
2071
2061
  const warnings = [];
2072
- pairs.forEach((p, i) => {
2073
- const def = defaults[i];
2062
+ pairs.forEach((p) => {
2063
+ const def = defaultsById.get(Number(p.ex.id));
2074
2064
  if (!def) return;
2075
2065
  const advisory = unitAdvisory(p.block.title, p.ex, def);
2076
2066
  notes.push(...advisory.notes);
@@ -2083,6 +2073,7 @@ async function collectAdvisories(blocks, index) {
2083
2073
  }
2084
2074
  //#endregion
2085
2075
  //#region src/workout-session.ts
2076
+ const EXERCISE_SAVE_CONCURRENCY = 4;
2086
2077
  /**
2087
2078
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2088
2079
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -2116,15 +2107,14 @@ async function buildSession(client, opts) {
2116
2107
  const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2117
2108
  const byOrder = new Map(created.map((b) => [b.order, b.id]));
2118
2109
  let counter = 0;
2119
- const payloads = blocks.map((block, i) => {
2110
+ await mapPool(blocks.map((block, i) => {
2120
2111
  const wsid = byOrder.get(i + 1);
2121
2112
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2122
2113
  return block.exercises.map((ex, j) => {
2123
2114
  counter += 1;
2124
2115
  return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2125
2116
  });
2126
- });
2127
- await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2117
+ }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (payload) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", payload));
2128
2118
  if (opts.instruction !== void 0 && opts.instruction !== "") {
2129
2119
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2130
2120
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -2330,7 +2320,8 @@ async function copySession(client, args) {
2330
2320
  year,
2331
2321
  dayOfWeek,
2332
2322
  isToday: false
2333
- }
2323
+ },
2324
+ toTimelineDate: null
2334
2325
  } });
2335
2326
  if (!res.ok) {
2336
2327
  const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
@@ -2832,9 +2823,11 @@ async function deleteComment(client, streamId, commentId) {
2832
2823
  if (!res.ok) throw new Error(`Message delete failed (HTTP ${res.status}).`);
2833
2824
  return res.data;
2834
2825
  }
2835
- async function readLive(client, streamId, limit) {
2836
- const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=`);
2826
+ async function readLive(client, streamId, limit, afterCommentId) {
2827
+ const cursor = afterCommentId === void 0 ? "" : String(afterCommentId);
2828
+ const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=${cursor}`);
2837
2829
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`Message read failed (HTTP ${res.status}).`);
2830
+ if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
2838
2831
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
2839
2832
  }
2840
2833
  //#endregion
@@ -2938,12 +2931,16 @@ var ExerciseLibrary = class {
2938
2931
  if (!s) return null;
2939
2932
  return presentExercise(s.raw);
2940
2933
  }
2941
- async defaults(id) {
2942
- const s = this.#byId.get(id);
2943
- return s ? {
2944
- param1: s.param_1_type,
2945
- param2: s.param_2_type
2946
- } : null;
2934
+ async defaultsMany(ids) {
2935
+ const result = /* @__PURE__ */ new Map();
2936
+ for (const id of ids) {
2937
+ const s = this.#byId.get(id);
2938
+ if (s) result.set(id, {
2939
+ param1: s.param_1_type,
2940
+ param2: s.param_2_type
2941
+ });
2942
+ }
2943
+ return result;
2947
2944
  }
2948
2945
  async search(query, limit = 20) {
2949
2946
  await this.ensureFresh();
@@ -2961,21 +2958,12 @@ var ExerciseLibrary = class {
2961
2958
  }
2962
2959
  async resolve(name) {
2963
2960
  await this.ensureFresh();
2964
- let hit = this.#exact(name);
2961
+ const hit = this.#exact(name);
2965
2962
  if (hit) return {
2966
2963
  match: hit,
2967
2964
  candidates: [hit]
2968
2965
  };
2969
- let candidates = this.#searchOnly(name, 20);
2970
- if (candidates.length === 0) {
2971
- await this.refresh();
2972
- hit = this.#exact(name);
2973
- if (hit) return {
2974
- match: hit,
2975
- candidates: [hit]
2976
- };
2977
- candidates = this.#searchOnly(name, 20);
2978
- }
2966
+ const candidates = this.#searchOnly(name, 20);
2979
2967
  if (candidates.length === 1) return {
2980
2968
  match: candidates[0] ?? null,
2981
2969
  candidates
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "2.1.1",
3
+ "version": "3.0.1",
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": "2.1.1"
30
+ "@trainheroic-unofficial/dto": "3.0.1"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.2.0",