npm package: @idto/digilocker-sdk
Description: Official JavaScript SDK for integrating DigiLocker authentication with IDTO platform. Provides secure Aadhaar verification with real-time event tracking and reference key delivery.
Author: IDTO
Latest version: 0.1.4

# @idto/digilocker-sdk

Official JavaScript SDK for integrating DigiLocker authentication with IDTO platform. Provides secure Aadhaar verification with real-time event tracking and reference key delivery.

## Features

- 🔐 **Secure DigiLocker Integration** - Government-approved Aadhaar verification
- 📱 **Responsive Design** - Optimized for mobile and desktop
- 🌐 **Multi-language Support** - English & Hindi
- 🔊 **Audio Controls** - User-friendly audio management
- 📡 **Real-time Events** - Track user state and progress
- 🎯 **User State Tracking** - Monitor authentication flow
- 🔑 **Reference Key Delivery** - Get verification results instantly
- ⚡ **Lightweight** - Minimal bundle size with maximum functionality
- 📝 **Full TypeScript Support** - Complete type definitions and IntelliSense

## Installation

```bash
npm install @idto/digilocker-sdk
# or
yarn add @idto/digilocker-sdk
# or
pnpm add @idto/digilocker-sdk
```

## Domain Whitelisting

**Important**: Before using the SDK, please contact the organization to whitelist your domain. This is required for the DigiLocker integration to work properly.

**Required Setup**:
- **Domain Whitelisting**: Contact support to whitelist your domain
- **User ID**: Obtain your unique user identifier from the organization
- **Authentication Token**: Get your secure authentication token

Contact: support@idto.ai

## Quick Start

```tsx
import { DigilockerIdtoSdk } from '@idto/digilocker-sdk';

function App() {
  return (
    <DigilockerIdtoSdk
      userId="user123"
      token="your-auth-token"
      isShowDrawerInMobile={false}
    />
  );
}
```

## Loading CSS Styles

**✅ CSS is automatically included!** When you import the `DigilockerIdtoSdk` component, all necessary styles are automatically loaded. No additional CSS imports are required.

```tsx
import { DigilockerIdtoSdk } from '@idto/digilocker-sdk';

function App() {
  return (
    <DigilockerIdtoSdk
      userId="user123"
      token="your-auth-token"
      isShowDrawerInMobile={false}
    />
  );
}
```

**Note**: The CSS is embedded directly into the JavaScript bundle, so you don't need to worry about loading external stylesheets.

## Event-Driven Architecture

The SDK emits real-time events to keep your application informed about the user's DigiLocker authentication status.

### Event Types

| Event | Description | Data Payload |
|-------|-------------|--------------|
| `SESSION_INITIATED` | DigiLocker session started | `{ user_id, redirect_url }` |
| `REFERENCE_RECEIVED` | **Reference key received** | `{ user_id, reference_key, expires_at }` |
| `SESSION_COMPLETED` | Authentication completed | `{ user_id }` |
| `ERROR_OCCURRED` | Error during process | `{ user_id, error, error_code }` |
| `SESSION_EXPIRED` | Session expired | `{ user_id, reference_key }` |
| `LANGUAGE_CHANGED` | Language preference changed | `{ language, language_code }` |
| `AUDIO_TOGGLED` | Audio state changed | `{ is_muted }` |

### Using Event Callbacks

```tsx
import { DigilockerIdtoSdk } from '@idto/digilocker-sdk';

function App() {
  const handleReferenceReceived = (data) => {
    console.log('✅ Reference Key:', data.reference_key);
    console.log('⏰ Expires at:', data.expires_at);
    
    // Store reference key in your database
    saveReferenceKey(data.user_id, data.reference_key);
  };

  const handleSessionCompleted = (data) => {
    console.log('🎉 Session completed for user:', data.user_id);
    // Redirect user or update UI
  };

  const handleError = (data) => {
    console.error('❌ Error occurred:', data.error);
    // Show error message to user
  };

  return (
    <DigilockerIdtoSdk
      userId="user123"
      token="your-auth-token"
      onReferenceReceived={handleReferenceReceived}
      onSessionCompleted={handleSessionCompleted}
      onError={handleError}
    />
  );
}
```

### Global Event Emitter

For advanced event handling across components:

```tsx
import { globalEventEmitter } from '@idto/digilocker-sdk';

// Listen to all events
globalEventEmitter.on('REFERENCE_RECEIVED', (event) => {
  console.log('Event:', event.type);
  console.log('Data:', event.data);
  console.log('Timestamp:', event.timestamp);
});

// Listen to specific events
globalEventEmitter.on('SESSION_INITIATED', (event) => {
  console.log('Session initiated for user:', event.data.user_id);
});

// Remove listener
const handleError = (event) => console.log('Error:', event.data.error);
globalEventEmitter.on('ERROR_OCCURRED', handleError);

// Later remove the listener
globalEventEmitter.off('ERROR_OCCURRED', handleError);

// Remove all listeners
globalEventEmitter.removeAllListeners();
```

