@abraca/dabra 2.101.0 → 2.103.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 (151) hide show
  1. package/dist/abracadabra-provider.cjs +6673 -6543
  2. package/dist/abracadabra-provider.cjs.map +1 -1
  3. package/dist/esm/AbracadabraBaseProvider.js +558 -0
  4. package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
  5. package/dist/esm/AbracadabraClient.js +1424 -0
  6. package/dist/esm/AbracadabraClient.js.map +1 -0
  7. package/dist/esm/AbracadabraProvider.js +547 -0
  8. package/dist/esm/AbracadabraProvider.js.map +1 -0
  9. package/dist/esm/AbracadabraWS.js +398 -0
  10. package/dist/esm/AbracadabraWS.js.map +1 -0
  11. package/dist/esm/BackgroundSyncManager.js +571 -0
  12. package/dist/esm/BackgroundSyncManager.js.map +1 -0
  13. package/dist/esm/BackgroundSyncPersistence.js +62 -0
  14. package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
  15. package/dist/esm/ChatClient.js +176 -0
  16. package/dist/esm/ChatClient.js.map +1 -0
  17. package/dist/esm/CloseEvents.js +45 -0
  18. package/dist/esm/CloseEvents.js.map +1 -0
  19. package/dist/esm/ContentManager.js +153 -0
  20. package/dist/esm/ContentManager.js.map +1 -0
  21. package/dist/esm/CoverReconcile.js +124 -0
  22. package/dist/esm/CoverReconcile.js.map +1 -0
  23. package/dist/esm/CryptoIdentityKeystore.js +580 -0
  24. package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
  25. package/dist/esm/DeviceRegistrationService.js +158 -0
  26. package/dist/esm/DeviceRegistrationService.js.map +1 -0
  27. package/dist/esm/DocConverters.js +1300 -0
  28. package/dist/esm/DocConverters.js.map +1 -0
  29. package/dist/esm/DocKeyManager.js +145 -0
  30. package/dist/esm/DocKeyManager.js.map +1 -0
  31. package/dist/esm/DocTypes.js +792 -0
  32. package/dist/esm/DocTypes.js.map +1 -0
  33. package/dist/esm/DocUtils.js +180 -0
  34. package/dist/esm/DocUtils.js.map +1 -0
  35. package/dist/esm/DocumentCache.js +131 -0
  36. package/dist/esm/DocumentCache.js.map +1 -0
  37. package/dist/esm/DocumentManager.js +240 -0
  38. package/dist/esm/DocumentManager.js.map +1 -0
  39. package/dist/esm/E2EAbracadabraProvider.js +273 -0
  40. package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
  41. package/dist/esm/E2EOfflineStore.js +53 -0
  42. package/dist/esm/E2EOfflineStore.js.map +1 -0
  43. package/dist/esm/EncryptedChatClient.js +156 -0
  44. package/dist/esm/EncryptedChatClient.js.map +1 -0
  45. package/dist/esm/EncryptedY.js +115 -0
  46. package/dist/esm/EncryptedY.js.map +1 -0
  47. package/dist/esm/EventEmitter.js +40 -0
  48. package/dist/esm/EventEmitter.js.map +1 -0
  49. package/dist/esm/FileBlobStore.js +410 -0
  50. package/dist/esm/FileBlobStore.js.map +1 -0
  51. package/dist/esm/IdentityDoc.js +413 -0
  52. package/dist/esm/IdentityDoc.js.map +1 -0
  53. package/dist/esm/IncomingMessage.js +39 -0
  54. package/dist/esm/IncomingMessage.js.map +1 -0
  55. package/dist/esm/LifecycleGate.js +124 -0
  56. package/dist/esm/LifecycleGate.js.map +1 -0
  57. package/dist/esm/MessageReceiver.js +86 -0
  58. package/dist/esm/MessageReceiver.js.map +1 -0
  59. package/dist/esm/MessageSender.js +19 -0
  60. package/dist/esm/MessageSender.js.map +1 -0
  61. package/dist/esm/MetaManager.js +112 -0
  62. package/dist/esm/MetaManager.js.map +1 -0
  63. package/dist/esm/MnemonicKeyDerivation.js +137 -0
  64. package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
  65. package/dist/esm/NodeConnect.js +63 -0
  66. package/dist/esm/NodeConnect.js.map +1 -0
  67. package/dist/esm/NodeIdentity.js +212 -0
  68. package/dist/esm/NodeIdentity.js.map +1 -0
  69. package/dist/esm/NotificationsClient.js +136 -0
  70. package/dist/esm/NotificationsClient.js.map +1 -0
  71. package/dist/esm/OfflineStore.js +291 -0
  72. package/dist/esm/OfflineStore.js.map +1 -0
  73. package/dist/esm/OutgoingMessage.js +18 -0
  74. package/dist/esm/OutgoingMessage.js.map +1 -0
  75. package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
  76. package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
  77. package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
  78. package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
  79. package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
  80. package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
  81. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
  82. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
  83. package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
  84. package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
  85. package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
  86. package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
  87. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
  88. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
  89. package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
  90. package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
  91. package/dist/esm/PerfCounters.js +336 -0
  92. package/dist/esm/PerfCounters.js.map +1 -0
  93. package/dist/esm/QueryClient.js +117 -0
  94. package/dist/esm/QueryClient.js.map +1 -0
  95. package/dist/esm/RpcClient.js +456 -0
  96. package/dist/esm/RpcClient.js.map +1 -0
  97. package/dist/esm/SchemaTypes.js +38 -0
  98. package/dist/esm/SchemaTypes.js.map +1 -0
  99. package/dist/esm/SearchIndex.js +167 -0
  100. package/dist/esm/SearchIndex.js.map +1 -0
  101. package/dist/esm/ServerRegistry.js +139 -0
  102. package/dist/esm/ServerRegistry.js.map +1 -0
  103. package/dist/esm/ServerReset.js +170 -0
  104. package/dist/esm/ServerReset.js.map +1 -0
  105. package/dist/esm/TokenManager.js +236 -0
  106. package/dist/esm/TokenManager.js.map +1 -0
  107. package/dist/esm/TreeManager.js +655 -0
  108. package/dist/esm/TreeManager.js.map +1 -0
  109. package/dist/esm/TreeTimestamps.js +61 -0
  110. package/dist/esm/TreeTimestamps.js.map +1 -0
  111. package/dist/esm/auth.js +43 -0
  112. package/dist/esm/auth.js.map +1 -0
  113. package/dist/esm/awarenessStatesToArray.js +13 -0
  114. package/dist/esm/awarenessStatesToArray.js.map +1 -0
  115. package/dist/esm/docIds.js +53 -0
  116. package/dist/esm/docIds.js.map +1 -0
  117. package/dist/esm/encryptedContent.js +21 -0
  118. package/dist/esm/encryptedContent.js.map +1 -0
  119. package/dist/esm/index.js +61 -0
  120. package/dist/esm/messageRecord.js +64 -0
  121. package/dist/esm/messageRecord.js.map +1 -0
  122. package/dist/esm/sync/BroadcastChannelSync.js +160 -0
  123. package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
  124. package/dist/esm/types.js +54 -0
  125. package/dist/esm/types.js.map +1 -0
  126. package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
  127. package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
  128. package/dist/esm/webrtc/DataChannelRouter.js +124 -0
  129. package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
  130. package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
  131. package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
  132. package/dist/esm/webrtc/E2EEChannel.js +137 -0
  133. package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
  134. package/dist/esm/webrtc/FileTransferChannel.js +250 -0
  135. package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
  136. package/dist/esm/webrtc/ManualSignaling.js +161 -0
  137. package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
  138. package/dist/esm/webrtc/PeerConnection.js +96 -0
  139. package/dist/esm/webrtc/PeerConnection.js.map +1 -0
  140. package/dist/esm/webrtc/SignalingSocket.js +274 -0
  141. package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
  142. package/dist/esm/webrtc/YjsDataChannel.js +135 -0
  143. package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
  144. package/dist/esm/webrtc/types.js +29 -0
  145. package/dist/esm/webrtc/types.js.map +1 -0
  146. package/dist/esm/x25519Convert.js +69 -0
  147. package/dist/esm/x25519Convert.js.map +1 -0
  148. package/dist/index.d.ts +26 -11
  149. package/package.json +6 -4
  150. package/dist/abracadabra-provider.esm.js +0 -14860
  151. package/dist/abracadabra-provider.esm.js.map +0 -1
