@serfab/cadre-client 0.0.0-stage → 2.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.
Files changed (116) hide show
  1. package/ADOPTING.md +228 -0
  2. package/README.md +130 -3
  3. package/dist/address.d.ts +45 -0
  4. package/dist/address.js +109 -0
  5. package/dist/address.js.map +1 -0
  6. package/dist/app-link/index.d.ts +16 -0
  7. package/dist/app-link/index.js +17 -0
  8. package/dist/app-link/index.js.map +1 -0
  9. package/dist/app-link/join-response.d.ts +31 -0
  10. package/dist/app-link/join-response.js +87 -0
  11. package/dist/app-link/join-response.js.map +1 -0
  12. package/dist/app-link/known-apps.d.ts +32 -0
  13. package/dist/app-link/known-apps.js +51 -0
  14. package/dist/app-link/known-apps.js.map +1 -0
  15. package/dist/app-link/link-request-store.d.ts +50 -0
  16. package/dist/app-link/link-request-store.js +101 -0
  17. package/dist/app-link/link-request-store.js.map +1 -0
  18. package/dist/app-link/links.d.ts +47 -0
  19. package/dist/app-link/links.js +76 -0
  20. package/dist/app-link/links.js.map +1 -0
  21. package/dist/app-link/recommend-links.d.ts +30 -0
  22. package/dist/app-link/recommend-links.js +33 -0
  23. package/dist/app-link/recommend-links.js.map +1 -0
  24. package/dist/app-link/recommendation-store.d.ts +54 -0
  25. package/dist/app-link/recommendation-store.js +99 -0
  26. package/dist/app-link/recommendation-store.js.map +1 -0
  27. package/dist/bootstrap.d.ts +106 -0
  28. package/dist/bootstrap.js +106 -0
  29. package/dist/bootstrap.js.map +1 -0
  30. package/dist/inbox.d.ts +10 -0
  31. package/dist/inbox.js +28 -0
  32. package/dist/inbox.js.map +1 -0
  33. package/dist/index.d.ts +15 -0
  34. package/dist/index.js +16 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/invitation-text.d.ts +81 -0
  37. package/dist/invitation-text.js +80 -0
  38. package/dist/invitation-text.js.map +1 -0
  39. package/dist/lifecycle/background-runner.d.ts +94 -0
  40. package/dist/lifecycle/background-runner.js +278 -0
  41. package/dist/lifecycle/background-runner.js.map +1 -0
  42. package/dist/lifecycle/index.d.ts +9 -0
  43. package/dist/lifecycle/index.js +10 -0
  44. package/dist/lifecycle/index.js.map +1 -0
  45. package/dist/loader.d.ts +47 -0
  46. package/dist/loader.js +93 -0
  47. package/dist/loader.js.map +1 -0
  48. package/dist/model.d.ts +309 -0
  49. package/dist/model.js +22 -0
  50. package/dist/model.js.map +1 -0
  51. package/dist/node-code-text.d.ts +10 -0
  52. package/dist/node-code-text.js +30 -0
  53. package/dist/node-code-text.js.map +1 -0
  54. package/dist/result.d.ts +79 -0
  55. package/dist/result.js +84 -0
  56. package/dist/result.js.map +1 -0
  57. package/dist/sereus/client.d.ts +49 -0
  58. package/dist/sereus/client.js +420 -0
  59. package/dist/sereus/client.js.map +1 -0
  60. package/dist/sereus/edge-host.d.ts +22 -0
  61. package/dist/sereus/edge-host.js +61 -0
  62. package/dist/sereus/edge-host.js.map +1 -0
  63. package/dist/sereus/host.d.ts +57 -0
  64. package/dist/sereus/host.js +2 -0
  65. package/dist/sereus/host.js.map +1 -0
  66. package/dist/sereus/index.d.ts +8 -0
  67. package/dist/sereus/index.js +9 -0
  68. package/dist/sereus/index.js.map +1 -0
  69. package/dist/sereus/invitations.d.ts +16 -0
  70. package/dist/sereus/invitations.js +333 -0
  71. package/dist/sereus/invitations.js.map +1 -0
  72. package/dist/sereus/node-code.d.ts +52 -0
  73. package/dist/sereus/node-code.js +51 -0
  74. package/dist/sereus/node-code.js.map +1 -0
  75. package/dist/store.d.ts +27 -0
  76. package/dist/store.js +51 -0
  77. package/dist/store.js.map +1 -0
  78. package/dist/stores.d.ts +38 -0
  79. package/dist/stores.js +48 -0
  80. package/dist/stores.js.map +1 -0
  81. package/examples/README.md +20 -0
  82. package/examples/nativescript/cadrons-page.xml +24 -0
  83. package/examples/nativescript/cadrons-view-model.ts +68 -0
  84. package/examples/react-native/CadronList.tsx +204 -0
  85. package/examples/react-native/InvitationPanel.tsx +191 -0
  86. package/examples/react-native/useStore.ts +11 -0
  87. package/examples/svelte/CadronList.svelte +86 -0
  88. package/examples/svelte/InvitationPanel.svelte +97 -0
  89. package/package.json +65 -3
  90. package/src/address.ts +125 -0
  91. package/src/app-link/index.ts +45 -0
  92. package/src/app-link/join-response.ts +109 -0
  93. package/src/app-link/known-apps.ts +70 -0
  94. package/src/app-link/link-request-store.ts +129 -0
  95. package/src/app-link/links.ts +90 -0
  96. package/src/app-link/recommend-links.ts +49 -0
  97. package/src/app-link/recommendation-store.ts +132 -0
  98. package/src/bootstrap.ts +184 -0
  99. package/src/globals.d.ts +26 -0
  100. package/src/inbox.ts +36 -0
  101. package/src/index.ts +15 -0
  102. package/src/invitation-text.ts +156 -0
  103. package/src/lifecycle/background-runner.ts +363 -0
  104. package/src/lifecycle/index.ts +17 -0
  105. package/src/loader.ts +103 -0
  106. package/src/model.ts +327 -0
  107. package/src/node-code-text.ts +25 -0
  108. package/src/result.ts +131 -0
  109. package/src/sereus/client.ts +454 -0
  110. package/src/sereus/edge-host.ts +81 -0
  111. package/src/sereus/host.ts +56 -0
  112. package/src/sereus/index.ts +8 -0
  113. package/src/sereus/invitations.ts +359 -0
  114. package/src/sereus/node-code.ts +80 -0
  115. package/src/store.ts +61 -0
  116. package/src/stores.ts +62 -0
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Invitations over a running node: which addresses one names (`bootstrap.ts` plans, this
3
+ * gathers the evidence), whether it is ready to hand out, and what it says in words.
4
+ *
5
+ * The evidence for each cadron (each other machine of the party), best first:
6
+ * - `connection`: a connection this device opened to it with no relay hop is open now;
7
+ * - `record`: its signed, recently published record (`resolvePeerAddrs`), every address;
8
+ * - `claim`: what this device was handed when it claimed it (cadre-core's bootstrap peer store),
9
+ * which is all there is in the minute before the cadron's first record arrives. cadre-core's
10
+ * own invitation leaves such a cadron out altogether.
11
+ *
12
+ * READINESS comes from cadre-core's probe of the machines an invitation names
13
+ * (`CadreNode.readInvitationReadiness`), which asks each of them whether it could answer a
14
+ * redemption of that invitation right now. Nothing here infers it from replication: this module
15
+ * keeps the probe's answer per token, asks again on cadre-core's ladder while the answer is
16
+ * still `waiting`, and reports which of the five things the machines said they are missing.
17
+ */
18
+ import { multiaddr } from '@multiformats/multiaddr';
19
+ import { nextFormationReadyPoll, type CadreNode, type FormationReadinessGap, type FormationReadinessReport, type MachineFormationReadiness } from '@serfab/cadre-core';
20
+ import { CADRON_PREFERENCES_FORMAT, normalizePreferences, planBootstrap, type CadronCandidate, type CadronPreferences } from '../bootstrap.js';
21
+ import { describeInvitation, destinationPeerId } from '../invitation-text.js';
22
+ import type { CadreMachine, InvitationReadiness, InvitationsModel } from '../model.js';
23
+ import { cadreAttempt, CadreFailure, describeThrown, withTimeout } from '../result.js';
24
+ import type { CadreHost } from './host.js';
25
+
26
+ /** `addr` ending in `/p2p/<peerId>` (a claim's or a connection's address may not); unchanged when it does not parse. */
27
+ function withPeer(addr: string, peerId: string): string {
28
+ try {
29
+ const ma = multiaddr(addr);
30
+ return ma.getComponents().at(-1)?.value === peerId ? ma.toString() : ma.encapsulate(`/p2p/${peerId}`).toString();
31
+ } catch {
32
+ return addr;
33
+ }
34
+ }
35
+
36
+ /** The answer before a probe has landed, and when there is no node to probe with. */
37
+ const NOT_YET: InvitationReadiness = { state: 'waiting', missing: [] };
38
+
39
+ /** Each gap the OTHER machines reported, once, in the order they reported it. */
40
+ function missingAcross(machines: readonly MachineFormationReadiness[]): FormationReadinessGap[] {
41
+ const gaps = new Set<FormationReadinessGap>();
42
+ for (const machine of machines) {
43
+ if (!machine.self) for (const gap of machine.gaps) gaps.add(gap);
44
+ }
45
+ return [...gaps];
46
+ }
47
+
48
+ /**
49
+ * cadre-core's per-machine report as one answer about the invitation.
50
+ *
51
+ * `spent` is read first: a machine holding the invitation's record and reading it dead settles
52
+ * the question, and a gap another machine reports cannot change that. `no-cadron` is the
53
+ * invitation naming no machine but this one, which is settled too — the machines probed are the
54
+ * ones its bootstrap list names, and that list cannot grow after minting.
55
+ */
56
+ function readinessOf(report: FormationReadinessReport): InvitationReadiness {
57
+ if (report.machines.some(m => m.outcome === 'spent')) return { state: 'spent', missing: [] };
58
+ if (report.answerable) return { state: 'ready', missing: [] };
59
+ if (!report.machines.some(m => !m.self)) return { state: 'no-cadron', missing: [] };
60
+ return { state: 'waiting', missing: missingAcross(report.machines) };
61
+ }
62
+
63
+ /** Two answers a screen would render identically, so the change signal can stay quiet. */
64
+ function sameReadiness(a: InvitationReadiness | null, b: InvitationReadiness): boolean {
65
+ return a !== null && a.state === b.state && a.missing.length === b.missing.length
66
+ && a.missing.every((gap, i) => gap === b.missing[i]);
67
+ }
68
+
69
+ /** One token's readiness: the last answer, and where its re-ask ladder stands. */
70
+ interface ReadinessProbe {
71
+ /** What the last probe answered; null until the first one lands. */
72
+ answer: InvitationReadiness | null;
73
+ /** Probes taken, which sets the ladder's next gap (`nextFormationReadyPoll`). */
74
+ asks: number;
75
+ /** A probe is in flight. */
76
+ asking: boolean;
77
+ /** The ladder's next ask, scheduled; null when none is. */
78
+ timer: ReturnType<typeof setTimeout> | null;
79
+ /** When the last probe landed (epoch ms); 0 before the first. */
80
+ at: number;
81
+ }
82
+
83
+ export interface InvitationsDeps {
84
+ host: CadreHost;
85
+ /** The person's cadron list, as the cadre screen has it; empty when it cannot be read. */
86
+ machines(): Promise<CadreMachine[]>;
87
+ controlReadMs: number;
88
+ log: { info(...args: unknown[]): void; warn(...args: unknown[]): void };
89
+ }
90
+
91
+ export function createInvitations({ host, machines, controlReadMs, log }: InvitationsDeps): {
92
+ invitations: InvitationsModel;
93
+ onChange(listener: () => void): () => void;
94
+ } {
95
+ const listeners = new Set<() => void>();
96
+ const changed = () => { for (const l of [...listeners]) l(); };
97
+
98
+ // Preferences: per device, in the host's slot. Without one, kept in memory for the session.
99
+ let prefs: CadronPreferences | null = null;
100
+ // One first read, however many callers ask at once.
101
+ let loading: Promise<CadronPreferences> | null = null;
102
+ function loadPrefs(): Promise<CadronPreferences> {
103
+ if (prefs) return Promise.resolve(prefs);
104
+ loading ??= (async () => {
105
+ let raw: Partial<CadronPreferences> | null = null;
106
+ try {
107
+ const text = await host.preferences?.load();
108
+ raw = text ? JSON.parse(text) as Partial<CadronPreferences> : null;
109
+ } catch (err) {
110
+ log.warn('[cadre-client] cadron preferences unreadable; using defaults:', describeThrown(err));
111
+ }
112
+ prefs ??= normalizePreferences(raw);
113
+ return prefs;
114
+ })();
115
+ return loading;
116
+ }
117
+ // Writes one after another: each merges into the result of the one before, so two changes made
118
+ // in quick succession (two stars) both stay.
119
+ let writing: Promise<unknown> = Promise.resolve();
120
+
121
+ // Readiness per encoded invitation: what cadre-core's probe last answered, read in the
122
+ // background and cached. Per token, because half of what it answers is whether that
123
+ // invitation's own record has reached the machine that would answer a join through it.
124
+ // NOTE: one ladder per token, and nothing coalesces two tokens of the same party — each costs
125
+ // one small control request per machine the invitation names, at most four a minute once the
126
+ // ladder tops out. Fine for an invitation screen, which shows one. If an app ever shows a list
127
+ // of pending invitations, share one ladder across them.
128
+ // NOTE: an entry is never evicted, so a session holds one small object per token it has read.
129
+ // A token is only ever re-minted by `rebootstrap`, so that is one per address the person
130
+ // toggled. If an app ever reads readiness for tokens it mints in a loop, evict by last read.
131
+ const probes = new Map<string, ReadinessProbe>();
132
+ /** `waiting` is the only answer a further probe can change. */
133
+ const settled = (probe: ReadinessProbe) => probe.answer !== null && probe.answer.state !== 'waiting';
134
+
135
+ /**
136
+ * cadre-core's probe for an encoded invitation, as a promise even for a token that will not decode.
137
+ *
138
+ * NOTE: no `withTimeout` here, unlike the control reads below. cadre-core bounds each dial it
139
+ * makes, and a probe that outran a bound of ours would still be in flight behind it; the one
140
+ * unbounded leg is its read of this machine's own control database. A probe that never settles
141
+ * leaves the token reading `waiting` with its ladder stopped. Bound it here if that is ever seen.
142
+ */
143
+ async function askReadiness(node: CadreNode, token: string): Promise<FormationReadinessReport> {
144
+ return await node.readInvitationReadiness(node.decodeInvitation(token));
145
+ }
146
+
147
+ /** The cached probe for `token`, carrying its ladder on before the answer is read. */
148
+ function probeFor(node: CadreNode, token: string): ReadinessProbe {
149
+ const probe = probes.get(token) ?? { answer: null, asks: 0, asking: false, timer: null, at: 0 };
150
+ probes.set(token, probe);
151
+ ladder(node, token, probe);
152
+ return probe;
153
+ }
154
+
155
+ /**
156
+ * Ask again while the answer is still `waiting`, each ask no sooner than cadre-core's own
157
+ * ladder allows (`nextFormationReadyPoll`: two seconds doubling to fifteen) — the one cadence
158
+ * there is, so the client adds none of its own. An ask the ladder allows now is made at once,
159
+ * which is what answers the first read for a token. A later one is scheduled only while
160
+ * something is watching, because an answer nothing listens for has nowhere to go; the next
161
+ * read, or the next listener, picks the ladder up where it stopped.
162
+ */
163
+ function ladder(node: CadreNode, token: string, probe: ReadinessProbe): void {
164
+ if (probe.asking || probe.timer !== null || settled(probe)) return;
165
+ const waitMs = Math.max(0, probe.at + nextFormationReadyPoll(probe.asks) - Date.now());
166
+ if (waitMs === 0) {
167
+ ask(node, token, probe);
168
+ return;
169
+ }
170
+ if (listeners.size === 0) return;
171
+ probe.timer = setTimeout(() => {
172
+ probe.timer = null;
173
+ if (probes.get(token) === probe && listeners.size > 0) ladder(node, token, probe);
174
+ }, waitMs);
175
+ }
176
+
177
+ /** Cancel a scheduled re-ask, so no timer outlives what wanted its answer. */
178
+ function unschedule(probe: ReadinessProbe): void {
179
+ if (probe.timer === null) return;
180
+ clearTimeout(probe.timer);
181
+ probe.timer = null;
182
+ }
183
+
184
+ function ask(node: CadreNode, token: string, probe: ReadinessProbe): void {
185
+ probe.asking = true;
186
+ void askReadiness(node, token).then(
187
+ report => keep(node, token, probe, readinessOf(report)),
188
+ err => {
189
+ // A failed read forgets its entry: the next read asks again, and a failure is never
190
+ // reported as an answer. Never log the token itself.
191
+ // NOTE: forgetting also drops the ladder's backoff, so a probe that keeps throwing is
192
+ // re-asked — and warns — once per read rather than on a climbing gap. Reads are driven
193
+ // by the change signal, so that is bounded in practice. If a persistent failure ever
194
+ // shows up as a run of warnings, keep the entry and carry `asks` on instead of deleting.
195
+ if (probes.get(token) === probe) probes.delete(token);
196
+ log.warn('[cadre-client] an invitation\'s readiness could not be read:', describeThrown(err));
197
+ },
198
+ );
199
+ }
200
+
201
+ /**
202
+ * Keep what a probe answered, and tell the app only when it differs from the answer before:
203
+ * the ladder asks every couple of seconds while a machine is still catching up, and a screen
204
+ * has nothing to re-render for an unchanged answer.
205
+ */
206
+ function keep(node: CadreNode, token: string, probe: ReadinessProbe, answer: InvitationReadiness): void {
207
+ if (probes.get(token) !== probe) return; // forgotten while the probe was in flight
208
+ const differs = !sameReadiness(probe.answer, answer);
209
+ probe.asking = false;
210
+ probe.asks += 1;
211
+ probe.at = Date.now();
212
+ if (differs) {
213
+ probe.answer = answer;
214
+ changed();
215
+ }
216
+ ladder(node, token, probe);
217
+ }
218
+
219
+ /** Something is watching again: carry on every ladder that stopped for want of a listener. */
220
+ function resumeLadders(): void {
221
+ const node = host.node.node;
222
+ if (!node) return;
223
+ for (const [token, probe] of probes) ladder(node, token, probe);
224
+ }
225
+
226
+ /** Put every token still waiting back at the foot of the ladder, so the next read asks at once. */
227
+ function restartLadders(): void {
228
+ for (const probe of probes.values()) {
229
+ if (settled(probe)) continue;
230
+ unschedule(probe);
231
+ probe.asks = 0;
232
+ probe.at = 0;
233
+ }
234
+ }
235
+
236
+ // A cadron coming or going may make a machine an invitation names reachable for the probe: ask
237
+ // again at once for the tokens still waiting. A settled answer is KEPT, where the serving counts
238
+ // this replaced were cleared wholesale: `ready` would otherwise read `waiting` again until the
239
+ // re-probe landed, so a screen already telling the person they may close the app would take it
240
+ // back for a second or two. Nor can a connection change the other two — `spent` is permanent,
241
+ // and `no-cadron` is the invitation's own bootstrap list, which does not grow after minting.
242
+ host.node.on('control:connected', () => { restartLadders(); changed(); });
243
+
244
+ async function candidates(node: CadreNode): Promise<CadronCandidate[]> {
245
+ const machines = await withTimeout(node.listMachines(), controlReadMs, 'listMachines').catch(() => []);
246
+ const claimed = node.getBootstrapPeerStore()?.all() ?? new Map<string, { addrs: string[] }>();
247
+ const connections = node.getControlNode()?.getConnections() ?? [];
248
+ const others = machines.filter(m => !m.isSelf && m.trusted);
249
+ return Promise.all(others.map(async (m): Promise<CadronCandidate> => {
250
+ const addrs: CadronCandidate['addrs'][number][] = [];
251
+ const record = await withTimeout(node.resolvePeerAddrs(m.peerId), controlReadMs, 'resolvePeerAddrs').catch(() => []);
252
+ for (const a of record) addrs.push({ addr: withPeer(a.toString(), m.peerId), source: 'record' });
253
+ // WORKAROUND(sereus: name a just-claimed machine): until its first record arrives, what its
254
+ // node code carried. cadre-core's own invitation leaves such a machine out.
255
+ for (const a of claimed.get(m.peerId)?.addrs ?? []) addrs.push({ addr: withPeer(a, m.peerId), source: 'claim' });
256
+ for (const c of connections) {
257
+ const remote = c.remoteAddr.toString();
258
+ if (c.remotePeer.toString() !== m.peerId || c.direction !== 'outbound' || c.limits !== undefined || remote.includes('/p2p-circuit')) continue;
259
+ addrs.push({ addr: withPeer(remote, m.peerId), source: 'connection' });
260
+ }
261
+ return { peerId: m.peerId, alwaysOn: m.alwaysOn === true, lastPublishedAt: m.lastPublishedAt, addrs };
262
+ }));
263
+ }
264
+
265
+ const requireNode = (): CadreNode => {
266
+ const node = host.node.node;
267
+ if (!node) throw new CadreFailure('unavailable', 'The cadre node is not running yet.');
268
+ return node;
269
+ };
270
+
271
+ async function plan() {
272
+ const node = requireNode();
273
+ return planBootstrap({
274
+ cadrons: await candidates(node),
275
+ thisDevice: { peerId: node.peerId?.toString() ?? '', addrs: node.getMultiaddrs().map(a => a.toString()) },
276
+ prefs: await loadPrefs(),
277
+ });
278
+ }
279
+
280
+ const invitations: InvitationsModel = {
281
+ preferences: loadPrefs,
282
+
283
+ setPreferences: changes => {
284
+ const write = writing.then(() => cadreAttempt(async () => {
285
+ const next = normalizePreferences({ ...(await loadPrefs()), ...changes });
286
+ if (host.preferences) await host.preferences.save(JSON.stringify({ format: CADRON_PREFERENCES_FORMAT, ...next }));
287
+ prefs = next;
288
+ changed();
289
+ return next;
290
+ }));
291
+ writing = write;
292
+ return write;
293
+ },
294
+
295
+ bootstrapPlan: () => cadreAttempt(plan),
296
+
297
+ // WORKAROUND(sereus: an option on `createOpenInvitation`): the list is replaced after minting,
298
+ // before the app encodes it. It is not signed; the responder checks only the token.
299
+ async withBootstrap(invitation) {
300
+ try {
301
+ const { entries, warnings } = await plan();
302
+ if (entries.length === 0) return invitation;
303
+ if (warnings.length) log.info('[cadre-client] invitation bootstrap:', warnings.join(', '));
304
+ return { ...invitation, bootstrap: entries.map(e => e.addr) };
305
+ } catch (err) {
306
+ log.warn('[cadre-client] kept cadre-core\'s bootstrap list:', err instanceof Error ? err.message : err);
307
+ return invitation;
308
+ }
309
+ },
310
+
311
+ readiness(token): InvitationReadiness {
312
+ const node = host.node.node;
313
+ // NOTE: with no node the question is dropped rather than remembered, so a store built
314
+ // while the node is stopped reads `waiting` until something else fires the change signal.
315
+ // Harmless as apps use it — a token exists only because a running node minted it. If an
316
+ // app ever reads readiness for a token it kept across a restart, queue the token here.
317
+ if (!node) return NOT_YET;
318
+ return probeFor(node, token).answer ?? NOT_YET;
319
+ },
320
+
321
+ describe: (token, link) => cadreAttempt(async () => {
322
+ const node = requireNode();
323
+ const decoded = node.decodeInvitation(token);
324
+ const [{ names, maxAddrs }, list, now] = await Promise.all([
325
+ loadPrefs(),
326
+ machines(),
327
+ plan().catch(() => ({ entries: [], others: [] })),
328
+ ]);
329
+ return describeInvitation(decoded, {
330
+ link: link ?? token, names, thisDevicePeerId: node.peerId?.toString() ?? null,
331
+ machines: list, others: [...now.entries, ...now.others].map(e => e.addr), maxAddrs,
332
+ });
333
+ }),
334
+
335
+ // WORKAROUND(sereus: an option on `createOpenInvitation`), as `withBootstrap`.
336
+ rebootstrap: (token, addrs) => cadreAttempt(async () => {
337
+ const node = requireNode();
338
+ if (addrs.length === 0) throw new CadreFailure('invalid-address', 'An invitation must name at least one address.');
339
+ if (addrs.some(a => !destinationPeerId(a))) throw new CadreFailure('invalid-address', 'An address does not end in the peer it reaches.');
340
+ return node.encodeInvitation({ ...node.decodeInvitation(token), bootstrap: [...new Set(addrs)] });
341
+ }),
342
+ };
343
+
344
+ return {
345
+ invitations,
346
+ onChange(listener) {
347
+ listeners.add(listener);
348
+ if (listeners.size === 1) resumeLadders();
349
+ return () => {
350
+ listeners.delete(listener);
351
+ // Nothing is watching: stop the ladders here rather than leave timers to fire into an
352
+ // empty listener set — under Node one would hold the process open for up to fifteen
353
+ // seconds. The next read, or the next listener, picks each one up where it stopped.
354
+ if (listeners.size === 0) for (const probe of probes.values()) unschedule(probe);
355
+ };
356
+ },
357
+ };
358
+ }
359
+
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Node codes: the `sereus-join:1.…` text a cadre node shows (as a QR code, a link or plain
3
+ * text) while it waits to be claimed, and how to read one and sort a claim's failure.
4
+ *
5
+ * Descends from reference-app-rn's `src/node-claim.ts`; this one returns codes rather than
6
+ * English, so each app words them in its own catalog.
7
+ *
8
+ * SECURITY: a code carries the node's one-time claim secret. Never log the code text, a
9
+ * link containing one, or a decoded payload — log the peer id only.
10
+ */
11
+ import {
12
+ ClaimRefusedError,
13
+ NODE_CLAIM_PAYLOAD_PREFIX,
14
+ PeerUnreachableError,
15
+ decodeNodeClaimPayload,
16
+ describeThrown,
17
+ type NodeClaimPayload,
18
+ } from '@serfab/cadre-core';
19
+ import type { NodeReach } from '../model.js';
20
+ import { NODE_CODE_SCHEME, nodeCodeFromUrl } from '../node-code-text.js';
21
+ import { nodeReach } from '../address.js';
22
+
23
+ /** A code with a version this build does not read: `sereus-join:<n>.` with n ≠ 1. */
24
+ const VERSIONED_NODE_CODE = /^sereus-join:(\d+)\./;
25
+
26
+ export type NodeCodeProblem =
27
+ /** Does not start with `sereus-join:` — some other QR, link or text. */
28
+ | 'not-node-code'
29
+ /** A node code from a newer node than this build reads: the app needs updating. */
30
+ | 'newer-version'
31
+ /** Right prefix, but cut short or corrupted. */
32
+ | 'damaged';
33
+
34
+ export type NodeCodeReading =
35
+ | { ok: true; payload: NodeClaimPayload }
36
+ | { ok: false; problem: NodeCodeProblem; /** The decoder's words (never the secret), for logs. */ detail?: string };
37
+
38
+ /** Decode scanned or pasted text, or say which problem it has. */
39
+ export function readNodeCode(text: string): NodeCodeReading {
40
+ const trimmed = (nodeCodeFromUrl(text) ?? text).trim();
41
+ if (!trimmed.startsWith(NODE_CODE_SCHEME)) return { ok: false, problem: 'not-node-code' };
42
+ if (!trimmed.startsWith(NODE_CLAIM_PAYLOAD_PREFIX) && VERSIONED_NODE_CODE.test(trimmed)) {
43
+ return { ok: false, problem: 'newer-version' };
44
+ }
45
+ try {
46
+ return { ok: true, payload: decodeNodeClaimPayload(trimmed) };
47
+ } catch (err) {
48
+ // The decoder never echoes the secret, so its message is safe to keep.
49
+ return { ok: false, problem: 'damaged', detail: describeThrown(err) };
50
+ }
51
+ }
52
+
53
+ /** Refusals after which the same code can still succeed. */
54
+ const RETRYABLE_REFUSALS: ReadonlySet<string> = new Set(['claim-rate-limited', 'claim-not-persisted']);
55
+
56
+ export type ClaimFailure =
57
+ /** No connection formed from any address; nothing was sent. */
58
+ | { kind: 'node-unreachable'; reach: NodeReach; retryable: true; detail: string }
59
+ /** The node answered and said no. `refusal` is absent when it gave no (known) code. */
60
+ | { kind: 'claim-refused'; refusal?: string; retryable: boolean; detail: string }
61
+ /** Reached, then the exchange or a local step failed. Repeating with the same code is safe. */
62
+ | { kind: 'claim-failed'; retryable: true; detail: string };
63
+
64
+ /** Sort an error thrown by `CadreNode.claimNode(payload)` into what to say and whether to keep the code. */
65
+ export function classifyClaimFailure(error: unknown, payload: NodeClaimPayload): ClaimFailure {
66
+ const detail = describeThrown(error);
67
+ if (error instanceof PeerUnreachableError) {
68
+ return { kind: 'node-unreachable', reach: nodeReach(payload.multiaddrs), retryable: true, detail };
69
+ }
70
+ if (error instanceof ClaimRefusedError) {
71
+ const refusal = error.code;
72
+ return {
73
+ kind: 'claim-refused',
74
+ refusal,
75
+ retryable: refusal !== undefined && RETRYABLE_REFUSALS.has(refusal),
76
+ detail: error.reason ?? detail,
77
+ };
78
+ }
79
+ return { kind: 'claim-failed', retryable: true, detail };
80
+ }
package/src/store.ts ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The store primitive cadre screens bind to: the Svelte store contract — `subscribe(fn)`
3
+ * calls `fn` at once with the current value and returns an unsubscribe function — plus
4
+ * `get()`, with two rules:
5
+ *
6
+ * - `get()` returns the same object until the value changes. React's
7
+ * `useSyncExternalStore` re-renders whenever the snapshot is a new object, so a store
8
+ * that rebuilt its value on every read would loop.
9
+ * - Reference-counted: `start` runs when the first subscriber arrives and the function it
10
+ * returns runs when the last one leaves, so a store costs nothing while nothing shows it.
11
+ *
12
+ * Binding: Svelte uses a store directly (`$store`); React through
13
+ * `useSyncExternalStore(store.subscribe, store.get)`; NativeScript by copying each value
14
+ * into an `Observable` from `subscribe`. Self-contained on purpose, so the package
15
+ * depends on nothing but cadre-core; an app with its own store type of the same contract
16
+ * binds these the same way.
17
+ */
18
+
19
+ export interface Readable<T> {
20
+ subscribe(run: (value: T) => void): () => void;
21
+ get(): T;
22
+ }
23
+
24
+ export interface Writable<T> extends Readable<T> {
25
+ set(value: T): void;
26
+ update(fn: (value: T) => T): void;
27
+ }
28
+
29
+ export type StartStop<T> = (set: (value: T) => void, update: (fn: (value: T) => T) => void) => void | (() => void);
30
+
31
+ export function writable<T>(initial: T, start?: StartStop<T>): Writable<T> {
32
+ let value = initial;
33
+ let stop: (() => void) | void = undefined;
34
+ const subscribers = new Set<(value: T) => void>();
35
+
36
+ const set = (next: T) => {
37
+ if (Object.is(next, value)) return;
38
+ value = next;
39
+ for (const run of [...subscribers]) run(value);
40
+ };
41
+ const update = (fn: (value: T) => T) => set(fn(value));
42
+
43
+ return {
44
+ get: () => value,
45
+ set,
46
+ update,
47
+ subscribe(run) {
48
+ subscribers.add(run);
49
+ if (subscribers.size === 1 && start) stop = start(set, update);
50
+ run(value);
51
+ return () => {
52
+ if (!subscribers.delete(run)) return;
53
+ if (subscribers.size === 0 && stop) {
54
+ const halt = stop;
55
+ stop = undefined;
56
+ halt();
57
+ }
58
+ };
59
+ },
60
+ };
61
+ }
package/src/stores.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The stores a cadre screen binds to. Each reads through a view (`CadreView`,
3
+ * `ReachabilityView`), so it works over the Sereus client, an app's mock, or an app's
4
+ * whole model when that has the same two members.
5
+ */
6
+ import type { CadreStatus, CadreView, InvitationReadiness, InvitationsView, Reachability, ReachabilityView } from './model.js';
7
+ import { writable, type Readable } from './store.js';
8
+ import { cadreOk } from './result.js';
9
+ import { loader, type Loader } from './loader.js';
10
+
11
+ /** How often a store re-reads with nothing announcing a change, while subscribed. */
12
+ export interface StoreOptions {
13
+ /** Milliseconds; 0 turns the poll off. Default 30 s. */
14
+ pollMs?: number;
15
+ }
16
+
17
+ /**
18
+ * The cadre: this device, its cadrons, and whether it is an enrolled owner. Re-read on every
19
+ * change that has an event: this node starting or stopping, a cadron connecting or dropping, the
20
+ * cadron preferences. The poll catches what has none: a cadron added or removed on another
21
+ * device (it arrives by control replication), and a cadron's `lastSeenAt` ageing, so its
22
+ * presence turns from recent to quiet. A store kept subscribed app-wide (a status badge) can poll
23
+ * less often, or not at all if those can wait for the next screen.
24
+ */
25
+ export function cadreStore(view: CadreView, opts: StoreOptions = {}): Loader<CadreStatus> {
26
+ return loader({
27
+ load: () => view.cadre.status(),
28
+ changes: onChange => view.changes.cadre(onChange),
29
+ pollMs: opts.pollMs ?? 30_000,
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Reachability: can anybody answer an invitation from this device, which relays it is
35
+ * configured with, and whether the relay reservation holds — read live, because a
36
+ * configured relay is not a working one and a reservation can be lost after it was
37
+ * granted. Re-read when this device's addresses change; a slow backstop poll covers a
38
+ * change no event announces (a machine of the party's coming up or going quiet).
39
+ */
40
+ export function reachabilityStore(view: ReachabilityView, opts: StoreOptions = {}): Loader<Reachability> {
41
+ return loader({
42
+ load: async () => cadreOk(await view.reachability.get()),
43
+ changes: onChange => view.changes.reachability(onChange),
44
+ debounceMs: 250,
45
+ pollMs: opts.pollMs ?? 30_000,
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Whether the invitation `token` is ready to hand out (`InvitationReadiness`), live: it turns
51
+ * `ready` once one of the machines the invitation names can answer a join through it, and until
52
+ * then says what those machines are missing. The answer comes from cadre-core's probe of those
53
+ * machines, which the model asks in the background and asks again on its own ladder while the
54
+ * answer is still `waiting`; this store re-reads each time one lands.
55
+ */
56
+ export function invitationReadinessStore(view: InvitationsView, token: string): Readable<InvitationReadiness> {
57
+ const read = () => view.invitations.readiness(token);
58
+ return writable<InvitationReadiness>(read(), set => {
59
+ set(read());
60
+ return view.changes.invitations(() => set(read()));
61
+ });
62
+ }