@trainheroic-unofficial/js 3.1.0 → 3.1.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/README.md CHANGED
@@ -161,6 +161,12 @@ The `.` entry imports no `node:*` modules. Anything that touches the filesystem
161
161
  - **Messaging.** Tools for conversation streams: listing them, reading a stream, and
162
162
  building or sending or deleting a comment.
163
163
 
164
+ `createProgram(client, { kind, name })` creates a standalone `calendar` or `fixed` program and
165
+ returns both `containerId` (the id in `GET /1.0/coach/programs`) and `programId` (the id used by
166
+ program detail and workout writes). TrainHeroic may replace the requested name; inspect the
167
+ returned `title` and `nameApplied`. Creation is not idempotent, so do not blindly retry an
168
+ uncertain result.
169
+
164
170
  ## Working with exercises
165
171
 
166
172
  `ExerciseLibrary` loads the full library once, caches it, and answers name lookups and fuzzy
package/dist/index.d.mts CHANGED
@@ -44,6 +44,8 @@ type ApiBase = "coach" | "apis";
44
44
  type RequestOptions = {
45
45
  body?: unknown;
46
46
  base?: ApiBase;
47
+ /** Final non-2xx statuses the caller handles as part of normal control flow. */
48
+ expectedStatuses?: readonly number[];
47
49
  };
