npm package: @raindrop-ai/query
Description: Official TypeScript SDK for the [Raindrop Query API](https://query.raindrop.ai).
Author: Raindrop
Latest version: 0.1.5

# @raindrop-ai/query

Official TypeScript SDK for the [Raindrop Query API](https://query.raindrop.ai).

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![npm](https://img.shields.io/npm/v/@raindrop-ai/query)](https://www.npmjs.com/package/@raindrop-ai/query)

<!-- Start Summary [summary] -->
## Summary

Raindrop Query API (Beta): API for querying Signals, Events, Users, and Conversations data.
<!-- End Summary [summary] -->

<!-- Start Table of Contents [toc] -->
## Table of Contents
<!-- $toc-max-depth=2 -->
* [@raindrop-ai/query](#raindrop-aiquery)
  * [SDK Installation](#sdk-installation)
  * [Requirements](#requirements)
  * [SDK Example Usage](#sdk-example-usage)
  * [Authentication](#authentication)
  * [Available Resources and Operations](#available-resources-and-operations)
  * [Standalone functions](#standalone-functions)
  * [Retries](#retries)
  * [Error Handling](#error-handling)
  * [Server Selection](#server-selection)
  * [Custom HTTP Client](#custom-http-client)
  * [Debugging](#debugging)
* [Development](#development)
  * [Maturity](#maturity)
  * [Support](#support)

<!-- End Table of Contents [toc] -->

<!-- Start SDK Installation [installation] -->
## SDK Installation

The SDK can be installed with either [npm](https://www.npmjs.com/), [pnpm](https://pnpm.io/), [bun](https://bun.sh/) or [yarn](https://classic.yarnpkg.com/en/) package managers.

### NPM

```bash
npm add @raindrop-ai/query
```

### PNPM

```bash
pnpm add @raindrop-ai/query
```

### Bun

```bash
bun add @raindrop-ai/query
```

### Yarn

```bash
yarn add @raindrop-ai/query
```

This package is published with CommonJS and ES Modules (ESM) support.
<!-- End SDK Installation [installation] -->

<!-- Start Requirements [requirements] -->
## Requirements

For supported JavaScript runtimes, please consult [RUNTIMES.md](RUNTIMES.md).
<!-- End Requirements [requirements] -->

<!-- Start SDK Example Usage [usage] -->
## SDK Example Usage

### Example

```typescript
import { RaindropQuery } from "@raindrop-ai/query";

const raindropQuery = new RaindropQuery({
  apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await raindropQuery.signals.list({});

  console.log(result);
}

run();

```
<!-- End SDK Example Usage [usage] -->

<!-- Start Authentication [security] -->
## Authentication

### Per-Client Security Schemes

This SDK supports the following security scheme globally:

| Name     | Type | Scheme      |
| -------- | ---- | ----------- |
| `apiKey` | http | HTTP Bearer |

To authenticate with the API the `apiKey` parameter must be set when initializing the SDK client instance. For example:
```typescript
import { RaindropQuery } from "@raindrop-ai/query";

const raindropQuery = new RaindropQuery({
  apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await raindropQuery.signals.list({});

  console.log(result);
}

run();

```
<!-- End Authentication [security] -->

<!-- Start Available Resources and Operations [operations] -->
## Available Resources and Operations

<details open>
<summary>Available methods</summary>

### [Conversations](docs/sdks/conversations/README.md)

* [list](docs/sdks/conversations/README.md#list) - List conversations
* [get](docs/sdks/conversations/README.md#get) - Get conversation details

### [Events](docs/sdks/events/README.md)

* [list](docs/sdks/events/README.md#list) - List events
* [search](docs/sdks/events/README.md#search) - Search events (GET)
* [count](docs/sdks/events/README.md#count) - Count events
* [timeseries](docs/sdks/events/README.md#timeseries) - Get event timeseries
* [facets](docs/sdks/events/README.md#facets) - Get event facets
* [get](docs/sdks/events/README.md#get) - Get event details

### [SignalGroups](docs/sdks/signalgroups/README.md)

* [list](docs/sdks/signalgroups/README.md#list) - List all signal groups
* [get](docs/sdks/signalgroups/README.md#get) - Get signal group details
* [listSignals](docs/sdks/signalgroups/README.md#listsignals) - List signals in group

### [Signals](docs/sdks/signals/README.md)

* [list](docs/sdks/signals/README.md#list) - List all signals
* [get](docs/sdks/signals/README.md#get) - Get signal details

### [Traces](docs/sdks/traces/README.md)

* [list](docs/sdks/traces/README.md#list) - List traces for an event

### [Users](docs/sdks/users/README.md)

* [list](docs/sdks/users/README.md#list) - List users
* [get](docs/sdks/users/README.md#get) - Get user details

</details>
<!-- End Available Resources and Operations [operations] -->

<!-- Start Standalone functions [standalone-funcs] -->
## Standalone functions

All the methods listed above are available as standalone functions. These
functions are ideal for use in applications running in the browser, serverless
runtimes or other environments where application bundle size is a primary
concern. When using a bundler to build your application, all unused
functionality will be either excluded from the final bundle or tree-shaken away.

To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md).

<details>

<summary>Available standalone functions</summary>

- [`conversationsGet`](docs/sdks/conversations/README.md#get) - Get conversation details
- [`conversationsList`](docs/sdks/conversations/README.md#list) - List conversations
- [`eventsCount`](docs/sdks/events/README.md#count) - Count events
- [`eventsFacets`](docs/sdks/events/README.md#facets) - Get event facets
- [`eventsGet`](docs/sdks/events/README.md#get) - Get event details
- [`eventsList`](docs/sdks/events/README.md#list) - List events
- [`eventsSearch`](docs/sdks/events/README.md#search) - Search events (GET)
- [`eventsTimeseries`](docs/sdks/events/README.md#timeseries) - Get event timeseries
- [`signalGroupsGet`](docs/sdks/signalgroups/README.md#get) - Get signal group details
- [`signalGroupsList`](docs/sdks/signalgroups/README.md#list) - List all signal groups
- [`signalGroupsListSignals`](docs/sdks/signalgroups/README.md#listsignals) - List signals in group
- [`signalsGet`](docs/sdks/signals/README.md#get) - Get signal details
- [`signalsList`](docs/sdks/signals/README.md#list) - List all signals
- [`tracesList`](docs/sdks/traces/README.md#list) - List traces for an event
- [`usersGet`](docs/sdks/users/README.md#get) - Get user details
- [`usersList`](docs/sdks/users/README.md#list) - List users

</details>
<!-- End Standalone functions [standalone-funcs] -->

<!-- Start Retries [retries] -->
## Retries

Some of the endpoints in this SDK support retries.  If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API.  However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
```typescript
import { RaindropQuery } from "@raindrop-ai/query";

const raindropQuery = new RaindropQuery({
  apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await raindropQuery.signals.list({}, {
    retries: {
      strategy: "backoff",
      backoff: {
        initialInterval: 1,
        maxInterval: 50,
        exponent: 1.1,
        maxElapsedTime: 100,
      },
      retryConnectionErrors: false,
    },
  });

  console.log(result);
}

run();

```

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
```typescript
import { RaindropQuery } from "@raindrop-ai/query";

const raindropQuery = new RaindropQuery({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await raindropQuery.signals.list({});

  console.log(result);
}

run();

```
<!-- End Retries [retries] -->

<!-- Start Error Handling [errors] -->
## Error Handling

[`RaindropQueryError`](./src/models/errors/raindrop-query-error.ts) is the base class for all HTTP error responses. It has the following properties:

| Property            | Type       | Description                                                                             |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| `error.message`     | `string`   | Error message                                                                           |
| `error.statusCode`  | `number`   | HTTP response status code eg `404`                                                      |
| `error.headers`     | `Headers`  | HTTP response headers                                                                   |
| `error.body`        | `string`   | HTTP body. Can be empty string if no body is returned.                                  |
| `error.rawResponse` | `Response` | Raw HTTP response                                                                       |
| `error.data$`       |            | Optional. Some errors may contain structured data. [See Error Classes](#error-classes). |

### Example
```typescript
import { RaindropQuery } from "@raindrop-ai/query";
import * as errors from "@raindrop-ai/query/models/errors";

const raindropQuery = new RaindropQuery({
  apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  try {
    const result = await raindropQuery.signals.list({});

    console.log(result);
  } catch (error) {
    // The base class for HTTP error responses
    if (error instanceof errors.RaindropQueryError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);

      // Depending on the method different errors may be thrown
      if (error instanceof errors.SignalsListUnauthorizedError) {
        console.log(error.data$.error); // operations.SignalsListError
      }
    }
  }
}

run();

```

### Error Classes
**Primary error:**
* [`RaindropQueryError`](./src/models/errors/raindrop-query-error.ts): The base class for HTTP error responses.

<details><summary>Less common errors (21)</summary>

<br />

**Network errors:**
* [`ConnectionError`](./src/models/errors/http-client-errors.ts): HTTP client was unable to make a request to a server.
* [`RequestTimeoutError`](./src/models/errors/http-client-errors.ts): HTTP request timed out due to an AbortSignal signal.
* [`RequestAbortedError`](./src/models/errors/http-client-errors.ts): HTTP request was aborted by the client.
* [`InvalidRequestError`](./src/models/errors/http-client-errors.ts): Any input used to create a request is invalid.
* [`UnexpectedClientError`](./src/models/errors/http-client-errors.ts): Unrecognised or unexpected error.


**Inherit from [`RaindropQueryError`](./src/models/errors/raindrop-query-error.ts)**:
* [`EventsSearchBadRequestError`](./src/models/errors/events-search-bad-request-error.ts): Invalid request (e.g., date range exceeds maximum). Status code `400`. Applicable to 1 of 16 methods.*
* [`EventsFacetsBadRequestError`](./src/models/errors/events-facets-bad-request-error.ts): Invalid field name. Status code `400`. Applicable to 1 of 16 methods.*
* [`TracesListBadRequestError`](./src/models/errors/traces-list-bad-request-error.ts): Bad request (missing event_id). Status code `400`. Applicable to 1 of 16 methods.*
* [`SignalsListUnauthorizedError`](./src/models/errors/signals-list-unauthorized-error.ts): Unauthorized. Status code `401`. Applicable to 1 of 16 methods.*
* [`SignalGroupsListUnauthorizedError`](./src/models/errors/signal-groups-list-unauthorized-error.ts): Unauthorized. Status code `401`. Applicable to 1 of 16 methods.*
* [`EventsListUnauthorizedError`](./src/models/errors/events-list-unauthorized-error.ts): Unauthorized. Status code `401`. Applicable to 1 of 16 methods.*
* [`UsersListUnauthorizedError`](./src/models/errors/users-list-unauthorized-error.ts): Unauthorized. Status code `401`. Applicable to 1 of 16 methods.*
* [`ConversationsListUnauthorizedError`](./src/models/errors/conversations-list-unauthorized-error.ts): Unauthorized. Status code `401`. Applicable to 1 of 16 methods.*
* [`TracesListUnauthorizedError`](./src/models/errors/traces-list-unauthorized-error.ts): Unauthorized. Status code `401`. Applicable to 1 of 16 methods.*
* [`SignalsGetNotFoundError`](./src/models/errors/signals-get-not-found-error.ts): Signal not found. Status code `404`. Applicable to 1 of 16 methods.*
* [`SignalGroupsGetNotFoundError`](./src/models/errors/signal-groups-get-not-found-error.ts): Signal group not found. Status code `404`. Applicable to 1 of 16 methods.*
* [`SignalGroupsListSignalsNotFoundError`](./src/models/errors/signal-groups-list-signals-not-found-error.ts): Signal group not found. Status code `404`. Applicable to 1 of 16 methods.*
* [`EventsGetNotFoundError`](./src/models/errors/events-get-not-found-error.ts): Event not found. Status code `404`. Applicable to 1 of 16 methods.*
* [`UsersGetNotFoundError`](./src/models/errors/users-get-not-found-error.ts): User not found. Status code `404`. Applicable to 1 of 16 methods.*
* [`ConversationsGetNotFoundError`](./src/models/errors/conversations-get-not-found-error.ts): Conversation not found. Status code `404`. Applicable to 1 of 16 methods.*
* [`ResponseValidationError`](./src/models/errors/response-validation-error.ts): Type mismatch between the data returned from the server and the structure expected by the SDK. See `error.rawValue` for the raw value and `error.pretty()` for a nicely formatted multi-line string.

</details>

\* Check [the method documentation](#available-resources-and-operations) to see if the error is applicable.
<!-- End Error Handling [errors] -->

<!-- Start Server Selection [server] -->
## Server Selection

### Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the `serverURL: string` optional parameter when initializing the SDK client instance. For example:
```typescript
import { RaindropQuery } from "@raindrop-ai/query";

const raindropQuery = new RaindropQuery({
  serverURL: "https://query.raindrop.ai",
  apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await raindropQuery.signals.list({});

  console.log(result);
}

run();

```
<!-- End Server Selection [server] -->

<!-- Start Custom HTTP Client [http-client] -->
## Custom HTTP Client

The TypeScript SDK makes API calls using an `HTTPClient` that wraps the native
[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). This
client is a thin wrapper around `fetch` and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.

The `HTTPClient` constructor takes an optional `fetcher` argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.

The following example shows how to:
- route requests through a proxy server using [undici](https://www.npmjs.com/package/undici)'s ProxyAgent
- use the `"beforeRequest"` hook to add a custom header and a timeout to requests
- use the `"requestError"` hook to log errors

```typescript
import { RaindropQuery } from "@raindrop-ai/query";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@raindrop-ai/query/lib/http";

const dispatcher = new ProxyAgent("http://proxy.example.com:8080");

const httpClient = new HTTPClient({
  // 'fetcher' takes a function that has the same signature as native 'fetch'.
  fetcher: (input, init) =>
    // 'dispatcher' is specific to undici and not part of the standard Fetch API.
    fetch(input, { ...init, dispatcher } as RequestInit),
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000)
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new RaindropQuery({ httpClient: httpClient });
```
<!-- End Custom HTTP Client [http-client] -->

<!-- Start Debugging [debug] -->
## Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches `console`'s interface as an SDK option.

> [!WARNING]
> Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

```typescript
import { RaindropQuery } from "@raindrop-ai/query";

const sdk = new RaindropQuery({ debugLogger: console });
```
<!-- End Debugging [debug] -->

<!-- Placeholder for Future Speakeasy SDK Sections -->

# Development

## Maturity

This SDK is in beta. We recommend pinning to a specific version.

## Support

For questions or issues, contact support@raindrop.ai