@@ -0,0 +1,456 @@
1
+ import EventEmitter from "./EventEmitter.js";
2
+
3
+ //#region packages/provider/src/RpcClient.ts
4
+ /**
5
+ * RPC v1 — request/response over `MSG_STATELESS`.
6
+ *
7
+ * Mirrors `docs/rpc-v1.md` in the abracadabra-rs server. Frames travel as
8
+ * `MSG_STATELESS` payloads with the literal prefix `rpc:v1:` followed by a
9
+ * JSON envelope. The provider's existing `sendStateless` / `stateless` event
10
+ * stream is the only transport surface this layer touches; everything else
11
+ * (state machine, deadlines, handler registry, dedupe of self-replies) lives
12
+ * here.
13
+ */
14
+ const RPC_PREFIX = "rpc:v1:";
15
+ /** Thrown by `rpc.call(...)` on terminal nack / error / timeout. */
16
+ var RpcError = class extends Error {
17
+ constructor(code, message, details) {
18
+ super(message);
19
+ this.name = "RpcError";
20
+ this.code = code;
21
+ this.details = details;
22
+ }
23
+ };
24
+ function uuidv7() {
25
+ const tsHex = Date.now().toString(16).padStart(12, "0");
26
+ const rand = new Uint8Array(10);
27
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(rand);
28
+ else for (let i = 0; i < rand.length; i++) rand[i] = Math.floor(Math.random() * 256);
29
+ rand[0] = rand[0] & 15 | 112;
30
+ rand[2] = rand[2] & 63 | 128;
31
+ const hex = Array.from(rand, (b) => b.toString(16).padStart(2, "0")).join("");
32
+ return `${tsHex.slice(0, 8)}-${tsHex.slice(8, 12)}-${hex.slice(0, 4)}-${hex.slice(4, 8)}-${hex.slice(8, 20)}`;
33
+ }
34
+ /**
35
+ * Per-provider RPC layer. Construct one and attach by passing the provider
36
+ * (or any `RpcTransport`). Disposes on `destroy()`.
37
+ *
38
+ * Caller side: `rpc.call('ai.summarize@1', { docId }, { onProgress })`.
39
+ *
40
+ * Runner side: `rpc.handle('ai.summarize@1', async (args, ctx) => …)`.
41
+ */
42
+ var RpcClient = class RpcClient extends EventEmitter {
43
+ static {
44
+ this.DISCONNECT_GRACE_MS = 1e4;
45
+ }
46
+ constructor(transport) {
47
+ super();
48
+ this.pending = /* @__PURE__ */ new Map();
49
+ this.handlers = /* @__PURE__ */ new Map();
50
+ this.runningHandlers = /* @__PURE__ */ new Map();
51
+ this.pendingRegistrations = /* @__PURE__ */ new Map();
52
+ this.destroyed = false;
53
+ this.transport = transport;
54
+ this.onStatelessBound = (data) => this.receive(data.payload);
55
+ this.onSyncedBound = (data) => {
56
+ if (data.state) this.replayRegistrations();
57
+ };
58
+ this.onDisconnectBound = () => this.armDisconnectGrace();
59
+ this.onConnectBound = () => this.cancelDisconnectGrace();
60
+ transport.on("stateless", this.onStatelessBound);
61
+ transport.on("synced", this.onSyncedBound);
62
+ transport.on("disconnect", this.onDisconnectBound);
63
+ transport.on("connect", this.onConnectBound);
64
+ }
65
+ armDisconnectGrace() {
66
+ if (this.destroyed) return;
67
+ if (this.disconnectGrace) return;
68
+ this.disconnectGrace = setTimeout(() => this.failPendingOnDisconnect(), RpcClient.DISCONNECT_GRACE_MS);
69
+ }
70
+ cancelDisconnectGrace() {
71
+ if (this.disconnectGrace) {
72
+ clearTimeout(this.disconnectGrace);
73
+ this.disconnectGrace = void 0;
74
+ }
75
+ }
76
+ /**
77
+ * Called when the WS has been down for the full grace window. Every
78
+ * in-flight call is dead from the server's perspective (its `close_session`
79
+ * already fired `HANDLER_GONE` to a now-disconnected caller; on reconnect
80
+ * the server-side session is fresh, so any cached cancel/result frames
81
+ * the server tried to deliver were lost). Fail pending immediately.
82
+ */
83
+ failPendingOnDisconnect() {
84
+ this.disconnectGrace = void 0;
85
+ if (this.destroyed) return;
86
+ for (const [, p] of this.pending) {
87
+ if (p.deadlineTimer) clearTimeout(p.deadlineTimer);
88
+ this.settle(p, () => p.reject(new RpcError("HANDLER_GONE", "websocket disconnected")));
89
+ }
90
+ }
91
+ /**
92
+ * Re-emit a `register` frame for every locally-known handler. Called on
93
+ * every `synced` event from the provider, since a reconnected WS gets a
94
+ * fresh server-side session with empty capability state.
95
+ */
96
+ replayRegistrations() {
97
+ if (this.destroyed) return;
98
+ if (this.pendingRegistrations.size > 0) {
99
+ const stale = [...this.pendingRegistrations.values()];
100
+ this.pendingRegistrations.clear();
101
+ for (const r of stale) r();
102
+ }
103
+ if (this.handlers.size === 0) return;
104
+ const methods = [...this.handlers.keys()];
105
+ const id = uuidv7();
106
+ this.pendingRegistrations.set(id, () => {});
107
+ this.send({
108
+ kind: "register",
109
+ id,
110
+ methods
111
+ });
112
+ }
113
+ destroy() {
114
+ if (this.destroyed) return;
115
+ this.destroyed = true;
116
+ this.transport.off("stateless", this.onStatelessBound);
117
+ this.transport.off("synced", this.onSyncedBound);
118
+ this.transport.off("disconnect", this.onDisconnectBound);
119
+ this.transport.off("connect", this.onConnectBound);
120
+ this.cancelDisconnectGrace();
121
+ for (const [, ac] of this.runningHandlers) try {
122
+ ac.abort();
123
+ } catch {}
124
+ this.runningHandlers.clear();
125
+ for (const [, p] of this.pending) {
126
+ if (p.deadlineTimer) clearTimeout(p.deadlineTimer);
127
+ p.reject(new RpcError("CANCELLED", "RpcClient destroyed"));
128
+ }
129
+ this.pending.clear();
130
+ for (const [, resolve] of this.pendingRegistrations) try {
131
+ resolve();
132
+ } catch {}
133
+ this.pendingRegistrations.clear();
134
+ this.handlers.clear();
135
+ this.removeAllListeners();
136
+ }
137
+ /**
138
+ * Send an RPC and return a handle that resolves with the runner's result.
139
+ * Throws `RpcError` on nack / handler error / timeout / cancellation.
140
+ */
141
+ call(method, args, options) {
142
+ const opts = options ?? {};
143
+ const id = uuidv7();
144
+ const target = opts.target ?? {
145
+ kind: "role",
146
+ role: "service"
147
+ };
148
+ let resolve;
149
+ let reject;
150
+ const promise = new Promise((res, rej) => {
151
+ resolve = res;
152
+ reject = rej;
153
+ });
154
+ if (this.destroyed) {
155
+ const handle = promise;
156
+ Object.defineProperty(handle, "id", {
157
+ value: id,
158
+ enumerable: true
159
+ });
160
+ Object.defineProperty(handle, "claimedBy", {
161
+ enumerable: true,
162
+ get: () => void 0
163
+ });
164
+ handle.cancel = () => {};
165
+ reject(new RpcError("CANCELLED", "rpc client destroyed"));
166
+ return handle;
167
+ }
168
+ if (opts.signal?.aborted) {
169
+ const reason = opts.signal.reason;
170
+ const handle = promise;
171
+ Object.defineProperty(handle, "id", {
172
+ value: id,
173
+ enumerable: true
174
+ });
175
+ Object.defineProperty(handle, "claimedBy", {
176
+ enumerable: true,
177
+ get: () => void 0
178
+ });
179
+ handle.cancel = () => {};
180
+ reject(new RpcError("CANCELLED", typeof reason === "string" ? reason : "aborted"));
181
+ return handle;
182
+ }
183
+ const pending = {
184
+ id,
185
+ resolve,
186
+ reject,
187
+ options: opts,
188
+ state: "pending",
189
+ claimedBy: void 0,
190
+ deadlineTimer: void 0
191
+ };
192
+ this.pending.set(id, pending);
193
+ const deadline = opts.deadline ?? 3e4;
194
+ pending.deadlineTimer = setTimeout(() => {
195
+ if (pending.state !== "settled") this.settle(pending, () => reject(new RpcError("TIMEOUT", "rpc deadline exceeded (client-side)")));
196
+ }, deadline + 5e3);
197
+ if (opts.signal) opts.signal.addEventListener("abort", () => this.abortInFlight(pending, opts.signal?.reason), { once: true });
198
+ const frame = {
199
+ kind: "req",
200
+ id,
201
+ ts: Date.now(),
202
+ method,
203
+ args,
204
+ to: serializeTarget(target),
205
+ deadline_ms: deadline
206
+ };
207
+ this.send(frame);
208
+ const handle = promise;
209
+ Object.defineProperty(handle, "id", {
210
+ value: id,
211
+ enumerable: true
212
+ });
213
+ Object.defineProperty(handle, "claimedBy", {
214
+ enumerable: true,
215
+ get: () => pending.claimedBy
216
+ });
217
+ handle.cancel = (reason) => this.abortInFlight(pending, reason);
218
+ return handle;
219
+ }
220
+ abortInFlight(pending, reason) {
221
+ if (pending.state === "settled") return;
222
+ this.send({
223
+ kind: "cancel",
224
+ id: pending.id,
225
+ ts: Date.now(),
226
+ data: reason ? { reason: String(reason) } : void 0
227
+ });
228
+ this.settle(pending, () => pending.reject(new RpcError("CANCELLED", typeof reason === "string" ? reason : "cancelled")));
229
+ }
230
+ /**
231
+ * Register a handler for `method` and advertise it to the server so
232
+ * incoming `to: role:service` calls resolve here. Returns an unsubscribe
233
+ * function. Calling `register` twice for the same method replaces the
234
+ * handler and re-advertises.
235
+ *
236
+ * The advertise is fire-and-forget; if you need to wait until the server
237
+ * has acknowledged registration (typical in tests with a separate caller
238
+ * connection), `await rpc.ready()` after registering all handlers.
239
+ */
240
+ handle(method, handler) {
241
+ this.handlers.set(method, handler);
242
+ const id = uuidv7();
243
+ this.pendingRegistrations.set(id, () => {});
244
+ this.send({
245
+ kind: "register",
246
+ id,
247
+ methods: [method]
248
+ });
249
+ return () => {
250
+ if (this.handlers.get(method) === handler) {
251
+ this.handlers.delete(method);
252
+ this.send({
253
+ kind: "unregister",
254
+ id: uuidv7(),
255
+ methods: [method]
256
+ });
257
+ }
258
+ };
259
+ }
260
+ /**
261
+ * Resolve once every outstanding `register` frame has been acknowledged
262
+ * by the server. Useful when a separate connection is about to issue
263
+ * `rpc.call(...)` and you need the capability registry to be live first.
264
+ * Resolves immediately if there's nothing pending.
265
+ */
266
+ ready() {
267
+ if (this.pendingRegistrations.size === 0) return Promise.resolve();
268
+ const ids = [...this.pendingRegistrations.keys()];
269
+ return Promise.all(ids.map((id) => new Promise((resolve) => {
270
+ this.pendingRegistrations.set(id, resolve);
271
+ }))).then(() => void 0);
272
+ }
273
+ send(frame) {
274
+ if (this.destroyed) return;
275
+ const payload = `${RPC_PREFIX}${JSON.stringify(frame)}`;
276
+ this.transport.sendStateless(payload);
277
+ }
278
+ receive(payload) {
279
+ if (!payload.startsWith(RPC_PREFIX)) return;
280
+ const json = payload.slice(7);
281
+ let frame;
282
+ try {
283
+ frame = JSON.parse(json);
284
+ } catch {
285
+ return;
286
+ }
287
+ switch (frame.kind) {
288
+ case "ack": return this.onAck(frame);
289
+ case "progress": return this.onProgress(frame);
290
+ case "result": return this.onResult(frame);
291
+ case "nack": return this.onNack(frame);
292
+ case "req":
293
+ this.onReq(frame);
294
+ return;
295
+ case "cancel": return this.onCancel(frame);
296
+ default: return;
297
+ }
298
+ }
299
+ onAck(frame) {
300
+ const pendingReg = this.pendingRegistrations.get(frame.id);
301
+ if (pendingReg) {
302
+ this.pendingRegistrations.delete(frame.id);
303
+ pendingReg();
304
+ return;
305
+ }
306
+ const pending = this.pending.get(frame.id);
307
+ if (!pending) return;
308
+ if (frame.by === "server" && pending.state === "pending") pending.state = "accepted";
309
+ else if (frame.by === "runner") {
310
+ pending.state = "claimed";
311
+ pending.claimedBy = frame.runner_id;
312
+ pending.options.onClaim?.(frame.runner_id ?? "");
313
+ }
314
+ }
315
+ onProgress(frame) {
316
+ const pending = this.pending.get(frame.id);
317
+ if (!pending) return;
318
+ pending.options.onProgress?.(frame.data, frame.seq ?? 0);
319
+ }
320
+ onResult(frame) {
321
+ const pending = this.pending.get(frame.id);
322
+ if (!pending) return;
323
+ if (frame.error) {
324
+ const err = new RpcError(frame.error.code, frame.error.message, frame.error.details);
325
+ this.settle(pending, () => pending.reject(err));
326
+ } else this.settle(pending, () => pending.resolve(frame.data));
327
+ }
328
+ onNack(frame) {
329
+ const pending = this.pending.get(frame.id);
330
+ if (!pending) return;
331
+ const err = frame.error ? new RpcError(frame.error.code, frame.error.message, frame.error.details) : new RpcError("INTERNAL", "rpc nack");
332
+ this.settle(pending, () => pending.reject(err));
333
+ }
334
+ settle(pending, finalize) {
335
+ if (pending.state === "settled") return;
336
+ pending.state = "settled";
337
+ if (pending.deadlineTimer) clearTimeout(pending.deadlineTimer);
338
+ this.pending.delete(pending.id);
339
+ finalize();
340
+ }
341
+ async onReq(frame) {
342
+ const method = frame.method ?? "";
343
+ const handler = this.handlers.get(method);
344
+ if (!handler) return;
345
+ if (this.runningHandlers.has(frame.id)) return;
346
+ const ac = new AbortController();
347
+ this.runningHandlers.set(frame.id, ac);
348
+ this.send({
349
+ kind: "ack",
350
+ id: frame.id,
351
+ ts: Date.now(),
352
+ by: "runner"
353
+ });
354
+ const ctx = {
355
+ id: frame.id,
356
+ method,
357
+ from: frame.from ?? "",
358
+ signal: ac.signal
359
+ };
360
+ const hbInterval = setInterval(() => {
361
+ if (!ac.signal.aborted) this.send({
362
+ kind: "hb",
363
+ id: frame.id,
364
+ ts: Date.now()
365
+ });
366
+ }, 5e3);
367
+ try {
368
+ const ret = handler(frame.args, ctx);
369
+ if (ret && typeof ret.next === "function" && typeof ret[Symbol.asyncIterator] === "function") {
370
+ const gen = ret;
371
+ let seq = 0;
372
+ let final = void 0;
373
+ while (true) {
374
+ const { value, done } = await gen.next();
375
+ if (done) {
376
+ final = value;
377
+ break;
378
+ }
379
+ if (ac.signal.aborted) break;
380
+ this.send({
381
+ kind: "progress",
382
+ id: frame.id,
383
+ ts: Date.now(),
384
+ seq: seq++,
385
+ data: value
386
+ });
387
+ }
388
+ if (ac.signal.aborted) this.send({
389
+ kind: "result",
390
+ id: frame.id,
391
+ ts: Date.now(),
392
+ error: {
393
+ code: "CANCELLED",
394
+ message: "handler cancelled"
395
+ }
396
+ });
397
+ else this.send({
398
+ kind: "result",
399
+ id: frame.id,
400
+ ts: Date.now(),
401
+ data: final ?? null
402
+ });
403
+ } else {
404
+ const value = await ret;
405
+ if (ac.signal.aborted) this.send({
406
+ kind: "result",
407
+ id: frame.id,
408
+ ts: Date.now(),
409
+ error: {
410
+ code: "CANCELLED",
411
+ message: "handler cancelled"
412
+ }
413
+ });
414
+ else this.send({
415
+ kind: "result",
416
+ id: frame.id,
417
+ ts: Date.now(),
418
+ data: value ?? null
419
+ });
420
+ }
421
+ } catch (err) {
422
+ const error = err instanceof RpcError ? {
423
+ code: err.code,
424
+ message: err.message,
425
+ details: err.details
426
+ } : {
427
+ code: "INTERNAL",
428
+ message: err instanceof Error ? err.message : String(err)
429
+ };
430
+ this.send({
431
+ kind: "result",
432
+ id: frame.id,
433
+ ts: Date.now(),
434
+ error
435
+ });
436
+ } finally {
437
+ clearInterval(hbInterval);
438
+ this.runningHandlers.delete(frame.id);
439
+ }
440
+ }
441
+ onCancel(frame) {
442
+ const ac = this.runningHandlers.get(frame.id);
443
+ if (ac) ac.abort(frame.error?.message ?? "cancelled by caller");
444
+ }
445
+ };
446
+ function serializeTarget(t) {
447
+ switch (t.kind) {
448
+ case "role": return `role:${t.role}`;
449
+ case "user": return `user:${t.userId}`;
450
+ case "runner": return `runner:${t.sessionId}`;
451
+ }
452
+ }
453
+
454
+ //#endregion
455
+ export { RPC_PREFIX, RpcClient, RpcError };
456
+ //# sourceMappingURL=RpcClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RpcClient.js","names":[],"sources":["../../src/RpcClient.ts"],"sourcesContent":["import EventEmitter from \"./EventEmitter.ts\";\n\n/**\n * RPC v1 — request/response over `MSG_STATELESS`.\n *\n * Mirrors `docs/rpc-v1.md` in the abracadabra-rs server. Frames travel as\n * `MSG_STATELESS` payloads with the literal prefix `rpc:v1:` followed by a\n * JSON envelope. The provider's existing `sendStateless` / `stateless` event\n * stream is the only transport surface this layer touches; everything else\n * (state machine, deadlines, handler registry, dedupe of self-replies) lives\n * here.\n */\n\nexport const RPC_PREFIX = \"rpc:v1:\";\n\nexport type RpcKind =\n | \"req\"\n | \"ack\"\n | \"nack\"\n | \"progress\"\n | \"result\"\n | \"cancel\"\n | \"hb\"\n | \"register\"\n | \"unregister\";\n\nexport interface RpcFrame {\n kind: RpcKind;\n id: string;\n ts?: number;\n from?: string;\n to?: string;\n method?: string;\n args?: unknown;\n deadline_ms?: number;\n data?: unknown;\n error?: RpcErrorPayload;\n by?: \"server\" | \"runner\";\n runner_id?: string;\n seq?: number;\n methods?: string[];\n}\n\nexport interface RpcErrorPayload {\n code: string;\n message: string;\n details?: unknown;\n}\n\nexport type RpcErrorCode =\n | \"NO_HANDLER\"\n | \"HANDLER_GONE\"\n | \"TIMEOUT\"\n | \"CANCELLED\"\n | \"RATE_LIMITED\"\n | \"UNAUTHORIZED\"\n | \"SCHEMA\"\n | \"INTERNAL\"\n | \"APP\"\n | string; // forward-compat for unknown codes from runners\n\n/** Thrown by `rpc.call(...)` on terminal nack / error / timeout. */\nexport class RpcError extends Error {\n code: RpcErrorCode;\n details?: unknown;\n constructor(code: RpcErrorCode, message: string, details?: unknown) {\n super(message);\n this.name = \"RpcError\";\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Minimal provider surface RpcClient needs. The base provider already\n * satisfies it; the indirection is here so handlers can be tested against\n * a stub without booting a Y.Doc.\n */\nexport interface RpcTransport {\n sendStateless(payload: string): void;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n on(event: string, fn: Function): unknown;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n off(event: string, fn?: Function): unknown;\n}\n\nexport type RpcTarget =\n | { kind: \"role\"; role: \"service\" }\n | { kind: \"user\"; userId: string }\n | { kind: \"runner\"; sessionId: string };\n\nexport interface RpcCallOptions {\n /** Defaults to `{ kind: \"role\", role: \"service\" }`. */\n target?: RpcTarget;\n /** Wall-clock deadline in ms. Server clamps to its own ceiling. */\n deadline?: number;\n /** Abort the call (sends `rpc:cancel` to the runner). */\n signal?: AbortSignal;\n /** Fired when a runner claims the call (after the server ack). */\n onClaim?: (runnerId: string) => void;\n /** Fired for every `rpc:progress` frame the runner emits. */\n onProgress?: (data: unknown, seq: number) => void;\n}\n\nexport interface RpcCallHandle<T = unknown> extends Promise<T> {\n /** RPC id (UUID v7) — useful for log correlation. */\n readonly id: string;\n /** Runner session id, populated once a runner has claimed the call. */\n readonly claimedBy: string | undefined;\n /** Cancel the call. Equivalent to `signal.abort()` if a signal was passed. */\n cancel(reason?: string): void;\n}\n\ninterface PendingRpc {\n id: string;\n resolve: (value: unknown) => void;\n reject: (err: Error) => void;\n options: RpcCallOptions;\n state: \"pending\" | \"accepted\" | \"claimed\" | \"settled\";\n claimedBy: string | undefined;\n deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n}\n\n/**\n * Handler signature for a runner-side RPC handler.\n *\n * Returning a value emits `rpc:result(ok)`. Throwing emits\n * `rpc:result(err)` — `RpcError` instances pass through their `code` and\n * `details`; any other thrown value becomes `INTERNAL`.\n *\n * Returning an async generator turns each `yield` into a `rpc:progress`\n * frame (with monotonic `seq`); the generator's return value is the final\n * `result.data`.\n */\nexport type RpcHandler = (\n args: unknown,\n ctx: RpcHandlerContext,\n) =>\n | unknown\n | Promise<unknown>\n | AsyncGenerator<unknown, unknown, void>;\n\nexport interface RpcHandlerContext {\n id: string;\n method: string;\n /** Server-stamped caller user id. Trusted. */\n from: string;\n /** Aborted when the caller cancels or the deadline is reached. */\n signal: AbortSignal;\n}\n\n// ── UUID v7 (small inline impl) ─────────────────────────────────────────────\n\nfunction uuidv7(): string {\n // Minimal UUID v7 — time-ordered, 122 random bits.\n const ts = Date.now();\n const tsHex = ts.toString(16).padStart(12, \"0\");\n const rand = new Uint8Array(10);\n if (typeof crypto !== \"undefined\" && crypto.getRandomValues) {\n crypto.getRandomValues(rand);\n } else {\n for (let i = 0; i < rand.length; i++) rand[i] = Math.floor(Math.random() * 256);\n }\n // version=7, variant=10\n rand[0] = (rand[0] & 0x0f) | 0x70;\n rand[2] = (rand[2] & 0x3f) | 0x80;\n const hex = Array.from(rand, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return (\n `${tsHex.slice(0, 8)}-${tsHex.slice(8, 12)}-` +\n `${hex.slice(0, 4)}-${hex.slice(4, 8)}-${hex.slice(8, 20)}`\n );\n}\n\n// ── Client ──────────────────────────────────────────────────────────────────\n\n/**\n * Per-provider RPC layer. Construct one and attach by passing the provider\n * (or any `RpcTransport`). Disposes on `destroy()`.\n *\n * Caller side: `rpc.call('ai.summarize@1', { docId }, { onProgress })`.\n *\n * Runner side: `rpc.handle('ai.summarize@1', async (args, ctx) => …)`.\n */\nexport class RpcClient extends EventEmitter {\n private readonly transport: RpcTransport;\n private readonly pending = new Map<string, PendingRpc>();\n private readonly handlers = new Map<string, RpcHandler>();\n /** Tracks live runner-side invocations so we can route `rpc:cancel`. */\n private readonly runningHandlers = new Map<string, AbortController>();\n /** Pending register frames awaiting server ack — resolved by id. */\n private readonly pendingRegistrations = new Map<string, () => void>();\n /** Grace timer armed on `disconnect`; cancelled on `connect`. Fires\n * `HANDLER_GONE` on every pending RPC if the WS is still down after\n * the grace window. v1 used to wait `deadline + 5s` which could be\n * 35s on default deadlines — way too long for a definitively-dead\n * connection. */\n private disconnectGrace: ReturnType<typeof setTimeout> | undefined;\n private static readonly DISCONNECT_GRACE_MS = 10_000;\n private readonly onStatelessBound: (data: { payload: string }) => void;\n /**\n * Replays all live `register` frames whenever the underlying provider\n * (re)syncs — covers WebSocket reconnects where the server allocated a\n * new session id and the old capability entries were freed.\n */\n private readonly onSyncedBound: (data: { state: boolean }) => void;\n private readonly onDisconnectBound: () => void;\n private readonly onConnectBound: () => void;\n private destroyed = false;\n\n constructor(transport: RpcTransport) {\n super();\n this.transport = transport;\n this.onStatelessBound = (data) => this.receive(data.payload);\n this.onSyncedBound = (data) => {\n if (data.state) this.replayRegistrations();\n };\n this.onDisconnectBound = () => this.armDisconnectGrace();\n this.onConnectBound = () => this.cancelDisconnectGrace();\n transport.on(\"stateless\", this.onStatelessBound);\n transport.on(\"synced\", this.onSyncedBound);\n transport.on(\"disconnect\", this.onDisconnectBound);\n transport.on(\"connect\", this.onConnectBound);\n }\n\n private armDisconnectGrace(): void {\n if (this.destroyed) return;\n if (this.disconnectGrace) return; // already armed\n this.disconnectGrace = setTimeout(\n () => this.failPendingOnDisconnect(),\n RpcClient.DISCONNECT_GRACE_MS,\n );\n }\n\n private cancelDisconnectGrace(): void {\n if (this.disconnectGrace) {\n clearTimeout(this.disconnectGrace);\n this.disconnectGrace = undefined;\n }\n }\n\n /**\n * Called when the WS has been down for the full grace window. Every\n * in-flight call is dead from the server's perspective (its `close_session`\n * already fired `HANDLER_GONE` to a now-disconnected caller; on reconnect\n * the server-side session is fresh, so any cached cancel/result frames\n * the server tried to deliver were lost). Fail pending immediately.\n */\n private failPendingOnDisconnect(): void {\n this.disconnectGrace = undefined;\n if (this.destroyed) return;\n for (const [, p] of this.pending) {\n if (p.deadlineTimer) clearTimeout(p.deadlineTimer);\n this.settle(p, () =>\n p.reject(new RpcError(\"HANDLER_GONE\", \"websocket disconnected\")),\n );\n }\n }\n\n /**\n * Re-emit a `register` frame for every locally-known handler. Called on\n * every `synced` event from the provider, since a reconnected WS gets a\n * fresh server-side session with empty capability state.\n */\n private replayRegistrations(): void {\n if (this.destroyed) return;\n // A fresh server-side session will never ack any register frame issued\n // before this `synced` event, so prior pending entries are dead. Resolve\n // them with the current map clear so any awaiting `ready()` doesn't\n // hang forever — the new register below is the source of truth now.\n if (this.pendingRegistrations.size > 0) {\n const stale = [...this.pendingRegistrations.values()];\n this.pendingRegistrations.clear();\n for (const r of stale) r();\n }\n if (this.handlers.size === 0) return;\n const methods = [...this.handlers.keys()];\n const id = uuidv7();\n // Track this re-register so `ready()` resolves once the server ack lands.\n this.pendingRegistrations.set(id, () => {});\n this.send({ kind: \"register\", id, methods });\n }\n\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n this.transport.off(\"stateless\", this.onStatelessBound);\n this.transport.off(\"synced\", this.onSyncedBound);\n this.transport.off(\"disconnect\", this.onDisconnectBound);\n this.transport.off(\"connect\", this.onConnectBound);\n this.cancelDisconnectGrace();\n // Abort every in-flight handler.\n for (const [, ac] of this.runningHandlers) {\n try { ac.abort(); } catch { /* noop */ }\n }\n this.runningHandlers.clear();\n // Reject every pending caller.\n for (const [, p] of this.pending) {\n if (p.deadlineTimer) clearTimeout(p.deadlineTimer);\n p.reject(new RpcError(\"CANCELLED\", \"RpcClient destroyed\"));\n }\n this.pending.clear();\n // Unblock any awaiters of `ready()` — the WS is gone and no register\n // ack will ever land. Resolving (vs rejecting) keeps `ready(): Promise<void>`\n // semantically clean; the call sites that follow `ready()` are typically\n // diagnostic/orchestration, not request hot paths.\n for (const [, resolve] of this.pendingRegistrations) {\n try { resolve(); } catch { /* noop */ }\n }\n this.pendingRegistrations.clear();\n this.handlers.clear();\n this.removeAllListeners();\n }\n\n // ── Caller side ───────────────────────────────────────────────────────────\n\n /**\n * Send an RPC and return a handle that resolves with the runner's result.\n * Throws `RpcError` on nack / handler error / timeout / cancellation.\n */\n call<T = unknown>(method: string, args?: unknown, options?: RpcCallOptions): RpcCallHandle<T> {\n const opts = options ?? {};\n const id = uuidv7();\n const target = opts.target ?? { kind: \"role\", role: \"service\" };\n\n let resolve!: (value: unknown) => void;\n let reject!: (err: Error) => void;\n const promise = new Promise<unknown>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n // Calling on a destroyed client used to silently hang because `send()`\n // short-circuits but the pending entry was already created. Reject now\n // and skip the rest so consumers always get a terminal outcome.\n if (this.destroyed) {\n const handle = promise as RpcCallHandle<T>;\n Object.defineProperty(handle, \"id\", { value: id, enumerable: true });\n Object.defineProperty(handle, \"claimedBy\", { enumerable: true, get: () => undefined });\n handle.cancel = () => {};\n reject(new RpcError(\"CANCELLED\", \"rpc client destroyed\"));\n return handle;\n }\n\n // Pre-aborted signal: no point sending the `req` (the runner would do\n // wasted work for a caller that's already given up) and no point sending\n // a `cancel` for an id the server has never seen. Short-circuit cleanly.\n if (opts.signal?.aborted) {\n const reason = opts.signal.reason;\n const handle = promise as RpcCallHandle<T>;\n Object.defineProperty(handle, \"id\", { value: id, enumerable: true });\n Object.defineProperty(handle, \"claimedBy\", { enumerable: true, get: () => undefined });\n handle.cancel = () => {};\n reject(new RpcError(\"CANCELLED\", typeof reason === \"string\" ? reason : \"aborted\"));\n return handle;\n }\n\n const pending: PendingRpc = {\n id,\n resolve,\n reject,\n options: opts,\n state: \"pending\",\n claimedBy: undefined,\n deadlineTimer: undefined,\n };\n this.pending.set(id, pending);\n\n // Local fallback timeout so we don't wait past `deadline` if the server\n // somehow goes silent (it shouldn't — server enforces its own).\n const deadline = opts.deadline ?? 30_000;\n pending.deadlineTimer = setTimeout(() => {\n if (pending.state !== \"settled\") {\n this.settle(pending, () =>\n reject(new RpcError(\"TIMEOUT\", \"rpc deadline exceeded (client-side)\")),\n );\n }\n }, deadline + 5_000); // grace window so server-side TIMEOUT lands first\n\n // Pre-aborted signals were handled above (no req frame sent). For a live\n // signal, listen for abort and cancel mid-flight when it trips.\n if (opts.signal) {\n opts.signal.addEventListener(\n \"abort\",\n () => this.abortInFlight(pending, opts.signal?.reason),\n { once: true },\n );\n }\n\n const frame: RpcFrame = {\n kind: \"req\",\n id,\n ts: Date.now(),\n method,\n args,\n to: serializeTarget(target),\n deadline_ms: deadline,\n };\n this.send(frame);\n\n const handle = promise as RpcCallHandle<T>;\n Object.defineProperty(handle, \"id\", { value: id, enumerable: true });\n Object.defineProperty(handle, \"claimedBy\", {\n enumerable: true,\n get: () => pending.claimedBy,\n });\n handle.cancel = (reason?: string) => this.abortInFlight(pending, reason);\n return handle;\n }\n\n private abortInFlight(pending: PendingRpc, reason?: unknown): void {\n if (pending.state === \"settled\") return;\n // Tell the runner we're cancelling.\n this.send({ kind: \"cancel\", id: pending.id, ts: Date.now(), data: reason ? { reason: String(reason) } : undefined });\n // Reject locally; the server may still emit a CANCELLED result later\n // (we'll see it but the pending is gone, so it's a no-op).\n this.settle(pending, () =>\n pending.reject(new RpcError(\"CANCELLED\", typeof reason === \"string\" ? reason : \"cancelled\")),\n );\n }\n\n // ── Runner side ───────────────────────────────────────────────────────────\n\n /**\n * Register a handler for `method` and advertise it to the server so\n * incoming `to: role:service` calls resolve here. Returns an unsubscribe\n * function. Calling `register` twice for the same method replaces the\n * handler and re-advertises.\n *\n * The advertise is fire-and-forget; if you need to wait until the server\n * has acknowledged registration (typical in tests with a separate caller\n * connection), `await rpc.ready()` after registering all handlers.\n */\n handle(method: string, handler: RpcHandler): () => void {\n this.handlers.set(method, handler);\n const id = uuidv7();\n this.pendingRegistrations.set(id, () => {\n // Default no-op; overwritten when ready() is awaited.\n });\n this.send({ kind: \"register\", id, methods: [method] });\n return () => {\n if (this.handlers.get(method) === handler) {\n this.handlers.delete(method);\n this.send({ kind: \"unregister\", id: uuidv7(), methods: [method] });\n }\n };\n }\n\n /**\n * Resolve once every outstanding `register` frame has been acknowledged\n * by the server. Useful when a separate connection is about to issue\n * `rpc.call(...)` and you need the capability registry to be live first.\n * Resolves immediately if there's nothing pending.\n */\n ready(): Promise<void> {\n if (this.pendingRegistrations.size === 0) return Promise.resolve();\n const ids = [...this.pendingRegistrations.keys()];\n return Promise.all(\n ids.map(\n (id) =>\n new Promise<void>((resolve) => {\n this.pendingRegistrations.set(id, resolve);\n }),\n ),\n ).then(() => undefined);\n }\n\n // ── Wire ───────────────────────────────────────────────────────────────────\n\n private send(frame: Partial<RpcFrame> & Pick<RpcFrame, \"kind\" | \"id\">): void {\n if (this.destroyed) return;\n const payload = `${RPC_PREFIX}${JSON.stringify(frame)}`;\n this.transport.sendStateless(payload);\n }\n\n private receive(payload: string): void {\n if (!payload.startsWith(RPC_PREFIX)) return;\n const json = payload.slice(RPC_PREFIX.length);\n let frame: RpcFrame;\n try {\n frame = JSON.parse(json) as RpcFrame;\n } catch {\n return;\n }\n switch (frame.kind) {\n case \"ack\": return this.onAck(frame);\n case \"progress\": return this.onProgress(frame);\n case \"result\": return this.onResult(frame);\n case \"nack\": return this.onNack(frame);\n case \"req\": return void this.onReq(frame);\n case \"cancel\": return this.onCancel(frame);\n // hb / register / unregister never travel client-bound.\n default: return;\n }\n }\n\n private onAck(frame: RpcFrame): void {\n // Register-ack: server confirmed a `register` frame.\n const pendingReg = this.pendingRegistrations.get(frame.id);\n if (pendingReg) {\n this.pendingRegistrations.delete(frame.id);\n pendingReg();\n return;\n }\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n if (frame.by === \"server\" && pending.state === \"pending\") {\n pending.state = \"accepted\";\n } else if (frame.by === \"runner\") {\n pending.state = \"claimed\";\n pending.claimedBy = frame.runner_id;\n pending.options.onClaim?.(frame.runner_id ?? \"\");\n }\n }\n\n private onProgress(frame: RpcFrame): void {\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n pending.options.onProgress?.(frame.data, frame.seq ?? 0);\n }\n\n private onResult(frame: RpcFrame): void {\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n if (frame.error) {\n const err = new RpcError(frame.error.code, frame.error.message, frame.error.details);\n this.settle(pending, () => pending.reject(err));\n } else {\n this.settle(pending, () => pending.resolve(frame.data));\n }\n }\n\n private onNack(frame: RpcFrame): void {\n const pending = this.pending.get(frame.id);\n if (!pending) return;\n const err = frame.error\n ? new RpcError(frame.error.code, frame.error.message, frame.error.details)\n : new RpcError(\"INTERNAL\", \"rpc nack\");\n this.settle(pending, () => pending.reject(err));\n }\n\n private settle(pending: PendingRpc, finalize: () => void): void {\n if (pending.state === \"settled\") return;\n pending.state = \"settled\";\n if (pending.deadlineTimer) clearTimeout(pending.deadlineTimer);\n this.pending.delete(pending.id);\n finalize();\n }\n\n // ── Inbound request (runner side) ─────────────────────────────────────────\n\n private async onReq(frame: RpcFrame): Promise<void> {\n const method = frame.method ?? \"\";\n const handler = this.handlers.get(method);\n if (!handler) {\n // Server should have nacked NO_HANDLER before we got here; ignore.\n return;\n }\n if (this.runningHandlers.has(frame.id)) {\n // Duplicate req — server retry path. Server will re-emit the cached\n // terminal frame on its own; we just don't double-invoke.\n return;\n }\n const ac = new AbortController();\n this.runningHandlers.set(frame.id, ac);\n\n // Send the runner-claim ack immediately.\n this.send({\n kind: \"ack\",\n id: frame.id,\n ts: Date.now(),\n by: \"runner\",\n });\n\n const ctx: RpcHandlerContext = {\n id: frame.id,\n method,\n from: frame.from ?? \"\",\n signal: ac.signal,\n };\n\n // Heartbeat while the handler runs. The server doesn't enforce\n // inactivity in v1 but we send these so tooling can observe liveness\n // and a v2 server can fail stalled calls.\n const hbInterval = setInterval(() => {\n if (!ac.signal.aborted) {\n this.send({ kind: \"hb\", id: frame.id, ts: Date.now() });\n }\n }, 5_000);\n\n try {\n const ret = handler(frame.args, ctx);\n if (ret && typeof (ret as AsyncGenerator).next === \"function\" && typeof (ret as AsyncGenerator)[Symbol.asyncIterator] === \"function\") {\n // Generator: stream progress, return final.\n const gen = ret as AsyncGenerator<unknown, unknown, void>;\n let seq = 0;\n let final: unknown = undefined;\n while (true) {\n const { value, done } = await gen.next();\n if (done) {\n final = value;\n break;\n }\n if (ac.signal.aborted) break;\n this.send({ kind: \"progress\", id: frame.id, ts: Date.now(), seq: seq++, data: value });\n }\n if (ac.signal.aborted) {\n this.send({\n kind: \"result\",\n id: frame.id,\n ts: Date.now(),\n error: { code: \"CANCELLED\", message: \"handler cancelled\" },\n });\n } else {\n this.send({ kind: \"result\", id: frame.id, ts: Date.now(), data: final ?? null });\n }\n } else {\n const value = await (ret as Promise<unknown>);\n if (ac.signal.aborted) {\n this.send({\n kind: \"result\",\n id: frame.id,\n ts: Date.now(),\n error: { code: \"CANCELLED\", message: \"handler cancelled\" },\n });\n } else {\n this.send({ kind: \"result\", id: frame.id, ts: Date.now(), data: value ?? null });\n }\n }\n } catch (err) {\n const error =\n err instanceof RpcError\n ? { code: err.code, message: err.message, details: err.details }\n : { code: \"INTERNAL\", message: err instanceof Error ? err.message : String(err) };\n this.send({ kind: \"result\", id: frame.id, ts: Date.now(), error });\n } finally {\n clearInterval(hbInterval);\n this.runningHandlers.delete(frame.id);\n }\n }\n\n private onCancel(frame: RpcFrame): void {\n // The runner only ever observes `cancel` for an id whose `req` it has\n // already seen — frame ordering on a single WS preserves the\n // (req, cancel) sequence the server emits. If `runningHandlers` has\n // no entry for this id, the handler has already completed (cancel\n // arrived after result), so the cancel is informational and can be\n // dropped silently.\n const ac = this.runningHandlers.get(frame.id);\n if (ac) ac.abort(frame.error?.message ?? \"cancelled by caller\");\n }\n}\n\nfunction serializeTarget(t: RpcTarget): string {\n switch (t.kind) {\n case \"role\": return `role:${t.role}`;\n case \"user\": return `user:${t.userId}`;\n case \"runner\": return `runner:${t.sessionId}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,aAAa;;AAiD1B,IAAa,WAAb,cAA8B,MAAM;CAGlC,YAAY,MAAoB,SAAiB,SAAmB;AAClE,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,UAAU;;;AAoFnB,SAAS,SAAiB;CAGxB,MAAM,QADK,KAAK,KAAK,CACJ,SAAS,GAAG,CAAC,SAAS,IAAI,IAAI;CAC/C,MAAM,OAAO,IAAI,WAAW,GAAG;AAC/B,KAAI,OAAO,WAAW,eAAe,OAAO,gBAC1C,QAAO,gBAAgB,KAAK;KAE5B,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,IAAK,MAAK,KAAK,KAAK,MAAM,KAAK,QAAQ,GAAG,IAAI;AAGjF,MAAK,KAAM,KAAK,KAAK,KAAQ;AAC7B,MAAK,KAAM,KAAK,KAAK,KAAQ;CAC7B,MAAM,MAAM,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,KAAK,GAAG;AAC7E,QACE,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,MAAM,MAAM,GAAG,GAAG,CAAC,GACxC,IAAI,MAAM,GAAG,EAAE,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,GAAG,IAAI,MAAM,GAAG,GAAG;;;;;;;;;;AAc7D,IAAa,YAAb,MAAa,kBAAkB,aAAa;;6BAcI;;CAY9C,YAAY,WAAyB;AACnC,SAAO;iCAzBkB,IAAI,KAAyB;kCAC5B,IAAI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AAK,OAAU,QAAO,QAAQ,EAAE;EAChC,KAAK,SAAU,QAAO,UAAU,EAAE"}
@@ -0,0 +1,38 @@
1
+ //#region packages/provider/src/SchemaTypes.ts
2
+ /**
3
+ * Thrown by typed write methods on `TypedDocsClient` when the stored
4
+ * entry's `type` doesn't match the caller's `expectedType`. Distinct from
5
+ * `MetaValidationError` (which signals schema-content mismatches).
6
+ */
7
+ var TypedDocTypeMismatchError = class extends Error {
8
+ constructor(docId, expectedType, actualType) {
9
+ super(`Typed write on document ${docId} expected type "${expectedType}" but stored type is ${actualType === void 0 ? "(none)" : `"${actualType}"`}`);
10
+ this.name = "TypedDocTypeMismatchError";
11
+ this.docId = docId;
12
+ this.expectedType = expectedType;
13
+ this.actualType = actualType;
14
+ }
15
+ };
16
+ /**
17
+ * Project a raw `TreeEntry` to a `TypedTreeEntry<TMap, N>` if its `type`
18
+ * matches; otherwise return `null`. Used by both `TreeManager.getTyped`
19
+ * and `TypedDocsClient.{get,narrow}` to keep semantics consistent.
20
+ */
21
+ function projectTreeEntry(entry, expectedType) {
22
+ if (!entry) return null;
23
+ if (entry.type !== expectedType) return null;
24
+ return {
25
+ id: entry.id,
26
+ type: expectedType,
27
+ label: entry.label,
28
+ parentId: entry.parentId,
29
+ order: entry.order,
30
+ meta: entry.meta,
31
+ createdAt: entry.createdAt,
32
+ updatedAt: entry.updatedAt
33
+ };
34
+ }
35
+
36
+ //#endregion
37
+ export { TypedDocTypeMismatchError, projectTreeEntry };
38
+ //# sourceMappingURL=SchemaTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SchemaTypes.js","names":[],"sources":["../../src/SchemaTypes.ts"],"sourcesContent":["/**\n * Phase 2 Day 1 — typed projection types for the provider.\n *\n * The provider package never imports `@abraca/schema` directly (Rule 1 —\n * core stays schema-free). Instead, it declares a structural witness that\n * any registry — including `@abraca/schema`'s `SchemaRegistry<TMap>` — can\n * satisfy.\n *\n * Consumers parameterise typed accessors with the registry value:\n *\n * const board = dm.tree.getTyped(kanbanSchema, \"kanban\", id);\n * // board.meta.kanbanColumnWidth is typed as the kanban enum | undefined\n *\n * The phantom `__metaMap` carries the per-doc-type meta map so the\n * generics below can extract it without a runtime dependency.\n */\nimport type { PageMeta, TreeEntry } from \"./DocTypes.ts\";\n\n/**\n * Structural shape of a typed schema registry. The `TMap` parameter is the\n * meta-type map keyed by doc-type name (e.g. `{ \"kanban\": KanbanMeta, ... }`).\n * `@abraca/schema`'s `SchemaRegistry<TMap>` satisfies this shape.\n */\nexport interface SchemaRegistryLike<\n\tTMap extends Record<string, unknown> = Record<string, unknown>,\n> {\n\treadonly types: ReadonlyMap<string, unknown>;\n\treadonly __metaMap?: TMap;\n}\n\n/** Extract the doc-type names from a registry. */\nexport type SchemaDocTypeName<S> =\n\tS extends SchemaRegistryLike<infer M> ? keyof M & string : never;\n\n/** Extract the meta type for a given doc-type name from a registry. */\nexport type SchemaMetaOf<S, N extends string> =\n\tS extends SchemaRegistryLike<infer M>\n\t\t? N extends keyof M\n\t\t\t? M[N]\n\t\t\t: never\n\t\t: never;\n\n/**\n * A tree entry projected against a typed registry. The `meta` field is\n * narrowed to `TMap[N] | undefined` so consumers get full type inference\n * without an explicit cast.\n *\n * Note: `meta` is optional even when the registry mandates fields — the\n * tree may contain entries written before the schema was authored, and\n * Rule 4 means we don't reject them at read time.\n */\nexport interface TypedTreeEntry<\n\tTMap extends Record<string, unknown>,\n\tN extends keyof TMap & string,\n> {\n\treadonly id: string;\n\treadonly type: N;\n\treadonly label: string;\n\treadonly parentId: string | null;\n\treadonly order: number;\n\treadonly meta: TMap[N] | undefined;\n\treadonly createdAt: number | undefined;\n\treadonly updatedAt: number | undefined;\n}\n\n/**\n * A typed surface bound to a schema. Returned by\n * `DocumentManager.docs(schema)` so the schema doesn't have to be repeated\n * at every call site.\n *\n * Read methods (`get`, `getEntry`, `narrow`) project the existing\n * untyped tree without performing schema validation. Write methods\n * (`update`, `set`, `clear`) delegate to `MetaManager` and are subject\n * to whatever validator was attached via `MetaManager.setSchema` —\n * they do NOT auto-attach the registry passed to `dm.docs()`.\n */\nexport interface TypedDocsClient<TMap extends Record<string, unknown>> {\n\t/**\n\t * Fetch a tree entry projected as the requested doc-type. Returns\n\t * `null` when the entry doesn't exist OR when its `type` field doesn't\n\t * match `expectedType`.\n\t */\n\tget<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t): TypedTreeEntry<TMap, N> | null;\n\t/**\n\t * Fetch the raw, untyped entry (no type-narrowing applied). Useful when\n\t * the caller wants the underlying record without the projection.\n\t */\n\tgetEntry(id: string): TreeEntry | null;\n\t/**\n\t * Discriminator helper: narrows an arbitrary `TreeEntry` to the\n\t * requested doc-type, returning a typed projection or `null` on mismatch.\n\t * No runtime read — pure type-guard helper.\n\t */\n\tnarrow<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tentry: TreeEntry | null | undefined,\n\t): TypedTreeEntry<TMap, N> | null;\n\t/**\n\t * Merge typed meta into a document's metadata. Throws\n\t * `TypedDocTypeMismatchError` when the stored entry's `type` doesn't\n\t * match `expectedType`; throws `MetaValidationError` when a validator\n\t * is attached and the merged meta fails validation.\n\t */\n\tupdate<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t\tmeta: Partial<TMap[N]>,\n\t): void;\n\t/**\n\t * Replace all metadata on a document with a fully-typed payload.\n\t * Same throw semantics as `update`.\n\t */\n\tset<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t\tmeta: TMap[N],\n\t): void;\n\t/**\n\t * Delete specific metadata keys. Constrained to the typed key-set of\n\t * `TMap[N]` so typos surface at compile time.\n\t */\n\tclear<N extends keyof TMap & string>(\n\t\texpectedType: N,\n\t\tid: string,\n\t\tkeys: ReadonlyArray<keyof TMap[N] & string>,\n\t): void;\n}\n\n/**\n * Thrown by typed write methods on `TypedDocsClient` when the stored\n * entry's `type` doesn't match the caller's `expectedType`. Distinct from\n * `MetaValidationError` (which signals schema-content mismatches).\n */\nexport class TypedDocTypeMismatchError extends Error {\n\treadonly docId: string;\n\treadonly expectedType: string;\n\treadonly actualType: string | undefined;\n\tconstructor(docId: string, expectedType: string, actualType: string | undefined) {\n\t\tsuper(\n\t\t\t`Typed write on document ${docId} expected type \"${expectedType}\" but stored type is ${\n\t\t\t\tactualType === undefined ? \"(none)\" : `\"${actualType}\"`\n\t\t\t}`,\n\t\t);\n\t\tthis.name = \"TypedDocTypeMismatchError\";\n\t\tthis.docId = docId;\n\t\tthis.expectedType = expectedType;\n\t\tthis.actualType = actualType;\n\t}\n}\n\n// ── Internal: shared projection helper ──────────────────────────────────────\n\n/**\n * Project a raw `TreeEntry` to a `TypedTreeEntry<TMap, N>` if its `type`\n * matches; otherwise return `null`. Used by both `TreeManager.getTyped`\n * and `TypedDocsClient.{get,narrow}` to keep semantics consistent.\n */\nexport function projectTreeEntry<\n\tTMap extends Record<string, unknown>,\n\tN extends keyof TMap & string,\n>(entry: TreeEntry | null | undefined, expectedType: N):\n\tTypedTreeEntry<TMap, N> | null\n{\n\tif (!entry) return null;\n\tif (entry.type !== expectedType) return null;\n\treturn {\n\t\tid: entry.id,\n\t\ttype: expectedType,\n\t\tlabel: entry.label,\n\t\tparentId: entry.parentId,\n\t\torder: entry.order,\n\t\tmeta: entry.meta as (TMap[N] & PageMeta) | undefined,\n\t\tcreatedAt: entry.createdAt,\n\t\tupdatedAt: entry.updatedAt,\n\t};\n}\n"],"mappings":";;;;;;AAwIA,IAAa,4BAAb,cAA+C,MAAM;CAIpD,YAAY,OAAe,cAAsB,YAAgC;AAChF,QACC,2BAA2B,MAAM,kBAAkB,aAAa,uBAC/D,eAAe,SAAY,WAAW,IAAI,WAAW,KAEtD;AACD,OAAK,OAAO;AACZ,OAAK,QAAQ;AACb,OAAK,eAAe;AACpB,OAAK,aAAa;;;;;;;;AAWpB,SAAgB,iBAGd,OAAqC,cAEvC;AACC,KAAI,CAAC,MAAO,QAAO;AACnB,KAAI,MAAM,SAAS,aAAc,QAAO;AACxC,QAAO;EACN,IAAI,MAAM;EACV,MAAM;EACN,OAAO,MAAM;EACb,UAAU,MAAM;EAChB,OAAO,MAAM;EACb,MAAM,MAAM;EACZ,WAAW,MAAM;EACjB,WAAW,MAAM;EACjB"}