@graview/ship 0.1.2 → 0.1.4

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.
Files changed (46) hide show
  1. package/README.md +312 -13
  2. package/dist/browser.d.ts +4 -4
  3. package/dist/browser.d.ts.map +1 -1
  4. package/dist/browser.js +2 -2
  5. package/dist/browser.js.map +1 -1
  6. package/dist/handler.d.ts +192 -26
  7. package/dist/handler.d.ts.map +1 -1
  8. package/dist/handler.js +383 -340
  9. package/dist/handler.js.map +1 -1
  10. package/dist/health.d.ts +12 -1
  11. package/dist/health.d.ts.map +1 -1
  12. package/dist/health.js +15 -4
  13. package/dist/health.js.map +1 -1
  14. package/dist/index.d.ts +7 -5
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/live-protocol.d.ts +451 -0
  19. package/dist/live-protocol.d.ts.map +1 -0
  20. package/dist/live-protocol.js +957 -0
  21. package/dist/live-protocol.js.map +1 -0
  22. package/dist/live.d.ts +156 -9
  23. package/dist/live.d.ts.map +1 -1
  24. package/dist/live.js +31 -1
  25. package/dist/live.js.map +1 -1
  26. package/dist/remote.d.ts +180 -5
  27. package/dist/remote.d.ts.map +1 -1
  28. package/dist/remote.js +793 -76
  29. package/dist/remote.js.map +1 -1
  30. package/dist/runtime.d.ts +7 -5
  31. package/dist/runtime.d.ts.map +1 -1
  32. package/dist/runtime.js +3 -2
  33. package/dist/runtime.js.map +1 -1
  34. package/dist/seat-headers.d.ts +6 -0
  35. package/dist/seat-headers.d.ts.map +1 -1
  36. package/dist/seat-headers.js +6 -0
  37. package/dist/seat-headers.js.map +1 -1
  38. package/dist/serve.d.ts +5 -3
  39. package/dist/serve.d.ts.map +1 -1
  40. package/dist/serve.js +18 -4
  41. package/dist/serve.js.map +1 -1
  42. package/dist/websocket.d.ts +1 -1
  43. package/dist/websocket.d.ts.map +1 -1
  44. package/dist/websocket.js +10 -2
  45. package/dist/websocket.js.map +1 -1
  46. package/package.json +3 -3