48
50
  type ClientResult<T = unknown> = {
49
51
  status: number;
@@ -60,8 +62,9 @@ type ClientOptions = {
60
62
  onSession?: (sessionId: string) => void;
61
63
  /**
62
64
  * Called once when a login or API request finishes with a non-2xx response. Transient 401/403
63
- * API responses that succeed after the built-in re-login are not reported. The callback is
64
- * best-effort: telemetry failures never change the API result returned to the caller.
65
+ * API responses that succeed after the built-in re-login and final statuses declared through
66
+ * `RequestOptions.expectedStatuses` are not reported. The callback is best-effort: telemetry
67
+ * failures never change the API result returned to the caller.
65
68
  */
66
69
  onHttpError?: TrainHeroicHttpErrorHandler;
67
70
  };
@@ -780,6 +783,32 @@ declare function fetchRosterMainLiftPRs(client: TrainHeroicClient, opts?: {
780
783
  //#endregion
781
784
  //#region src/coach.d.ts
782
785
  declare const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
786
+ declare const PROGRAM_KINDS: readonly ["calendar", "fixed"];
787
+ type ProgramKind = (typeof PROGRAM_KINDS)[number];
788
+ type CreatedProgram = {
789
+ /** Container/group id returned by list_programs and used by calendar edit/sync endpoints. */
790
+ containerId: number;
791
+ /** Actual program id used by get_program, workout creation, and other program-scoped writes. */
792
+ programId: number;
793
+ /** Title TrainHeroic actually assigned. The current API may ignore the requested name. */
794
+ title: string;
795
+ kind: ProgramKind;
796
+ requestedName: string;
797
+ nameApplied: boolean;
798
+ };
799
+ /**
800
+ * Create a standalone ongoing calendar or fixed-length program.
801
+ *
802
+ * TrainHeroic returns both a container id and the underlying program id. They are deliberately
803
+ * named separately here because `/3.0/coach/program/{containerId}` returns 401, while the
804
+ * `programId` works. This write is not idempotent: callers must not blindly retry an uncertain
805
+ * result. The live API currently accepts `name` but may generate its own title; `nameApplied`
806
+ * reports what happened.
807
+ */
808
+ declare function createProgram(client: TrainHeroicClient, args: {
809
+ kind: ProgramKind;
810
+ name: string;
811
+ }): Promise<CreatedProgram>;
783
812
  /** A roster member as id + display name. */
784
813
  type CoachRosterAthlete = {
785
814
  id: number;
@@ -996,4 +1025,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
996
1025
  stats(): Promise<Record<string, unknown>>;
997
1026
  }
998
1027
  //#endregion
999
- 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, prescribeAthleteSet, 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 };
1028
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, CreatedProgram, 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, PROGRAM_KINDS, PersonalWorkoutCreated, ProgramKind, 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, createProgram, 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, prescribeAthleteSet, 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
@@ -1,4 +1,4 @@
1
- import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
1
+ import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programCreateResponseSchema, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
2
  import { z } from "zod";
3
3
  export * from "@trainheroic-unofficial/dto";
4
4
  //#region src/http-error.ts
@@ -149,7 +149,7 @@ var TrainHeroicClient = class {
149
149
  session = await this.#ensureSession();
150
150
  res = await this.#send(method, url, session, options.body);
151
151
  }
152
- if (!res.ok) notifyHttpError(this.#onHttpError, method, url, res.status);
152
+ if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
153
153
  const text = await res.text();
154
154
  let data = text;
155
155
  if (text.length > 0) try {
@@ -2219,6 +2219,45 @@ function readExercise(ex) {
2219
2219
  //#endregion
2220
2220
  //#region src/coach.ts
2221
2221
  const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
2222
+ const PROGRAM_KINDS = ["calendar", "fixed"];
2223
+ /**
2224
+ * Create a standalone ongoing calendar or fixed-length program.
2225
+ *
2226
+ * TrainHeroic returns both a container id and the underlying program id. They are deliberately
2227
+ * named separately here because `/3.0/coach/program/{containerId}` returns 401, while the
2228
+ * `programId` works. This write is not idempotent: callers must not blindly retry an uncertain
2229
+ * result. The live API currently accepts `name` but may generate its own title; `nameApplied`
2230
+ * reports what happened.
2231
+ */
2232
+ async function createProgram(client, args) {
2233
+ if (!PROGRAM_KINDS.includes(args.kind)) throw new Error(`Unknown program kind: ${String(args.kind)}.`);
2234
+ if (typeof args.name !== "string" || args.name.trim() === "") throw new Error("Program name must not be blank.");
2235
+ const requestedName = args.name.trim();
2236
+ const res = await client.request("POST", "/1.0/coach/programs/create", { body: {
2237
+ finite: args.kind === "fixed",
2238
+ name: requestedName
2239
+ } });
2240
+ if (!res.ok) {
2241
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2242
+ throw new Error(`Program create failed (HTTP ${res.status}): ${detail}`);
2243
+ }
2244
+ checkResponse(programCreateResponseSchema, res.data, "program create");
2245
+ const rec = isRecord(res.data) ? res.data : {};
2246
+ const nested = isRecord(rec.program) ? rec.program : {};
2247
+ const containerId = coerceInt(rec.id);
2248
+ const programId = coerceInt(rec.programId) ?? coerceInt(rec.group_program) ?? coerceInt(nested.id);
2249
+ if (containerId === null || programId === null) throw new Error("Program create response is missing the container id or program id.");
2250
+ if (typeof rec.title !== "string" || rec.title.trim() === "") throw new Error("Program create response is missing the assigned title.");
2251
+ const title = rec.title;
2252
+ return {
2253
+ containerId,
2254
+ programId,
2255
+ title,
2256
+ kind: args.kind,
2257
+ requestedName,
2258
+ nameApplied: title === requestedName
2259
+ };
2260
+ }
2222
2261
  /** Normalize one-or-many emails into a deduped, trimmed list. */
2223
2262
  function emailList(emails) {
2224
2263
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -3020,4 +3059,4 @@ var ExerciseLibrary = class {
3020
3059
  }
3021
3060
  };
3022
3061
  //#endregion
3023
- 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, TrainHeroicHttpError, 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, prescribeAthleteSet, 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 };
3062
+ 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, PROGRAM_KINDS, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, createProgram, 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, prescribeAthleteSet, 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "3.1.0",
3
+ "version": "3.1.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": "3.1.0"
30
+ "@trainheroic-unofficial/dto": "3.1.1"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.2.0",