Eve library

Meditation Shared Libraries

Guide

Revision 1

On this page

Meditation - Cross-Platform Meditation Engine Libraries

The Meditation libraries (libs/meditation/) provide the complete platform-agnostic engine layer for meditation applications. These six libraries implement every core capability a meditation app needs: audio playback with multi-layer mixing and streaming, configurable timers with bells and ambient sounds, breathing exercise guidance with haptic feedback, session lifecycle management with persistence, progress tracking with streaks and achievements, and offline content management with smart download suggestions.

All libraries are designed to be consumed by the Tara domain (apps/tara/ and libs/tara/) but are deliberately kept in libs/meditation/ because they are domain-agnostic -- any meditation application, not just Tara, can use them. They share a common architectural pattern: an event-driven core class built on eventemitter3, multiple storage backend implementations (in-memory, localStorage, IndexedDB), and React hook factories using the createUse* pattern for framework-agnostic UI integration.

Two additional directories (analytics/ and core/) exist as placeholder reservations with .gitkeep files; they do not contain source code yet.


Architecture#

text
                    @oshun/meditation-player
                  (audio playback, mixing, streaming,
                   caching, visualization, background)
                          |
                          |   plays audio for
                          v
              @oshun/meditation-session
            (session lifecycle, persistence,
             analytics tracking, scheduling)
            /           |            \
           /            |             \
@oshun/meditation-   @oshun/meditation-   @oshun/meditation-
    timer                breathing             offline
 (countdown,          (patterns,          (download queue,
  bells, ambient,      guidance,           storage, versioning,
  presets, haptics)    visualization,       suggestions, network)
                       haptics, history)
           \            |             /
            \           |            /
              @oshun/meditation-progress
            (streaks, statistics, achievements,
             milestones, export, sync)

