Detalhes do pacote

trainingpeaks-sdk

pablo-albaladejo1.3kMIT1.1.5

TypeScript SDK for TrainingPeaks API integration

trainingpeaks, api, sdk, typescript

readme (leia-me)

TrainingPeaks SDK

npm version License: MIT Node.js CI

A comprehensive TypeScript SDK for TrainingPeaks API integration, built with Clean Architecture principles and designed for modern JavaScript/TypeScript applications.

📋 Product Context: For comprehensive business objectives, target market analysis, and feature roadmap, see PRODUCT.md.

Features

  • 🏗️ Clean Architecture: Follows hexagonal architecture (ports & adapters) for maintainability
  • 🔒 Type-Safe: Full TypeScript support with comprehensive type definitions
  • 📦 Dual Package: Supports both ESM and CommonJS module systems
  • 🧪 Well Tested: Comprehensive unit, integration, and E2E test coverage
  • 🔐 Authentication: Secure session management with cookie support
  • 📊 Workout Management: Complete workout CRUD operations
  • 🏃 User Management: User profile and settings management
  • 📁 File Upload: Support for TCX, GPX, and FIT file formats
  • 🚀 Modern Stack: Built with Axios, Zod validation, and Playwright

Requirements

  • Node.js: >=20.0.0
  • npm: >=9.0.0 (included with Node.js 20+)

Installation

npm install trainingpeaks-sdk

⚠️ Node.js Version: This SDK requires Node.js 20.0.0 or higher due to the use of modern APIs like crypto.randomUUID(). Node.js 18 and earlier are not supported.

Quick Start

Authentication & Basic Usage

import { createTrainingPeaksSdk } from 'trainingpeaks-sdk';

// Initialize the SDK
const sdk = createTrainingPeaksSdk({
  debug: false, // Optional: enable debug logging
  timeout: 30000, // Optional: request timeout in ms
});

// Login with credentials
const loginResult = await sdk.login({
  username: 'your-username',
  password: 'your-password',
});

console.log('Login successful:', loginResult);
// Returns: { token: {...}, user: {...} }

Workout Management

// Get user's workouts list
const workouts = await sdk.getWorkoutsList({
  startDate: '2024-01-01',
  endDate: '2024-12-31',
  // athleteId is optional - uses current user if not provided
});

console.log('Workouts:', workouts);
// Returns: WorkoutListItem[] with id, name, date, etc.

⚠️ Current Limitations: This SDK currently supports authentication and workout list retrieval. Additional features like workout creation, updates, and individual workout details are planned for future releases.

Logout

// Clear authentication and logout
await sdk.logout();
console.log('Logged out successfully');

Error Handling

try {
  const result = await sdk.login({
    username: 'invalid-user',
    password: 'wrong-password',
  });
} catch (error) {
  console.error('Login failed:', error.message);
  // Handle authentication errors
}

API Reference

SDK Creation

const sdk = createTrainingPeaksSdk(config?: TrainingPeaksClientConfig)

Config Options:

  • debug?: boolean - Enable debug logging
  • timeout?: number - Request timeout in milliseconds
  • baseUrl?: string - Custom API base URL

Authentication Methods

login(credentials: LoginCredentials)

Authenticate with username and password.

type LoginCredentials = {
  username: string;
  password: string;
};

type LoginResponse = {
  token: {
    accessToken: string;
    tokenType: string;
    expiresAt: string;
    refreshToken?: string;
  };
  user: {
    id: string;
    name: string;
    username: string;
    avatar?: string;
  };
};

logout()

Clear authentication and end the current session.

Workout Methods

getWorkoutsList(command: GetWorkoutsListCommand)

Get user's workouts list with date filtering.

type GetWorkoutsListCommand = {
  athleteId?: string; // Optional - uses current user if not provided
  startDate: string; // YYYY-MM-DD format
  endDate: string; // YYYY-MM-DD format
};

type WorkoutListItem = {
  id: string;
  name: string;
  date: string;
  duration: number;
  distance?: number;
  activityType?: string;
  // Additional workout metadata...
};

Current Features

Available Now:

  • User authentication (login/logout)
  • Workout list retrieval with date filtering
  • Session management with automatic cookie handling
  • TypeScript support with full type definitions
  • Clean Architecture implementation

