# TypeScript client

> A single-file client with retries, pagination, idempotency and polling. Copy it into your project.

Type: Reference. Updated 2 December 2026. Page: https://www.colossium.cloud/docs/client-typescript

## About this client

There is no SDK package yet, so here is the next best thing: one file you own. It has no dependencies, uses the global `fetch`, and runs on Node 20 and later, Bun, Deno and edge runtimes. It is the file the [tutorial](/docs/build-a-tool) uses, and the tests in this repository run it against a stand-in for the API.

| It does | How |
| --- | --- |
| Keeps the token safe | Reads `COLOSSIUM_API_TOKEN`, refuses a malformed one before sending, and never writes it to a log, an error or a printed object. |
| Retries safely | Retries 429, 500, 502, 503 and 504 and network failures with exponential backoff and jitter, obeying `Retry-After`. A POST is retried only if it has an idempotency key. |
| Paginates | `iterate()` walks every page for you. |
| Waits | `requests.waitFor()` polls a request to its end and slows down near the rate limit. |
| Reports errors properly | Throws a `ColossiumError` with the status, code, request id and docs link. |
| Blocks path tricks | Ids are checked to be UUIDs before they go into a path. |

## Using it

```typescript
import { Colossium, ColossiumError } from "./colossium-client"

const colossium = new Colossium()               // reads COLOSSIUM_API_TOKEN

const me = await colossium.verify()
console.log(me.scopes)

// Every page of a list, without holding it all in memory:
for await (const project of colossium.projects.iterate()) console.log(project.slug)

// Ask for something. The key makes it safe to retry.
const { request, replayed } = await colossium.requests.create(
  { kind: "storage.create", project_id: "3f2b8c1e-5d4a-4e7b-9c1d-2a6f8e0b4d37", input: { name: "assets", region: "eu" } },
  "release-2026-12-02-assets",
)

try {
  const done = await colossium.requests.waitFor(request.id, { onUpdate: (r) => console.log(r.state) })
  console.log(done.state, done.resource_id)
} catch (e) {
  if (e instanceof ColossiumError) console.error(e.code, e.status, e.requestId)   // never the token
  else throw e
}
```

## The source

