> ## Documentation Index
> Fetch the complete documentation index at: https://docs.solvice.io/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Official TypeScript/JavaScript SDK with full type safety and modern developer experience

<Info>
  The official Solvice VRP Solver SDK is now available! Install it today to streamline your route optimization integrations.
</Info>

## Installation

Install the SDK using your preferred package manager:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install solvice-vrp-solver
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add solvice-vrp-solver
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add solvice-vrp-solver
    ```
  </Tab>
</Tabs>

## Quick Start

Get up and running with the VRP Solver in minutes:

```typescript theme={null}
import SolviceVrpSolver from 'solvice-vrp-solver';

const client = new SolviceVrpSolver({
  apiKey: process.env.SOLVICE_API_KEY, // Required
});

// Solve a simple routing problem
const solution = await client.vrp.syncSolve({
  jobs: [
    { 
      name: 'delivery-1',
      location: { latitude: 51.0500, longitude: 3.7300 },
      duration: 900 // 15 minutes
    },
    { 
      name: 'delivery-2',
      location: { latitude: 51.0543, longitude: 3.7174 },
      duration: 600 // 10 minutes
    }
  ],
  resources: [{ 
    name: 'vehicle-1', 
    shifts: [{ 
      from: '2024-01-15T08:00:00Z', 
      to: '2024-01-15T17:00:00Z',
      start: { latitude: 51.0543, longitude: 3.7174 }
    }] 
  }],
});

console.log(solution.routes);
```

## Key Features

<CardGroup cols={2}>
  <Card title="Type Safety" icon="shield-check">
    Full TypeScript support with comprehensive type definitions for all request and response objects
  </Card>

  <Card title="Auto Retry" icon="rotate">
    Built-in retry logic with configurable attempts for resilient integrations
  </Card>

  <Card title="Modern Runtime Support" icon="browser">
    Works in Node.js, Deno, Bun, browsers, and Cloudflare Workers
  </Card>

  <Card title="Error Handling" icon="exclamation-triangle">
    Typed error responses with detailed debugging information
  </Card>
</CardGroup>

## Configuration

Configure the SDK client with these options:

```typescript theme={null}
const client = new SolviceVrpSolver({
  apiKey: process.env.SOLVICE_API_KEY,     // Required: Your API key
  maxRetries: 2,                           // Optional: Number of retry attempts (default: 2)
  timeout: 60000,                          // Optional: Request timeout in ms (default: 60000)
  logLevel: 'info',                        // Optional: 'debug' | 'info' | 'warn' | 'error' | 'off'
});
```

<Warning>
  Never hardcode your API key. Always use environment variables or secure key management systems.
</Warning>

## Advanced Usage

### Asynchronous Solve with Polling

For large routing problems, use the asynchronous solve method:

```typescript theme={null}
// Submit the job
const { jobId } = await client.vrp.solve({
  jobs: [...],
  resources: [...],
  options: {
    maxSolvingTime: 300 // 5 minutes
  }
});

// Check status
const status = await client.vrp.getStatus({ jobId });

if (status.status === 'SOLVED') {
  // Retrieve solution
  const solution = await client.vrp.getSolution({ jobId });
  console.log(solution);
}
```

### Error Handling

The SDK provides typed error responses for better debugging:

```typescript theme={null}
import { BadRequestError, AuthenticationError } from 'solvice-vrp-solver';

