npm package: @ldauth/client
Description: Browser client library for ldauth permission checking
Author: Bart Riepe
Latest version: 0.10.1

# @ldauth/client

Framework-agnostic browser client library for ldauth permission checking. This library provides core functionality for managing permissions and authentication in browser environments.

## Features

- 🎯 Framework agnostic - works with React, Vue, Angular, or vanilla JS
- 🔐 Permission checking and caching
- ⚡ Automatic token management
- 🎨 Event-driven architecture
- 💾 Built-in caching with TTL
- 🔄 Auto-refresh capabilities
- 📦 TypeScript support

## Installation

```bash
npm install @ldauth/client
# or
yarn add @ldauth/client
# or
pnpm add @ldauth/client
```

## Quick Start

### Basic Usage

```javascript
import { LDAuthClient } from '@ldauth/client';

// Initialize the client
const ldauth = new LDAuthClient({
  apiUrl: 'https://auth.example.com',
  clientId: 'my-app',
  schema: 'default',
  cacheDuration: 5 * 60 * 1000, // 5 minutes
  autoFetch: true
});

// Set the access token
await ldauth.setToken(accessToken);

// Check a permission
const canRead = await ldauth.checkPermission({
  resource: 'users',
  action: 'read'
});

// Get all permissions
const permissions = await ldauth.fetchPermissions();

// Check cached permissions
if (ldauth.hasPermission('users', 'write')) {
  // User can write users
}

// Get user info
const userInfo = await ldauth.fetchUserInfo();
```

### Event Handling

```javascript
// Listen for permission updates
const unsubscribe = ldauth.on('permissions:fetched', (permissions) => {
  console.log('Permissions updated:', permissions);
});

// Listen for errors
ldauth.on('permissions:error', (error) => {
  console.error('Permission error:', error);
});

// Listen for token changes
ldauth.on('token:changed', (tokenInfo) => {
  console.log('Token changed:', tokenInfo);
});

// Clean up
unsubscribe();
```

### With Vanilla JavaScript

```html
<!DOCTYPE html>
<html>
<head>
  <script type="module">
    import { LDAuthClient } from '@ldauth/client';
    
    const ldauth = new LDAuthClient({
      apiUrl: 'https://auth.example.com',
      clientId: 'my-app'
    });
    
    // After user logs in
    async function handleLogin(token) {
      await ldauth.setToken(token);
      
      // Check permissions
      const canViewDashboard = await ldauth.checkPermission({
        resource: 'dashboard',
        action: 'view'
      });
      
      if (canViewDashboard) {
        showDashboard();
      }
    }
    
    // Update UI based on permissions
    function updateUI() {
      const permissions = ldauth.getPermissions();
      
      if (permissions) {
        // Show/hide UI elements based on permissions
        document.getElementById('admin-panel').style.display = 
          ldauth.hasPermission('admin', 'access') ? 'block' : 'none';
      }
    }
    
    // Listen for permission updates
    ldauth.on('permissions:fetched', updateUI);
  </script>
</head>
</html>
```

### With Vue.js

```javascript
// composables/useLDAuth.js
import { ref, computed } from 'vue';
import { LDAuthClient } from '@ldauth/client';

const ldauth = new LDAuthClient({
  apiUrl: import.meta.env.VITE_AUTH_API_URL,
  clientId: import.meta.env.VITE_CLIENT_ID
});

const permissions = ref(null);
const loading = ref(false);

ldauth.on('permissions:fetched', (perms) => {
  permissions.value = perms;
  loading.value = false;
});

export function useLDAuth() {
  const setToken = async (token) => {
    loading.value = true;
    await ldauth.setToken(token);
  };
  
  const hasPermission = (resource, action) => {
    return ldauth.hasPermission(resource, action);
  };
  
  return {
    ldauth,
    permissions: computed(() => permissions.value),
    loading: computed(() => loading.value),
    setToken,
    hasPermission
  };
}
```

## Configuration

```typescript
interface LDAuthClientConfig {
  // Required
  apiUrl: string;        // Your ldauth API URL
  clientId: string;      // OAuth2 client ID
  
  // Optional
  profile?: string;      // Permission profile (default: '__default')
  schema?: string;       // Permission schema
  cacheDuration?: number; // Cache TTL in ms (default: 300000)
  autoFetch?: boolean;   // Auto-fetch permissions (default: true)
  onError?: (error: Error) => void; // Error callback
  headers?: Record<string, string>; // Custom headers
}
```

## API Reference

### Methods

#### `setToken(token: string | null): Promise<void>`
Set or clear the access token. If autoFetch is enabled, permissions will be fetched automatically.

#### `fetchPermissions(): Promise<PermissionEvaluation>`
Fetch all permissions for the current user.

#### `checkPermission(check: PermissionCheck): Promise<boolean>`
Check a specific permission against the API.

#### `hasPermission(resource: string, action: string, profile?: string): boolean`
Check a permission from cached data (synchronous).

#### `hasAnyPermission(checks: Array<{resource, action, profile?}>): boolean`
Check if user has any of the specified permissions.

#### `hasAllPermissions(checks: Array<{resource, action, profile?}>): boolean`
Check if user has all of the specified permissions.

#### `hasRole(role: string): boolean`
Check if user has a specific role.

#### `getResourceActions(resource: string): string[]`
Get all allowed actions for a resource.

#### `getAccessibleResources(): string[]`
Get all resources the user has access to.

#### `fetchUserInfo(): Promise<UserInfo>`
Fetch user information from the API.

#### `clearCache(): void`
Clear all cached data.

#### `getPermissions(): PermissionEvaluation | null`
Get current cached permissions.

#### `destroy(): void`
Clean up the client and remove all listeners.

### Events

- `permissions:fetched` - Emitted when permissions are successfully fetched
- `permissions:error` - Emitted when permission fetch fails
- `permissions:cleared` - Emitted when permissions are cleared
- `token:changed` - Emitted when token changes
- `cache:expired` - Emitted when cache is cleared

## Framework Integrations

This is the core library. For framework-specific integrations, see:

- [@ldauth/react](../react-permissions) - React hooks and components
- [@ldauth/vue](../vue-permissions) - Vue composables (coming soon)
- [@ldauth/angular](../angular-permissions) - Angular services (coming soon)

## License

MIT