Each library is self-contained with its own types, core logic, storage backends, event system, and React hooks. Libraries do not depend on each other at the package level -- they share only the eventemitter3 runtime dependency and optional react peer dependency. Integration between them happens at the application layer (Tara's web and mobile apps).


Libraries (6)#

@oshun/meditation-player - Audio Player Engine#

Cross-platform meditation audio player with background playback, crossfade transitions, multi-layer mixing, lock screen controls, and platform-specific adapters. This is the most feature-rich library in the collection.

Core class: MeditationPlayer -- event-driven audio player with load, play, pause, seek, and stop operations. Emits state change, track change, progress, volume change, marker, and error events.

Key subsystems:

Subsystem Classes / Functions Description
Playback Queue PlaybackQueue Manages ordered playback with shuffle and repeat modes. Supports queue manipulation (add, remove, reorder, clear).
Background Audio BackgroundAudioHandler, WebBackgroundAudioHandler, NoopBackgroundAudioHandler Platform-abstracted background playback with lock screen controls (LockScreenControlsConfig), now-playing info, and remote command handling. Factory: createBackgroundAudioHandler.
Audio Session AudioSessionManager, WebAudioSessionManager, NoopAudioSessionManager Manages audio session categories, interruption handling (phone calls, other apps), audio route changes, and focus state. Factory: createAudioSessionManager.
Audio Mixer AudioMixer Multi-layer audio mixing with per-layer volume, crossfade, ducking (DuckConfig), and volume automation (AutomationPoint, VolumeAutomation). Supports layer types for voice, background music, ambient, and effects.
Visualization AudioVisualizer Real-time audio visualization with frequency analysis, beat detection (BeatData), standard frequency bands, and utility functions (frequencyToDecibels, binToFrequency).
Caching AudioCacheManager, ServiceWorkerCacheAdapter, AudioPreloader Audio file caching with configurable limits, preloading of upcoming tracks, and Service Worker integration for web.
Streaming StreamingManager, NetworkQualityMonitor, BufferManager, AdaptiveBitrateSelector Adaptive bitrate streaming with network quality monitoring, buffer health tracking, and automatic quality selection.

React hooks: createUsePlayer, createUsePlaybackProgress, createUseQueue, createUseVisualization, createUseAudioSession, createUseMixer, createPlayerHooks (all-in-one factory).

Types: Extensive type system including MeditationTrack, AudioSource, ContentMarker, PlayerState, PlaybackProgress, AudioLayer, MixerState, CrossfadeConfig, QueueItem, QueueState, PlayerConfig, AudioBackend, PlatformCapabilities, AudioAdapter, NowPlayingInfo, RemoteCommand, AudioSessionCategory, AudioInterruptionType, AudioRoute, and more.

Dependencies: eventemitter3 Peer dependencies: react >=18.0.0 (optional) Build: @nx/js:tsc Tags: scope:meditation, layer:core, type:lib


@oshun/meditation-timer - Meditation Timer Engine#

Cross-platform meditation timer with configurable durations, preparation and wind-down phases, interval bells, ambient sound mixing, background operation, and haptic feedback.

Core class: MeditationTimer -- event-driven countdown timer with support for multiple phases (preparation, meditation, wind-down). Emits tick, state change, phase change, interval, bell rung, complete, and error events at configurable intervals.

Key subsystems:

Subsystem Classes / Functions Description
Presets 9 built-in presets (1, 3, 5, 10, 15, 20, 30, 45, 60 minutes), PresetManager Pre-configured timer durations organized into quick, standard, and extended collections. createCustomPreset for user-defined presets.
Bells BellPlayer Bell sound playback with 6 built-in sounds: Tibetan bowl, singing bowl, gong, temple bell, chime, and soft tone. Configurable triggers for start, end, and intervals.
Ambient Sounds AmbientPlayer Multi-layer ambient sound mixing with 7 built-in sounds (rain, ocean, forest, fire, white/pink/brown noise) and 3 curated mixes (peaceful, focus, sleep).
Background TimerBackgroundHandler, WebTimerBackgroundHandler, NoopTimerBackgroundHandler Platform-abstracted background timer operation with notification display. Factory: createTimerBackgroundHandler.
Haptics HapticManager, WebHapticManager, NoopHapticManager Platform-abstracted haptic feedback for timer events (start, bell, phase change, completion). Configurable intensity levels.

React hooks: createUseMeditationTimer, createUseTimerState, createUseTimerProgress, createUseTimerPresets, createTimerHooks.

Types: TimerState, TimerPhase, BellType, BellTrigger, BellConfiguration, IntervalAction, TimerInterval, RecurringInterval, AmbientSoundCategory, AmbientSoundType, AmbientMix, PreparationConfig, WindDownConfig, TimerConfig, TimerSession, TimerProgress, TimerStatistics, HapticIntensity, HapticType.

Dependencies: eventemitter3 Peer dependencies: react >=18.0.0 (optional) Build: @nx/js:tsc Tags: scope:meditation, layer:core, type:lib


@oshun/meditation-session - Session Lifecycle Management#

Complete session management solution covering session creation, lifecycle (start/pause/resume/complete/abandon), persistence across multiple storage backends, analytics tracking with aggregation, and recurring session scheduling with reminders.

Core class: SessionManager -- manages the full lifecycle of a meditation session. Sessions have typed configurations (SessionConfig) with audio, timing, and notification settings. The manager tracks interruptions, pauses, and completion status, and emits events for all state transitions.

Key subsystems:

Subsystem Classes / Functions Description
Persistence SessionPersistenceManager, InMemorySessionStorage, LocalSessionStorage, IndexedDBSessionStorage Three storage backends for session data with auto-save capability. PersistenceConfig controls save behavior.
Analytics SessionAnalyticsManager, ConsoleAnalyticsTracker, InMemoryAnalyticsStorage Session analytics tracking with event recording, aggregated analytics computation, and pluggable tracker/storage interfaces.
Scheduling SessionScheduler, InMemorySchedulerStorage, LocalSchedulerStorage Recurring session scheduling with day-of-week recurrence patterns, notification reminders, and upcoming session queries. Covered by 5 spec files testing CRUD, iCal generation, recurrence logic, trigger evaluation, and storage.

React hooks: createUseSessionManager, createUseCurrentSession, createUseSessionProgress, createUseSessionState, createUseScheduler, createSessionHooks.

Types: Branded types (SessionId, DurationSeconds, Timestamp, DateString, Percentage), SessionType, SessionState, InterruptionReason, CompletionStatus, SessionProgress, SessionInterruption, SessionResult, RecurrencePattern, DayOfWeek, ScheduledSession, UpcomingSession.

Dependencies: eventemitter3 Peer dependencies: react >=18.0.0 (optional) Build: @nx/esbuild:esbuild (ESM + CJS dual format with declaration files) Tags: scope:shared, type:lib, domain:meditation


@oshun/meditation-progress - Progress and Achievement Tracking#

Progress tracking system covering session recording, streak calculation with timezone support, comprehensive statistics, an achievement system with unlock tracking, milestone tracking, data export, and multi-device sync with conflict resolution.

Core class: ProgressTracker -- records completed sessions and automatically updates streaks, checks for new achievements, and evaluates milestones. Returns a result containing the updated streak, any newly unlocked achievements, and triggered milestones.

Key subsystems:

Subsystem Classes / Functions Description
Streak Calculator StreakCalculator Timezone-aware streak tracking with configurable minimum session duration, forgiveness days, and freeze tokens. Emits events on streak changes.
Statistics StatisticsCalculator, getDateRangeFromPredefined Computes aggregate statistics over configurable date ranges: time-of-day distribution, day-of-week distribution, session type breakdown, and predefined ranges (today, this week, this month, all time).
Achievements AchievementManager, ACHIEVEMENT_DEFINITIONS Achievement system with built-in definitions, category and rarity classifications, and automatic unlock evaluation when sessions are recorded.
Milestones MilestoneManager, MILESTONE_DEFINITIONS Milestone tracking for significant progress markers (e.g., first session, 100 hours, 365-day streak) with notification support.
Export ProgressExporter Data export in multiple formats with configurable data type selection (ExportDataTypes).
Sync ProgressSyncManager Multi-device synchronization with conflict detection and configurable resolution strategies (ConflictStrategy). Tracks sync state and status.

Storage backends: InMemoryProgressStorage, LocalProgressStorage.

React hooks: createUseStreak, createUseStatistics, createUseAchievements, createUseMilestones, createUseSync, createUseProgressTracker, createProgressHooks. Also provides pre-bound convenience hooks (useStreak, useStatistics, etc.) that work after calling setProgressReactHooks.

Dependencies: eventemitter3 Peer dependencies: typescript >=5.0.0 Build: @nx/js:tsc Tags: domain:meditation, type:library


@oshun/meditation-breathing - Breathing Exercise Engine#

Cross-platform breathing exercise engine with 10 built-in patterns, custom pattern creation via a fluent builder API, real-time visualization data, audio guidance, haptic feedback, and session history tracking.

Core class: BreathingExercise -- event-driven exercise runner that progresses through breathing phases (inhale, hold, exhale, rest) according to a pattern definition. Supports both cycle-based and duration-based completion modes. Emits state change, phase change, cycle complete, tick, countdown, complete, and error events.

Built-in patterns (10):

Pattern Description
PATTERN_BOX_BREATHING Equal 4-phase breathing (4-4-4-4)
PATTERN_4_7_8 Dr. Andrew Weil's relaxation technique
PATTERN_COHERENT Heart rate variability optimization
PATTERN_ENERGIZING Quick energizing breath
PATTERN_CALMING Extended exhale for calm
PATTERN_2_1_RATIO 2:1 inhale-to-exhale ratio
PATTERN_ALTERNATE_NOSTRIL Nadi Shodhana pranayama
PATTERN_WIM_HOF Wim Hof Method breathing
PATTERN_SLEEP Sleep-optimized breathing
PATTERN_FOCUS Focus-enhancing breath

Patterns are organized into collections: BEGINNER_PATTERNS, RELAXATION_PATTERNS, FOCUS_PATTERNS, ENERGY_PATTERNS, MEDITATION_PATTERNS.

Key subsystems:

Subsystem Classes / Functions Description
Pattern Builder BreathingPatternBuilder, createPatternBuilder, createBoxBreathing, createCoherentBreathing Fluent API for building custom breathing patterns phase by phase, plus convenience constructors for common patterns.
Visualization VisualizationProvider, calculateVisualization, interpolatePhaseColor Real-time visualization state with easing functions, phase colors, and animation data for driving breathing circle/sphere UIs.
Audio Guidance GuidancePlayer Audio cues synchronized with breathing phases (inhale, hold, exhale prompts).
Haptics BreathingHapticManager Haptic feedback patterns timed to breathing phases for eyes-closed practice.
Session History SessionHistoryManager, InMemorySessionStorage, LocalSessionStorage Persist breathing session records with history statistics.

React hooks: createUseBreathingExercise, createUseBreathingState, createUseBreathingAnimation, createUseBreathingPatterns, createBreathingHooks. Also provides convenience hooks (useBreathingExercise, etc.).

Dependencies: eventemitter3 Peer dependencies: react >=18.0.0 (optional) Build: @nx/js:tsc Tags: scope:meditation, layer:core, type:lib


@oshun/meditation-offline - Offline Content Management#

Comprehensive offline content management system with a priority download queue, multiple storage backends, content versioning with update checks, smart download suggestions based on user behavior, network state detection, and React hooks for UI integration.

Core class: OfflineManager -- orchestrates downloads, storage, versioning, and suggestions. Supports checksum verification, automatic resume on startup, and network-aware downloading (WiFi-only, metered data policies). Factory functions: createOfflineManager (generic), createBrowserOfflineManager (browser-optimized with IndexedDB and network API detection).

Key subsystems:

Subsystem Classes / Functions Description
Download Queue DownloadQueue Priority-based download queue with retry logic, concurrent download limits, pause/resume, and cancellation via AbortSignal. Configurable via QueueConfig.
Storage StorageManager, IndexedDBStorage, InMemoryStorage, LocalStorageBackend Three storage backends for tracking downloaded content metadata and managing cleanup. CleanupStrategy and CleanupConfig control automatic storage reclamation.
Versioning ContentVersionManager Content version tracking with manifest fetching, version comparison, update policy enforcement (UpdatePolicy), and version range filtering. Includes utilities: createVersion, incrementVersion, isValidVersion, sortVersions, getLatestVersion.
Suggestions SuggestionEngine, getQuickSuggestions Smart download suggestions based on user preferences, content usage statistics (ContentUsageStats), and configurable scoring weights (ScoringWeights). Analyzes catalog content to recommend downloads.
Network detectNetworkState, detectNetworkType Network state detection with connection type identification. NetworkPreferences configures download behavior based on connection quality.

React hooks: createUseOfflineManager, createUseOfflineContent, createUseOfflineContentById, createUseDownloadStatus, createUseDownloadProgress, createUseAllOfflineContent, createUseNetworkState, createUseQueueState, createUseStorageInfo, createUseSuggestions, createOfflineHooks.

Types: Branded types (ByteSize, ContentId, DownloadId, UrlString, VersionString), DownloadableContent, DownloadedContent, DownloadProgress, DownloadStatus, QueuePriority, QueueState, StorageInfo, StorageLimits, ContentVersion, UpdateCheckResult, DownloadSuggestion, SuggestionReason, NetworkState, NetworkType.

Dependencies: eventemitter3 Peer dependencies: react >=18.0.0 (optional) Build: @nx/js:tsc Tags: scope:shared, type:lib, domain:meditation


Common Architectural Patterns#

All six libraries follow consistent design patterns:

Event-Driven Core#

Every library's primary class extends or wraps eventemitter3 for typed event emission. Events use discriminated union types with specific data payloads per event type (e.g., StateChangeEventData, TickEventData, CompleteEventData).

Platform Abstraction#

Libraries that interact with platform APIs (player, timer, breathing) provide a three-tier abstraction:

  1. Abstract base class defining the interface (e.g., BackgroundAudioHandler)
  2. Web implementation using Web APIs (e.g., WebBackgroundAudioHandler)
  3. Noop implementation for testing or unsupported platforms (e.g., NoopBackgroundAudioHandler)
  4. Factory function that selects the right implementation (e.g., createBackgroundAudioHandler)

Storage Backends#

Libraries needing persistence provide interchangeable backends:

  • InMemory -- for testing and server-side rendering
  • LocalStorage -- for simple browser persistence
  • IndexedDB -- for larger datasets with structured queries

React Hook Factories#

All libraries export createUse* factory functions rather than direct hooks. This allows the consuming application to inject its React dependency once via setReactHooks({ useState, useEffect, useCallback, useRef }) and then create bound hooks. This pattern avoids requiring React as a hard dependency and enables use in non-React environments (React Native, Vue adapters, vanilla JS).

Branded Types#

Type safety is enforced through branded types (SessionId, TrackId, ContentId, DurationSeconds, Timestamp, Percentage, ByteSize, etc.) that prevent accidental misuse of plain strings and numbers.


Technology Stack#

Layer Technology
Language TypeScript (ESM)
Event System eventemitter3
Build (most) @nx/js:tsc
Build (session) @nx/esbuild:esbuild (ESM + CJS dual output)
Testing Vitest
React Integration Optional peer dependency, hook factory pattern

Testing#

The libraries have comprehensive test suites totaling 18 spec files:

Library Test Files Coverage
player player.spec.ts, queue.spec.ts Core playback, queue operations
timer timer.spec.ts Timer lifecycle, phases, events
breathing exercise.spec.ts Exercise lifecycle, pattern execution
session manager.spec.ts, persistence.spec.ts, analytics.spec.ts, scheduler-crud.spec.ts, scheduler-ical.spec.ts, scheduler-recurrence.spec.ts, scheduler-triggers.spec.ts, scheduling-storage.spec.ts Session lifecycle, storage backends, analytics, scheduling CRUD/iCal/recurrence/triggers
progress tracker.spec.ts Progress recording, streak calculation
offline manager.spec.ts, queue.spec.ts, storage.spec.ts, suggestions.spec.ts, versioning.spec.ts Offline manager, download queue, storage, suggestions, versioning

Development#

bash
# Run tests for a specific library
pnpm nx test @oshun/meditation-player
pnpm nx test @oshun/meditation-timer
pnpm nx test @oshun/meditation-session
pnpm nx test @oshun/meditation-progress
pnpm nx test @oshun/meditation-breathing
pnpm nx test @oshun/meditation-offline

# Build a specific library
pnpm nx build @oshun/meditation-player

# Run all meditation library tests
pnpm nx run-many --target=test --projects=tag:scope:meditation
pnpm nx run-many --target=test --projects=tag:domain:meditation

# Build all meditation libraries
pnpm nx run-many --target=build --projects=tag:scope:meditation

# Lint a specific library
pnpm nx lint @oshun/meditation-timer

Note: Project tags are not fully consistent across libraries. Some use scope:meditation while others use domain:meditation. Use both tag filters when running commands across the full set.


Relationship to the Tara Domain#

The Tara domain (apps/tara/ and libs/tara/) is a meditation and mindfulness application that consumes all six meditation libraries. Tara provides:

  • apps/tara/api -- Backend API server
  • apps/tara/web -- Next.js web application
  • apps/tara/mobile -- React Native mobile application
  • libs/tara/content -- Content hooks (collections, courses)
  • libs/tara/database -- Prisma database schema and client
  • libs/tara/ui -- Shared UI component library

The meditation libraries handle all platform-agnostic logic (audio playback, timer counting, breathing patterns, session tracking, progress calculation, offline management), while Tara's apps and libs handle platform-specific concerns (API endpoints, UI components, database persistence, push notifications, app store submissions).


  • Tara - The meditation and mindfulness app domain that consumes these libraries for its web, mobile, and API applications
  • Arete - Personal development domain with complementary habit tracking and goal setting features that could integrate meditation progress
  • Kuanyin - Compassion and ethics domain providing wellness frameworks