@moonbooth/sdk 0.0.0-stage → 0.1.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/index.js ADDED
@@ -0,0 +1,877 @@
1
+ // TypeScript SDK for the ACT hosted API.
2
+ //
3
+ // ActClient wraps the REST API under /api/v1. It authenticates with a
4
+ // personal API token (Authorization: Bearer <token>). Create a token on
5
+ // the dashboard of the hosted service. A token carries the owning
6
+ // user's identity only; there are no scopes in v0.1.
7
+ //
8
+ // Response shapes mirror the JSON returned by the route handlers in
9
+ // apps/web/src/app/api/v1.
10
+ export const PACKAGE_NAME = "@moonbooth/sdk";
11
+ /** Structured error returned by the API: { error: { code, message, details? } }. */
12
+ export class ActApiError extends Error {
13
+ status;
14
+ code;
15
+ details;
16
+ constructor(status, code, message, details) {
17
+ super(message);
18
+ this.name = "ActApiError";
19
+ this.status = status;
20
+ this.code = code;
21
+ this.details = details;
22
+ }
23
+ }
24
+ // ---------------------------------------------------------------------------
25
+ // Client
26
+ // ---------------------------------------------------------------------------
27
+ export class ActClient {
28
+ baseUrl;
29
+ token;
30
+ fetchFn;
31
+ constructor(options) {
32
+ if (!options.baseUrl)
33
+ throw new Error("ActClient requires a baseUrl.");
34
+ if (!options.token)
35
+ throw new Error("ActClient requires a token.");
36
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
37
+ this.token = options.token;
38
+ this.fetchFn = options.fetchFn ?? ((url, init) => fetch(url, init));
39
+ }
40
+ /** The service base URL this client was constructed with. */
41
+ get serviceBaseUrl() {
42
+ return this.baseUrl;
43
+ }
44
+ async request(method, path, body) {
45
+ const init = {
46
+ method,
47
+ headers: {
48
+ authorization: `Bearer ${this.token}`,
49
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
50
+ },
51
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
52
+ };
53
+ const res = await this.fetchFn(`${this.baseUrl}${path}`, init);
54
+ const data = (await res.json().catch(() => ({})));
55
+ if (!res.ok) {
56
+ const err = (data?.error ?? {});
57
+ throw new ActApiError(res.status, err.code ?? "unknown_error", err.message ?? `Request failed with status ${res.status}.`, err.details);
58
+ }
59
+ return data;
60
+ }
61
+ // Capabilities -----------------------------------------------------------
62
+ async createCapability(input) {
63
+ return this.request("POST", "/api/v1/capabilities", input);
64
+ }
65
+ async listCapabilities() {
66
+ return this.request("GET", "/api/v1/capabilities");
67
+ }
68
+ async getCapability(id) {
69
+ return this.request("GET", `/api/v1/capabilities/${encodeURIComponent(id)}`);
70
+ }
71
+ // Transfers --------------------------------------------------------------
72
+ async createTransfer(input) {
73
+ return this.request("POST", "/api/v1/transfers", input);
74
+ }
75
+ async getTransfer(id) {
76
+ return this.request("GET", `/api/v1/transfers/${encodeURIComponent(id)}`);
77
+ }
78
+ async listTransfers() {
79
+ return this.request("GET", "/api/v1/transfers");
80
+ }
81
+ /** Sender approval. The digest must be the digest the sender reviewed. */
82
+ async approveTransfer(id, digest, recipientEmail) {
83
+ return this.request("POST", `/api/v1/transfers/${encodeURIComponent(id)}/approve`, {
84
+ digest,
85
+ ...(recipientEmail ? { recipientEmail } : {}),
86
+ });
87
+ }
88
+ async revokeTransfer(id) {
89
+ return this.request("POST", `/api/v1/transfers/${encodeURIComponent(id)}/revoke`, {});
90
+ }
91
+ async getPackage(id) {
92
+ return this.request("GET", `/api/v1/transfers/${encodeURIComponent(id)}/package`);
93
+ }
94
+ async acceptTransfer(id) {
95
+ return this.request("POST", `/api/v1/transfers/${encodeURIComponent(id)}/accept`, {});
96
+ }
97
+ async rejectTransfer(id, reason) {
98
+ return this.request("POST", `/api/v1/transfers/${encodeURIComponent(id)}/reject`, {
99
+ ...(reason ? { reason } : {}),
100
+ });
101
+ }
102
+ // Invitations --------------------------------------------------------------
103
+ async getOffer(token) {
104
+ return this.request("GET", `/api/v1/invitations/${encodeURIComponent(token)}`);
105
+ }
106
+ async receiveInvitation(token) {
107
+ return this.request("POST", `/api/v1/invitations/${encodeURIComponent(token)}/receive`, {});
108
+ }
109
+ // Share links --------------------------------------------------------------
110
+ /**
111
+ * Create a share link. Name a transferId (the transfer must already
112
+ * be approved and offered; an unapproved transfer fails with an
113
+ * ActApiError whose code is "needs_approval" and whose details carry
114
+ * the package digest and a contents summary), or a
115
+ * capabilityVersionId with the digest the sender reviewed (approval
116
+ * is recorded as part of creation).
117
+ */
118
+ async createShareLink(input) {
119
+ return this.request("POST", "/api/v1/links", input);
120
+ }
121
+ async listShareLinks() {
122
+ return this.request("GET", "/api/v1/links");
123
+ }
124
+ async revokeShareLink(id) {
125
+ return this.request("POST", "/api/v1/links/revoke", { id });
126
+ }
127
+ /** Read the public rendezvous document for a link token. */
128
+ async inspectShareLink(token) {
129
+ return this.request("GET", `/api/v1/links/${encodeURIComponent(token)}`);
130
+ }
131
+ /** Claim a link as the token owner (an account claim). */
132
+ async claimShareLink(token) {
133
+ return this.request("POST", `/api/v1/links/${encodeURIComponent(token)}/claim`, {});
134
+ }
135
+ // Verification -------------------------------------------------------------
136
+ async requestVerification(transferId, profile) {
137
+ return this.request("POST", `/api/v1/transfers/${encodeURIComponent(transferId)}/verify`, profile !== undefined ? { profile } : {});
138
+ }
139
+ async getVerification(transferId) {
140
+ return this.request("GET", `/api/v1/transfers/${encodeURIComponent(transferId)}/verification`);
141
+ }
142
+ async getReceipt(receiptId) {
143
+ return this.request("GET", `/api/v1/receipts/${encodeURIComponent(receiptId)}`);
144
+ }
145
+ // Webhooks ---------------------------------------------------------------
146
+ //
147
+ // Account-owned outbound event delivery (Living Network Phase 2).
148
+ // A webhook registers a target URL and an event filter; the
149
+ // service POSTs a signed envelope when a matching event lands in a
150
+ // covered booth. The signing secret is returned once, by create
151
+ // and by rotateWebhookSecret; no other method returns it.
152
+ /** Register a webhook. The returned secret is shown once: store it now. */
153
+ async createWebhook(input) {
154
+ return this.request("POST", "/api/v1/webhooks", {
155
+ url: input.url,
156
+ ...(input.eventTypes !== undefined ? { event_types: input.eventTypes } : {}),
157
+ ...(input.boothId !== undefined ? { booth_id: input.boothId } : {}),
158
+ ...(input.participantCredential !== undefined
159
+ ? { participant_credential: input.participantCredential }
160
+ : {}),
161
+ });
162
+ }
163
+ async listWebhooks() {
164
+ return this.request("GET", "/api/v1/webhooks");
165
+ }
166
+ async getWebhook(id) {
167
+ return this.request("GET", `/api/v1/webhooks/${encodeURIComponent(id)}`);
168
+ }
169
+ async updateWebhook(id, patch) {
170
+ return this.request("PATCH", `/api/v1/webhooks/${encodeURIComponent(id)}`, {
171
+ ...(patch.url !== undefined ? { url: patch.url } : {}),
172
+ ...(patch.eventTypes !== undefined ? { event_types: patch.eventTypes } : {}),
173
+ ...(patch.status !== undefined ? { status: patch.status } : {}),
174
+ });
175
+ }
176
+ /** Replace the signing secret. The new secret is shown once. */
177
+ async rotateWebhookSecret(id) {
178
+ return this.request("POST", `/api/v1/webhooks/${encodeURIComponent(id)}/rotate-secret`, {});
179
+ }
180
+ async deleteWebhook(id) {
181
+ return this.request("DELETE", `/api/v1/webhooks/${encodeURIComponent(id)}`);
182
+ }
183
+ /** Enqueue one signed test delivery to the webhook's target. */
184
+ async testWebhook(id) {
185
+ return this.request("POST", `/api/v1/webhooks/${encodeURIComponent(id)}/test`, {});
186
+ }
187
+ async listWebhookDeliveries(id, limit) {
188
+ const query = limit !== undefined ? `?limit=${encodeURIComponent(String(limit))}` : "";
189
+ return this.request("GET", `/api/v1/webhooks/${encodeURIComponent(id)}/deliveries${query}`);
190
+ }
191
+ // Persistent booths, namespaces, aliases ---------------------------------
192
+ //
193
+ // Living Network Phase 7. A persistent booth is account-owned and
194
+ // does not expire; the account administers it through these methods
195
+ // (an API token carries exactly its owner's powers over its owner's
196
+ // own booths). The account claims one namespace; a persistent booth
197
+ // carries at most one alias inside it. An alias is a locator, never
198
+ // a credential: resolving one returns the booth's public discovery
199
+ // document.
200
+ /** The account's namespace, or null when none is claimed. */
201
+ async getNamespace() {
202
+ return this.request("GET", "/api/v1/account/namespace");
203
+ }
204
+ /** Claim the account's one namespace. */
205
+ async claimNamespace(slug) {
206
+ return this.request("POST", "/api/v1/account/namespace", { slug });
207
+ }
208
+ /** Rename the namespace (at most once every 30 days). */
209
+ async renameNamespace(slug) {
210
+ return this.request("PATCH", "/api/v1/account/namespace", { slug });
211
+ }
212
+ /** Create a persistent booth. The creator credential is shown once. */
213
+ async createPersistentBooth(input = {}) {
214
+ return this.request("POST", "/api/v1/account/booths", {
215
+ ...(input.displayName !== undefined ? { display_name: input.displayName } : {}),
216
+ ...(input.objective !== undefined ? { objective: input.objective } : {}),
217
+ ...(input.accessMode !== undefined ? { access_mode: input.accessMode } : {}),
218
+ ...(input.password !== undefined ? { password: input.password } : {}),
219
+ ...(input.invitations !== undefined ? { invitations: input.invitations } : {}),
220
+ ...(input.parentBoothId !== undefined ? { parent_booth_id: input.parentBoothId } : {}),
221
+ });
222
+ }
223
+ async listOwnedBooths() {
224
+ return this.request("GET", "/api/v1/account/booths");
225
+ }
226
+ async getOwnedBooth(id) {
227
+ return this.request("GET", `/api/v1/account/booths/${encodeURIComponent(id)}`);
228
+ }
229
+ async configureOwnedBooth(id, patch) {
230
+ return this.request("PATCH", `/api/v1/account/booths/${encodeURIComponent(id)}`, {
231
+ ...(patch.displayName !== undefined ? { display_name: patch.displayName } : {}),
232
+ ...(patch.objective !== undefined ? { objective: patch.objective } : {}),
233
+ ...(patch.limits !== undefined
234
+ ? {
235
+ limits: {
236
+ ...(patch.limits.maxParticipants !== undefined
237
+ ? { max_participants: patch.limits.maxParticipants }
238
+ : {}),
239
+ ...(patch.limits.retentionDays !== undefined
240
+ ? { retention_days: patch.limits.retentionDays }
241
+ : {}),
242
+ },
243
+ }
244
+ : {}),
245
+ });
246
+ }
247
+ /** Delete a persistent booth. Records are retained; the booth stops resolving. */
248
+ async deleteOwnedBooth(id) {
249
+ return this.request("DELETE", `/api/v1/account/booths/${encodeURIComponent(id)}`);
250
+ }
251
+ async closeOwnedBooth(id) {
252
+ return this.request("POST", `/api/v1/account/booths/${encodeURIComponent(id)}/close`, {});
253
+ }
254
+ async archiveOwnedBooth(id) {
255
+ return this.request("POST", `/api/v1/account/booths/${encodeURIComponent(id)}/archive`, {});
256
+ }
257
+ async restoreOwnedBooth(id) {
258
+ return this.request("POST", `/api/v1/account/booths/${encodeURIComponent(id)}/restore`, {});
259
+ }
260
+ /** Rotate every live participant credential. The new credentials are shown once. */
261
+ async rotateOwnedBoothCredentials(id) {
262
+ return this.request("POST", `/api/v1/account/booths/${encodeURIComponent(id)}/rotate-credentials`, {});
263
+ }
264
+ async revokeOwnedBoothParticipant(id, participantId) {
265
+ return this.request("DELETE", `/api/v1/account/booths/${encodeURIComponent(id)}/participants/${encodeURIComponent(participantId)}`);
266
+ }
267
+ /** The full booth record export (works on a deleted booth too). */
268
+ async exportOwnedBooth(id) {
269
+ return this.request("GET", `/api/v1/account/booths/${encodeURIComponent(id)}/export`);
270
+ }
271
+ async getBoothAlias(id) {
272
+ return this.request("GET", `/api/v1/account/booths/${encodeURIComponent(id)}/alias`);
273
+ }
274
+ async claimBoothAlias(id, slug) {
275
+ return this.request("POST", `/api/v1/account/booths/${encodeURIComponent(id)}/alias`, { slug });
276
+ }
277
+ async renameBoothAlias(id, slug) {
278
+ return this.request("PATCH", `/api/v1/account/booths/${encodeURIComponent(id)}/alias`, { slug });
279
+ }
280
+ async releaseBoothAlias(id) {
281
+ return this.request("DELETE", `/api/v1/account/booths/${encodeURIComponent(id)}/alias`);
282
+ }
283
+ /** Resolve an alias (@namespace/slug) to its booth's public discovery document. */
284
+ async resolveAlias(namespace, slug) {
285
+ return this.request("GET", `/api/v1/aliases/${encodeURIComponent(namespace)}/${encodeURIComponent(slug)}`);
286
+ }
287
+ }
288
+ function serializeInvitationSpec(spec) {
289
+ return {
290
+ ...(spec.role ? { role: spec.role } : {}),
291
+ ...(spec.scopes ? { scopes: spec.scopes } : {}),
292
+ ...(spec.label ? { label: spec.label } : {}),
293
+ ...(spec.subjectRestrictions ? { subject_restrictions: spec.subjectRestrictions } : {}),
294
+ ...(spec.maxRedemptions !== undefined ? { max_redemptions: spec.maxRedemptions } : {}),
295
+ ...(spec.expiresInSeconds !== undefined ? { expires_in_seconds: spec.expiresInSeconds } : {}),
296
+ };
297
+ }
298
+ /** Create a booth. Anonymous: no credential of any kind is sent. */
299
+ export async function createBooth(baseUrl, input = {}, fetchFn) {
300
+ const doFetch = fetchFn ?? ((url, init) => fetch(url, init));
301
+ const body = {};
302
+ if (input.ttlSeconds !== undefined)
303
+ body.ttl_seconds = input.ttlSeconds;
304
+ if (input.closeCondition !== undefined)
305
+ body.close_condition = input.closeCondition;
306
+ if (input.access !== undefined) {
307
+ body.access = {
308
+ mode: input.access.mode,
309
+ ...(input.access.method ? { method: input.access.method } : {}),
310
+ ...(input.access.password ? { password: input.access.password } : {}),
311
+ ...(input.access.defaultScopes ? { default_scopes: input.access.defaultScopes } : {}),
312
+ ...(input.access.invitations
313
+ ? { invitations: input.access.invitations.map(serializeInvitationSpec) }
314
+ : {}),
315
+ };
316
+ }
317
+ if (input.parent !== undefined) {
318
+ body.parent = {
319
+ booth_id: input.parent.boothId,
320
+ ...(input.parent.credential ? { credential: input.parent.credential } : {}),
321
+ };
322
+ }
323
+ const res = await doFetch(`${baseUrl.replace(/\/+$/, "")}/api/v1/booths`, {
324
+ method: "POST",
325
+ headers: { "content-type": "application/json" },
326
+ body: JSON.stringify(body),
327
+ });
328
+ const data = (await res.json().catch(() => ({})));
329
+ if (!res.ok) {
330
+ const err = (data?.error ?? {});
331
+ throw new ActApiError(res.status, err.code ?? "unknown_error", err.message ?? `Request failed with status ${res.status}.`, err.details);
332
+ }
333
+ return data;
334
+ }
335
+ export class BoothClient {
336
+ baseUrl;
337
+ boothId;
338
+ credential;
339
+ fetchFn;
340
+ constructor(options) {
341
+ if (!options.baseUrl)
342
+ throw new Error("BoothClient requires a baseUrl.");
343
+ if (!options.boothId)
344
+ throw new Error("BoothClient requires a boothId.");
345
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
346
+ this.boothId = options.boothId;
347
+ this.credential = options.credential;
348
+ this.fetchFn = options.fetchFn ?? ((url, init) => fetch(url, init));
349
+ }
350
+ /** The credential this client sends, once a join has provided one. */
351
+ get currentCredential() {
352
+ return this.credential;
353
+ }
354
+ async request(method, suffix, body, credentialOverride) {
355
+ const credential = credentialOverride ?? this.credential;
356
+ const init = {
357
+ method,
358
+ headers: {
359
+ ...(credential ? { authorization: `Bearer ${credential}` } : {}),
360
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
361
+ },
362
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
363
+ };
364
+ const res = await this.fetchFn(`${this.baseUrl}/api/v1/booths/${encodeURIComponent(this.boothId)}${suffix}`, init);
365
+ const data = (await res.json().catch(() => ({})));
366
+ if (!res.ok) {
367
+ const err = (data?.error ?? {});
368
+ throw new ActApiError(res.status, err.code ?? "unknown_error", err.message ?? `Request failed with status ${res.status}.`, err.details);
369
+ }
370
+ return data;
371
+ }
372
+ /** The booth's discovery document (no credential required). */
373
+ async discovery() {
374
+ return this.request("GET", "");
375
+ }
376
+ /**
377
+ * Phase 8: publish this child booth's results to its parent. This
378
+ * client's credential is the caller's credential in this booth
379
+ * (the child) and must hold events.read; parentCredential proves
380
+ * standing in the parent (a parent participant credential or the
381
+ * parent's creator credential). What travels is named records
382
+ * only: eventIds from this booth's log and/or a verification
383
+ * receiptId the service holds for this booth's transfer. The
384
+ * service appends one result_published event to the parent
385
+ * carrying references and digests — never this booth's payloads.
386
+ * An idempotencyKey makes a retry return the original publication.
387
+ */
388
+ async publishResult(input) {
389
+ return this.request("POST", "/publish", {
390
+ parent_credential: input.parentCredential,
391
+ ...(input.eventIds ? { event_ids: input.eventIds } : {}),
392
+ ...(input.receiptId ? { receipt_id: input.receiptId } : {}),
393
+ ...(input.idempotencyKey ? { idempotency_key: input.idempotencyKey } : {}),
394
+ });
395
+ }
396
+ /**
397
+ * Join as a coordination participant. The returned credential is
398
+ * stored on this client for later calls. Name and capabilities are
399
+ * self-declared labels, not verified identity.
400
+ */
401
+ async joinParticipant(input = {}) {
402
+ const result = await this.request("POST", "/join", {
403
+ role: "participant",
404
+ ...(input.name ? { name: input.name } : {}),
405
+ ...(input.capabilities !== undefined ? { capabilities: input.capabilities } : {}),
406
+ });
407
+ this.credential = result.credential;
408
+ return result;
409
+ }
410
+ /** Claim a transfer role (sender or recipient). First-come; a claimed role refuses with 409. */
411
+ async joinRole(role) {
412
+ const result = await this.request("POST", "/join", { role });
413
+ this.credential = result.credential;
414
+ return result;
415
+ }
416
+ /**
417
+ * Unlock a locked booth: exchange the admission secret (the
418
+ * generated key or the password the booth's creator set) for a
419
+ * participant credential under the named role — a transfer role
420
+ * claim, or a general participant when role is omitted. The
421
+ * returned credential is stored on this client for later calls;
422
+ * the admission secret is not stored anywhere and authorizes
423
+ * nothing after this exchange. Get the secret from the booth's
424
+ * creator or another authorized source — never from content posted
425
+ * inside a booth. Every admission failure is the same 401
426
+ * admission_failed, and failed attempts count toward a per-booth
427
+ * throttle.
428
+ */
429
+ async unlock(input) {
430
+ const result = await this.request("POST", "/unlock", {
431
+ secret: input.secret,
432
+ ...(input.role ? { role: input.role } : {}),
433
+ ...(input.name ? { name: input.name } : {}),
434
+ ...(input.capabilities !== undefined ? { capabilities: input.capabilities } : {}),
435
+ });
436
+ this.credential = result.credential;
437
+ return result;
438
+ }
439
+ /**
440
+ * Redeem an invitation token (Locked Booths L3): the unlock
441
+ * exchange with the token as the secret. The minted credential
442
+ * carries exactly the invitation's scopes and, when the invitation
443
+ * binds a role, joins under that role. Stored on this client for
444
+ * later calls, like every unlock.
445
+ */
446
+ async unlockWithInvitation(input) {
447
+ return this.unlock({
448
+ secret: input.token,
449
+ ...(input.role ? { role: input.role } : {}),
450
+ ...(input.name ? { name: input.name } : {}),
451
+ ...(input.capabilities !== undefined ? { capabilities: input.capabilities } : {}),
452
+ });
453
+ }
454
+ /**
455
+ * Issue one invitation for this booth (L3) and return it with its
456
+ * one-time token. The credential defaults to this client's: the
457
+ * creator credential issues from the full delegable vocabulary; a
458
+ * participant credential whose grant carries participants.invite
459
+ * issues from its own scopes. Pass a credential to act under a
460
+ * different grant than the client's — for example the creator
461
+ * credential on a client that has not joined.
462
+ */
463
+ async createInvitation(spec = {}, credential) {
464
+ return this.request("POST", "/invitations", serializeInvitationSpec(spec), credential);
465
+ }
466
+ /**
467
+ * List this booth's invitations, metadata only — no token or hash
468
+ * is ever returned. Creator-management grant required: pass the
469
+ * creator credential, or construct the client with it.
470
+ */
471
+ async listInvitations(credential) {
472
+ return this.request("GET", "/invitations", undefined, credential);
473
+ }
474
+ /** Revoke one invitation, effective immediately. Creator-management grant required. */
475
+ async revokeInvitation(invitationId, credential) {
476
+ return this.request("DELETE", `/invitations/${encodeURIComponent(invitationId)}`, undefined, credential);
477
+ }
478
+ /**
479
+ * Rotate this booth's admission secret (Locked Booths L4). The old
480
+ * secret stops admitting new joins the moment this returns; the
481
+ * new generated key is shown once, in the result. Participants who
482
+ * already joined keep their credentials and access — rotation is
483
+ * about admission, not eviction. Omitting method keeps the booth's
484
+ * current method; a password rotation (or a switch to password)
485
+ * requires the new password, which the service never echoes.
486
+ * Creator-management grant required: pass the creator credential,
487
+ * or construct the client with it.
488
+ */
489
+ async rotateAdmissionSecret(input = {}, credential) {
490
+ return this.request("POST", "/rotate-secret", { ...input }, credential);
491
+ }
492
+ /**
493
+ * Protect this booth (Locked Booths L5): lock a booth that was
494
+ * created link-only, applying the create-time admission machinery
495
+ * to it atomically — the verifier and the locked policy land
496
+ * together or not at all. Omitting method mints a generated key,
497
+ * shown once in the result; a password lock requires the password,
498
+ * which the service never echoes. Participants who joined while
499
+ * the booth was link-only keep their credentials and access —
500
+ * locking closes admission behind them, it does not remove them.
501
+ * A booth that is already locked (or invitation-only) refuses.
502
+ * Creator-management grant required: pass the creator credential,
503
+ * or construct the client with it.
504
+ */
505
+ async protectBooth(input = {}, credential) {
506
+ return this.request("POST", "/protect", { ...input }, credential);
507
+ }
508
+ /**
509
+ * List this booth's participant grants, metadata only — no
510
+ * credential or hash is ever returned. Creator-management grant
511
+ * required: pass the creator credential, or construct the client
512
+ * with it.
513
+ */
514
+ async listParticipants(credential) {
515
+ return this.request("GET", "/participants", undefined, credential);
516
+ }
517
+ /**
518
+ * Revoke one participant grant (L4), effective on the revoked
519
+ * credential's very next call. The participant's browser sessions
520
+ * and subscription row are revoked in the same step; revoking a
521
+ * transfer-role grant also releases the role claim.
522
+ * Creator-management grant required — participants.revoke is
523
+ * non-delegable, so no participant credential authorizes this.
524
+ */
525
+ async revokeParticipant(participantId, credential) {
526
+ return this.request("DELETE", `/participants/${encodeURIComponent(participantId)}`, undefined, credential);
527
+ }
528
+ /**
529
+ * Revoke every live grant one invitation issued (L4) — the
530
+ * distinct companion to revokeInvitation, which stops new
531
+ * redemptions and leaves issued grants standing. Each grant dies
532
+ * exactly as if revoked directly. Creator-management grant
533
+ * required.
534
+ */
535
+ async revokeInvitationGrants(invitationId, credential) {
536
+ return this.request("POST", `/invitations/${encodeURIComponent(invitationId)}/revoke-grants`, {}, credential);
537
+ }
538
+ /**
539
+ * File an access request against this booth (L4): a bounded note
540
+ * for the booth's creator from a caller who cannot unlock it. No
541
+ * credential is sent — the filer is precisely a caller without
542
+ * one — and the request grants nothing and admits no one. The
543
+ * creator acts on it, if at all, by issuing an invitation.
544
+ */
545
+ async requestAccess(input = {}) {
546
+ // The empty-string override suppresses the client's credential:
547
+ // an access request is filed by a caller who has none.
548
+ return this.request("POST", "/access-requests", { ...input }, "");
549
+ }
550
+ /**
551
+ * List this booth's access requests in filing order.
552
+ * Creator-management grant required: pass the creator credential,
553
+ * or construct the client with it.
554
+ */
555
+ async listAccessRequests(credential) {
556
+ return this.request("GET", "/access-requests", undefined, credential);
557
+ }
558
+ async listEvents(options = {}) {
559
+ const q = new URLSearchParams();
560
+ if (options.since !== undefined)
561
+ q.set("since", String(options.since));
562
+ if (options.type)
563
+ q.set("type", options.type);
564
+ if (options.subject)
565
+ q.set("subject", options.subject);
566
+ const qs = q.toString();
567
+ return this.request("GET", `/events${qs ? `?${qs}` : ""}`);
568
+ }
569
+ async appendEvent(input) {
570
+ return this.request("POST", "/events", {
571
+ type: input.type,
572
+ subject: input.subject,
573
+ payload: input.payload,
574
+ ...(input.idempotencyKey ? { idempotency_key: input.idempotencyKey } : {}),
575
+ ...(input.inReplyTo ? { in_reply_to: input.inReplyTo } : {}),
576
+ ...(input.relatedIds ? { related_ids: input.relatedIds } : {}),
577
+ });
578
+ }
579
+ async getState() {
580
+ return this.request("GET", "/state");
581
+ }
582
+ /**
583
+ * Propose a pact (Living Network Phase 3): a commitment record in
584
+ * the booth log. The named parties endorse it with acceptPact —
585
+ * never the proposer; endorsement here means a second credential
586
+ * stood behind the pact, and "authorized" is reserved for account
587
+ * holders. Fulfillment is computed from the log: every named
588
+ * party endorsed and every checkable condition met.
589
+ */
590
+ async proposePact(input) {
591
+ return this.appendEvent({
592
+ type: "pact",
593
+ subject: input.subject ?? input.subjects?.[0] ?? "pact",
594
+ payload: {
595
+ title: input.title,
596
+ ...(input.parties ? { parties: input.parties } : {}),
597
+ ...(input.commitments ? { commitments: input.commitments } : {}),
598
+ ...(input.conditions ? { conditions: input.conditions } : {}),
599
+ ...(input.dueAt ? { due_at: input.dueAt } : {}),
600
+ ...(input.subjects ? { subjects: input.subjects } : {}),
601
+ },
602
+ });
603
+ }
604
+ /**
605
+ * Endorse a pact. Refused from the pact's proposer (403
606
+ * pact_self_accept), mirroring decision acceptance: an
607
+ * endorsement is a second participant standing behind the pact.
608
+ */
609
+ async acceptPact(pactEventId) {
610
+ return this.appendEvent({
611
+ type: "pact_accept",
612
+ subject: "pact",
613
+ payload: { pact_event_id: pactEventId },
614
+ });
615
+ }
616
+ /**
617
+ * Cancel a pact. Only the pact's proposer or one of its endorsers
618
+ * may cancel (403 pact_cancel_forbidden otherwise); a cancelled
619
+ * pact is terminal.
620
+ */
621
+ async cancelPact(pactEventId) {
622
+ return this.appendEvent({
623
+ type: "pact_cancel",
624
+ subject: "pact",
625
+ payload: { pact_event_id: pactEventId },
626
+ });
627
+ }
628
+ /** The booth's pacts with their computed statuses, from the state document. */
629
+ async listPacts() {
630
+ const state = await this.getState();
631
+ return state.pacts;
632
+ }
633
+ /**
634
+ * Declare a check (Living Network Phase 5): a set of typed
635
+ * assertions the service evaluates against the booth's log. The
636
+ * declaration is an ordinary log event; the result is computed
637
+ * on read by getCheck / listChecks and is never stored, so the
638
+ * same declaration re-evaluates as evidence lands. The service
639
+ * never runs package code — assertions are data, evaluated by
640
+ * the service's deterministic evaluator.
641
+ */
642
+ async declareCheck(input) {
643
+ return this.appendEvent({
644
+ type: "check",
645
+ subject: input.subject ?? "check",
646
+ payload: {
647
+ title: input.title,
648
+ ...(input.target ? { target: input.target } : {}),
649
+ ...(input.assertions ? { assertions: input.assertions } : {}),
650
+ },
651
+ });
652
+ }
653
+ /** The booth's checks with their computed results. */
654
+ async listChecks() {
655
+ const result = await this.request("GET", "/checks");
656
+ return result.checks;
657
+ }
658
+ /** One check's computed result, by the check event's id. */
659
+ async getCheck(checkEventId) {
660
+ return this.request("GET", `/checks/${encodeURIComponent(checkEventId)}`);
661
+ }
662
+ /**
663
+ * Set or clear the booth's close condition (Phase 3). Pass
664
+ * "pact_terminal:<pact event id>" to close the booth when the
665
+ * named pact reaches a terminal state, "transfer_accepted" or
666
+ * "all_acks" for the standing conditions, or null to clear.
667
+ * Creator-management grant required: pass the creator credential,
668
+ * or construct the client with it.
669
+ */
670
+ async setCloseCondition(closeCondition, credential) {
671
+ return this.request("POST", "/close-condition", { close_condition: closeCondition }, credential);
672
+ }
673
+ /**
674
+ * The changes feed: events relevant to this participant after the
675
+ * cursor, with reasons. waitSeconds holds the request open for a
676
+ * relevant event (25 seconds at most) and returns early when one
677
+ * lands. Delivery is at-least-once; resume with next_since.
678
+ */
679
+ async getChanges(options = {}) {
680
+ const q = new URLSearchParams();
681
+ if (options.since !== undefined)
682
+ q.set("since", String(options.since));
683
+ if (options.until !== undefined)
684
+ q.set("until", String(options.until));
685
+ if (options.mode)
686
+ q.set("mode", options.mode);
687
+ if (options.waitSeconds !== undefined)
688
+ q.set("wait_seconds", String(options.waitSeconds));
689
+ const qs = q.toString();
690
+ return this.request("GET", `/changes${qs ? `?${qs}` : ""}`);
691
+ }
692
+ /** Record that this participant has seen events up to seq. An ack never resolves a conflict. */
693
+ async ack(seq) {
694
+ return this.request("POST", "/ack", { seq });
695
+ }
696
+ /** Replace this participant's subject subscriptions in full. */
697
+ async setSubscriptions(subjects) {
698
+ return this.request("POST", "/subscriptions", { subjects });
699
+ }
700
+ /** Read this participant's durable subscription (subjects, delivery mode, cursors). */
701
+ async getSubscription() {
702
+ return this.request("GET", "/subscriptions");
703
+ }
704
+ /** The participant's pending signals: what in this booth needs their attention, and why. */
705
+ async listSignals() {
706
+ return this.request("GET", "/signals");
707
+ }
708
+ /** Acknowledge a signal. This records that it was seen; it never changes the underlying condition. */
709
+ async ackSignal(signalKey) {
710
+ return this.request("POST", `/signals/${encodeURIComponent(signalKey)}/ack`, {});
711
+ }
712
+ /** Dismiss a signal: seen, and no action will be taken on it. */
713
+ async dismissSignal(signalKey) {
714
+ return this.request("POST", `/signals/${encodeURIComponent(signalKey)}/dismiss`, {});
715
+ }
716
+ /**
717
+ * Declare a watcher: one typed condition on this participant's
718
+ * subscription (Phase 6). When the condition holds against the
719
+ * booth's log it derives as a signal with reason watcher_triggered.
720
+ * Declaring the same condition again returns the existing watcher
721
+ * with created false.
722
+ */
723
+ async createWatcher(condition) {
724
+ return this.request("POST", "/watchers", { condition });
725
+ }
726
+ /** This participant's declared watchers in this booth. */
727
+ async listWatchers() {
728
+ return this.request("GET", "/watchers");
729
+ }
730
+ /** Revoke one of this participant's watchers, by its id. */
731
+ async revokeWatcher(watcherId) {
732
+ return this.request("DELETE", `/watchers/${encodeURIComponent(watcherId)}`);
733
+ }
734
+ /**
735
+ * Phase 10: create a cross-booth subscription into this booth.
736
+ * This client's credential is the caller's credential in this
737
+ * booth (the destination) and must hold subscriptions.manage;
738
+ * sourceCredential proves standing in the source (a source
739
+ * participant holding events.read, or the source's creator
740
+ * credential) and is checked at creation, never stored. The
741
+ * source must be account-owned in v1, and its owner must have set
742
+ * a publication policy for anything to cross. subjects and
743
+ * eventTypes narrow what this subscription receives on top of the
744
+ * policy. An identical active subscription is returned with
745
+ * created false.
746
+ */
747
+ async createCrossSubscription(input) {
748
+ return this.request("POST", "/cross-subscriptions", {
749
+ source_booth_id: input.sourceBoothId,
750
+ source_credential: input.sourceCredential,
751
+ ...(input.subjects ? { subjects: input.subjects } : {}),
752
+ ...(input.eventTypes !== undefined ? { event_types: input.eventTypes } : {}),
753
+ });
754
+ }
755
+ /** This participant's cross-booth subscriptions into this booth. */
756
+ async listCrossSubscriptions() {
757
+ return this.request("GET", "/cross-subscriptions");
758
+ }
759
+ /**
760
+ * Revoke one of this participant's cross-booth subscriptions, by
761
+ * its id. Revoking stops further forwards from that source into
762
+ * this booth; events already forwarded stay in the log.
763
+ */
764
+ async revokeCrossSubscription(subscriptionId) {
765
+ return this.request("DELETE", `/cross-subscriptions/${encodeURIComponent(subscriptionId)}`);
766
+ }
767
+ briefSuffix(options, format) {
768
+ const q = new URLSearchParams();
769
+ if (options.participant)
770
+ q.set("participant", options.participant);
771
+ if (options.subject)
772
+ q.set("subject", options.subject);
773
+ if (options.role)
774
+ q.set("role", options.role);
775
+ if (options.dependencyOf)
776
+ q.set("dependency_of", options.dependencyOf);
777
+ if (options.since !== undefined)
778
+ q.set("since", String(options.since));
779
+ if (options.maxRecords !== undefined)
780
+ q.set("max_records", String(options.maxRecords));
781
+ if (options.maxBytes !== undefined)
782
+ q.set("max_bytes", String(options.maxBytes));
783
+ if (format)
784
+ q.set("format", format);
785
+ const qs = q.toString();
786
+ return `/brief${qs ? `?${qs}` : ""}`;
787
+ }
788
+ /**
789
+ * The booth Brief (Living Network Phase 4): the state cut to the
790
+ * given filters, as a deterministic projection of the log.
791
+ * Accepted and proposed material sit in separate sections, every
792
+ * entry carries its source event id, and omitted counts what the
793
+ * filters and limits cut, with the reason. Nothing is stored and
794
+ * nothing is reworded.
795
+ */
796
+ async getBrief(options = {}) {
797
+ return this.request("GET", this.briefSuffix(options));
798
+ }
799
+ /** The same Brief rendered as Markdown (the server's format=md form). */
800
+ async getBriefMarkdown(options = {}) {
801
+ const credential = this.credential;
802
+ const res = await this.fetchFn(`${this.baseUrl}/api/v1/booths/${encodeURIComponent(this.boothId)}${this.briefSuffix(options, "md")}`, {
803
+ method: "GET",
804
+ headers: { ...(credential ? { authorization: `Bearer ${credential}` } : {}) },
805
+ });
806
+ const text = await res.text();
807
+ if (!res.ok) {
808
+ let code = "unknown_error";
809
+ let message = `Request failed with status ${res.status}.`;
810
+ try {
811
+ const data = JSON.parse(text);
812
+ code = data.error?.code ?? code;
813
+ message = data.error?.message ?? message;
814
+ }
815
+ catch {
816
+ // The error body was not JSON; keep the status-based message.
817
+ }
818
+ throw new ActApiError(res.status, code, message);
819
+ }
820
+ return text;
821
+ }
822
+ /**
823
+ * The booth Replay (Living Network Phase 4): the state as of a
824
+ * sequence number, plus the event slice. With a participant, also
825
+ * the changes that reached them by then; their ack cursor is
826
+ * labeled as a current value, not as-of, and the response carries
827
+ * its causation note — sequence order is never causation.
828
+ */
829
+ async getReplay(options = {}) {
830
+ const q = new URLSearchParams();
831
+ if (options.untilSeq !== undefined)
832
+ q.set("until_seq", String(options.untilSeq));
833
+ if (options.subject)
834
+ q.set("subject", options.subject);
835
+ if (options.participant)
836
+ q.set("participant", options.participant);
837
+ const qs = q.toString();
838
+ return this.request("GET", `/replay${qs ? `?${qs}` : ""}`);
839
+ }
840
+ /**
841
+ * Ask the Booth (Living Network Phase 4): an exact-subject lookup
842
+ * over the log with citations on every record. q is a substring
843
+ * match over subjects and summary fields — the response labels it
844
+ * as substring matching, not semantic search. At least one of
845
+ * subject, type, or q is required.
846
+ */
847
+ async ask(options = {}) {
848
+ const q = new URLSearchParams();
849
+ if (options.subject)
850
+ q.set("subject", options.subject);
851
+ if (options.type)
852
+ q.set("type", options.type);
853
+ if (options.q)
854
+ q.set("q", options.q);
855
+ const qs = q.toString();
856
+ return this.request("GET", `/ask${qs ? `?${qs}` : ""}`);
857
+ }
858
+ /**
859
+ * The booth What-If evaluation (Living Network Phase 11):
860
+ * validate the hypothetical event inputs with the append path's
861
+ * own validation, append them in memory to a copy of the log
862
+ * (truncated at atSeq when given), and return the delta — new
863
+ * conflicts, competing contracts, stale assumptions, affected
864
+ * participants, pact and check status changes — every entry
865
+ * labeled hypothetical with its base seq. Nothing is written:
866
+ * the booth's log and state are unchanged, and making any of it
867
+ * real means posting the events. The impact graph covers
868
+ * declared dependencies and subject links only; the evaluation
869
+ * cannot see anything the log does not declare.
870
+ */
871
+ async evaluateWhatIf(input) {
872
+ return this.request("POST", "/whatif", {
873
+ events: input.events,
874
+ ...(input.atSeq !== undefined ? { at_seq: input.atSeq } : {}),
875
+ });
876
+ }
877
+ }