npm package: @khaleejiapi/sdk
Description: Official TypeScript/JavaScript SDK for KhaleejiAPI - Middle East API Platform
Author: KhaleejiAPI
Latest version: 1.2.0

# @khaleejiapi/sdk

Official TypeScript/JavaScript SDK for [KhaleejiAPI](https://khaleejiapi.dev) — the Middle East API Platform.

[![npm version](https://img.shields.io/npm/v/@khaleejiapi/sdk)](https://www.npmjs.com/package/@khaleejiapi/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

- **Zero dependencies** — uses native `fetch`
- **Works everywhere** — Node.js 18+, Deno, Bun, browsers
- **Fully typed** — first-class TypeScript support with complete type definitions
- **Automatic retries** — exponential backoff on 429 and 5xx responses
- **Rate limit aware** — parsed rate limit headers available after every request

## Installation

```bash
# npm
npm install @khaleejiapi/sdk

# yarn
yarn add @khaleejiapi/sdk

# pnpm
pnpm add @khaleejiapi/sdk

# bun
bun add @khaleejiapi/sdk
```

## Quick Start

```typescript
import { KhaleejiAPI } from '@khaleejiapi/sdk';

const client = new KhaleejiAPI({
  apiKey: 'kapi_live_...', // Get yours at https://khaleejiapi.dev/dashboard/api-keys
});

// Validate an email
const email = await client.validation.validateEmail({ email: 'user@example.com' });
console.log(email.valid, email.checks);

// Look up an IP
const ip = await client.geo.lookupIp({ ip: '8.8.8.8' });
console.log(ip.country, ip.city);

// Get exchange rates
const rates = await client.finance.getExchangeRates({ base: 'AED', symbols: 'USD,EUR,GBP' });
console.log(rates.rates);
```

## Configuration

```typescript
const client = new KhaleejiAPI({
  apiKey: 'kapi_live_...',        // Required
  baseUrl: 'https://khaleejiapi.dev/api', // Default
  timeout: 30000,                  // Request timeout in ms (default: 30s)
  retries: 2,                      // Retry count on 429/5xx (default: 2)
  retryDelay: 1000,                // Initial retry delay in ms (default: 1s)
});
```

## API Reference

### Validation

#### `validateEmail`

Validate an email address with syntax, domain, MX record, and disposable checks.

```typescript
const result = await client.validation.validateEmail({ email: 'user@example.com' });
// {
//   valid: true,
//   email: 'user@example.com',
//   checks: { format: true, mx: true, disposable: false, role: false },
//   domain: 'example.com',
//   mx_records: ['mx.example.com']
// }
```

#### `validatePhone`

Validate an international phone number with carrier and line type detection.

```typescript
const result = await client.validation.validatePhone({
  phone: '+971501234567',
  country: 'AE',
});
// { valid: true, formatted: '+971 50 123 4567', carrier: 'Etisalat', line_type: 'mobile' }
```

#### `validateVat`

Validate a VAT/TRN number and look up company information.

```typescript
const result = await client.validation.validateVat({
  vat_number: '100123456700003',
  country_code: 'AE',
});
// { valid: true, company_name: 'Example Trading LLC', ... }
```

#### `validateIban`

Validate an IBAN and retrieve bank and branch information.

```typescript
const result = await client.validation.validateIban({
  iban: 'AE070331234567890123456',
});
// { valid: true, bank_name: 'ADCB', country_code: 'AE', ... }
```

#### `validateEmiratesId`

Validate a UAE Emirates ID number.

```typescript
const result = await client.validation.validateEmiratesId({
  id: '784-1990-1234567-1',
});
// { valid: true, formatted: '784-1990-1234567-1', check_digit: '1' }
```

---

### Geolocation

#### `lookupIp`

Get geolocation data for an IP address. Omit `ip` to use the caller's IP.

```typescript
const result = await client.geo.lookupIp({ ip: '8.8.8.8' });
// { country: 'United States', city: 'Mountain View', isp: 'Google', ... }
```

#### `getTimezone`

Get timezone information by location name or coordinates.

```typescript
const result = await client.geo.getTimezone({ location: 'Dubai' });
// { timezone: 'Asia/Dubai', utc_offset: '+04:00', current_time: '...' }
```

#### `geocode`

Convert addresses to coordinates or coordinates to addresses.

```typescript
// Forward geocoding
const result = await client.geo.geocode({ address: 'Burj Khalifa, Dubai' });
// { latitude: 25.1972, longitude: 55.2744, formatted_address: '...' }

// Reverse geocoding
const result2 = await client.geo.geocode({ lat: 25.1972, lon: 55.2744 });
```

#### `getWeather`

Current weather and forecast for a city or coordinates.

```typescript
const result = await client.geo.getWeather({ city: 'Dubai' });
// { temperature: 35, humidity: 60, conditions: 'Clear', forecast: [...] }
```

---

### Finance

#### `getExchangeRates`

Real-time exchange rates for 170+ currencies. Defaults to AED base.

```typescript
const result = await client.finance.getExchangeRates({
  base: 'AED',
  symbols: 'USD,EUR,GBP,SAR',
});
// { base: 'AED', rates: { USD: 0.2723, EUR: 0.2514, ... } }
```

#### `calculateVat`

Calculate VAT for amounts with automatic rate detection.

```typescript
const result = await client.finance.calculateVat({
  amount: 100,
  country_code: 'AE',
});
// { net_amount: 100, vat_amount: 5, gross_amount: 105, vat_rate: 5 }

// Inclusive VAT (extract VAT from total)
const result2 = await client.finance.calculateVat({
  amount: 105,
  country_code: 'AE',
  inclusive: true,
});
// { net_amount: 100, vat_amount: 5, gross_amount: 105, vat_rate: 5 }
```

#### `getHolidays`

Public holidays for UAE and GCC countries with Islamic calendar support.

```typescript
const result = await client.finance.getHolidays({ country: 'AE', year: 2026 });
// { holidays: [{ date: '2026-01-01', name: "New Year's Day", type: 'public' }, ...] }
```

---

### Documents

#### `processImage`

Resize, crop, format-convert, and optimize images. Returns an `ArrayBuffer`.

```typescript
import { readFileSync, writeFileSync } from 'node:fs';

const imageBuffer = readFileSync('photo.jpg');
const result = await client.documents.processImage({
  image: imageBuffer,
  operations: {
    resize: { width: 800, height: 600, fit: 'cover' },
    format: 'webp',
    quality: 80,
  },
});
writeFileSync('photo-optimized.webp', Buffer.from(result));
```

#### `generatePdf`

Generate PDFs from HTML or URLs. Returns an `ArrayBuffer`.

```typescript
import { writeFileSync } from 'node:fs';

const pdf = await client.documents.generatePdf({
  html: '<h1>Invoice #1234</h1><p>Total: AED 500.00</p>',
  options: {
    format: 'A4',
    margin: { top: '20mm', bottom: '20mm' },
  },
});
writeFileSync('invoice.pdf', Buffer.from(pdf));
```

---

### Communication

#### `translate`

Translate text between languages. Arabic and regional languages are fully supported.

```typescript
const result = await client.communication.translate({
  text: 'Hello, how are you?',
  target: 'ar',
});
// { translated_text: 'مرحباً، كيف حالك؟', confidence: 0.98 }
```

#### `shortenUrl`

Shorten URLs with optional custom aliases.

```typescript
const result = await client.communication.shortenUrl({
  url: 'https://example.com/very/long/path',
  custom_alias: 'my-link',
});
// { short_url: 'https://klj.to/my-link', alias: 'my-link' }
```

---

### Utility

#### `generateQr`

Generate QR code images. Returns an `ArrayBuffer`.

```typescript
import { writeFileSync } from 'node:fs';

const qr = await client.utility.generateQr({
  data: 'https://khaleejiapi.dev',
  size: 512,
  format: 'png',
});
writeFileSync('qr.png', Buffer.from(qr));
```

#### `checkFraud`

Detect fraud signals across email, IP, phone, and name.

```typescript
const result = await client.utility.checkFraud({
  email: 'suspicious@tempmail.com',
  ip: '185.234.218.0',
});
// {
//   risk_score: 85,
//   risk_level: 'high',
//   signals: [{ type: 'disposable_email', description: '...', severity: 'high' }]
// }
```

---

## Error Handling

All errors extend `KhaleejiAPIError` which includes `code`, `statusCode`, and `message`:

```typescript
import { KhaleejiAPI, KhaleejiAPIError, RateLimitError, AuthenticationError } from '@khaleejiapi/sdk';

const client = new KhaleejiAPI({ apiKey: 'kapi_live_...' });

try {
  await client.validation.validateEmail({ email: 'user@example.com' });
} catch (err) {
  if (err instanceof RateLimitError) {
    console.log(`Rate limited. Retry after ${err.retryAfter}s`);
  } else if (err instanceof AuthenticationError) {
    console.log('Invalid API key');
  } else if (err instanceof KhaleejiAPIError) {
    console.log(`API error: ${err.code} — ${err.message} (HTTP ${err.statusCode})`);
  }
}
```

### Error Classes

| Class | Status Code | Description |
|-------|-------------|-------------|
| `AuthenticationError` | 401, 403 | Invalid or missing API key |
| `ValidationError` | 400 | Invalid request parameters |
| `NotFoundError` | 404 | Endpoint or resource not found |
| `RateLimitError` | 429 | Rate limit exceeded |
| `InternalError` | 5xx | Server error |
| `ConnectionError` | — | Network or timeout error |
| `KhaleejiAPIError` | any | Base class for all API errors |

## Rate Limits

Rate limit information is available after every request:

```typescript
await client.validation.validateEmail({ email: 'user@example.com' });

console.log(client.rateLimit);
// { limit: 1000, remaining: 999, reset: 1700000000 }
```

The SDK automatically retries on `429` responses using the `Retry-After` header value.

## TypeScript Support

The SDK is written in TypeScript and ships with complete type definitions. All request parameters and response types are fully typed:

```typescript
import type {
  ValidateEmailParams,
  ValidateEmailData,
  LookupIpData,
  GetExchangeRatesData,
} from '@khaleejiapi/sdk';
```

## Requirements

- **Node.js** 18.0.0 or later
- **Deno** 1.28 or later
- **Bun** 0.5 or later
- Modern browsers with `fetch` support

## Contributing

1. Clone the repository
2. Install dependencies: `pnpm install`
3. Run tests: `pnpm test`
4. Build: `pnpm build`

## License

[MIT](LICENSE)

---

Built with ❤️ for the Middle East developer community by [KhaleejiAPI](https://khaleejiapi.dev).