@graview/ship 0.1.2 → 0.1.3

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/remote.js CHANGED
@@ -1,6 +1,46 @@
1
- import { FieldRevisions, foldPresence, PRESENCE_TTL_MS, REMOTE_PRESENCE_TTL_MS, samePresence, Store, WIRE_PROTOCOL, writtenBy, } from "@graview/core";
2
- import { LIVE_PATH } from "./live.js";
1
+ import { FieldRevisions, foldPresence, PRESENCE_TTL_MS, ReceiveError, refusalOf, REMOTE_PRESENCE_TTL_MS, samePresence, Store, WIRE_PROTOCOL, writtenBy, } from "@graview/core";
2
+ import { LIVE_PATH, LIVE_SUBPROTOCOL, LIVE_WIRE } from "./live.js";
3
3
  import { SEAT_HEADERS } from "./seat-headers.js";
4
+ /** A call this client let go of for a new declaration or a reload: not refused, so nothing is taken back or said. */
5
+ class Superseded extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "Superseded";
9
+ }
10
+ }
11
+ /** "rename (Version 2 has no …)": a call that no longer fits, named in a sentence. */
12
+ const named = (carried, error) => `${carried.calls.map((call) => call.name.replace(/-/g, " ")).join(", ")} (${error instanceof Error ? (error.message.split("\n")[0] ?? "") : String(error)})`;
13
+ /** Calls kept across a reload, as the next page reads them: read once, then forgotten. */
14
+ function takeCarried(carry) {
15
+ if (!carry)
16
+ return [];
17
+ try {
18
+ const raw = carry.storage.getItem(carry.key);
19
+ if (raw === null)
20
+ return [];
21
+ carry.storage.removeItem(carry.key);
22
+ const parsed = JSON.parse(raw);
23
+ return Array.isArray(parsed) ? parsed.filter((one) => !!one && Array.isArray(one.calls)) : [];
24
+ }
25
+ catch {
26
+ return [];
27
+ }
28
+ }
29
+ /**
30
+ * WHAT `send` THROWS, AND WHAT A TAKEN-BACK CHANGE WAS REFUSED WITH: the
31
+ * server's sentence as the message, and `refusal` for a program to branch
32
+ * on (FR-46).
33
+ */
34
+ export class RemoteRefusedError extends Error {
35
+ refusal;
36
+ constructor(refusal) {
37
+ super(refusal.sentence);
38
+ this.refusal = refusal;
39
+ this.name = "RemoteRefusedError";
40
+ }
41
+ }
42
+ /** A server before FR-46 says no reason: read one from the status it answered with. */
43
+ const REASON_BY_STATUS = { 401: "forbidden", 403: "forbidden", 404: "missing", 413: "limit" };
4
44
  /** A refusal that is a stale write: the server's sentence, and the fields that moved. */
5
45
  class StaleWrite extends Error {
6
46
  conflicts;
@@ -10,6 +50,15 @@ class StaleWrite extends Error {
10
50
  this.name = "StaleWrite";
11
51
  }
12
52
  }
