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

# Helpers (Node.js)

> API reference for the @iii-dev/helpers package (Node.js / TypeScript).

{/* AI: any skill-check (vale/AI) text fixes belong in the source doc-comments under sdk/packages/node/helpers/src (prose) or docs/next/scripts/ (structure/formatting), then regenerate. Never edit this file directly. */}

## Installation

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
npm install @iii-dev/helpers
```

API reference for the @iii-dev/helpers package (Node.js / TypeScript).

## http

HTTP request/response types, auth config, and the `http` helper.

**Import**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { ... } from '@iii-dev/helpers/http'
```

### Functions

### http

Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)
into the function handler format expected by the SDK.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
http(callback: (req: HttpStreamingRequest, res: HttpStreamingResponse) => Promise<void | HttpResponse<number, string | Buffer<ArrayBufferLike> | Record<string, unknown>>>) => (req: HttpInternalRequest) => Promise<void | HttpResponse<number, string | Buffer<ArrayBufferLike> | Record<string, unknown>>>
```

#### Parameters

| Name       | Type                                                                                                                                                                                  | Required | Description                                               |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | --------------------------------------------------------- |
| `callback` | (req: HttpStreamingRequest, res: HttpStreamingResponse) => Promise\<void \| [`HttpResponse`](#httpresponse)\<number, string \| Buffer\<ArrayBufferLike> \| Record\<string, unknown>>> | Yes      | Async handler receiving a streaming request and response. |

#### Example

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { http } from '@iii-dev/helpers/http'

worker.registerFunction(
  'my-api',
  http(async (req, res) => {
    res.status(200)
    res.headers({ 'content-type': 'application/json' })
    res.stream.end(JSON.stringify({ hello: 'world' }))
    res.close()
  }),
)
```

### Types

