@trainheroic-unofficial/js 1.4.0 → 1.5.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 +30 -7
- package/dist/index.mjs +151 -76
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -66,6 +66,9 @@ declare const PARAM_WEIGHT = 1;
|
|
|
66
66
|
declare const PARAM_PCT_MAX = 2;
|
|
67
67
|
declare const PARAM_REPS = 3;
|
|
68
68
|
declare const PARAM_RPE = 14;
|
|
69
|
+
/** TrainHeroic stores up to 10 sets per exercise as `param_N_data_1..10`. One source of truth for
|
|
70
|
+
* the bound, shared by the workout presenters and the set-logging write path. */
|
|
71
|
+
declare const MAX_PARAM_SLOTS = 10;
|
|
69
72
|
declare function coerceInt(value: unknown): number | null;
|
|
70
73
|
declare function coerceNum(value: unknown): number | null;
|
|
71
74
|
declare function unitLabel(paramType: unknown): string | null;
|
|
@@ -88,6 +91,8 @@ declare function unwrapEnvelope(body: unknown): unknown;
|
|
|
88
91
|
/** Pull the exercise array out of whatever shape the bulk endpoint returns. */
|
|
89
92
|
declare function asExerciseList(body: unknown): Array<Record<string, unknown>>;
|
|
90
93
|
declare function isRecord(x: unknown): x is Record<string, unknown>;
|
|
94
|
+
/** A non-empty string, or null. Narrows a loosely-typed API field to a usable string. */
|
|
95
|
+
declare function str(v: unknown): string | null;
|
|
91
96
|
/**
|
|
92
97
|
* Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
|
|
93
98
|
* exact title, then prefix, then count of matched tokens, with shorter titles and
|
|
@@ -252,16 +257,22 @@ declare function summarizeAthleteWorkouts(list: readonly AthleteWorkoutView[]):
|
|
|
252
257
|
* specific lift's PRs.
|
|
253
258
|
*/
|
|
254
259
|
declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId: number, year: number, month: number): CoachAthleteTraining;
|
|
260
|
+
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
261
|
+
declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
|
|
262
|
+
//#endregion
|
|
263
|
+
//#region src/athlete-set-write.d.ts
|
|
255
264
|
/**
|
|
256
265
|
* One set of entered values for a single exercise within a saved workout set.
|
|
257
266
|
* `param1` and `param2` correspond to the exercise's first and second parameter types
|
|
258
|
-
* (e.g. reps and weight).
|
|
267
|
+
* (e.g. reps and weight). Optional `slot` is the 1-based prescribed position this set fills;
|
|
268
|
+
* omit it and the sets fill positions sequentially from the first. At most 10 sets are supported.
|
|
259
269
|
*/
|
|
260
270
|
type SetResult = {
|
|
261
271
|
savedWorkoutSetExerciseId: number;
|
|
262
272
|
sets: Array<{
|
|
263
273
|
param1?: number | string;
|
|
264
274
|
param2?: number | string;
|
|
275
|
+
slot?: number;
|
|
265
276
|
}>;
|
|
266
277
|
};
|
|
267
278
|
/**
|
|
@@ -282,6 +293,7 @@ declare function toSetResults(results: ReadonlyArray<{
|
|
|
282
293
|
sets: ReadonlyArray<{
|
|
283
294
|
param1?: number | string | undefined;
|
|
284
295
|
param2?: number | string | undefined;
|
|
296
|
+
slot?: number | undefined;
|
|
285
297
|
}>;
|
|
286
298
|
}>): SetResult[];
|
|
287
299
|
/**
|
|
@@ -291,20 +303,31 @@ declare function toSetResults(results: ReadonlyArray<{
|
|
|
291
303
|
*
|
|
292
304
|
* `mode` selects which write this is — the same endpoint serves both:
|
|
293
305
|
* - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
|
|
294
|
-
* and the exercise `completed` flag is 1 when any set has data.
|
|
306
|
+
* and the exercise `completed` flag is 1 when any set has logged data.
|
|
295
307
|
* - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
|
|
296
308
|
* `completed` left at 0 so the set is not marked done. This matches what the app sends when a
|
|
297
309
|
* coach edits an athlete's prescribed reps/weight.
|
|
298
310
|
*
|
|
311
|
+
* Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
|
|
312
|
+
* when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
|
|
313
|
+
* it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
|
|
314
|
+
* a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
|
|
315
|
+
* (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
|
|
316
|
+
* the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
|
|
317
|
+
* sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
|
|
318
|
+
* copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
|
|
319
|
+
*
|
|
299
320
|
* Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
|
|
300
|
-
* required from the live exercise record; everything else is derived from `results
|
|
321
|
+
* required from the live exercise record; everything else is derived from `results` and the
|
|
322
|
+
* preserved slots of `existing`.
|
|
301
323
|
*
|
|
302
324
|
* Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
|
|
303
325
|
*/
|
|
304
326
|
declare function buildExerciseSetPayload(savedWorkoutSetExerciseId: number, savedWorkoutSetId: number, workoutSetExerciseId: number, results: readonly {
|
|
305
327
|
param1?: number | string;
|
|
306
328
|
param2?: number | string;
|
|
307
|
-
|
|
329
|
+
slot?: number;
|
|
330
|
+
}[], mode: SetWriteMode, existing?: Record<string, unknown>): Record<string, unknown>;
|
|
308
331
|
/**
|
|
309
332
|
* Locate the target saved workout set across all program workouts on the given day.
|
|
310
333
|
* Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
|
|
@@ -356,6 +379,7 @@ declare function logAthleteSet(client: TrainHeroicClient, args: {
|
|
|
356
379
|
}): Promise<{
|
|
357
380
|
savedWorkoutSetId: number;
|
|
358
381
|
exercisesLogged: number;
|
|
382
|
+
setCompleted: boolean;
|
|
359
383
|
}>;
|
|
360
384
|
/**
|
|
361
385
|
* Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
|
|
@@ -375,6 +399,7 @@ declare function logForAthlete(client: TrainHeroicClient, args: {
|
|
|
375
399
|
}): Promise<{
|
|
376
400
|
savedWorkoutSetId: number;
|
|
377
401
|
exercisesLogged: number;
|
|
402
|
+
setCompleted: boolean;
|
|
378
403
|
}>;
|
|
379
404
|
/**
|
|
380
405
|
* Coach prescription override: set the prescribed reps/weight for one of a roster athlete's saved
|
|
@@ -498,8 +523,6 @@ declare function logSessionForAthlete(client: TrainHeroicClient, args: {
|
|
|
498
523
|
date: string;
|
|
499
524
|
exercises: readonly SessionExercise[];
|
|
500
525
|
}): Promise<LogSessionResult>;
|
|
501
|
-
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
502
|
-
declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
|
|
503
526
|
//#endregion
|
|
504
527
|
//#region src/main-lifts.d.ts
|
|
505
528
|
type MainLiftFamilyKey = "cleanjerk" | "snatch" | "deadlift" | "squat" | "bench" | "overhead";
|
|
@@ -775,4 +798,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
775
798
|
stats(): Promise<Record<string, unknown>>;
|
|
776
799
|
}
|
|
777
800
|
//#endregion
|
|
778
|
-
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BuildOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
801
|
+
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BuildOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
package/dist/index.mjs
CHANGED
|
@@ -177,6 +177,9 @@ const PARAM_WEIGHT = 1;
|
|
|
177
177
|
const PARAM_PCT_MAX = 2;
|
|
178
178
|
const PARAM_REPS = 3;
|
|
179
179
|
const PARAM_RPE = 14;
|
|
180
|
+
/** TrainHeroic stores up to 10 sets per exercise as `param_N_data_1..10`. One source of truth for
|
|
181
|
+
* the bound, shared by the workout presenters and the set-logging write path. */
|
|
182
|
+
const MAX_PARAM_SLOTS = 10;
|
|
180
183
|
function coerceInt(value) {
|
|
181
184
|
if (typeof value === "boolean") return value ? 1 : 0;
|
|
182
185
|
if (typeof value === "number") return Number.isFinite(value) ? Math.trunc(value) : null;
|
|
@@ -270,6 +273,10 @@ function asExerciseList(body) {
|
|
|
270
273
|
function isRecord(x) {
|
|
271
274
|
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
272
275
|
}
|
|
276
|
+
/** A non-empty string, or null. Narrows a loosely-typed API field to a usable string. */
|
|
277
|
+
function str(v) {
|
|
278
|
+
return typeof v === "string" && v !== "" ? v : null;
|
|
279
|
+
}
|
|
273
280
|
/**
|
|
274
281
|
* Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
|
|
275
282
|
* exact title, then prefix, then count of matched tokens, with shorter titles and
|
|
@@ -454,7 +461,6 @@ function fetchLeaderboard(client, workoutId, opts = {}) {
|
|
|
454
461
|
const query = qs.toString();
|
|
455
462
|
return getJson(client, `/3.0/athlete/leaderboard/${workoutId}${query ? `?${query}` : ""}`, "athlete leaderboard");
|
|
456
463
|
}
|
|
457
|
-
const SLOTS = 10;
|
|
458
464
|
function nonEmpty(value) {
|
|
459
465
|
return value !== void 0 && value !== null && String(value).trim() !== "";
|
|
460
466
|
}
|
|
@@ -465,7 +471,7 @@ function nonEmpty(value) {
|
|
|
465
471
|
*/
|
|
466
472
|
function prescribedSets(ex) {
|
|
467
473
|
const out = [];
|
|
468
|
-
for (let i = 1; i <=
|
|
474
|
+
for (let i = 1; i <= 10; i += 1) {
|
|
469
475
|
const p1 = ex[`param_1_data_${i}`];
|
|
470
476
|
const p2 = ex[`param_2_data_${i}`];
|
|
471
477
|
const has1 = nonEmpty(p1);
|
|
@@ -486,7 +492,7 @@ function prescribedSets(ex) {
|
|
|
486
492
|
*/
|
|
487
493
|
function performedSets(ex) {
|
|
488
494
|
const out = [];
|
|
489
|
-
for (let i = 1; i <=
|
|
495
|
+
for (let i = 1; i <= 10; i += 1) {
|
|
490
496
|
if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
|
|
491
497
|
const p1 = ex[`param_1_data_${i}`];
|
|
492
498
|
const p2 = ex[`param_2_data_${i}`];
|
|
@@ -520,9 +526,6 @@ function presentBlock(set, performedById) {
|
|
|
520
526
|
exercises: exercises.filter(isRecord).map((ex) => presentExercise$1(ex, performedById))
|
|
521
527
|
};
|
|
522
528
|
}
|
|
523
|
-
function str$1(v) {
|
|
524
|
-
return typeof v === "string" && v !== "" ? v : null;
|
|
525
|
-
}
|
|
526
529
|
/** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
|
|
527
530
|
function savedSets(saved) {
|
|
528
531
|
const out = [];
|
|
@@ -607,11 +610,11 @@ function presentAthleteWorkout(raw) {
|
|
|
607
610
|
}
|
|
608
611
|
return {
|
|
609
612
|
id: coerceInt(rec.id),
|
|
610
|
-
date: str
|
|
611
|
-
title: str
|
|
612
|
-
program: str
|
|
613
|
-
team: str
|
|
614
|
-
instruction: str
|
|
613
|
+
date: str(rec.date) ?? "",
|
|
614
|
+
title: str(rec.workout_title) ?? "",
|
|
615
|
+
program: str(rec.program_title),
|
|
616
|
+
team: str(rec.team_title),
|
|
617
|
+
instruction: str(workout.instruction),
|
|
615
618
|
logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
|
|
616
619
|
blocks
|
|
617
620
|
};
|
|
@@ -636,7 +639,7 @@ function selectWorkoutsByProgram(list, filter) {
|
|
|
636
639
|
if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
|
|
637
640
|
if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
|
|
638
641
|
if (needle) {
|
|
639
|
-
if (`${str
|
|
642
|
+
if (`${str(rec.program_title) ?? ""} ${str(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
|
|
640
643
|
}
|
|
641
644
|
return false;
|
|
642
645
|
});
|
|
@@ -657,11 +660,11 @@ function presentLogTargets(list) {
|
|
|
657
660
|
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
658
661
|
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
659
662
|
if (!saved) continue;
|
|
660
|
-
const date = str
|
|
661
|
-
const workoutTitle = str
|
|
662
|
-
const program = str
|
|
663
|
+
const date = str(rec.date) ?? "";
|
|
664
|
+
const workoutTitle = str(rec.workout_title) ?? "";
|
|
665
|
+
const program = str(rec.program_title);
|
|
663
666
|
const programId = coerceInt(rec.program_id);
|
|
664
|
-
const team = str
|
|
667
|
+
const team = str(rec.team_title);
|
|
665
668
|
const teamId = coerceInt(rec.team_id);
|
|
666
669
|
const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
|
|
667
670
|
for (const s of sets) {
|
|
@@ -687,7 +690,7 @@ function presentLogTargets(list) {
|
|
|
687
690
|
team,
|
|
688
691
|
teamId,
|
|
689
692
|
savedWorkoutSetId,
|
|
690
|
-
setTitle: str
|
|
693
|
+
setTitle: str(s.title),
|
|
691
694
|
exercises
|
|
692
695
|
});
|
|
693
696
|
}
|
|
@@ -775,7 +778,29 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
|
|
|
775
778
|
sessions
|
|
776
779
|
};
|
|
777
780
|
}
|
|
778
|
-
|
|
781
|
+
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
782
|
+
function presentExerciseHistory(detail) {
|
|
783
|
+
return {
|
|
784
|
+
liftPRs: (detail.liftPRs ?? []).map((p) => ({
|
|
785
|
+
description: p.description ?? null,
|
|
786
|
+
reps: p.reps ?? null,
|
|
787
|
+
weight: p.weight ?? null,
|
|
788
|
+
units: p.units ?? null,
|
|
789
|
+
date: p.dateCompleted ?? null
|
|
790
|
+
})),
|
|
791
|
+
sessions: (detail.history ?? []).map((h) => ({
|
|
792
|
+
date: h.dateCompleted,
|
|
793
|
+
abr: h.abr ?? null,
|
|
794
|
+
estimated1RM: h.bestEstimated1RM ?? null,
|
|
795
|
+
sets: (h.sets ?? []).map((s) => ({
|
|
796
|
+
setNumber: s.setNumber,
|
|
797
|
+
value: s.formattedValue ?? null
|
|
798
|
+
}))
|
|
799
|
+
}))
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
//#endregion
|
|
803
|
+
//#region src/athlete-set-write.ts
|
|
779
804
|
/**
|
|
780
805
|
* Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
|
|
781
806
|
* {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
|
|
@@ -790,10 +815,11 @@ function toSetResults(results) {
|
|
|
790
815
|
return {
|
|
791
816
|
savedWorkoutSetExerciseId: id,
|
|
792
817
|
sets: r.sets.map((s) => {
|
|
793
|
-
const
|
|
794
|
-
if (s.param1 !== void 0)
|
|
795
|
-
if (s.param2 !== void 0)
|
|
796
|
-
|
|
818
|
+
const set = {};
|
|
819
|
+
if (s.param1 !== void 0) set.param1 = s.param1;
|
|
820
|
+
if (s.param2 !== void 0) set.param2 = s.param2;
|
|
821
|
+
if (s.slot !== void 0) set.slot = s.slot;
|
|
822
|
+
return set;
|
|
797
823
|
})
|
|
798
824
|
};
|
|
799
825
|
});
|
|
@@ -805,36 +831,96 @@ function toSetResults(results) {
|
|
|
805
831
|
*
|
|
806
832
|
* `mode` selects which write this is — the same endpoint serves both:
|
|
807
833
|
* - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
|
|
808
|
-
* and the exercise `completed` flag is 1 when any set has data.
|
|
834
|
+
* and the exercise `completed` flag is 1 when any set has logged data.
|
|
809
835
|
* - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
|
|
810
836
|
* `completed` left at 0 so the set is not marked done. This matches what the app sends when a
|
|
811
837
|
* coach edits an athlete's prescribed reps/weight.
|
|
812
838
|
*
|
|
839
|
+
* Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
|
|
840
|
+
* when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
|
|
841
|
+
* it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
|
|
842
|
+
* a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
|
|
843
|
+
* (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
|
|
844
|
+
* the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
|
|
845
|
+
* sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
|
|
846
|
+
* copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
|
|
847
|
+
*
|
|
813
848
|
* Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
|
|
814
|
-
* required from the live exercise record; everything else is derived from `results
|
|
849
|
+
* required from the live exercise record; everything else is derived from `results` and the
|
|
850
|
+
* preserved slots of `existing`.
|
|
815
851
|
*
|
|
816
852
|
* Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
|
|
817
853
|
*/
|
|
818
|
-
function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
|
|
819
|
-
if (results.length >
|
|
854
|
+
function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
|
|
855
|
+
if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
|
|
856
|
+
const bySlot = /* @__PURE__ */ new Map();
|
|
857
|
+
results.forEach((set, i) => {
|
|
858
|
+
const slot = set.slot ?? i + 1;
|
|
859
|
+
if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
|
|
860
|
+
if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
|
|
861
|
+
bySlot.set(slot, set);
|
|
862
|
+
});
|
|
820
863
|
const performed = mode === "log";
|
|
821
|
-
const
|
|
864
|
+
const carryOver = performed && existing !== void 0;
|
|
822
865
|
const body = {
|
|
823
866
|
id: savedWorkoutSetExerciseId,
|
|
824
867
|
saved_workout_set_id: savedWorkoutSetId,
|
|
825
|
-
workout_set_exercise_id: workoutSetExerciseId
|
|
826
|
-
completed: performed && hasData ? 1 : 0
|
|
868
|
+
workout_set_exercise_id: workoutSetExerciseId
|
|
827
869
|
};
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
const
|
|
831
|
-
|
|
832
|
-
|
|
870
|
+
let anyMade = false;
|
|
871
|
+
for (let i = 1; i <= 10; i += 1) {
|
|
872
|
+
const target = bySlot.get(i);
|
|
873
|
+
let p1;
|
|
874
|
+
let p2;
|
|
875
|
+
let made;
|
|
876
|
+
if (target) {
|
|
877
|
+
p1 = target.param1 !== void 0 ? String(target.param1) : "";
|
|
878
|
+
p2 = target.param2 !== void 0 ? String(target.param2) : "";
|
|
879
|
+
made = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
|
|
880
|
+
} else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
|
|
881
|
+
p1 = existingSlotData(existing, `param_1_data_${i}`);
|
|
882
|
+
p2 = existingSlotData(existing, `param_2_data_${i}`);
|
|
883
|
+
made = 1;
|
|
884
|
+
} else {
|
|
885
|
+
p1 = "";
|
|
886
|
+
p2 = "";
|
|
887
|
+
made = 0;
|
|
888
|
+
}
|
|
889
|
+
if (made === 1) anyMade = true;
|
|
890
|
+
body[`param_${i}_made`] = made;
|
|
833
891
|
body[`param_1_data_${i}`] = p1;
|
|
834
892
|
body[`param_2_data_${i}`] = p2;
|
|
835
893
|
}
|
|
894
|
+
body.completed = performed && anyMade ? 1 : 0;
|
|
836
895
|
return body;
|
|
837
896
|
}
|
|
897
|
+
/** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
|
|
898
|
+
function existingSlotData(existing, key) {
|
|
899
|
+
const v = existing?.[key];
|
|
900
|
+
return v === void 0 || v === null ? "" : String(v);
|
|
901
|
+
}
|
|
902
|
+
/** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
|
|
903
|
+
function exerciseHasLoggedData(ex) {
|
|
904
|
+
for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
|
|
905
|
+
return false;
|
|
906
|
+
}
|
|
907
|
+
/** True when a result carries at least one non-empty param value (so it produces a performed slot). */
|
|
908
|
+
function resultHasData(result) {
|
|
909
|
+
return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "" || s.param2 !== void 0 && String(s.param2) !== "");
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Whether every exercise in a saved workout set now has logged data — either written with data in
|
|
913
|
+
* this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
|
|
914
|
+
* superset/circuit stays open until the last exercise is logged, so completing it on a partial log
|
|
915
|
+
* does not flip its still-empty siblings to "done". An exercise written with only empty values does
|
|
916
|
+
* not count (it would not be marked performed), so an all-empty log never completes the set.
|
|
917
|
+
*/
|
|
918
|
+
function isSetFullyLogged(exercises, loggedIds) {
|
|
919
|
+
return exercises.every((ex) => {
|
|
920
|
+
const id = coerceInt(ex.id);
|
|
921
|
+
return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
|
|
922
|
+
});
|
|
923
|
+
}
|
|
838
924
|
/**
|
|
839
925
|
* Locate the target saved workout set across all program workouts on the given day.
|
|
840
926
|
* Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
|
|
@@ -933,7 +1019,8 @@ async function logAthleteSet(client, args) {
|
|
|
933
1019
|
const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
|
|
934
1020
|
return {
|
|
935
1021
|
savedWorkoutSetId: r.savedWorkoutSetId,
|
|
936
|
-
exercisesLogged: r.exercisesWritten
|
|
1022
|
+
exercisesLogged: r.exercisesWritten,
|
|
1023
|
+
setCompleted: r.setCompleted
|
|
937
1024
|
};
|
|
938
1025
|
}
|
|
939
1026
|
/**
|
|
@@ -954,7 +1041,8 @@ async function logForAthlete(client, args) {
|
|
|
954
1041
|
}, workouts, args.savedWorkoutSetId, args.results, "log");
|
|
955
1042
|
return {
|
|
956
1043
|
savedWorkoutSetId: r.savedWorkoutSetId,
|
|
957
|
-
exercisesLogged: r.exercisesWritten
|
|
1044
|
+
exercisesLogged: r.exercisesWritten,
|
|
1045
|
+
setCompleted: r.setCompleted
|
|
958
1046
|
};
|
|
959
1047
|
}
|
|
960
1048
|
/**
|
|
@@ -1015,7 +1103,7 @@ async function swapAthleteExercise(client, args) {
|
|
|
1015
1103
|
savedWorkoutSetExerciseId: args.savedWorkoutSetExerciseId,
|
|
1016
1104
|
athleteId: coerceInt(row.user_id),
|
|
1017
1105
|
newExerciseId: coerceInt(row.exercise_id) ?? args.exerciseId,
|
|
1018
|
-
newExerciseTitle: str
|
|
1106
|
+
newExerciseTitle: str(exercise.title),
|
|
1019
1107
|
originalTeamExerciseId: coerceInt(template.exercise_id)
|
|
1020
1108
|
};
|
|
1021
1109
|
}
|
|
@@ -1049,7 +1137,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
1049
1137
|
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
1050
1138
|
if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
|
|
1051
1139
|
const body = {
|
|
1052
|
-
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
|
|
1140
|
+
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
|
|
1053
1141
|
...extra
|
|
1054
1142
|
};
|
|
1055
1143
|
const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
|
|
@@ -1059,17 +1147,22 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
1059
1147
|
}
|
|
1060
1148
|
exercisesWritten += 1;
|
|
1061
1149
|
}
|
|
1150
|
+
let setCompleted = false;
|
|
1062
1151
|
if (mode === "log") {
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1152
|
+
if (isSetFullyLogged(exercises, new Set(results.filter(resultHasData).map((r) => r.savedWorkoutSetExerciseId)))) {
|
|
1153
|
+
const setBody = {
|
|
1154
|
+
...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
|
|
1155
|
+
...extra
|
|
1156
|
+
};
|
|
1157
|
+
const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
|
|
1158
|
+
if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
|
|
1159
|
+
setCompleted = true;
|
|
1160
|
+
}
|
|
1069
1161
|
}
|
|
1070
1162
|
return {
|
|
1071
1163
|
savedWorkoutSetId,
|
|
1072
|
-
exercisesWritten
|
|
1164
|
+
exercisesWritten,
|
|
1165
|
+
setCompleted
|
|
1073
1166
|
};
|
|
1074
1167
|
}
|
|
1075
1168
|
/**
|
|
@@ -1226,7 +1319,10 @@ async function logResolvedExercises(client, target, date, resolved) {
|
|
|
1226
1319
|
savedWorkoutSetId,
|
|
1227
1320
|
results
|
|
1228
1321
|
});
|
|
1229
|
-
out.push(
|
|
1322
|
+
out.push({
|
|
1323
|
+
savedWorkoutSetId: written.savedWorkoutSetId,
|
|
1324
|
+
exercisesLogged: written.exercisesLogged
|
|
1325
|
+
});
|
|
1230
1326
|
}
|
|
1231
1327
|
return out;
|
|
1232
1328
|
}
|
|
@@ -1304,27 +1400,6 @@ async function logSessionForAthlete(client, args) {
|
|
|
1304
1400
|
sets
|
|
1305
1401
|
};
|
|
1306
1402
|
}
|
|
1307
|
-
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
1308
|
-
function presentExerciseHistory(detail) {
|
|
1309
|
-
return {
|
|
1310
|
-
liftPRs: (detail.liftPRs ?? []).map((p) => ({
|
|
1311
|
-
description: p.description ?? null,
|
|
1312
|
-
reps: p.reps ?? null,
|
|
1313
|
-
weight: p.weight ?? null,
|
|
1314
|
-
units: p.units ?? null,
|
|
1315
|
-
date: p.dateCompleted ?? null
|
|
1316
|
-
})),
|
|
1317
|
-
sessions: (detail.history ?? []).map((h) => ({
|
|
1318
|
-
date: h.dateCompleted,
|
|
1319
|
-
abr: h.abr ?? null,
|
|
1320
|
-
estimated1RM: h.bestEstimated1RM ?? null,
|
|
1321
|
-
sets: (h.sets ?? []).map((s) => ({
|
|
1322
|
-
setNumber: s.setNumber,
|
|
1323
|
-
value: s.formattedValue ?? null
|
|
1324
|
-
}))
|
|
1325
|
-
}))
|
|
1326
|
-
};
|
|
1327
|
-
}
|
|
1328
1403
|
//#endregion
|
|
1329
1404
|
//#region src/coach.ts
|
|
1330
1405
|
const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
@@ -2148,7 +2223,7 @@ async function removeSession(client, programId, pwId) {
|
|
|
2148
2223
|
async function publishSession(client, pwId) {
|
|
2149
2224
|
await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
|
|
2150
2225
|
}
|
|
2151
|
-
function str(value) {
|
|
2226
|
+
function str$1(value) {
|
|
2152
2227
|
return value === void 0 || value === null ? "" : String(value);
|
|
2153
2228
|
}
|
|
2154
2229
|
async function readSession(client, programId, date, pwId) {
|
|
@@ -2161,9 +2236,9 @@ async function readSession(client, programId, date, pwId) {
|
|
|
2161
2236
|
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
2162
2237
|
return {
|
|
2163
2238
|
pwId,
|
|
2164
|
-
date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
|
|
2239
|
+
date: `${str$1(pw.year)}-${str$1(pw.month)}-${str$1(pw.day)}`,
|
|
2165
2240
|
published: pw.published,
|
|
2166
|
-
instruction: str(pw.instruction),
|
|
2241
|
+
instruction: str$1(pw.instruction),
|
|
2167
2242
|
blocks
|
|
2168
2243
|
};
|
|
2169
2244
|
}
|
|
@@ -2174,7 +2249,7 @@ function readBlock(b) {
|
|
|
2174
2249
|
const exercises = (Array.isArray(b.exercises) ? b.exercises : []).sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
|
|
2175
2250
|
return {
|
|
2176
2251
|
order: Number(b.order),
|
|
2177
|
-
title: str(b.title),
|
|
2252
|
+
title: str$1(b.title),
|
|
2178
2253
|
leaderboard,
|
|
2179
2254
|
exercises
|
|
2180
2255
|
};
|
|
@@ -2183,19 +2258,19 @@ function readExercise(ex) {
|
|
|
2183
2258
|
const reps = [];
|
|
2184
2259
|
const load = [];
|
|
2185
2260
|
for (let i = 1; i <= 10; i += 1) {
|
|
2186
|
-
const r = str(ex[`param_1_data_${i}`]);
|
|
2261
|
+
const r = str$1(ex[`param_1_data_${i}`]);
|
|
2187
2262
|
if (r !== "") reps.push(r);
|
|
2188
|
-
const w = str(ex[`param_2_data_${i}`]);
|
|
2263
|
+
const w = str$1(ex[`param_2_data_${i}`]);
|
|
2189
2264
|
if (w !== "") load.push(w);
|
|
2190
2265
|
}
|
|
2191
2266
|
return {
|
|
2192
2267
|
order: Number(ex.order),
|
|
2193
|
-
title: str(ex.title),
|
|
2268
|
+
title: str$1(ex.title),
|
|
2194
2269
|
reps,
|
|
2195
2270
|
primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
|
|
2196
2271
|
load,
|
|
2197
2272
|
loadUnit: unitLabel(coerceInt(ex.param_2_type)),
|
|
2198
|
-
instruction: str(ex.instruction)
|
|
2273
|
+
instruction: str$1(ex.instruction)
|
|
2199
2274
|
};
|
|
2200
2275
|
}
|
|
2201
2276
|
//#endregion
|
|
@@ -2431,4 +2506,4 @@ var ExerciseLibrary = class {
|
|
|
2431
2506
|
}
|
|
2432
2507
|
};
|
|
2433
2508
|
//#endregion
|
|
2434
|
-
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
2509
|
+
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, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"zod": "^4.4.3",
|
|
30
|
-
"@trainheroic-unofficial/dto": "1.
|
|
30
|
+
"@trainheroic-unofficial/dto": "1.5.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^26.0.0",
|