npm package: @mybambu/account-service-sdk
Description: TypeScript SDK for MyBambu Account Service
Author: MyBambu
Latest version: 1.0.0

# MyBambu Account Service SDK

TypeScript SDK for interacting with the MyBambu Account Service API.

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Authentication](#authentication)
- [API Reference](#api-reference)
  - [User Management](#user-management)
  - [Address Management](#address-management)
  - [Device Management](#device-management)
  - [Security Questions](#security-questions)
  - [Verification](#verification)
  - [Password Reset](#password-reset)
  - [Disclosures](#disclosures)
- [Error Handling](#error-handling)
- [Examples](#examples)

## Installation

```bash
npm install @mybambu/account-service-sdk
```

## Quick Start

```typescript
import { AccountServiceClient } from '@mybambu/account-service-sdk';

// Initialize the client
const client = new AccountServiceClient({
  baseURL: 'http://localhost:3000',
  apiPrefix: 'api/v1', // optional, defaults to 'api/v1'
  timeout: 30000, // optional, defaults to 30000ms
});

// Register a new user
const { access_token, user } = await client.register({
  email: 'user@example.com',
  password: 'SecurePassword123!',
  firstName: 'John',
  lastName: 'Doe',
});

// The token is automatically set after registration/login
console.log('Logged in as:', user.email);

// Make authenticated requests
const profile = await client.getUserProfile();
```

## Configuration

### AccountServiceConfig

| Property | Type | Required | Default | Description |
|----------|------|----------|---------|-------------|
| baseURL | string | Yes | - | Base URL of the Account Service |
| apiPrefix | string | No | 'api/v1' | API prefix path |
| timeout | number | No | 30000 | Request timeout in milliseconds |
| headers | Record<string, string> | No | {} | Additional headers to include |

## Authentication

The SDK automatically handles JWT token management. After successful login or registration, the token is stored and included in all subsequent requests.

### Manual Token Management

```typescript
// Set token manually
client.setToken('your-jwt-token');

// Get current token
const token = client.getToken();

// Clear token
client.clearToken();
```

### Token Auto-Clear on 401

The SDK automatically clears the stored token when a 401 Unauthorized response is received.

## API Reference

### Authentication

#### register(data: RegisterDto): Promise<LoginResponse>

Register a new user account.

```typescript
const response = await client.register({
  email: 'user@example.com',
  password: 'SecurePassword123!',
  firstName: 'John',
  lastName: 'Doe',
  phoneNumber: '+1234567890', // optional
  dateOfBirth: '1990-01-01', // optional
});
```

#### login(data: LoginDto): Promise<LoginResponse>

Login with email and password.

```typescript
const response = await client.login({
  email: 'user@example.com',
  password: 'SecurePassword123!',
});
```

#### getCurrentUser(): Promise<UserResponse>

Get the current authenticated user's profile.

```typescript
const user = await client.getCurrentUser();
```

#### logout(): Promise<{ message: string }>

Logout the current user.

```typescript
await client.logout();
```

### User Management

#### getUserProfile(): Promise<UserResponse>

Get detailed user profile.

```typescript
const profile = await client.getUserProfile();
```

#### updateProfile(data: UpdateProfileDto): Promise<UserResponse>

Update user profile information.

```typescript
const updatedProfile = await client.updateProfile({
  firstName: 'Jane',
  lastName: 'Smith',
  phoneNumber: '+1987654321',
});
```

#### updatePassword(data: UpdatePasswordDto): Promise<{ message: string }>

Change user password.

```typescript
await client.updatePassword({
  currentPassword: 'OldPassword123!',
  newPassword: 'NewPassword123!',
});
```

#### getUserPreferences(): Promise<any>

Get user preferences.

```typescript
const preferences = await client.getUserPreferences();
```

#### updatePreferences(data: any): Promise<any>

Update user preferences.

```typescript
const updated = await client.updatePreferences({
  theme: 'dark',
  notifications: true,
});
```

#### deactivateAccount(): Promise<{ message: string }>

Deactivate user account.

```typescript
await client.deactivateAccount();
```

#### PIN Management

```typescript
// Set PIN
await client.setPin('1234');

// Verify PIN
const { valid } = await client.verifyPin('1234');

// Update PIN
await client.updatePin('1234', '5678');
```

### Address Management

#### getAddress(): Promise<AddressResponse>

Get user's address.

```typescript
const address = await client.getAddress();
```

#### createAddress(data: CreateAddressDto): Promise<AddressResponse>

Create a new address.

```typescript
const address = await client.createAddress({
  street: '123 Main St',
  city: 'New York',
  state: 'NY',
  postalCode: '10001',
  country: 'USA',
});
```

#### updateAddress(data: UpdateAddressDto): Promise<AddressResponse>

Update existing address.

```typescript
const updated = await client.updateAddress({
  street: '456 Oak Ave',
});
```

#### deleteAddress(): Promise<void>

Delete user's address.

```typescript
await client.deleteAddress();
```

#### Address Validation

```typescript
// Get pending address
const pending = await client.getPendingAddress();

// Submit for validation
await client.submitAddressForValidation({
  street: '123 Main St',
  city: 'New York',
  state: 'NY',
  postalCode: '10001',
  country: 'USA',
});

// Approve pending address
const approved = await client.approvePendingAddress();
```

### Device Management

#### registerDevice(data: RegisterDeviceDto): Promise<DeviceResponse>

Register a new device.

```typescript
const device = await client.registerDevice({
  deviceId: 'unique-device-id',
  deviceType: 'ios',
  deviceModel: 'iPhone 14',
  osVersion: '16.0',
  appVersion: '1.0.0',
  pushToken: 'fcm-token',
});
```

#### getUserDevices(): Promise<DeviceResponse[]>

Get all user devices.

```typescript
const devices = await client.getUserDevices();
```

#### getDevice(deviceId: string): Promise<DeviceResponse>

Get specific device.

```typescript
const device = await client.getDevice('device-id');
```

#### updateDevice(deviceId: string, data: UpdateDeviceDto): Promise<DeviceResponse>

Update device information.

```typescript
const updated = await client.updateDevice('device-id', {
  appVersion: '1.1.0',
  osVersion: '16.1',
});
```

#### deleteDevice(deviceId: string): Promise<{ message: string }>

Delete a device.

```typescript
await client.deleteDevice('device-id');
```

#### deactivateDevice(deviceId: string): Promise<DeviceResponse>

Deactivate a device.

```typescript
await client.deactivateDevice('device-id');
```

#### updateDevicePushToken(deviceId: string, pushToken: string): Promise<DeviceResponse>

Update device push notification token.

```typescript
await client.updateDevicePushToken('device-id', 'new-fcm-token');
```

### Security Questions

#### getAvailableSecurityQuestions(): Promise<SecurityQuestionResponse[]>

Get list of available security questions.

```typescript
const questions = await client.getAvailableSecurityQuestions();
```

#### getUserSecurityQuestions(): Promise<any[]>

Get user's configured security questions.

```typescript
const userQuestions = await client.getUserSecurityQuestions();
```

#### setSecurityQuestion(data: SetSecurityQuestionDto): Promise<any>

Set a security question.

```typescript
await client.setSecurityQuestion({
  questionId: 'question-uuid',
  answer: 'My Answer',
});
```

#### verifySecurityAnswer(data: VerifySecurityAnswerDto): Promise<{ valid: boolean }>

Verify a security answer.

```typescript
const { valid } = await client.verifySecurityAnswer({
  questionId: 'question-uuid',
  answer: 'My Answer',
});
```

#### deleteSecurityQuestion(questionId: string): Promise<{ message: string }>

Delete a security question.

```typescript
await client.deleteSecurityQuestion('question-uuid');
```

### Verification

#### sendVerification(data: SendVerificationDto): Promise<any>

Send verification code via email or phone.

```typescript
// Send email verification
await client.sendVerification({
  type: 'email',
});

// Send phone verification
await client.sendVerification({
  type: 'phone',
  target: '+1234567890', // optional
});
```

#### verifyCode(data: VerifyCodeDto): Promise<{ verified: boolean }>

Verify a code.

```typescript
const { verified } = await client.verifyCode({
  type: 'email',
  code: '123456',
});
```

#### getVerificationStatus(): Promise<VerificationStatusResponse>

Get user's verification status.

```typescript
const status = await client.getVerificationStatus();
console.log('Email verified:', status.emailVerified);
console.log('Phone verified:', status.phoneVerified);
```

### Password Reset

#### requestPasswordReset(email: string): Promise<{ sent: boolean; expiresAt: Date }>

Request a password reset.

```typescript
const response = await client.requestPasswordReset('user@example.com');
console.log('Reset email sent:', response.sent);
console.log('Expires at:', response.expiresAt);
```

#### resetPassword(data: ResetPasswordDto): Promise<{ message: string }>

Reset password with token.

```typescript
await client.resetPassword({
  token: 'reset-token-from-email',
  newPassword: 'NewSecurePassword123!',
});
```

### Disclosures

#### getCurrentDisclosures(): Promise<DisclosureResponse[]>

Get all current disclosures.

```typescript
const disclosures = await client.getCurrentDisclosures();
```

#### getPendingDisclosures(): Promise<DisclosureResponse[]>

Get disclosures pending user acceptance.

```typescript
const pending = await client.getPendingDisclosures();
```

#### getUserAcceptedDisclosures(): Promise<any[]>

Get user's accepted disclosures.

```typescript
const accepted = await client.getUserAcceptedDisclosures();
```

#### getDisclosureById(id: string): Promise<DisclosureResponse>

Get specific disclosure by ID.

```typescript
const disclosure = await client.getDisclosureById('disclosure-uuid');
```

#### acceptDisclosure(data: AcceptDisclosureDto): Promise<any>

Accept a disclosure.

```typescript
await client.acceptDisclosure({
  disclosureId: 'disclosure-uuid',
  version: '1.0',
});
```

## Error Handling

The SDK uses Axios for HTTP requests. All errors are Axios errors with response data.

```typescript
try {
  await client.login({
    email: 'user@example.com',
    password: 'wrong-password',
  });
} catch (error) {
  if (error.response) {
    // Server responded with error
    console.error('Status:', error.response.status);
    console.error('Message:', error.response.data.message);
  } else if (error.request) {
    // Request made but no response
    console.error('No response received');
  } else {
    // Error setting up request
    console.error('Error:', error.message);
  }
}
```

### Common HTTP Status Codes

- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized (token cleared automatically)
- `404` - Not Found
- `409` - Conflict (e.g., user already exists)
- `500` - Internal Server Error

## Examples

See the [examples](./examples) directory for complete working examples:

- [Basic Authentication](./examples/auth.ts)
- [User Profile Management](./examples/user-profile.ts)
- [Address Management](./examples/address.ts)
- [Device Management](./examples/devices.ts)
- [Password Reset Flow](./examples/password-reset.ts)

## TypeScript Support

This SDK is written in TypeScript and includes type definitions. You get full IntelliSense and type checking out of the box.

```typescript
import { AccountServiceClient, UserResponse, LoginResponse } from '@mybambu/account-service-sdk';

const client = new AccountServiceClient({ baseURL: 'http://localhost:3000' });

// TypeScript knows the shape of the response
const loginResponse: LoginResponse = await client.login({
  email: 'user@example.com',
  password: 'password',
});

// Type-safe access to properties
console.log(loginResponse.access_token);
console.log(loginResponse.user.email);
```

## License

MIT