TypeScript plugin SDK
This page shows how to write a Bookclerk plugin in TypeScript with
@bookclerk/plugin-sdk (api_version = 3). A TypeScript plugin runs in
a workerd isolate; bookclerk-workerd injects the SDK into the isolate
under its package name, so your module imports it like any dependency.
| Import | What it holds |
|---|---|
@bookclerk/plugin-sdk/workerd |
BookclerkEntrypoint and the named *Entrypoint bases (they extend WorkerEntrypoint) |
@bookclerk/plugin-sdk |
The ABI types, codecs and the same author classes |
@bookclerk/plugin-sdk/sparse-workerd |
Run a workerd plugin without a built host (smoke) |
Depend on the package from npm, a file: path or a workspace. Never
import a relative path to the embed; the module name is what the host
injects.
{
"dependencies": {
"@bookclerk/plugin-sdk": "file:../../packages/plugin-sdk"
}
}
A plugin is a Workers-shaped module. The default export extends
BookclerkEntrypoint and implements the triggers plugin.toml declares;
every named entrypoint in entrypoints = [...] is an exported class
with the matching name (storefront → Storefront, cli → Cli, …)
extending its base:
plugin.toml |
Export | Base class |
|---|---|---|
[[events.consumers]] |
default |
BookclerkEntrypoint.event(batch) |
[triggers] jobs = [...] |
default |
BookclerkEntrypoint.job(job) |
[triggers] crons = [...] |
default |
BookclerkEntrypoint.scheduled(controller) |
[[databases]] |
default |
BookclerkEntrypoint.databaseMigrations(binding) |
entrypoints = ["storefront"] |
Storefront |
StorefrontEntrypoint |
entrypoints = ["storage"] |
Storage |
StorageEntrypoint |
entrypoints = ["remoteLibrary"] |
RemoteLibrary |
RemoteLibraryEntrypoint |
entrypoints = ["databaseAdapter"] |
DatabaseAdapter |
DatabaseAdapterEntrypoint |
entrypoints = ["cli"] |
Cli |
CliEntrypoint |
entrypoints = ["oidc"] |
Oidc |
OidcEntrypoint |
entrypoints = ["metadata"] |
Metadata |
MetadataEntrypoint |
entrypoints = ["covers"] |
Covers |
CoverEntrypoint |
entrypoints = ["metadataFiles"] |
MetadataFiles |
MetadataFilesEntrypoint |
entrypoints = ["notifier"] |
Notifier |
NotifierEntrypoint |
entrypoints = ["ingress"] |
Ingress |
IngressEntrypoint |
entrypoints = ["ai"] |
Ai |
AiEntrypoint |
import {
BookclerkEntrypoint,
CliEntrypoint,
cliArgs,
jsonPayload,
type CliInvokeParams,
type EventBatch,
} from "@bookclerk/plugin-sdk/workerd";
import type { Env } from "./bookclerk-configuration.js";
export class Cli extends CliEntrypoint<Env> {
async describe() {
return { commands: [{ name: "ping", about: "Probe", args: [] }] };
}
async invoke(params: CliInvokeParams) {
const { message = "hi" } = cliArgs(params);
return { exitCode: 0, stdout: `pong: ${message}\n`, stderr: "", payload: jsonPayload({ pong: message }) };
}
}
export default class MyPlugin extends BookclerkEntrypoint<Env> {
async event(batch: EventBatch) {
for (const msg of batch.messages) {
if (msg.type !== "book_acquired") {
msg.reject(`unexpected ${msg.type}`);
continue;
}
await this.env.EVENTS.publish({ eventType: "echo_seen", payload: msg.body });
msg.ack();
}
}
}
Identity (apiVersion, id, capabilities) comes from plugin.toml; an
optional describe() on the default export only refines displayName
and similar fields.
A database adapter runs each host batch through executeAdapterBatch or
executeAdapterBatchStreamed, which stores the guest's replay receipt
before COMMIT and, for a streamed reply, rolls back when the frames do
not fit one scalar or the adapter's advertised streamed budget
(executeStreamLimits(caps)) (see
Isolate adapter batches).
event(batch)mirrors Workersqueue(batch). EachEventMessagerecords exactly one outcome,ack(),retry({ retryAt | delaySeconds, reason }),reject(reason),deadLetter(reason)orsuspend({ checkpoint, wakeAt, wakeOnEventType, wakeOnFilter }), and the first call wins. Untouched messages ack when the handler returns and retry when it throws.job(job)mirrors Workersscheduled(controller). Return (optionally{ message, bytesCopied }) to complete, throw to reject (unavailableanddeadline_exceedederrors are retryable,cancelledis cancelled), or calljob.suspend({ checkpoint, wakeAt })orjob.retryLater({ retryAt, reason }).job.input,job.output,job.progress()andjob.signalexpose the granted streams and host cancellation.
The host grants bindings per invocation on this.env: CONFIG ([vars]
plus operator settings), SECRETS ([secrets]), EVENTS
([[events.producers]]), WORK_FS ([work_fs]), and one
DatabaseBinding per [[databases]] entry under its binding name.
A binding's limits() returns the DbCapabilities its session negotiated
(maxRequestBytes, maxStatements, maxResultBytes, maxResultRows,
…); a request or result over one of them rejects with a PluginError
whose code is limit_exceeded and whose limit names the cap. On a
host that predates limits() the call rejects with unsupported.
all() reads through the session's streamed budget when it advertises
one, prepare(sql).iterate() yields rows one at a time from the same
read, db.chunk(statements) splits a long list into batches that each
fit one request, and db.writeChunks(...) commits those batches
resumably; see
Working within database limits.
A storefront's scan can hand its paging to scanPage(params, fetch),
which slices the store's own pages into replies the host accepts; see
Paged scans.
A relay [ingress] plugin also
gets ORIGIN while it is the active ingress; ORIGIN.fetch(request, { clientAddress }) hands one request to the library (see
Public addresses).
Generate the Env type from plugin.toml:
npx bookclerk-plugin types . # writes bookclerk-configuration.d.ts
npx bookclerk-plugin types . --out src/env.d.ts
A plugin that declares [sockets] (see
Pushed sockets) gets
this.env.SOCKETS, shaped like Durable Objects' hibernatable WebSockets.
The host holds the connection, so the plugin may sleep between messages,
and each message reaches the default entrypoint's webSocketMessage:
export default class Plugin extends BookclerkEntrypoint<Env> {
async scheduled() {
if ((await this.env.SOCKETS.getWebSockets()).length > 0) return;
await this.env.SOCKETS.connect("wss://abs.example.com/socket.io/?EIO=4&transport=websocket", {
headers: { Authorization: `Bearer ${this.env.SECRETS.token}` },
autoResponses: [{ request: "2", response: "3" }], // answered without waking the plugin
attachment: { library: "main" },
});
}
async webSocketMessage(ws: HostWebSocket, message: string | ArrayBuffer) {
const { library } = ws.deserializeAttachment() as { library: string };
// …
}
async webSocketClose(ws: HostWebSocket, code: number, reason: string, wasClean: boolean) {}
}
Text arrives as a string and binary as an ArrayBuffer. ws.send,
ws.close and ws.serializeAttachment act on the host's socket; the
attachment is JSON of at most 2 KiB, kept for the socket's life, so the
handler doesn't depend on memory a restart would lose. Without a
webSocketMessage handler the host is told the plugin has none; without
webSocketClose, closes are ignored.
A remote library whose message announced a new user returns
{ pollEvents: true } from webSocketMessage, and the host calls
pollEvents right away instead of at its next scheduled poll.
A plugin that declares [[webhooks]] (see
Inbound webhooks) gets
this.env.WEBHOOKS, read like a pulled Workers Queue. Hand url(name) to
the outside service, then pull what it sent:
export default class Plugin extends BookclerkEntrypoint<Env> {
async scheduled() {
const { messages, missed } = await this.env.WEBHOOKS.pull("events", { batchSize: 50 });
if (missed) await this.relist(); // requests expired unread: resynchronize
for (const message of messages) {
await this.handle(JSON.parse(new TextDecoder().decode(message.body)));
}
await this.env.WEBHOOKS.ack("events", { acks: messages.map((m) => m.leaseId) });
}
// Optional: called on a running plugin as soon as a request is stored.
async webhookDelivered({ name, waiting }: WebhookDeliveredEvent) {}
}
url resolves to null when the library has no public https address or
webhooks are off. Each message has leaseId, timestamp (a Date),
attempts, headers (lowercase names) and body (Uint8Array); leases
not acknowledged in time come back on a later pull.
this.env.NETWORK is the grant in effect (see
Network grant). A setting whose
destination still awaits approval shows state: "pending", and a refused
fetch() answers 403 with an x-bookclerk-error: network_not_granted
header:
const row = this.env.NETWORK?.settings.find((s) => s.key === "server_url");
if (row?.state === "pending") {
throw new Error(`Approve ${row.destination} on the plugin's consent form`);
}
const res = await fetch(`${this.env.CONFIG.server_url}/api/libraries`);
if (res.headers.get("x-bookclerk-error") === "network_not_granted") {
// The grant does not cover it: report it, don't retry.
}
createTestDatabase() from @bookclerk/plugin-sdk/testkit gives a
Node test suite the same binding a host grants, served by the
bookclerk-db-testkit executable under one capability profile with the
plugin's databaseMigrations applied. bookclerk-plugin test . runs the
suite once per profile (first-party, d1 and minimum), so code that
passes on the shipped adapters is also proven against D1's caps and the
smallest advertisement a host accepts:
import { createTestDatabase } from "@bookclerk/plugin-sdk/testkit";
const db = await createTestDatabase({ migrations: MIGRATIONS }); // profile from `bookclerk-plugin test`
try {
await addNotes(db.binding, ["hello"]);
} finally {
await db.close();
}
The echo_workerd_ts example (examples/plugins-echo-workerd-ts/) is a
worked plugin: a notes table it writes with chunk(), lists with
iterate() or key-paged reads, sizes with limits(), and tests under
every profile. See
Testing against the limits.
npx bookclerk-plugin check .
npx bookclerk-plugin types [dir] [--out <file>]
npx bookclerk-plugin fmt [--check] plugin.toml
npx bookclerk-plugin package --out dist/plugins .
npx bookclerk-plugin smoke . # download the pinned workerd, then describe + health
check enforces the v3 author model: the main module imports the SDK,
does not reference the removed BookclerkPlugin base, and exports one
class per named entrypoint.
smoke does not need a built bookclerk-workerd. It downloads the
pinned Cloudflare workerd into ~/.cache/bookclerk/workerd (override
with BOOKCLERK_WORKERD_CACHE or BOOKCLERK_WORKERD_BIN).
- plugin.toml: declare the entrypoints and triggers the classes above implement.
- Entrypoints, events and the ABI: every method and event in detail.
- Try the Echo example: a
complete TypeScript plugin under
examples/.
The sections below are generated from the SDK's source: one page per module, and what the package root exports.
@bookclerk/plugin-sdk — ABI types + workerd author runtime + tools.
Package root re-exports the workerd BookclerkEntrypoint base, the
named *Entrypoint bases, and the camelCase ABI types from generated.ts.
Prefer the dedicated subpath imports when writing guests:
- Workerd:
import { BookclerkEntrypoint } from "@bookclerk/plugin-sdk/workerd" - Native: Rust
serve/PluginWorker - Tools:
npx bookclerk-plugin check|fmt|types|package - Sparse workerd:
import { runSmoke } from "@bookclerk/plugin-sdk/sparse-workerd"
See docs/plugins/README.md and docs/contributing/code-documentation.md.
Sans-IO decoder of a streamed execute reply: feed it bytes in any split, then take the reassembled ExecuteReply.
It fails closed on more raw bytes than the budget allows, on a statement with more rows than the row cap, and on any frame out of sequence.
new ExecuteStreamDecoder(limits, options?): ExecuteStreamDecoder;
| Parameter | Type | Description |
|---|---|---|
limits |
ExecuteStreamLimits |
Budget the stream is held to. |
options? |
{ retainRows?: boolean; } |
retainRows: false counts rows against the budget but drops them from the collected reply (for iterate()). |
options.retainRows? |
boolean |
- |
get columns(): DbColumn[];
Columns of the statement whose rows are arriving.
DbColumn[]
The open statement's columns, or an empty list between statements.
get finished(): boolean;
Whether the final frame (end or err) has been decoded.
boolean
True once the stream is complete.
finish(): ExecuteReply;
Takes the reassembled reply once the stream has ended.
The reply the frames described.
The adapter's PluginError when the stream ended with err, and
unavailable when it ended before its final frame.
push(bytes): ExecuteStreamFrame[];
Feeds the next bytes of the stream.
| Parameter | Type | Description |
|---|---|---|
bytes |
Uint8Array |
Any slice of the frame sequence. |
The frames completed by these bytes, in order.
PluginError limit_exceeded when the stream exceeds the byte
or row budget, invalid_params when a frame is malformed or out of
sequence or bytes follow the final frame.
Thrown by the SDK when a wire union carries err. Unknown codes are kept.
Error
new PluginError(
code,
message,
details?
): PluginError;
| Parameter | Type | Description |
|---|---|---|
code |
string |
Wire error code. |
message |
string |
Operator-facing error text. |
details? |
string | Readonly<Record<string, unknown>> |
Detail object, or its JSON text as carried on the wire. |
Error.constructor
readonly code: string;
Known PluginErrorCode wire string, or unknown.
readonly details: Readonly<Record<string, unknown>> | undefined;
Structured detail object from the wire (details JSON), when the error carries one.
readonly wireCode: string;
Raw wire code, including codes this SDK does not know.
get detailsText(): string;
details as the JSON text the wire carries.
string
JSON object text, or an empty string when the error has none.
get limit(): LimitExceeded | undefined;
The exceeded cap when this is a limit_exceeded error.
LimitExceeded | undefined
The cap from details first, then from the canonical message;
undefined for every other code.
static fromWire(
code,
message,
details?
): PluginError;
Construct a PluginError from a Cap'n Proto / JSON wire code.
Unknown codes become unknown on PluginError.code while
PluginError.wireCode keeps the raw value.
| Parameter | Type | Default value | Description |
|---|---|---|---|
code |
string |
undefined |
Wire error code (known or unknown). |
message |
string |
undefined |
Operator-facing error text. |
details? |
string |
"" |
details JSON text from the wire (empty when none). |
Typed plugin error.
static limitExceeded(limit): PluginError;
Builds a limit_exceeded error whose message and details both carry
the exceeded cap.
| Parameter | Type | Description |
|---|---|---|
limit |
LimitExceeded |
Exceeded cap. |
Typed plugin error.
Options shared by the batch runners.
timingSource: string;
Observability source on the reply timing (for example sqlite_txn).
The parts of an AdapterExecuteRequest the batch runner reads.
operationId: string;
Host-chosen idempotency key, echoed on the reply and keyed on the receipt.
receipt: AdapterReceipt;
Receipt hint; guestLen 0 means the batch carries no guest receipt.
statements: AdapterBatchStatement[];
Wrapped statements in execution order (proofs are not read).
Options of executeAdapterBatchStreamed.
limits: ExecuteStreamLimits;
The streamed budget this adapter advertises
(executeStreamLimits(caps)); the host decodes the reply under it.
timingSource: string;
Observability source on the reply timing (for example sqlite_txn).
AdapterBatchOptions.timingSource
One open transaction on the adapter's engine.
The runner calls run once per statement in order, including the finalize
statements it adds (canonical SQL with ? placeholders, lowered by the
adapter like any other statement), then commit, or rollback when any
step failed.
commit(): Promise<void>;
Commits the transaction.
Promise<void>
Resolves once the batch is durable.
rollback(): Promise<void>;
Rolls the transaction back.
Promise<void>
Resolves once nothing of the batch remains.
run(statement): Promise<StatementResult>;
Runs one statement inside the transaction.
| Parameter | Type | Description |
|---|---|---|
statement |
AdapterBatchStatement |
Canonical statement to lower and execute. |
Promise<StatementResult>
The statement's result (rows only when resultSelection is rows).
What a receiver lets a streamed reply grow to.
bytesLimit: "maxStreamedResultBytes" | "maxAtomicResultBytes";
Capability field maxBytes came from, for the error it raises.
maxBytes: number;
Encoded reply budget in bytes (0 = only the framing slack).
maxRows: number;
Rows one statement may return (0 = unlimited).
rowsLimit: "maxStreamedResultRows" | "maxResultRows";
Capability field maxRows came from, for the error it raises.
A negotiated SQL-v1 cap that a request or its result exceeded
(limit_exceeded errors).
cap: number;
The negotiated cap.
limit: string;
Capability field name as advertised (maxResultBytes, maxRequestBytes, ...).
used: number;
The observed value that exceeded cap.
env.ORIGIN: the library as a relay ingress plugin reaches it. The host
serves each request on public https (never as loopback) with the client
address the plugin reports.
fetch(request, options?): Promise<Response>;
Serves one request through the library.
Only the path and query of request.url are sent; the library answers
on its own public origin. Connection headers (connection, upgrade,
...) and forwarding headers (host, x-forwarded-*, forwarded,
x-real-ip) are dropped.
| Parameter | Type | Description |
|---|---|---|
request |
Request |
The request the provider delivered. |
options? |
OriginFetchOptions |
The client address, when the provider reports one. |
Promise<Response>
The library's response; its body streams.
invalid_params for a request the host refuses
(bad method, target or headers past maxOriginHeaders /
maxOriginHeaderBytes); unavailable when the library cannot serve.
Options for one OriginBinding.fetch.
clientAddress?: string;
IP address of the client from the provider's own connection metadata
(for example cf-connecting-ip on a Cloudflare relay). Omit it when the
provider gives none; never take it from a header the client controls.
The adapter's origin grant, as the author isolate reaches it. Never
throws: every failure comes back as err.
fetch(head, body): Promise<OriginTransportReply>;
Hand one request to the library.
| Parameter | Type | Description |
|---|---|---|
head |
OriginRequest |
Method, origin-form target, header fields and client address. |
body |
ReadableStream<Uint8Array<ArrayBufferLike>> | null |
Request body; null when the request has none. |
Promise<OriginTransportReply>
The library's response or a typed failure.
One library response as the transport hands it to the author isolate.
OriginResponseHead
body: ReadableStream<Uint8Array<ArrayBufferLike>> | null;
Response body; null when the response has none.
headers: OriginHeader[];
Response header fields in order; repeated names stay separate.
OriginResponseHead.headers
status: number;
HTTP status code, 100 to 599.
OriginResponseHead.status
One page of a storefront's own library listing, as the plugin fetched it.
books: ScanBook[];
Titles on this store page, in the store's order; any number of them.
complete?: boolean;
On the last store page: whether the pass listed every title the account holds (a full pass). Ignored on earlier pages.
next?: string;
The storefront's own cursor for the store page after this one; empty or absent when this is the last store page.
removed?: string[];
Product ids gone from the account since ScanParams.syncToken, on a
delta pass only; any number of them.
storePages?: number;
Storefront requests this fetch took; 1 when absent.
syncToken?: string;
On the last store page: the token the host sends as
ScanParams.syncToken on the account's next pass. Ignored on earlier
pages.
type AdapterBatchStatement = Pick<AdapterStatement, "sql" | "parameters" | "kind" | "maxRows" | "resultSelection">;
The parts of an AdapterStatement an adapter executes.
type FetchStorePage = (storeCursor, params) => Promise<StorePage>;
Fetches one store page.
| Parameter | Type | Description |
|---|---|---|
storeCursor |
string |
The storefront's own cursor: empty for the first store page of a pass, otherwise a StorePage.next it returned. |
params |
ScanParams |
The scan call's params (account, credential, sync token). |
Promise<StorePage>
That store page.
type OriginTransportReply =
| {
ok: OriginTransportResponse;
}
| {
err: {
code: string;
message: string;
};
};
One transport answer: the library's response, or a typed failure.
const GUEST_READ_ONLY_REPLAY_PAYLOAD: "{\"readOnly\":true}" = '{"readOnly":true}';
Payload stored for a read-only guest batch instead of its rows: reads are not gated, so they run again on replay and need no recorded result.
const GUEST_RECEIPT_CLAIM_LOST: "guest receipt claimed by a concurrent attempt; retry to replay it" = "guest receipt claimed by a concurrent attempt; retry to replay it";
unavailable message when a concurrent attempt committed the receipt
between this attempt's prior-receipt SELECT and its stub INSERT.
const GUEST_RECEIPT_RESULT_LOST: "guest receipt committed without payload; original response lost" = "guest receipt committed without payload; original response lost";
Error text when a receipt committed but the reply it should hold was lost.
const GUEST_RECEIPT_STUB_SUFFIX: 1 = 1;
Receipt stub INSERT after the guest statements.
const GUEST_RECEIPT_WRAP_PREFIX: 2 = 2;
Prune + prior-receipt SELECT statements ahead of the guest statements.
const GUEST_REPLAY_PAYLOAD_MAX_BYTES: 65536 = 65536;
Largest replay payload, in UTF-8 bytes, a receipt stores for a write batch.
const STREAM_FRAME_TARGET_BYTES: number;
Encoded size an encoder aims for per rows frame (one wider row may exceed it).
function collectExecuteStream(chunks, limits): Promise<ExecuteReply>;
Collects an async chunk source into one reply under limits.
| Parameter | Type | Description |
|---|---|---|
chunks |
AsyncIterable<Uint8Array<ArrayBufferLike>> |
Frame bytes as the transport delivers them. |
limits |
ExecuteStreamLimits |
Budget the stream is held to. |
Promise<ExecuteReply>
The reassembled reply.
function decodeExecuteStream(bytes, limits): ExecuteReply;
Decodes a whole frame sequence under limits.
| Parameter | Type | Description |
|---|---|---|
bytes |
Uint8Array |
Every frame, concatenated. |
limits |
ExecuteStreamLimits |
Budget the stream is held to. |
The reassembled reply.
See ExecuteStreamDecoder.push and ExecuteStreamDecoder.finish.
function encodeExecuteStream(
reply,
frameTargetBytes?,
maxBytes?
): Uint8Array;
Frames reply as the byte sequence executeStreamed answers: head,
each statement with its rows split near frameTargetBytes, then end. A
slice whose frame still exceeds one scalar is halved until each frame fits
or holds one row.
| Parameter | Type | Default value | Description |
|---|---|---|---|
reply |
ExecuteReply |
undefined |
The committed reply. |
frameTargetBytes? |
number |
STREAM_FRAME_TARGET_BYTES |
Estimated encoded size to aim for per rows frame. |
maxBytes? |
number |
Number.POSITIVE_INFINITY |
Stop as soon as the frames pass this many bytes. |
Uint8Array
Every frame, concatenated.
PluginError limit_exceeded (maxScalarBytes) when the frames
pass maxBytes.
function executeAdapterBatch(
request,
begin,
options
): Promise<ExecuteReply>;
Runs one host batch in a transaction and commits it with its replay receipt.
| Parameter | Type | Description |
|---|---|---|
request |
AdapterBatchRequest |
The adapter request (execute). |
begin |
() => Promise<AdapterTransaction> |
Opens a transaction on the adapter's engine. |
options |
AdapterBatchOptions |
Timing source. |
Promise<ExecuteReply>
The committed reply, wrap statements included (the host unwraps it).
Whatever a statement, the finalize or commit raised, after the
transaction was rolled back; PluginError unavailable when a prior
receipt committed without its reply.
function executeAdapterBatchStreamed(
request,
begin,
options
): Promise<Uint8Array<ArrayBufferLike>>;
Runs one host batch for executeStreamed and commits it only when the
host can receive its frames.
The frames are encoded inside the transaction. Encoding stops with
limit_exceeded (maxScalarBytes) as soon as they pass one invoke
scalar, the finished frames are decoded under options.limits the way
the host decodes them, and the reassembled reply's encoded size is held to
options.limits.maxBytes the way the host validates it (the decoder alone
allows framing slack past the budget). Any failure rolls the batch back,
so nothing commits that the host would refuse.
| Parameter | Type | Description |
|---|---|---|
request |
AdapterBatchRequest |
The adapter request (executeStreamed). |
begin |
() => Promise<AdapterTransaction> |
Opens a transaction on the adapter's engine. |
options |
AdapterBatchStreamedOptions |
Timing source and the advertised streamed budget. |
Promise<Uint8Array<ArrayBufferLike>>
Every frame of the committed reply, concatenated.
PluginError limit_exceeded when the frames do not fit one
scalar or the budget, or whatever executeAdapterBatch throws.
function executeStreamLimits(caps): ExecuteStreamLimits;
The streamed budget of caps, or its inline caps when the session does
not stream.
| Parameter | Type | Description |
|---|---|---|
caps |
DbCapabilities |
Session capabilities (limits()). |
Limits for an ExecuteStreamDecoder.
function guestBatchIsReadOnly(statements, guestLen): boolean;
True when every guest statement inside the receipt wrap is a SELECT.
An empty or out-of-range guest slice is not read-only, so a write batch never skips its replay payload.
| Parameter | Type | Description |
|---|---|---|
statements |
readonly Pick<AdapterBatchStatement, "kind">[] |
The wrapped statements. |
guestLen |
number |
Guest statement count from the receipt hint. |
boolean
Whether the batch only reads.
function guestReceiptFinalizeStatements(
partial,
guestLen,
guestHash,
readOnly
): AdapterBatchStatement[];
Statements that persist the guest reply on the claimed receipt.
Empty when the prior receipt already holds a payload, belongs to a different request (the host reports the conflict), or is an in-flight claim whose stub this attempt did not insert.
| Parameter | Type | Description |
|---|---|---|
partial |
ExecuteReply |
The wrapped reply so far (prefix, guest and stub results). |
guestLen |
number |
Guest statement count from the receipt hint. |
guestHash |
string |
Guest requestHash from the receipt hint. |
readOnly |
boolean |
Whether the guest slice only reads (guestBatchIsReadOnly). |
The finalize statements to run before COMMIT.
PluginError unavailable when a prior receipt committed without
its reply, internal when the wrap shape is malformed or the payload is
over GUEST_REPLAY_PAYLOAD_MAX_BYTES.
function guestReplayPayload(reply): string;
The replay payload for a guest reply: the JSON envelope the host decodes,
{"operation_id", "statements", "timing"} with each value in the host's
serde form.
| Parameter | Type | Description |
|---|---|---|
reply |
ExecuteReply |
The guest slice of the reply. |
string
The payload text.
PluginError internal when a cell does not encode or the
payload is over GUEST_REPLAY_PAYLOAD_MAX_BYTES.
function limitExceededMessage(limit): string;
Canonical message for a limit error: limit exceeded: maxResultBytes is 262144; used 300000.
| Parameter | Type | Description |
|---|---|---|
limit |
LimitExceeded |
Exceeded cap. |
string
Message text the host and every SDK parse back with parseLimitExceeded.
function parseLimitExceeded(message): LimitExceeded | undefined;
Parses a message produced by limitExceededMessage, possibly wrapped in further text.
| Parameter | Type | Description |
|---|---|---|
message |
string |
Error text. |
LimitExceeded | undefined
The exceeded cap, or undefined when the text is not a limit error.
function rawStreamCeiling(limits): number;
Raw frame bytes a receiver accepts before failing closed: the reply budget plus one eighth for frame headers and one window of slack.
| Parameter | Type | Description |
|---|---|---|
limits |
ExecuteStreamLimits |
Budget. |
number
Byte ceiling on the whole frame sequence and on any one frame.
function requirePluginMigrationRegistration(migrations): PluginMigration[];
Rejects a plugin migration registration that exceeds ABI resource limits.
| Parameter | Type | Description |
|---|---|---|
migrations |
PluginMigration[] |
Ordered databaseMigrations registration. |
The same array when within limits.
Error with code / wireCode payload_too_large when a limit is exceeded.
function runAdapterBatch(
request,
txn,
options
): Promise<ExecuteReply>;
Runs the wrapped statements and the receipt finalize on an open transaction, without committing.
After the prior-receipt SELECT, a completed receipt for this operation
skips the remaining guest work (its results are padded so the wrap shape
stays intact) and the host replays the stored reply.
| Parameter | Type | Description |
|---|---|---|
request |
AdapterBatchRequest |
The adapter request. |
txn |
Pick<AdapterTransaction, "run"> |
The open transaction. |
options |
AdapterBatchOptions |
Timing source. |
Promise<ExecuteReply>
The reply to deliver once the transaction commits.
PluginError unavailable when a prior receipt committed without
its reply, internal when the wrap shape is malformed or the payload is
over GUEST_REPLAY_PAYLOAD_MAX_BYTES, invalid_params when a
result cell is not a valid DbValue, or whatever run threw.
function scanPage(params, fetchStorePage): Promise<ScanPage>;
Answers one scan call from the storefront's own pages.
Fetches the store page params.cursor names and returns at most
MAX_SCAN_PAGE_BOOKS of its titles and removed ids. A store page larger
than that is returned over several calls, each fetching it again. The pass
ends on the last slice of the store page whose StorePage.next is
empty, which carries that page's syncToken and complete.
| Parameter | Type | Description |
|---|---|---|
params |
ScanParams |
The scan call's params. |
fetchStorePage |
FetchStorePage |
Fetches one store page. |
Promise<ScanPage>
The reply for this call.
scan(params: ScanParams): Promise<ScanPage> {
return scanPage(params, async (storeCursor) => {
const page = Number(storeCursor || "1");
const listing = await this.library(params.accountId, page);
return {
books: listing.items.map(toScanBook),
next: listing.hasMore ? String(page + 1) : "",
complete: true,
};
});
}
PluginError invalid_cursor when the cursor was not
written by this helper or no longer fits the store page (the store
changed mid-pass), so the host restarts the pass; internal when a
store cursor is too long for a scan cursor.
function shouldSkipRemainingGuestWork(
results,
total,
guestHash
): boolean;
True when the prefix results show a completed prior receipt, so the guest statements must not run again.
An in-flight claim with the same hash and a read-only receipt with the same hash do not skip; a receipt with a different hash does (the host reports the conflict).
| Parameter | Type | Description |
|---|---|---|
results |
readonly StatementResult[] |
Results so far. |
total |
number |
Wrapped statement count. |
guestHash |
string |
Guest requestHash from the receipt hint. |
boolean
Whether to pad the remaining results instead of running them.
function streamsResults(caps): boolean;
True when caps advertises a streamed result budget.
| Parameter | Type | Description |
|---|---|---|
caps |
DbCapabilities |
Session capabilities (limits()). |
boolean
Whether executeStreamed is worth calling on this session.
Re-exports Abridgement
Re-exports AccountCredential
Re-exports AdapterDatabaseSession
Re-exports AdapterEnv
Re-exports AdapterExecuteRequest
Re-exports AdapterReceipt
Re-exports AdapterSessionReply
Re-exports AdapterStatement
Re-exports AiBinding
Re-exports AiEmbedText
Re-exports AiEntrypoint
Re-exports AiInput
Re-exports AiModel
Re-exports AiModelList
Re-exports AiModels
Re-exports AiModelsReply
Re-exports AiOutput
Re-exports AiRunner
Re-exports AiRunOk
Re-exports AiRunParams
Re-exports AiRunReply
Re-exports AiTask
Re-exports AiTextEmbeddingsInput
Re-exports AiTextEmbeddingsOutput
Re-exports AiTextEmbeddingsRequest
Re-exports AiTextEmbeddingsResponse
Re-exports AiTextRole
Re-exports allowedEntrypointFamilies
Re-exports AtomicTransport
Re-exports AuthenticateUserParams
Re-exports AuthorStub
Re-exports Bindings
Re-exports BookclerkEntrypoint
Re-exports BookclerkEnv
Re-exports Brand
Re-exports ByteRange
Re-exports ByteSource
Re-exports Cancellation
Re-exports CancelledOutcome
Re-exports CancelWatchLike
Re-exports canonicalExecuteRequestHash
Re-exports CatalogCapabilities
Re-exports CatalogDetail
Re-exports CatalogDetailParams
Re-exports CatalogDetailReply
Re-exports CatalogField
Re-exports CatalogHit
Re-exports CatalogHits
Re-exports CatalogHitsReply
Re-exports CatalogSort
Re-exports ChangesPage
Re-exports ChangesReply
Re-exports ChangesRequest
Re-exports ChapterKind
Re-exports ChapterMarker
Re-exports Checkpoint
Re-exports chunkIndexes
Re-exports CliArg
Re-exports CliArgKind
Re-exports cliArgs
Re-exports CliArgSpec
Re-exports CliCommandSpec
Re-exports CliEntrypoint
Re-exports CliInvokeParams
Re-exports CliInvokeReply
Re-exports CliInvokeResult
Re-exports CliSchema
Re-exports CliSchemaReply
Re-exports ColumnReference
Re-exports CompletedOutcome
Re-exports ConfigOption
Re-exports ConfigOptionValue
Re-exports ContentSource
Re-exports CopyReply
Re-exports CopyResult
Re-exports CoverCondition
Re-exports CoverEntrypoint
Re-exports CoverFetcher
Re-exports CoverFetchParams
Re-exports CoverImage
Re-exports CoverImages
Re-exports CoverImagesReply
Re-exports createDatabaseBinding
Re-exports CreateTableSchema
Re-exports Credit
Re-exports CreditLevel
Re-exports CreditRole
Re-exports D1ExecResult
Re-exports D1Meta
Re-exports D1Result
Re-exports Database
Re-exports DatabaseAdapterConfig
Re-exports DatabaseAdapterEntrypoint
Re-exports DatabaseBinding
Re-exports DatabaseBindingOptions
Re-exports dataMigrationOp
Re-exports DbBootstrap
Re-exports DbBootstrapReply
Re-exports DbCapabilities
Re-exports DbCapabilitiesReply
Re-exports DbColumn
Re-exports DbResultSelection
Re-exports DbRow
Re-exports DbStatement
Re-exports DbStatementKind
Re-exports DbTiming
Re-exports DbType
Re-exports DbValue
Re-exports decodeDbCapabilitiesReply
Re-exports decodeDbValue
Re-exports decodeExecuteRequest
Re-exports decodeExecuteResultReply
Re-exports decodeExtensibleConfig
Re-exports DeleteManyReply
Re-exports DeleteManyResult
Re-exports DeliveredCheckpoint
Re-exports DescribeReply
Re-exports Destination
Re-exports DiagnoseReply
Re-exports DiagnoseResult
Re-exports DomainEvent
Re-exports EmptyReply
Re-exports encodeDbCapabilitiesReply
Re-exports encodeDbValue
Re-exports encodeExecuteRequest
Re-exports encodeExecuteResultReply
Re-exports Entrypoint
Re-exports ENTRYPOINT_BINDINGS
Re-exports ENTRYPOINT_CLASSES
Re-exports EntrypointName
Re-exports Entrypoints
Re-exports EntrypointsReply
Re-exports EventAck
Re-exports EventBatch
Re-exports EventBatchReply
Re-exports eventBatchResults
Re-exports EventConsumer
Re-exports EventConsumerSpec
Re-exports EventDeadLetter
Re-exports EventMessage
Re-exports EventOutcome
Re-exports EventPollReply
Re-exports EventPollResult
Re-exports EventPublisher
Re-exports EventPublisherBinding
Re-exports EventReadOptions
Re-exports EventReadPage
Re-exports EventReadReply
Re-exports EventReadRequest
Re-exports EventReject
Re-exports EventResult
Re-exports EventRetry
Re-exports EventSuspended
Re-exports EventSuspendOptions
Re-exports ExecuteReply
Re-exports executeReplyToD1Results
Re-exports ExecuteRequest
Re-exports ExecuteResultReply
Re-exports ExecuteStreamFrame
Re-exports ExecuteStreamHead
Re-exports ExecuteStreamReply
Re-exports ExecuteStreamStatement
Re-exports ExpandCandidatesParams
Re-exports Explicitness
Re-exports ExpressionKind
Re-exports ExtensibleConfig
Re-exports ExternalUser
Re-exports ExternalUserReply
Re-exports FEATURE_SCALAR_LIMITS
Re-exports FEATURE_STORAGE_CHANGES
Re-exports FEATURE_STORAGE_CONDITIONAL_WRITE
Re-exports FEATURE_STORAGE_COPY
Re-exports FEATURE_STORAGE_DELETE_MANY
Re-exports FEATURE_STORAGE_HEAD_MANY
Re-exports FEATURE_STORAGE_MOVE
Re-exports FEATURE_STORAGE_MOVE_MANY
Re-exports FEATURE_STREAMS
Re-exports FetchedFile
Re-exports FetchedFileRole
Re-exports FetchOptions
Re-exports FetchTitleParams
Re-exports FetchTitleReply
Re-exports ForeignKeyConstraint
Re-exports GetOk
Re-exports GetReply
Re-exports GrantedContext
Re-exports GrantedDatabaseTransport
Re-exports GrantedFetcher
Re-exports GrantedJobCapabilities
Re-exports GuestDatabase
Re-exports GuestDatabaseReply
Re-exports HandleReply
Re-exports HeadManyReply
Re-exports HeadManyResult
Re-exports HeadOk
Re-exports HeadReply
Re-exports HealthOk
Re-exports HealthReply
Re-exports HostWebSocket
Re-exports Identifier
Re-exports IdentifierScheme
Re-exports IdentityExportReply
Re-exports IdentityHighWater
Re-exports Ingress
Re-exports IngressEntrypoint
Re-exports IngressHealth
Re-exports IngressHealthReply
Re-exports IngressStarted
Re-exports IngressStartReply
Re-exports Instant
Re-exports IntegerArithKind
Re-exports IntegerArithSite
Re-exports Invocation
Re-exports invocationOf
Re-exports IsolationReq
Re-exports JobCheckpoint
Re-exports JobCompletion
Re-exports JobController
Re-exports JobInvocation
Re-exports JobOutcome
Re-exports jobOutcomeFor
Re-exports JobOutcomeRecord
Re-exports JobRetryOptions
Re-exports JobRunner
Re-exports JobRunnerContext
Re-exports JobSuspendOptions
Re-exports JsonObject
Re-exports jsonPayload
Re-exports KeyOutcome
Re-exports KeyPair
Re-exports KvDeleteOk
Re-exports KvDeleteReply
Re-exports KvGetOk
Re-exports KvGetReply
Re-exports KvListKey
Re-exports KvListKeyBinding
Re-exports KvListOk
Re-exports KvListOptions
Re-exports KvListOptionsBinding
Re-exports KvListReply
Re-exports KvListResultBinding
Re-exports KvNamespace
Re-exports KvNamespaceBinding
Re-exports KvPutOk
Re-exports KvPutOptions
Re-exports KvPutOptionsBinding
Re-exports KvPutReply
Re-exports KvValueType
Re-exports KvValueWithMetadata
Re-exports ListDealsParams
Re-exports ListeningProgress
Re-exports ListOptions
Re-exports ListPage
Re-exports ListReply
Re-exports LoginCompleteParams
Re-exports LoginParams
Re-exports LoginReply
Re-exports LoginResult
Re-exports LoginStartReply
Re-exports LoginStartResult
Re-exports MAX_BATCH_KEYS
Re-exports MAX_CHANGES_CURSOR_BYTES
Re-exports MAX_CHANGES_PAGE
Re-exports MAX_CHECKPOINT_BYTES
Re-exports MAX_LIST_PAGE
Re-exports MAX_PLUGIN_MIGRATION_OPS
Re-exports MAX_PLUGIN_MIGRATION_REGISTRATION_BYTES
Re-exports MAX_PLUGIN_MIGRATION_TOTAL_OPS
Re-exports MAX_SCALAR_BYTES
Re-exports MAX_STREAM_WINDOW_BYTES
Re-exports MAX_WRITE_KEY_BYTES
Re-exports MediaKind
Re-exports MediaSupport
Re-exports MetadataAudioFile
Re-exports MetadataChapter
Re-exports MetadataChapters
Re-exports MetadataChaptersParams
Re-exports MetadataChaptersReply
Re-exports MetadataEntrypoint
Re-exports MetadataField
Re-exports MetadataFileParsed
Re-exports MetadataFileParseParams
Re-exports MetadataFileParseReply
Re-exports MetadataFileRecord
Re-exports MetadataFileRendered
Re-exports MetadataFileRenderParams
Re-exports MetadataFileRenderReply
Re-exports MetadataFiles
Re-exports MetadataFilesEntrypoint
Re-exports MetadataLookupParams
Re-exports MetadataProvider
Re-exports MetadataRecord
Re-exports MetadataRecords
Re-exports MetadataRecordsReply
Re-exports MetadataSearchParams
Re-exports MoveManyPage
Re-exports MoveManyReply
Re-exports MoveManyRequest
Re-exports MoveManyTarget
Re-exports MoveOptions
Re-exports MoveReply
Re-exports MoveResult
Re-exports NamedDatabase
Re-exports NamedEntrypoint
Re-exports NamedKv
Re-exports NamedQueue
Re-exports NamedSqlType
Re-exports NamedStub
Re-exports NetworkGrant
Re-exports NotificationAlertAction
Re-exports NotificationAudience
Re-exports NotificationField
Re-exports NotificationMessage
Re-exports NotificationRaiser
Re-exports NotificationSeverity
Re-exports Notifier
Re-exports NotifierEntrypoint
Re-exports NotifyBinding
Re-exports NotifyDestination
Re-exports NotifyDestinationKind
Re-exports NotifyRaise
Re-exports NotifyRaised
Re-exports NotifyRaiseParams
Re-exports NotifyRaiseReply
Re-exports NotifySendParams
Re-exports NotifySendReply
Re-exports NotifySent
Re-exports NotifyValidated
Re-exports NotifyValidateParams
Re-exports NotifyValidateReply
Re-exports ObjectChange
Re-exports ObjectChangeKind
Re-exports ObjectInfo
Re-exports ObjectMetadata
Re-exports OfferedAacProfile
Re-exports OfferedCodec
Re-exports Oidc
Re-exports OidcClientsOk
Re-exports OidcClientsReply
Re-exports OidcClientTemplate
Re-exports OidcEntrypoint
Re-exports OpenOk
Re-exports OpenReply
Re-exports OptionalColumnReference
Re-exports Origin
Re-exports OriginFetchReply
Re-exports OriginHeader
Re-exports OriginRequest
Re-exports OriginResponse
Re-exports packEmbeddingVectors
Re-exports parseDbValue
Re-exports PhysicalAccess
Re-exports PlainFetch
Re-exports PluginCapabilities
Re-exports PluginCli
Re-exports PluginDescribe
Re-exports PluginErrorCode
Re-exports PluginEvent
Re-exports PluginMigration
Re-exports PluginMigrationOp
Re-exports PluginMigrationsOk
Re-exports PluginMigrationsReply
Re-exports PluginWorker
Re-exports PortalAuthMode
Re-exports PreparedStatement
Re-exports PricedRecord
Re-exports PriceLookup
Re-exports PRODUCT_API_VERSION
Re-exports ProgressSink
Re-exports PublishEvent
Re-exports PublishOk
Re-exports PublishReply
Re-exports PullOk
Re-exports PullReply
Re-exports PurchaseHint
Re-exports PurchaseHintAnswer
Re-exports PurchaseHintParams
Re-exports PurchaseHintReply
Re-exports PurchaseHintResult
Re-exports PurchaseHintsParams
Re-exports PurchaseHintsReply
Re-exports PurchaseHintsResult
Re-exports PutReply
Re-exports PutResult
Re-exports QualityOffer
Re-exports QualityOffersParams
Re-exports QualityOffersReply
Re-exports QualityOffersResult
Re-exports QueueBatch
Re-exports QueueBatchOk
Re-exports QueueBatchReply
Re-exports queueBatchResults
Re-exports QueueBinding
Re-exports QueueConsumer
Re-exports QueueMessage
Re-exports QueueOutcome
Re-exports QueueProducer
Re-exports QueueResult
Re-exports QueueRetry
Re-exports QueueRetryOptions
Re-exports QueueSendBatchEntry
Re-exports QueueSendMessage
Re-exports QueueSendOk
Re-exports QueueSendOptions
Re-exports QueueSendReply
Re-exports ReadOptions
Re-exports ReadResult
Re-exports RejectedOutcome
Re-exports RemoteLibrary
Re-exports RemoteLibraryEntrypoint
Re-exports ResolvedAssignment
Re-exports ResolvedSqlType
Re-exports ResolvedStatement
Re-exports RetryableOutcome
Re-exports RetryOptions
Re-exports RetryToken
Re-exports RevokeAccountParams
Re-exports ScalarLimits
Re-exports ScanBook
Re-exports ScanLibraryParams
Re-exports ScanPage
Re-exports ScanParams
Re-exports ScanReply
Re-exports ScheduledController
Re-exports ScheduledHandler
Re-exports SchemaAction
Re-exports SchemaCreate
Re-exports schemaMigrationOp
Re-exports SearchCatalogParams
Re-exports SeriesEntry
Re-exports SettingGrantState
Re-exports SettingNetworkGrant
Re-exports SettingNetworkKind
Re-exports SocketAutoResponse
Re-exports SocketAutoResponsePair
Re-exports SocketClosed
Re-exports SocketConnectOptions
Re-exports SocketConnectReply
Re-exports SocketConnectRequest
Re-exports SocketFrame
Re-exports SocketHandler
Re-exports SocketHeader
Re-exports SocketInfo
Re-exports SocketList
Re-exports SocketListReply
Re-exports SocketMessage
Re-exports SocketMessageData
Re-exports SocketMessageOk
Re-exports SocketMessageReply
Re-exports Sockets
Re-exports SocketsBinding
Re-exports SocketSendData
Re-exports Source
Re-exports SourceAccount
Re-exports SourceAccounts
Re-exports SourceAccountsReply
Re-exports SqlSpan
Re-exports StatementResult
Re-exports statementResultToD1Result
Re-exports StorageBinding
Re-exports StorageEntrypoint
Re-exports StorefrontEntrypoint
Re-exports SuspendedOutcome
Re-exports SyncListeningReply
Re-exports SyncListeningResult
Re-exports TableConstraint
Re-exports TextCollateSite
Re-exports TitleQualityOffer
Re-exports toBridgeJson
Re-exports TranslateKeysReply
Re-exports TranslateKeysResult
Re-exports TypedDbStatement
Re-exports unpackEmbeddingVectors
Re-exports UserRelationsReply
Re-exports WebhookAckRequest
Re-exports WebhookDelivered
Re-exports WebhookDeliveredEvent
Re-exports WebhookDelivery
Re-exports WebhookHandler
Re-exports WebhookHeader
Re-exports WebhookMessage
Re-exports WebhookPullOptions
Re-exports WebhookPullPage
Re-exports WebhookPullReply
Re-exports WebhookPullRequest
Re-exports WebhookPullResult
Re-exports Webhooks
Re-exports WebhooksBinding
Re-exports WebhookUrl
Re-exports WebhookUrlReply
Re-exports WireEventBatch
Re-exports WireQueueBatch
Re-exports WorkKind
Re-exports wrapPluginFromBinding
Re-exports wrapPluginFromNative
Re-exports WriteChunksError
Re-exports writeChunksOperationId
Re-exports WriteChunksOptions
Re-exports WriteOptions
Re-exports WriteProgress
Source: docs/plugins/sdk/typescript/README.md at main · View as Markdown