[`HttpAuthConfig`](#httpauthconfig) · [`HttpInvocationConfig`](#httpinvocationconfig) · [`HttpMethod`](#httpmethod) · [`HttpRequest`](#httprequest) · [`HttpResponse`](#httpresponse)

### HttpAuthConfig

Authentication configuration for HTTP-invoked functions.

* `hmac` -- HMAC signature verification using a shared secret.
* `bearer` -- Bearer token authentication.
* `api_key` -- API key sent via a custom header.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type HttpAuthConfig = { secret_key: string; type: "hmac" } | { token_key: string; type: "bearer" } | { header: string; type: "api_key"; value_key: string }
```

### HttpInvocationConfig

Configuration for registering an HTTP-invoked function (Lambda, Cloudflare
Workers, etc.) instead of a local handler.

| Name         | Type                                | Required | Description                              |
| ------------ | ----------------------------------- | -------- | ---------------------------------------- |
| `auth`       | [`HttpAuthConfig`](#httpauthconfig) | No       | Authentication configuration.            |
| `headers`    | `Record<string, string>`            | No       | Custom headers to send with the request. |
| `method`     | [`HttpMethod`](#httpmethod)         | No       | HTTP method. Defaults to `POST`.         |
| `timeout_ms` | `number`                            | No       | Timeout in milliseconds.                 |
| `url`        | `string`                            | Yes      | URL to invoke.                           |

### HttpMethod

HTTP method accepted by HttpInvocationConfig. Distinct from the core
`builtin_triggers` HTTP method enum, which also covers HEAD/OPTIONS.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
```

### HttpRequest

Incoming buffered HTTP request received by a function handler.

| Name           | Type                                 | Required | Description |
| -------------- | ------------------------------------ | -------- | ----------- |
| `body`         | `TBody`                              | Yes      | -           |
| `headers`      | `Record<string, string \| string[]>` | Yes      | -           |
| `method`       | `string`                             | Yes      | -           |
| `path_params`  | `Record<string, string>`             | Yes      | -           |
| `query_params` | `Record<string, string \| string[]>` | Yes      | -           |
| `request_body` | `HttpStreamReader`                   | Yes      | -           |

### HttpResponse

Structured buffered HTTP response returned from function handlers.

| Name          | Type                     | Required | Description       |
| ------------- | ------------------------ | -------- | ----------------- |
| `body`        | `TBody`                  | No       | Response body.    |
| `headers`     | `Record<string, string>` | No       | Response headers. |
| `status_code` | `TStatus`                | Yes      | HTTP status code. |

## observability

Logger, OpenTelemetry config, and span helpers.

**Import**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { ... } from '@iii-dev/helpers/observability'
```

### Functions

### currentSpanId

Extract the current span ID from the active span context.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
currentSpanId() => string | undefined
```

### currentSpanIsRecording

Returns `false` when there is no active span or the sampler dropped it.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
currentSpanIsRecording() => boolean
```

### currentTraceId

Extract the current trace ID from the active span context.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
currentTraceId() => string | undefined
```

### executeTracedRequest

Execute a fetch request inside an OTel CLIENT span.

Mirrors the Rust execute\_traced\_request shape: injects W3C traceparent into
outgoing headers, records HTTP semantic-convention attributes, and sets
ERROR span status for HTTP responses with status >= 400 or network errors.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
executeTracedRequest(input: RequestInfo | URL, init: TracedFetchInit) => Promise<Response>
```

#### Parameters

| Name    | Type                                  | Required | Description |
| ------- | ------------------------------------- | -------- | ----------- |
| `input` | `RequestInfo \| URL`                  | Yes      | -           |
| `init`  | [`TracedFetchInit`](#tracedfetchinit) | Yes      | -           |

### extractBaggage

Extract baggage from a W3C baggage header string.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
extractBaggage(baggage: string) => Context
```

#### Parameters

| Name      | Type     | Required | Description |
| --------- | -------- | -------- | ----------- |
| `baggage` | `string` | Yes      | -           |

### extractContext

Extract both trace context and baggage from their respective headers.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
extractContext(traceparent: string, baggage: string) => Context
```

#### Parameters

| Name          | Type     | Required | Description |
| ------------- | -------- | -------- | ----------- |
| `traceparent` | `string` | Yes      | -           |
| `baggage`     | `string` | Yes      | -           |

### extractTraceparent

Extract a trace context from a W3C traceparent header string.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
extractTraceparent(traceparent: string) => Context
```

#### Parameters

| Name          | Type     | Required | Description |
| ------------- | -------- | -------- | ----------- |
| `traceparent` | `string` | Yes      | -           |

### flushOtel

Force-flush all OTel providers without tearing them down.

Counterpart to shutdownOtel. Use before short-lived process exits
where you want pending spans/metrics/logs delivered but plan to keep using
OTel afterwards.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
flushOtel() => Promise<void>
```

### getAllBaggage

Get all baggage entries from the current context.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
getAllBaggage() => Record<string, string>
```

### getBaggageEntry

Get a baggage entry from the current context.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
getBaggageEntry(key: string) => string | undefined
```

#### Parameters

| Name  | Type     | Required | Description |
| ----- | -------- | -------- | ----------- |
| `key` | `string` | Yes      | -           |

### getLogger

Get the OpenTelemetry logger instance.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
getLogger() => Logger | null
```

### initOtel

Initialize OpenTelemetry with the given configuration.
This should be called once at application startup.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
initOtel(config: OtelConfig) => void
```

#### Parameters

| Name     | Type                        | Required | Description |
| -------- | --------------------------- | -------- | ----------- |
| `config` | [`OtelConfig`](#otelconfig) | Yes      | -           |

### injectBaggage

Inject the current baggage into a W3C baggage header string.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
injectBaggage() => string | undefined
```

### injectTraceparent

Inject the current trace context into a W3C traceparent header string.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
injectTraceparent() => string | undefined
```

### patchGlobalFetch

Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
patchGlobalFetch(tracer: Tracer) => void
```

#### Parameters

| Name     | Type     | Required | Description |
| -------- | -------- | -------- | ----------- |
| `tracer` | `Tracer` | Yes      | -           |

### recordSpanEvent

No-op when the current span is not recording.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
recordSpanEvent(name: string, attrs: Attributes) => void
```

#### Parameters

| Name    | Type         | Required | Description |
| ------- | ------------ | -------- | ----------- |
| `name`  | `string`     | Yes      | -           |
| `attrs` | `Attributes` | Yes      | -           |

### redact

Recursively redact values of sensitive keys. Returns a new value.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
redact(value: unknown) => unknown
```

#### Parameters

| Name    | Type      | Required | Description |
| ------- | --------- | -------- | ----------- |
| `value` | `unknown` | Yes      | -           |

### redactAndTruncate

Redact then serialize to JSON, optionally capped at `maxBytes`.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
redactAndTruncate(value: unknown, maxBytes: number | null) => { json: string; truncated: boolean }
```

#### Parameters

| Name       | Type             | Required | Description |
| ---------- | ---------------- | -------- | ----------- |
| `value`    | `unknown`        | Yes      | -           |
| `maxBytes` | `number \| null` | Yes      | -           |

### registerWorkerGauges

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions) => void
```

#### Parameters

| Name      | Type                                          | Required | Description |
| --------- | --------------------------------------------- | -------- | ----------- |
| `meter`   | `Meter`                                       | Yes      | -           |
| `options` | [`WorkerGaugesOptions`](#workergaugesoptions) | Yes      | -           |

### removeBaggageEntry

Remove a baggage entry from the current context.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
removeBaggageEntry(key: string) => Context
```

#### Parameters

| Name  | Type     | Required | Description |
| ----- | -------- | -------- | ----------- |
| `key` | `string` | Yes      | -           |

### resolveMaxBytesFromEnv

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
resolveMaxBytesFromEnv() => number | null
```

### safeStringify

Safely stringify a value, handling circular references, BigInt, and other edge cases.
Returns "\[unserializable]" if serialization fails for any reason.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
safeStringify(value: unknown) => string
```

#### Parameters

| Name    | Type      | Required | Description |
| ------- | --------- | -------- | ----------- |
| `value` | `unknown` | Yes      | -           |

### setBaggageEntry

Set a baggage entry in the current context.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
setBaggageEntry(key: string, value: string) => Context
```

#### Parameters

| Name    | Type     | Required | Description |
| ------- | -------- | -------- | ----------- |
| `key`   | `string` | Yes      | -           |
| `value` | `string` | Yes      | -           |

### setCurrentSpanAttribute

No-op when the current span is not recording.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
setCurrentSpanAttribute(key: string, value: AttributeValue) => void
```

#### Parameters

| Name    | Type             | Required | Description |
| ------- | ---------------- | -------- | ----------- |
| `key`   | `string`         | Yes      | -           |
| `value` | `AttributeValue` | Yes      | -           |

### setCurrentSpanError

No-op when there is no active span.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
setCurrentSpanError(message: string) => void
```

#### Parameters

| Name      | Type     | Required | Description |
| --------- | -------- | -------- | ----------- |
| `message` | `string` | Yes      | -           |

### shutdownOtel

Shutdown OpenTelemetry, flushing any pending data.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
shutdownOtel() => Promise<void>
```

### stopWorkerGauges

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
stopWorkerGauges() => void
```

### unpatchGlobalFetch

Restore globalThis.fetch to its original implementation.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
unpatchGlobalFetch() => void
```

### withSpan

Start a new span with the given name and run the callback within it.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
withSpan(name: string, options: { kind?: SpanKind; traceparent?: string }, fn: (span: Span) => Promise<T>) => Promise<T>
```

#### Parameters

| Name      | Type                                        | Required | Description |
| --------- | ------------------------------------------- | -------- | ----------- |
| `name`    | `string`                                    | Yes      | -           |
| `options` | `{ kind?: SpanKind; traceparent?: string }` | Yes      | -           |
| `fn`      | `(span: Span) => Promise<T>`                | Yes      | -           |

### Types

[`BaggageSpanProcessor`](#baggagespanprocessor) · [`Logger`](#logger) · [`OtelConfig`](#otelconfig) · [`OtelLogEvent`](#otellogevent) · [`ReconnectionConfig`](#reconnectionconfig) · [`TracedFetchInit`](#tracedfetchinit) · [`WorkerGaugesOptions`](#workergaugesoptions) · [`WorkerMetrics`](#workermetrics) · [`WorkerMetricsCollector`](#workermetricscollector) · [`WorkerMetricsCollectorOptions`](#workermetricscollectoroptions)

### BaggageSpanProcessor

### Logger

Structured logger that emits logs as OpenTelemetry LogRecords.

Every log call automatically captures the active trace and span context,
correlating your logs with distributed traces without any manual wiring.
When OTel is not initialized, Logger gracefully falls back to `console.*`.

Pass structured data as the second argument to any log method. Using an
object of key-value pairs (instead of string interpolation) lets you
filter, aggregate, and build dashboards in your observability backend.

### OtelConfig

Configuration for OpenTelemetry initialization.

| Name                          | Type                                                  | Required | Description                                                                                                                                                                                                                                                                                                          |
| ----------------------------- | ----------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled`                     | `boolean`                                             | No       | Whether OpenTelemetry export is enabled. Defaults to true. Set to false or OTEL\_ENABLED=false/0/no/off to disable.                                                                                                                                                                                                  |
| `engineWsUrl`                 | `string`                                              | No       | III Engine WebSocket URL. Defaults to III\_URL or "ws\://localhost:49134".                                                                                                                                                                                                                                           |
| `fetchInstrumentationEnabled` | `boolean`                                             | No       | Whether to auto-instrument globalThis.fetch calls. Defaults to true. Works on Node.js, Bun, and Deno. Set to false to disable.                                                                                                                                                                                       |
| `instrumentations`            | `Instrumentation<InstrumentationConfig>[]`            | No       | OpenTelemetry instrumentations to register (e.g., PrismaInstrumentation).                                                                                                                                                                                                                                            |
| `logsBatchSize`               | `number`                                              | No       | Maximum number of log records exported per batch. Defaults to 1.                                                                                                                                                                                                                                                     |
| `logsFlushIntervalMs`         | `number`                                              | No       | Log processor flush delay in milliseconds. Defaults to 100ms. Env override: OTEL\_LOGS\_FLUSH\_INTERVAL\_MS.                                                                                                                                                                                                         |
| `metricsEnabled`              | `boolean`                                             | No       | Whether OpenTelemetry metrics export is enabled. Defaults to true. Set to false or OTEL\_METRICS\_ENABLED=false/0/no/off to disable.                                                                                                                                                                                 |
| `metricsExportIntervalMs`     | `number`                                              | No       | Metrics export interval in milliseconds. Defaults to 60000 (60 seconds).                                                                                                                                                                                                                                             |
| `reconnectionConfig`          | Partial\<[`ReconnectionConfig`](#reconnectionconfig)> | No       | Optional reconnection configuration for the WebSocket connection.                                                                                                                                                                                                                                                    |
| `serviceInstanceId`           | `string`                                              | No       | The service instance ID to report. Defaults to SERVICE\_INSTANCE\_ID env var or auto-generated UUID.                                                                                                                                                                                                                 |
| `serviceName`                 | `string`                                              | No       | The service name to report. Defaults to OTEL\_SERVICE\_NAME or "iii-node".                                                                                                                                                                                                                                           |
| `serviceNamespace`            | `string`                                              | No       | The service namespace to report. Defaults to SERVICE\_NAMESPACE env var.                                                                                                                                                                                                                                             |
| `serviceVersion`              | `string`                                              | No       | The service version to report. Defaults to SERVICE\_VERSION env var or "unknown".                                                                                                                                                                                                                                    |
| `spansFlushIntervalMs`        | `number`                                              | No       | Span processor flush delay in milliseconds. Defaults to 100ms. This is how<br />long an ended span waits in the batch buffer before it is flushed to the<br />engine, the OpenTelemetry default of 5000ms is what makes traces appear<br />seconds after the action. Env override: OTEL\_SPANS\_FLUSH\_INTERVAL\_MS. |

### OtelLogEvent

OTEL Log Event from the engine

| Name                            | Type                      | Required | Description                                                                                        |
| ------------------------------- | ------------------------- | -------- | -------------------------------------------------------------------------------------------------- |
| `attributes`                    | `Record<string, unknown>` | Yes      | Structured attributes                                                                              |
| `body`                          | `string`                  | Yes      | Log message body                                                                                   |
| `instrumentation_scope_name`    | `string`                  | No       | Instrumentation scope name (if available)                                                          |
| `instrumentation_scope_version` | `string`                  | No       | Instrumentation scope version (if available)                                                       |
| `observed_timestamp_unix_nano`  | `number`                  | Yes      | Observed timestamp in Unix nanoseconds                                                             |
| `resource`                      | `Record<string, string>`  | Yes      | Resource attributes from the emitting service                                                      |
| `service_name`                  | `string`                  | Yes      | Service name that emitted the log                                                                  |
| `severity_number`               | `number`                  | Yes      | OTEL severity number (1-24): TRACE=1-4, DEBUG=5-8, INFO=9-12, WARN=13-16, ERROR=17-20, FATAL=21-24 |
| `severity_text`                 | `string`                  | Yes      | Severity text (e.g., "INFO", "WARN", "ERROR")                                                      |
| `span_id`                       | `string`                  | No       | Span ID for correlation (if available)                                                             |
| `timestamp_unix_nano`           | `number`                  | Yes      | Timestamp in Unix nanoseconds                                                                      |
| `trace_id`                      | `string`                  | No       | Trace ID for correlation (if available)                                                            |

### ReconnectionConfig

Configuration for WebSocket reconnection behavior

| Name                | Type     | Required | Description                                           |
| ------------------- | -------- | -------- | ----------------------------------------------------- |
| `backoffMultiplier` | `number` | Yes      | Exponential backoff multiplier (default: 2)           |
| `initialDelayMs`    | `number` | Yes      | Starting delay in milliseconds (default: 1000ms)      |
| `jitterFactor`      | `number` | Yes      | Random jitter factor 0-1 (default: 0.3)               |
| `maxDelayMs`        | `number` | Yes      | Maximum delay cap in milliseconds (default: 30000ms)  |
| `maxRetries`        | `number` | Yes      | Maximum retry attempts, -1 for infinite (default: -1) |

### TracedFetchInit

| Name     | Type     | Required | Description |
| -------- | -------- | -------- | ----------- |
| `tracer` | `Tracer` | No       | -           |

### WorkerGaugesOptions

| Name         | Type     | Required | Description |
| ------------ | -------- | -------- | ----------- |
| `workerId`   | `string` | Yes      | -           |
| `workerName` | `string` | No       | -           |

### WorkerMetrics

Worker metrics data structure used internally for OTEL metric collection.

| Name                | Type     | Required | Description |
| ------------------- | -------- | -------- | ----------- |
| `cpu_percent`       | `number` | No       | -           |
| `cpu_system_micros` | `number` | No       | -           |
| `cpu_user_micros`   | `number` | No       | -           |
| `event_loop_lag_ms` | `number` | No       | -           |
| `memory_external`   | `number` | No       | -           |
| `memory_heap_total` | `number` | No       | -           |
| `memory_heap_used`  | `number` | No       | -           |
| `memory_rss`        | `number` | No       | -           |
| `runtime`           | `string` | Yes      | -           |
| `timestamp_ms`      | `number` | Yes      | -           |
| `uptime_seconds`    | `number` | No       | -           |

### WorkerMetricsCollector

Collects worker resource metrics including CPU, memory, and event loop lag.

Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop
delay measurements instead of manual `setImmediate` timing.

### WorkerMetricsCollectorOptions

Configuration options for the WorkerMetricsCollector.

| Name                    | Type     | Required | Description                                                                                                                         |
| ----------------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `eventLoopResolutionMs` | `number` | No       | Event loop delay histogram resolution in milliseconds.<br />Lower values provide more accurate measurements but use more resources. |

## queue

Queue enqueue result types.

**Import**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { ... } from '@iii-dev/helpers/queue'
```

### Types

[`EnqueueResult`](#enqueueresult)

### EnqueueResult

Result returned when a function is invoked with `TriggerAction.Enqueue`.

| Name               | Type     | Required | Description                                 |
| ------------------ | -------- | -------- | ------------------------------------------- |
| `messageReceiptId` | `string` | Yes      | Unique receipt ID for the enqueued message. |

## stream

Stream trigger configs, change events, IO inputs, and update operations.

**Import**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { ... } from '@iii-dev/helpers/stream'
```

### Types

[`MergePath`](#mergepath) · [`StreamAuthInput`](#streamauthinput) · [`StreamAuthResult`](#streamauthresult) · [`StreamChangeEvent`](#streamchangeevent) · [`StreamChangeEventDetail`](#streamchangeeventdetail) · [`StreamContext`](#streamcontext) · [`StreamDeleteInput`](#streamdeleteinput) · [`StreamDeleteResult`](#streamdeleteresult) · [`StreamGetInput`](#streamgetinput) · [`StreamJoinLeaveEvent`](#streamjoinleaveevent) · [`StreamJoinLeaveTriggerConfig`](#streamjoinleavetriggerconfig) · [`StreamJoinResult`](#streamjoinresult) · [`StreamListGroupsInput`](#streamlistgroupsinput) · [`StreamListInput`](#streamlistinput) · [`StreamSetInput`](#streamsetinput) · [`StreamSetResult`](#streamsetresult) · [`StreamTriggerConfig`](#streamtriggerconfig) · [`StreamUpdateInput`](#streamupdateinput) · [`StreamUpdateResult`](#streamupdateresult) · [`UpdateAppend`](#updateappend) · [`UpdateDecrement`](#updatedecrement) · [`UpdateIncrement`](#updateincrement) · [`UpdateMerge`](#updatemerge) · [`UpdateOp`](#updateop) · [`UpdateOpError`](#updateoperror) · [`UpdateRemove`](#updateremove) · [`UpdateSet`](#updateset)

### MergePath

Path target for a UpdateMerge op. Accepts:

* a single string (legacy / first-level field)
* an array of literal segments (nested path; each element is one
  literal key, dots are NOT interpreted as separators)

Omit `path`, pass `""`, or pass `[]` to target the root value.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type MergePath = string | string[]
```

### StreamAuthInput

Input for stream authentication.

| Name           | Type                       | Required | Description       |
| -------------- | -------------------------- | -------- | ----------------- |
| `addr`         | `string`                   | Yes      | Client address.   |
| `headers`      | `Record<string, string>`   | Yes      | Request headers.  |
| `path`         | `string`                   | Yes      | Request path.     |
| `query_params` | `Record<string, string[]>` | Yes      | Query parameters. |

### StreamAuthResult

Result of stream authentication.

| Name      | Type  | Required | Description                                                       |
| --------- | ----- | -------- | ----------------------------------------------------------------- |
| `context` | `any` | No       | Arbitrary context passed to stream handlers after authentication. |

### StreamChangeEvent

Handler input for `stream` triggers, fired when an item changes via `stream::set`, `stream::update`, or `stream::delete`.

| Name         | Type                                                  | Required | Description                                         |
| ------------ | ----------------------------------------------------- | -------- | --------------------------------------------------- |
| `event`      | [`StreamChangeEventDetail`](#streamchangeeventdetail) | Yes      | The event detail containing mutation type and data. |
| `groupId`    | `string`                                              | Yes      | The group where the change occurred.                |
| `id`         | `string`                                              | No       | The item ID that changed.                           |
| `streamName` | `string`                                              | Yes      | The stream where the change occurred.               |
| `timestamp`  | `number`                                              | Yes      | Unix timestamp of the event.                        |
| `type`       | `"stream"`                                            | Yes      | The event type.                                     |

### StreamChangeEventDetail

Detail of a stream change event containing the mutation type and data.

| Name   | Type                               | Required | Description                                       |
| ------ | ---------------------------------- | -------- | ------------------------------------------------- |
| `data` | `any`                              | Yes      | The data associated with the event.               |
| `type` | `"create" \| "update" \| "delete"` | Yes      | The kind of mutation (create, update, or delete). |

### StreamContext

Context type extracted from StreamAuthResult.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type StreamContext = StreamAuthResult["context"]
```

### StreamDeleteInput

Input for deleting a stream item.

| Name          | Type     | Required | Description         |
| ------------- | -------- | -------- | ------------------- |
| `group_id`    | `string` | Yes      | Group identifier.   |
| `item_id`     | `string` | Yes      | Item identifier.    |
| `stream_name` | `string` | Yes      | Name of the stream. |

### StreamDeleteResult

Result of a stream delete operation.

| Name        | Type  | Required | Description                     |
| ----------- | ----- | -------- | ------------------------------- |
| `old_value` | `any` | No       | Previous value (if it existed). |

### StreamGetInput

Input for retrieving a single stream item.

| Name          | Type     | Required | Description         |
| ------------- | -------- | -------- | ------------------- |
| `group_id`    | `string` | Yes      | Group identifier.   |
| `item_id`     | `string` | Yes      | Item identifier.    |
| `stream_name` | `string` | Yes      | Name of the stream. |

### StreamJoinLeaveEvent

Event payload for stream join/leave events.

| Name              | Type     | Required | Description                         |
| ----------------- | -------- | -------- | ----------------------------------- |
| `context`         | `any`    | No       | Auth context from StreamAuthResult. |
| `group_id`        | `string` | Yes      | Group identifier.                   |
| `id`              | `string` | No       | Item identifier (if applicable).    |
| `stream_name`     | `string` | Yes      | Name of the stream.                 |
| `subscription_id` | `string` | Yes      | Unique subscription identifier.     |

### StreamJoinLeaveTriggerConfig

Trigger config for `stream:join` and `stream:leave` triggers.

| Name                    | Type     | Required | Description                                                                           |
| ----------------------- | -------- | -------- | ------------------------------------------------------------------------------------- |
| `condition_function_id` | `string` | No       | Function ID for conditional execution. If it returns `false`, the handler is skipped. |

### StreamJoinResult

Result of a stream join request.

| Name           | Type      | Required | Description                        |
| -------------- | --------- | -------- | ---------------------------------- |
| `unauthorized` | `boolean` | Yes      | Whether the join was unauthorized. |

### StreamListGroupsInput

Input for listing all groups in a stream.

| Name          | Type     | Required | Description         |
| ------------- | -------- | -------- | ------------------- |
| `stream_name` | `string` | Yes      | Name of the stream. |

### StreamListInput

Input for listing all items in a stream group.

| Name          | Type     | Required | Description         |
| ------------- | -------- | -------- | ------------------- |
| `group_id`    | `string` | Yes      | Group identifier.   |
| `stream_name` | `string` | Yes      | Name of the stream. |

### StreamSetInput

Input for setting a stream item.

| Name          | Type     | Required | Description         |
| ------------- | -------- | -------- | ------------------- |
| `data`        | `any`    | Yes      | Data to store.      |
| `group_id`    | `string` | Yes      | Group identifier.   |
| `item_id`     | `string` | Yes      | Item identifier.    |
| `stream_name` | `string` | Yes      | Name of the stream. |

### StreamSetResult

Result of a stream set operation.

| Name        | Type    | Required | Description                     |
| ----------- | ------- | -------- | ------------------------------- |
| `new_value` | `TData` | Yes      | New value that was stored.      |
| `old_value` | `TData` | No       | Previous value (if it existed). |

### StreamTriggerConfig

Trigger config for `stream` triggers. Filters which item changes fire the handler.

| Name                    | Type     | Required | Description                                                                           |
| ----------------------- | -------- | -------- | ------------------------------------------------------------------------------------- |
| `condition_function_id` | `string` | No       | Function ID for conditional execution. If it returns `false`, the handler is skipped. |
| `group_id`              | `string` | No       | If set, only changes within this group fire the handler.                              |
| `item_id`               | `string` | No       | If set, only changes to this specific item fire the handler.                          |
| `stream_name`           | `string` | Yes      | Stream name to watch. Only changes on this stream fire the handler.                   |

### StreamUpdateInput

Input for atomically updating a stream item.

| Name          | Type                       | Required | Description                                            |
| ------------- | -------------------------- | -------- | ------------------------------------------------------ |
| `group_id`    | `string`                   | Yes      | Group identifier.                                      |
| `item_id`     | `string`                   | Yes      | Item identifier.                                       |
| `ops`         | [`UpdateOp`](#updateop)\[] | Yes      | Ordered list of update operations to apply atomically. |
| `stream_name` | `string`                   | Yes      | Name of the stream.                                    |

### StreamUpdateResult

Result of a stream update operation.

| Name        | Type                                 | Required | Description                                                                                                                                                                                                                                                                                                                                                                                                                |
| ----------- | ------------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `errors`    | [`UpdateOpError`](#updateoperror)\[] | No       | Per-op errors. Emitted by `merge` and `append` for validation<br />rejections (path depth/size, value depth, or a<br />`__proto__`/`constructor`/`prototype` segment or top-level key)<br />and by `append` for the case-2 `append.type_mismatch` and<br />`append.target_not_object` surfaces. Successfully applied ops are<br />still reflected in `new_value`. The field is omitted from the<br />JSON wire when empty. |
| `new_value` | `TData`                              | Yes      | New value after the update.                                                                                                                                                                                                                                                                                                                                                                                                |
| `old_value` | `TData`                              | No       | Previous value (if it existed).                                                                                                                                                                                                                                                                                                                                                                                            |

### UpdateAppend

Append an element to an array, concatenate a string, or push a new
value at a nested path. The target is the root (when `path` is
omitted, empty, or `[]`), a single first-level key (when `path` is
a non-empty string), or an arbitrary nested location (when `path`
is an array of literal segments).

Engine semantics:

* Missing or non-object intermediates along a nested path are
  auto-replaced with `{}` so a stray `null` or scalar never blocks
  future appends.
* At the leaf:
  * missing/null + nested path → `[value]` (always an array)
  * missing/null + single-string path → string-as-string for the
    string-concat tier, otherwise `[value]`
  * existing array → push
  * existing string + string value → concatenate
  * existing object/scalar at the leaf → `append.type_mismatch`
* Each path segment is a literal key. `["a.b"]` targets a single
  key named `"a.b"`, not `a → b`.

Validation: invalid paths (depth > 32 segments, segment > 256
bytes, or any `__proto__`/`constructor`/`prototype` segment) are
rejected with a structured error in the `errors` field of the
`state::update` / `stream::update` response. The append does not
apply when an error is returned for that op.

| Name    | Type                      | Required | Description                                                                                                                                                                                   |
| ------- | ------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `path`  | [`MergePath`](#mergepath) | No       | Optional path to the append target. Accepts a single first-level<br />key (legacy `string`) or an array of literal segments for nested<br />append. See MergePath (the same shape is reused). |
| `type`  | `"append"`                | Yes      | -                                                                                                                                                                                             |
| `value` | `any`                     | Yes      | Value to append. String targets only accept string values.                                                                                                                                    |

### UpdateDecrement

Decrement a numeric field by a given amount.

| Name   | Type          | Required | Description             |
| ------ | ------------- | -------- | ----------------------- |
| `by`   | `number`      | Yes      | Amount to decrement by. |
| `path` | `string`      | Yes      | First-level field path. |
| `type` | `"decrement"` | Yes      | -                       |

### UpdateIncrement

Increment a numeric field by a given amount.

| Name   | Type          | Required | Description             |
| ------ | ------------- | -------- | ----------------------- |
| `by`   | `number`      | Yes      | Amount to increment by. |
| `path` | `string`      | Yes      | First-level field path. |
| `type` | `"increment"` | Yes      | -                       |

### UpdateMerge

Shallow-merge an object into the target. The target is the root
(when `path` is omitted/empty) or an arbitrary nested location
specified by an array of literal segments.

Engine semantics:

* Missing or non-object intermediates along the path are
  auto-replaced with `{}` so a stray `null` or scalar never
  blocks future merges.
* The merge is shallow at the target, top-level keys of `value`
  replace same-named keys; siblings are preserved.
* Each path segment is a literal key. `["a.b"]` writes a single
  key named `"a.b"`, not `a → b`.

Validation: invalid paths/values (depth > 32 segments, segment >
256 bytes, value depth > 16, > 1024 top-level keys, or any
`__proto__`/`constructor`/`prototype` segment or top-level key)
are rejected with a structured error in the `errors` field of the
`state::update` / `stream::update` response. The merge does not
apply when an error is returned for that op.

| Name    | Type                      | Required | Description                                       |
| ------- | ------------------------- | -------- | ------------------------------------------------- |
| `path`  | [`MergePath`](#mergepath) | No       | Optional path to the merge target. See MergePath. |
| `type`  | `"merge"`                 | Yes      | -                                                 |
| `value` | `any`                     | Yes      | Object to merge. Must be a JSON object.           |

### UpdateOp

Union of all atomic update operations supported by streams.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type UpdateOp = UpdateSet | UpdateIncrement | UpdateDecrement | UpdateAppend | UpdateRemove | UpdateMerge
```

### UpdateOpError

Per-op error returned by `state::update` / `stream::update`.

| Name       | Type     | Required | Description                                                       |
| ---------- | -------- | -------- | ----------------------------------------------------------------- |
| `code`     | `string` | Yes      | Stable error code, e.g. `"merge.path.too_deep"`.                  |
| `doc_url`  | `string` | No       | Optional documentation URL.                                       |
| `message`  | `string` | Yes      | Human-readable description with concrete numbers when applicable. |
| `op_index` | `number` | Yes      | Index of the offending op within the original `ops` array.        |

### UpdateRemove

Remove a field at the given path.

| Name   | Type       | Required | Description             |
| ------ | ---------- | -------- | ----------------------- |
| `path` | `string`   | Yes      | First-level field path. |
| `type` | `"remove"` | Yes      | -                       |

### UpdateSet

Set a field at the given path to a value.

| Name    | Type     | Required | Description                                                           |
| ------- | -------- | -------- | --------------------------------------------------------------------- |
| `path`  | `string` | Yes      | First-level field path. Use an empty string to target the root value. |
| `type`  | `"set"`  | Yes      | -                                                                     |
| `value` | `any`    | Yes      | Value to set.                                                         |

## worker-connection-manager

RBAC auth and registration callback types.

**Import**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { ... } from '@iii-dev/helpers/worker-connection-manager'
```

### Types

[`AuthInput`](#authinput) · [`AuthResult`](#authresult) · [`OnFunctionRegistrationInput`](#onfunctionregistrationinput) · [`OnFunctionRegistrationResult`](#onfunctionregistrationresult) · [`OnTriggerRegistrationInput`](#ontriggerregistrationinput) · [`OnTriggerRegistrationResult`](#ontriggerregistrationresult) · [`OnTriggerTypeRegistrationInput`](#ontriggertyperegistrationinput) · [`OnTriggerTypeRegistrationResult`](#ontriggertyperegistrationresult)

### AuthInput

Input passed to the RBAC auth function during WebSocket upgrade.
Contains the HTTP headers, query parameters, and client IP from the
connecting worker's upgrade request.

| Name           | Type                       | Required | Description                                                                                          |
| -------------- | -------------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
| `headers`      | `Record<string, string>`   | Yes      | HTTP headers from the WebSocket upgrade request.                                                     |
| `ip_address`   | `string`                   | Yes      | IP address of the connecting client.                                                                 |
| `query_params` | `Record<string, string[]>` | Yes      | Query parameters from the upgrade URL. Each key maps to an array of values to support repeated keys. |

### AuthResult

Return value from the RBAC auth function. Controls which functions the
authenticated worker can invoke and what context is forwarded to the
middleware.

| Name                              | Type                      | Required | Description                                                                                                             |
| --------------------------------- | ------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- |
| `allow_function_registration`     | `boolean`                 | No       | Whether the worker may register new functions. Defaults to `true` if omitted.                                           |
| `allow_trigger_type_registration` | `boolean`                 | No       | Whether the worker may register new trigger types. Defaults to `false` if omitted.                                      |
| `allowed_functions`               | `string[]`                | No       | Additional function IDs to allow beyond the `expose_functions` config. Defaults to `[]` if omitted.                     |
| `allowed_trigger_types`           | `string[]`                | No       | Trigger type IDs the worker may register triggers for. When omitted, all types are allowed.                             |
| `context`                         | `Record<string, unknown>` | No       | Arbitrary context forwarded to the middleware function on every invocation. Defaults to `{}` if omitted.                |
| `forbidden_functions`             | `string[]`                | No       | Function IDs to deny even if they match `expose_functions`. Takes precedence over allowed. Defaults to `[]` if omitted. |
| `function_registration_prefix`    | `string`                  | No       | Optional prefix applied to all function IDs registered by this worker.                                                  |

### OnFunctionRegistrationInput

Input passed to the `on_function_registration_function_id` hook
when a worker attempts to register a function through the RBAC port.
Return an OnFunctionRegistrationResult with the (possibly mapped)
fields, or throw to deny the registration.

| Name          | Type                      | Required | Description                                              |
| ------------- | ------------------------- | -------- | -------------------------------------------------------- |
| `context`     | `Record<string, unknown>` | Yes      | Auth context from `AuthResult.context` for this session. |
| `description` | `string`                  | No       | Human-readable description of the function.              |
| `function_id` | `string`                  | Yes      | ID of the function being registered.                     |
| `metadata`    | `Record<string, unknown>` | No       | Arbitrary metadata attached to the function.             |

### OnFunctionRegistrationResult

Result returned from the `on_function_registration_function_id` hook.
All fields are optional -- omitted fields keep the original value from the
registration request.

| Name          | Type                      | Required | Description         |
| ------------- | ------------------------- | -------- | ------------------- |
| `description` | `string`                  | No       | Mapped description. |
| `function_id` | `string`                  | No       | Mapped function ID. |
| `metadata`    | `Record<string, unknown>` | No       | Mapped metadata.    |

### OnTriggerRegistrationInput

Input passed to the `on_trigger_registration_function_id` hook
when a worker attempts to register a trigger through the RBAC port.
Return an OnTriggerRegistrationResult with the (possibly mapped)
fields, or throw to deny the registration.

| Name           | Type                      | Required | Description                                              |
| -------------- | ------------------------- | -------- | -------------------------------------------------------- |
| `config`       | `unknown`                 | Yes      | Trigger-specific configuration.                          |
| `context`      | `Record<string, unknown>` | Yes      | Auth context from `AuthResult.context` for this session. |
| `function_id`  | `string`                  | Yes      | ID of the function this trigger is bound to.             |
| `metadata`     | `Record<string, unknown>` | No       | Arbitrary metadata attached to the trigger.              |
| `trigger_id`   | `string`                  | Yes      | ID of the trigger being registered.                      |
| `trigger_type` | `string`                  | Yes      | Trigger type identifier.                                 |

### OnTriggerRegistrationResult

Result returned from the `on_trigger_registration_function_id` hook.
All fields are optional -- omitted fields keep the original value from the
registration request.

| Name           | Type      | Required | Description                   |
| -------------- | --------- | -------- | ----------------------------- |
| `config`       | `unknown` | No       | Mapped trigger configuration. |
| `function_id`  | `string`  | No       | Mapped function ID.           |
| `trigger_id`   | `string`  | No       | Mapped trigger ID.            |
| `trigger_type` | `string`  | No       | Mapped trigger type.          |

### OnTriggerTypeRegistrationInput

Input passed to the `on_trigger_type_registration_function_id` hook
when a worker attempts to register a new trigger type through the RBAC port.
Return an OnTriggerTypeRegistrationResult with the (possibly mapped)
fields, or throw to deny the registration.

| Name              | Type                      | Required | Description                                              |
| ----------------- | ------------------------- | -------- | -------------------------------------------------------- |
| `context`         | `Record<string, unknown>` | Yes      | Auth context from `AuthResult.context` for this session. |
| `description`     | `string`                  | Yes      | Human-readable description of the trigger type.          |
| `trigger_type_id` | `string`                  | Yes      | ID of the trigger type being registered.                 |

### OnTriggerTypeRegistrationResult

Result returned from the `on_trigger_type_registration_function_id` hook.
All fields are optional -- omitted fields keep the original value from the
registration request.

| Name              | Type     | Required | Description             |
| ----------------- | -------- | -------- | ----------------------- |
| `description`     | `string` | No       | Mapped description.     |
| `trigger_type_id` | `string` | No       | Mapped trigger type ID. |
