API Reference
Complete reference for the BodyTracker class — the single entry point for the core @bodytracker/sdk package. Every constructor, method, and property is documented below with its full signature, parameters, return value, and a runnable example. If you're building with React, the Hooks reference wraps this same class with reactive bindings.
new BodyTracker()
Constructorsince v1.0.0Creates a new tracker instance from a configuration object. The constructor is synchronous and does no camera or model work — it validates the config, stores it, and puts the tracker in the idle status. Call init() afterward to perform the async setup that actually prepares tracking.
new BodyTracker(config: BodyTrackerConfig)Parameters
| Parameter | Type | Description |
|---|---|---|
configRequired | BodyTrackerConfig | Tracker configuration: your API key, target environment, optional camera device, activity type allowlist, movement smoothing, and locale. |
Returns
BodyTracker — A new tracker instance in the idle status, ready to be initialized.
Throws
TypeError— Thrown synchronously if config.apiKey is missing, empty, or not a string.
Example
import { BodyTracker } from "@bodytracker/sdk"; const tracker = new BodyTracker({ apiKey: "bt_live_7Gm3q...redacted", environment: "production", activityTypes: ["standing", "walking", "running"], smoothing: { enabled: true, windowSize: 5 },}); console.log(tracker.getStatus()); // "idle"Notes
- Constructing a tracker has no side effects on the page — no camera prompt, no network request — until init() is called.
- Use environment: "sandbox" during development to exercise the full API against synthetic tracking data without a real camera feed.
init()
Methodsince v1.0.0Performs the tracker's asynchronous setup: requests camera permission via getUserMedia, downloads and warms up the on-device tracking model, and transitions status from idle to initializing to ready. Every other tracking method requires init() to have resolved first.
init(): Promise<void>Returns
Promise<void> — Resolves once the tracker has reached the ready status and startSession() can be called.
Throws
CameraPermissionDeniedError— Thrown if the user denies the camera permission prompt or the browser blocks getUserMedia.ModelLoadError— Thrown if the tracking model fails to download or fails to initialize on the current device.
Example
const tracker = new BodyTracker({ apiKey: "bt_test_2Lp9x...redacted" }); try { await tracker.init(); console.log(tracker.getStatus()); // "ready"} catch (error) { console.error("Failed to initialize tracker:", error);}Notes
- Calling init() more than once on the same instance is safe — subsequent calls resolve immediately once the tracker is ready.
- In environment: "sandbox" mode, init() skips the camera permission prompt entirely and resolves against synthetic data.
startSession()
Methodsince v1.0.0Begins a new tracking session and transitions status to tracking. A session groups continuous movement data under a single id until stopSession() is called, and can be paused and resumed without ending it.
startSession(options?: StartSessionOptions): Promise<Session>Parameters
| Parameter | Type | Description |
|---|---|---|
optionsOptional | StartSessionOptions | Optional session metadata: the activity to record under and a human-readable label shown in exports and dashboards. |
Returns
Promise<Session> — Resolves with the newly created session once recording has started.
Throws
TrackerNotReadyError— Thrown if init() has not resolved yet — the tracker must be in the ready status.SessionAlreadyActiveError— Thrown if a session is already recording or paused; stop it first.
Example
await tracker.init(); const session = await tracker.startSession({ activity: "running", label: "Morning run",}); console.log(session.id, session.status); // "recording"Notes
- If options.activity is omitted, the SDK infers the initial activity from the live camera feed as soon as tracking starts.
stopSession()
Methodsince v1.0.0Ends the active tracking session, finalizes its analytics, and transitions status back to ready. Use exportSession() afterward if you need the raw or formatted session data.
stopSession(): Promise<SessionSummary>Returns
Promise<SessionSummary> — Resolves with the completed session's duration, activity, and average tracking quality.
Throws
NoActiveSessionError— Thrown if there is no recording or paused session to stop.
Example
const summary = await tracker.stopSession(); console.log(`Tracked ${summary.durationSeconds}s of ${summary.activity}`);console.log(`Average quality: ${summary.averageQuality}`);pauseSession()
Methodsince v1.0.0Pauses the active session without ending it — movement data stops accumulating and status becomes paused, but the session id and elapsed duration are preserved. Call resumeSession() to continue.
pauseSession(): voidReturns
void — No return value; check getStatus() to confirm the tracker is now paused.
Throws
NoActiveSessionError— Thrown if there is no recording session to pause.
Example
tracker.pauseSession();console.log(tracker.getStatus()); // "paused"Notes
- Unlike stopSession(), pausing does not produce a SessionSummary — the session is still open.
resumeSession()
Methodsince v1.0.0Resumes a session previously paused with pauseSession(), transitioning status back to tracking and continuing to accumulate movement data on the same session id.
resumeSession(): voidReturns
void — No return value; check getStatus() to confirm the tracker is tracking again.
Throws
NoActiveSessionError— Thrown if there is no paused session to resume.
Example
tracker.resumeSession();console.log(tracker.getStatus()); // "tracking"getStatus()
Methodsince v1.0.0Synchronously reads the tracker's current lifecycle status. Useful for guarding calls to session methods or driving UI state without subscribing to events.
getStatus(): TrackerStatusReturns
TrackerStatus — One of "idle" | "initializing" | "ready" | "tracking" | "paused" | "stopped" | "error".
Example
const status = tracker.getStatus(); if (status === "tracking") { console.log("Currently recording a session.");}getActivity()
Methodsince v1.0.0Synchronously reads the most recently detected activity and tracking quality, along with the timestamp since that activity began. Useful for polling in render loops where subscribing to activityChanged would be overkill.
getActivity(): ActivitySnapshotReturns
ActivitySnapshot — The current activity, its tracking quality, and an ISO 8601 timestamp for when it started.
Example
const snapshot = tracker.getActivity(); console.log(`${snapshot.activity} (${snapshot.quality} quality) since ${snapshot.since}`);Notes
- Before the first activity is detected, activity defaults to "idle" and quality to "searching".
on()
Methodsince v2.0.0Subscribes handler to the given event and returns an unsubscribe function — the preferred way to detach a listener, especially for handlers created inline. See the Events reference for every event name and its payload shape.
on(event: TrackerEventName, handler: (payload: unknown) => void): () => voidParameters
| Parameter | Type | Description |
|---|---|---|
eventRequired | TrackerEventName | The event to subscribe to, e.g. "activityChanged" or "sessionEnded". |
handlerRequired | (payload: unknown) => void | Called with the event's payload each time it fires. Narrow payload's type per-event using the Events reference. |
Returns
() => void — A function that, when called, removes this exact handler from this exact event.
Example
const unsubscribe = tracker.on("activityChanged", (event) => { console.log("Activity changed:", event);}); // Later, when you no longer need updates:unsubscribe();Notes
- The same handler can be registered for multiple events, and the same event can have multiple handlers — all are called in registration order.
off()
Methodsince v2.0.0Removes a previously registered handler from an event. Requires the exact same function reference passed to on() — prefer the unsubscribe function on() returns unless you need to detach a named handler from elsewhere.
off(event: TrackerEventName, handler: (payload: unknown) => void): voidParameters
| Parameter | Type | Description |
|---|---|---|
eventRequired | TrackerEventName | The event the handler was registered on. |
handlerRequired | (payload: unknown) => void | The exact handler reference originally passed to on(). |
Returns
void — No return value. Calling off() with a handler that isn't registered is a safe no-op.
Example
function handleQualityChanged(payload: unknown) { console.log("Quality changed:", payload);} tracker.on("qualityChanged", handleQualityChanged); // ...later, from anywhere with a reference to the same function:tracker.off("qualityChanged", handleQualityChanged);exportSession()
Methodsince v2.0.0Generates a downloadable export of a completed session's tracking data in the requested format. json includes the full frame-level movement timeline; csv flattens it into rows suitable for spreadsheets; pdf renders a human-readable summary report.
exportSession(sessionId: string, format: "json" | "csv" | "pdf"): Promise<Blob>Parameters
| Parameter | Type | Description |
|---|---|---|
sessionIdRequired | string | The id of a completed session, as returned by startSession() or stopSession(). |
formatRequired | "json" | "csv" | "pdf" | The export format to generate. |
Returns
Promise<Blob> — Resolves with a Blob you can download via a generated object URL or upload elsewhere.
Throws
SessionNotFoundError— Thrown if no session with the given sessionId exists for this API key.UnsupportedFormatError— Thrown if format is not one of "json", "csv", or "pdf".
Example
const summary = await tracker.stopSession();const blob = await tracker.exportSession(summary.id, "csv"); const url = URL.createObjectURL(blob);const link = document.createElement("a");link.href = url;link.download = `session-${summary.id}.csv`;link.click();URL.revokeObjectURL(url);Notes
- pdf exports are generated server-side and take noticeably longer to resolve than json or csv.
destroy()
Methodsince v1.0.0Tears down the tracker: stops any active session without producing a summary, releases the camera stream, unloads the tracking model, and removes all event listeners. Transitions status to stopped.
destroy(): voidReturns
void — No return value.
Example
tracker.destroy();console.log(tracker.getStatus()); // "stopped"Notes
- A destroyed instance cannot be reused — construct a new BodyTracker if you need to track again.
- Always call destroy() when unmounting the component or page that owns the tracker to release the camera. @bodytracker/react's hooks do this for you automatically.