53
+ /** A request that never reached the server: the network refused it, or a gateway said the server is away. */
54
+ class Unreached extends Error {
55
+ constructor(message) {
56
+ super(message);
57
+ this.name = "Unreached";
58
+ }
59
+ }
60
+ /** What a gateway in front of a server says when the server behind it is not there. */
61
+ const AWAY = new Set([502, 503, 504]);
13
62
  /**
14
63
  * Opens a store from a server and keeps it in step with it.
15
64
  *
@@ -25,14 +74,74 @@ function localIds() {
25
74
  }
26
75
  const OPEN = 1;
27
76
  export async function openRemote(options) {
77
+ return (await opening(options, takeCarried(options.carry), "This app was updated while your changes were on the way.")).remote;
78
+ }
79
+ /**
80
+ * The remote store, and what the store it replaces needs from it: the
81
+ * sentences about carried calls nobody has heard yet, for it to tell
82
+ * when the new store's own listeners are not there (FR-43).
83
+ */
84
+ async function opening(options, offered, lostSaid) {
28
85
  const call = options.fetch ?? fetch;
29
86
  const headers = { "content-type": "application/json", ...(options.headers ?? {}) };
30
- Object.assign(headers, seatHeaders(options.principal));
87
+ // Who, and through what: a claim only a server that trusts the seat headers believes (FR-06, FR-52).
88
+ const seat = { ...seatHeaders(options.principal), [SEAT_HEADERS.via]: options.via ?? "web" };
89
+ Object.assign(headers, seat);
31
90
  const live = options.live === true;
32
- const reached = await call(`${options.url}/graview/state`, { headers });
33
- if (!reached.ok)
34
- throw new Error((await reached.json().catch(() => ({}))).error ?? `The server refused (${reached.status})`);
35
- const state = (await reached.json());
91
+ const presenceEveryMs = options.presenceEveryMs ?? PRESENCE_TTL_MS / 2;
92
+ const visible = options.visible ?? pageVisible;
93
+ /*
94
+ * WHETHER THE SERVER IS BEING REACHED (FR-49), for a host's banner. Every
95
+ * request after the first goes through `reach`, which says so either way;
96
+ * the socket says so on its welcome and when a welcomed socket drops.
97
+ */
98
+ let status = "connecting";
99
+ const statusListeners = new Set();
100
+ const tally = { reconnects: 0, rebases: 0, conflicts: 0, resyncs: 0 };
101
+ /** Calls that could not reach the server, each waiting to be sent again once it is back. */
102
+ const held = [];
103
+ const become = (next) => {
104
+ if (next === status)
105
+ return;
106
+ if (status === "offline" && next === "online")
107
+ tally.reconnects++;
108
+ status = next;
109
+ for (const told of statusListeners)
110
+ told(next);
111
+ if (next === "online")
112
+ for (const waiting of held.splice(0))
113
+ waiting.again();
114
+ };
115
+ const reach = async (url, init) => {
116
+ let response;
117
+ try {
118
+ response = await call(url, init);
119
+ }
120
+ catch (error) {
121
+ // A live client whose socket is up is reaching the server, whatever one request met.
122
+ if (!socketReady())
123
+ become("offline");
124
+ throw new Unreached(error instanceof Error ? error.message : String(error));
125
+ }
126
+ if (AWAY.has(response.status)) {
127
+ if (!socketReady())
128
+ become("offline");
129
+ throw new Unreached(`The server is away (${response.status})`);
130
+ }
131
+ become("online");
132
+ return response;
133
+ };
134
+ const fetchState = async (first = false) => {
135
+ const url = `${options.url}/graview/state`;
136
+ const reached = first ? await call(url, { headers }) : await reach(url, { headers });
137
+ if (!reached.ok)
138
+ throw new Error((await reached.json().catch(() => ({}))).error ?? `The server refused (${reached.status})`);
139
+ return (await reached.json());
140
+ };
141
+ const state = await fetchState(true);
142
+ // A polling client has its first answer; a live one is connecting until its socket is welcomed.
143
+ if (!live)
144
+ status = "online";
36
145
  const enabledModules = state.enabledModules ?? options.enabledModules;
37
146
  const store = new Store({
38
147
  schema: options.app.schema,
@@ -70,7 +179,7 @@ export async function openRemote(options) {
70
179
  });
71
180
  let seen = state.log.at(-1)?.seq ?? (state.horizon ?? 0) - 1;
72
181
  /** Every field's revision as the server's ops this client has say it (FR-05). */
73
- const revisions = FieldRevisions.of(state.log);
182
+ let revisions = FieldRevisions.of(state.log);
74
183
  /*
75
184
  * PRESENCE, beside the log and never in it. `mine` is the last word this
76
185
  * browser said about itself; it goes out with every poll (or down the
@@ -78,10 +187,15 @@ export async function openRemote(options) {
78
187
  * whoever is listening.
79
188
  */
80
189
  let mine = null;
190
+ /** The key the server holds this client under, as its welcome or its last `here` said (FR-47). */
191
+ let self;
81
192
  let known = new Map();
82
193
  const whoListeners = new Set();
83
194
  const heard = (who) => {
84
195
  const next = foldPresence(new Map(), who, Date.now(), REMOTE_PRESENCE_TTL_MS, mine?.participant);
196
+ // Never yourself, under the key you made or the one the server built for you.
197
+ if (self !== undefined)
198
+ next.delete(self);
85
199
  let changed = next.size !== known.size;
86
200
  if (!changed)
87
201
  for (const [participant, presence] of next)
@@ -103,7 +217,7 @@ export async function openRemote(options) {
103
217
  * never sits in the log beside the server's op for the same press.
104
218
  *
105
219
  * `provisional` is every batch whose provisional ops may still be in the
106
- * log: a batch is dropped once, and only while it is, because a live
220
+ * log: a batch is dropped once, and only while it is, because a
107
221
  * client's batch id is the one the server's op lands in too, and
108
222
  * dropping it again would cut the server's op.
109
223
  */
@@ -116,48 +230,166 @@ export async function openRemote(options) {
116
230
  };
117
231
  /** Socket calls not yet answered, by cid: what was sent, and how to tell the sender. */
118
232
  const waiting = new Map();
233
+ /** Tells whoever sent a batch the server has now answered, with the ops it landed as. */
234
+ const tellAnswered = (batch, ops) => {
235
+ const answered = waiting.get(batch);
236
+ if (!answered)
237
+ return;
238
+ waiting.delete(batch);
239
+ answered.resolve({ ops: ops.filter((op) => op.batch === batch), batch });
240
+ };
241
+ /** Set while the client takes the server's whole state; what arrives meanwhile waits for it, in order. */
242
+ let resyncing;
243
+ let meanwhile = [];
119
244
  const land = (ops, drop = []) => {
120
245
  if (ops.length === 0 && drop.length === 0)
121
246
  return [];
247
+ if (resyncing) {
248
+ meanwhile.push({ ops, drop });
249
+ return [];
250
+ }
251
+ /*
252
+ * NEVER NUMBERED OUT OF THE SERVER'S ORDER (FR-53). `rebase` lands each
253
+ * op at the end of this log, so ops that begin past the next seq this
254
+ * client has would be numbered as if the ones between never happened.
255
+ * They begin there when the server compacted past where this client
256
+ * left off: `/graview/since` and the welcome begin at the horizon, and
257
+ * the ops between are in no answer. The client takes the state instead.
258
+ */
259
+ const first = Math.min(...ops.filter((op) => op.seq > seen).map((op) => op.seq));
260
+ if (Number.isFinite(first) && first > seen + 1) {
261
+ meanwhile.push({ ops, drop });
262
+ resync();
263
+ return [];
264
+ }
122
265
  /*
123
- * A live client names the batch its call lands in, so an op of the
266
+ * A client names the batch its call lands in (FR-49), so an op of the
124
267
  * server's in one of its pending batches IS that batch's answer —
125
- * pushed, or caught up on after a reconnect, before its ack arrived.
268
+ * pushed, polled, or caught up on after a reconnect, before its answer arrived.
126
269
  */
127
- const echoed = live ? pending.filter((batch) => ops.some((op) => op.batch === batch)) : [];
270
+ const echoed = pending.filter((batch) => ops.some((op) => op.batch === batch));
271
+ const dropping = [...new Set([...drop, ...echoed])].filter((batch) => provisional.has(batch));
272
+ let landed;
273
+ const under = pending.filter((batch) => !echoed.includes(batch));
274
+ try {
275
+ landed = store.rebase({ confirmed: ops, pending: under, drop: dropping }).confirmed;
276
+ }
277
+ catch (error) {
278
+ // An op of the server's that does not fit here: this copy drifted, and is as it was. The server's state is the truth.
279
+ if (!(error instanceof ReceiveError))
280
+ throw error;
281
+ meanwhile.push({ ops, drop });
282
+ resync();
283
+ return [];
284
+ }
128
285
  for (const batch of echoed)
129
286
  settle(batch);
130
- const dropping = [...new Set([...drop, ...echoed])].filter((batch) => provisional.has(batch));
287
+ if (ops.some((op) => op.seq > seen) && under.some((batch) => !dropping.includes(batch)))
288
+ tally.rebases++;
131
289
  if (ops.length > 0) {
132
290
  seen = Math.max(seen, ...ops.map((op) => op.seq));
133
291
  revisions.note(ops);
134
292
  }
135
- const landed = store.rebase({ confirmed: ops, pending: [...pending], drop: dropping }).confirmed;
136
293
  for (const batch of dropping)
137
294
  provisional.delete(batch);
138
- for (const batch of echoed) {
139
- const answered = waiting.get(batch);
140
- if (!answered)
141
- continue;
142
- waiting.delete(batch);
143
- answered.resolve({ ops: ops.filter((op) => op.batch === batch), batch });
144
- }
295
+ for (const batch of echoed)
296
+ tellAnswered(batch, ops);
145
297
  return landed;
146
298
  };
299
+ /*
300
+ * THE SERVER'S WHOLE STATE, ADOPTED (FR-53): fetched, taken as this
301
+ * store's graph and log by `store.adopt`, and this client's unanswered
302
+ * batches applied again on top. A batch the state already holds (a live
303
+ * client's, landed before its ack came) is answered, not applied twice.
304
+ * What arrived while the state was on its way lands after it; whatever
305
+ * the state already holds is skipped. A state that cannot be fetched
306
+ * leaves the client as it was, and the next answer that cannot land asks
307
+ * again.
308
+ */
309
+ const resync = () => {
310
+ if (resyncing)
311
+ return;
312
+ resyncing = track(fetchState()
313
+ .then((next) => {
314
+ // A state on another declaration is not this store's to adopt: the client opens on it instead (FR-43).
315
+ if (moved(next)) {
316
+ meanwhile = [];
317
+ return;
318
+ }
319
+ const held = new Set(next.log.map((op) => op.batch));
320
+ const answered = pending.filter((batch) => held.has(batch));
321
+ for (const batch of answered)
322
+ settle(batch);
323
+ const adopted = store.adopt({
324
+ snapshot: next.snapshot,
325
+ log: next.log,
326
+ ...(next.horizon !== undefined ? { horizon: next.horizon } : {}),
327
+ pending: [...pending],
328
+ drop: [...provisional].filter((batch) => !pending.includes(batch)),
329
+ });
330
+ // The only provisional ops in the log now are the ones applied again.
331
+ provisional.clear();
332
+ for (const op of adopted.pending)
333
+ provisional.add(op.batch);
334
+ seen = next.log.at(-1)?.seq ?? (next.horizon ?? 0) - 1;
335
+ revisions = FieldRevisions.of(next.log);
336
+ tally.resyncs++;
337
+ for (const batch of answered)
338
+ tellAnswered(batch, next.log);
339
+ })
340
+ .then(() => {
341
+ resyncing = undefined;
342
+ const later = meanwhile;
343
+ meanwhile = [];
344
+ for (const { ops, drop } of later)
345
+ land(ops, drop);
346
+ }, () => {
347
+ // Not reached, or not adopted: as it was. What waited comes again from `seen`.
348
+ resyncing = undefined;
349
+ meanwhile = [];
350
+ }));
351
+ };
352
+ /*
353
+ * EVERY ANSWER A POLL READS SAYS WHICH DECLARATION AND WHICH BUILD
354
+ * (FR-43, FR-44). One on another declaration is not landed here: the
355
+ * client opens on the new one, exactly as a socket's `declaration` makes
356
+ * it, and its calls on the way go with it.
357
+ */
358
+ const moved = (answer) => {
359
+ if (typeof answer.build === "string")
360
+ noticeBuild(answer.build);
361
+ if (typeof answer.version !== "number" || answer.version === state.version)
362
+ return false;
363
+ void declarationChanged(answer.version);
364
+ return true;
365
+ };
147
366
  const since = async (seq) => {
148
- const response = await call(`${options.url}/graview/since?seq=${seq}`, { headers });
149
- return (await response.json()).ops ?? [];
367
+ const response = await reach(`${options.url}/graview/since?seq=${seq}`, { headers });
368
+ const answer = (await response.json());
369
+ return moved(answer) ? [] : (answer.ops ?? []);
150
370
  };
371
+ /** Asks for what is new, and waits for a resync the answer started, so the store is the server's when it returns. */
151
372
  const pull = async () => {
152
- if (mine && !socketReady()) {
153
- const response = await call(`${options.url}/graview/here`, {
373
+ const landed = await pulled();
374
+ if (resyncing)
375
+ await resyncing;
376
+ return landed;
377
+ };
378
+ const pulled = async () => {
379
+ // Presence rides the poll only while somebody is looking (FR-49).
380
+ if (mine && !socketReady() && visible()) {
381
+ const response = await reach(`${options.url}/graview/here`, {
154
382
  method: "POST",
155
383
  headers,
156
384
  body: JSON.stringify({ presence: mine, seq: seen }),
157
385
  });
158
- const { who, ops } = (await response.json());
159
- heard(who ?? []);
160
- return land(ops ?? []);
386
+ const answer = (await response.json());
387
+ if (moved(answer))
388
+ return [];
389
+ if (typeof answer.participant === "string")
390
+ self = answer.participant;
391
+ heard(answer.who ?? []);
392
+ return land(answer.ops ?? []);
161
393
  }
162
394
  return land(await since(seen));
163
395
  };
@@ -180,19 +412,78 @@ export async function openRemote(options) {
180
412
  * dropped, in one rebase. `send` never applies first, so its answer
181
413
  * lands under whatever is pending.
182
414
  */
183
- const post = async (body, mine) => {
184
- const response = await call(`${options.url}/graview/ops`, {
185
- method: "POST",
186
- headers,
187
- // A person at an interface, unless the caller said otherwise (FR-06).
188
- body: JSON.stringify({ via: options.via ?? "web", ...body }),
189
- });
190
- const answer = (await response.json());
415
+ /*
416
+ * ONE POST AT A TIME, IN THE ORDER THE CHANGES WERE MADE. The server
417
+ * judges them in the order they reach it, and a post that has to wait —
418
+ * the host is busy (FR-45), or the server cannot be reached (FR-49) —
419
+ * must not be overtaken by one made after it. So a post waits in its
420
+ * turn and goes again from there, and the posts behind it wait for it.
421
+ */
422
+ let lane = Promise.resolve();
423
+ const post = (body, mine) => {
424
+ const turn = lane.then(() => posted(body, mine));
425
+ lane = turn.catch(() => { });
426
+ return turn;
427
+ };
428
+ /** Resolves once the server is reached again (FR-49); rejects if the client closes first. */
429
+ const backOnline = () => new Promise((again, give) => held.push({ again, give }));
430
+ const posted = async (body, mine) => {
431
+ let response;
432
+ let answer;
433
+ for (;;) {
434
+ try {
435
+ response = await reach(`${options.url}/graview/ops`, {
436
+ method: "POST",
437
+ headers,
438
+ body: JSON.stringify(body),
439
+ });
440
+ }
441
+ catch (error) {
442
+ /*
443
+ * NOT REFUSED, NOT REACHED (FR-49). A call the server never heard is
444
+ * not taken back as if it had been refused: it stays shown, counts as
445
+ * pending, and goes again — down the socket or over HTTP, whichever is
446
+ * up — the moment the server is reached again. Posts batch-named, so
447
+ * one the server did hear is answered with the ops it made.
448
+ */
449
+ if (!(error instanceof Unreached) || closed)
450
+ throw error;
451
+ await backOnline();
452
+ if (socketReady())
453
+ return viaSocket(body, mine);
454
+ continue;
455
+ }
456
+ answer = (await response.json().catch(() => ({})));
457
+ if (response.status !== 429 || closed)
458
+ break;
459
+ /*
460
+ * BUSY, NOT REFUSED (FR-45): the host asked for it again later. The
461
+ * change stays shown and pending, and goes again after the wait.
462
+ */
463
+ const header = Number(response.headers.get("retry-after"));
464
+ const wait = typeof answer.retryAfter === "number" ? answer.retryAfter : Number.isFinite(header) && header > 0 ? header * 1000 : 1000;
465
+ await new Promise((later) => setTimeout(later, Math.max(0, wait)));
466
+ if (socketReady())
467
+ return viaSocket(body, mine);
468
+ }
469
+ /*
470
+ * Answered on another declaration, or after this store was let go: the
471
+ * call goes with the rest to the store on the new one, under its batch,
472
+ * where the server answers it once (FR-43).
473
+ */
474
+ if (retiring || moved(answer))
475
+ throw new Superseded("The app was changed.");
191
476
  if (!response.ok) {
192
477
  // The policy's own sentence, carried across the wire unchanged: a
193
478
  // refusal a person can read is the whole point of having one.
194
479
  const sentence = answer.error ?? `The server refused (${response.status})`;
195
- throw answer.conflict ? new StaleWrite(sentence, answer.conflicts ?? []) : new Error(sentence);
480
+ if (answer.conflict)
481
+ throw new StaleWrite(sentence, answer.conflicts ?? []);
482
+ throw new RemoteRefusedError({
483
+ reason: answer.reason ?? REASON_BY_STATUS[response.status] ?? "invalid",
484
+ sentence,
485
+ ...(answer.wouldNeed?.length ? { wouldNeed: answer.wouldNeed } : {}),
486
+ });
196
487
  }
197
488
  let ops = answer.ops ?? [];
198
489
  /*
@@ -241,23 +532,50 @@ export async function openRemote(options) {
241
532
  }
242
533
  };
243
534
  const sayWhere = (force = false) => {
244
- if (!mine || !socketReady())
535
+ if (!mine || !socketReady() || !visible())
245
536
  return;
246
- if (!force && said && samePresence(mine, said) && Date.now() - saidAt < PRESENCE_TTL_MS / 2)
537
+ if (!force && said && samePresence(mine, said) && Date.now() - saidAt < presenceEveryMs)
247
538
  return;
248
539
  if (say({ t: "here", presence: mine })) {
249
540
  said = mine;
250
541
  saidAt = Date.now();
251
542
  }
252
543
  };
544
+ /*
545
+ * CALLS THE HOST ASKED TO WAIT (FR-45), by cid. They stay shown and
546
+ * pending, and go again together once the wait is over, in the order
547
+ * they were made; a call made meanwhile joins them rather than going
548
+ * ahead of them.
549
+ */
550
+ const busy = new Set();
551
+ let busyTimer;
552
+ const sendBusy = () => {
553
+ busyTimer = undefined;
554
+ const again = [...waiting.entries()].filter(([cid]) => busy.has(cid));
555
+ busy.clear();
556
+ for (const [, waiter] of again)
557
+ say(waiter.message);
558
+ };
559
+ const hold = (cid, retryAfter) => {
560
+ if (!waiting.has(cid))
561
+ return;
562
+ busy.add(cid);
563
+ if (busyTimer)
564
+ clearTimeout(busyTimer);
565
+ busyTimer = setTimeout(sendBusy, Math.max(0, retryAfter));
566
+ };
253
567
  /** A call down the socket; its answer lands when it comes, in the order the server said it. */
254
568
  const viaSocket = (body, mine) => new Promise((resolve, reject) => {
255
569
  const cid = mine ?? `send-${++counter}`;
256
- const via = options.via ?? "web";
257
570
  const message = body.undo
258
- ? { t: "undo", cid, batches: body.undo, via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}) }
259
- : { t: "call", cid, calls: body.calls ?? [], via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}), ...(body.base?.length ? { base: body.base } : {}) };
571
+ ? { t: "undo", cid, batches: body.undo, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}) }
572
+ : { t: "call", cid, calls: body.calls ?? [], ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}), ...(body.base?.length ? { base: body.base } : {}) };
260
573
  waiting.set(cid, { message, ...(mine !== undefined ? { mine } : {}), resolve, reject });
574
+ // Behind calls the host asked to wait: it goes with them.
575
+ if (busy.size > 0) {
576
+ busy.add(cid);
577
+ return;
578
+ }
261
579
  // Not open: it goes when the socket is back, after the welcome has caught this client up.
262
580
  say(message);
263
581
  });
@@ -266,13 +584,27 @@ export async function openRemote(options) {
266
584
  const hear = (message) => {
267
585
  switch (message.t) {
268
586
  case "welcome": {
587
+ noticeBuild(message.build);
588
+ // Back on a server whose declaration moved while this socket was away (FR-43): its ops are not this store's to fold.
589
+ if (typeof message.version === "number" && message.version !== state.version) {
590
+ void declarationChanged(message.version);
591
+ return;
592
+ }
269
593
  welcomed = true;
270
594
  attempts = 0;
595
+ if (typeof message.participant === "string")
596
+ self = message.participant;
271
597
  land(message.ops ?? []);
272
598
  // Whatever was sent and never answered goes again: the server answers a batch it already has with its ops.
599
+ busy.clear();
600
+ if (busyTimer)
601
+ clearTimeout(busyTimer);
602
+ busyTimer = undefined;
273
603
  for (const waiter of waiting.values())
274
604
  say(waiter.message);
275
605
  sayWhere(true);
606
+ // And what could not reach the server at all goes after it.
607
+ become("online");
276
608
  opened();
277
609
  return;
278
610
  }
@@ -300,16 +632,160 @@ export async function openRemote(options) {
300
632
  if (!waiter)
301
633
  return;
302
634
  waiting.delete(message.cid);
303
- waiter.reject(message.t === "conflict" ? new StaleWrite(message.sentence, message.conflicts ?? []) : new Error(message.sentence));
635
+ waiter.reject(message.t === "conflict"
636
+ ? new StaleWrite(message.sentence, message.conflicts ?? [])
637
+ : new RemoteRefusedError({
638
+ // A server before FR-46 says no reason.
639
+ reason: message.reason ?? "invalid",
640
+ sentence: message.sentence,
641
+ ...(message.wouldNeed?.length ? { wouldNeed: [...message.wouldNeed] } : {}),
642
+ }));
304
643
  return;
305
644
  }
645
+ case "busy":
646
+ // Not now, and not refused (FR-45): kept, and sent again after the wait.
647
+ if (typeof message.cid === "string")
648
+ hold(message.cid, typeof message.retryAfter === "number" ? message.retryAfter : 1000);
649
+ return;
306
650
  case "presence":
307
651
  heard(message.who ?? []);
308
652
  return;
653
+ case "declaration":
654
+ if (typeof message.version === "number" && message.version !== state.version)
655
+ void declarationChanged(message.version);
656
+ return;
657
+ case "reload":
658
+ reloadOntoNewer(typeof message.reason === "string" ? message.reason : "This app was updated.");
659
+ return;
309
660
  default:
310
661
  return;
311
662
  }
312
663
  };
664
+ /* ── SKEW AND CHANGE (FR-43, FR-44) ─────────────────────────────────── */
665
+ /** Set once this store has been let go of, for a new declaration or a reload: it acts on nothing more. */
666
+ let retiring = false;
667
+ const declarationListeners = new Set();
668
+ const buildListeners = new Set();
669
+ let otherBuild;
670
+ const noticeBuild = (build) => {
671
+ if (otherBuild !== undefined || !options.build || typeof build !== "string" || build.length === 0 || build === options.build)
672
+ return;
673
+ otherBuild = build;
674
+ for (const listener of buildListeners)
675
+ listener(build);
676
+ };
677
+ /** Every call this client applied that the server has not answered, oldest first; and how many undos are. */
678
+ const unanswered = () => {
679
+ const carried = [];
680
+ let undos = 0;
681
+ for (const batch of pending) {
682
+ const made = asked.get(batch);
683
+ if (made)
684
+ carried.push({ calls: made.calls, ...(made.intent ? { intent: made.intent } : {}), batch });
685
+ else
686
+ undos++;
687
+ }
688
+ return { carried, undos };
689
+ };
690
+ const undosSaid = (undos, why) => `${why} while ${undos === 1 ? "an undo of yours was" : "undos of yours were"} on the way; ${undos === 1 ? "it was" : "they were"} not made.`;
691
+ /** Lets this store go: what it waits for is let go too, never said to be refused, and its socket closes without a goodbye. */
692
+ const retire = (why) => {
693
+ retiring = true;
694
+ // Where this page stands is the next store's to say now: closing this one later must not say it left.
695
+ mine = null;
696
+ const superseded = new Superseded(why);
697
+ for (const waiter of waiting.values())
698
+ waiter.reject(superseded);
699
+ waiting.clear();
700
+ if (timer)
701
+ clearInterval(timer);
702
+ closed = true;
703
+ if (retry)
704
+ clearTimeout(retry);
705
+ if (busyTimer)
706
+ clearTimeout(busyTimer);
707
+ // A post waiting for the server to be reached again goes with the rest instead.
708
+ for (const waiting of held.splice(0))
709
+ waiting.give(superseded);
710
+ const was = socket;
711
+ socket = undefined;
712
+ welcomed = false;
713
+ try {
714
+ was?.close(1000, why);
715
+ }
716
+ catch {
717
+ // Already gone.
718
+ }
719
+ opened();
720
+ };
721
+ /*
722
+ * THE DECLARATION CHANGED (FR-43). The host's `resolveApp` names the app
723
+ * at the server's version; a remote store is opened on it — the
724
+ * server's migrated state — and handed to `onDeclaration`, with every
725
+ * call this one had on the way offered again there under the batch it
726
+ * was sent in, so one the server already made is not made twice.
727
+ */
728
+ async function declarationChanged(version) {
729
+ if (retiring)
730
+ return;
731
+ if (!options.resolveApp) {
732
+ reloadOntoNewer(`This app was changed on its server (version ${version}); reload the page to carry on.`);
733
+ return;
734
+ }
735
+ const { carried, undos } = unanswered();
736
+ const resolveApp = options.resolveApp;
737
+ const standing = mine;
738
+ retire("The app was changed.");
739
+ try {
740
+ const app = await resolveApp(version);
741
+ const next = await opening({ ...options, app }, carried, "The app was changed while your changes were on the way.");
742
+ if (standing)
743
+ next.remote.presence.here(standing);
744
+ for (const listener of declarationListeners)
745
+ listener(next.remote, version);
746
+ const said = [...(undos > 0 ? [refused(undosSaid(undos, "The app was changed"))] : []), ...next.unheard()];
747
+ for (const refusal of said)
748
+ for (const told of refusals)
749
+ told(refusal.sentence, refusal);
750
+ }
751
+ catch (error) {
752
+ const sentence = `The app was changed, but the new version could not be opened: ${error instanceof Error ? error.message : String(error)}`;
753
+ for (const told of refusals)
754
+ told(sentence, refused(sentence));
755
+ }
756
+ }
757
+ /*
758
+ * THE SERVER NO LONGER SERVES THIS PAGE'S PROTOCOL (FR-44). Every call
759
+ * not yet answered is kept in `carry`, the page reloads, and the next
760
+ * `openRemote` with the same key offers them again. Without `carry`
761
+ * they are refused in words first, so nobody believes they were made.
762
+ */
763
+ function reloadOntoNewer(reason) {
764
+ if (retiring)
765
+ return;
766
+ const { carried, undos } = unanswered();
767
+ retire(reason);
768
+ let kept = false;
769
+ if (options.carry && carried.length > 0) {
770
+ try {
771
+ options.carry.storage.setItem(options.carry.key, JSON.stringify(carried));
772
+ kept = true;
773
+ }
774
+ catch {
775
+ // Storage full or refused: the reload still happens, and the calls are said lost below.
776
+ }
777
+ }
778
+ const said = [];
779
+ if (!kept && carried.length > 0) {
780
+ said.push(`${reason} ${carried.length === 1 ? "A change of yours was" : `${carried.length} changes of yours were`} not sent; make ${carried.length === 1 ? "it" : "them"} again after the page reloads.`);
781
+ }
782
+ if (undos > 0)
783
+ said.push(undosSaid(undos, "This app was updated"));
784
+ for (const sentence of said)
785
+ for (const told of refusals)
786
+ told(sentence, refused(sentence));
787
+ (options.reloadPage ?? pageReload)();
788
+ }
313
789
  const connect = () => {
314
790
  if (closed || !live)
315
791
  return;
@@ -317,7 +793,7 @@ export async function openRemote(options) {
317
793
  const { "content-type": _json, ...carried } = headers;
318
794
  let made;
319
795
  try {
320
- made = (options.socket ?? platformSocket)(url, carried);
796
+ made = options.socket ? options.socket(url, carried, [LIVE_SUBPROTOCOL]) : platformSocket(url, carried);
321
797
  }
322
798
  catch {
323
799
  return reconnect();
@@ -328,7 +804,8 @@ export async function openRemote(options) {
328
804
  if (socket !== made)
329
805
  return;
330
806
  // From the last op this client has: the welcome brings exactly the ones after it.
331
- made.send(JSON.stringify({ t: "hello", seq: seen, protocol: WIRE_PROTOCOL }));
807
+ // Which codec, which protocol and which build this page speaks (FR-44).
808
+ made.send(JSON.stringify({ t: "hello", seq: seen, protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, ...(options.build ? { build: options.build.slice(0, 64) } : {}) }));
332
809
  };
333
810
  made.onmessage = (event) => {
334
811
  if (socket !== made)
@@ -345,9 +822,13 @@ export async function openRemote(options) {
345
822
  made.onclose = () => {
346
823
  if (socket !== made)
347
824
  return;
825
+ const dropped = welcomed;
348
826
  socket = undefined;
349
827
  welcomed = false;
350
828
  said = null;
829
+ // A socket that never opened says nothing a poll does not; one that was up and dropped is the server gone.
830
+ if (dropped)
831
+ become("offline");
351
832
  reconnect();
352
833
  };
353
834
  made.onerror = () => {
@@ -357,7 +838,7 @@ export async function openRemote(options) {
357
838
  const reconnect = () => {
358
839
  if (closed)
359
840
  return;
360
- const wait = Math.min(10_000, 250 * 2 ** attempts) * (0.75 + Math.random() * 0.5);
841
+ const wait = backoffFor(options.backoff, attempts);
361
842
  attempts++;
362
843
  retry = setTimeout(connect, wait);
363
844
  };
@@ -378,6 +859,10 @@ export async function openRemote(options) {
378
859
  const appliedAll = store.applyAll.bind(store);
379
860
  const undone = store.undo.bind(store);
380
861
  const refusals = new Set();
862
+ /** What became of carried calls before anybody listened: told to the first listener (FR-43, FR-44). */
863
+ let unheard = [];
864
+ /** A change of this client's that did not survive a new declaration or a reload: `invalid`, it no longer fits (FR-46). */
865
+ const refused = (sentence) => ({ reason: "invalid", sentence });
381
866
  const conflictListeners = new Set();
382
867
  /** Set while `useMine` sends a change again: it goes without the revisions it was refused for. */
383
868
  let overriding = false;
@@ -389,7 +874,11 @@ export async function openRemote(options) {
389
874
  * as it never happened there.
390
875
  */
391
876
  const takeBack = async (batch, error) => {
392
- const reason = error instanceof Error ? error.message : String(error);
877
+ // Let go of for a new declaration or a reload: carried, not refused (FR-43, FR-44).
878
+ if (error instanceof Superseded || retiring)
879
+ return;
880
+ const refusal = error instanceof RemoteRefusedError ? error.refusal : refusalOf(error);
881
+ const reason = refusal.sentence;
393
882
  settle(batch);
394
883
  try {
395
884
  land([], [batch]);
@@ -400,6 +889,8 @@ export async function openRemote(options) {
400
889
  }
401
890
  const made = asked.get(batch);
402
891
  asked.delete(batch);
892
+ if (error instanceof StaleWrite)
893
+ tally.conflicts++;
403
894
  /*
404
895
  * A stale write means this client is behind: theirs is on the server
405
896
  * and not yet here. A socket has already pushed it; a poller asks, so
@@ -433,7 +924,7 @@ export async function openRemote(options) {
433
924
  return;
434
925
  }
435
926
  for (const told of refusals)
436
- told(reason);
927
+ told(reason, refusal);
437
928
  };
438
929
  /*
439
930
  * EVERY WAY THE GRAPH CHANGES GOES DOWN THE WIRE. `apply` is one call;
@@ -471,7 +962,7 @@ export async function openRemote(options) {
471
962
  answers.set(result.batch, track(transmit({
472
963
  calls,
473
964
  ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}),
474
- ...(live ? { batch: result.batch } : {}),
965
+ batch: result.batch,
475
966
  ...(base.length > 0 ? { base } : {}),
476
967
  }, result.batch).catch((error) => takeBack(result.batch, error))));
477
968
  return result;
@@ -500,12 +991,22 @@ export async function openRemote(options) {
500
991
  .then(() => transmit({
501
992
  undo: ids.map((id) => batches.get(id) ?? id),
502
993
  ...(undoOptions?.intent ? { intent: undoOptions.intent } : {}),
503
- ...(live ? { batch: result.batch } : {}),
994
+ batch: result.batch,
504
995
  }, result.batch))
505
996
  .catch((error) => takeBack(result.batch, error))));
506
997
  return result;
507
998
  });
508
- const send = async (calls, sending = {}) => (await track(transmit({ calls, ...sending }))).ops;
999
+ const send = async (calls, sending = {}) => {
1000
+ sendsOut++;
1001
+ try {
1002
+ return (await track(transmit({ calls, ...sending }))).ops;
1003
+ }
1004
+ finally {
1005
+ sendsOut--;
1006
+ }
1007
+ };
1008
+ /** `send` calls not yet answered: they apply nothing here first, so `pending` does not hold them. */
1009
+ let sendsOut = 0;
509
1010
  const presence = {
510
1011
  here(next) {
511
1012
  mine = next;
@@ -520,7 +1021,7 @@ export async function openRemote(options) {
520
1021
  leave() {
521
1022
  if (!mine)
522
1023
  return;
523
- const body = JSON.stringify({ participant: mine.participant });
1024
+ const body = JSON.stringify({ participant: self ?? mine.participant });
524
1025
  mine = null;
525
1026
  if (say({ t: "bye" }))
526
1027
  return;
@@ -551,7 +1052,30 @@ export async function openRemote(options) {
551
1052
  await Promise.race([openedLive, new Promise((done) => (waited = setTimeout(done, options.openTimeoutMs ?? 3000)))]);
552
1053
  clearTimeout(waited);
553
1054
  }
554
- return {
1055
+ /*
1056
+ * CALLS CARRIED HERE — from the store this one replaces, or across a
1057
+ * reload — offered again now it is open, each under the batch it was
1058
+ * sent in. One the server's log already holds landed before the change
1059
+ * and is not made twice; one that no longer fits is named, in words.
1060
+ */
1061
+ if (offered.length > 0 && !retiring) {
1062
+ const lost = [];
1063
+ const landed = new Set(store.log.all().map((op) => op.batch));
1064
+ for (const one of offered) {
1065
+ if (one.batch !== undefined && landed.has(one.batch))
1066
+ continue;
1067
+ try {
1068
+ store.applyAll(one.calls, { ...(one.intent ? { intent: one.intent } : {}), ...(one.batch ? { batch: one.batch } : {}) });
1069
+ }
1070
+ catch (error) {
1071
+ lost.push(named(one, error));
1072
+ }
1073
+ }
1074
+ if (lost.length > 0) {
1075
+ unheard.push(refused(`${lostSaid} ${lost.length === 1 ? "One no longer fits and was not made" : `${lost.length} no longer fit and were not made`}: ${lost.join("; ")}.`));
1076
+ }
1077
+ }
1078
+ const remote = {
555
1079
  store,
556
1080
  version: state.version,
557
1081
  migrated: state.migrated ?? [],
@@ -559,15 +1083,37 @@ export async function openRemote(options) {
559
1083
  pull,
560
1084
  onRefusal(listener) {
561
1085
  refusals.add(listener);
1086
+ const told = unheard;
1087
+ unheard = [];
1088
+ for (const refusal of told)
1089
+ listener(refusal.sentence, refusal);
562
1090
  return () => refusals.delete(listener);
563
1091
  },
1092
+ onDeclaration(listener) {
1093
+ declarationListeners.add(listener);
1094
+ return () => declarationListeners.delete(listener);
1095
+ },
1096
+ onBuild(listener) {
1097
+ buildListeners.add(listener);
1098
+ if (otherBuild !== undefined)
1099
+ listener(otherBuild);
1100
+ return () => buildListeners.delete(listener);
1101
+ },
564
1102
  onConflict(listener) {
565
1103
  conflictListeners.add(listener);
566
1104
  return () => conflictListeners.delete(listener);
567
1105
  },
568
1106
  revision: (node, field) => revisions.of(node, field),
569
1107
  seq: () => seen,
1108
+ participant: () => self,
570
1109
  transport: () => (socketReady() ? "socket" : "poll"),
1110
+ status: () => status,
1111
+ onStatus(listener) {
1112
+ statusListeners.add(listener);
1113
+ return () => statusListeners.delete(listener);
1114
+ },
1115
+ counters: () => ({ ...tally }),
1116
+ pending: () => pending.length + sendsOut,
571
1117
  async settled() {
572
1118
  // Whatever is in flight now — and whatever a settling handler put in flight after it.
573
1119
  while (inFlight.size > 0)
@@ -581,6 +1127,10 @@ export async function openRemote(options) {
581
1127
  closed = true;
582
1128
  if (retry)
583
1129
  clearTimeout(retry);
1130
+ if (busyTimer)
1131
+ clearTimeout(busyTimer);
1132
+ for (const waiting of held.splice(0))
1133
+ waiting.give(new Error("The client closed before the server could be reached."));
584
1134
  const was = socket;
585
1135
  socket = undefined;
586
1136
  welcomed = false;
@@ -592,26 +1142,51 @@ export async function openRemote(options) {
592
1142
  }
593
1143
  },
594
1144
  };
1145
+ return {
1146
+ remote,
1147
+ unheard() {
1148
+ const told = unheard;
1149
+ unheard = [];
1150
+ return told;
1151
+ },
1152
+ };
595
1153
  /** The platform's WebSocket, with the headers where the runtime can send them. */
596
1154
  function platformSocket(url, carried) {
597
1155
  const Socket = globalThis.WebSocket;
598
1156
  if (!Socket)
599
1157
  throw new Error("This runtime has no WebSocket; the client polls instead.");
600
1158
  const page = typeof globalThis.document !== "undefined";
1159
+ const protocols = options.subprotocol ? [LIVE_SUBPROTOCOL] : [];
601
1160
  if (!page) {
602
1161
  try {
603
- return new Socket(url, { headers: carried });
1162
+ return new Socket(url, { headers: carried, ...(protocols.length > 0 ? { protocols } : {}) });
604
1163
  }
605
1164
  catch {
606
1165
  // A runtime whose WebSocket takes protocols only: the seat rides in the query, as a page's does.
607
1166
  }
608
1167
  }
609
1168
  const withSeat = new URL(url);
610
- for (const [name, value] of Object.entries(seatHeaders(options.principal)))
1169
+ for (const [name, value] of Object.entries(seat))
611
1170
  withSeat.searchParams.set(name, value);
612
- return new Socket(withSeat.toString());
1171
+ return protocols.length > 0 ? new Socket(withSeat.toString(), protocols) : new Socket(withSeat.toString());
613
1172
  }
614
1173
  }
1174
+ /** The page's own reload, where there is a page. */
1175
+ function pageReload() {
1176
+ globalThis.location?.reload?.();
1177
+ }
1178
+ /** Whether a page is being looked at; a runtime with no document always is. */
1179
+ function pageVisible() {
1180
+ const page = globalThis.document;
1181
+ return page?.visibilityState !== "hidden";
1182
+ }
1183
+ /** How long before reconnect attempt `attempt` (FR-49): the host's own, or jittered exponential. */
1184
+ function backoffFor(backoff, attempt) {
1185
+ if (typeof backoff === "function")
1186
+ return Math.max(0, backoff(attempt));
1187
+ const { min = 250, max = 10_000, factor = 2 } = backoff ?? {};
1188
+ return Math.min(max, min * factor ** attempt) * (0.75 + Math.random() * 0.5);
1189
+ }
615
1190
  /**
616
1191
  * A principal as the headers a TRUSTED server reads (`trustSeatHeaders`):
617
1192
  * who, as what, by what name, and for whom. A server that does not trust