npm package: @navios-sdk/core
Description: Pure TypeScript maps SDK — routing, geocoding, and autocomplete with zero dependencies
Author: naviOS
Latest version: 1.1.0

# @navios-sdk/core

Pure TypeScript maps SDK — routing, geocoding, and autocomplete with zero dependencies.

Built on [OpenStreetMap](https://openstreetmap.org), [Valhalla](https://github.com/valhalla/valhalla), and [Nominatim](https://nominatim.org). No API keys required.

[![npm version](https://img.shields.io/npm/v/@navios-sdk/core.svg)](https://www.npmjs.com/package/@navios-sdk/core)
[![license](https://img.shields.io/npm/l/@navios-sdk/core.svg)](https://opensource.org/licenses/MIT)

> **Need interactive maps?** Use [`@navios-sdk/web`](https://www.npmjs.com/package/@navios-sdk/web) instead — it includes everything in `@navios-sdk/core` plus MapLibre GL maps, markers, route rendering, and offline tile support.

## Installation

```bash
npm install @navios-sdk/core
```

## Quick Start

```typescript
import { NaviosCore } from '@navios-sdk/core'

const nav = new NaviosCore()

// Geocode an address
const result = await nav.geocode({ address: 'Eiffel Tower, Paris' })
console.log(result.lat, result.lng, result.displayName)

// Reverse geocode
const place = await nav.reverseGeocode({ lat: 48.8584, lng: 2.2945 })
console.log(place.displayName) // 'Eiffel Tower, Avenue Anatole France, ...'

// Autocomplete search
const results = await nav.autocomplete({ query: 'Berlin Brandenb', limit: 5 })

// Turn-by-turn routing
const route = await nav.route({
  origin: { lat: 48.8566, lng: 2.3522 },
  destination: { lat: 48.8606, lng: 2.3376 },
  mode: 'walk'
})
console.log(route.distanceText)  // "1.2 km"
console.log(route.durationText)  // "14 mins"
console.log(route.steps)         // Turn-by-turn instructions
```

## Features

- **Geocoding** — forward and reverse, powered by Nominatim
- **Autocomplete** — real-time search suggestions via Photon
- **Routing** — turn-by-turn directions for driving, walking, and cycling via Valhalla
- **Retry with backoff** — exponential backoff on transient failures (network, 429, 5xx)
- **URL fallback** — provide multiple service URLs; each is tried before the next
- **LRU caching** — in-memory cache per method with configurable size and TTL
- **Persistent storage** — plug in any `StorageAdapter` for cross-session caching
- **Offline queue** — failed requests are queued and replayed when connectivity returns
- **Typed errors** — structured `NaviosError` with error codes, HTTP status, and service info
- **Tree-shakeable** — multiple entry points for minimal bundle size
- **Zero dependencies** — pure TypeScript, runs anywhere (Node.js, Deno, Bun, edge runtimes)

## Configuration

Works out of the box with zero configuration. Optionally customize service URLs, retry behavior, caching, and offline persistence:

```typescript
const nav = new NaviosCore({
  // Service URLs — string or string[] for fallback
  valhallaUrl: ['https://primary.example.com', 'https://backup.example.com'],
  nominatimUrl: 'https://your-nominatim.example.com',
  photonUrl: 'https://your-photon.example.com',

  // Retry — exponential backoff on transient failures
  retry: { maxRetries: 3, baseDelay: 300, maxDelay: 5000 },

  // In-memory LRU cache
  cache: { enabled: true, maxSize: 100, ttl: 300000 },

  // Offline persistence
  offline: {
    enabled: true,
    storageTtl: 86400000,       // 24 hours
    staleWhileOffline: true,
    queueRequests: true
  }
})
```

| Option | Type | Description |
|---|---|---|
| `valhallaUrl` | `string \| string[]` | Valhalla routing engine URL(s). Arrays enable automatic fallback |
| `nominatimUrl` | `string \| string[]` | Nominatim geocoding service URL(s) |
| `photonUrl` | `string \| string[]` | Photon search/autocomplete URL(s) |
| `retry` | `RetryConfig` | Retry behavior: `maxRetries`, `baseDelay` (ms), `maxDelay` (ms) |
| `cache` | `CacheConfig` | In-memory LRU cache: `enabled`, `maxSize`, `ttl` (ms) |
| `offline` | `OfflineConfig` | Persistent storage and offline queueing configuration |

## API Reference

### `geocode({ address })`

Convert an address to coordinates. Returns `Promise<GeocodeResult>` with `lat`, `lng`, and `displayName`.

### `reverseGeocode({ lat, lng })`

Convert coordinates to an address. Returns `Promise<GeocodeResult>`.

### `autocomplete({ query, limit? })`

Real-time search suggestions. Returns `Promise<AutocompleteResult[]>`.

### `route({ origin, destination, mode? })`

Calculate turn-by-turn directions. Supports `'drive'`, `'walk'`, and `'bicycle'`. Returns `Promise<RouteResult>` with `distanceText`, `durationText`, `polyline`, and `steps`.

### `clearCache()`

Clears all in-memory caches and persistent storage.

## Error Handling

All methods throw typed `NaviosError` instances:

```typescript
import { NaviosError, NaviosErrorCode } from '@navios-sdk/core'

try {
  const result = await nav.geocode({ address: 'xyznonexistent' })
} catch (err) {
  if (err instanceof NaviosError) {
    console.log(err.code)      // 'NOT_FOUND'
    console.log(err.service)   // 'nominatim'
    console.log(err.retryable) // false
    console.log(err.status)    // 404
  }
}
```

**Error codes:** `NETWORK_ERROR` (retryable), `RATE_LIMITED` (retryable), `SERVICE_ERROR` (retryable), `NOT_FOUND`, `INVALID_INPUT`, `PARSE_ERROR`, `OFFLINE` (request queued).

## Custom Storage Adapter

Implement the `StorageAdapter` interface for any storage backend:

```typescript
import type { StorageAdapter } from '@navios-sdk/core'

class LocalStorageAdapter implements StorageAdapter {
  async get(key: string) { return localStorage.getItem(key) }
  async set(key: string, value: string) { localStorage.setItem(key, value) }
  async delete(key: string) { localStorage.removeItem(key) }
  async clear() { localStorage.clear() }
}
```

## Tree-Shakeable Imports

Import only what you need:

```typescript
import { getRoute } from '@navios-sdk/core/route'
import { geocode } from '@navios-sdk/core/geocode'
import { autocomplete } from '@navios-sdk/core/autocomplete'
import { NaviosError } from '@navios-sdk/core/errors'
import { LRUCache } from '@navios-sdk/core/cache'
import { RequestQueue } from '@navios-sdk/core/queue'
```

## Documentation

Full documentation with interactive examples: [openai4africa.org](https://openai4africa.org)

## License

[MIT](https://opensource.org/licenses/MIT)