@open-conduit/sdk 0.0.0-bootstrap.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.
@@ -0,0 +1,711 @@
1
+ // An in-memory host for unit-testing an extension, as protocol/sdk/sdktest
2
+ // is for Go. testHost serves an Extension over a pair of in-memory streams,
3
+ // as the daemon would, initializes it, and answers the extension-to-host
4
+ // methods from memory: KV with versions and conflicts, event.accept and
5
+ // ingress.deliver, the state.* reads of seeded scopes, Work and Events,
6
+ // secrets from options, artifacts and wait.progress. A test then calls into
7
+ // the extension (configure, operation, route, samples, reconcile, webhook,
8
+ // trigger, task, check, validate, and call for any other method) and
9
+ // inspects what it wrote (kv, events, artifacts, progress).
10
+ //
11
+ // It is not the host: causal depth and rate limits, timers, Work control and
12
+ // config.* are not served (they answer unsupported). Nothing here reads a
13
+ // real clock, the network or the operator's config: the clock is a
14
+ // TestClock the test moves, fixed at testStart until it does.
15
+ import { createHash } from "node:crypto";
16
+ import { PassThrough } from "node:stream";
17
+ import { Code, ProtocolError } from "./errors.js";
18
+ import { base64, toBytes } from "./host.js";
19
+ import { Conn } from "./jsonrpc.js";
20
+ import { matches, t } from "./schema.js";
21
+ import { ConfigureResult, EmitCommit, EmitPlan, EventAcceptParams, IngressDeliverParams, KVCommitParams, KVGetParams, KVListParams, OperationResult, PushResult, RouteDecision, RouteSample, SecretResolveParams, Snapshot, StateParams, WaitPlan, WebhookHandleResult, } from "./wire.js";
22
+ /** The test clock's start (sdktest.Start, conformance.NewClock's start). */
23
+ export const testStart = "2026-10-24T12:00:00.000Z";
24
+ /** The host's clock. It moves only when the test moves it. */
25
+ export class TestClock {
26
+ #ms;
27
+ constructor(start = testStart) {
28
+ this.#ms = new Date(start).getTime();
29
+ }
30
+ /** The clock's time, as an RFC 3339 string. */
31
+ now() {
32
+ return new Date(this.#ms).toISOString();
33
+ }
34
+ /** Moves the clock on by ms milliseconds. */
35
+ advance(ms) {
36
+ this.#ms += ms;
37
+ }
38
+ /** Sets the clock to a time. */
39
+ set(at) {
40
+ this.#ms = new Date(at).getTime();
41
+ }
42
+ }
43
+ /** A KV value's version: a digest of its content, as sdktest.Version. */
44
+ export function kvVersion(value) {
45
+ return createHash("sha256").update(value).digest("hex").slice(0, 32);
46
+ }
47
+ function digest(s) {
48
+ return createHash("sha256").update(s).digest("hex").slice(0, 32);
49
+ }
50
+ function unauthorized(message) {
51
+ return new ProtocolError(Code.Unauthorized, message);
52
+ }
53
+ function invalid(message) {
54
+ return new ProtocolError(Code.Invalid, message);
55
+ }
56
+ /** Decodes a request's params, refusing malformed ones as the host does. */
57
+ function params(schema, raw) {
58
+ const p = raw ?? {};
59
+ if (!matches(schema, p))
60
+ throw invalid("malformed params");
61
+ return p;
62
+ }
63
+ /** Decodes an extension's answer, failing the test's call when it is malformed. */
64
+ function result(schema, method, raw) {
65
+ if (!matches(schema, raw))
66
+ throw new ProtocolError(Code.Invalid, `malformed ${method} result: ${JSON.stringify(raw)}`);
67
+ return raw;
68
+ }
69
+ function bytes(b64) {
70
+ return b64 ? new Uint8Array(Buffer.from(b64, "base64")) : new Uint8Array();
71
+ }
72
+ /**
73
+ * Serves ext on an in-memory host and initializes it. Close it when the
74
+ * test ends (in an after hook), so the served connection ends.
75
+ */
76
+ export async function testHost(ext, o = {}) {
77
+ const h = new TestHost(ext, o);
78
+ await h._initialize();
79
+ return h;
80
+ }
81
+ export class TestHost {
82
+ clock;
83
+ stateDir;
84
+ #ext;
85
+ #conn;
86
+ #toExt;
87
+ #o;
88
+ #scopes = new Set();
89
+ #kv = new Map();
90
+ #events = [];
91
+ #causal = new Map();
92
+ #works;
93
+ #sources = new Map();
94
+ #writers = new Map();
95
+ #artifacts = [];
96
+ #progress = new Map();
97
+ /** The webhook paths the last configure registered. */
98
+ #paths = [];
99
+ #kvVersion;
100
+ #calls = 0;
101
+ constructor(ext, o) {
102
+ this.#ext = ext;
103
+ this.#o = o;
104
+ this.clock = o.clock ?? new TestClock();
105
+ this.stateDir = o.stateDir ?? "/sdktest/state";
106
+ this.#kvVersion = o.kvVersion ?? 0;
107
+ this.#works = [...(o.works ?? [])];
108
+ for (const s of o.scopes ?? [])
109
+ this.#scopes.add(s);
110
+ for (const w of this.#works)
111
+ this.#scopes.add(w.scope_id);
112
+ for (const s of Object.keys(o.secrets ?? {}))
113
+ this.#scopes.add(s);
114
+ for (const k of o.kv ?? [])
115
+ this.#put(k.namespace, k.key, toBytes(k.value));
116
+ for (const e of o.events ?? []) {
117
+ this.#scopes.add(e.scopeId);
118
+ this.#accept(e.scopeId, e.event, "");
119
+ }
120
+ this.#toExt = new PassThrough();
121
+ const fromExt = new PassThrough();
122
+ ext.serve(this.#toExt, fromExt);
123
+ this.#conn = new Conn(fromExt, this.#toExt, (method, raw, signal) => this.#handle(method, raw, signal));
124
+ }
125
+ /** @internal */
126
+ async _initialize() {
127
+ await this.#conn.call("initialize", {
128
+ protocol_versions: [1],
129
+ host: { name: "sdktest", version: "0" },
130
+ state_dir: this.stateDir,
131
+ });
132
+ }
133
+ /** Ends the served connection. */
134
+ close() {
135
+ this.#toExt.end();
136
+ }
137
+ /** The host clock's time. */
138
+ now() {
139
+ return this.clock.now();
140
+ }
141
+ // Calls into the extension.
142
+ /** Makes any host-to-extension call, for a surface without a helper. */
143
+ call(method, p) {
144
+ return this.#conn.call(method, p);
145
+ }
146
+ /**
147
+ * Applies a configuration generation. Each entry's scope becomes
148
+ * configured, and the sources the result registers can be delivered to,
149
+ * reconciled and sent webhooks.
150
+ */
151
+ async configure(entries, o = {}) {
152
+ const out = result(ConfigureResult, "configure", await this.#conn.call("configure", {
153
+ generation: `sdktest-${++this.#calls}`,
154
+ entries,
155
+ ...(o.disabled ? { disabled: o.disabled } : {}),
156
+ ...(o.publicUrl ? { public_url: o.publicUrl } : {}),
157
+ kv: {
158
+ stored: this.#kvVersion,
159
+ declared: this.#ext.manifest.kv_version ?? 0,
160
+ },
161
+ }));
162
+ for (const e of entries)
163
+ this.#scopes.add(e.scope_id);
164
+ this.#sources.clear();
165
+ for (const s of out.sources ?? [])
166
+ this.#sources.set(s.name, s);
167
+ this.#paths = out.webhook_paths ?? [];
168
+ this.#kvVersion = out.kv_version;
169
+ return out;
170
+ }
171
+ /** Checks a config object as config check does: throws the extension's refusal. */
172
+ async validate(kind, type, config) {
173
+ await this.#conn.call("validate", { kind, type, config });
174
+ }
175
+ /**
176
+ * Calls a declared operation with input as its data, by the kind the
177
+ * manifest declares. Unset authority fields default: the first
178
+ * configured scope, Work "sdktest-work", execution "sdktest-execution",
179
+ * an expiry an hour from now, every declared operation and family. An
180
+ * emission is accepted in the authority's scope, and its commit's
181
+ * records are written to KV, as the toolbelt would.
182
+ */
183
+ async operation(name, input = {}, authority = {}) {
184
+ const decl = this.#ext.manifest.provides.operations?.find((d) => d.name === name);
185
+ if (decl === undefined)
186
+ throw new ProtocolError(Code.Undeclared, `operation ${name} is not declared`);
187
+ const a = this.#authority(authority);
188
+ const p = {
189
+ operation: name,
190
+ authority: a,
191
+ input: { data: input },
192
+ request_id: `sdktest-${++this.#calls}`,
193
+ };
194
+ if (decl.kind === "wait") {
195
+ const plan = result(WaitPlan, "operation.wait", await this.#conn.call("operation.wait", p));
196
+ return { output: plan.output.data, wait: plan };
197
+ }
198
+ if (decl.kind === "emit")
199
+ return this.#emit(a, result(EmitPlan, "operation.emit", await this.#conn.call("operation.emit", p)));
200
+ const out = result(OperationResult, "operation.call", await this.#conn.call("operation.call", p));
201
+ return { output: out.output.data };
202
+ }
203
+ /** Asks a route handler to match one input; route.config is given as its data. */
204
+ async route(handler, input) {
205
+ const event = "event" in input.event
206
+ ? input.event
207
+ : { event: input.event, sequence: 1, routed: false };
208
+ return result(RouteDecision, "route.match", await this.#conn.call("route.match", {
209
+ handler,
210
+ input: { ...input, event },
211
+ }));
212
+ }
213
+ /** The sample Events a route handler offers for a route of a scope, as of the clock's now. */
214
+ async samples(handler, scope, route) {
215
+ const out = result(t.object({ samples: t.array(RouteSample) }, { open: true }), "route.samples", await this.#conn.call("route.samples", {
216
+ handler,
217
+ scope,
218
+ route,
219
+ now: this.now(),
220
+ }));
221
+ return out.samples;
222
+ }
223
+ /** Reads one page of a registered source. */
224
+ async reconcile(source, scan = {}) {
225
+ const decl = this.#source(source);
226
+ return result(Snapshot, "ingress.reconcile", await this.#conn.call("ingress.reconcile", {
227
+ name: source,
228
+ scan: { ...scan, source: decl.source },
229
+ }));
230
+ }
231
+ /** Reads every page of a registered source, from its first. */
232
+ async reconcileAll(source) {
233
+ const pages = [];
234
+ let scan = {};
235
+ for (;;) {
236
+ const page = await this.reconcile(source, scan);
237
+ pages.push(page);
238
+ if (!page.next_cursor)
239
+ return pages;
240
+ if (pages.length > 10_000)
241
+ throw new Error(`sdktest: ${source} never stops paging`);
242
+ scan = { scan_id: page.scan_id, cursor: page.next_cursor };
243
+ }
244
+ }
245
+ /** Pushes a delivery to a registered source and accepts what it observed, as the host's ingress does. */
246
+ async push(source, delivery) {
247
+ return this.#deliver({
248
+ name: source,
249
+ delivery: {
250
+ id: delivery.id,
251
+ received_at: delivery.receivedAt ?? this.now(),
252
+ ...(delivery.contentType ? { content_type: delivery.contentType } : {}),
253
+ body: base64(toBytes(delivery.body)),
254
+ },
255
+ });
256
+ }
257
+ /**
258
+ * Sends one HTTP request on a webhook path, as the host's listener
259
+ * does. A path no registered source took answers 404 here, as the
260
+ * listener answers it, without reaching the extension.
261
+ */
262
+ async webhook(path, req = {}) {
263
+ if (!this.#paths.some((p) => path === p || path.startsWith(`${p}/`)))
264
+ return { status: 404, headers: {}, body: new Uint8Array() };
265
+ const header = {};
266
+ for (const [k, v] of Object.entries(req.headers ?? {}))
267
+ header[k] = Array.isArray(v) ? v : [v];
268
+ const out = result(WebhookHandleResult, "webhook.handle", await this.#conn.call("webhook.handle", {
269
+ path,
270
+ method: req.method ?? "POST",
271
+ ...(req.query ? { query: req.query } : {}),
272
+ ...(Object.keys(header).length ? { header } : {}),
273
+ ...(req.body === undefined ? {} : { body: base64(toBytes(req.body)) }),
274
+ received_at: req.receivedAt ?? this.now(),
275
+ ...(req.forwardId ? { forward_id: req.forwardId } : {}),
276
+ }));
277
+ return {
278
+ status: out.status,
279
+ headers: out.header ?? {},
280
+ body: bytes(out.body),
281
+ };
282
+ }
283
+ /** Asks a Work kind's trigger which of inputs triggers the next execution. */
284
+ async trigger(kind, inputs) {
285
+ const out = result(t.object({ index: t.integer() }, { open: true }), "work_kind.trigger", await this.#conn.call("work_kind.trigger", { kind, inputs }));
286
+ return out.index;
287
+ }
288
+ /** Runs a background task once. */
289
+ async task(name) {
290
+ await this.#conn.call("task.run", { task: name });
291
+ }
292
+ /** Runs a doctor check, with an empty configuration view unless config is given. */
293
+ async check(name, o = {}) {
294
+ return (await this.#conn.call("check.run", {
295
+ check: name,
296
+ ...(o.deep ? { deep: true } : {}),
297
+ config: o.config ?? {},
298
+ }));
299
+ }
300
+ // What the extension wrote.
301
+ /** A KV value, or undefined. */
302
+ kv(namespace, key) {
303
+ return this.#kv.get(namespace)?.get(key);
304
+ }
305
+ /** A KV value as UTF-8 text, or undefined. */
306
+ kvText(namespace, key) {
307
+ const v = this.kv(namespace, key);
308
+ return v === undefined ? undefined : new TextDecoder().decode(v);
309
+ }
310
+ /** Every accepted Event, in order, seeded ones included. */
311
+ events() {
312
+ return this.#events.map((e) => e.accepted);
313
+ }
314
+ /** The sources the last configure registered. */
315
+ sources() {
316
+ return [...this.#sources.values()];
317
+ }
318
+ /** Committed artifacts, in order. */
319
+ artifacts() {
320
+ return [...this.#artifacts];
321
+ }
322
+ /** The progress line wait.progress last set for a Work ("" for none). */
323
+ progress(workId) {
324
+ return this.#progress.get(workId) ?? "";
325
+ }
326
+ // Serving the extension's calls.
327
+ #authority(a) {
328
+ const scope = a.scope_id ?? [...this.#scopes][0] ?? "";
329
+ const execution = a.execution_id ?? "sdktest-execution";
330
+ return {
331
+ scope_id: scope,
332
+ work_id: a.work_id ?? "sdktest-work",
333
+ execution_id: execution,
334
+ lease: a.lease ?? { execution_id: execution, owner: "sdktest", epoch: 1 },
335
+ expires_at: a.expires_at ??
336
+ new Date(new Date(this.now()).getTime() + 3_600_000).toISOString(),
337
+ operations: a.operations ??
338
+ (this.#ext.manifest.provides.operations ?? []).map((d) => d.name),
339
+ event_types: a.event_types ??
340
+ (this.#ext.manifest.provides.families ?? []).map((f) => f.type),
341
+ ...(a.trigger_id ? { trigger_id: a.trigger_id } : {}),
342
+ ...(a.connection ? { connection: a.connection } : {}),
343
+ ...(a.work_kinds ? { work_kinds: a.work_kinds } : {}),
344
+ };
345
+ }
346
+ async #emit(a, plan) {
347
+ const e = plan.event;
348
+ if (!(a.event_types ?? []).includes(e.type) || !this.#ownFamily(e.type))
349
+ throw new ProtocolError(Code.Undeclared, "family not declared");
350
+ if (e.id ||
351
+ e.source ||
352
+ e.causation_id ||
353
+ e.work_id ||
354
+ e.execution_id ||
355
+ e.received_at)
356
+ throw unauthorized("the host assigns an emission's identity, source and causation");
357
+ if (!e.delivery_id)
358
+ throw invalid("an emission needs a delivery ID");
359
+ this.#checkWrite(e.data);
360
+ const event = {
361
+ ...e,
362
+ id: `emit/${digest(`${a.execution_id}\x00${e.delivery_id}`)}`,
363
+ source: `execution/${a.execution_id}`,
364
+ work_id: a.work_id,
365
+ execution_id: a.execution_id,
366
+ };
367
+ const { accepted, added } = this.#accept(a.scope_id, event, plan.cause || a.trigger_id || "");
368
+ const info = this.#causal.get(accepted.event.id ?? "");
369
+ const out = { output: undefined, event: accepted, added };
370
+ if (!plan.commit_id)
371
+ return out;
372
+ const commit = result(EmitCommit, "emit.commit", await this.#conn.call("emit.commit", {
373
+ commit_id: plan.commit_id,
374
+ emitted: { event: accepted, added, root: info.root, depth: info.depth },
375
+ }));
376
+ for (const r of commit.records ?? [])
377
+ this.#ownNamespace(r.namespace, r.key);
378
+ if (added)
379
+ for (const r of commit.records ?? [])
380
+ this.#put(r.namespace, r.key, bytes(r.value));
381
+ out.output = commit.output.data;
382
+ return out;
383
+ }
384
+ async #handle(method, raw, _signal) {
385
+ switch (method) {
386
+ case "kv.get": {
387
+ const p = params(KVGetParams, raw);
388
+ this.#ownNamespace(p.namespace, p.key);
389
+ const v = this.kv(p.namespace, p.key);
390
+ return v === undefined
391
+ ? { found: false, entry: { key: "", value: null, version: "" } }
392
+ : {
393
+ found: true,
394
+ entry: { key: p.key, value: base64(v), version: kvVersion(v) },
395
+ };
396
+ }
397
+ case "kv.list": {
398
+ const p = params(KVListParams, raw);
399
+ this.#ownNamespace(p.namespace, "-");
400
+ const entries = [...(this.#kv.get(p.namespace) ?? new Map()).entries()]
401
+ .filter(([k]) => k.startsWith(p.prefix ?? ""))
402
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
403
+ .map(([key, v]) => ({
404
+ key,
405
+ value: base64(v),
406
+ version: kvVersion(v),
407
+ }));
408
+ return { entries };
409
+ }
410
+ case "kv.commit": {
411
+ const p = params(KVCommitParams, raw);
412
+ this.#checkBatch(p.checks ?? [], p.puts ?? [], p.deletes ?? []);
413
+ if ((p.puts?.length ?? 0) + (p.deletes?.length ?? 0) === 0)
414
+ throw invalid("empty batch");
415
+ this.#checks(p.checks ?? []);
416
+ this.#apply(p.puts ?? [], p.deletes ?? []);
417
+ return {};
418
+ }
419
+ case "event.accept":
420
+ return this.#eventAccept(params(EventAcceptParams, raw));
421
+ case "ingress.deliver":
422
+ return this.#deliver(params(IngressDeliverParams, raw));
423
+ case "secret.resolve": {
424
+ const p = params(SecretResolveParams, raw);
425
+ if (!this.#scopes.has(p.scope_id))
426
+ throw unauthorized("scope is not configured for this extension");
427
+ let values;
428
+ if (p.connection) {
429
+ values = this.#o.connectionSecrets?.find((c) => c.scopeId === p.scope_id && c.connection === p.connection)?.values;
430
+ if (values === undefined)
431
+ throw unauthorized("connection is not bound to the extension in the scope");
432
+ }
433
+ else
434
+ values = this.#o.secrets?.[p.scope_id] ?? {};
435
+ return {
436
+ values: Object.fromEntries(p.names.filter((n) => n in values).map((n) => [n, values[n]])),
437
+ };
438
+ }
439
+ case "state.events":
440
+ case "state.work_events": {
441
+ const p = params(StateParams, raw);
442
+ const limit = p.limit && p.limit > 0 && p.limit <= 1000 ? p.limit : 1000;
443
+ if (method === "state.work_events" && !p.id)
444
+ return [];
445
+ return this.#events
446
+ .filter((e) => e.accepted.sequence > (p.after ?? 0) &&
447
+ this.#scopes.has(e.scopeId) &&
448
+ (method === "state.events" ||
449
+ e.accepted.event.work_id === p.id ||
450
+ e.accepted.routed_work_id === p.id))
451
+ .slice(0, limit)
452
+ .map((e) => ({ ...e.accepted, scope_id: e.scopeId }));
453
+ }
454
+ case "state.works":
455
+ return this.#queryWorks(params(StateParams, raw));
456
+ case "state.pending": {
457
+ const p = params(StateParams, raw);
458
+ const w = this.#works.find((x) => x.id === p.id && this.#scopes.has(x.scope_id));
459
+ if (w === undefined)
460
+ throw new ProtocolError(Code.NotFound, "not found");
461
+ return this.#o.pending?.[w.id] ?? [];
462
+ }
463
+ case "wait.progress": {
464
+ const p = params(t.object({ work_id: t.string(), progress: t.string() }, { open: true }), raw);
465
+ this.#progress.set(p.work_id, p.progress);
466
+ return {};
467
+ }
468
+ case "artifact.create": {
469
+ const p = params(t.object({ media_type: t.string() }, { open: true }), raw);
470
+ const id = `writer-${++this.#calls}`;
471
+ this.#writers.set(id, { mediaType: p.media_type, chunks: [] });
472
+ return { writer: id };
473
+ }
474
+ case "artifact.write":
475
+ case "artifact.commit":
476
+ case "artifact.abort": {
477
+ const p = params(t.object({ writer: t.string(), chunk: t.optional(t.string()) }, { open: true }), raw);
478
+ const w = this.#writers.get(p.writer);
479
+ if (w === undefined)
480
+ throw new ProtocolError(Code.NotFound, "unknown writer");
481
+ if (method === "artifact.write") {
482
+ w.chunks.push(bytes(p.chunk));
483
+ return {};
484
+ }
485
+ this.#writers.delete(p.writer);
486
+ if (method === "artifact.abort")
487
+ return {};
488
+ const data = new Uint8Array(Buffer.concat(w.chunks));
489
+ const sha256 = createHash("sha256").update(data).digest("hex");
490
+ const ref = {
491
+ id: `artifact-${this.#artifacts.length + 1}`,
492
+ size: data.length,
493
+ media_type: w.mediaType,
494
+ sha256,
495
+ };
496
+ this.#artifacts.push({ ref, mediaType: w.mediaType, data });
497
+ return ref;
498
+ }
499
+ }
500
+ throw new ProtocolError(Code.Unsupported, `${method} is not served by the test host`);
501
+ }
502
+ /** state.works as the host answers it (StateParams.Query, storage.SelectWorks). */
503
+ #queryWorks(p) {
504
+ if (p.scope_id && !this.#scopes.has(p.scope_id))
505
+ throw unauthorized("scope is not configured for this extension");
506
+ const order = p.order ?? "";
507
+ if (!["", "created", "-created", "updated", "-updated"].includes(order) ||
508
+ (p.limit ?? 0) < 0 ||
509
+ (p.states ?? []).some((s) => !workStates.includes(s)) ||
510
+ (p.updated_since !== undefined &&
511
+ Number.isNaN(Date.parse(p.updated_since))) ||
512
+ (p.cursor !== undefined && Number.isNaN(Date.parse(p.cursor.at))))
513
+ throw invalid("malformed works query");
514
+ const limit = Math.min(p.limit ?? 0, MaxWorksPage);
515
+ const byUpdated = order.endsWith("updated");
516
+ const desc = order.startsWith("-");
517
+ // A Work's position: its time as an instant, then its ID.
518
+ const key = (at, id) => ({ at: Date.parse(at), id });
519
+ const keyOf = (w) => key(byUpdated ? w.updated_at : w.created_at, w.id);
520
+ const cmp = (a, b) => (a.at !== b.at ? a.at - b.at : a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
521
+ const since = p.updated_since === undefined ? undefined : Date.parse(p.updated_since);
522
+ const cursor = p.cursor === undefined ? undefined : key(p.cursor.at, p.cursor.id);
523
+ const selected = this.#works
524
+ .filter((w) => this.#scopes.has(w.scope_id) &&
525
+ (!p.states?.length || p.states.includes(w.state)) &&
526
+ (!p.scope_id || w.scope_id === p.scope_id) &&
527
+ (!p.kind || w.kind === p.kind) &&
528
+ (!p.parent_id || w.parent_id === p.parent_id) &&
529
+ (!p.sources?.length || p.sources.includes(workSource(w))) &&
530
+ (!p.executor || w.latest_executor === p.executor) &&
531
+ (since === undefined || Date.parse(w.updated_at) >= since) &&
532
+ (!p.correlation ||
533
+ (w.correlation_keys ?? []).some((k) => k.source === p.correlation.source &&
534
+ k.external_id === p.correlation.external_id)))
535
+ .sort((a, b) => desc ? cmp(keyOf(b), keyOf(a)) : cmp(keyOf(a), keyOf(b)))
536
+ .filter((w) => cursor === undefined ||
537
+ (desc ? cmp(keyOf(w), cursor) < 0 : cmp(keyOf(w), cursor) > 0));
538
+ return limit > 0 ? selected.slice(0, limit) : selected;
539
+ }
540
+ /**
541
+ * The host's write rule (Manifest.CheckWrite): a payload an extension
542
+ * writes is absent, or names the current version of one of its own
543
+ * declared schemas.
544
+ */
545
+ #checkWrite(data) {
546
+ const schema = data?.schema ?? "";
547
+ const value = data?.data;
548
+ if (schema === "" && (value === undefined || value === null))
549
+ return;
550
+ const name = this.#ext.manifest.name;
551
+ if (!inNamespace(name, schema, "."))
552
+ throw new ProtocolError(Code.Schema, `schema "${schema}" is outside namespace "${name}"`);
553
+ const m = /^(.+)\.v([1-9][0-9]{0,8})$/.exec(schema);
554
+ const decl = m && this.#ext.manifest.provides.schemas?.find((d) => d.name === m[1]);
555
+ const current = decl ? decl.versions[decl.versions.length - 1] : undefined;
556
+ if (!m || current === undefined || Number(m[2]) !== current)
557
+ throw new ProtocolError(Code.Schema, `schema "${schema}" is not the current version of a schema the extension declares`);
558
+ }
559
+ async #deliver(p) {
560
+ const src = this.#sources.get(p.name);
561
+ if (src === undefined)
562
+ throw unauthorized("not a source this extension registered");
563
+ const pushed = result(PushResult, "ingress.push", await this.#conn.call("ingress.push", {
564
+ name: p.name,
565
+ source: src.source,
566
+ delivery: {
567
+ ...p.delivery,
568
+ received_at: p.delivery.received_at || this.now(),
569
+ },
570
+ }));
571
+ const out = { accepted: [], added: [] };
572
+ const events = [
573
+ ...(pushed.events ?? []),
574
+ ...(pushed.observations ?? []).map((o) => o.event),
575
+ ];
576
+ // Checked before any is accepted, so a refused delivery accepts nothing.
577
+ for (const e of events)
578
+ this.#checkWrite(e.data);
579
+ for (const e of events) {
580
+ const r = this.#accept(src.source.scope_id, { ...e, source: e.source || src.source.namespace }, "");
581
+ out.accepted.push(r.accepted);
582
+ out.added.push(r.added);
583
+ }
584
+ return out;
585
+ }
586
+ #eventAccept(p) {
587
+ if (!p.parent)
588
+ throw unauthorized("a subprocess never mints a causal root outside ingress");
589
+ const e = p.event;
590
+ const name = this.#ext.manifest.name;
591
+ if (!this.#ownFamily(e.type))
592
+ throw new ProtocolError(Code.Undeclared, "family not declared");
593
+ if (!e.source || !inNamespace(name, e.source, "/") || !e.delivery_id)
594
+ throw unauthorized("source is outside the extension's namespace");
595
+ if (e.causation_id || e.execution_id)
596
+ throw unauthorized("causation and execution are assigned by the host");
597
+ this.#checkWrite(e.data);
598
+ this.#checkBatch(p.checks ?? [], p.records ?? [], p.deletes ?? []);
599
+ if (!this.#scopes.has(p.scope_id))
600
+ throw unauthorized("scope is not configured for this extension");
601
+ const parent = this.#causal.get(p.parent);
602
+ if (parent === undefined)
603
+ throw unauthorized("parent is not an accepted event");
604
+ if (parent.scopeId !== p.scope_id)
605
+ throw unauthorized("parent is outside the scope");
606
+ this.#checks(p.checks ?? []);
607
+ const r = this.#accept(p.scope_id, { ...e, id: `ext/${digest(`${e.source}\x00${e.delivery_id}`)}` }, p.parent);
608
+ if (r.added)
609
+ this.#apply(p.records ?? [], p.deletes ?? []);
610
+ return { event: r.accepted, added: r.added };
611
+ }
612
+ /** Records e in scope, deduplicated by ID or delivery, as a root or derived from parent. */
613
+ #accept(scopeId, e, parent) {
614
+ const id = e.id || `ext/${digest(`${e.source ?? ""}\x00${e.delivery_id ?? ""}`)}`;
615
+ for (const x of this.#events) {
616
+ const a = x.accepted.event;
617
+ if (a.id === id ||
618
+ (e.delivery_id &&
619
+ a.source === e.source &&
620
+ a.delivery_id === e.delivery_id))
621
+ return { accepted: x.accepted, added: false };
622
+ }
623
+ const received = e.received_at || this.now();
624
+ const event = {
625
+ ...e,
626
+ id,
627
+ received_at: received,
628
+ occurred_at: e.occurred_at || received,
629
+ ...(parent ? { causation_id: parent } : {}),
630
+ };
631
+ const p = parent ? this.#causal.get(parent) : undefined;
632
+ this.#causal.set(id, {
633
+ scopeId,
634
+ root: p?.root ?? id,
635
+ depth: p === undefined ? 0 : p.depth + 1,
636
+ });
637
+ const accepted = {
638
+ event,
639
+ sequence: this.#events.length + 1,
640
+ routed: false,
641
+ };
642
+ this.#events.push({ scopeId, accepted });
643
+ return { accepted, added: true };
644
+ }
645
+ #source(name) {
646
+ const s = this.#sources.get(name);
647
+ if (s === undefined)
648
+ throw new Error(`sdktest: no source ${name}; configure registered ${[...this.#sources.keys()].join(", ") || "none"}`);
649
+ return s;
650
+ }
651
+ #ownFamily(type) {
652
+ return (this.#ext.manifest.provides.families ?? []).some((f) => f.type === type);
653
+ }
654
+ #ownNamespace(ns, key) {
655
+ if (!key || !inNamespace(this.#ext.manifest.name, ns, "."))
656
+ throw unauthorized(`namespace ${ns} is not owned by ${this.#ext.manifest.name}`);
657
+ }
658
+ #checkBatch(checks, puts, deletes) {
659
+ for (const c of checks) {
660
+ this.#ownNamespace(c.namespace, c.key);
661
+ if (Boolean(c.absent) === Boolean(c.version))
662
+ throw invalid("a check names a version or absence");
663
+ }
664
+ for (const p of puts) {
665
+ this.#ownNamespace(p.namespace, p.key);
666
+ if (p.value === null)
667
+ throw invalid("a put needs a value");
668
+ }
669
+ for (const d of deletes)
670
+ this.#ownNamespace(d.namespace, d.key);
671
+ }
672
+ #checks(checks) {
673
+ for (const c of checks) {
674
+ const v = this.kv(c.namespace, c.key);
675
+ if (v === undefined ? !c.absent : c.absent || kvVersion(v) !== c.version)
676
+ throw new ProtocolError(Code.Conflict, "precondition failed");
677
+ }
678
+ }
679
+ #apply(puts, deletes) {
680
+ for (const p of puts)
681
+ this.#put(p.namespace, p.key, bytes(p.value));
682
+ for (const d of deletes)
683
+ this.#kv.get(d.namespace)?.delete(d.key);
684
+ }
685
+ #put(ns, key, value) {
686
+ let m = this.#kv.get(ns);
687
+ if (m === undefined)
688
+ this.#kv.set(ns, (m = new Map()));
689
+ m.set(key, new Uint8Array(value));
690
+ }
691
+ }
692
+ /** The Work states a query may name (domain.WorkState). */
693
+ const workStates = [
694
+ "ready",
695
+ "running",
696
+ "waiting",
697
+ "completed",
698
+ "failed",
699
+ "cancelled",
700
+ ];
701
+ /** The most Work one state.works page holds (protocol.MaxWorksPage). */
702
+ const MaxWorksPage = 1000;
703
+ /** storage.WorkSource: the source of a Work's subject key, or its kind. */
704
+ function workSource(w) {
705
+ return ((w.correlation_keys ?? []).find((k) => k.source !== "core.work")?.source ??
706
+ w.kind);
707
+ }
708
+ /** protocol.Namespace (sep ".") and protocol.SourceNamespace (sep "/"). */
709
+ function inNamespace(name, ns, sep) {
710
+ return (ns === name || (ns.startsWith(name + sep) && ns.length > name.length + 1));
711
+ }