npm package: @netdiag/client
Description: Official JS/TS client for NetDiag API - network diagnostics (HTTP, DNS, TLS, ping) as a service. Run distributed health checks from multiple regions worldwide.
Author: XAKPC Dev Labs
Latest version: 1.1.0

# @netdiag/client

Official JavaScript/TypeScript client for [NetDiag API](https://netdiag.dev) - network diagnostics (HTTP, DNS, TLS, ping) as a service. Run distributed health checks from multiple regions worldwide.

## Installation

```bash
npm install @netdiag/client
```

## Quick Start

```typescript
import { NetDiagClient } from '@netdiag/client';

const client = new NetDiagClient();

// Run a full diagnostic check
const result = await client.check('example.com');

console.log(`Status: ${result.status}`);        // 'Healthy', 'Warning', or 'Unhealthy'
console.log(`Quorum: ${result.quorum.required}/${result.quorum.total} (met: ${result.quorum.met})`);
console.log(`Duration: ${result.durationMs}ms`);

// Check for cross-region observations
for (const obs of result.observations) {
  console.log(`  [${obs.severity}] ${obs.code}: ${obs.message}`);
}

// Inspect per-region results
for (const region of result.regions) {
  console.log(`${region.region}: ${region.status}`);
  if (region.ping) console.log(`  Ping: ${region.ping.avgRttMs}ms (${region.ping.received}/${region.ping.sent})`);
  if (region.dns) console.log(`  DNS: ${region.dns.queryTimeMs}ms`);
  if (region.http) console.log(`  HTTP: ${region.http.statusCode} in ${region.http.totalTimeMs}ms`);
}
```

## API Reference

### Constructor

```typescript
// Default configuration
const client = new NetDiagClient();

// With API key (increases rate limits)
const client = new NetDiagClient({ apiKey: 'your-api-key' });

// Full options
const client = new NetDiagClient({
  baseUrl: 'https://api.netdiag.dev',  // API base URL
  apiKey: 'your-api-key',              // API key for authentication
  timeout: 30000,                       // Request timeout in ms
  fetch: customFetch,                   // Custom fetch implementation
});
```

### Methods

#### `check(host: string | CheckRequest): Promise<CheckResponse>`

Run network diagnostics against a host.

```typescript
// Simple usage
const result = await client.check('example.com');

// URLs are accepted (host is extracted automatically)
const result = await client.check('https://example.com/path');

// With options
const result = await client.check({
  host: 'example.com',
  port: 443,
  regions: 'us-west,eu-central',
  pingCount: 10,
  pingTimeout: 5,
  dns: '8.8.8.8',
});
```

#### `checkPrometheus(host: string | CheckRequest): Promise<string>`

Run diagnostics and get results in Prometheus exposition format.

```typescript
const metrics = await client.checkPrometheus('example.com');
// Returns:
// netdiag_check_success{host="example.com",region="us-west"} 1
// netdiag_ping_rtt_ms{host="example.com",region="us-west"} 15.2
// netdiag_http_time_ms{host="example.com",region="us-west"} 120.0
// ...
```

#### `isHealthy(host: string): Promise<boolean>`

Quick check if a host is healthy.

```typescript
if (await client.isHealthy('example.com')) {
  console.log('All systems operational');
}
```

#### `getStatus(host: string): Promise<Status>`

Get the health status of a host.

```typescript
const status = await client.getStatus('example.com');
// 'Healthy', 'Warning', or 'Unhealthy'
```

## Error Handling

```typescript
import {
  NetDiagClient,
  NetDiagApiError,
  NetDiagRateLimitError
} from '@netdiag/client';

try {
  const result = await client.check('example.com');
} catch (error) {
  if (error instanceof NetDiagRateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfterSeconds}s`);
  } else if (error instanceof NetDiagApiError) {
    console.log(`API error: ${error.statusCode} - ${error.message}`);
  }
}
```

## TypeScript

Full TypeScript support with exported types:

```typescript
import type {
  CheckRequest,
  CheckResponse,
  LocationResult,
  QuorumInfo,
  Observation,
  PingResult,
  DnsResult,
  TlsResult,
  HttpResult,
  Status
} from '@netdiag/client';
```

## Response Types

### CheckResponse

| Property | Type | Description |
|----------|------|-------------|
| `host` | string | Target hostname |
| `status` | Status | Overall health status |
| `quorum` | QuorumInfo | Quorum details (required, total, met) |
| `durationMs` | number | Total check duration |
| `observations` | Observation[] | Cross-region analysis findings |
| `regions` | LocationResult[] | Per-region results |

### Observation Codes

| Code | Severity | Description |
|------|----------|-------------|
| `DNS_ANSWERS_MISMATCH` | warning | DNS differs across regions |
| `CERT_EXPIRING_SOON` | warning | Certificate expires < 30 days |
| `CERT_WEAK_PROTOCOL` | warning | TLS 1.0 or 1.1 detected |
| `REGIONAL_FAILURE` | error | Probe failed in some regions |

## Requirements

- Node.js 18+ (uses native fetch)
- For older Node.js versions, provide a fetch polyfill via `options.fetch`

## Documentation

Full documentation available at [netdiag.dev/docs/js](https://netdiag.dev/docs/js)

## License

MIT