🚧 Planned Features:

  • Individual workout details retrieval
  • Workout file upload (TCX, GPX, FIT formats)
  • Workout creation and updates
  • User profile management
  • Workout statistics and analytics

Configuration

SDK Configuration

import {
  createTrainingPeaksSdk,
  type TrainingPeaksClientConfig,
} from 'trainingpeaks-sdk';

const config: TrainingPeaksClientConfig = {
  baseUrl: 'https://tpapi.trainingpeaks.com', // Optional
  timeout: 30000, // Optional: request timeout in ms
  debug: true, // Optional: enable debug logging
  headers: {
    // Optional: custom headers
    'User-Agent': 'MyApp/1.0.0',
  },
};

const sdk = createTrainingPeaksSdk(config);

Environment Variables

You can also configure the SDK using environment variables:

# API Base URL (optional)
TRAININGPEAKS_API_BASE_URL=https://tpapi.trainingpeaks.com

# Request timeout in milliseconds (optional)
TRAININGPEAKS_TIMEOUT=30000

# Enable debug logging (optional)
TRAININGPEAKS_DEBUG=true

Error Handling

The SDK provides structured error handling with HTTP-specific error information:

import { createTrainingPeaksSdk } from 'trainingpeaks-sdk';

const sdk = createTrainingPeaksSdk();

try {
  await sdk.login({ username: 'user', password: 'pass' });
} catch (error) {
  // HTTP errors include status, statusText, and response data
  if (error.status) {
    console.error(`HTTP ${error.status}: ${error.statusText}`);
    console.error('Response:', error.data);
  } else {
    console.error('Network or other error:', error.message);
  }
}

TypeScript Support

The SDK is written in TypeScript and provides comprehensive type definitions:

import { createTrainingPeaksSdk } from 'trainingpeaks-sdk';
import type {
  TrainingPeaksClientConfig,
  LoginCredentials,
  GetWorkoutsListCommand,
  WorkoutListItem,
} from 'trainingpeaks-sdk';

// All types are fully typed
const config: TrainingPeaksClientConfig = {
  debug: true,
  timeout: 30000,
};

const credentials: LoginCredentials = {
  username: 'myuser',
  password: 'mypass',
};

const workoutsQuery: GetWorkoutsListCommand = {
  startDate: '2024-01-01',
  endDate: '2024-12-31',
};

Module Exports

The SDK supports multiple import patterns for different use cases:

// Main SDK factory function
import { createTrainingPeaksSdk } from 'trainingpeaks-sdk';

// Type imports
import type {
  TrainingPeaksClientConfig,
  LoginCredentials,
  GetWorkoutsListCommand,
  WorkoutListItem,
} from 'trainingpeaks-sdk';

// ⚠️ UNSTABLE: Internal modules - No SemVer guarantees
// These imports may introduce breaking changes in any version
// Use at your own risk - prefer [public API documentation](./docs/clean-architecture.md#public-api) when possible
import { User } from 'trainingpeaks-sdk/domain';
import { Logger } from 'trainingpeaks-sdk/adapters';
import type { WorkoutType } from 'trainingpeaks-sdk/types';

Development

Prerequisites

  • Node.js >= 18.0.0
  • npm >= 8.0.0
  • GitHub CLI (gh) - for project setup automation

GitHub CLI Authentication:

# Authenticate with GitHub using web browser (recommended for security)
gh auth login --web

# For GitHub Enterprise Server users, specify your hostname
# gh auth login --web --hostname your-enterprise-hostname.com
# Or set GH_HOST environment variable: 
# Linux/macOS: export GH_HOST=your-enterprise-hostname.com
# Windows CMD: set GH_HOST=your-enterprise-hostname.com
# Windows PowerShell: $env:GH_HOST="your-enterprise-hostname.com"

# Verify authentication
gh auth status

Project Setup

This repository includes automated setup scripts for GitHub project management:

# Run the automated GitHub project setup
./scripts/github/setup/setup-github-project.sh

# Test the setup script functionality
./scripts/github/setup/test-setup.sh

# Get help and options
./scripts/github/setup/setup-github-project.sh --help

