# env

## Interfaces

### AiBinding

`AI` binding, present when `plugin.toml` lists tasks under `[ai].calls` and
the operator approved them. The host routes each run to the deployed plugin
that serves the model; the shape follows the `AI` binding of Cloudflare
Workers.

#### Methods

##### run()

```ts
run(model, input): Promise<AiTextEmbeddingsResponse>;
```

Run one model on one input.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `model` | `string` | `@<plugin id>/<model id>`, or a task alias such as `@library/text-embeddings` for the model the library chose. |
| `input` | [`AiTextEmbeddingsRequest`](#aitextembeddingsrequest) | The input of the model's task. |

###### Returns

`Promise`\<[`AiTextEmbeddingsResponse`](#aitextembeddingsresponse)\>

The model's output.

###### Throws

PluginError `invalid_params` for a malformed run, `not_found` when
  nothing deployed serves the model, `forbidden` for a task that is not
  granted, `rate_limited` past the plugin's budget (work over many items
  belongs in a job), `deadline_exceeded` or `unavailable` when the model
  plugin cannot answer.

***

### AiTextEmbeddingsRequest

Input of a text-embedding model on [AiBinding.run](#run).

#### Properties

##### role?

```ts
role?: "document" | "query";
```

What the texts are: `document` (the default) for stored content, `query`
for a search query matched against documents. Some models embed the two
differently.

##### text

```ts
text: string | string[];
```

One text or a batch (at most `MAX_AI_EMBED_TEXTS`), none empty.

***

### AiTextEmbeddingsResponse

Output of a text-embedding model on [AiBinding.run](#run).

#### Properties

##### data

```ts
data: number[][];
```

One vector per input text, in input order.

##### fallbacks

```ts
fallbacks: number[];
```

Indexes of the texts the tokenizer could not cover with the loaded
language packs; their vectors are worth recomputing once a pack is added.

##### model

```ts
model: string;
```

Full name of the model that ran, also when an alias was asked for.

##### revision

```ts
revision: string;
```

Revision of the model that made the vectors. Vectors are comparable only
when their model and revision match, so store both beside each vector.

##### shape

```ts
shape: [number, number];
```

`[number of texts, numbers per vector]`.

***

### BookclerkEnv

Guest `env` bindings for `api_version = 3` manifests. Every host-provided
facility is a binding here; there is no `HOST` object. Bindings appear only
when `plugin.toml` declares them and the operator has consented.

Run `bookclerk-plugin types` to generate a precise `Env` for one manifest
(`bookclerk-configuration.d.ts`), then `extends BookclerkEntrypoint<Env>`.

#### Indexable

```ts
[binding: string]: unknown
```

Named `[[databases]]` bindings, `[[queues.producers]]` bindings, and any
renamed `binding = "..."` entries.

#### Properties

##### AI?

```ts
AI?: AiBinding;
```

`[ai].calls` model runner.

##### CONFIG?

```ts
CONFIG?: JsonObject;
```

`[vars]` plus operator settings, decoded from the granted `CONFIG` payload.

##### EVENTS?

```ts
EVENTS?: EventPublisherBinding;
```

`[[events.producers]]` outbox publisher.

##### KV?

```ts
KV?: KvNamespaceBinding;
```

`[[kv_namespaces]]` durable KV binding (default name).

##### NETWORK?

```ts
NETWORK?: NetworkGrant;
```

The network grant in effect: fetch hosts, TCP destinations, and each
network setting's destination with its approval state (`pending` until
the operator approves it). Read-only; the host enforces the grant.

##### NOTIFY?

```ts
NOTIFY?: NotifyBinding;
```

`[[notifications.types]]` raiser.

##### OAUTH?

```ts
OAUTH?: unknown;
```

`[oauth]` loopback helper; surface reserved.

##### ORIGIN?

```ts
ORIGIN?: OriginBinding;
```

The library a relay `ingress` plugin serves; present only while this
instance is the active ingress.

##### SECRETS?

```ts
SECRETS?: JsonObject;
```

`[secrets]` values, decoded from the granted `SECRETS` payload.

##### SOCKETS?

```ts
SOCKETS?: SocketsBinding;
```

`[sockets]` host-brokered WebSockets (default name).

##### WEBHOOKS?

```ts
WEBHOOKS?: WebhooksBinding;
```

`[[webhooks]]` inbound webhooks.

##### WORK\_FS?

```ts
WORK_FS?: StorageBinding;
```

`[work_fs]` object storage.

***

### EventPublisherBinding

`EVENTS` binding, present when a `[[events.producers]]` or
`[[events.consumers]]` entry is declared and granted. Publishing needs a
granted producer; reading needs a granted consumer.

#### Methods

##### publish()

```ts
publish(event): Promise<PublishOk>;
```

Publish one domain event through the host outbox.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `event` | [`PublishEvent`](#publishevent) | Event type, schema version, payload, dedup key. |

###### Returns

`Promise`\<[`PublishOk`](/docs/plugins/sdk/typescript/generated/index.md#publishok)\>

Outbox row identity (`duplicate` when the dedup key matched).

##### read()

```ts
read(options?): Promise<EventReadPage>;
```

Read one page of past events the plugin's granted subscriptions match,
oldest first, to catch up after its deliveries expired.

Pass the page's `cursor` back as `after` while `more` is true.
`expiredEventIds` names events in the page whose delivery to this
plugin expired unhandled, and `truncated` says the start was older
than the host keeps. Read events are not deliveries: `deliveryAttempt`
is `0` and `deduplicationKey` is the event id.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `options?` | [`EventReadOptions`](#eventreadoptions) | Start position, types, and page size. |

###### Returns

`Promise`\<[`EventReadPage`](/docs/plugins/sdk/typescript/generated/index.md#eventreadpage)\>

One page of events and the cursor after it.

###### Throws

PluginError `forbidden` for a type that is not a granted
  consumer, `invalid_cursor` for a cursor the host did not issue.

***

### EventReadOptions

Where an [EventPublisherBinding.read](#read) starts and which events it
returns. Set at most one of `after` and `since`; with neither, the read
starts at the oldest event the host still keeps (`[events].retention_days`).

#### Properties

##### after?

```ts
after?: string;
```

Opaque cursor from an earlier page's `cursor`: resume right after it.

##### limit?

```ts
limit?: number;
```

Most events in the page; `0` or omitted means the host maximum.

##### since?

```ts
since?: number | Date;
```

Start at this instant (a `Date`, or UTC unix milliseconds).

##### sinceUnixMs?

```ts
sinceUnixMs?: number;
```

The ABI spelling of `since` (UTC unix milliseconds), as the generated
`EventReadRequest` names it; used when `since` is absent.

##### types?

```ts
types?: string[];
```

Event types to return; each must be a granted `[[events.consumers]]`
type. Empty or omitted means every granted type.

***

### HostWebSocket

One host-brokered WebSocket, shaped like a hibernatable Workers WebSocket.

The host holds the connection while the plugin sleeps and wakes the
plugin's `webSocketMessage` / `webSocketClose` handlers when something
arrives. The object is a handle: it carries the socket's id and the
attachment as it was when the handle was made, and each method is one call
to the host.

#### Properties

##### id

```ts
readonly id: string;
```

Host-minted id, stable for the socket's life and never reused.

##### protocol

```ts
readonly protocol: string;
```

Subprotocol the server chose; empty when none or unknown.

##### url

```ts
readonly url: string;
```

URL the socket was opened to, without credentials; empty in a handler.

#### Methods

##### close()

```ts
close(code?, reason?): Promise<void>;
```

Close the socket. Closing a closed socket is not an error.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `code?` | `number` | Close code; omitted sends 1000. |
| `reason?` | `string` | Close reason, at most 123 UTF-8 bytes. |

###### Returns

`Promise`\<`void`\>

##### deserializeAttachment()

```ts
deserializeAttachment(): unknown;
```

The attachment as this handle last saw it.

###### Returns

`unknown`

The stored value, or `null` when none is set.

##### send()

```ts
send(message): Promise<void>;
```

Send one message.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `message` | [`SocketSendData`](#socketsenddata) | Text or bytes, at most `MAX_SOCKET_FRAME_BYTES`. |

###### Returns

`Promise`\<`void`\>

###### Throws

PluginError `not_found` when the socket has closed.

##### serializeAttachment()

```ts
serializeAttachment(value): Promise<void>;
```

Replace the attachment the host keeps for this socket and hands back
with every message, so state survives the plugin sleeping. The value is
stored as JSON and must encode to at most `MAX_SOCKET_ATTACHMENT_BYTES`.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `value` | `unknown` | JSON-serializable value; `null` or `undefined` clears it. |

###### Returns

`Promise`\<`void`\>

###### Throws

PluginError `payload_too_large` when it does not fit.

***

### KvListKeyBinding

One key on a [KvNamespaceBinding.list](#list) page.

#### Properties

##### expiration?

```ts
expiration?: number;
```

Absolute expiry in seconds since the Unix epoch, when set.

##### metadata?

```ts
metadata?: unknown;
```

Stored metadata, when set.

##### name

```ts
name: string;
```

Key name.

***

### KvListOptionsBinding

Page request for [KvNamespaceBinding.list](#list).

#### Properties

##### cursor?

```ts
cursor?: string;
```

Cursor from a previous page.

##### limit?

```ts
limit?: number;
```

Most keys to return (host default when omitted, at most `maxListPage`).

##### prefix?

```ts
prefix?: string;
```

Only keys starting with this prefix.

***

### KvListResultBinding

One page of [KvNamespaceBinding.list](#list).

#### Properties

##### cursor?

```ts
cursor?: string;
```

Cursor for the next page; absent when `list_complete`.

##### keys

```ts
keys: KvListKeyBinding[];
```

Keys in lexical order.

##### list\_complete

```ts
list_complete: boolean;
```

True when no further page exists.

***

### KvNamespaceBinding

`[[kv_namespaces]]` binding (`env.<BINDING>`, default `KV`): Workers
`KVNamespace`-shaped durable storage the host serves from the library
database, scoped to this plugin and the namespace the row names. Values
follow the instance across hosts.

#### Methods

##### delete()

```ts
delete(key): Promise<void>;
```

Delete one key; a missing key is not an error.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key to delete. |

###### Returns

`Promise`\<`void`\>

##### get()

###### Call Signature

```ts
get(key, type?): Promise<string | null>;
```

Read one key.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key, at most `maxKvKeyBytes` UTF-8 bytes. |
| `type?` | `"text"` | Decoding (`text` by default). |

###### Returns

`Promise`\<`string` \| `null`\>

The value, or `null` when absent or expired.

###### Call Signature

```ts
get<T>(key, type): Promise<T | null>;
```

Read one key and parse it as JSON.

###### Type Parameters

| Type Parameter | Default type |
| ------ | ------ |
| <a id="type-parameter-t"></a> `T` | `unknown` |

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key, at most `maxKvKeyBytes` UTF-8 bytes. |
| `type` | `"json"` | `json`. |

###### Returns

`Promise`\<`T` \| `null`\>

The parsed value, or `null` when absent or expired.

###### Call Signature

```ts
get(key, type): Promise<ArrayBuffer | null>;
```

Read one key as bytes.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key, at most `maxKvKeyBytes` UTF-8 bytes. |
| `type` | `"arrayBuffer"` | `arrayBuffer`. |

###### Returns

`Promise`\<`ArrayBuffer` \| `null`\>

The bytes, or `null` when absent or expired.

##### getWithMetadata()

###### Call Signature

```ts
getWithMetadata(key, type?): Promise<KvValueWithMetadata<string>>;
```

Read one key with its metadata.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key to read. |
| `type?` | `"text"` | Decoding (`text` by default). |

###### Returns

`Promise`\<[`KvValueWithMetadata`](#kvvaluewithmetadata)\<`string`\>\>

Value and metadata; both `null` when absent.

###### Call Signature

```ts
getWithMetadata<T>(key, type): Promise<KvValueWithMetadata<T>>;
```

Read one key as JSON with its metadata.

###### Type Parameters

| Type Parameter | Default type |
| ------ | ------ |
| <a id="type-parameter-t-1"></a> `T` | `unknown` |

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key to read. |
| `type` | `"json"` | `json`. |

###### Returns

`Promise`\<[`KvValueWithMetadata`](#kvvaluewithmetadata)\<`T`\>\>

Parsed value and metadata; both `null` when absent.

###### Call Signature

```ts
getWithMetadata(key, type): Promise<KvValueWithMetadata<ArrayBuffer>>;
```

Read one key as bytes with its metadata.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key to read. |
| `type` | `"arrayBuffer"` | `arrayBuffer`. |

###### Returns

`Promise`\<[`KvValueWithMetadata`](#kvvaluewithmetadata)\<`ArrayBuffer`\>\>

Bytes and metadata; both `null` when absent.

##### list()

```ts
list(options?): Promise<KvListResultBinding>;
```

List keys in lexical order, one page at a time.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `options?` | [`KvListOptionsBinding`](#kvlistoptionsbinding) | Prefix, cursor, and page size. |

###### Returns

`Promise`\<[`KvListResultBinding`](#kvlistresultbinding)\>

One page of keys.

##### put()

```ts
put(
   key, 
   value, 
   options?
): Promise<void>;
```

Write one key, replacing any previous value and metadata.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Key to write. |
| `value` | `string` \| `ArrayBuffer` \| `ArrayBufferView`\<`ArrayBufferLike`\> | String (stored as UTF-8) or bytes. |
| `options?` | [`KvPutOptionsBinding`](#kvputoptionsbinding) | Expiration and metadata. |

###### Returns

`Promise`\<`void`\>

***

### KvPutOptionsBinding

Options for [KvNamespaceBinding.put](#put) (Workers KV names).

#### Properties

##### expiration?

```ts
expiration?: number;
```

Absolute expiry in seconds since the Unix epoch.

##### expirationTtl?

```ts
expirationTtl?: number;
```

Relative expiry in seconds from the write; ignored when `expiration` is set.

##### metadata?

```ts
metadata?: unknown;
```

JSON-serializable metadata, at most `maxKvMetadataBytes` once encoded.

***

### KvValueWithMetadata

Value plus metadata from [KvNamespaceBinding.getWithMetadata](#getwithmetadata).

#### Type Parameters

| Type Parameter |
| ------ |
| <a id="type-parameter-t-2"></a> `T` |

#### Properties

##### metadata

```ts
metadata: unknown;
```

Stored metadata, or `null` when none.

##### value

```ts
value: T | null;
```

Decoded value, or `null` when the key is absent or expired.

***

### NotifyBinding

`NOTIFY` binding, present when `plugin.toml` declares
`[[notifications.types]]`. The host routes each raise by the
administrators' rules and each patron's preferences; the plugin never
learns where it went.

#### Methods

##### raise()

```ts
raise(raise): Promise<NotifyRaised>;
```

Raise one declared notification type.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `raise` | [`NotifyRaise`](#notifyraise) | Type, fields, optional patron, link path and alert. |

###### Returns

`Promise`\<[`NotifyRaised`](/docs/plugins/sdk/typescript/generated/index.md#notifyraised)\>

The host's notification id.

###### Throws

PluginError `invalid_params` for an undeclared type or a malformed
  raise, `forbidden` for a patron outside the account scope, `rate_limited`
  past the per-instance raise budget.

***

### NotifyRaise

One notification a plugin raises through [NotifyBinding.raise](#raise).

#### Properties

##### alertAction?

```ts
alertAction?: "none" | "trigger" | "resolve";
```

Alert lifecycle step; `none` (the default) for a one-off notification.

##### alertKey?

```ts
alertKey?: string;
```

Alert to open or close; required unless `alertAction` is `none`.

##### fields?

```ts
fields?: 
  | Record<string, string>
  | NotificationField[];
```

Labelled values shown with the notification, as `{ name, value }` rows or
a plain object (at most `MAX_NOTIFICATION_FIELDS`).

##### groupKey?

```ts
groupKey?: string;
```

Notifications with one group key may be threaded or collapsed together.

##### linkPath?

```ts
linkPath?: string;
```

Path inside the library to link to (`/books/42`); the host adds its origin.

##### notificationType

```ts
notificationType: string;
```

Type id from the plugin's `[[notifications.types]]`, without a plugin prefix.

##### patronId?

```ts
patronId?: string;
```

Patron the notification is for; required for a `patron` type and must be
inside the invocation's account scope.

***

### QueueBinding

`[[queues.producers]]` binding (`env.<BINDING>`): Workers `Queue`-shaped
producer into the queue the row names. The host assigns ids, stamps the
sending plugin as `source`, and bounds each body at `maxEventPayloadBytes`.

#### Methods

##### send()

```ts
send(body, options?): Promise<QueueSendOk>;
```

Send one message.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `body` | `unknown` | JSON value (default), string, or bytes per `contentType`. |
| `options?` | [`QueueSendOptions`](#queuesendoptions) | Encoding and delay. |

###### Returns

`Promise`\<[`QueueSendOk`](/docs/plugins/sdk/typescript/generated/index.md#queuesendok)\>

The outbox id the host assigned.

##### sendBatch()

```ts
sendBatch(messages, options?): Promise<QueueSendOk>;
```

Send up to `maxListPage` messages in order.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `messages` | readonly [`QueueSendBatchEntry`](#queuesendbatchentry)[] | Bodies with per-message options. |
| `options?` | `Pick`\<[`QueueSendOptions`](#queuesendoptions), `"delaySeconds"`\> | Default delay for entries that carry none. |

###### Returns

`Promise`\<[`QueueSendOk`](/docs/plugins/sdk/typescript/generated/index.md#queuesendok)\>

The outbox ids in send order.

***

### QueueSendBatchEntry

One entry of [QueueBinding.sendBatch](#sendbatch).

#### Extends

- [`QueueSendOptions`](#queuesendoptions)

#### Properties

##### body

```ts
body: unknown;
```

Message body (JSON value, string, or bytes per `contentType`).

##### contentType?

```ts
contentType?: "text" | "bytes" | "json";
```

Body encoding: `json` (default; the body is JSON-encoded), `text`
(UTF-8 string), or `bytes` (raw `Uint8Array`).

###### Inherited from

[`QueueSendOptions`](#queuesendoptions).[`contentType`](#contenttype-1)

##### delaySeconds?

```ts
delaySeconds?: number;
```

Seconds before the message may be delivered; `0` means now.

###### Inherited from

[`QueueSendOptions`](#queuesendoptions).[`delaySeconds`](#delayseconds-1)

***

### QueueSendOptions

Per-send options for a [QueueBinding](#queuebinding).

#### Extended by

- [`QueueSendBatchEntry`](#queuesendbatchentry)

#### Properties

##### contentType?

```ts
contentType?: "text" | "bytes" | "json";
```

Body encoding: `json` (default; the body is JSON-encoded), `text`
(UTF-8 string), or `bytes` (raw `Uint8Array`).

##### delaySeconds?

```ts
delaySeconds?: number;
```

Seconds before the message may be delivered; `0` means now.

***

### SocketAutoResponsePair

A heartbeat the host answers itself, like a Workers
`WebSocketRequestResponsePair`: when a message equal to `request` (same
kind, same bytes) arrives, the host sends `response` and does not wake the
plugin.

#### Properties

##### request

```ts
request: SocketSendData;
```

Message to match, 1 to `MAX_SOCKET_AUTO_RESPONSE_BYTES` bytes.

##### response

```ts
response: SocketSendData;
```

Message to send back, 1 to `MAX_SOCKET_AUTO_RESPONSE_BYTES` bytes.

***

### SocketConnectOptions

Options for [SocketsBinding.connect](#connect).

#### Properties

##### attachment?

```ts
attachment?: unknown;
```

Initial attachment, as [HostWebSocket.serializeAttachment](#serializeattachment) would
store it.

##### autoResponses?

```ts
autoResponses?: SocketAutoResponsePair[];
```

Heartbeats the host answers without waking the plugin, at most 4.

##### headers?

```ts
headers?: Record<string, string> | [string, string][];
```

Extra request headers, at most 16. Values may be credentials; the host
never logs them. Handshake and hop-by-hop headers are refused.

##### protocols?

```ts
protocols?: string[];
```

Subprotocols to request (`Sec-WebSocket-Protocol`), at most 16.

***

### SocketsBinding

`SOCKETS` binding (`[sockets]`, renamed by `binding = "..."`): outbound
WebSockets the host holds open while the plugin sleeps. Messages and
closes reach the default entrypoint's `webSocketMessage(ws, message)` and
`webSocketClose(ws, code, reason, wasClean)`.

#### Methods

##### connect()

```ts
connect(url, options?): Promise<HostWebSocket>;
```

Open a socket once the handshake finishes. It belongs to the plugin
instance and outlives this invocation.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `url` | `string` | `wss://` or `ws://` URL on the plugin's network grant. |
| `options?` | [`SocketConnectOptions`](#socketconnectoptions) | Subprotocols, headers, heartbeats and attachment. |

###### Returns

`Promise`\<[`HostWebSocket`](#hostwebsocket)\>

The open socket.

###### Throws

PluginError `forbidden` for a host outside the network grant,
  `limit_exceeded` when the instance already holds `MAX_SOCKETS_PER_INSTANCE`
  sockets.

##### getWebSockets()

```ts
getWebSockets(): Promise<HostWebSocket[]>;
```

The instance's open sockets, oldest first, for a plugin that just woke.

###### Returns

`Promise`\<[`HostWebSocket`](#hostwebsocket)[]\>

One handle per open socket.

***

### StorageBinding

`WORK_FS` binding: host-granted object storage for durable plugin files.
Same surface as the `storage` entrypoint the host calls on storage plugins.

#### Methods

##### delete()

```ts
delete(key): Promise<void>;
```

Remove an object; missing keys are not an error.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Object key. |

###### Returns

`Promise`\<`void`\>

Resolves when the delete is durable.

##### get()

```ts
get(key, options?): Promise<{
  body: ReadableStream<Uint8Array<ArrayBufferLike>>;
  meta: {
     key: string;
     size: number;
  };
}>;
```

Stream an object (optionally a byte range).

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Object key. |
| `options?` | \{ `range?`: \{ `length?`: `number`; `offset`: `number`; \}; \} | Optional byte range. |
| `options.range?` | \{ `length?`: `number`; `offset`: `number`; \} | - |
| `options.range.length?` | `number` | - |
| `options.range.offset` | `number` | - |

###### Returns

`Promise`\<\{
  `body`: `ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>;
  `meta`: \{
     `key`: `string`;
     `size`: `number`;
  \};
\}\>

Metadata and the body stream.

##### head()

```ts
head(key): Promise<
  | {
  contentType?: string;
  etag?: string;
  key: string;
  size: number;
}
| null>;
```

Object metadata without the body.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Object key. |

###### Returns

`Promise`\<
  \| \{
  `contentType?`: `string`;
  `etag?`: `string`;
  `key`: `string`;
  `size`: `number`;
\}
  \| `null`\>

Metadata, or `null` when the key does not exist.

##### list()

```ts
list(options): Promise<{
  nextCursor?: string;
  objects: object[];
}>;
```

One page of keys under `prefix`.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `options` | \{ `cursor?`: `string`; `limit?`: `number`; `prefix?`: `string`; \} | Prefix, continuation cursor, and page size. |
| `options.cursor?` | `string` | - |
| `options.limit?` | `number` | - |
| `options.prefix?` | `string` | - |

###### Returns

`Promise`\<\{
  `nextCursor?`: `string`;
  `objects`: `object`[];
\}\>

Objects plus the cursor for the next page, when any.

##### put()

```ts
put(
   key, 
   body, 
   options?
): Promise<{
  bytesWritten: number;
  key: string;
}>;
```

Write an object from a stream.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `key` | `string` | Object key. |
| `body` | `ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\> | Body bytes. |
| `options?` | \{ `contentLength?`: `number`; `contentType?`: `string`; \} | Content type and length hints. |
| `options.contentLength?` | `number` | - |
| `options.contentType?` | `string` | - |

###### Returns

`Promise`\<\{
  `bytesWritten`: `number`;
  `key`: `string`;
\}\>

Key and bytes written.

***

### WebhookDeliveredEvent

Argument of the default entrypoint's `webhookDelivered(event)`.

#### Properties

##### name

```ts
name: string;
```

`[[webhooks]]` name.

##### waiting

```ts
waiting: number;
```

Requests waiting for this webhook when the host called.

***

### WebhookMessage

One stored webhook request, leased to the plugin by
[WebhooksBinding.pull](#pull). Shaped like a pulled Workers Queue message:
acknowledge it with [WebhooksBinding.ack](#ack) once handled, or it is
offered again when its lease runs out.

#### Properties

##### attempts

```ts
attempts: number;
```

How many times the request has been pulled, counting this one.

##### body

```ts
body: Uint8Array;
```

Request body as received.

##### headers

```ts
headers: Record<string, string>;
```

Kept request headers, lowercase names: those the `[[webhooks]]` row
lists, plus `content-type`.

##### leaseId

```ts
leaseId: string;
```

Lease id for `ack`; a new one each time the request is pulled.

##### timestamp

```ts
timestamp: Date;
```

When the host stored the request, as a `Date`.

***

### WebhookPullOptions

Options for [WebhooksBinding.pull](#pull).

#### Properties

##### batchSize?

```ts
batchSize?: number;
```

Most requests to lease, 1 to 100; defaults to 10.

##### visibilityTimeoutMs?

```ts
visibilityTimeoutMs?: number;
```

How long leased requests stay hidden from the next pull, in
milliseconds, at most 12 hours; defaults to one minute.

***

### WebhookPullResult

What one [WebhooksBinding.pull](#pull) leased.

#### Properties

##### messages

```ts
messages: WebhookMessage[];
```

Leased requests, oldest first.

##### missed

```ts
missed: boolean;
```

True when the host dropped requests for this webhook since the last
pull (its waiting cap was full, or a request expired unacknowledged):
treat what the requests describe as incomplete and fall back to a full
listing.

***

### WebhooksBinding

`WEBHOOKS` binding (`[[webhooks]]`): the instance's inbound webhooks. The
host serves each row at a secret URL, checks each request's size, rate
and signature, and stores it until the plugin pulls and acknowledges it.
The default entrypoint's `webhookDelivered(event)` runs when requests
arrive.

#### Methods

##### ack()

```ts
ack(name, leases): Promise<void>;
```

Finish leased requests: `acks` are deleted, `retries` are offered again
on the next pull.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `name` | `string` | `[[webhooks]]` name. |
| `leases` | \{ `acks?`: `string`[]; `retries?`: `string`[]; \} | Lease ids to acknowledge and to retry. |
| `leases.acks?` | `string`[] | - |
| `leases.retries?` | `string`[] | - |

###### Returns

`Promise`\<`void`\>

Resolves when the host recorded both lists.

##### pull()

```ts
pull(name, options?): Promise<WebhookPullResult>;
```

Lease waiting requests for one webhook, oldest first.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `name` | `string` | `[[webhooks]]` name. |
| `options?` | [`WebhookPullOptions`](#webhookpulloptions) | Batch size and lease length. |

###### Returns

`Promise`\<[`WebhookPullResult`](#webhookpullresult)\>

The leased requests and whether any were missed.

##### url()

```ts
url(name): Promise<string | null>;
```

The URL to register with the outside service for one webhook.

###### Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `name` | `string` | `[[webhooks]]` name. |

###### Returns

`Promise`\<`string` \| `null`\>

The URL, or `null` when the library cannot be reached from the
  Internet or webhooks are turned off; use the fallback then.

## Type Aliases

### JsonObject

```ts
type JsonObject = Record<string, unknown>;
```

Plain JSON object (string keys, JSON values).

***

### KvValueType

```ts
type KvValueType = "text" | "json" | "arrayBuffer";
```

How [KvNamespaceBinding.get](#get) decodes a stored value.

***

### PublishEvent

```ts
type PublishEvent = Pick<PluginEvent, "eventType"> & Partial<Omit<PluginEvent, "eventType" | "payload">> & object;
```

Event a guest publishes; the host stamps id, `source`, and `accountId`.

#### Type Declaration

| Name | Type | Description |
| ------ | ------ | ------ |
| `payload?` | `Uint8Array` \| [`JsonObject`](#jsonobject) \| `unknown`[] \| `string` | Payload bytes or a JSON-serializable value encoded as UTF-8 JSON. |

***

### SocketMessageData

```ts
type SocketMessageData = string | ArrayBuffer;
```

A message that arrived on a host-brokered socket: text as a string, binary
as an `ArrayBuffer` (as Workers delivers to `webSocketMessage`).

***

### SocketSendData

```ts
type SocketSendData = string | ArrayBuffer | ArrayBufferView;
```

A message to send on a host-brokered socket.
