"use strict";
import StepCounterModule, { eventName, NAME, VERSION } from "./NativeStepCounter.js";
import { Platform } from "react-native";
/* A way to check if the module is linked. */
const LINKING_ERROR = "The package 'react-native-step-counter-newarch' doesn't seem to be linked. Make sure: \n\n" + Platform.select({
ios: "- You have run `pod install` in the `ios` directory and then clean, rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.\n",
android: "- You have the Android development environment set up: `https://reactnative.dev/docs/environment-setup.`",
default: ""
}) + '- Use the "npx react-native clean" command to clean up the module\'s cache and select the ' + '"watchman", "yarn", "metro", "android", "npm" options with comma-separated. ' + "Re-Install packages and re-build the app again ." + "- You rebuilt the app after installing the package\n" + "- You are not using Expo Go\n" + "If none of these fix the issue, please open an issue on the Github repository: " + "https://github.com/AndrewDongminYoo/react-native-step-counter`";
/**
* A module that allows you to get the step count data.
* `CMStepCounter` is deprecated in iOS 8.0. Used `CMPedometer` instead.
* floorsAscended - The number of floors ascended during the time period. iOS Only.
* floorsDescended - The number of floors descended during the time period. iOS Only.
* counterType - The type of counter used to count the steps.
* @throws {Error} LINKING_ERROR - Throws Error If global variable turboModuleProxy is undefined.
* @example
* import { StepCounter } from 'react-native-step-counter-newarch';
*/
const StepCounter = StepCounterModule ? StepCounterModule : new Proxy({}, {
get() {
throw new Error(LINKING_ERROR);
}
});
/** Subscribe without owning or starting native sensors. Remove the returned listener on cleanup. */
export const onStepCounterUpdate = listener => StepCounter.onStepCounterUpdate(listener);
/** Subscribe to platform detection/status diagnostics without starting sensors. */
export const onStepDetected = listener => StepCounter.onStepDetected(listener);
/** Subscribe to serializable native errors without owning a counting session. */
export const onErrorOccurred = listener => StepCounter.onErrorOccurred(listener);
/** Subscribe to platform-specific sensor metadata without starting sensors. */
export const onStepsSensorInfo = listener => StepCounter.onStepsSensorInfo(listener);
const DEFAULT_MINIMUM_STEP_INTERVAL_MS = 250;
// Tracks the subscription created by the most recent startStepCounterUpdate call.
// Its handle owns native teardown; external debug listeners remain registered.
let _activeSubscription = null;
let sessionSequence = 0;
/**
* Transform the step count data into a more readable format.
* You can use it or directly use the `StepCountData` type.
* @param {StepCountData} data - Step Counter Sensor Event Data.
* @returns {ParsedStepCountData} - String Parsed Count Data.
*/
export function parseStepData(data) {
const {
steps,
startDate,
endDate,
distance
} = data;
const dailyGoal = 10000;
const stepsString = steps + " steps";
const kCal = (steps * 0.045).toFixed(2) + "kCal";
const endDateTime = new Date(endDate).toLocaleTimeString("en-gb");
const startDateTime = new Date(startDate).toLocaleTimeString("en-gb");
const roundedDistance = distance === null ? "N/A" : distance.toFixed(1) + "m";
const stepGoalStatus = steps >= dailyGoal ? "Goal Reached" : `${steps}/${dailyGoal} steps`;
return {
dailyGoal: stepGoalStatus,
steps,
stepsString,
calories: kCal,
startDate: startDateTime,
endDate: endDateTime,
distance: roundedDistance
};
}
/**
* Create a stateful filter for live step-count updates.
*
* Native pedometer APIs can already include device/OS false positives, and the
* Android accelerometer fallback can also react to quick hand rotation. This
* helper rejects totals that exceed the session's measurement-time cadence budget
* and rebases later values so demonstrated impossible steps do not come back.
* It cannot detect false steps hidden by idle time earlier in the session.
* A newer startDate or backend change resets adjustments; stale events are ignored.
* Create a fresh filter when restarting with the same startDate and backend.
* Unavailable distance remains null. Distance correction cannot attribute increments
* across unavailable intervals; only observed adjacent increments are removed.
*/
export function createStepCountFilter(options = {}) {
const minimumStepIntervalMs = Number.isFinite(options.minimumStepIntervalMs) && options.minimumStepIntervalMs !== undefined && options.minimumStepIntervalMs > 0 ? options.minimumStepIntervalMs : DEFAULT_MINIMUM_STEP_INTERVAL_MS;
let previousRawData = null;
let ignoredSteps = 0;
let ignoredDistance = 0;
let lastKnownDistance = null;
const retiredBackends = new Set();
return data => {
if (!Number.isSafeInteger(data.steps) || data.steps < 0 || !Number.isFinite(data.startDate) || !Number.isFinite(data.endDate) || !Number.isFinite(data.endDate - data.startDate) || data.endDate < data.startDate || data.distance !== null && (!Number.isFinite(data.distance) || data.distance < 0)) {
return null;
}
if (previousRawData) {
if (data.startDate < previousRawData.startDate) {
return null;
}
if (data.startDate > previousRawData.startDate) {
previousRawData = null;
ignoredSteps = 0;
ignoredDistance = 0;
lastKnownDistance = null;
retiredBackends.clear();
} else {
if (data.endDate <= previousRawData.endDate) {
return null;
}
if (data.counterType !== previousRawData.counterType) {
if (retiredBackends.has(data.counterType)) {
return null;
}
retiredBackends.add(previousRawData.counterType);
previousRawData = null;
ignoredSteps = 0;
ignoredDistance = 0;
lastKnownDistance = null;
} else if (data.steps < previousRawData.steps || data.distance !== null && lastKnownDistance !== null && data.distance < lastKnownDistance) {
// A decrease alone cannot distinguish a reset from a stale report.
return null;
}
}
}
const stepDelta = previousRawData ? data.steps - previousRawData.steps : data.steps;
// An unavailable interval cannot be attributed to rejected steps.
const distanceDelta = data.distance === null || previousRawData && previousRawData.distance === null ? 0 : data.distance - (previousRawData?.distance ?? 0);
const elapsedMs = data.endDate - data.startDate;
// Cumulative reports may arrive close together even when their steps were
// measured over a longer window. Only the session total proves an excess.
const isSuspiciousBurst = stepDelta > 0 && data.steps - ignoredSteps > elapsedMs / minimumStepIntervalMs;
previousRawData = {
...data
};
if (data.distance !== null) lastKnownDistance = data.distance;
if (isSuspiciousBurst) {
ignoredSteps += stepDelta;
if (distanceDelta > 0) {
ignoredDistance += distanceDelta;
}
return null;
}
if (ignoredSteps === 0 && ignoredDistance === 0) {
return data;
}
return {
...data,
steps: Math.max(0, data.steps - ignoredSteps),
distance: data.distance === null ? null : Math.max(0, data.distance - ignoredDistance)
};
};
}
/**
* If you're using a method or property that's not available on the current platform, throw this error.
* @param {string} moduleName The name of the module.
* @param {string} propertyName The name of the property.
* @returns {Error} The error.
* @example
* if (!StepCounter.startStepCounterUpdate) {
* throw new UnavailabilityError(NativeModuleName, eventName);
* }
*/
class UnavailabilityError extends Error {
constructor(moduleName, propertyName) {
super(`The method or property ${moduleName}.${propertyName} is not available on ${Platform.OS}, ` + "are you sure you've linked all the native dependencies properly?");
this.code = "ERR_UNAVAILABLE";
}
}
/**
* Returns whether the stepCounter is enabled on the device.
* iOS 8.0+ only. Android is available since KitKat (4.4 / API 19).
* @see https://developer.android.com/about/versions/android-4.4.html
* @see https://developer.apple.com/documentation/coremotion/cmpedometer/1613963-isstepcountingavailable
* @returns {Promise<{ supported: boolean, granted: boolean }>} A promise that resolves with an object containing the stepCounter availability.
* supported - Whether a counting sensor is present, including the Android accelerometer fallback.
* granted - Whether permission is allowed, independently of sensor availability.
* Android requires activity recognition for both backends on API 29+ under the package consent policy.
* API 24–28 requires no activity runtime permission, so `granted` is true.
* Check capabilities again after requesting permission; support does not guarantee registration.
*/
export function isStepCountingSupported() {
return StepCounter.isStepCountingSupported();
}
/**
* Start to subscribe stepCounter updates.
* If native start throws synchronously, the new listener is removed and the error is rethrown.
* If stopping a previous session throws, its listener is removed and that error
* propagates before a replacement listener or native session is started.
* ### iOS
* Live updates exclude activity recorded before this call, even for a past start date.
* iOS queries the available history from `start` to the call time as a baseline,
* then subtracts it from steps, distance, and floors. Emitted `startDate` is that
* cutoff and `endDate` is the measurement time. Future origins clamp to the call time.
* Missing baseline/current optional metrics remain null; an unknown baseline stays
* null for the session. If the query fails with a non-permission error, the first
* valid live sample becomes the baseline and its end date becomes the cutoff;
* that sample is not emitted. Permission errors stop counting even when reported
* by the baseline query.
* Zero-step, stale, or decreasing windows are ignored without lowering baselines.
* Native `queryStepCounterDataBetweenDates` instead returns the requested historical
* interval (limited to available Core Motion history) without live-session subtraction.
* It is not exposed by this TypeScript wrapper.
* `CMPedometer.startUpdates` replaces the deprecated `CMStepCounter` API.
* @see https://developer.apple.com/documentation/coremotion/cmpedometer/1613950-startupdates
* @see https://developer.apple.com/documentation/coremotion/cmstepcounter/1616151-startstepcountingupdates
* @param {Date} start Native origin; on iOS, used to query the baseline, not to replay past steps.
* @param {StepCountUpdateCallback} callBack - This callback function makes it easy for app developers to receive sensor events.
* @param onError Optional session-scoped native failure callback; remove the subscription on fatal errors.
* @throws {RangeError} If start is an invalid Date, before replacing the current subscription.
* @returns {EventSubscription} - Returns a Subscription that enables you to call.
* Calling `remove()` on the current subscription stops native sensors and removes
* that listener. Repeated removal and removing a replaced handle are safe.
* Independent debug listeners remain subscribed but do not keep sensors running.
* @example
* const startDate = new Date();
* subscriptionRef.current = startStepCounterUpdate(startDate, (response) => {
* const data = parseStepData(response);
* })
*/
export function startStepCounterUpdate(start, callBack, onError) {
if (!StepCounter.startStepCounterUpdate) {
throw new UnavailabilityError(NAME, eventName);
}
if (onError && !StepCounter.startStepCounterUpdateWithSession) {
throw new UnavailabilityError(NAME, "startStepCounterUpdateWithSession");
}
const from = start.getTime();
if (!Number.isFinite(from)) {
throw new RangeError("start must be a valid Date");
}
// Clean up any previous subscription registered by this library before creating a new one.
_activeSubscription?.remove();
const listener = StepCounter.onStepCounterUpdate(callBack);
const sessionId = `${Date.now()}-${++sessionSequence}`;
let errorListener;
let removed = false;
const subscription = {
remove() {
if (removed) return;
removed = true;
const ownsSession = _activeSubscription === subscription;
if (ownsSession) _activeSubscription = null;
try {
if (ownsSession) StepCounter.stopStepCounterUpdate();
} finally {
try {
listener.remove();
} finally {
errorListener?.remove();
}
}
}
};
_activeSubscription = subscription;
try {
if (onError) {
errorListener = StepCounter.onErrorOccurred(error => {
if (!removed && _activeSubscription === subscription && error.sessionId === sessionId) {
onError(error);
}
});
StepCounter.startStepCounterUpdateWithSession(from, sessionId);
} else {
StepCounter.startStepCounterUpdate(from);
}
} catch (error) {
try {
subscription.remove();
} catch {
// Listener removal still runs in finally; preserve the original start error.
}
throw error;
}
return subscription;
}
/**
* Stop the step counter updates.
* ### iOS
* `CMStepCounter.stopStepCountingUpdates` is deprecated since iOS 8.0. so used `CMPedometer.stopUpdates` instead.
* @see https://developer.apple.com/documentation/coremotion/cmpedometer/1613973-stopupdates
* @see https://developer.apple.com/documentation/coremotion/cmstepcounter/1616157-stopstepcountingupdates
*/
export function stopStepCounterUpdate() {
// Remove only the subscription registered by this library, not all listeners.
// Calling removeAllListeners would break external subscribers such as debug log components.
if (_activeSubscription) {
_activeSubscription.remove();
} else {
StepCounter.stopStepCounterUpdate();
}
}
export { NAME, VERSION };
//# sourceMappingURL=index.js.map