The setup script automatically creates:

  • 🎯 GitHub project board with views and columns
  • 🏷️ Comprehensive label system for issue categorization
  • 📋 Issue templates for different types of requests
  • 🔧 Initial project setup issues and epics
  • ⚡ Dependabot and security automation

For detailed setup instructions, see scripts/github/setup/README.md.

Building

# Install dependencies
npm install

# Build the project
npm run build

# Build specific targets
npm run build:esm  # ES modules
npm run build:cjs  # CommonJS

Testing

# Run unit tests
npm test

# Run integration tests
npm run test:integration

# Run E2E tests
npm run test:e2e

# Run tests with coverage
npm run test:coverage

Code Quality

# Lint code
npm run lint

# Format code
npm run format

# Type check
npm run type-check

# Validate imports
npm run check-imports

Architecture

This SDK follows Clean Architecture principles with a hexagonal architecture approach:

  • Domain Layer: Core business entities and rules
  • Application Layer: Business logic orchestration and contracts
  • Adapters Layer: External integrations and concrete implementations (formerly Infrastructure) - see migration guide for infrastructure → adapters transition details

Key Benefits:

  • 🧪 Highly Testable: Each layer can be tested independently
  • 🔄 Maintainable: Clear separation of concerns and dependencies
  • 🔧 Extensible: Easy to add new features or swap implementations
  • 📦 Modular: Use individual components or the complete SDK

Documentation:

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes following the existing code style
  4. Add tests for your changes
  5. Run the full test suite (npm run pre-release)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

See CHANGELOG.md for a list of changes and version history.


Made with ❤️ for the TrainingPeaks community

changelog (log de mudanças)

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

1.1.5 (2025-08-12)

  • Merge pull request #58 from pablo-albaladejo/dependabot/npm_and_yarn/eslint/js-9.33.0 (ce37ac4), closes #58
  • Merge pull request #59 from pablo-albaladejo/dependabot/npm_and_yarn/eslint-9.33.0 (91cde37), closes #59
  • chore(deps-dev): bump @eslint/js from 9.32.0 to 9.33.0 (2f88c36)
  • chore(deps-dev): bump eslint from 9.32.0 to 9.33.0 (0e648ac)

1.1.4 (2025-08-12)

  • Merge pull request #57 from pablo-albaladejo/dependabot/npm_and_yarn/semantic-release/github-11.0.4 (f4a938f), closes #57
  • Merge pull request #66 from pablo-albaladejo/fix/issue-65-github-username-references (ccc62dd), closes #66
  • fix: resolve invalid GitHub username references in CODEOWNERS (bae3709), closes #65
  • chore(deps-dev): bump @semantic-release/github from 11.0.3 to 11.0.4 (ec2953e)

1.1.3 (2025-08-12)

  • Merge pull request #56 from pablo-albaladejo/dependabot/npm_and_yarn/zod-4.0.17 (e0af0ff), closes #56
  • chore(deps): bump zod from 4.0.14 to 4.0.17 (711b8cc)

1.1.2 (2025-08-12)

  • Merge pull request #62 from pablo-albaladejo/dependabot/npm_and_yarn/typescript-eslint-8.39.1 (85c3a62), closes #62
  • Merge pull request #63 from pablo-albaladejo/dependabot/npm_and_yarn/types/node-24.2.1 (36b6321), closes #63
  • chore(deps-dev): bump @types/node from 22.17.0 to 24.2.1 (fe9ce32)
  • chore(deps-dev): bump typescript-eslint from 8.39.0 to 8.39.1 (cb55cc0)
  • chore(release): 1.1.2 [skip ci] (b0a2fcf)

1.1.2 (2025-08-12)

  • Merge pull request #63 from pablo-albaladejo/dependabot/npm_and_yarn/types/node-24.2.1 (36b6321), closes #63
  • chore(deps-dev): bump @types/node from 22.17.0 to 24.2.1 (fe9ce32)

1.1.1 (2025-08-12)

  • Merge pull request #64 from pablo-albaladejo/dependabot/npm_and_yarn/dotenv-17.2.1 (8c587b5), closes #64
  • chore(deps-dev): bump dotenv from 16.6.1 to 17.2.1 (2d95aee)

