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

# JavaScript / TypeScript

[![@sunra/client npm package](https://img.shields.io/npm/v/@sunra/client?color=%237527D7\&label=JavaScript\&style=flat-square)](https://www.npmjs.com/package/@sunra/client)

### Introduction

The client library for JavaScript/TypeScript offers an easy-to-use interface to interact with Sunra's services.

### Installation

To integrate the client into your project, install it using npm:

<CodeGroup>
  ```bash npm theme={null}
  npm install @sunra/client
  ```

  ```bash pnpm theme={null}
  pnpm add @sunra/client
  ```

  ```bash yarn theme={null}
  yarn add @sunra/client
  ```
</CodeGroup>

### Features

#### Calling Endpoints

Sunra manages endpoint requests through a queue system, ensuring reliability and scalability. Use the `subscribe` method to submit a request and await the result.

**Example:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const result = await sunra.subscribe("black-forest-labs/flux-kontext-pro/text-to-image", {
  input: {
    prompt: "A glass teapot with blooming flower tea inside, placed on a wooden table by a sunlit window with gentle morning light.",
    "aspect_ratio": "16:9",
    "output_format": "jpeg",
  },
  logs: true,
  onQueueUpdate: (update) => {
    if (update.status === "IN_PROGRESS") {
      console.log(update.logs)
    }
  },
});

console.log(result.data);
console.log(result.requestId);
```

#### Queue Management

Manage your requests with these methods:

##### Submitting a Request

Submit a request and retrieve the `request_id` for later use.

**Example:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const { request_id } = await sunra.queue.submit("black-forest-labs/flux-kontext-max", {
  input: {
    prompt: "A glass teapot with blooming flower tea inside, placed on a wooden table by a sunlit window with gentle morning light.",
    "aspect_ratio": "16:9",
    "output_format": "jpeg",
  },
});
```

##### Checking Request Status

Retrieve the status of a request.

**Example:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const status = await sunra.queue.status({
  requestId: "pd_eTYYuw4EqYLzRBHgnAMHA8zH",
  logs: true,
});
```

##### Retrieving Request Results

Fetch the result of a completed request.

**Example:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const result = await sunra.queue.result({
  requestId: "pd_eTYYuw4EqYLzRBHgnAMHA8zH",
});

console.log(result.data);
console.log(result.requestId);
```

#### Storage

The `storage` API allows you to upload files and receive a URL, which can then be used in your model endpoint requests. This is particularly useful for models that require file inputs, such as image-to-video or speech-to-text.

<Note>Maximum file size: 100MB</Note>

##### Uploading Files in the Browser

You can allow users to upload files directly from their browser. The following example shows how to use an `<input type="file">` element to select a file and upload it.

<CodeGroup>
  ```javascript upload.js theme={null}
  import { sunra } from "@sunra/client";

  const fileInput = document.getElementById('file-input');

  fileInput.addEventListener('change', async (event) => {
    const file = event.target.files[0];
    if (file) {
      try {
        const url = await sunra.storage.upload(file);
        console.log('File uploaded successfully:', url);
        // Now you can use this URL with a model endpoint
      } catch (error) {
        console.error('Upload failed:', error);
      }
    }
  });
  ```

  ```html index.html theme={null}
  <input type="file" id="file-input" />
  ```
</CodeGroup>

##### Uploading Files in Node.js

On the server-side with Node.js, you can read files from the local filesystem and upload them.

```javascript theme={null}
import { sunra } from "@sunra/client";
import { readFile } from "node:fs/promises";
import { basename } from "node:path";

async function uploadLocalFile(filePath) {
  try {
    const buffer = await readFile(filePath);
    // The client needs a File object, which we can create from a buffer
    const file = new File([buffer], basename(filePath));

    const url = await sunra.storage.upload(file);
    console.log('File uploaded successfully:', url);
    return url;
  } catch (error) {
    console.error('Upload failed:', error);
  }
}

uploadLocalFile("./path/to/your/image.png");
```

#### Automatic Uploads with Model Endpoints

The JavaScript SDK can automatically handle file uploads for you. When you pass a `File` object, `Blob`, or a base64 data URI to a model endpoint's input, the SDK will first upload it to storage and then use the resulting URL in the request.

This simplifies the process as you don't need to perform a separate upload step.

```javascript theme={null}
import { sunra } from "@sunra/client";

// A File object from a browser file input will be automatically uploaded
const fileInput = document.getElementById('file-input');
const file = fileInput.files[0];

const result = await sunra.subscribe("some-model-that-takes-images", {
  input: {
    image: file, // SDK automatically uploads this file
    prompt: "A prompt describing what to do with the image"
  }
});

// A base64 data URI will also be automatically uploaded
const base64Image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...";

const result2 = await sunra.subscribe("some-model-that-takes-images", {
  input: {
    image: base64Image, // SDK automatically converts this to a Blob and uploads it
    prompt: "A prompt describing what to do with the image"
  }
});
```

### Support

Join our community for help or discussions:

* **Discord Community**: [Join us](https://discord.gg/897qCzvCcU)
* **GitHub Repository**: [Visit here](https://github.com/sunra-ai/sunra-clients)

We're here to assist you!
