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

# JavaScript SDK

> Install and use the official VidNavigator JavaScript SDK to interact with the API.

## Installation

Install the SDK from npm or yarn:

<CodeGroup>
  ```bash npm theme={null}
  npm install vidnavigator
  ```

  ```bash yarn theme={null}
  yarn add vidnavigator
  ```
</CodeGroup>

## Initialization

Initialize the client with your API key. You can find your key in the [Developer Dashboard](https://vidnavigator.com/studio/api).

```javascript theme={null}
const { VidNavigatorClient } = require('vidnavigator');

const client = new VidNavigatorClient({
  apiKey: process.env.VIDNAVIGATOR_API_KEY,
});
```

***

## Online Videos

### Get Video Transcript

```javascript theme={null}
async function getTranscript() {
  try {
    const {video_info, transcript} = await client.getTranscript({
      video_url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    });
    console.log(video_info.title);
    console.log(transcript);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
getTranscript();
```

### Transcribe a Video

```javascript theme={null}
async function transcribeVideo() {
  try {
    const { video_info, transcript } = await client.transcribeVideo({
      video_url: "https://www.instagram.com/reel/C86ZvEaqRmo/"
    });
    console.log(video_info.title);
    console.log(transcript[0].text);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
transcribeVideo();
```

### Analyze a Video

```javascript theme={null}
async function analyzeVideo() {
  try {
    const result = await client.analyzeVideo({
      video_url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
      query: "What is the main topic of this song?",
    });
    console.log(result.transcript_analysis);
    // GET analysis summary
    console.log(result.transcript_analysis.summary);
    // GET analysis by timestamp
    console.log(result.transcript_analysis.timestamp);
    // GET key subjects
    console.log(result.transcript_analysis.key_subjects);
    // GET places
    console.log(result.transcript_analysis.places);
    // GET people
    console.log(result.transcript_analysis.people);
    // GET query answer
    console.log(result.transcript_analysis.query_answer);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
analyzeVideo();
```

### Search for Videos

```javascript theme={null}
async function searchVideos() {
  try {
    const searchResults = await client.searchVideos({
      query: "What are the best practices for React development?"
    });
    searchResults.data.results.forEach(video => {
      console.log(`- ${video.title}`);
    });
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
searchVideos();
```

***

## Files

### Upload a File

```javascript theme={null}
import fs from 'fs';

async function uploadFile() {
  try {
    const uploadResponse = await client.uploadFile({
      filePath: "path/to/your/video.mp4",
      wait_for_completion: false,
    });
    console.log(`File uploaded with ID: ${uploadResponse.file_id}`);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
uploadFile();
```

### List Files

```javascript theme={null}
async function listFiles() {
  try {
    const filesResponse = await client.getFiles({ limit: 10, status: 'completed' });
    filesResponse.files.forEach(file => {
      console.log(`- ${file.file_name} (ID: ${file.file_id})`);
    });
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
listFiles();
```

### Get File Info

```javascript theme={null}
async function getFile() {
  try {
    const fileId = "your_file_id_here";
    const fileDetails = await client.getFile(fileId);
    console.log(fileDetails);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
getFile();
```

### Get Temporary File URL to view it in the browser

```javascript theme={null}
async function getFileUrl() {
  try {
    const fileId = "your_file_id_here";
    const response = await client.getFileUrl(fileId);
    console.log(`Temporary URL: ${response.file_url}`);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
getFileUrl();
```

### Retry File Processing

```javascript theme={null}
async function retryFile() {
  try {
    const fileId = "your_failed_file_id_here";
    const response = await client.retryFileProcessing(fileId);
    console.log(response.message);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
retryFile();
```

### Cancel File Processing

```javascript theme={null}
async function cancelFile() {
  try {
    const fileId = "your_processing_file_id_here";
    const response = await client.cancelFileUpload(fileId);
    console.log(response.message);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
cancelFile();
```

### Delete a File

```javascript theme={null}
async function deleteFile() {
  try {
    const fileId = "your_file_id_here";
    const deleteResponse = await client.deleteFile(fileId);
    console.log(deleteResponse.message);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
deleteFile();
```

### Analyze an Uploaded File

```javascript theme={null}
async function analyzeFile() {
  try {
    const analysisData = await client.analyzeFile({
      file_id: "your_file_id_here",
      query: "What are the key topics discussed?",
    });
    console.log(analysisData.transcript_analysis);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
analyzeFile();
```

### Search Uploaded Files

```javascript theme={null}
async function searchFiles() {
  try {
    const searchResults = await client.searchFiles({
      query: "Customer feedback on pricing"
    });
    searchResults.results.forEach(result => {
      console.log(`- Found in: ${result.file_name}, Score: ${result.relevance_score}`);
    });
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
searchFiles();
```

***

## System

### Get API Usage

```javascript theme={null}
async function getUsage() {
  try {
    const usageData = await client.getUsage();
    console.log(usageData);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
getUsage();
```

### Health Check

```javascript theme={null}
async function healthCheck() {
  try {
    const healthStatus = await client.healthCheck();
    console.log(healthStatus);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}
healthCheck();
```

***

## Data Models

The SDK returns structured data objects that correspond to the API's JSON responses. Here are the main data models:

### Online Videos Data Models

<AccordionGroup>
  <Accordion title="getTranscript()">
    Returns a promise that resolves to an object with:

    * **`video_info`**: A `VideoInfo` object.
    * **`transcript`**: An array of `TranscriptSegment` objects.
  </Accordion>

  <Accordion title="transcribeVideo()">
    Returns a promise that resolves to the **same structure** as `getTranscript()` above. Use this when a transcript is not already available and you need speech-to-text processing.
  </Accordion>

  <Accordion title="analyzeVideo()">
    Returns a promise that resolves to an object with:

    * **`video_info`**: A `VideoInfo` object.
    * **`transcript`**: An array of `TranscriptSegment` objects.
    * **`transcript_analysis`**: An `AnalysisResult` object.
  </Accordion>

  <Accordion title="searchVideos()">
    Returns a promise that resolves to an object with:

    * **`results`**: An array of `VideoSearchResult` objects.
    * **`total_found`**: The total number of results found.
  </Accordion>
</AccordionGroup>

### Files Data Models

<AccordionGroup>
  <Accordion title="getFiles()">
    Returns a promise resolving to an object with:

    * **`files`**: An array of `FileInfo` objects.
    * **`total_count`**: The total number of files.
    * **`has_more`**: A boolean indicating if more pages are available.
  </Accordion>

  <Accordion title="getFile()">
    Returns a promise resolving to an object with:

    * **`file_info`**: A `FileInfo` object.
    * **`transcript`**: An optional array of `TranscriptSegment` objects.
  </Accordion>

  <Accordion title="uploadFile()">
    Returns a promise resolving to an object with:

    * **`file_id`**: The ID of the uploaded file.
    * **`file_info`**: A `FileInfo` object.
    * **`transcript`**: An optional array of `TranscriptSegment` objects if `wait_for_completion` is true.
  </Accordion>

  <Accordion title="searchFiles()">
    Returns a promise resolving to an object with:

    * **`results`**: An array of `FileSearchResult` objects.
  </Accordion>
</AccordionGroup>

## Exceptions

The JavaScript SDK throws custom `Error` objects when an API request fails. All custom errors inherit from the base `VidNavigatorError`.

You should use `try...catch` blocks to handle errors gracefully and can use `instanceof` to check for specific error types.

```javascript theme={null}
import { VidNavigatorError, AuthenticationError } from 'vidnavigator';

try {
  const data = await client.getTranscript({ video_url: "invalid-url" });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("Authentication failed:", error.message);
  } else if (error instanceof VidNavigatorError) {
    console.error(`A VidNavigator error occurred: ${error.message}`);
  } else {
    console.error("An unexpected error occurred:", error);
  }
}
```

<AccordionGroup>
  <Accordion title="VidNavigatorError">
    The base exception for all SDK-related errors. It contains the following properties:

    * `status_code`: The HTTP status code of the response.
    * `error_code`: The error code from the API response.
    * `error_message`: The error message from the API response.
    * `details`: Any additional details provided by the API.
  </Accordion>

  <Accordion title="AuthenticationError">
    Raised for `401 Unauthorized` errors when the API key is missing or invalid.
  </Accordion>

  <Accordion title="BadRequestError">
    Raised for `400 Bad Request` errors, typically due to invalid parameters.
  </Accordion>

  <Accordion title="AccessDeniedError">
    Raised for `403 Forbidden` errors, indicating insufficient permissions.
  </Accordion>

  <Accordion title="NotFoundError">
    Raised for `404 Not Found` errors when a resource does not exist.
  </Accordion>

  <Accordion title="RateLimitExceededError">
    Raised for `429 Too Many Requests` errors when you have exceeded your rate limit.
  </Accordion>

  <Accordion title="PaymentRequiredError">
    Raised for `402 Payment Required` errors when you have exceeded your usage quota.
  </Accordion>

  <Accordion title="ServerError">
    Raised for `5xx` server-side errors.
  </Accordion>
</AccordionGroup>

***

## More Information

For the complete source code and more examples, visit the [npm package](https://www.npmjs.com/package/vidnavigator) or the [GitHub repository](https://github.com/vidnavigator/vidnavigator-js).