1.1.0 (2025-08-11)

  • Merge pull request #16 from pablo-albaladejo/feat/list-workouts (3bae455), closes #16
  • Merge pull request #61 from pablo-albaladejo/fix/semantic-release-commitlint (37b8064), closes #61
  • Update test/e2e/test-built-library.cjs (0945fbc)
  • fix: disable body and footer max line length in commitlint (5bfcc5c)
  • fix: re-enable body max line length in commitlint configuration (5fb01f3)
  • chore: add husky for Git hooks and improve error handling (a51aee7)
  • chore: add local testing scripts and configuration for GitHub Actions (358df1d)
  • chore: add project configuration (22086f1)
  • chore: enforce mandatory validation (eaea2df)
  • chore: enhance architecture documentation (5a0ce6e)
  • chore: enhance error handling logic in documentation (a442fa8)
  • chore: improve documentation (9015ee7)
  • chore: refine architecture documentation (bd4a736)
  • chore: remove TypeScript ESLint dependencies from package.json and package-lock.json (984016c)
  • chore: remove unnecessary whitespace in workout entrypoint fixture (45c719b)
  • chore: synchronize package.json and package-lock.json, add check script (c1b35f3)
  • chore: update docs (a269eb3)
  • chore: update documentation and workflows to require Node.js 20+ (c17b4a0)
  • chore: update project configuration (255b797)
  • chore: update project configuration and scripts (c0cc238)
  • chore: update testing requirements (fcb9289)
  • refactor: clean up CI workflow and improve test formatting (73802a8)
  • refactor: enhance error handling and improve user entity management (3bbfdd3)
  • refactor: enhance test structure (27c5531)
  • refactor: improve code consistency and enhance error handling (41ff5e3)
  • refactor: improve type safety in fixtures (7978580)
  • refactor: standardize mock reset method and enhance error handling in API calls (e72cb8b)
  • refactor: standardize whitespace (dde2a46)
  • refactor: standardize whitespace and formatting across multiple files (37a4eee)
  • refactor: streamline authentication tests (db3152d)
  • refactor: update documentation and changelog structure (031af4a)
  • feat: implement workout repository and entrypoints (9e2f146)
  • feat: add integration tests (2fbeace)
  • feat: add session storage support for Bearer token (d57d340)
  • feat: enhance error handling and add workout entrypoint test fixtures (72ed2eb)

1.0.0 (2025-08-05)

1.0.1 (2025-08-05)

1.0.0 (2025-08-05)

  • docs: update README for clean repository (a8f50bc)
  • chore: initial commit (a160e58)
  • chore(release): 1.0.0 [skip ci] (e617487)

1.0.0 (2025-08-05)

1.9.0 (2025-07-23)

  • feat: add comprehensive integration tests for authentication (01a9caa)

1.8.1 (2025-07-23)

  • refactor: centralize type definitions (6add43a)
  • refactor: enhance workout structure builders and converters (709c52a)

1.8.0 (2025-07-23)

  • feat: add workout builder service and unit tests (50631e3)

1.7.0 (2025-07-22)

  • feat: integrate codecov for test analytics (a0a181f)

1.6.0 (2025-07-22)

  • chore: disable coverage for integration tests in configuration (ba60405)
  • fix: improve configuration validation in end-to-end tests (3884dfd)
  • feat: add comprehensive end-to-end tests (e26f60e)
  • feat: add rosie factory patterns for test data generation (15d2b9d)
  • feat: enhance configuration validation and add comprehensive tests (72f1e1b)
  • feat: enhance trainingpeaks client with persistent storage support (53c1277)
  • feat: enhance workout validation and error handling (70f76fe)
  • feat: implement centralized error handling (745b7ad)
  • feat: implement error handling service (71c4a41)
  • feat: improve end-to-end tests with environment variable support (6f45811)
  • feat: update cursor guidelines for improved clarity and consistency (8167b89)
  • refactor: streamline use case implementations and enhance type exports (00fbfd5)
  • refactor: update documentation and improve code structure (01f035c)

Changes

All important changes to this project are listed here.

The format follows Keep a Changelog, and this project follows Semantic Versioning.

1.5.1 (2025-07-20)

  • refactor: transition from interface to type (8a39888)