```typescript
/**
 * A small client for the Colossium API. Copy this file into your project. It has no dependencies and uses the global fetch, so it
 * runs on Node 20 or later, Bun, Deno and edge runtimes.
 *
 * It does the things every integration needs and most get wrong:
 *   - reads the token from COLOSSIUM_API_TOKEN, never from code, and never writes it to a log or an error;
 *   - retries 429 and 5xx responses and network failures with exponential backoff and jitter, obeying Retry-After;
 *   - retries a POST only when it carries an Idempotency-Key, so a retry can never make a second request;
 *   - walks every page of a list for you;
 *   - waits for a request to finish by polling at a gentle pace.
 */

export type RateInfo = { limit: number; remaining: number; reset: number }

export type Project = { id: string; name: string; slug: string; description: string; created_at: string }
export type Resource = { id: string; project_id: string | null; service: string; kind: string; name: string; region: string | null; observed_status: string; drift: boolean; last_observed_at: string | null; created_at: string }
export type RequestState = 'awaiting_approval' | 'queued' | 'running' | 'awaiting_verification' | 'succeeded' | 'failed' | 'cancelled'
export type ServiceRequest = { id: string; project_id: string | null; resource_id: string | null; kind: string; state: RequestState; input: Record<string, unknown>; failure: string | null; created_at: string; started_at: string | null; finished_at: string | null; events?: { at: string; kind: string; message: string }[] }
export type AuditEvent = { id: number; created_at: string; actor_kind: string; actor_id: string | null; action: string; target_type: string | null; target_id: string | null; outcome: string; detail: Record<string, unknown> }
export type Page<T> = { data: T[]; next_cursor: string | null }

/** Every error the API returns arrives as this. Log requestId and code. Never log the token. */
export class ColossiumError extends Error {
  constructor(readonly status: number, readonly code: string, message: string, readonly requestId: string | null, readonly docUrl: string | null, readonly details?: unknown) {
    super(message)
    this.name = 'ColossiumError'
  }
}

export type ClientOptions = {
  /** Defaults to the COLOSSIUM_API_TOKEN environment variable. */
  token?: string
  /** Defaults to https://api.colossium.cloud/v1. */
  baseUrl?: string
  /** Give up on one attempt after this long. Default 30 seconds. */
  timeoutMs?: number
  /** How many times to retry a request that can safely be retried. Default 4. */
  maxRetries?: number
  fetch?: typeof fetch
  sleep?: (ms: number) => Promise<void>
}

const TERMINAL: RequestState[] = ['succeeded', 'failed', 'cancelled']
const TOKEN_SHAPE = /^clsm_[0-9A-Za-z]{46}$/
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const defaultSleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))

export class Colossium {
  private readonly token: string
  private readonly baseUrl: string
  private readonly timeoutMs: number
  private readonly maxRetries: number
  private readonly fetchImpl: typeof fetch
  private readonly sleep: (ms: number) => Promise<void>
  /** The rate limit as of the last response, so you can slow down before you are told to. */
  lastRate: RateInfo | null = null

  constructor(options: ClientOptions = {}) {
    const token = options.token ?? (typeof process !== 'undefined' ? process.env.COLOSSIUM_API_TOKEN : undefined)
    if (!token) throw new Error('Set COLOSSIUM_API_TOKEN, or pass { token }.')
    if (!TOKEN_SHAPE.test(token)) throw new Error('That does not look like a Colossium token. It should start with clsm_ and be 51 characters long.')
    this.token = token
    this.baseUrl = (options.baseUrl ?? 'https://api.colossium.cloud/v1').replace(/\/+$/, '')
    this.timeoutMs = options.timeoutMs ?? 30_000
    this.maxRetries = options.maxRetries ?? 4
    this.fetchImpl = options.fetch ?? fetch
    this.sleep = options.sleep ?? defaultSleep
  }

  /** The token never appears when the client is printed or logged. */
  toJSON() { return { baseUrl: this.baseUrl } }
  [Symbol.for('nodejs.util.inspect.custom')]() { return `Colossium { baseUrl: '${this.baseUrl}' }` }

  private id(value: string, what: string): string {
    if (!UUID.test(value)) throw new Error(`${what} must be an id like 3f2b8c1e-5d4a-4e7b-9c1d-2a6f8e0b4d37.`)
    return value
  }

  /** One call, with retries. Returns the body and the request id. Throws ColossiumError for an error response. */
  async request<T>(method: 'GET' | 'POST', path: string, options: { query?: Record<string, string | number | undefined>; body?: unknown; idempotencyKey?: string } = {}): Promise<{ data: T; requestId: string | null; replayed: boolean }> {
    const url = new URL(this.baseUrl + path)
    for (const [k, v] of Object.entries(options.query ?? {})) if (v !== undefined) url.searchParams.set(k, String(v))
    // A POST is retried only if repeating it cannot do harm: it has an idempotency key.
    const retryable = method === 'GET' || options.idempotencyKey !== undefined
    let attempt = 0
    for (;;) {
      let res: Response | null = null
      let failure: unknown = null
      const ctl = new AbortController()
      const timer = setTimeout(() => ctl.abort(), this.timeoutMs)
      try {
        res = await this.fetchImpl(url, {
          method,
          signal: ctl.signal,
          headers: {
            Authorization: `Bearer ${this.token}`,
            Accept: 'application/json',
            ...(options.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
            ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),
          },
          body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
        })
      } catch (e) { failure = e } finally { clearTimeout(timer) }

      if (res) {
        const rate = rateOf(res)
        if (rate) this.lastRate = rate
        if (res.ok) return { data: (await res.json()) as T, requestId: res.headers.get('x-request-id'), replayed: res.headers.get('idempotent-replayed') === 'true' }
        const transient = res.status === 429 || res.status === 500 || res.status === 502 || res.status === 503 || res.status === 504
        if (!(transient && retryable && attempt < this.maxRetries)) throw await toError(res)
        await this.sleep(delayFor(attempt, res.headers.get('retry-after')))
      } else {
        if (!(retryable && attempt < this.maxRetries)) throw new ColossiumError(0, 'network_error', failure instanceof Error && failure.name === 'AbortError' ? 'The request timed out.' : 'The request could not be sent.', null, null)
        await this.sleep(delayFor(attempt, null))
      }
      attempt++
    }
  }

  /** Every item of a list, one page at a time, without holding them all in memory. */
  async *iterate<T>(path: string, query: Record<string, string | number | undefined> = {}): AsyncGenerator<T> {
    let cursor: string | undefined
    do {
      const { data } = await this.request<Page<T>>('GET', path, { query: { limit: 100, ...query, cursor } })
      for (const item of data.data) yield item
      cursor = data.next_cursor ?? undefined
    } while (cursor)
  }

  async collect<T>(source: AsyncGenerator<T>, max = 10_000): Promise<T[]> {
    const out: T[] = []
    for await (const item of source) { out.push(item); if (out.length >= max) break }
    return out
  }

  /** What the token is, and what it can do right now. A good first call, and a good health check. */
  verify() { return this.request<{ id: string; name: string; status: string; organisation_id: string; scopes: string[]; granted_scopes: string[]; project_ids: string[] | null; expires_at: string | null }>('GET', '/token/verify').then((r) => r.data) }
  organisation() { return this.request<{ id: string; name: string; slug: string; status: string; created_at: string }>('GET', '/organisation').then((r) => r.data) }

  projects = {
    list: (query: { limit?: number; cursor?: string } = {}) => this.request<Page<Project>>('GET', '/projects', { query }).then((r) => r.data),
    iterate: () => this.iterate<Project>('/projects'),
    get: (id: string) => this.request<Project>('GET', `/projects/${this.id(id, 'id')}`).then((r) => r.data),
    create: (input: { name: string; slug: string; description?: string }) => this.request<Project>('POST', '/projects', { body: input }).then((r) => r.data),
  }

  resources = {
    list: (query: { limit?: number; cursor?: string; project_id?: string; service?: string } = {}) => this.request<Page<Resource>>('GET', '/resources', { query }).then((r) => r.data),
    iterate: (query: { project_id?: string; service?: string } = {}) => this.iterate<Resource>('/resources', query),
    get: (id: string) => this.request<Resource>('GET', `/resources/${this.id(id, 'id')}`).then((r) => r.data),
  }

  requests = {
    list: (query: { limit?: number; cursor?: string; state?: RequestState; kind?: string; project_id?: string } = {}) => this.request<Page<ServiceRequest>>('GET', '/requests', { query }).then((r) => r.data),
    iterate: (query: { state?: RequestState; kind?: string; project_id?: string } = {}) => this.iterate<ServiceRequest>('/requests', query),
    get: (id: string) => this.request<ServiceRequest>('GET', `/requests/${this.id(id, 'id')}`).then((r) => r.data),
    cancel: (id: string) => this.request<ServiceRequest>('POST', `/requests/${this.id(id, 'id')}/cancel`).then((r) => r.data),
    /**
     * Asks for something. The idempotencyKey makes it safe to retry: send the same key again and you get the original request back
     * (replayed: true) and never a second one. Derive it from something that identifies the intent, such as "release-2026-12-02-db",
     * and never from personal data.
     */
    create: (input: { kind: string; project_id?: string | null; input: Record<string, unknown> }, idempotencyKey: string) =>
      this.request<ServiceRequest>('POST', '/requests', { body: input, idempotencyKey }).then((r) => ({ request: r.data, replayed: r.replayed })),
    /** Polls until the request reaches a final state. A request can wait for approval for some time, so allow plenty. */
    waitFor: async (id: string, options: { timeoutMs?: number; intervalMs?: number; onUpdate?: (r: ServiceRequest) => void } = {}): Promise<ServiceRequest> => {
      const deadline = Date.now() + (options.timeoutMs ?? 15 * 60_000)
      let last: RequestState | null = null
      for (;;) {
        const r = await this.requests.get(id)
        if (r.state !== last) { last = r.state; options.onUpdate?.(r) }
        if (TERMINAL.includes(r.state)) return r
        if (Date.now() >= deadline) throw new ColossiumError(0, 'wait_timeout', `The request is still ${r.state.replace(/_/g, ' ')} after waiting.`, null, null)
        // Slow down when close to the rate limit, otherwise poll every few seconds.
        const base = options.intervalMs ?? 5_000
        await this.sleep(this.lastRate && this.lastRate.remaining < 5 ? Math.max(base, 15_000) : base)
      }
    },
  }

  auditEvents = {
    list: (query: { limit?: number; cursor?: string; action?: string; outcome?: 'success' | 'denied' | 'failure' } = {}) => this.request<Page<AuditEvent>>('GET', '/audit-events', { query }).then((r) => r.data),
    iterate: (query: { action?: string; outcome?: 'success' | 'denied' | 'failure' } = {}) => this.iterate<AuditEvent>('/audit-events', query),
  }
}

function rateOf(res: Response): RateInfo | null {
  const limit = Number(res.headers.get('x-ratelimit-limit'))
  const remaining = Number(res.headers.get('x-ratelimit-remaining'))
  const reset = Number(res.headers.get('x-ratelimit-reset'))
  return Number.isFinite(limit) && res.headers.has('x-ratelimit-limit') ? { limit, remaining, reset } : null
}

/** Exponential backoff with full jitter, capped at 30 seconds. Retry-After, when present, wins (capped at 60 seconds). */
export function delayFor(attempt: number, retryAfter: string | null, random: () => number = Math.random): number {
  const seconds = retryAfter !== null && /^\d+$/.test(retryAfter) ? Number(retryAfter) : null
  if (seconds !== null) return Math.min(seconds, 60) * 1000
  return Math.floor(random() * Math.min(30_000, 500 * 2 ** attempt))
}

async function toError(res: Response): Promise<ColossiumError> {
  const requestId = res.headers.get('x-request-id')
  try {
    const body = (await res.json()) as { error?: { code?: string; message?: string; request_id?: string; doc_url?: string; details?: unknown } }
    const e = body.error
    return new ColossiumError(res.status, e?.code ?? 'unknown_error', e?.message ?? `The API answered ${res.status}.`, e?.request_id ?? requestId, e?.doc_url ?? null, e?.details)
  } catch {
    return new ColossiumError(res.status, 'unknown_error', `The API answered ${res.status}.`, requestId, null)
  }
}

```

## Notes

- **Server only.** Do not bundle this into a web page. A token in a browser is a leaked token.
- **Pin a copy.** It is yours. Change it freely, and keep the retry and token-handling rules when you do.
- **Unknown fields.** Responses may gain new fields in `v1`. The types here list what exists today. Do not fail when you see more.
