npm package: @io.complyance/unify-sdk
Description: TypeScript SDK for the Complyance Unified e-invoicing platform
Author: Complyance
Latest version: 3.0.0

# Complyance TypeScript SDK

TypeScript SDK for the Complyance Unified e-invoicing platform. This SDK provides a native TypeScript interface for integrating e-invoicing compliance into your Node.js applications.

## Installation

```bash
npm install @complyance/sdk
# or
yarn add @complyance/sdk
```

## Quick Start

```typescript
import {
  ComplyanceSDK,
  DocumentType,
  Environment,
  Mode,
  Operation,
  Purpose,
  SDKConfigBuilder,
} from '@complyance/sdk';

// Configure the SDK
const config = new SDKConfigBuilder()
  .apiKey('your-api-key')
  .environment(Environment.SANDBOX)
  .useRetryPreset('default')
  .build();

ComplyanceSDK.configure(config);

// Use the SDK
async function submitInvoice() {
  try {
    const response = await ComplyanceSDK.pushToUnify({
      source: {
        id: 'my-erp',
        type: 'first_party',
        name: 'My ERP System',
      },
      documentType: DocumentType.TAX_INVOICE,
      country: 'SA',
      operation: Operation.SINGLE,
      mode: Mode.DOCUMENTS,
      purpose: Purpose.INVOICING,
      payload: {
        // Your invoice data here
        invoice_number: 'INV-001',
        issue_date: '2023-09-15',
        // ...
      },
    });

    console.log('Response:', response);
  } catch (error) {
    console.error('Error:', error);
  }
}

submitInvoice();
```

## Configuration

### Using the Builder Pattern

```typescript
import { Environment, SDKConfigBuilder } from '@complyance/sdk';

const config = new SDKConfigBuilder()
  .apiKey('your-api-key')
  .environment(Environment.SANDBOX)
  .addSource({
    id: 'my-erp',
    type: 'first_party',
    name: 'My ERP System',
  })
  .useRetryPreset('aggressive')
  .timeout(60000)
  .logLevel('debug')
  .build();
```

### Using Environment Variables

```typescript
import { SDKConfig } from '@complyance/sdk';

// Set environment variables
process.env.COMPLYANCE_API_KEY = 'your-api-key';
process.env.COMPLYANCE_ENVIRONMENT = 'sandbox';
process.env.COMPLYANCE_RETRY_PRESET = 'default';
process.env.COMPLYANCE_TIMEOUT = '30000';
process.env.COMPLYANCE_LOG_LEVEL = 'info';

const config = SDKConfig.fromEnv();
```

## Express.js Integration

The SDK provides built-in middleware for Express.js applications:

```typescript
import {
  ComplyanceSDK,
  Environment,
  SDKConfigBuilder,
  complyanceMiddleware,
} from '@complyance/sdk';
import express from 'express';

const app = express();
app.use(express.json());

// Configure the SDK
ComplyanceSDK.configure(
  new SDKConfigBuilder().apiKey('your-api-key').environment(Environment.SANDBOX).build()
);

// Use the middleware
app.post(
  '/api/documents',
  complyanceMiddleware({
    requestExtractor: (req) => req.body,
  })
);

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

### Custom Response Handling

```typescript
app.post(
  '/api/documents',
  complyanceMiddleware({
    requestExtractor: (req) => req.body,
    responseHandler: (res, unifyResponse) => {
      res.status(200).json({
        success: true,
        documentId: unifyResponse.data?.document?.documentId,
        message: 'Document processed successfully',
      });
    },
  })
);
```

### Validation Middleware

```typescript
app.post(
  '/api/validate',
  complyanceValidationMiddleware({
    requestExtractor: (req) => req.body,
  }),
  (req, res) => {
    // This handler will only be called if validation passes
    res.status(200).json({
      valid: true,
      message: 'Request validation passed',
    });
  }
);
```

For more details, see the [Express.js Middleware Documentation](./docs/express-middleware.md).

## Error Handling

```typescript
import { APIError, ComplyanceSDK, NetworkError, ValidationError } from '@complyance/sdk';

try {
  const response = await ComplyanceSDK.pushToUnify(request);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(`Validation error: ${error.message}`);
    console.error(`Suggestion: ${error.suggestion}`);
  } else if (error instanceof NetworkError) {
    console.error(`Network error: ${error.message}`);
    // Implement retry logic or fallback
  } else if (error instanceof APIError) {
    console.error(`API error (${error.statusCode}): ${error.message}`);
    console.error(`Error code: ${error.code}`);
  } else {
    console.error(`Unexpected error: ${error.message}`);
  }
}
```

## Retry Configuration

```typescript
import { SDKConfigBuilder, RetryPresets } from '@complyance/sdk';

// Use a preset
const config = new SDKConfigBuilder().apiKey('your-api-key').useRetryPreset('aggressive').build();

// Or customize retry behavior
const config = new SDKConfigBuilder()
  .apiKey('your-api-key')
  .retryConfig({
    maxAttempts: 5,
    baseDelay: 500,
    maxDelay: 30000,
    backoffMultiplier: 2,
    jitterFactor: 0.2,
    circuitBreakerEnabled: true,
    failureThreshold: 5,
    circuitBreakerTimeout: 60000,
    retryableHttpCodes: [408, 429, 500, 502, 503, 504],
  })
  .build();
```

## License

Proprietary - Copyright © Complyance