@open-conduit/sdk 0.0.0-stage → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/host.d.ts ADDED
@@ -0,0 +1,131 @@
1
+ import { type Infer, type Type } from "./schema.js";
2
+ import { AcceptedEvent, ArtifactRef, type Event, EventAcceptResult, type KVCheck, type KVDelete, PendingInput, Work } from "./wire.js";
3
+ /** The most Work one state.works page holds (protocol.MaxWorksPage). */
4
+ export declare const MaxWorksPage = 1000;
5
+ /**
6
+ * What a state.works read selects (storage.WorkQuery): Work in any of
7
+ * `states`, of `scopeId`, `kind`, `parentId`, any of `sources` and
8
+ * `executor`, updated at or after `updatedSince` (an RFC 3339 time).
9
+ * `order` is "created", "-created", "updated" or "-updated".
10
+ */
11
+ export interface WorksQuery {
12
+ scopeId?: string;
13
+ states?: string[];
14
+ kind?: string;
15
+ parentId?: string;
16
+ sources?: string[];
17
+ executor?: string;
18
+ updatedSince?: string;
19
+ order?: "created" | "-created" | "updated" | "-updated";
20
+ limit?: number;
21
+ }
22
+ /** Makes one extension-to-host call; the result is decoded by the caller. */
23
+ export type Caller = (method: string, params: unknown, signal?: AbortSignal) => Promise<unknown>;
24
+ /** A KV value: bytes, or a string stored as its UTF-8 bytes. */
25
+ export type Value = Uint8Array | string;
26
+ /** A KV entry and its version, which a later commit can require unchanged. */
27
+ export interface Entry {
28
+ key: string;
29
+ value: Uint8Array;
30
+ version: string;
31
+ }
32
+ export interface Put {
33
+ namespace: string;
34
+ key: string;
35
+ value: Value;
36
+ }
37
+ /** A precondition batch, applied atomically: a failed check changes nothing. */
38
+ export interface Batch {
39
+ checks?: KVCheck[];
40
+ puts?: Put[];
41
+ deletes?: KVDelete[];
42
+ }
43
+ /** A delivery to push to a source: a webhook's body, say. */
44
+ export interface DeliveryInput {
45
+ /** The sender's delivery ID: a retry carries the same one. */
46
+ id: string;
47
+ /** When it was received (default now). */
48
+ receivedAt?: string;
49
+ contentType?: string;
50
+ body?: Value;
51
+ }
52
+ /** One Event derived from parent, committed atomically with the batch. */
53
+ export interface Accept extends Batch {
54
+ scopeId: string;
55
+ parent: string;
56
+ event: Event;
57
+ }
58
+ export declare class Host {
59
+ #private;
60
+ constructor(call: Caller);
61
+ /** Makes any extension-to-host call, decoding its result through result. */
62
+ call<S extends Type<unknown>>(method: string, params: unknown, result: S, signal?: AbortSignal): Promise<Infer<S>>;
63
+ /** Runs one of the extension's own tasks on the host's next pass. */
64
+ wakeTask(task: string, signal?: AbortSignal): Promise<void>;
65
+ /** A KV value and its version, or undefined when the key is absent. */
66
+ get(namespace: string, key: string, signal?: AbortSignal): Promise<Entry | undefined>;
67
+ /** The entries under prefix, in lexical key order. */
68
+ list(namespace: string, prefix?: string, signal?: AbortSignal): Promise<Entry[]>;
69
+ /** Applies a batch atomically; a failed check throws ProtocolError conflict. */
70
+ commit(b: Batch, signal?: AbortSignal): Promise<void>;
71
+ /**
72
+ * Reads a key, applies fn and commits with a version check, retrying when
73
+ * another writer got there first. fn returns undefined to delete the key.
74
+ */
75
+ update(namespace: string, key: string, fn: (old: Uint8Array | undefined) => Value | undefined | Promise<Value | undefined>, signal?: AbortSignal): Promise<void>;
76
+ /**
77
+ * Derives one Event from parent (an accepted Event in a configured scope),
78
+ * committing the batch's KV writes atomically with it.
79
+ */
80
+ accept(a: Accept, signal?: AbortSignal): Promise<EventAcceptResult>;
81
+ /**
82
+ * Hands a delivery (a verified webhook's body) to the source registered
83
+ * as name. The host calls the source's push with it and answers once its
84
+ * Events are durably accepted: added[i] is false for an Event it already
85
+ * had, such as a sender's retry.
86
+ */
87
+ deliver(name: string, delivery: DeliveryInput, signal?: AbortSignal): Promise<{
88
+ accepted: AcceptedEvent[];
89
+ added: boolean[];
90
+ }>;
91
+ /** Accepted Events of the configured scopes after a sequence. */
92
+ events(after?: number, limit?: number, signal?: AbortSignal): Promise<AcceptedEvent[]>;
93
+ /**
94
+ * One Work's accepted Events of the configured scopes after a sequence:
95
+ * those naming it and those routed to it. The host reads them from its
96
+ * index, so the cost follows the Work's own Events, not the whole log.
97
+ */
98
+ workEvents(workId: string, after?: number, limit?: number, signal?: AbortSignal): Promise<AcceptedEvent[]>;
99
+ /** Work of the configured scopes (one scope when scopeId is set). */
100
+ works(scopeId?: string, signal?: AbortSignal): Promise<Work[]>;
101
+ /**
102
+ * The Work a query selects, of the configured scopes and the extension's
103
+ * own kinds, in its order (by creation unless `order` says otherwise),
104
+ * at most `limit` (all when unset). The host reads them through its
105
+ * indexes a page at a time, so the cost follows the Work selected, not
106
+ * every Work ever made: ask for live Work with `states`, or for Work
107
+ * changed since a time with `updatedSince`.
108
+ */
109
+ queryWorks(query: WorksQuery, signal?: AbortSignal): Promise<Work[]>;
110
+ /**
111
+ * The input routed to a Work that no attempt of it has read yet, oldest
112
+ * first. Ready Work with none has read everything routed to it; ready
113
+ * Work with some is about to start on it.
114
+ */
115
+ pending(workId: string, signal?: AbortSignal): Promise<PendingInput[]>;
116
+ /** Resolves secret names bound to the extension's entry in a scope. */
117
+ secrets(scopeId: string, names: string[], signal?: AbortSignal): Promise<Record<string, string>>;
118
+ /**
119
+ * Resolves secret names of a connection an entry or binding in the scope
120
+ * names, such as an operation's authority.connection.
121
+ */
122
+ connectionSecrets(scopeId: string, connection: string, names: string[], signal?: AbortSignal): Promise<Record<string, string>>;
123
+ /** Writes an immutable artifact in chunks, each acknowledged before the next. */
124
+ artifact(mediaType: string, data: Value, signal?: AbortSignal): Promise<ArtifactRef>;
125
+ /** Sets the progress line of a Work's active Wait ("" clears it). */
126
+ waitProgress(workId: string, progress: string, signal?: AbortSignal): Promise<void>;
127
+ }
128
+ export declare function toBytes(v: Value): Uint8Array;
129
+ export declare function base64(b: Uint8Array): string;
130
+ /** Decodes a KV value as UTF-8 text. */
131
+ export declare function text(v: Uint8Array): string;
package/dist/host.js ADDED
@@ -0,0 +1,253 @@
1
+ // The extension's client for the scoped extension-to-host methods, as
2
+ // protocol/sdk/host.go offers them. The host binds every call to the
3
+ // identity it started the process with, so nothing here can name another
4
+ // extension's namespaces or scopes.
5
+ import { Code, ProtocolError } from "./errors.js";
6
+ import { MaxChunkBytes } from "./jsonrpc.js";
7
+ import { matches, t } from "./schema.js";
8
+ import { AcceptedEvent, ArtifactCreateResult, ArtifactRef, EventAcceptResult, IngressDeliverResult, KVGetResult, KVListResult, PendingInput, SecretResolveResult, Work, } from "./wire.js";
9
+ /** The most Work one state.works page holds (protocol.MaxWorksPage). */
10
+ export const MaxWorksPage = 1000;
11
+ const Empty = t.any();
12
+ export class Host {
13
+ #call;
14
+ constructor(call) {
15
+ this.#call = call;
16
+ }
17
+ /** Makes any extension-to-host call, decoding its result through result. */
18
+ async call(method, params, result, signal) {
19
+ const out = await this.#call(method, params, signal);
20
+ // A result that doesn't match is refused, as the Go SDK's decoding refuses it.
21
+ if (!matches(result, out))
22
+ throw new ProtocolError(Code.Invalid, `malformed ${method} result`);
23
+ return out;
24
+ }
25
+ /** Runs one of the extension's own tasks on the host's next pass. */
26
+ async wakeTask(task, signal) {
27
+ await this.#call("task.wake", { task }, signal);
28
+ }
29
+ /** A KV value and its version, or undefined when the key is absent. */
30
+ async get(namespace, key, signal) {
31
+ const out = await this.call("kv.get", { namespace, key }, KVGetResult, signal);
32
+ return out.found ? entry(out.entry) : undefined;
33
+ }
34
+ /** The entries under prefix, in lexical key order. */
35
+ async list(namespace, prefix = "", signal) {
36
+ const out = await this.call("kv.list", prefix === "" ? { namespace } : { namespace, prefix }, KVListResult, signal);
37
+ return (out.entries ?? []).map(entry);
38
+ }
39
+ /** Applies a batch atomically; a failed check throws ProtocolError conflict. */
40
+ async commit(b, signal) {
41
+ const { puts, ...rest } = batchFields(b);
42
+ await this.call("kv.commit", puts === undefined ? rest : { ...rest, puts }, Empty, signal);
43
+ }
44
+ /**
45
+ * Reads a key, applies fn and commits with a version check, retrying when
46
+ * another writer got there first. fn returns undefined to delete the key.
47
+ */
48
+ async update(namespace, key, fn, signal) {
49
+ for (let attempt = 0; attempt < 16; attempt++) {
50
+ const old = await this.get(namespace, key, signal);
51
+ const value = await fn(old?.value);
52
+ const check = old === undefined
53
+ ? { namespace, key, absent: true }
54
+ : { namespace, key, version: old.version };
55
+ const b = value === undefined
56
+ ? { checks: [check], deletes: [{ namespace, key }] }
57
+ : { checks: [check], puts: [{ namespace, key, value }] };
58
+ try {
59
+ return await this.commit(b, signal);
60
+ }
61
+ catch (err) {
62
+ if (!(err instanceof ProtocolError && err.code === Code.Conflict))
63
+ throw err;
64
+ }
65
+ }
66
+ throw new ProtocolError(Code.Conflict, "update kept conflicting");
67
+ }
68
+ /**
69
+ * Derives one Event from parent (an accepted Event in a configured scope),
70
+ * committing the batch's KV writes atomically with it.
71
+ */
72
+ async accept(a, signal) {
73
+ const { puts, ...rest } = batchFields(a);
74
+ // event.accept calls its puts "records".
75
+ const params = {
76
+ scope_id: a.scopeId,
77
+ parent: a.parent,
78
+ event: a.event,
79
+ ...rest,
80
+ };
81
+ return this.call("event.accept", puts === undefined ? params : { ...params, records: puts }, EventAcceptResult, signal);
82
+ }
83
+ /**
84
+ * Hands a delivery (a verified webhook's body) to the source registered
85
+ * as name. The host calls the source's push with it and answers once its
86
+ * Events are durably accepted: added[i] is false for an Event it already
87
+ * had, such as a sender's retry.
88
+ */
89
+ async deliver(name, delivery, signal) {
90
+ const out = await this.call("ingress.deliver", {
91
+ name,
92
+ delivery: {
93
+ id: delivery.id,
94
+ received_at: delivery.receivedAt ?? new Date().toISOString(),
95
+ ...(delivery.contentType
96
+ ? { content_type: delivery.contentType }
97
+ : {}),
98
+ ...(delivery.body === undefined
99
+ ? {}
100
+ : { body: base64(toBytes(delivery.body)) }),
101
+ },
102
+ }, IngressDeliverResult, signal);
103
+ return { accepted: out.accepted ?? [], added: out.added ?? [] };
104
+ }
105
+ /** Accepted Events of the configured scopes after a sequence. */
106
+ async events(after = 0, limit = 0, signal) {
107
+ const params = {
108
+ ...(after > 0 ? { after } : {}),
109
+ ...(limit > 0 ? { limit } : {}),
110
+ };
111
+ return ((await this.call("state.events", params, t.nullable(t.array(AcceptedEvent)), signal)) ?? []);
112
+ }
113
+ /**
114
+ * One Work's accepted Events of the configured scopes after a sequence:
115
+ * those naming it and those routed to it. The host reads them from its
116
+ * index, so the cost follows the Work's own Events, not the whole log.
117
+ */
118
+ async workEvents(workId, after = 0, limit = 0, signal) {
119
+ if (workId === "")
120
+ return [];
121
+ const params = {
122
+ id: workId,
123
+ ...(after > 0 ? { after } : {}),
124
+ ...(limit > 0 ? { limit } : {}),
125
+ };
126
+ return ((await this.call("state.work_events", params, t.nullable(t.array(AcceptedEvent)), signal)) ?? []);
127
+ }
128
+ /** Work of the configured scopes (one scope when scopeId is set). */
129
+ async works(scopeId = "", signal) {
130
+ return this.queryWorks(scopeId === "" ? {} : { scopeId }, signal);
131
+ }
132
+ /**
133
+ * The Work a query selects, of the configured scopes and the extension's
134
+ * own kinds, in its order (by creation unless `order` says otherwise),
135
+ * at most `limit` (all when unset). The host reads them through its
136
+ * indexes a page at a time, so the cost follows the Work selected, not
137
+ * every Work ever made: ask for live Work with `states`, or for Work
138
+ * changed since a time with `updatedSince`.
139
+ */
140
+ async queryWorks(query, signal) {
141
+ const order = query.order ?? "created";
142
+ const all = [];
143
+ let cursor;
144
+ for (;;) {
145
+ const page = query.limit !== undefined && query.limit > 0
146
+ ? Math.min(MaxWorksPage, query.limit - all.length)
147
+ : MaxWorksPage;
148
+ const params = {
149
+ ...(query.scopeId ? { scope_id: query.scopeId } : {}),
150
+ ...(query.states?.length ? { states: query.states } : {}),
151
+ ...(query.kind ? { kind: query.kind } : {}),
152
+ ...(query.parentId ? { parent_id: query.parentId } : {}),
153
+ ...(query.sources?.length ? { sources: query.sources } : {}),
154
+ ...(query.executor ? { executor: query.executor } : {}),
155
+ ...(query.updatedSince ? { updated_since: query.updatedSince } : {}),
156
+ ...(query.order ? { order: query.order } : {}),
157
+ ...(cursor ? { cursor } : {}),
158
+ limit: page,
159
+ };
160
+ const got = (await this.call("state.works", params, t.nullable(t.array(Work)), signal)) ?? [];
161
+ // A host that predates the query answers every Work in one page.
162
+ if (got.length > page)
163
+ return got;
164
+ all.push(...got);
165
+ const last = got[got.length - 1];
166
+ if (got.length < page ||
167
+ last === undefined ||
168
+ (query.limit !== undefined &&
169
+ query.limit > 0 &&
170
+ all.length >= query.limit))
171
+ return all;
172
+ cursor = {
173
+ at: order.endsWith("updated") ? last.updated_at : last.created_at,
174
+ id: last.id,
175
+ };
176
+ }
177
+ }
178
+ /**
179
+ * The input routed to a Work that no attempt of it has read yet, oldest
180
+ * first. Ready Work with none has read everything routed to it; ready
181
+ * Work with some is about to start on it.
182
+ */
183
+ async pending(workId, signal) {
184
+ return ((await this.call("state.pending", { id: workId }, t.nullable(t.array(PendingInput)), signal)) ?? []);
185
+ }
186
+ /** Resolves secret names bound to the extension's entry in a scope. */
187
+ async secrets(scopeId, names, signal) {
188
+ const out = await this.call("secret.resolve", { scope_id: scopeId, names }, SecretResolveResult, signal);
189
+ return out.values ?? {};
190
+ }
191
+ /**
192
+ * Resolves secret names of a connection an entry or binding in the scope
193
+ * names, such as an operation's authority.connection.
194
+ */
195
+ async connectionSecrets(scopeId, connection, names, signal) {
196
+ const out = await this.call("secret.resolve", { scope_id: scopeId, connection, names }, SecretResolveResult, signal);
197
+ return out.values ?? {};
198
+ }
199
+ /** Writes an immutable artifact in chunks, each acknowledged before the next. */
200
+ async artifact(mediaType, data, signal) {
201
+ const bytes = toBytes(data);
202
+ const { writer } = await this.call("artifact.create", { media_type: mediaType }, ArtifactCreateResult, signal);
203
+ try {
204
+ for (let at = 0; at < bytes.length; at += MaxChunkBytes) {
205
+ await this.call("artifact.write", { writer, chunk: base64(bytes.subarray(at, at + MaxChunkBytes)) }, Empty, signal);
206
+ }
207
+ }
208
+ catch (err) {
209
+ // Not under signal: a cancelled write must still release the writer.
210
+ await this.call("artifact.abort", { writer }, Empty).catch(() => { });
211
+ throw err;
212
+ }
213
+ return this.call("artifact.commit", { writer }, ArtifactRef, signal);
214
+ }
215
+ /** Sets the progress line of a Work's active Wait ("" clears it). */
216
+ async waitProgress(workId, progress, signal) {
217
+ await this.call("wait.progress", { work_id: workId, progress }, Empty, signal);
218
+ }
219
+ }
220
+ function entry(e) {
221
+ return {
222
+ key: e.key,
223
+ value: e.value === null
224
+ ? new Uint8Array()
225
+ : new Uint8Array(Buffer.from(e.value, "base64")),
226
+ version: e.version,
227
+ };
228
+ }
229
+ function batchFields(b) {
230
+ return {
231
+ ...(b.checks?.length ? { checks: b.checks } : {}),
232
+ ...(b.puts?.length
233
+ ? {
234
+ puts: b.puts.map((p) => ({
235
+ namespace: p.namespace,
236
+ key: p.key,
237
+ value: base64(toBytes(p.value)),
238
+ })),
239
+ }
240
+ : {}),
241
+ ...(b.deletes?.length ? { deletes: b.deletes } : {}),
242
+ };
243
+ }
244
+ export function toBytes(v) {
245
+ return typeof v === "string" ? new TextEncoder().encode(v) : v;
246
+ }
247
+ export function base64(b) {
248
+ return Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString("base64");
249
+ }
250
+ /** Decodes a KV value as UTF-8 text. */
251
+ export function text(v) {
252
+ return new TextDecoder().decode(v);
253
+ }
@@ -0,0 +1,10 @@
1
+ export { extension, Extension, Server, ProtocolVersions } from "./extension.js";
2
+ export type { CallContext, CheckContext, CheckFn, CommitOut, Context, EmitOut, EmitSpec, EntryOf, EntryTypeSpec, IngressTypeSpec, MigrateFn, OperationSpec, Options, PushDelivery, RouteCall, RouteSpec, SampleCall, SourceSpec, TaskFn, WaitOut, WaitSpec, WebhookContext, WebhookRequest, WebhookResponse, WorkKindSpec, } from "./extension.js";
3
+ export { Host, MaxWorksPage, text } from "./host.js";
4
+ export type { Accept, Batch, Caller, DeliveryInput, Entry, Put, Value, WorksQuery, } from "./host.js";
5
+ export { t, check, diagnose, matches, isRecord } from "./schema.js";
6
+ export type { Infer, Type } from "./schema.js";
7
+ export { Code, OperationError, ProtocolError, ConfigError, pointer, CancelledError, TransportError, isProtocolCode, } from "./errors.js";
8
+ export type { ConfigDiagnostic } from "./errors.js";
9
+ export { Conn, MaxMessageBytes, MaxChunkBytes, MaxInflight, MaxControlInflight, laneOf, } from "./jsonrpc.js";
10
+ export * from "./wire.js";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ // @open-conduit/sdk: build an Open Conduit extension in TypeScript.
2
+ //
3
+ // import { extension, t, OperationError } from "@open-conduit/sdk";
4
+ //
5
+ // const ext = extension("weather", { version: "0.1.0" })
6
+ // .operation("weather.forecast", {
7
+ // input: t.object({ city: t.string({ description: "The city, by name." }) }),
8
+ // guidance: "Call `weather.forecast` before planning anything outdoors.",
9
+ // handler: async ({ city }) => ({ city, summary: "sunny" }),
10
+ // });
11
+ // await ext.main();
12
+ //
13
+ // The guide is site/src/content/docs/architecture/extension-packaging.md.
14
+ export { extension, Extension, Server, ProtocolVersions } from "./extension.js";
15
+ export { Host, MaxWorksPage, text } from "./host.js";
16
+ export { t, check, diagnose, matches, isRecord } from "./schema.js";
17
+ export { Code, OperationError, ProtocolError, ConfigError, pointer, CancelledError, TransportError, isProtocolCode, } from "./errors.js";
18
+ export { Conn, MaxMessageBytes, MaxChunkBytes, MaxInflight, MaxControlInflight, laneOf, } from "./jsonrpc.js";
19
+ export * from "./wire.js";
@@ -0,0 +1,39 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ /** Bounds of protocol version 1 (protocol/protocol.go). */
3
+ export declare const MaxMessageBytes: number;
4
+ export declare const MaxChunkBytes: number;
5
+ export declare const MaxInflight = 64;
6
+ /** Capacity reserved for control methods on top of MaxInflight. */
7
+ export declare const MaxControlInflight = 16;
8
+ /** Which capacity an extension serves a host request from. */
9
+ export type Lane = "bounded" | "held" | "control";
10
+ /** The lane of a host-to-extension method (protocol.LaneOf). */
11
+ export declare function laneOf(method: string): Lane;
12
+ export declare const CancelMethod = "$/cancel";
13
+ /** Serves one inbound request. Its signal aborts when the peer cancels. */
14
+ export type Handler = (method: string, params: unknown, signal: AbortSignal) => Promise<unknown>;
15
+ export interface ConnOptions {
16
+ maxMessage?: number;
17
+ maxInflight?: number;
18
+ /** Classifies inbound requests; an extension sets it, a host does not. */
19
+ lane?: (method: string) => Lane;
20
+ /** Receives why a malformed stream closed the connection. */
21
+ onProtocolError?: (reason: string) => void;
22
+ }
23
+ /** One JSON-RPC peer. */
24
+ export declare class Conn {
25
+ #private;
26
+ readonly done: Promise<void>;
27
+ constructor(input: Readable, output: Writable, handler: Handler, o?: ConnOptions);
28
+ /** Reports whether the connection has ended. */
29
+ get closed(): boolean;
30
+ /** Ends the connection; pending calls reject with TransportError. */
31
+ close(): void;
32
+ /**
33
+ * Sends a request and resolves with its result, undecoded. Aborting
34
+ * signal sends $/cancel and rejects at once with CancelledError.
35
+ */
36
+ call(method: string, params?: unknown, signal?: AbortSignal): Promise<unknown>;
37
+ /** Sends a notification (no response). */
38
+ notify(method: string, params?: unknown): void;
39
+ }