@serfab/cadre-client 0.0.0-stage → 2.0.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 +220 -0
  2. package/README.md +129 -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 +284 -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 +196 -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 +37 -0
  79. package/dist/stores.js +45 -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 +162 -0
  86. package/examples/react-native/useStore.ts +11 -0
  87. package/examples/svelte/CadronList.svelte +86 -0
  88. package/examples/svelte/InvitationPanel.svelte +79 -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 +299 -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 +206 -0
  114. package/src/sereus/node-code.ts +80 -0
  115. package/src/store.ts +61 -0
  116. package/src/stores.ts +59 -0
@@ -0,0 +1,16 @@
1
+ import type { CadreMachine, InvitationsModel } from '../model.js';
2
+ import type { CadreHost } from './host.js';
3
+ export interface InvitationsDeps {
4
+ host: CadreHost;
5
+ /** The person's cadron list, as the cadre screen has it; empty when it cannot be read. */
6
+ machines(): Promise<CadreMachine[]>;
7
+ controlReadMs: number;
8
+ log: {
9
+ info(...args: unknown[]): void;
10
+ warn(...args: unknown[]): void;
11
+ };
12
+ }
13
+ export declare function createInvitations({ host, machines, controlReadMs, log }: InvitationsDeps): {
14
+ invitations: InvitationsModel;
15
+ onChange(listener: () => void): () => void;
16
+ };
@@ -0,0 +1,196 @@
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. A new strand's copy is on a cadron once a commit of the strand is held elsewhere
13
+ * (`strand:commit-held`, or a commit reported `heldElsewhere`). The cadron may still be starting
14
+ * then, but it holds the strand's data and finishes starting on its own. Its `StrandPeer` row is
15
+ * not enough: it is written before the cadron's copy is live, and a join answered by a cadron
16
+ * whose copy is not live is refused `host-strand-unavailable`.
17
+ * WORKAROUND(sereus: a readiness signal for an invitation): read from commit durability.
18
+ */
19
+ import { multiaddr } from '@multiformats/multiaddr';
20
+ import { CADRON_PREFERENCES_FORMAT, normalizePreferences, planBootstrap } from '../bootstrap.js';
21
+ import { describeInvitation, destinationPeerId } from '../invitation-text.js';
22
+ import { cadreAttempt, CadreFailure, describeThrown, withTimeout } from '../result.js';
23
+ /** `addr` ending in `/p2p/<peerId>` (a claim's or a connection's address may not); unchanged when it does not parse. */
24
+ function withPeer(addr, peerId) {
25
+ try {
26
+ const ma = multiaddr(addr);
27
+ return ma.getComponents().at(-1)?.value === peerId ? ma.toString() : ma.encapsulate(`/p2p/${peerId}`).toString();
28
+ }
29
+ catch {
30
+ return addr;
31
+ }
32
+ }
33
+ export function createInvitations({ host, machines, controlReadMs, log }) {
34
+ const listeners = new Set();
35
+ const changed = () => { for (const l of [...listeners])
36
+ l(); };
37
+ // Preferences: per device, in the host's slot. Without one, kept in memory for the session.
38
+ let prefs = null;
39
+ // One first read, however many callers ask at once.
40
+ let loading = null;
41
+ function loadPrefs() {
42
+ if (prefs)
43
+ return Promise.resolve(prefs);
44
+ loading ??= (async () => {
45
+ let raw = null;
46
+ try {
47
+ const text = await host.preferences?.load();
48
+ raw = text ? JSON.parse(text) : null;
49
+ }
50
+ catch (err) {
51
+ log.warn('[cadre-client] cadron preferences unreadable; using defaults:', describeThrown(err));
52
+ }
53
+ prefs ??= normalizePreferences(raw);
54
+ return prefs;
55
+ })();
56
+ return loading;
57
+ }
58
+ // Writes one after another: each merges into the result of the one before, so two changes made
59
+ // in quick succession (two stars) both stay.
60
+ let writing = Promise.resolve();
61
+ // Strands with a commit held elsewhere this session.
62
+ const held = new Set();
63
+ const markHeld = (strandId) => {
64
+ if (held.has(strandId))
65
+ return;
66
+ held.add(strandId);
67
+ changed();
68
+ };
69
+ host.node.on('strand:commit-durability', d => { if (d.heldElsewhere)
70
+ markHeld(d.strandId); });
71
+ host.node.on('strand:commit-held', d => markHeld(d.strandId));
72
+ // Established strands: how many other cadrons serve each (their `StrandPeer` rows), read in
73
+ // the background and cached; null while unknown.
74
+ const serving = new Map();
75
+ function servingOthers(node, strandId) {
76
+ if (!serving.has(strandId)) {
77
+ serving.set(strandId, null);
78
+ const self = node.peerId?.toString();
79
+ void withTimeout(node.getControlDatabase()?.queryStrandPeers(strandId) ?? Promise.resolve([]), controlReadMs, 'queryStrandPeers')
80
+ .then(rows => { serving.set(strandId, rows.filter(r => r.peerId !== self && r.role === null).length); changed(); })
81
+ .catch(() => { serving.delete(strandId); });
82
+ }
83
+ return serving.get(strandId) ?? null;
84
+ }
85
+ // A cadron coming or going changes who serves: forget the cached counts.
86
+ host.node.on('control:connected', () => { serving.clear(); changed(); });
87
+ async function candidates(node) {
88
+ const machines = await withTimeout(node.listMachines(), controlReadMs, 'listMachines').catch(() => []);
89
+ const claimed = node.getBootstrapPeerStore()?.all() ?? new Map();
90
+ const connections = node.getControlNode()?.getConnections() ?? [];
91
+ const others = machines.filter(m => !m.isSelf && m.trusted);
92
+ return Promise.all(others.map(async (m) => {
93
+ const addrs = [];
94
+ const record = await withTimeout(node.resolvePeerAddrs(m.peerId), controlReadMs, 'resolvePeerAddrs').catch(() => []);
95
+ for (const a of record)
96
+ addrs.push({ addr: withPeer(a.toString(), m.peerId), source: 'record' });
97
+ // WORKAROUND(sereus: name a just-claimed machine): until its first record arrives, what its
98
+ // node code carried. cadre-core's own invitation leaves such a machine out.
99
+ for (const a of claimed.get(m.peerId)?.addrs ?? [])
100
+ addrs.push({ addr: withPeer(a, m.peerId), source: 'claim' });
101
+ for (const c of connections) {
102
+ const remote = c.remoteAddr.toString();
103
+ if (c.remotePeer.toString() !== m.peerId || c.direction !== 'outbound' || c.limits !== undefined || remote.includes('/p2p-circuit'))
104
+ continue;
105
+ addrs.push({ addr: withPeer(remote, m.peerId), source: 'connection' });
106
+ }
107
+ return { peerId: m.peerId, alwaysOn: m.alwaysOn === true, lastPublishedAt: m.lastPublishedAt, addrs };
108
+ }));
109
+ }
110
+ const requireNode = () => {
111
+ const node = host.node.node;
112
+ if (!node)
113
+ throw new CadreFailure('unavailable', 'The cadre node is not running yet.');
114
+ return node;
115
+ };
116
+ async function plan() {
117
+ const node = requireNode();
118
+ return planBootstrap({
119
+ cadrons: await candidates(node),
120
+ thisDevice: { peerId: node.peerId?.toString() ?? '', addrs: node.getMultiaddrs().map(a => a.toString()) },
121
+ prefs: await loadPrefs(),
122
+ });
123
+ }
124
+ const invitations = {
125
+ preferences: loadPrefs,
126
+ setPreferences: changes => {
127
+ const write = writing.then(() => cadreAttempt(async () => {
128
+ const next = normalizePreferences({ ...(await loadPrefs()), ...changes });
129
+ if (host.preferences)
130
+ await host.preferences.save(JSON.stringify({ format: CADRON_PREFERENCES_FORMAT, ...next }));
131
+ prefs = next;
132
+ changed();
133
+ return next;
134
+ }));
135
+ writing = write;
136
+ return write;
137
+ },
138
+ bootstrapPlan: () => cadreAttempt(plan),
139
+ // WORKAROUND(sereus: an option on `createOpenInvitation`): the list is replaced after minting,
140
+ // before the app encodes it. It is not signed; the responder checks only the token.
141
+ async withBootstrap(invitation) {
142
+ try {
143
+ const { entries, warnings } = await plan();
144
+ if (entries.length === 0)
145
+ return invitation;
146
+ if (warnings.length)
147
+ log.info('[cadre-client] invitation bootstrap:', warnings.join(', '));
148
+ return { ...invitation, bootstrap: entries.map(e => e.addr) };
149
+ }
150
+ catch (err) {
151
+ log.warn('[cadre-client] kept cadre-core\'s bootstrap list:', err instanceof Error ? err.message : err);
152
+ return invitation;
153
+ }
154
+ },
155
+ readiness(strandId, opts = {}) {
156
+ if (held.has(strandId))
157
+ return 'ready';
158
+ const node = host.node.node;
159
+ if (!node)
160
+ return 'waiting';
161
+ const others = servingOthers(node, strandId);
162
+ if (opts.newStrand)
163
+ return others === 0 ? 'no-cadron' : 'waiting';
164
+ if (others === null)
165
+ return 'waiting';
166
+ return others > 0 ? 'ready' : 'no-cadron';
167
+ },
168
+ describe: (token, link) => cadreAttempt(async () => {
169
+ const node = requireNode();
170
+ const decoded = node.decodeInvitation(token);
171
+ const [{ names, maxAddrs }, list, now] = await Promise.all([
172
+ loadPrefs(),
173
+ machines(),
174
+ plan().catch(() => ({ entries: [], others: [] })),
175
+ ]);
176
+ return describeInvitation(decoded, {
177
+ link: link ?? token, names, thisDevicePeerId: node.peerId?.toString() ?? null,
178
+ machines: list, others: [...now.entries, ...now.others].map(e => e.addr), maxAddrs,
179
+ });
180
+ }),
181
+ // WORKAROUND(sereus: an option on `createOpenInvitation`), as `withBootstrap`.
182
+ rebootstrap: (token, addrs) => cadreAttempt(async () => {
183
+ const node = requireNode();
184
+ if (addrs.length === 0)
185
+ throw new CadreFailure('invalid-address', 'An invitation must name at least one address.');
186
+ if (addrs.some(a => !destinationPeerId(a)))
187
+ throw new CadreFailure('invalid-address', 'An address does not end in the peer it reaches.');
188
+ return node.encodeInvitation({ ...node.decodeInvitation(token), bootstrap: [...new Set(addrs)] });
189
+ }),
190
+ };
191
+ return {
192
+ invitations,
193
+ onChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
194
+ };
195
+ }
196
+ //# sourceMappingURL=invitations.js.map
@@ -0,0 +1 @@
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AE,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;KACxF,CAAC;AACH,CAAC"}
@@ -0,0 +1,52 @@
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 { type NodeClaimPayload } from '@serfab/cadre-core';
12
+ import type { NodeReach } from '../model.js';
13
+ export type NodeCodeProblem =
14
+ /** Does not start with `sereus-join:` — some other QR, link or text. */
15
+ 'not-node-code'
16
+ /** A node code from a newer node than this build reads: the app needs updating. */
17
+ | 'newer-version'
18
+ /** Right prefix, but cut short or corrupted. */
19
+ | 'damaged';
20
+ export type NodeCodeReading = {
21
+ ok: true;
22
+ payload: NodeClaimPayload;
23
+ } | {
24
+ ok: false;
25
+ problem: NodeCodeProblem; /** The decoder's words (never the secret), for logs. */
26
+ detail?: string;
27
+ };
28
+ /** Decode scanned or pasted text, or say which problem it has. */
29
+ export declare function readNodeCode(text: string): NodeCodeReading;
30
+ export type ClaimFailure =
31
+ /** No connection formed from any address; nothing was sent. */
32
+ {
33
+ kind: 'node-unreachable';
34
+ reach: NodeReach;
35
+ retryable: true;
36
+ detail: string;
37
+ }
38
+ /** The node answered and said no. `refusal` is absent when it gave no (known) code. */
39
+ | {
40
+ kind: 'claim-refused';
41
+ refusal?: string;
42
+ retryable: boolean;
43
+ detail: string;
44
+ }
45
+ /** Reached, then the exchange or a local step failed. Repeating with the same code is safe. */
46
+ | {
47
+ kind: 'claim-failed';
48
+ retryable: true;
49
+ detail: string;
50
+ };
51
+ /** Sort an error thrown by `CadreNode.claimNode(payload)` into what to say and whether to keep the code. */
52
+ export declare function classifyClaimFailure(error: unknown, payload: NodeClaimPayload): ClaimFailure;
@@ -0,0 +1,51 @@
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 { ClaimRefusedError, NODE_CLAIM_PAYLOAD_PREFIX, PeerUnreachableError, decodeNodeClaimPayload, describeThrown, } from '@serfab/cadre-core';
12
+ import { NODE_CODE_SCHEME, nodeCodeFromUrl } from '../node-code-text.js';
13
+ import { nodeReach } from '../address.js';
14
+ /** A code with a version this build does not read: `sereus-join:<n>.` with n ≠ 1. */
15
+ const VERSIONED_NODE_CODE = /^sereus-join:(\d+)\./;
16
+ /** Decode scanned or pasted text, or say which problem it has. */
17
+ export function readNodeCode(text) {
18
+ const trimmed = (nodeCodeFromUrl(text) ?? text).trim();
19
+ if (!trimmed.startsWith(NODE_CODE_SCHEME))
20
+ return { ok: false, problem: 'not-node-code' };
21
+ if (!trimmed.startsWith(NODE_CLAIM_PAYLOAD_PREFIX) && VERSIONED_NODE_CODE.test(trimmed)) {
22
+ return { ok: false, problem: 'newer-version' };
23
+ }
24
+ try {
25
+ return { ok: true, payload: decodeNodeClaimPayload(trimmed) };
26
+ }
27
+ catch (err) {
28
+ // The decoder never echoes the secret, so its message is safe to keep.
29
+ return { ok: false, problem: 'damaged', detail: describeThrown(err) };
30
+ }
31
+ }
32
+ /** Refusals after which the same code can still succeed. */
33
+ const RETRYABLE_REFUSALS = new Set(['claim-rate-limited', 'claim-not-persisted']);
34
+ /** Sort an error thrown by `CadreNode.claimNode(payload)` into what to say and whether to keep the code. */
35
+ export function classifyClaimFailure(error, payload) {
36
+ const detail = describeThrown(error);
37
+ if (error instanceof PeerUnreachableError) {
38
+ return { kind: 'node-unreachable', reach: nodeReach(payload.multiaddrs), retryable: true, detail };
39
+ }
40
+ if (error instanceof ClaimRefusedError) {
41
+ const refusal = error.code;
42
+ return {
43
+ kind: 'claim-refused',
44
+ refusal,
45
+ retryable: refusal !== undefined && RETRYABLE_REFUSALS.has(refusal),
46
+ detail: error.reason ?? detail,
47
+ };
48
+ }
49
+ return { kind: 'claim-failed', retryable: true, detail };
50
+ }
51
+ //# sourceMappingURL=node-code.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-code.js","sourceRoot":"","sources":["../../src/sereus/node-code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EACN,iBAAiB,EACjB,yBAAyB,EACzB,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,GAEd,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,qFAAqF;AACrF,MAAM,mBAAmB,GAAG,sBAAsB,CAAC;AAcnD,kEAAkE;AAClE,MAAM,UAAU,YAAY,CAAC,IAAY;IACxC,MAAM,OAAO,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;IACvD,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;IAC1F,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,yBAAyB,CAAC,IAAI,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACzF,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;IAChD,CAAC;IACD,IAAI,CAAC;QACJ,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,sBAAsB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC/D,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,uEAAuE;QACvE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC;IACvE,CAAC;AACF,CAAC;AAED,4DAA4D;AAC5D,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC,CAAC,oBAAoB,EAAE,qBAAqB,CAAC,CAAC,CAAC;AAUvG,4GAA4G;AAC5G,MAAM,UAAU,oBAAoB,CAAC,KAAc,EAAE,OAAyB;IAC7E,MAAM,MAAM,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;IACrC,IAAI,KAAK,YAAY,oBAAoB,EAAE,CAAC;QAC3C,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IACpG,CAAC;IACD,IAAI,KAAK,YAAY,iBAAiB,EAAE,CAAC;QACxC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC;QAC3B,OAAO;YACN,IAAI,EAAE,eAAe;YACrB,OAAO;YACP,SAAS,EAAE,OAAO,KAAK,SAAS,IAAI,kBAAkB,CAAC,GAAG,CAAC,OAAO,CAAC;YACnE,MAAM,EAAE,KAAK,CAAC,MAAM,IAAI,MAAM;SAC9B,CAAC;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC1D,CAAC"}
@@ -0,0 +1,27 @@
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
+ export interface Readable<T> {
19
+ subscribe(run: (value: T) => void): () => void;
20
+ get(): T;
21
+ }
22
+ export interface Writable<T> extends Readable<T> {
23
+ set(value: T): void;
24
+ update(fn: (value: T) => T): void;
25
+ }
26
+ export type StartStop<T> = (set: (value: T) => void, update: (fn: (value: T) => T) => void) => void | (() => void);
27
+ export declare function writable<T>(initial: T, start?: StartStop<T>): Writable<T>;
package/dist/store.js ADDED
@@ -0,0 +1,51 @@
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
+ export function writable(initial, start) {
19
+ let value = initial;
20
+ let stop = undefined;
21
+ const subscribers = new Set();
22
+ const set = (next) => {
23
+ if (Object.is(next, value))
24
+ return;
25
+ value = next;
26
+ for (const run of [...subscribers])
27
+ run(value);
28
+ };
29
+ const update = (fn) => set(fn(value));
30
+ return {
31
+ get: () => value,
32
+ set,
33
+ update,
34
+ subscribe(run) {
35
+ subscribers.add(run);
36
+ if (subscribers.size === 1 && start)
37
+ stop = start(set, update);
38
+ run(value);
39
+ return () => {
40
+ if (!subscribers.delete(run))
41
+ return;
42
+ if (subscribers.size === 0 && stop) {
43
+ const halt = stop;
44
+ stop = undefined;
45
+ halt();
46
+ }
47
+ };
48
+ },
49
+ };
50
+ }
51
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAcH,MAAM,UAAU,QAAQ,CAAI,OAAU,EAAE,KAAoB;IAC3D,IAAI,KAAK,GAAG,OAAO,CAAC;IACpB,IAAI,IAAI,GAAwB,SAAS,CAAC;IAC1C,MAAM,WAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;IAElD,MAAM,GAAG,GAAG,CAAC,IAAO,EAAE,EAAE;QACvB,IAAI,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC;YAAE,OAAO;QACnC,KAAK,GAAG,IAAI,CAAC;QACb,KAAK,MAAM,GAAG,IAAI,CAAC,GAAG,WAAW,CAAC;YAAE,GAAG,CAAC,KAAK,CAAC,CAAC;IAChD,CAAC,CAAC;IACF,MAAM,MAAM,GAAG,CAAC,EAAmB,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IAEvD,OAAO;QACN,GAAG,EAAE,GAAG,EAAE,CAAC,KAAK;QAChB,GAAG;QACH,MAAM;QACN,SAAS,CAAC,GAAG;YACZ,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACrB,IAAI,WAAW,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK;gBAAE,IAAI,GAAG,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAC/D,GAAG,CAAC,KAAK,CAAC,CAAC;YACX,OAAO,GAAG,EAAE;gBACX,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC;oBAAE,OAAO;gBACrC,IAAI,WAAW,CAAC,IAAI,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC;oBACpC,MAAM,IAAI,GAAG,IAAI,CAAC;oBAClB,IAAI,GAAG,SAAS,CAAC;oBACjB,IAAI,EAAE,CAAC;gBACR,CAAC;YACF,CAAC,CAAC;QACH,CAAC;KACD,CAAC;AACH,CAAC"}
@@ -0,0 +1,37 @@
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 { type Readable } from './store.js';
8
+ import { type Loader } from './loader.js';
9
+ /** How often a store re-reads with nothing announcing a change, while subscribed. */
10
+ export interface StoreOptions {
11
+ /** Milliseconds; 0 turns the poll off. Default 30 s. */
12
+ pollMs?: number;
13
+ }
14
+ /**
15
+ * The cadre: this device, its cadrons, and whether it is an enrolled owner. Re-read on every
16
+ * change that has an event: this node starting or stopping, a cadron connecting or dropping, the
17
+ * cadron preferences. The poll catches what has none: a cadron added or removed on another
18
+ * device (it arrives by control replication), and a cadron's `lastSeenAt` ageing, so its
19
+ * presence turns from recent to quiet. A store kept subscribed app-wide (a status badge) can poll
20
+ * less often, or not at all if those can wait for the next screen.
21
+ */
22
+ export declare function cadreStore(view: CadreView, opts?: StoreOptions): Loader<CadreStatus>;
23
+ /**
24
+ * Reachability: can anybody answer an invitation from this device, which relays it is
25
+ * configured with, and whether the relay reservation holds — read live, because a
26
+ * configured relay is not a working one and a reservation can be lost after it was
27
+ * granted. Re-read when this device's addresses change; a slow backstop poll covers a
28
+ * change no event announces (a machine of the party's coming up or going quiet).
29
+ */
30
+ export declare function reachabilityStore(view: ReachabilityView, opts?: StoreOptions): Loader<Reachability>;
31
+ /**
32
+ * Whether a new invitation to `strandId` is ready to hand out (`InvitationReadiness`), live: it
33
+ * turns `ready` when a cadron comes to hold the strand.
34
+ */
35
+ export declare function invitationReadinessStore(view: InvitationsView, strandId: string, opts?: {
36
+ newStrand?: boolean;
37
+ }): Readable<InvitationReadiness>;
package/dist/stores.js ADDED
@@ -0,0 +1,45 @@
1
+ import { writable } from './store.js';
2
+ import { cadreOk } from './result.js';
3
+ import { loader } from './loader.js';
4
+ /**
5
+ * The cadre: this device, its cadrons, and whether it is an enrolled owner. Re-read on every
6
+ * change that has an event: this node starting or stopping, a cadron connecting or dropping, the
7
+ * cadron preferences. The poll catches what has none: a cadron added or removed on another
8
+ * device (it arrives by control replication), and a cadron's `lastSeenAt` ageing, so its
9
+ * presence turns from recent to quiet. A store kept subscribed app-wide (a status badge) can poll
10
+ * less often, or not at all if those can wait for the next screen.
11
+ */
12
+ export function cadreStore(view, opts = {}) {
13
+ return loader({
14
+ load: () => view.cadre.status(),
15
+ changes: onChange => view.changes.cadre(onChange),
16
+ pollMs: opts.pollMs ?? 30_000,
17
+ });
18
+ }
19
+ /**
20
+ * Reachability: can anybody answer an invitation from this device, which relays it is
21
+ * configured with, and whether the relay reservation holds — read live, because a
22
+ * configured relay is not a working one and a reservation can be lost after it was
23
+ * granted. Re-read when this device's addresses change; a slow backstop poll covers a
24
+ * change no event announces (a machine of the party's coming up or going quiet).
25
+ */
26
+ export function reachabilityStore(view, opts = {}) {
27
+ return loader({
28
+ load: async () => cadreOk(await view.reachability.get()),
29
+ changes: onChange => view.changes.reachability(onChange),
30
+ debounceMs: 250,
31
+ pollMs: opts.pollMs ?? 30_000,
32
+ });
33
+ }
34
+ /**
35
+ * Whether a new invitation to `strandId` is ready to hand out (`InvitationReadiness`), live: it
36
+ * turns `ready` when a cadron comes to hold the strand.
37
+ */
38
+ export function invitationReadinessStore(view, strandId, opts = {}) {
39
+ const read = () => view.invitations.readiness(strandId, opts);
40
+ return writable(read(), set => {
41
+ set(read());
42
+ return view.changes.invitations(() => set(read()));
43
+ });
44
+ }
45
+ //# sourceMappingURL=stores.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stores.js","sourceRoot":"","sources":["../src/stores.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,QAAQ,EAAiB,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAQlD;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CAAC,IAAe,EAAE,OAAqB,EAAE;IAClE,OAAO,MAAM,CAAC;QACb,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;QAC/B,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;QACjD,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,MAAM;KAC7B,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAsB,EAAE,OAAqB,EAAE;IAChF,OAAO,MAAM,CAAC;QACb,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC;QACxD,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC;QACxD,UAAU,EAAE,GAAG;QACf,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,MAAM;KAC7B,CAAC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAAqB,EAAE,QAAgB,EAAE,OAAgC,EAAE;IACnH,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC9D,OAAO,QAAQ,CAAsB,IAAI,EAAE,EAAE,GAAG,CAAC,EAAE;QAClD,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QACZ,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,20 @@
1
+ # cadre-client examples
2
+
3
+ Screens to copy and adapt, one folder per UI framework. They are not built, tested or published;
4
+ each shows how to bind the client's stores and call its operations, with inline English strings
5
+ and plain styles an app replaces with its own.
6
+
7
+ | | React Native | Svelte 5 | NativeScript |
8
+ |---|---|---|---|
9
+ | The person's cadrons with a status dot, a name (else the host name) and what to match them by (host, short id) | [`CadronList.tsx`](react-native/CadronList.tsx) | [`CadronList.svelte`](svelte/CadronList.svelte) | [`cadrons-view-model.ts`](nativescript/cadrons-view-model.ts) + [`cadrons-page.xml`](nativescript/cadrons-page.xml) |
10
+ | Starring a cadron (preferred in invitations) | ✔ | ✔ | ✔ |
11
+ | Addresses per invitation | ✔ | ✔ | |
12
+ | Renaming, removal (with its plan), adding one by its code (named after its host) | ✔ | | |
13
+ | Beside a minted invitation: ready to hand out, the machines it names (each address a checkbox, the ones it could name unchecked), the QR code full screen | [`InvitationPanel.tsx`](react-native/InvitationPanel.tsx) | [`InvitationPanel.svelte`](svelte/InvitationPanel.svelte) | |
14
+ | Binding a store | [`useStore.ts`](react-native/useStore.ts) (`useSyncExternalStore`) | `$store` (the store contract) | `subscribe` into an `Observable` |
15
+
16
+ Each takes a `client`, `createCadreClient(...)` from `@serfab/cadre-client/sereus`. Wiring that
17
+ client into an app, and minting invitations through it, is in [ADOPTING.md](../ADOPTING.md).
18
+
19
+ Dependencies the examples assume, beyond the package: React Native and `react-native-qrcode-svg`;
20
+ Svelte 5 and `qrcode`; `@nativescript/core`.
@@ -0,0 +1,24 @@
1
+ <!--
2
+ Example (NativeScript): the page for cadrons-view-model.ts. In its code-behind:
3
+ navigatingTo: page.bindingContext = new CadronsViewModel(client)
4
+ navigatedFrom: (page.bindingContext as CadronsViewModel).dispose()
5
+ onStar: (page.bindingContext as CadronsViewModel).toggleStar(args.object.bindingContext.peerId)
6
+ -->
7
+ <Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" navigatedFrom="navigatedFrom">
8
+ <ActionBar title="My machines" />
9
+ <StackLayout>
10
+ <Label text="{{ message }}" visibility="{{ message ? 'visible' : 'collapsed' }}" />
11
+ <ListView items="{{ rows }}">
12
+ <ListView.itemTemplate>
13
+ <GridLayout columns="auto, *, auto" padding="8">
14
+ <Label col="0" width="8" height="8" borderRadius="4" backgroundColor="{{ dot }}" marginRight="10" />
15
+ <StackLayout col="1">
16
+ <Label text="{{ title }}" />
17
+ <Label text="{{ subtitle }}" fontSize="12" color="#666666" />
18
+ </StackLayout>
19
+ <Label col="2" text="{{ star }}" tap="onStar" visibility="{{ thisDevice ? 'collapsed' : 'visible' }}" />
20
+ </GridLayout>
21
+ </ListView.itemTemplate>
22
+ </ListView>
23
+ </StackLayout>
24
+ </Page>
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Example (NativeScript): a person's cadrons as a view model for `cadrons-page.xml`. Copy and
3
+ * adapt; it is not built or published. A cadre-client store is copied into an `Observable` from
4
+ * `subscribe`; unsubscribe when the page goes (`navigatedFrom`), so the store stops reading.
5
+ * `client` is `createCadreClient(...)` from `@serfab/cadre-client/sereus`.
6
+ */
7
+ import { Observable } from '@nativescript/core';
8
+ import { cadreStore, cadronPresence, shortPeerId, suggestedName, type CadreMachine, type CadronPresence } from '@serfab/cadre-client';
9
+ import type { CadreClient } from '@serfab/cadre-client/sereus';
10
+
11
+ const DOT: Record<CadronPresence, string> = { connected: '#2c8a3f', recent: '#c98a00', quiet: '#888888', unknown: '#dddddd' };
12
+ const PRESENCE: Record<CadronPresence, string> = {
13
+ connected: 'Connected', recent: 'Seen recently', quiet: 'Not seen lately', unknown: 'Not seen yet',
14
+ };
15
+
16
+ interface CadronRow {
17
+ peerId: string;
18
+ title: string;
19
+ subtitle: string;
20
+ dot: string;
21
+ star: string;
22
+ thisDevice: boolean;
23
+ }
24
+
25
+ function row(m: CadreMachine): CadronRow {
26
+ const presence = cadronPresence(m);
27
+ return {
28
+ peerId: m.peerId,
29
+ title: m.thisDevice ? 'This device' : m.name || suggestedName(m) || `Machine ${shortPeerId(m.peerId)}`,
30
+ subtitle: [
31
+ suggestedName(m), shortPeerId(m.peerId),
32
+ m.thisDevice ? null : m.trusted === false ? 'Not verified' : PRESENCE[presence],
33
+ m.alwaysOn ? 'Always on' : null,
34
+ ].filter(Boolean).join(' · '),
35
+ dot: DOT[presence],
36
+ star: m.preferred ? '★' : '☆',
37
+ thisDevice: m.thisDevice,
38
+ };
39
+ }
40
+
41
+ export class CadronsViewModel extends Observable {
42
+ rows: CadronRow[] = [];
43
+ message = 'Loading…';
44
+ private readonly unsubscribe: () => void;
45
+
46
+ constructor(private readonly client: CadreClient) {
47
+ super();
48
+ this.unsubscribe = cadreStore(client).subscribe(load => {
49
+ if (load.state === 'ready') {
50
+ this.set('rows', load.value.machines.map(row));
51
+ this.set('message', '');
52
+ } else {
53
+ this.set('message', load.state === 'failed' ? load.error.message : 'Loading…');
54
+ }
55
+ });
56
+ }
57
+
58
+ /** Bound to a row's star: name this cadron first in invitations, or stop. */
59
+ async toggleStar(peerId: string): Promise<void> {
60
+ const prefs = await this.client.invitations.preferences();
61
+ const preferred = prefs.preferred.includes(peerId) ? prefs.preferred.filter(id => id !== peerId) : [...prefs.preferred, peerId];
62
+ await this.client.invitations.setPreferences({ preferred });
63
+ }
64
+
65
+ dispose(): void {
66
+ this.unsubscribe();
67
+ }
68
+ }