### React Hooks

Use the provided React hooks for component-level event handling:

```tsx
import { useEventListener } from '@idto/digilocker-sdk';

function MyComponent() {
  useEventListener('REFERENCE_RECEIVED', (event) => {
    console.log('Reference received:', event.data.reference_key);
  });

  useEventListener('ERROR_OCCURRED', (event) => {
    console.error('Error:', event.data.error);
  });

  return <div>Listening to events...</div>;
}
```

## Complete Integration Example

```tsx
import React, { useState } from 'react';
import { DigilockerIdtoSdk } from '@idto/digilocker-sdk';

function App() {
  const [referenceKey, setReferenceKey] = useState('');
  const [sessionStatus, setSessionStatus] = useState('idle');

  const handleReferenceReceived = (data) => {
    setReferenceKey(data.reference_key);
    setSessionStatus('completed');
    
    // Send to your backend
    fetch('/api/store-reference', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        userId: data.user_id,
        referenceKey: data.reference_key,
        expiresAt: data.expires_at
      })
    });
  };

  const handleSessionInitiated = (data) => {
    setSessionStatus('initiated');
    console.log('Redirecting to:', data.redirect_url);
  };

  const handleError = (data) => {
    setSessionStatus('error');
    console.error('DigiLocker error:', data.error);
  };

  return (
    <div>
      <h1>DigiLocker Integration</h1>
      
      {sessionStatus === 'completed' && (
        <div>
          <h2>✅ Verification Complete!</h2>
          <p>Reference Key: {referenceKey}</p>
        </div>
      )}

      {sessionStatus === 'error' && (
        <div>
          <h2>❌ Error Occurred</h2>
          <p>Please try again</p>
        </div>
      )}

      <DigilockerIdtoSdk
        userId="user123"
        token="your-auth-token"
        onReferenceReceived={handleReferenceReceived}
        onSessionInitiated={handleSessionInitiated}
        onError={handleError}
        onSessionCompleted={() => setSessionStatus('completed')}
      />
    </div>
  );
}

export default App;
```

## API Reference

### Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `userId` | string | ✅ | - | Unique identifier for the user |
| `token` | string | ✅ | - | Authentication token |
| `isShowDrawerInMobile` | boolean | ❌ | false | Show drawer on mobile devices |

### Event Callback Props

| Prop | Type | Description |
|------|------|-------------|
| `onEvent` | function | General event handler for all events |
| `onSessionInitiated` | function | Called when session is initiated |
| `onReferenceReceived` | function | Called when reference key is received |
| `onSessionCompleted` | function | Called when session is completed |
| `onError` | function | Called when an error occurs |
| `onSessionExpired` | function | Called when session expires |
| `onLanguageChanged` | function | Called when language is changed |
| `onAudioToggled` | function | Called when audio is toggled |

### Event Data Structure

```typescript
interface DigilockerEvent {
  type: DigilockerEventType;
  timestamp: number;
  data?: any;
}
```

## Styling & Customization

The SDK includes comprehensive CSS classes that you can customize to match your application's design:

### Layout & Containers

```css
/* Main containers */
.idto_digilocker_app_container
.idto_digilocker_main_container
.idto_digilocker_init_container
.idto_digilocker_init_container_full_height

/* Responsive height classes */
.idto_digilocker_mobile_min_height
.idto_digilocker_desktop_min_height

/* Overview containers */
.idto_digilocker_overview_container
.idto_digilocker_overview_container_mobile
.idto_digilocker_overview_container_desktop
```

### Header & Navigation

```css
/* Header components */
.idto_digilocker_header
.idto_digilocker_header_mobile
.idto_digilocker_header_desktop
.idto_digilocker_header_logo_container
.idto_digilocker_header_logo_container_mobile
.idto_digilocker_header_logo_container_desktop

/* DigiLocker init header */
.idto_digilocker_init_header
.idto_digilocker_init_logo_container
```

### Controls & Interactive Elements

```css
/* Language controls */
.idto_digilocker_init_language_dropdown
.idto_digilocker_init_language_trigger
.idto_digilocker_init_language_dropdown_menu
.idto_digilocker_init_language_option
.idto_digilocker_init_language_text
.idto_digilocker_init_language_arrow

/* Audio controls */
.idto_digilocker_init_audio_control
.idto_digilocker_init_audio_text

/* Buttons */
.idto_digilocker_button
.idto_digilocker_button_primary
.idto_digilocker_button_secondary
.idto_digilocker_button_success
.idto_digilocker_button_error
.idto_digilocker_button_text
.idto_digilocker_button_loader
.idto_digilocker_init_button
.idto_digilocker_mobile_button
.idto_digilocker_desktop_button
```