try {
  const solution = await client.vrp.syncSolve({...});
} catch (error) {
  if (error instanceof BadRequestError) {
    console.error('Invalid request:', error.message);
    console.error('Details:', error.body);
  } else if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

### Using with Real Road Distances

Enable real-world routing distances instead of straight-line calculations:

```typescript theme={null}
const solution = await client.vrp.syncSolve({
  jobs: [...],
  resources: [...],
  options: {
    euclidian: false,    // Use real road networks instead of straight-line
    routingEngine: 'OSM', // OSM, TOMTOM, or GOOGLE
    traffic: 1.3,        // 30% traffic factor
    polylines: true      // Include route geometries for mapping
  }
});
```

## Runtime Support

The SDK supports multiple JavaScript runtimes:

<Tabs>
  <Tab title="Node.js">
    Requires Node.js 20 LTS or later:

    ```javascript theme={null}
    // CommonJS
    const SolviceVrpSolver = require('solvice-vrp-solver');

    // ESM
    import SolviceVrpSolver from 'solvice-vrp-solver';
    ```
  </Tab>

  <Tab title="Deno">
    Works with Deno v1.28.0 or later:

    ```typescript theme={null}
    import SolviceVrpSolver from "npm:solvice-vrp-solver";
    ```
  </Tab>

  <Tab title="Bun">
    Compatible with Bun 1.0 or later:

    ```typescript theme={null}
    import SolviceVrpSolver from 'solvice-vrp-solver';
    ```
  </Tab>

  <Tab title="Browser">
    Use with modern browsers via a bundler:

    ```javascript theme={null}
    import SolviceVrpSolver from 'solvice-vrp-solver';
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a comprehensive example showcasing various SDK features:

```typescript theme={null}
import SolviceVrpSolver from 'solvice-vrp-solver';

const client = new SolviceVrpSolver({
  apiKey: process.env.SOLVICE_API_KEY,
  maxRetries: 3,
  timeout: 120000, // 2 minutes
  logLevel: 'info'
});

async function optimizeDeliveryRoutes() {
  try {
    const solution = await client.vrp.syncSolve({
      resources: [{
        name: 'vehicle-1',
        shifts: [{
          from: '2024-01-15T08:00:00Z',
          to: '2024-01-15T17:00:00Z',
          start: { latitude: 51.0543, longitude: 3.7174 },
          end: { latitude: 51.0543, longitude: 3.7174 }
        }],
        capacity: [100],
        tags: ['refrigerated'],
        breaks: [{
          duration: 1800, // 30 minutes
          windows: [{
            from: '2024-01-15T12:00:00Z',
            to: '2024-01-15T13:00:00Z'
          }]
        }]
      }],
      jobs: [
        {
          name: 'customer-123',
          location: { latitude: 51.0500, longitude: 3.7300 },
          duration: 900,
          load: [20],
          priority: 10,
          tags: [{ name: 'refrigerated', hard: true }],
          windows: [{
            from: '2024-01-15T09:00:00Z',
            to: '2024-01-15T11:00:00Z'
          }]
        },
        {
          name: 'customer-456',
          location: { latitude: 51.0600, longitude: 3.7400 },
          duration: 600,
          load: [15],
          priority: 5,
          windows: [{
            from: '2024-01-15T14:00:00Z',
            to: '2024-01-15T16:00:00Z'
          }]
        }
      ],
      options: {
        euclidian: false,
        routingEngine: 'OSM',
        traffic: 1.2,
        maxSolvingTime: 60
      }
    });

    // Process the solution
    solution.routes.forEach(route => {
      console.log(`Route for ${route.resourceName}:`);
      route.stops.forEach(stop => {
        console.log(`- ${stop.jobName} at ${stop.arrival}`);
      });
    });

    // Check for unassigned jobs
    if (solution.unassigned.length > 0) {
      console.warn('Unassigned jobs:', solution.unassigned);
    }

  } catch (error) {
    console.error('Optimization failed:', error);
  }
}

optimizeDeliveryRoutes();
```

## API Methods

The SDK provides access to all VRP Solver endpoints:

### Core Methods

* `syncSolve()` - Synchronous solving for smaller problems
* `solve()` - Asynchronous solving for larger problems
* `getStatus()` - Check job status
* `getSolution()` - Retrieve solution

### Advanced Methods

* `evaluate()` - Evaluate an existing solution
* `suggest()` - Get improvement suggestions
* `explain()` - Get detailed explanations

<Tip>
  For problems with more than 100 jobs or complex constraints, use the asynchronous `solve()` method to avoid timeouts.
</Tip>

## Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/solvice/vrp-solver-sdk">
    View source code and contribute
  </Card>

  <Card title="npm Package" icon="npm" href="https://www.npmjs.com/package/solvice-vrp-solver">
    View on npm registry
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/vrp/introduction">
    Complete API documentation
  </Card>

  <Card title="Support" icon="life-ring" href="mailto:support@solvice.io">
    Get help from our team
  </Card>
</CardGroup>