1.5.0 (2025-07-14)

  • feat: enhance typescript linting rules and update sdk client structure (bb4f871)

1.4.6 (2025-07-14)

  • refactor: implement individual function types for application services (f572a68)

1.4.5 (2025-07-14)

  • refactor: update testing (95c3dda)

1.4.4 (2025-07-14)

  • refactor: implement logger service and remove deprecated service (11292ce)
  • refactor: update import paths and enhance logger (765df96)

1.4.3 (2025-07-14)

  • refactor: separate application vs domain services (ee46a87)

1.4.2 (2025-07-14)

  • refactor: move domain services (ff1dd2a)
  • feat!: function first refactor (33d4085)

1.4.1 (2025-07-13)

  • chore: update dependencies to use playwright-core and remove playwright (255ccbd)

1.4.0 (2025-07-13)

  • feat: add tags and activity type to workout metadata in tests (158557a)
  • fix: add playwright to package.json (87f4de4)

1.3.0 (2025-07-13)

  • fix: streamline import statements (856ea1d)
  • feat: enhance ts configuration and import paths (852f808)
  • feat: update package configuration and enhance build scripts (c615b9b)

1.2.0 (2025-07-13)

  • feat: enhance package configuration and build process (62e8094)
  • feat: update node.js setup for npm authentication (c99e94e)
  • chore(release): enable npm publishing in configuration (0a1975e)

1.1.0 (2025-07-13)

  • feat: add hexagonal architecture rules and coding conventions (a0ab8e5)
  • chore: remove local and simple semantic release configurations (5a3f32c)
  • chore(release): 1.0.2 [skip ci] (e0eb4a1)
  • docs: add comprehensive cursor rules with architecture decisions (d5de3c1)
  • fix: resolve github assets name collision in semantic-release (0b4a246)

1.0.2 (2025-07-13)

  • docs: add comprehensive cursor rules with architecture decisions (d5de3c1)
  • chore: remove local and simple semantic release configurations (5a3f32c)
  • fix: resolve github assets name collision in semantic-release (0b4a246)

1.0.1 (2025-07-13)

  • Merge pull request #1 from pablo-albaladejo/dependabot/github_actions/codecov/codecov-action-5 (98ab5ed), closes #1
  • ci: bump codecov/codecov-action from 3 to 5 (498d257)

1.0.0 (2025-07-13)

  • fix: add coverage dependency and fix delete workout test (badc56f)
  • fix: disable npm publishing temporarily to test semantic-release (87470a1)
  • fix: remove deprecated husky shebang lines (0d828ee)
  • fix: rename files to lowercase for case-sensitive filesystems (2fe1aed)
  • fix: resolve case sensitivity issues for github actions (1bb8d07)
  • feat: add husky with commitlint and lint-staged (180bbdb)
  • feat: add prettier code formatting support (42ffd90)
  • feat: add web authentication and integration testing support (117b7cb)
  • feat: implement semantic-release for automated versioning and publishing (1548c25)
  • ci: add github actions for ci/cd pipeline (3e71ce8)
  • ci: update nodejs version (f1f114e)
  • refactor: convert all files to kebab-case and remove redundancy (dce8d2d)
  • refactor: implement hexagonal architecture (fa544e3)
  • refactor(workout): implement hexagonal architecture (d2fddf0)

[Unreleased]

✨ Features

  • Initial TrainingPeaks SDK implementation
  • Web-based authentication with browser simulation
  • Workout upload functionality (GPX, TCX, FIT)
  • TypeScript support with full type definitions
  • Comprehensive test coverage
  • Hexagonal architecture implementation
  • Centralized configuration system

🐛 Bug Fixes

  • Fixed case sensitivity issues for Linux environments
  • Resolved delete workout test to use proper workflow
  • Fixed ESLint configuration for TypeScript

📚 Documentation

  • Complete README with usage examples
  • API documentation
  • Development setup guide

🏗️ Build System

  • GitHub Actions CI/CD pipeline
  • Automated testing and quality checks
  • Code formatting with Prettier
  • ESLint configuration
  • Commit message validation

🔧 Chores

  • Semantic release configuration
  • Automated changelog generation
  • NPM publishing automation