### Content Sections

```css
/* Main content areas */
.idto_digilocker_init_content
.idto_digilocker_init_main_content
.idto_digilocker_init_info_section
.idto_digilocker_init_visual_section
.idto_digilocker_init_footer

/* Text sections */
.idto_digilocker_init_text_section
.idto_digilocker_init_title
.idto_digilocker_init_description
.idto_digilocker_init_security_text

/* Mobile & Desktop content */
.idto_digilocker_mobile_content
.idto_digilocker_mobile_title
.idto_digilocker_mobile_description
.idto_digilocker_mobile_disclaimer
.idto_digilocker_desktop_content
.idto_digilocker_desktop_title
.idto_digilocker_desktop_subtitle
.idto_digilocker_desktop_description
.idto_digilocker_desktop_disclaimer
```

### Success & Loading States

```css
/* Success state */
.idto_digilocker_success_container
.idto_digilocker_success_content
.idto_digilocker_success_gif
.idto_digilocker_countdown_text

/* Loading states */
.idto_digilocker_loader
.idto_digilocker_loader_spinner

/* Error states */
.idto_digilocker_init_error_text
```

### Modal & Overlay Components

```css
/* Modal variants */
.idto_digilocker_modal_overlay
.idto_digilocker_modal_content
.idto_digilocker_modal_small
.idto_digilocker_modal_medium
.idto_digilocker_modal_large
.idto_digilocker_modal_custom

/* Bottom sheet */
.idto_digilocker_bottom_sheet_overlay
.idto_digilocker_bottom_sheet_content
.idto_digilocker_bottom_sheet_default
.idto_digilocker_bottom_sheet_custom
.idto_digilocker_bottom_sheet_drag_handle
.idto_digilocker_bottom_sheet_drag_indicator
```

### Branding & Visual Elements

```css
/* Branding */
.idto_digilocker_init_branding
.idto_digilocker_init_branding_text
.idto_digilocker_init_branding_logo

/* Icons & images */
.idto_digilocker_init_icon_container
.idto_digilocker_init_image_container
.idto_digilocker_init_security_badge
.idto_digilocker_desktop_logo
```

### Customization Examples

```css
/* Custom button styling */
.idto_digilocker_button {
  background-color: #your-brand-color;
  border-radius: 8px;
  font-weight: 600;
}

/* Custom header styling */
.idto_digilocker_init_header {
  background: linear-gradient(90deg, #your-color-1, #your-color-2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Custom modal styling */
.idto_digilocker_modal_content {
  border-radius: 16px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
}
```

## Error Handling

Comprehensive error handling with specific error codes:

```tsx
const handleError = (data) => {
  switch (data.error_code) {
    case 'SESSION_INITIATION_FAILED':
      // Handle session initiation failure
      showToast('Failed to start verification. Please try again.');
      break;
    case 'REFERENCE_FETCH_FAILED':
      // Handle reference fetch failure
      showToast('Verification failed. Please restart the process.');
      break;
    default:
      // Handle generic errors
      showToast('An unexpected error occurred. Please try again.');
      break;
  }
};
```

## Browser Support

- ✅ Chrome 80+
- ✅ Firefox 75+
- ✅ Safari 13+
- ✅ Edge 80+

## Requirements

- React >= 16.8.0
- React DOM >= 16.8.0
- Node.js >= 14.0.0

## TypeScript Support

This package includes complete TypeScript declarations. No additional `@types` packages are required.

```typescript
import { DigilockerIdtoSdk, DigilockerEvent } from '@idto/digilocker-sdk';

// Full IntelliSense support
const handleEvent = (event: DigilockerEvent) => {
  console.log(event.type, event.data);
};
```

## Development

### Build the Package

```bash
npm run build:lib
# or
pnpm run build:lib
# or
yarn build:lib
```

This creates the distribution files in the `dist/` folder, including:
- **ESM Bundle**: `index.esm.js` - For modern bundlers
- **CommonJS Bundle**: `index.cjs.js` - For Node.js compatibility
- **TypeScript Declarations**: `*.d.ts` files - For full type support
- **Source Maps**: `*.map` files - For debugging

### Type Checking

```bash
npm run type-check
```

### Linting

```bash
npm run lint
```

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Support

- 📧 Email: support@idto.ai
- 📖 Documentation: [https://docs.idto.ai](https://docs.idto.ai)
- 🐛 Issues: [GitHub Issues](https://github.com/idto-ai/digilocker-sdk/issues)

---

Built with ❤️ by [IDTO](https://idto.ai)