@@ -0,0 +1,957 @@
1
+ import { argumentWords, FieldRevisions, InvalidArguments, UnknownMutationError, hidesFrom, hueFor, isUnset, namesUnseen, participantKey, redact, seatLens, sha256Hex, seenBy, seesId, refusalOf, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, } from "@graview/core";
2
+ import { bytesOf, conflictSentence, LIVE_WIRE } from "./live.js";
3
+ /** The longest `cid` a socket's call or undo may name: it is kept in `held` while the call is busy. */
4
+ const MAX_CID = 64;
5
+ /** A change the host's `admit` answered: thrown through the store, which puts the change back. */
6
+ class NotAdmitted extends Error {
7
+ answer;
8
+ constructor(answer) {
9
+ super("Not admitted by the host.");
10
+ this.answer = answer;
11
+ }
12
+ }
13
+ /** A client's claim of what its change came through: a short string, or none. */
14
+ const claimOfVia = (via) => (typeof via === "string" && via.length > 0 ? via.slice(0, 64) : undefined);
15
+ /**
16
+ * A STORE'S REFUSAL, SAID TO A PERSON (FR-46). The store's own sentences
17
+ * were written for a developer: `Invalid arguments for mutation "add"
18
+ * label: Too small…`, and an unknown act listed every act the app has.
19
+ * Arguments are said field by field in the words the form asked in, and
20
+ * an unknown act by the name the call gave; anything else is the
21
+ * refusal's own sentence, the policy's among them.
22
+ */
23
+ export function wireRefusalOf(store, error) {
24
+ const refusal = refusalOf(error);
25
+ if (error instanceof UnknownMutationError)
26
+ return { ...refusal, sentence: `This app has no act called “${error.mutation}”.` };
27
+ if (error instanceof InvalidArguments) {
28
+ const mutation = store.allMutations().find((one) => one.name === error.mutation);
29
+ const said = error.issues.map((issue) => {
30
+ const message = issue.message.replace(/^./, (first) => first.toLowerCase());
31
+ return issue.path.length > 0 ? `${argumentWords(store.schema, mutation, String(issue.path[0])).label} — ${message}` : message;
32
+ });
33
+ return { ...refusal, sentence: `“${mutation?.title ?? error.mutation}” was not made: ${said.join("; ")}.` };
34
+ }
35
+ return refusal;
36
+ }
37
+ /** For whom an author acts, as a presence says it: the person's id and name, or nothing. */
38
+ const forWhom = (author) => author.onBehalfOf?.id ? { onBehalfOf: author.onBehalfOf.id, ...(author.onBehalfOf.name ? { onBehalfOfName: author.onBehalfOf.name } : {}) } : {};
39
+ /**
40
+ * A PRESENCE AS THE SERVER BUILDS IT. Keyed by the seat — a client cannot
41
+ * claim to be somebody else — with only the session taken from what it
42
+ * said, and stamped with the server's clock. What it is, and for whom it
43
+ * acts, are the seat's (FR-47): a claimed `kind`, `onBehalfOf`, `until` or
44
+ * `held` is dropped, and the seat's name stands over a claimed one. `participant`
45
+ * is the key the server already gave this socket (its welcome said it):
46
+ * given, the claimed key is not read at all.
47
+ */
48
+ export function presenceFrom(told, seat, now = new Date(), participant) {
49
+ const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, held: _held, at: _at, ...said } = told;
50
+ // The session is what follows the seat's own `kind:id:` — an id may hold a colon (`shopper:bethan`).
51
+ const own = `${seat.kind}:${seat.id ?? ""}:`;
52
+ const session = claimed.startsWith(own) ? claimed.slice(own.length) : (claimed.split(":").at(-1) ?? "");
53
+ const key = participant ?? (seat.id ? participantKey({ kind: seat.kind, id: seat.id, session }) : claimed);
54
+ const name = seat.name ?? claimedName;
55
+ return { ...said, participant: key, kind: seat.kind, ...(name ? { name } : {}), ...forWhom(seat), at: now.toISOString() };
56
+ }
57
+ /**
58
+ * A VISITOR WITHOUT A SOCKET, as a host announces it (FR-47): an agent
59
+ * acting over MCP or an RPC, a polling tab. Built from the author the host
60
+ * already trusts — what it is, what it is called, for whom — keyed
61
+ * `kind:id:visit` unless a session is given, so every call by one agent
62
+ * refreshes one figure rather than adding another.
63
+ */
64
+ export function visitorPresence(author, options = {}) {
65
+ const name = author.name ?? author.id;
66
+ return {
67
+ participant: participantKey({ kind: author.kind, ...(author.id ? { id: author.id } : {}), session: options.session ?? author.session ?? "visit" }),
68
+ kind: author.kind,
69
+ ...(name ? { name } : {}),
70
+ ...forWhom(author),
71
+ hue: options.hue ?? hueFor(author.id ?? author.kind),
72
+ stop: options.stop ?? "",
73
+ ...(options.over !== undefined ? { over: options.over } : {}),
74
+ at: (options.now ?? new Date()).toISOString(),
75
+ };
76
+ }
77
+ /**
78
+ * WHO IS HERE, WITH ONE MORE (FR-47) — for a host that holds `who` itself,
79
+ * as a hibernating one does. The visitor is stamped now and stands until
80
+ * `ttlMs` from now; the same participant announced again replaces it, and
81
+ * anybody whose announced time has passed is dropped. Pure: keep what it
82
+ * answers, and hand it to `receive` and `tell`.
83
+ */
84
+ export function announcePresence(who, presence, ttlMs = VISITOR_PRESENCE_TTL_MS, now = Date.now()) {
85
+ const stamped = { ...presence, at: new Date(now).toISOString(), until: new Date(now + ttlMs).toISOString() };
86
+ return [...who.filter((one) => one.participant !== presence.participant && (one.until === undefined || now < Date.parse(one.until))), stamped];
87
+ }
88
+ /**
89
+ * WHO IS HERE, AS THE SOCKETS SAY IT: a presence whose participant one of
90
+ * the host's sockets holds is held by that socket (`held: "socket"`, and no
91
+ * `until` — it stands while the socket does); everybody else, a visitor
92
+ * with its `until` among them, as the host built them. A new list: the
93
+ * host's own is not changed.
94
+ */
95
+ function heldBySockets(who, peers) {
96
+ const held = new Set();
97
+ for (const peer of peers)
98
+ if (peer.participant)
99
+ held.add(peer.participant);
100
+ if (held.size === 0)
101
+ return [...who];
102
+ return who.map((presence) => {
103
+ if (!held.has(presence.participant))
104
+ return presence;
105
+ const { until: _until, ...standing } = presence;
106
+ return { ...standing, held: "socket" };
107
+ });
108
+ }
109
+ /** A key for a socket that has not said one, minted by the server: the welcome tells the client what it is. */
110
+ const mintSession = () => globalThis.crypto.randomUUID().slice(0, 8);
111
+ /**
112
+ * WHO IS HERE, AS ONE SEAT MAY BE TOLD (FR-02). Somebody whose own record
113
+ * the seat may not see is not shown to it at all; anybody else is, without
114
+ * where they stand or what they hover when that names a record the seat
115
+ * may not see. A participant whose id is no record is shown as they are.
116
+ */
117
+ export function presenceSeenBy(who, sees) {
118
+ const names = (value) => value.split(/[/?#=&,;]/).every((part) => part === "" || sees(decodeURIComponent(part)));
119
+ return who
120
+ .filter((presence) => {
121
+ // `kind:id:session`, and an id may hold a colon of its own: every reading of it must be one the seat sees.
122
+ const parts = presence.participant.split(":");
123
+ return parts.slice(2).every((_, at) => sees(parts.slice(1, at + 2).join(":")));
124
+ })
125
+ .map((presence) => {
126
+ // An agent is shown; for whom it acts is not, to a seat that may not see that person (FR-47).
127
+ const { onBehalfOf, onBehalfOfName, ...rest } = presence;
128
+ const forWhom = onBehalfOf !== undefined && sees(onBehalfOf) ? { onBehalfOf, ...(onBehalfOfName !== undefined ? { onBehalfOfName } : {}) } : {};
129
+ return {
130
+ ...rest,
131
+ ...forWhom,
132
+ stop: names(presence.stop) ? presence.stop : "",
133
+ ...(typeof presence.over === "string" && !sees(presence.over) ? { over: null } : {}),
134
+ ...(presence.robot?.at && !sees(presence.robot.at) ? { robot: { ...presence.robot, at: null } } : {}),
135
+ };
136
+ });
137
+ }
138
+ /**
139
+ * THE SHAPE OF A BATCH A CLIENT NAMES: what a `Store` mints by default,
140
+ * `batch:<tag>:<n>` for a change and `undo:<tag>:<n>` for a take-back,
141
+ * the tag 1–24 lowercase letters and digits and `n` up to 12 digits. A
142
+ * client names the batch its call lands in, so a call sent twice is
143
+ * answered once (FR-49) — and anything else a client names is refused
144
+ * `invalid`, so it cannot claim a batch the host mints for itself
145
+ * (`setup`, `migration:v2`) before the host does.
146
+ */
147
+ const CLIENT_BATCH = /^(?:batch|undo):[0-9a-z]{1,24}:[0-9]{1,12}$/;
148
+ /** Whether a client may name this batch: `batch:<tag>:<n>` or `undo:<tag>:<n>`, as a `Store` mints them. */
149
+ export function isClientBatch(batch) {
150
+ return typeof batch === "string" && CLIENT_BATCH.test(batch);
151
+ }
152
+ /** A tag for one minter, from the platform's random source. */
153
+ const mintTag = () => globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 12);
154
+ /**
155
+ * BATCH IDS NO CLIENT CAN NAME FIRST: `served:<kind>:<tag>:<n>`, outside
156
+ * the shape `isClientBatch` accepts. Hand it to the host's own store —
157
+ * `new Store({ batchIds: serverBatchIds() })`, or `openStore`'s
158
+ * `storeOptions` — so what the host lands itself (an agent's RPC, a
159
+ * migration, a seed) is in a batch no client could have claimed.
160
+ * `createStoreHandler` mints its own this way, and `liveProtocol` mints
161
+ * one for a call that names none.
162
+ */
163
+ export function serverBatchIds() {
164
+ const tag = mintTag();
165
+ let count = 0;
166
+ return (kind) => `served:${kind}:${tag}:${++count}`;
167
+ }
168
+ /**
169
+ * THE SAME SEAT. An op is the asking seat's own when its author is the
170
+ * same kind and id — and, for an agent, acts for the same person: Claude
171
+ * for Ada is not Claude for Bo.
172
+ */
173
+ export function authoredBy(author, seat) {
174
+ if (author.kind !== seat.kind || (author.id ?? "") !== (seat.id ?? ""))
175
+ return false;
176
+ return seat.kind !== "agent" || (author.onBehalfOf?.id ?? "") === (seat.onBehalfOf?.id ?? "");
177
+ }
178
+ /**
179
+ * THE KEY A STORE'S WITHHELD BATCHES ARE MINTED UNDER, when the host gives
180
+ * none: drawn once per store held, so every route and socket over one
181
+ * store says the same opaque batch for one batch.
182
+ */
183
+ const WITHHELD_KEYS = new WeakMap();
184
+ /**
185
+ * EACH STORE'S OPAQUE BATCHES, BY KEY: a keyed hash per batch, made once
186
+ * for every route and socket over the store rather than once per protocol
187
+ * made over it — a protocol is made again on every wake.
188
+ */
189
+ const OPAQUE_BATCHES = new WeakMap();
190
+ export function wireOf(store, withheldKey) {
191
+ const sighted = (principal) => hidesFrom(store, principal);
192
+ /*
193
+ * A WITHHELD OP SAYS NOBODY'S SESSION. Its batch is the one its author's
194
+ * client minted — `batch:<that browser's tag>:<n>` — which would tell a
195
+ * seat that may not see the change which session made it, and link it to
196
+ * the changes it may see. So it is served under `withheld:<16 hex>`, a
197
+ * keyed SHA-256 of the batch: the same for every op of one batch, and not
198
+ * one a seat can work back from, the key never leaving the server. The
199
+ * seat that made it is served its own.
200
+ */
201
+ let key = withheldKey;
202
+ if (key === undefined) {
203
+ key = WITHHELD_KEYS.get(store) ?? mintTag() + mintTag();
204
+ WITHHELD_KEYS.set(store, key);
205
+ }
206
+ let byKey = OPAQUE_BATCHES.get(store);
207
+ if (!byKey)
208
+ OPAQUE_BATCHES.set(store, (byKey = new Map()));
209
+ let opaque = byKey.get(key);
210
+ if (!opaque)
211
+ byKey.set(key, (opaque = new Map()));
212
+ const opaqueBatch = (batch) => {
213
+ let said = opaque.get(batch);
214
+ if (said === undefined) {
215
+ said = `withheld:${sha256Hex(`${key}\u0000${batch}`).slice(0, 16)}`;
216
+ opaque.set(batch, said);
217
+ }
218
+ return said;
219
+ };
220
+ const unattributed = (principal, served, authorOf) => served.map((op, at) => {
221
+ if (!op.withheld)
222
+ return op;
223
+ const author = authorOf(op, at);
224
+ return author && authoredBy(author, principal) ? op : { ...op, batch: opaqueBatch(op.batch) };
225
+ });
226
+ // Withheld in place (FR-16), no id the seat may not see in any of them (FR-55), and no session it may not see.
227
+ const shown = (principal, ops) => sighted(principal) ? unattributed(principal, redact(ops, seatLens(store, principal)), (_op, at) => ops[at]?.author) : [...ops];
228
+ /*
229
+ * EVERY FIELD'S REVISION (FR-05): the seq of the op that last wrote it,
230
+ * read off the log once and caught up from wherever the log has grown
231
+ * to since — no subscription, so nothing here goes stale while a host
232
+ * sleeps, and a host that made this again reads the same revisions.
233
+ */
234
+ /*
235
+ * WHO EACH CLIENT TAG IS: the author of the first op landed under it,
236
+ * read off the log once and caught up as it grows — derived, so a host
237
+ * that wakes reads the same owners the sleeper had.
238
+ */
239
+ /*
240
+ * Both read on first asking, not when the protocol is made: a host makes
241
+ * it again on every wake, and most wakes are a message that names no
242
+ * batch and carries no base.
243
+ */
244
+ const owners = new Map();
245
+ const own = (ops) => {
246
+ for (const op of ops) {
247
+ if (!isClientBatch(op.batch))
248
+ continue;
249
+ const tag = op.batch.split(":")[1];
250
+ if (!owners.has(tag))
251
+ owners.set(tag, op.author);
252
+ }
253
+ };
254
+ let owned = store.log.horizon;
255
+ const tagOwner = (tag) => {
256
+ if (store.log.length > owned) {
257
+ own(store.log.opsFrom(owned));
258
+ owned = store.log.length;
259
+ }
260
+ return owners.get(tag);
261
+ };
262
+ let revisions;
263
+ let noted = 0;
264
+ const current = () => {
265
+ if (!revisions) {
266
+ revisions = FieldRevisions.of(store.log.all());
267
+ noted = store.log.length;
268
+ }
269
+ else if (store.log.length > noted) {
270
+ revisions.note(store.log.opsFrom(noted));
271
+ noted = store.log.length;
272
+ }
273
+ return revisions;
274
+ };
275
+ return {
276
+ store,
277
+ lastSeq: () => store.log.length - 1,
278
+ sighted,
279
+ shown,
280
+ since: (principal, seq) => shown(principal, store.log.opsFrom(Math.max(0, Math.floor(seq) + 1))),
281
+ seenFor: (principal) => seenBy(store, principal),
282
+ seenLog(principal) {
283
+ const log = seenBy(store, principal).log.all();
284
+ if (!sighted(principal))
285
+ return [...log];
286
+ // The seat's log holds every op in its place: who made one is the store's op at the same place.
287
+ const all = store.log.all();
288
+ return unattributed(principal, log, (op, at) => (all[at]?.id === op.id ? all[at].author : all.find((one) => one.id === op.id)?.author));
289
+ },
290
+ whoFor: (principal, who) => {
291
+ // A visitor whose announced time has passed is never told of, though a host may still hold it.
292
+ const now = Date.now();
293
+ const standing = who.filter((presence) => presence.until === undefined || now < Date.parse(presence.until));
294
+ return sighted(principal) ? presenceSeenBy(standing, seesId(store, principal)) : standing;
295
+ },
296
+ claim(batch, seat) {
297
+ if (batch === undefined || batch === null || batch === "")
298
+ return {};
299
+ if (!isClientBatch(batch)) {
300
+ const said = typeof batch === "string" ? `“${batch.length > 40 ? `${batch.slice(0, 37)}…` : batch}”` : "a batch that is not a string";
301
+ return {
302
+ refusal: {
303
+ reason: "invalid",
304
+ sentence: `A client names its batch batch:<tag>:<n> or undo:<tag>:<n>, as a Store mints it; ${said} is not one. Send the change without a batch, or under one this client minted.`,
305
+ },
306
+ };
307
+ }
308
+ /*
309
+ * A TAG IS THE FIRST SEAT'S. A client's tag is in every op it lands,
310
+ * so a batch it has not sent yet — `batch:<tag>:<n+1>` — could be
311
+ * named first by anybody who saw one. The store's own minting tag is
312
+ * nobody's to name: what the host lands later would join it.
313
+ */
314
+ const tag = batch.split(":")[1];
315
+ if (tag === store.batchTag) {
316
+ return { refusal: { reason: "invalid", sentence: "That batch is under the server's own tag: send the change under a batch this client minted." } };
317
+ }
318
+ const owner = tagOwner(tag);
319
+ if (owner && !authoredBy(owner, seat)) {
320
+ return { refusal: { reason: "invalid", sentence: "That batch is under somebody else's tag: send the change under a batch this client minted." } };
321
+ }
322
+ const ops = store.log.all().filter((op) => op.batch === batch);
323
+ if (ops.some((op) => !authoredBy(op.author, seat))) {
324
+ return { refusal: { reason: "invalid", sentence: "That batch is somebody else's: send the change under a batch this client minted." } };
325
+ }
326
+ return ops.length > 0 ? { answered: ops } : {};
327
+ },
328
+ horizonOf: () => (store.log.horizon > 0 ? { horizon: store.log.horizon } : {}),
329
+ enabledModules: () => [...store.modules.enabled].sort(),
330
+ conflictsOf(author, calls, base) {
331
+ if (!Array.isArray(base) || base.length === 0)
332
+ return [];
333
+ const lens = sighted(author) ? seatLens(store, author) : undefined;
334
+ // A record the seat is not served is not there to have moved: the call itself is refused for naming it.
335
+ const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" && (!lens || lens.shows(entry.node)));
336
+ const revs = current();
337
+ const stale = revs.stale(claimed);
338
+ if (stale.length === 0)
339
+ return [];
340
+ /*
341
+ * A conflict is a choice — keep theirs, or put yours over it — and only
342
+ * a call that could still land offers one. A call the policy refuses,
343
+ * or one that no longer runs on the graph as it is (somebody finished
344
+ * it first), is refused for that, in its own sentence.
345
+ */
346
+ if (store.policy && calls.some((call) => !store.permits(call, author).ok))
347
+ return [];
348
+ // Nor does a call naming a record that is not there for this seat: it is refused as missing, a hidden record and an absent one alike (FR-55).
349
+ if (calls.some((call) => store.missingFor(call, author)))
350
+ return [];
351
+ const yours = new Map();
352
+ try {
353
+ for (const primitive of store.previewAll(calls).primitives) {
354
+ if (primitive.op === "patch-node")
355
+ for (const [field, value] of Object.entries(primitive.after))
356
+ yours.set(`${primitive.id}\u0000${field}`, isUnset(value) ? undefined : value);
357
+ }
358
+ }
359
+ catch {
360
+ return [];
361
+ }
362
+ return stale.map((entry) => {
363
+ const rev = revs.of(entry.node, entry.field);
364
+ const wrote = rev >= store.log.horizon ? store.log.opsFrom(rev)[0] : undefined;
365
+ const seen = wrote && lens ? redact([wrote], lens)[0] : wrote;
366
+ // Theirs as the seat's view serves the record: a field naming what it may not see is cleared there too (FR-55).
367
+ const theirs = (lens ? seenBy(store, author) : store).graph.getNode(entry.node)?.[entry.field];
368
+ const mine = yours.get(`${entry.node}\u0000${entry.field}`);
369
+ return {
370
+ node: entry.node,
371
+ field: entry.field,
372
+ theirs,
373
+ yours: lens && namesUnseen(mine, lens.sees) ? undefined : mine,
374
+ by: seen?.author.name ?? seen?.author.id ?? "Someone",
375
+ rev,
376
+ saw: entry.rev,
377
+ };
378
+ });
379
+ },
380
+ };
381
+ }
382
+ const say = (peer, message) => sayText(peer, JSON.stringify(message));
383
+ const sayText = (peer, text) => {
384
+ try {
385
+ peer.send(text);
386
+ }
387
+ catch {
388
+ // A socket that cannot be written to is closing; its close is what forgets it.
389
+ }
390
+ };
391
+ const aSight = () => ({ seats: new Map(), texts: new Map() });
392
+ /**
393
+ * A SEAT, NOT ITS TAB: the principal without its session — and without the
394
+ * session of the person an agent acts for. What a seat is served never
395
+ * depends on which tab asks, so its key never does either: the key a
396
+ * handler asks a host for (`seatKey`), and the one a sight is kept under.
397
+ */
398
+ export function seatOfTab(seat) {
399
+ const { session: _session, onBehalfOf, ...rest } = seat;
400
+ return { ...rest, ...(onBehalfOf ? { onBehalfOf: seatOfTab(onBehalfOf) } : {}) };
401
+ }
402
+ /** What a socket's seat is, as a key a sight is kept under: a host's key, or the seat written out — one per seat, however many tabs hold it. */
403
+ const seatKeyOf = (peer) => (typeof peer.seat === "string" ? `key:${peer.seat}` : `seat:${JSON.stringify(seatOfTab(peer.seat))}`);
404
+ /** What a socket whose seat the host lost is told, and the code it is closed with. */
405
+ const SEAT_LOST = "The host no longer knows who this socket is: open it again, and it reads who you are from the new one.";
406
+ const SEAT_LOST_CODE = 4000;
407
+ /** The host lost this socket's seat: told to open again, closed when it can be, and served nothing more. */
408
+ const lost = (peer) => {
409
+ delete peer.cursor;
410
+ say(peer, { t: "error", reopen: true, sentence: SEAT_LOST });
411
+ try {
412
+ peer.close?.(SEAT_LOST_CODE, "Seat no longer known: open it again.");
413
+ }
414
+ catch {
415
+ // Already closing.
416
+ }
417
+ };
418
+ /**
419
+ * THE PROTOCOL OVER A STORE. Cheap to make, and safe to make again on
420
+ * every wake: what it keeps is derived from the store.
421
+ */
422
+ export function liveProtocol(options) {
423
+ const { store } = options;
424
+ const wire = wireOf(store, options.withheldKey);
425
+ /** A call that names no batch lands in one minted here, outside the shape a client may name. */
426
+ const mintServed = serverBatchIds();
427
+ /**
428
+ * OPS THAT LANDED AND ARE NOT DURABLE: a flush rejected them. Held back
429
+ * from every socket — nothing is sent past the first of them, so none is
430
+ * skipped — until a flush holds them. Derived: a host that wakes makes
431
+ * its store again from what is durable, where none of them is.
432
+ */
433
+ let unsaved = [];
434
+ /**
435
+ * OPS THAT LANDED AND ARE BEING FLUSHED: held back from every socket like
436
+ * the unsaved ones, so a change anybody else hears is a change that is
437
+ * written. Only with a `flush`: a host without one pushes at once.
438
+ */
439
+ let flying = [];
440
+ /** While the store takes a change (its subscribers hear it then): the seq its ops begin at, held back like the rest. */
441
+ let taking;
442
+ let flushing = Promise.resolve();
443
+ /** The first seq held back from every socket — not durable, or not yet — before `before`, when one is. */
444
+ const heldFrom = (before = Number.POSITIVE_INFINITY) => {
445
+ let first = taking !== undefined && taking < before ? taking : undefined;
446
+ for (const op of [...unsaved, ...flying])
447
+ if (op.seq < before && (first === undefined || op.seq < first))
448
+ first = op.seq;
449
+ return first;
450
+ };
451
+ /**
452
+ * THROUGH THE HOST'S FLUSH, ONE AT A TIME: `ops` and every op a failed
453
+ * flush left before them. Says whether they are durable now, and which
454
+ * ops became durable — for the host to publish.
455
+ */
456
+ const durable = (ops) => {
457
+ const turn = flushing.then(async () => {
458
+ const ids = new Set(unsaved.map((op) => op.id));
459
+ const handing = [...unsaved, ...ops.filter((op) => !ids.has(op.id))].sort((a, b) => a.seq - b.seq);
460
+ const handed = new Set(handing.map((op) => op.id));
461
+ try {
462
+ await options.flush?.(handing);
463
+ }
464
+ catch {
465
+ unsaved = handing;
466
+ flying = flying.filter((op) => !handed.has(op.id));
467
+ return { failed: true };
468
+ }
469
+ unsaved = unsaved.filter((op) => !handed.has(op.id));
470
+ flying = flying.filter((op) => !handed.has(op.id));
471
+ return { saved: handing };
472
+ });
473
+ flushing = turn.catch(() => { });
474
+ return turn;
475
+ };
476
+ /** Whether any of these ops is not durable yet. */
477
+ const unsavedIn = (ops) => unsaved.length > 0 && ops.some((op) => unsaved.some((one) => one.id === op.id));
478
+ const UNSAVED = "Your change could not be saved just now. It is kept, and sent again until it is.";
479
+ /** The principal a socket is: its seat, or what the host's `seatOf` says its key names — once per key in one sight. */
480
+ const principalOf = (peer, sight) => {
481
+ if (typeof peer.seat !== "string")
482
+ return peer.seat;
483
+ if (!sight)
484
+ return options.seatOf?.(peer.seat);
485
+ const key = seatKeyOf(peer);
486
+ if (!sight.seats.has(key))
487
+ sight.seats.set(key, options.seatOf?.(peer.seat));
488
+ return sight.seats.get(key);
489
+ };
490
+ /** The ops after this socket's cursor up to `last`, down it now, as its seat sees them — written once per seat and run in one sight. */
491
+ const sendUpTo = (peer, last, ops, known, sight) => {
492
+ if (peer.cursor === undefined || peer.cursor >= last)
493
+ return;
494
+ const seat = known ?? principalOf(peer, sight);
495
+ if (!seat)
496
+ return;
497
+ const from = peer.cursor + 1;
498
+ peer.cursor = last;
499
+ const key = sight ? `${seatKeyOf(peer)}\u0000${from}\u0000${last}` : undefined;
500
+ const kept = key !== undefined ? sight.texts.get(key) : undefined;
501
+ if (kept !== undefined) {
502
+ if (kept.length > 0)
503
+ sayText(peer, kept);
504
+ return;
505
+ }
506
+ // The ops handed in, when they are the whole of what this peer is missing; the log otherwise.
507
+ const after = (ops && ops.length > 0 && ops[0].seq <= from && ops.at(-1).seq >= last ? ops.filter((op) => op.seq >= from) : store.log.opsFrom(from)).filter((op) => op.seq <= last);
508
+ const text = after.length > 0 ? JSON.stringify({ t: "ops", seq: last, ops: wire.shown(seat, after) }) : "";
509
+ if (key !== undefined)
510
+ sight.texts.set(key, text);
511
+ if (text.length > 0)
512
+ sayText(peer, text);
513
+ };
514
+ /** Every op this socket has not been sent, down it now, as its seat sees them — up to the first that is not durable. */
515
+ const catchUp = (peer, ops, known, sight) => {
516
+ const held = heldFrom();
517
+ sendUpTo(peer, held === undefined ? wire.lastSeq() : Math.min(wire.lastSeq(), held - 1), ops, known, sight);
518
+ };
519
+ /** What the host's `limit` says of a change, before it is judged; nothing when it has none. */
520
+ const limitOf = async (seat, via, change, bytes) => options.limit ? options.limit({ seat, via, t: change.t, bytes, calls: change.t === "call" ? change.calls : [] }) : undefined;
521
+ /**
522
+ * ONE CHANGE, JUDGED AS ITS SEAT — the socket's and `POST /graview/ops`'s
523
+ * alike, so the two can never disagree. A stale write is a conflict and
524
+ * nothing is written (FR-05); then through the store, under the seat and
525
+ * the host's channel (never the client's, FR-52), in the batch the client
526
+ * named or one minted here; then flushed. `applied` runs between the
527
+ * store taking it and the flush, for the socket to move its cursor.
528
+ */
529
+ const land = async (seat, via, change, bytes, applied) => {
530
+ if (change.t === "call") {
531
+ const conflicts = wire.conflictsOf(seat, change.calls, change.base);
532
+ if (conflicts.length > 0)
533
+ return { conflicts };
534
+ }
535
+ const batch = typeof change.batch === "string" && change.batch.length > 0 ? change.batch : mintServed(change.t === "undo" ? "undo" : "batch");
536
+ let result;
537
+ // A host that publishes from the store's own subscription does so inside the apply: hold from here.
538
+ if (options.flush)
539
+ taking = wire.lastSeq() + 1;
540
+ try {
541
+ // The host's caps on what it would do, asked of the store's own plan before anything is kept.
542
+ const admit = options.admit;
543
+ const admitting = admit
544
+ ? (planned) => {
545
+ const answer = admit({ seat, via, t: change.t, bytes, calls: change.t === "call" ? change.calls : [] }, planned);
546
+ if (answer)
547
+ throw new NotAdmitted(answer);
548
+ }
549
+ : undefined;
550
+ const applying = { author: seat, via, ...(change.intent ? { intent: change.intent } : {}), batch, ...(admitting ? { admit: admitting } : {}) };
551
+ result = change.t === "undo" ? store.undo(change.batches, applying) : store.applyAll(change.calls, applying);
552
+ }
553
+ catch (error) {
554
+ taking = undefined;
555
+ if (error instanceof NotAdmitted)
556
+ return { limited: error.answer };
557
+ const worded = options.refusal?.(error, change.calls, { seat, via });
558
+ return { refusal: worded ?? wireRefusalOf(store, error) };
559
+ }
560
+ // Being written: nobody else hears it until it is (`heldFrom`).
561
+ if (options.flush)
562
+ flying = [...flying, ...result.ops];
563
+ taking = undefined;
564
+ applied?.(result.ops);
565
+ const flushed = await durable(result.ops);
566
+ return { result, saved: "saved" in flushed ? flushed.saved : undefined };
567
+ };
568
+ /** A change as the socket's message says it. */
569
+ const changeOf = (message) => ({
570
+ t: message.t,
571
+ calls: message.t === "call" && Array.isArray(message.calls) ? message.calls : [],
572
+ batches: message.t === "undo" && Array.isArray(message.batches) ? message.batches : [],
573
+ intent: typeof message.intent === "string" && message.intent.length > 0 ? message.intent : undefined,
574
+ batch: message.batch,
575
+ base: message.t === "call" ? message.base : undefined,
576
+ claimed: claimOfVia(message.via),
577
+ });
578
+ /** What a change came through: the host's word, or a claim its `viaOf` accepts (FR-52). */
579
+ const viaFor = (peer, change) => {
580
+ const judged = options.viaOf?.(peer, change.claimed);
581
+ return typeof judged === "string" && judged.length > 0 ? judged : peer.via;
582
+ };
583
+ /**
584
+ * THE HOST'S WORD ON A SOCKET'S CALL (FR-45, FR-46) — its `limit`'s, or
585
+ * its `admit`'s: refused at a cap, unavailable for a while, or busy, when
586
+ * every later call waits behind it.
587
+ */
588
+ const sayLimited = (peer, cid, limited) => {
589
+ if ("refuse" in limited) {
590
+ delete peer.held;
591
+ say(peer, { t: "refused", cid, reason: "limit", sentence: limited.refuse });
592
+ }
593
+ else if ("unavailable" in limited) {
594
+ // Not for a while, and no wait to name: refused `unavailable`, which the client keeps and sends again, backing off.
595
+ delete peer.held;
596
+ say(peer, { t: "refused", cid, reason: "unavailable", sentence: limited.unavailable });
597
+ }
598
+ else {
599
+ const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
600
+ peer.held = { cid, until: Date.now() + retryAfter };
601
+ say(peer, { t: "busy", cid, retryAfter, ...(limited.sentence ? { sentence: limited.sentence } : {}) });
602
+ }
603
+ return { cursor: peer.cursor };
604
+ };
605
+ /** The same word over HTTP: 413 `limit`, 503 `unavailable`, or 429 with `Retry-After`. */
606
+ const limitedReply = (limited, said) => {
607
+ if ("refuse" in limited)
608
+ return reply(413, { error: limited.refuse, refused: true, reason: "limit", ...said });
609
+ if ("unavailable" in limited)
610
+ return reply(503, { error: limited.unavailable, refused: true, reason: "unavailable", ...said });
611
+ const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
612
+ return reply(429, { error: limited.sentence ?? `The store is busy: send it again in ${retryAfter} ms.`, busy: true, retryAfter }, { "retry-after": String(Math.ceil(retryAfter / 1000)) });
613
+ };
614
+ /** A call or an undo from a socket, past its claim and the host's limit: judged as its seat, exactly as `POST /graview/ops` judges it. */
615
+ const answer = async (peer, seat, cid, change, via, bytes) => {
616
+ catchUp(peer, undefined, seat);
617
+ const prior = peer.cursor;
618
+ /*
619
+ * Every op before this call's went down this socket before it landed;
620
+ * its own go in the ack. Unless one before it is held back as not
621
+ * durable: then the cursor stays, and they go down after the flush.
622
+ */
623
+ const landing = await land(seat, via, change, bytes, (own) => {
624
+ if (own.length === 0 || heldFrom(own[0].seq) === undefined)
625
+ peer.cursor = wire.lastSeq();
626
+ });
627
+ // What it would do is over the host's caps: nothing was kept.
628
+ if (landing.limited)
629
+ return sayLimited(peer, cid, landing.limited);
630
+ if (landing.conflicts) {
631
+ say(peer, { t: "conflict", cid, sentence: conflictSentence(landing.conflicts), conflicts: [...landing.conflicts] });
632
+ return { cursor: peer.cursor };
633
+ }
634
+ if (landing.refusal) {
635
+ say(peer, { t: "refused", cid, ...landing.refusal });
636
+ return { cursor: peer.cursor };
637
+ }
638
+ const { result, saved } = landing;
639
+ if (!saved) {
640
+ // Not durable: refused `unavailable`, which the client keeps and sends again; nothing is acked and the cursor does not move.
641
+ peer.cursor = prior;
642
+ say(peer, { t: "refused", cid, reason: "unavailable", sentence: UNSAVED });
643
+ return { cursor: prior };
644
+ }
645
+ return acked(peer, seat, cid, result.batch, result.ops, saved);
646
+ };
647
+ /** The ack of ops that are durable: what was held back before them goes first, so none is skipped. */
648
+ const acked = (peer, seat, cid, batch, own, saved) => {
649
+ const first = own[0]?.seq;
650
+ if (first !== undefined) {
651
+ sendUpTo(peer, first - 1, undefined, seat);
652
+ peer.cursor = Math.max(peer.cursor, own.at(-1).seq);
653
+ }
654
+ const ops = wire.shown(seat, own);
655
+ say(peer, { t: "ack", cid, seq: ops.at(-1)?.seq ?? peer.cursor, batch, ops });
656
+ return { cursor: peer.cursor, ...(saved && saved.length > 0 ? { landed: saved } : {}) };
657
+ };
658
+ /** The host's build a socket — or a route's request — is served by (FR-44): its own, else the protocol's word for it. */
659
+ const buildFor = (peer) => peer.hostBuild ?? (typeof options.build === "function" ? options.build(peer) : options.build);
660
+ /** Which declaration, and which build, answered (FR-43, FR-44): on every route's answer a poll reads. */
661
+ const answering = (asked) => {
662
+ const build = buildFor({ seat: asked.seat, via: asked.via, ...(asked.build ? { hostBuild: asked.build } : {}) });
663
+ return { version: options.version ?? 1, ...(build ? { build } : {}) };
664
+ };
665
+ const reply = (status, body, headers = {}) => ({ status, body, headers });
666
+ return {
667
+ store,
668
+ open: (seat, via, opening = {}) => ({ seat, via, ...(opening.build ? { hostBuild: opening.build.slice(0, 64) } : {}) }),
669
+ async receive(peer, text, who = [], peers = [peer]) {
670
+ let message;
671
+ try {
672
+ message = JSON.parse(text);
673
+ }
674
+ catch {
675
+ say(peer, { t: "error", sentence: "A message on the live wire is one JSON object." });
676
+ return peer.cursor !== undefined ? { cursor: peer.cursor } : {};
677
+ }
678
+ const unchanged = () => (peer.cursor !== undefined ? { cursor: peer.cursor } : {});
679
+ if (!message || typeof message !== "object")
680
+ return unchanged();
681
+ // Who this socket is, on this message: its seat, or the principal its key names now.
682
+ const seat = principalOf(peer);
683
+ if (!seat) {
684
+ lost(peer);
685
+ return {};
686
+ }
687
+ const served = { seat, via: peer.via, ...(peer.hostBuild ? { hostBuild: peer.hostBuild } : {}) };
688
+ switch (message.t) {
689
+ case "hello": {
690
+ /*
691
+ * ANOTHER CODEC, OR A PROTOCOL NO LONGER SERVED (FR-44). Neither is
692
+ * welcomed, and neither has its cursor set, so its calls are
693
+ * refused rather than read as something they are not.
694
+ */
695
+ if (typeof message.wire === "string" && message.wire !== LIVE_WIRE) {
696
+ say(peer, { t: "error", sentence: `This socket speaks ${LIVE_WIRE}, not ${message.wire}: say hello in ${LIVE_WIRE}, or open the socket the ${message.wire} host serves.` });
697
+ return unchanged();
698
+ }
699
+ const speaks = typeof message.protocol === "number" && Number.isFinite(message.protocol) ? message.protocol : 1;
700
+ if (options.minProtocol !== undefined && speaks < options.minProtocol) {
701
+ delete peer.cursor;
702
+ say(peer, {
703
+ t: "reload",
704
+ reason: `This app was updated: its server no longer speaks protocol ${speaks} of the live wire, only ${options.minProtocol} and later. Reload the page; changes not yet sent are offered again after it.`,
705
+ protocol: options.minProtocol,
706
+ });
707
+ return {};
708
+ }
709
+ // The host's own half of the wire, numbered by the host: an older page reloads onto a build that speaks it.
710
+ const hostSpeaks = typeof message.hostProtocol === "number" && Number.isFinite(message.hostProtocol) ? message.hostProtocol : 0;
711
+ if (options.minHostProtocol !== undefined && hostSpeaks < options.minHostProtocol) {
712
+ delete peer.cursor;
713
+ say(peer, {
714
+ t: "reload",
715
+ reason: "This app was updated, and this page is from before it. Reload the page; changes not yet sent are offered again after it.",
716
+ protocol: options.minProtocol ?? WIRE_PROTOCOL,
717
+ hostProtocol: options.minHostProtocol,
718
+ });
719
+ return {};
720
+ }
721
+ if (typeof message.build === "string" && message.build.length > 0)
722
+ peer.build = message.build.slice(0, 64);
723
+ const seq = typeof message.seq === "number" && Number.isFinite(message.seq) ? message.seq : undefined;
724
+ peer.cursor = wire.lastSeq();
725
+ // Its own key, built from the seat, so the client can leave itself out of who is here (FR-47).
726
+ peer.participant ??= participantKey({ kind: seat.kind, ...(seat.id ? { id: seat.id } : {}), session: mintSession() });
727
+ const participant = peer.participant;
728
+ const build = buildFor(served);
729
+ const said = { protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, version: options.version ?? 1, participant, ...(build ? { build } : {}) };
730
+ if (seq === undefined) {
731
+ const seen = wire.seenFor(seat);
732
+ say(peer, {
733
+ t: "welcome",
734
+ ...said,
735
+ seq: peer.cursor,
736
+ ops: [],
737
+ state: {
738
+ version: options.version ?? 1,
739
+ snapshot: seen.snapshot(),
740
+ log: wire.seenLog(seat),
741
+ migrated: [...(options.migrated ?? [])],
742
+ enabledModules: wire.enabledModules(),
743
+ ...wire.horizonOf(),
744
+ },
745
+ });
746
+ }
747
+ else {
748
+ // Caught up to what is written: an op still being flushed, or one a flush failed, comes once it holds.
749
+ const held = heldFrom();
750
+ if (held !== undefined)
751
+ peer.cursor = Math.max(Math.floor(seq), held - 1);
752
+ say(peer, { t: "welcome", ...said, seq: peer.cursor, ops: wire.since(seat, seq).filter((op) => op.seq <= peer.cursor) });
753
+ }
754
+ const others = heldBySockets(who, [peer, ...peers]).filter((presence) => presence.participant !== peer.participant);
755
+ if (others.length > 0)
756
+ say(peer, { t: "presence", who: wire.whoFor(seat, others) });
757
+ return { cursor: peer.cursor };
758
+ }
759
+ case "call":
760
+ case "undo": {
761
+ const cid = String(message.cid ?? "");
762
+ // A cid is kept while its call is busy: a long one would crowd the host's attachment.
763
+ if (cid.length > MAX_CID) {
764
+ say(peer, { t: "refused", cid, reason: "invalid", sentence: `A call's cid is at most ${MAX_CID} characters; this one is ${cid.length}. Name it again shorter.` });
765
+ return unchanged();
766
+ }
767
+ if (peer.cursor === undefined) {
768
+ say(peer, { t: "refused", cid, reason: "invalid", sentence: "Say hello first: the live wire answers calls once it knows what the client has." });
769
+ return {};
770
+ }
771
+ /*
772
+ * SENT AGAIN AFTER IT LANDED: answered with what it made, before the
773
+ * host is asked anything. A call whose ack was lost is never told
774
+ * busy, capped or unavailable for a change already made — and only
775
+ * ever with the asking seat's own ops (`claim`).
776
+ */
777
+ const change = changeOf(message);
778
+ const claim = wire.claim(message.batch, seat);
779
+ if (claim.refusal) {
780
+ catchUp(peer, undefined, seat);
781
+ if (peer.held?.cid === cid)
782
+ delete peer.held;
783
+ say(peer, { t: "refused", cid, ...claim.refusal });
784
+ return { cursor: peer.cursor };
785
+ }
786
+ if (claim.answered) {
787
+ if (peer.held?.cid === cid)
788
+ delete peer.held;
789
+ // Landed, but a flush failed it: flushed again, and acked only once it holds.
790
+ if (unsavedIn(claim.answered)) {
791
+ const flushed = await durable([]);
792
+ if (!("saved" in flushed)) {
793
+ catchUp(peer, undefined, seat);
794
+ say(peer, { t: "refused", cid, reason: "unavailable", sentence: UNSAVED });
795
+ return { cursor: peer.cursor };
796
+ }
797
+ catchUp(peer, undefined, seat);
798
+ return acked(peer, seat, cid, message.batch, claim.answered, flushed.saved);
799
+ }
800
+ catchUp(peer, undefined, seat);
801
+ say(peer, { t: "ack", cid, seq: claim.answered.at(-1).seq, batch: message.batch, ops: wire.shown(seat, claim.answered) });
802
+ return { cursor: peer.cursor };
803
+ }
804
+ /*
805
+ * BUSY IS NOT REFUSED (FR-45). A call made after one that was told
806
+ * to wait waits too, whatever the rate says now: the client sends
807
+ * them again in the order it made them, the held one first.
808
+ */
809
+ const now = Date.now();
810
+ if (peer.held && peer.held.cid !== cid) {
811
+ say(peer, { t: "busy", cid, retryAfter: Math.max(0, peer.held.until - now) });
812
+ return { cursor: peer.cursor };
813
+ }
814
+ const via = viaFor(served, change);
815
+ const bytes = bytesOf(text);
816
+ const limited = await limitOf(seat, via, change, bytes);
817
+ if (limited)
818
+ return sayLimited(peer, cid, limited);
819
+ delete peer.held;
820
+ return answer(peer, seat, cid, change, via, bytes);
821
+ }
822
+ case "here": {
823
+ const told = message.presence;
824
+ if (!told || typeof told.participant !== "string" || typeof told.stop !== "string") {
825
+ say(peer, { t: "error", sentence: "A presence is a participant and a stop." });
826
+ return unchanged();
827
+ }
828
+ // Held by this socket: it stands while the socket does, with no heartbeat to keep it.
829
+ const presence = { ...presenceFrom(told, seat, new Date(), peer.participant), held: "socket" };
830
+ peer.participant = presence.participant;
831
+ return { ...unchanged(), presence };
832
+ }
833
+ case "bye":
834
+ if (!peer.participant)
835
+ return unchanged();
836
+ delete peer.participant;
837
+ return { ...unchanged(), presence: null };
838
+ default:
839
+ // A message this server does not know is ignored, never refused (docs/stability.md).
840
+ return unchanged();
841
+ }
842
+ },
843
+ publish(ops, peers) {
844
+ const sight = aSight();
845
+ for (const peer of peers) {
846
+ if (peer.cursor === undefined)
847
+ continue;
848
+ const seat = principalOf(peer, sight);
849
+ if (!seat)
850
+ lost(peer);
851
+ else
852
+ catchUp(peer, ops, seat, sight);
853
+ }
854
+ },
855
+ tell(said, peers) {
856
+ const sight = aSight();
857
+ const all = [...peers];
858
+ const who = heldBySockets(said, all);
859
+ for (const peer of all) {
860
+ if (peer.cursor === undefined)
861
+ continue;
862
+ const seat = principalOf(peer, sight);
863
+ if (!seat) {
864
+ lost(peer);
865
+ continue;
866
+ }
867
+ say(peer, { t: "presence", who: wire.whoFor(seat, who.filter((presence) => presence.participant !== peer.participant)) });
868
+ }
869
+ },
870
+ async post(text, asked) {
871
+ const said = answering(asked);
872
+ let body;
873
+ try {
874
+ body = text.length === 0 ? {} : JSON.parse(text);
875
+ }
876
+ catch {
877
+ return reply(400, { error: "A change is one JSON object: { calls } to make, or { undo } to take back.", reason: "invalid" });
878
+ }
879
+ if (!body || typeof body !== "object")
880
+ return reply(400, { error: "A change is one JSON object: { calls } to make, or { undo } to take back.", reason: "invalid" });
881
+ const undo = Array.isArray(body.undo) ? body.undo : undefined;
882
+ const change = {
883
+ t: undo ? "undo" : "call",
884
+ calls: !undo && Array.isArray(body.calls) ? body.calls : [],
885
+ batches: undo ?? [],
886
+ intent: typeof body.intent === "string" && body.intent.length > 0 ? body.intent : undefined,
887
+ batch: body.batch,
888
+ base: undo ? undefined : body.base,
889
+ claimed: claimOfVia(body.via),
890
+ };
891
+ const via = viaFor({ seat: asked.seat, via: asked.via, ...(asked.build ? { hostBuild: asked.build } : {}) }, change);
892
+ // Sent again after its answer was lost — or offered again on a new declaration, or after a reload (FR-43, FR-44, FR-49): only ever the asker's own ops.
893
+ const claim = wire.claim(change.batch, asked.seat);
894
+ if (claim.refusal)
895
+ return reply(409, { error: claim.refusal.sentence, refused: true, reason: claim.refusal.reason, ...said });
896
+ if (claim.answered) {
897
+ // Landed, but a flush failed it: flushed again, and answered only once it holds.
898
+ if (unsavedIn(claim.answered)) {
899
+ const flushed = await durable([]);
900
+ if (!("saved" in flushed))
901
+ return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
902
+ return { ...reply(200, { ops: wire.shown(asked.seat, claim.answered), batch: change.batch, ...said }), landed: flushed.saved };
903
+ }
904
+ return reply(200, { ops: wire.shown(asked.seat, claim.answered), batch: change.batch, ...said });
905
+ }
906
+ /*
907
+ * THE HOST'S LIMITS, BEFORE ANYTHING IS JUDGED. Busy is 429 and the
908
+ * change is kept to send again (FR-45); a hard cap is refused, `limit`,
909
+ * and the change is taken back (FR-46); unavailable is 503, kept.
910
+ */
911
+ const bytes = bytesOf(text);
912
+ const limited = await limitOf(asked.seat, via, change, bytes);
913
+ if (limited)
914
+ return limitedReply(limited, said);
915
+ const landing = await land(asked.seat, via, change, bytes);
916
+ // What it would do is over the host's caps (its `admit`): nothing was kept.
917
+ if (landing.limited)
918
+ return limitedReply(landing.limited, said);
919
+ // A stale write is a conflict, not a loss (FR-05): theirs and yours, by name, and nothing written.
920
+ if (landing.conflicts)
921
+ return reply(409, { error: conflictSentence(landing.conflicts), refused: true, conflict: true, conflicts: landing.conflicts, ...said });
922
+ // The policy's own sentence rather than a bare 403, because that sentence is the product.
923
+ if (landing.refusal) {
924
+ const { sentence, ...why } = landing.refusal;
925
+ return reply(409, { error: sentence, refused: true, ...why, ...said });
926
+ }
927
+ // Not durable: refused `unavailable`, which the client keeps and sends again.
928
+ if (!landing.saved)
929
+ return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
930
+ // An act may make what its own seat may not see: that op goes back withheld, as it would on a poll.
931
+ return { ...reply(200, { ops: wire.shown(asked.seat, landing.result.ops), batch: landing.result.batch, ...said }), landed: landing.saved };
932
+ },
933
+ state(asked) {
934
+ const seen = wire.seenFor(asked.seat);
935
+ return reply(200, {
936
+ ...answering(asked),
937
+ snapshot: seen.snapshot(),
938
+ log: wire.seenLog(asked.seat),
939
+ migrated: [...(options.migrated ?? [])],
940
+ enabledModules: wire.enabledModules(),
941
+ ...wire.horizonOf(),
942
+ });
943
+ },
944
+ since(seq, asked) {
945
+ return reply(200, { ops: wire.since(asked.seat, seq), ...answering(asked) });
946
+ },
947
+ declared(peers) {
948
+ for (const peer of peers) {
949
+ if (peer.cursor === undefined)
950
+ continue;
951
+ delete peer.cursor;
952
+ say(peer, { t: "declaration", version: options.version ?? 1 });
953
+ }
954
+ },
955
+ };
956
+ }
957
+ //# sourceMappingURL=live-protocol.js.map