npm package: @product-intelligence-hub/sdk-react-native
Description: React Native SDK for Product Intelligence Hub
Latest version: 0.4.2

# @product-intelligence-hub/sdk-react-native

React Native SDK for Product Intelligence Hub.

## Installation

```bash
npm install @product-intelligence-hub/sdk-react-native
# or
yarn add @product-intelligence-hub/sdk-react-native
# or
pnpm add @product-intelligence-hub/sdk-react-native
```

### Peer Dependencies

```bash
npm install @react-native-async-storage/async-storage
```

Optional for screen tracking:
```bash
npm install @react-navigation/native
```

Optional for network type tracking:
```bash
npm install @react-native-community/netinfo
```

## Quick Start

```typescript
import PIH from "@product-intelligence-hub/sdk-react-native";

// Initialize the SDK
const pih = PIH.init({
  apiKey: "your-api-key",
  projectId: "proj_xxx",
  environment: "production",
});

// Track an event
pih.track("button_pressed", {
  button_id: "checkout",
  screen: "Cart",
});

// Identify a user
pih.identify("user_123", {
  email: "user@example.com",
  subscription: "premium",
});
```

## Configuration Options

```typescript
PIH.init({
  // Required
  apiKey: string;           // Environment API key
  projectId: string;        // Project ID (proj_xxx)
  environment: string;      // Environment name

  // Optional
  apiUrl?: string;          // Ingest API URL (has default, override for self-hosted)
  tenantId?: string;        // Tenant ID for multi-tenant apps
  debug?: boolean;          // Enable debug logging (default: false)
  flushInterval?: number;   // Batch flush interval in ms (default: 10000)
  flushAt?: number;         // Flush when queue reaches this size (default: 20)
  maxQueueSize?: number;    // Max events to queue (default: 1000)
  sessionTimeout?: number;  // Session timeout in ms (default: 1800000)
  trackLifecycle?: boolean; // Track app lifecycle events (default: true)

  // Callbacks
  onError?: (error: PIHError) => void;
});
```

## API

### `PIH.init(config)`

Initialize the SDK. Returns the client instance.

### `pih.track(eventName, properties?, options?)`

Track an event.

```typescript
pih.track("item_added_to_cart", {
  product_id: "prod_123",
  quantity: 2,
  price: 29.99,
});
```

### `pih.identify(userId, traits?)`

Identify the current user.

```typescript
pih.identify("user_123", {
  email: "user@example.com",
  name: "Jane Doe",
});
```

### `pih.trackScreen(screenName, params?)`

Manually track a screen view.

```typescript
pih.trackScreen("ProductDetail", { product_id: "prod_123" });
```

### `pih.flush()`

Force flush the event queue.

```typescript
await pih.flush();
```

### `pih.reset()`

Reset identity (for logout).

```typescript
await pih.reset();
```

## Screen Tracking with React Navigation

```typescript
import { NavigationContainer } from "@react-navigation/native";
import PIH from "@product-intelligence-hub/sdk-react-native";

function App() {
  const navigationRef = useNavigationContainerRef();
  const pih = PIH.getInstance();

  useEffect(() => {
    if (pih) {
      const cleanup = pih.setupScreenTracking(navigationRef, {
        // Optional: transform screen names
        getScreenName: (route) => route.name,
        // Optional: include route params
        includeParams: true,
      });
      return cleanup;
    }
  }, []);

  return (
    <NavigationContainer ref={navigationRef}>
      {/* ... */}
    </NavigationContainer>
  );
}
```

## Lifecycle Tracking

By default, the SDK tracks app lifecycle events:

- `app_opened` - App comes to foreground
- `app_backgrounded` - App goes to background

Disable with:

```typescript
PIH.init({
  // ...
  trackLifecycle: false,
});

// Or at runtime
pih.disableLifecycleTracking();
pih.enableLifecycleTracking();
```

## Platform Detection

The SDK automatically detects the platform (`ios` or `android`) from React Native.

## Device Context

The SDK automatically collects device context on every event:

- `osVersion` -- OS version string
- `screenWidth` / `screenHeight` -- physical screen dims (via `Dimensions` + `PixelRatio`)
- `viewportWidth` / `viewportHeight` -- viewport dimensions
- `locale` -- device locale (via `Intl`)
- `timezone` -- IANA timezone (via `Intl.DateTimeFormat`)
- `deviceType` -- always `"mobile"`
- `connectionType` -- network type (wifi, cellular, etc.) when `@react-native-community/netinfo` is installed

These fields are included in the `context` property of each event.

## App Install / Update Detection

On initialization, the SDK compares the current `appVersion` against the previously stored version:

- **`app_installed`** -- fired on first launch (no stored version)
- **`app_updated`** -- fired when version changes (includes `previous_version` property)

## Session Enrichment

Each event includes session-level metadata:

- `sessionNumber` -- incrementing counter of sessions (persists across sessions)
- `eventIndex` -- zero-based position of the event within the current session

## TypeScript Support

Full TypeScript support included:

```typescript
import type {
  RNPIHConfig,
  TrackEvent,
  ScreenTrackerOptions,
} from "@product-intelligence-hub/sdk-react-native";
```

## Related

- [@product-intelligence-hub/sdk-core](https://www.npmjs.com/package/@product-intelligence-hub/sdk-core) - Core SDK internals
- [SDK Spec](https://github.com/maxivarela/product-intelligence-hub/blob/main/docs/06_SDK_SPEC.md) - Full SDK specification