@vercel/board 0.56.1 → 0.57.1

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 (96) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-HzqFpgL_.mjs → access-CZ419Vho.mjs} +1 -1
  3. package/dist/access.d.mts +2 -2
  4. package/dist/access.mjs +4 -4
  5. package/dist/{actors-D-u6bitG.mjs → actors-CXMWplob.mjs} +2 -2
  6. package/dist/{auth-D9ycDQK0.mjs → auth-AwZJQpCO.mjs} +2 -2
  7. package/dist/{auth-ULldUvir.d.mts → auth-C0Mla9OU.d.mts} +1 -1
  8. package/dist/{backend-BHN6GTjB.d.mts → backend-BuqwQbb4.d.mts} +6 -22
  9. package/dist/backend-local.d.mts +1 -1
  10. package/dist/backend-local.mjs +1 -1
  11. package/dist/backend-postgres/blob-vercel.d.mts +8 -0
  12. package/dist/backend-postgres/blob-vercel.mjs +81 -0
  13. package/dist/backend-postgres/scheduler-vercel.d.mts +2 -0
  14. package/dist/backend-postgres/scheduler-vercel.mjs +2 -0
  15. package/dist/backend-postgres.d.mts +74 -0
  16. package/dist/backend-postgres.mjs +3229 -0
  17. package/dist/blob-DjS53D1A.d.mts +35 -0
  18. package/dist/{chat-provider-F7UqWVZK.d.mts → chat-provider-CpYdXEpI.d.mts} +2 -2
  19. package/dist/cli-commands.d.mts +1 -1
  20. package/dist/cli-commands.mjs +1 -1
  21. package/dist/cli-embedded.d.mts +2 -2
  22. package/dist/cli-embedded.mjs +2 -2
  23. package/dist/cli.mjs +6 -6
  24. package/dist/{client-CFHunEFn.d.mts → client-B0DGOt7P.d.mts} +1 -1
  25. package/dist/{commands-DLPIX7Jw.d.mts → commands-Dcm4_pc1.d.mts} +3 -3
  26. package/dist/{commands-7FY_8p92.mjs → commands-DeYAQUcP.mjs} +10 -5
  27. package/dist/{conformance-BNiLcKra.mjs → conformance-EtEq22w1.mjs} +2 -2
  28. package/dist/conformance.d.mts +1 -1
  29. package/dist/conformance.mjs +1 -1
  30. package/dist/{engine-C8wCzkw-.mjs → engine-CfVTyEeo.mjs} +3 -3
  31. package/dist/errors-DBZtbfph.d.mts +19 -0
  32. package/dist/{errors-DDfXnZ2b.mjs → errors-DjatfYjl.mjs} +220 -18
  33. package/dist/{exports-DSX-CI5c.mjs → exports-B_UGnrnN.mjs} +187 -62
  34. package/dist/{exports-BBmjHyCB.d.mts → exports-BvJTIorX.d.mts} +5 -4
  35. package/dist/{index-Ce3SDZ3Y.d.mts → index-DuibwQf9.d.mts} +2 -2
  36. package/dist/index.d.mts +6 -5
  37. package/dist/index.mjs +4 -4
  38. package/dist/index.node.d.mts +7 -6
  39. package/dist/index.node.mjs +4 -4
  40. package/dist/inspect/app.js +126 -146
  41. package/dist/inspect/engine.js +3 -3
  42. package/dist/inspect/sheet-presentation.js +1 -0
  43. package/dist/{inspect-C-vDnB_n.mjs → inspect-DfJzHFiE.mjs} +2 -2
  44. package/dist/inspect-H1MISWwN.mjs +2 -0
  45. package/dist/inspect.d.mts +1 -1
  46. package/dist/inspect.mjs +1 -1
  47. package/dist/{internal-CvsrprnU-CEPOUpAv.mjs → internal-CvsrprnU-DhZF6sZK.mjs} +43 -1
  48. package/dist/local-BiG1WJk0.mjs +98 -0
  49. package/dist/{local-B5aZcAwj.mjs → local-D2i5sxuY.mjs} +141 -3957
  50. package/dist/{main-DSlpMoBN.mjs → main-Bbqg3Unf.mjs} +167 -38
  51. package/dist/{memory-wmUDblhm.mjs → memory-BmsyKyHu.mjs} +3 -3
  52. package/dist/{mentions-CnWt9Z5b.mjs → mentions-DBGmqkr2.mjs} +5 -1
  53. package/dist/{middleware-BY4qqIh3.mjs → middleware-D2AGrGj7.mjs} +2 -32
  54. package/dist/{provider-DgGp4Zej.d.mts → provider-BNVyVKtH.d.mts} +2 -2
  55. package/dist/{routes-DNmQSOvQ.d.mts → routes-CSnxZyyb.d.mts} +2 -2
  56. package/dist/{serve-CI3kvpx_.mjs → serve-D06-DMej.mjs} +6 -6
  57. package/dist/{server-55vryxAl.mjs → server-BXbcS-n9.mjs} +27 -12
  58. package/dist/server-DX7mM6nm-Cq1xPyqJ.mjs +3769 -0
  59. package/dist/{serving-C1mhZQqH.mjs → serving-B2BNr4PR.mjs} +1 -1
  60. package/dist/{shell-7nGyF--f.mjs → shell-C8EowDEz.mjs} +15 -7
  61. package/dist/{sql-D0MqINA6.mjs → sql-CvBbb5Ui.mjs} +33 -22
  62. package/dist/{sqlite-Dj2ZEtgy.mjs → sqlite-B9ZLSDUT.mjs} +3 -3
  63. package/dist/{sqlite-db-DjbTlUwN.mjs → sqlite-db-DawFxCk6.mjs} +22 -7
  64. package/dist/store-N8PXxDAS-DWWgv-Vz.mjs +5 -0
  65. package/dist/{store-N8PXxDAS-BdL4Sq-f.mjs → store-codec-pAG2oPgQ-DbEYfF5Y.mjs} +2 -6
  66. package/dist/{store-memory-CKQVEzXN.mjs → store-memory-DOMraCLN.mjs} +3 -2
  67. package/dist/store-memory-XNDFHASI.mjs +2 -0
  68. package/dist/{store-polling-BZt2Rf3D-oh3aU_An.mjs → store-polling-BZt2Rf3D-nlZUQLz2.mjs} +1 -1
  69. package/dist/store-sqlite-Cs8dH9EX.mjs +2 -0
  70. package/dist/{store-sqlite-D6fIszST.mjs → store-sqlite-DUdQnX_6.mjs} +4 -3
  71. package/dist/sync-chat-sdk.d.mts +2 -2
  72. package/dist/sync-github.d.mts +2 -2
  73. package/dist/sync-linear.d.mts +3 -3
  74. package/dist/sync-slack.d.mts +3 -3
  75. package/dist/sync-slack.mjs +1 -1
  76. package/dist/sync.d.mts +2 -2
  77. package/dist/{task-batch-iecHMssy.mjs → task-batch-YMVr_c5R.mjs} +4 -4
  78. package/dist/{tokens-B3gXkQCs.mjs → tokens-CaEPmiG1.mjs} +2 -2
  79. package/dist/vercel-B5FM4uS8.d.mts +21 -0
  80. package/dist/vercel-BUb8II-P.mjs +305 -0
  81. package/dist/{version-gbihG3ui.mjs → version-BRR9FkLa.mjs} +1 -1
  82. package/docs/01-board/01-mounting.md +10 -0
  83. package/docs/01-board/05-reading.md +2 -1
  84. package/docs/01-board/09-access.md +8 -4
  85. package/docs/01-board/11-tasks.md +1 -1
  86. package/docs/01-board/12-postgres.md +222 -0
  87. package/docs/03-guides/02-inspector.md +34 -1
  88. package/docs/03-guides/07-build-a-ui.md +8 -4
  89. package/docs/04-reference/01-cli.md +1 -1
  90. package/docs/04-reference/03-http.md +2 -1
  91. package/docs/index.md +4 -1
  92. package/package.json +32 -3
  93. package/sql/postgres/schema.sql +389 -0
  94. package/dist/inspect-CJ8osLQ-.mjs +0 -2
  95. package/dist/store-memory-OdGsc-t_.mjs +0 -2
  96. package/dist/store-sqlite-CTxAVCcz.mjs +0 -2
@@ -0,0 +1,3769 @@
1
+ import { E as sessionClearedError, S as asStoreUnavailable, _ as serverInternals, a as RESERVED_PARTICIPANT_IDS, c as STREAM_TIMINGS, d as drainSettledHooks, f as failedPreviousAttempt, g as runtimeConsumers, h as runtimeConsumerFactory, i as PRESENCE_TIMINGS, m as nullProtoRecord, o as SOCKET_TIMINGS, p as markSchedulerSendFailure, r as POLL_TIMINGS, s as STATE_CACHE, t as DRAIN_TIMINGS, v as stateTailReaders, w as isSessionCleared, x as NonRetriableError, y as A2Error } from "./internal-CvsrprnU-DhZF6sZK.mjs";
2
+ import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-nlZUQLz2.mjs";
3
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/reducer-Bswr11ar.js
4
+ /**
5
+ * Run a Standard Schema validator, requiring a synchronous result.
6
+ * Validators must be synchronous (specs/a2-api.md §1) — an async one is
7
+ * a definition bug, rejected at definition time where possible and here
8
+ * as a backstop. `what` names the schema in error messages, e.g.
9
+ * "event 'created'" or "the stateSchema".
10
+ */
11
+ function validateSync(schema, value, what) {
12
+ const result = schema["~standard"].validate(value);
13
+ if (result instanceof Promise) throw new TypeError(`the schema for ${what} is asynchronous — a2 schemas must validate synchronously`);
14
+ return result;
15
+ }
16
+ /**
17
+ * Probe a schema to reject always-async validators early. The probe
18
+ * value is deliberately garbage — we only care whether the result is a
19
+ * Promise, not whether it passes.
20
+ */
21
+ function assertSyncSchema(schema, what) {
22
+ const probe = Symbol("a2.schema-probe");
23
+ const result = schema["~standard"].validate(probe);
24
+ if (result instanceof Promise) {
25
+ result.catch(() => {});
26
+ throw new TypeError(`the schema for ${what} is asynchronous — a2 schemas must validate synchronously`);
27
+ }
28
+ }
29
+ /**
30
+ * A fresh copy of a reducer's seed, so a fold that mutates in place
31
+ * cannot corrupt the shared `initialState`. Non-cloneable seeds
32
+ * (functions, class instances, proxies) fall back to the original.
33
+ */
34
+ function cloneInitial(initial) {
35
+ try {
36
+ return structuredClone(initial);
37
+ } catch {
38
+ return initial;
39
+ }
40
+ }
41
+ const markerFolds = /* @__PURE__ */ new WeakSet();
42
+ /** One fold step; a clear marker resets to the seed on server and client alike. */
43
+ function foldEvent(source, state, event) {
44
+ if (!isSessionCleared(event)) return source.fold(state, event);
45
+ return markerFolds.has(source.fold) ? source.fold(state, event) : cloneInitial(source.initialState);
46
+ }
47
+ /** Internal — shared validation for inline and standalone reducer definitions. */
48
+ function makeReducerBuilder(events, presence, options) {
49
+ const { name } = options;
50
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("reducer name must be a non-empty string — it identifies the reducer and keys cached snapshots");
51
+ let initialState = options.initialState;
52
+ if (options.stateSchema) {
53
+ const result = validateSync(options.stateSchema, options.initialState, "the stateSchema");
54
+ if (result.issues) throw new TypeError(`reducer initialState does not match its stateSchema: ${result.issues.map((issue) => issue.message).join("; ")}`);
55
+ initialState = result.value;
56
+ const restored = validateSync(options.stateSchema, initialState, "the stateSchema");
57
+ if (restored.issues || JSON.stringify(restored.value) !== JSON.stringify(initialState)) throw new TypeError("stateSchema must accept and preserve its own output so snapshots can be restored");
58
+ }
59
+ return { fold(fold) {
60
+ if (typeof fold !== "function") throw new TypeError("reducer fold must be a function");
61
+ return {
62
+ name,
63
+ events,
64
+ presence,
65
+ fold,
66
+ initialState,
67
+ stateSchema: options.stateSchema
68
+ };
69
+ } };
70
+ }
71
+ function reducer(options) {
72
+ return makeReducerBuilder(options.contract.events, options.contract.presence, options);
73
+ }
74
+ //#endregion
75
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/reducer-runtime-DQwz_J59.js
76
+ const runtimeKey = Symbol("a2.reducerRuntime");
77
+ function encodeState(options) {
78
+ const storage = options.reducer[runtimeKey]?.storage;
79
+ return storage ? storage.encode(options.state) : options.state;
80
+ }
81
+ function decodeState(options) {
82
+ const storage = options.reducer[runtimeKey]?.storage;
83
+ return storage ? storage.decode(options.state) : options.state;
84
+ }
85
+ //#endregion
86
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/bounded-cache-CPHWF-8h.js
87
+ function boundedCache({ maxEntries, maxBytes }) {
88
+ const entries = /* @__PURE__ */ new Map();
89
+ let total = 0;
90
+ const remove = (key) => {
91
+ const entry = entries.get(key);
92
+ if (!entry) return;
93
+ entries.delete(key);
94
+ total -= entry.bytes;
95
+ };
96
+ return {
97
+ get(key) {
98
+ const entry = entries.get(key);
99
+ if (!entry) return void 0;
100
+ entries.delete(key);
101
+ entries.set(key, entry);
102
+ return entry.value;
103
+ },
104
+ set(key, value, bytes) {
105
+ remove(key);
106
+ if (bytes > maxBytes / 4) return;
107
+ entries.set(key, {
108
+ value,
109
+ bytes
110
+ });
111
+ total += bytes;
112
+ for (const oldest of entries.keys()) {
113
+ if (entries.size <= maxEntries && total <= maxBytes) break;
114
+ remove(oldest);
115
+ }
116
+ },
117
+ delete: remove,
118
+ deleteWhere(match) {
119
+ for (const key of entries.keys()) if (match(key)) remove(key);
120
+ }
121
+ };
122
+ }
123
+ //#endregion
124
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/stream-buffer-DrTyiIuo.js
125
+ const key = ({ participant, field }) => JSON.stringify([participant, field]);
126
+ function presenceTombstones() {
127
+ const stamps = /* @__PURE__ */ new Map();
128
+ const prune = () => {
129
+ const cutoff = Date.now() - PRESENCE_TIMINGS.tombstoneMs;
130
+ for (const [id, stamp] of stamps) {
131
+ if (stamp.keptAtMs > cutoff) return;
132
+ stamps.delete(id);
133
+ }
134
+ };
135
+ return {
136
+ outranks(write) {
137
+ if (stamps.size === 0) return false;
138
+ prune();
139
+ const stamp = stamps.get(key(write));
140
+ return stamp !== void 0 && stamp.atMs > write.at.getTime();
141
+ },
142
+ keep(deletion) {
143
+ prune();
144
+ const id = key(deletion);
145
+ stamps.delete(id);
146
+ stamps.set(id, {
147
+ atMs: deletion.at.getTime(),
148
+ keptAtMs: Date.now()
149
+ });
150
+ },
151
+ drop(field) {
152
+ if (stamps.size > 0) stamps.delete(key(field));
153
+ }
154
+ };
155
+ }
156
+ const isSerializedEvent = (event) => "payloadJson" in event;
157
+ const parseSerializedEvent = (event) => ({
158
+ id: event.id,
159
+ type: event.type,
160
+ payload: JSON.parse(event.payloadJson),
161
+ index: event.index,
162
+ sessionId: event.sessionId,
163
+ createdAt: new Date(event.createdAtMs)
164
+ });
165
+ /**
166
+ * The next event a stream iterator already holds, removed without
167
+ * awaiting its `next()`, which then continues after it; `undefined` when
168
+ * it holds none. Call only while no `next()` is pending. The SSE encoder
169
+ * writes these with the event `next()` just returned, so a buffered
170
+ * backlog leaves in few writes.
171
+ */
172
+ const bufferedEvents = /* @__PURE__ */ new WeakMap();
173
+ const takeBuffered = (iterator) => bufferedEvents.get(iterator)?.();
174
+ //#endregion
175
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/platform-B4TnJtWu.js
176
+ const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
177
+ function requestContext() {
178
+ try {
179
+ return Reflect.get(globalThis, SYMBOL_FOR_REQ_CONTEXT)?.get?.() ?? {};
180
+ } catch {
181
+ return {};
182
+ }
183
+ }
184
+ function platformWaitUntil(promise) {
185
+ try {
186
+ requestContext().waitUntil?.(promise);
187
+ } catch {}
188
+ }
189
+ /** The invocation's termination time in epoch ms, or null if unknowable. */
190
+ function invocationDeadlineMs() {
191
+ const deadline = requestContext().deadline;
192
+ if (deadline === void 0 || deadline === null) return null;
193
+ const ms = new Date(deadline).getTime();
194
+ return Number.isNaN(ms) ? null : ms;
195
+ }
196
+ //#endregion
197
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/wire-BFE9sIQf.js
198
+ /**
199
+ * The wire format shared by server.fetch and experimental-a2/client
200
+ * (browser side): events as JSON with ISO timestamps, and the A2Error
201
+ * envelope. Internal module — both entry points re-export what's
202
+ * public.
203
+ */
204
+ function eventToWire(event) {
205
+ return {
206
+ id: event.id,
207
+ type: event.type,
208
+ payload: event.payload,
209
+ index: event.index,
210
+ sessionId: event.sessionId,
211
+ createdAt: event.createdAt.toISOString()
212
+ };
213
+ }
214
+ const lastEncoding = (encode) => {
215
+ let last;
216
+ let text = "";
217
+ return (value) => {
218
+ if (value !== last) {
219
+ text = encode(value);
220
+ last = value;
221
+ }
222
+ return text;
223
+ };
224
+ };
225
+ const isoJson = lastEncoding((ms) => JSON.stringify(new Date(ms).toISOString()));
226
+ const sessionJson = lastEncoding((id) => JSON.stringify(id));
227
+ const typeJson = lastEncoding((type) => JSON.stringify(type));
228
+ /**
229
+ * `JSON.stringify(eventToWire(event))` for the parsed event, built around the
230
+ * stored payload text instead of parsing and re-serializing it.
231
+ */
232
+ function serializedEventToWireJson(event) {
233
+ return `{"id":${JSON.stringify(event.id)},"type":${typeJson(event.type)},"payload":${event.payloadJson},"index":${event.index},"sessionId":${sessionJson(event.sessionId)},"createdAt":${isoJson(event.createdAtMs)}}`;
234
+ }
235
+ function wireVersion(value) {
236
+ return value === "2" ? 2 : 1;
237
+ }
238
+ /**
239
+ * Events already held by a stream join one write while it is shorter than
240
+ * this many characters, so a write can exceed it by the event that crosses it.
241
+ */
242
+ const EVENT_WRITE_CHARS = 65536;
243
+ /** Stream items that are events, as opposed to snapshot or presence frames. */
244
+ function isStreamEvent(item) {
245
+ return !("kind" in item) && !("snapshot" in item) && !("participant" in item);
246
+ }
247
+ /**
248
+ * `first` and the events `iterator` already holds, encoded, until the batch
249
+ * reaches `EVENT_WRITE_CHARS`; `last` is the batch's final event.
250
+ */
251
+ function heldEventBatch(options) {
252
+ const { iterator, encode } = options;
253
+ let last = options.first;
254
+ const events = [encode(last)];
255
+ let chars = events[0].length;
256
+ while (chars < EVENT_WRITE_CHARS) {
257
+ const held = takeBuffered(iterator);
258
+ if (!held) break;
259
+ const json = encode(held);
260
+ events.push(json);
261
+ chars += json.length + 1;
262
+ last = held;
263
+ }
264
+ return {
265
+ events,
266
+ last
267
+ };
268
+ }
269
+ /** One version 2 event as JSON, splicing a held row's stored payload. */
270
+ function compactEventJson(event) {
271
+ if (!isSerializedEvent(event)) return JSON.stringify({
272
+ id: event.id,
273
+ type: event.type,
274
+ payload: event.payload,
275
+ index: event.index,
276
+ createdAt: event.createdAt.getTime()
277
+ });
278
+ return `{"id":${JSON.stringify(event.id)},"type":${typeJson(event.type)},"payload":${event.payloadJson},"index":${event.index},"createdAt":${event.createdAtMs}}`;
279
+ }
280
+ function presencePatchToWire(patch) {
281
+ return {
282
+ participant: patch.participant,
283
+ values: patch.values,
284
+ seen: patch.seen,
285
+ at: patch.at.toISOString()
286
+ };
287
+ }
288
+ function presenceSnapshotToWire(snapshot) {
289
+ const wire = nullProtoRecord();
290
+ for (const [participant, fields] of Object.entries(snapshot.snapshot)) {
291
+ const wireFields = nullProtoRecord();
292
+ for (const [field, entry] of Object.entries(fields)) {
293
+ if (entry === void 0) continue;
294
+ wireFields[field] = {
295
+ value: entry.value,
296
+ seen: entry.seen,
297
+ at: entry.at.toISOString()
298
+ };
299
+ }
300
+ wire[participant] = wireFields;
301
+ }
302
+ return { snapshot: wire };
303
+ }
304
+ const ERROR_STATUS = {
305
+ INVALID_PAYLOAD: 400,
306
+ FORBIDDEN: 403,
307
+ UNKNOWN_EVENT_TYPE: 400,
308
+ PARTIAL_DUPLICATE_BATCH: 400,
309
+ SUPERSEDED_ATTEMPT: 409,
310
+ SESSION_CLEARED: 409,
311
+ LAST_INDEX_MISMATCH: 409,
312
+ CLAIM_EXPIRED: 409,
313
+ STORE_UNAVAILABLE: 503,
314
+ STORE_NOT_CONFIGURED: 500,
315
+ UNKNOWN_PRESENCE_FIELD: 400,
316
+ PRESENCE_NOT_SUPPORTED: 500,
317
+ CONSUMER_DEAD_LETTERED: 500
318
+ };
319
+ function errorStatus(code) {
320
+ return ERROR_STATUS[isServerErrorCode(code) ? code : "STORE_UNAVAILABLE"];
321
+ }
322
+ function errorToWire(error) {
323
+ const failure = asA2Error(error);
324
+ const body = { error: {
325
+ code: failure.code,
326
+ message: failure.message
327
+ } };
328
+ if (failure.details !== void 0) body.error.details = failure.details;
329
+ return body;
330
+ }
331
+ /** Wrap an arbitrary thrown value for the wire: known server codes pass through,
332
+ * anything else becomes STORE_UNAVAILABLE — from the client's
333
+ * perspective an unknown server failure is retryable-once, not a
334
+ * protocol contract. */
335
+ function asA2Error(error) {
336
+ return error instanceof A2Error && isServerErrorCode(error.code) ? error : new A2Error("STORE_UNAVAILABLE", "internal error", { cause: error });
337
+ }
338
+ const isServerErrorCode = (code) => Object.hasOwn(ERROR_STATUS, code);
339
+ function stateSnapshotToWire(frame) {
340
+ return frame.state === void 0 ? {
341
+ ...frame,
342
+ state: null,
343
+ stateUndefined: true
344
+ } : frame;
345
+ }
346
+ const SOCKET_PING_FRAME = JSON.stringify({ kind: "ping" });
347
+ /** One stream item as a socket frame — `sseResponse`'s framing over
348
+ * the same codecs, with `kind` instead of an SSE event name. On a
349
+ * multiplexed socket presence frames carry the `sessionId` tag; events
350
+ * already carry theirs in the wire event. */
351
+ function socketFrameFor(item, sessionId) {
352
+ const tag = sessionId === void 0 ? {} : { sessionId };
353
+ if ("kind" in item) return JSON.stringify(stateSnapshotToWire(item));
354
+ if ("snapshot" in item) return JSON.stringify({
355
+ kind: "presence-snapshot",
356
+ ...presenceSnapshotToWire(item),
357
+ ...tag
358
+ });
359
+ if ("participant" in item) return JSON.stringify({
360
+ kind: "presence",
361
+ ...presencePatchToWire(item),
362
+ ...tag
363
+ });
364
+ return JSON.stringify({
365
+ kind: "event",
366
+ ...eventToWire(item)
367
+ });
368
+ }
369
+ /** A version 2 batch frame from compact event JSON; a multiplexed
370
+ * socket names the batch's session once. */
371
+ function socketEventsFor(events, sessionId) {
372
+ return `{"kind":"events",${sessionId === void 0 ? "" : `"sessionId":${JSON.stringify(sessionId)},`}"events":[${events.join(",")}]}`;
373
+ }
374
+ function socketAckFor(req, events, sessionId) {
375
+ return JSON.stringify({
376
+ kind: "ack",
377
+ req,
378
+ events: events.map(eventToWire),
379
+ ...sessionId === void 0 ? {} : { sessionId }
380
+ });
381
+ }
382
+ function socketErrorAckFor(req, error, sessionId) {
383
+ return JSON.stringify({
384
+ kind: "ack",
385
+ req,
386
+ ...errorToWire(error),
387
+ ...sessionId === void 0 ? {} : { sessionId }
388
+ });
389
+ }
390
+ function socketSubscribedFor(options) {
391
+ const { sessionId, attempt } = options;
392
+ return JSON.stringify({
393
+ kind: "subscribed",
394
+ sessionId,
395
+ ...attempt === void 0 ? {} : { attempt }
396
+ });
397
+ }
398
+ /** The subscription-over notice: with a `reason` the server rejected
399
+ * or lost the session's stream, without one it ended cleanly. */
400
+ function socketUnsubscribedFor(options) {
401
+ const { sessionId, attempt, reason, error } = options;
402
+ return JSON.stringify({
403
+ kind: "unsubscribed",
404
+ sessionId,
405
+ ...attempt === void 0 ? {} : { attempt },
406
+ ...reason === void 0 ? {} : { reason },
407
+ ...error === void 0 ? {} : errorToWire(error)
408
+ });
409
+ }
410
+ //#endregion
411
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/retryable-lazy-DZWmHpii.js
412
+ const retryableLazy = (initialize) => {
413
+ let current = null;
414
+ const get = () => {
415
+ if (current) return current;
416
+ const attempt = Promise.resolve().then(initialize);
417
+ current = attempt;
418
+ attempt.catch(() => {
419
+ if (current === attempt) current = null;
420
+ });
421
+ return attempt;
422
+ };
423
+ return {
424
+ get,
425
+ peek: () => current
426
+ };
427
+ };
428
+ //#endregion
429
+ //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/server-DX7mM6nm.js
430
+ /**
431
+ * The push envelope's trust boundary for `{ sessionId, events, presence? }`,
432
+ * shared verbatim by the HTTP
433
+ * POST lane and the socket's push/presence frames so INVALID_PAYLOAD
434
+ * shapes are one implementation. Internal module, not public API.
435
+ */
436
+ const invalidPushBody = (message) => new A2Error("INVALID_PAYLOAD", `malformed push body: ${message}`);
437
+ const invalid = invalidPushBody;
438
+ function parsePresenceSibling(value) {
439
+ if (value === void 0) return void 0;
440
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw invalid("presence must be an object when present");
441
+ const { participant, values, seen, at } = value;
442
+ if (typeof participant !== "string" || participant.length === 0) throw invalid("presence.participant must be a non-empty string");
443
+ if (RESERVED_PARTICIPANT_IDS.has(participant)) throw invalid(`presence.participant must not be '${participant}'`);
444
+ if (values === null || typeof values !== "object" || Array.isArray(values)) throw invalid("presence.values must be an object");
445
+ if (seen !== void 0 && (typeof seen !== "number" || !Number.isFinite(seen) || seen < 0)) throw invalid("presence.seen must be a non-negative number when present");
446
+ if (at !== void 0 && (typeof at !== "number" || !Number.isFinite(at) || at < 0 || at > 864e13)) throw invalid("presence.at must be a non-negative epoch-milliseconds timestamp within the Date range when present");
447
+ const out = {
448
+ participant,
449
+ values
450
+ };
451
+ if (seen !== void 0) out.seen = seen;
452
+ if (at !== void 0) out.at = at;
453
+ return out;
454
+ }
455
+ /** The longest event id a push may carry: ids are indexed, and Postgres's index rows have a limit. */
456
+ const MAX_PUSHED_ID = 256;
457
+ /** A UUIDv5, the shape of the ids A2 derives (deterministic-id.ts). */
458
+ const DERIVED_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
459
+ /** The events half of the envelope, shared by the POST body and socket
460
+ * `push` frames so INVALID_PAYLOAD shapes have one implementation. */
461
+ function parsePushEvents(events) {
462
+ if (!Array.isArray(events) || events.length === 0) throw invalid("events must be a non-empty array");
463
+ return events.map((event, i) => {
464
+ if (event === null || typeof event !== "object") throw invalid(`events[${i}] must be an object`);
465
+ const { type, payload, id } = event;
466
+ if (typeof type !== "string" || type.length === 0) throw invalid(`events[${i}].type must be a non-empty string`);
467
+ if (id !== void 0 && typeof id !== "string") throw invalid(`events[${i}].id must be a string when present`);
468
+ if (id !== void 0 && (id.length === 0 || id.length > MAX_PUSHED_ID)) throw invalid(`events[${i}].id must be 1-${MAX_PUSHED_ID} characters when present`);
469
+ if (id !== void 0 && DERIVED_ID.test(id)) throw invalid(`events[${i}].id is shaped like the ids A2 derives for consumers (a UUIDv5); use crypto.randomUUID() or idempotentId()`);
470
+ const out = {
471
+ type,
472
+ payload
473
+ };
474
+ if (id !== void 0) out.id = id;
475
+ return out;
476
+ });
477
+ }
478
+ /**
479
+ * Validate the push envelope — `{ sessionId, events, presence? }` —
480
+ * throwing `INVALID_PAYLOAD` on a malformed body. Payload validation
481
+ * against the machine's schemas happens in `append` and `setPresence`,
482
+ * not here. Either plane may appear alone: a presence-only push has no
483
+ * (or empty) `events`.
484
+ */
485
+ async function parsePushBody(req) {
486
+ let body;
487
+ try {
488
+ body = await req.json();
489
+ } catch (cause) {
490
+ throw new A2Error("INVALID_PAYLOAD", "push body is not valid JSON", { cause });
491
+ }
492
+ if (body === null || typeof body !== "object") throw invalid("expected an object");
493
+ const { sessionId, events, presence } = body;
494
+ if (typeof sessionId !== "string" || sessionId.length === 0) throw invalid("sessionId must be a non-empty string");
495
+ const parsedPresence = parsePresenceSibling(presence);
496
+ if (parsedPresence !== void 0 && (events === void 0 || Array.isArray(events) && events.length === 0)) return {
497
+ sessionId,
498
+ events: [],
499
+ presence: parsedPresence
500
+ };
501
+ const parsed = parsePushEvents(events);
502
+ return parsedPresence !== void 0 ? {
503
+ sessionId,
504
+ events: parsed,
505
+ presence: parsedPresence
506
+ } : {
507
+ sessionId,
508
+ events: parsed
509
+ };
510
+ }
511
+ /**
512
+ * The A2 socket protocol's server half (specs/a2-api.md §13): the
513
+ * per-socket shell — teardown, backpressure, heartbeat, the malformed
514
+ * budget, and the in-flight bound. `sessionSocket` binds one session to
515
+ * one socket; `sessionsSocket` is the opt-in multiplexed handler. Only
516
+ * `A2Socket`, the structural socket the platform hands over, is public.
517
+ */
518
+ const messageText = (data) => {
519
+ if (typeof data === "string") return data;
520
+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
521
+ if (ArrayBuffer.isView(data)) return new TextDecoder().decode(data);
522
+ if (Array.isArray(data) && data.every(ArrayBuffer.isView)) {
523
+ const decoder = new TextDecoder();
524
+ let text = "";
525
+ for (const part of data) text += decoder.decode(part, { stream: true });
526
+ return text + decoder.decode();
527
+ }
528
+ return null;
529
+ };
530
+ /**
531
+ * How many unparseable or invalid frames a socket may send before it
532
+ * is closed (1008): the budget absorbs isolated client bugs without
533
+ * letting a broken peer spin the validation path forever. Push frames
534
+ * with a usable `req` never count — their failures are answered with
535
+ * error acks, exactly like the POST path's 4xx bodies.
536
+ */
537
+ const MAX_MALFORMED_FRAMES = 5;
538
+ function socketShell(socket, release, onFrame, deadlineAt) {
539
+ let torn = false;
540
+ let malformed = 0;
541
+ let heartbeat;
542
+ let deadline;
543
+ const teardown = () => {
544
+ if (torn) return;
545
+ torn = true;
546
+ if (heartbeat !== void 0) clearInterval(heartbeat);
547
+ if (deadline !== void 0) clearTimeout(deadline);
548
+ release();
549
+ };
550
+ const shutdown = (code, reason) => {
551
+ if (torn) return;
552
+ teardown();
553
+ try {
554
+ socket.close(code, reason);
555
+ } catch {}
556
+ };
557
+ const send = (data) => {
558
+ if (torn) return;
559
+ if (typeof socket.bufferedAmount === "number" && socket.bufferedAmount > SOCKET_TIMINGS.disconnectWaterMarkBytes) {
560
+ shutdown(1008, "backpressure: peer not reading");
561
+ return;
562
+ }
563
+ try {
564
+ socket.send(data);
565
+ } catch {
566
+ teardown();
567
+ }
568
+ };
569
+ const malformedFrame = (reason) => {
570
+ malformed += 1;
571
+ if (malformed >= MAX_MALFORMED_FRAMES) shutdown(1008, `too many malformed frames (last: ${reason})`);
572
+ };
573
+ let inFlight = 0;
574
+ const track = (work) => {
575
+ inFlight += 1;
576
+ work.finally(() => {
577
+ inFlight -= 1;
578
+ });
579
+ };
580
+ const handleMessage = (data) => {
581
+ if (torn) return;
582
+ const text = messageText(data);
583
+ if (text === null) {
584
+ malformedFrame("non-text frame");
585
+ return;
586
+ }
587
+ let parsed;
588
+ try {
589
+ parsed = JSON.parse(text);
590
+ } catch {
591
+ malformedFrame("frame is not valid JSON");
592
+ return;
593
+ }
594
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
595
+ malformedFrame("frame is not an object");
596
+ return;
597
+ }
598
+ onFrame(parsed);
599
+ };
600
+ socket.on("message", handleMessage);
601
+ socket.on("close", teardown);
602
+ socket.on("error", teardown);
603
+ heartbeat = setInterval(() => send(SOCKET_PING_FRAME), STREAM_TIMINGS.sseHeartbeatMs);
604
+ heartbeat.unref?.();
605
+ if (deadlineAt !== void 0) {
606
+ deadline = setTimeout(() => shutdown(1e3, "deadline"), Math.max(0, deadlineAt - Date.now()));
607
+ deadline.unref?.();
608
+ }
609
+ return {
610
+ torn: () => torn,
611
+ send,
612
+ shutdown,
613
+ malformedFrame,
614
+ buffered: () => typeof socket.bufferedAmount === "number" ? socket.bufferedAmount : 0,
615
+ overCap: () => inFlight >= SOCKET_TIMINGS.maxInFlightMessages,
616
+ track
617
+ };
618
+ }
619
+ const socketSubscription = (options) => {
620
+ const { target, startAfter, presence, attempt } = options;
621
+ return {
622
+ target,
623
+ iterator: (presence ? target.stream({
624
+ startAfter,
625
+ presence: true
626
+ }) : target.stream({ startAfter }))[Symbol.asyncIterator](),
627
+ stopped: false,
628
+ ...attempt === void 0 ? {} : { attempt }
629
+ };
630
+ };
631
+ const stopSubscription = (subscription) => {
632
+ subscription.stopped = true;
633
+ subscription.iterator.return?.()?.catch(() => {});
634
+ };
635
+ /**
636
+ * Sends a subscription's items until it ends. With `batch`, an event and
637
+ * the events its iterator already holds go out as one frame.
638
+ */
639
+ const pumpSubscription = async (options) => {
640
+ const { shell, subscription, frameFor, batch } = options;
641
+ for (;;) {
642
+ while (!shell.torn() && !subscription.stopped && shell.buffered() > SOCKET_TIMINGS.highWaterMarkBytes) await new Promise((wake) => setTimeout(wake, SOCKET_TIMINGS.resumePollMs));
643
+ if (shell.torn() || subscription.stopped) return;
644
+ const { value, done } = await subscription.iterator.next();
645
+ if (shell.torn() || subscription.stopped || done) return;
646
+ if (!batch || !isStreamEvent(value)) {
647
+ shell.send(frameFor(value));
648
+ continue;
649
+ }
650
+ const { events } = heldEventBatch({
651
+ first: value,
652
+ iterator: subscription.iterator,
653
+ encode: compactEventJson
654
+ });
655
+ shell.send(batch(events));
656
+ }
657
+ };
658
+ const handleSocketPush = async (shell, target, sessionId, frame, req, ackSessionId, gatePush, activate) => {
659
+ try {
660
+ const events = parsePushEvents(frame["events"]);
661
+ const denial = await gatePush?.(sessionId, events, void 0) ?? null;
662
+ if (denial !== null) {
663
+ shell.send(socketErrorAckFor(req, denial, ackSessionId));
664
+ return;
665
+ }
666
+ activate();
667
+ const appended = await target.append(...events);
668
+ activate();
669
+ shell.send(socketAckFor(req, appended, ackSessionId));
670
+ } catch (error) {
671
+ shell.send(socketErrorAckFor(req, asA2Error(error), ackSessionId));
672
+ }
673
+ };
674
+ const applySocketPresence = async (shell, target, sessionId, frame, gatePush) => {
675
+ if (typeof target.setPresence !== "function") {
676
+ shell.malformedFrame("presence frame on a presence-less session");
677
+ return;
678
+ }
679
+ let patch;
680
+ try {
681
+ patch = parsePresenceSibling(frame);
682
+ } catch {
683
+ shell.malformedFrame("invalid presence frame");
684
+ return;
685
+ }
686
+ if (!patch) return;
687
+ try {
688
+ if ((await gatePush?.(sessionId, [], patch) ?? null) !== null) return;
689
+ await target.setPresence(patch);
690
+ } catch (error) {
691
+ const failure = asA2Error(error);
692
+ if (failure.code === "INVALID_PAYLOAD" || failure.code === "UNKNOWN_PRESENCE_FIELD") {
693
+ shell.malformedFrame("invalid presence frame");
694
+ return;
695
+ }
696
+ shell.shutdown(1011, "internal error");
697
+ }
698
+ };
699
+ function sessionSocket(sessionId, session, socket, options) {
700
+ const target = session;
701
+ const subscription = socketSubscription({
702
+ target,
703
+ startAfter: options?.startAfter ?? 0,
704
+ presence: options?.presence === true
705
+ });
706
+ const handleFrame = (frame) => {
707
+ switch (frame["kind"]) {
708
+ case "push": {
709
+ const req = frame["req"];
710
+ if (typeof req !== "number") {
711
+ shell.malformedFrame("push frame without a numeric req");
712
+ return;
713
+ }
714
+ if (frame["sessionId"] !== void 0) {
715
+ shell.send(socketErrorAckFor(req, new A2Error("INVALID_PAYLOAD", "sessionId is not allowed on a single-session socket")));
716
+ return;
717
+ }
718
+ if (shell.overCap()) {
719
+ shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "push shed: too many in flight on this socket")));
720
+ return;
721
+ }
722
+ shell.track(handleSocketPush(shell, target, sessionId, frame, req, void 0, options?.gatePush, () => streamActivities.get(subscription.iterator)?.activate()));
723
+ return;
724
+ }
725
+ case "presence":
726
+ if (frame["sessionId"] !== void 0) {
727
+ shell.malformedFrame("sessionId is not allowed on a single-session socket");
728
+ return;
729
+ }
730
+ if (!shell.overCap()) shell.track(applySocketPresence(shell, target, sessionId, frame, options?.gatePush));
731
+ return;
732
+ default: return;
733
+ }
734
+ };
735
+ const shell = socketShell(socket, () => stopSubscription(subscription), handleFrame, options?.deadline);
736
+ pumpSubscription({
737
+ shell,
738
+ subscription,
739
+ frameFor: socketFrameFor,
740
+ ...options?.wire === 2 ? { batch: (events) => socketEventsFor(events) } : {}
741
+ }).then(() => shell.shutdown(1e3), () => shell.shutdown(1011, "stream failed"));
742
+ }
743
+ const parseSubscribeEntries = (value) => {
744
+ if (!Array.isArray(value) || value.length === 0) return null;
745
+ const entries = [];
746
+ for (const entry of value) {
747
+ if (entry === null || typeof entry !== "object") return null;
748
+ const { id, attempt, index, bootstrap, reducer } = entry;
749
+ if (typeof id !== "string" || id.length === 0) return null;
750
+ if (attempt !== void 0 && (typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 0)) return null;
751
+ if (reducer !== void 0 && (typeof reducer !== "string" || reducer.length === 0)) return null;
752
+ const lane = {
753
+ id,
754
+ ...attempt === void 0 ? {} : { attempt }
755
+ };
756
+ if (bootstrap === true) {
757
+ if (index !== void 0 || typeof reducer !== "string") return null;
758
+ entries.push({
759
+ ...lane,
760
+ bootstrap: true,
761
+ reducer
762
+ });
763
+ } else {
764
+ if (bootstrap !== void 0 || typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
765
+ entries.push({
766
+ ...lane,
767
+ index,
768
+ ...reducer === void 0 ? {} : { reducer }
769
+ });
770
+ }
771
+ }
772
+ return entries;
773
+ };
774
+ /**
775
+ * Speak the multiplexed A2 socket protocol (specs/a2-api.md §13)
776
+ * against many sessions on one socket. `subscribe` frames open a
777
+ * per-session pump at that session's own resume frontier; push and
778
+ * presence frames route by `sessionId` through the same validation
779
+ * seams as the POST lane; every down frame carries the `sessionId` it
780
+ * belongs to. One heartbeat, one
781
+ * malformed budget, one in-flight bound, one backpressure gauge — per
782
+ * socket, shared by all sessions. A session's stream ending or failing
783
+ * answers `unsubscribed` for that session; only the peer, the
784
+ * deadline, the malformed budget, or backpressure closes the socket.
785
+ */
786
+ function sessionsSocket(resolve, socket, options) {
787
+ const presence = options?.presence === true;
788
+ const subscriptions = /* @__PURE__ */ new Map();
789
+ const retire = (id, subscription) => {
790
+ if (subscriptions.get(id) === subscription) subscriptions.delete(id);
791
+ };
792
+ const runSubscription = async (id, subscription) => {
793
+ const { attempt } = subscription;
794
+ try {
795
+ await pumpSubscription({
796
+ shell,
797
+ subscription,
798
+ frameFor: (item) => socketFrameFor(item, id),
799
+ ...options?.wire === 2 ? { batch: (events) => socketEventsFor(events, id) } : {}
800
+ });
801
+ if (shell.torn() || subscription.stopped) return;
802
+ retire(id, subscription);
803
+ shell.send(socketUnsubscribedFor({
804
+ sessionId: id,
805
+ attempt
806
+ }));
807
+ } catch (error) {
808
+ if (shell.torn() || subscription.stopped) return;
809
+ retire(id, subscription);
810
+ shell.send(socketUnsubscribedFor({
811
+ sessionId: id,
812
+ attempt,
813
+ reason: "stream failed",
814
+ error: asA2Error(error)
815
+ }));
816
+ }
817
+ };
818
+ const startSubscription = async (entry) => {
819
+ const { id, attempt } = entry;
820
+ const index = entry.index ?? 0;
821
+ const existing = subscriptions.get(id);
822
+ if (existing) {
823
+ stopSubscription(existing);
824
+ subscriptions.delete(id);
825
+ }
826
+ let session;
827
+ try {
828
+ session = await resolve(id, index, entry);
829
+ } catch (error) {
830
+ if (!shell.torn()) shell.send(socketUnsubscribedFor({
831
+ sessionId: id,
832
+ attempt,
833
+ reason: "stream failed",
834
+ error: asA2Error(error)
835
+ }));
836
+ return;
837
+ }
838
+ if (shell.torn()) return;
839
+ if (session === null) {
840
+ shell.send(socketUnsubscribedFor({
841
+ sessionId: id,
842
+ attempt,
843
+ reason: "subscribe rejected",
844
+ error: new A2Error("FORBIDDEN", "the subscription is not authorized")
845
+ }));
846
+ return;
847
+ }
848
+ const subscription = socketSubscription({
849
+ target: session,
850
+ startAfter: index,
851
+ presence,
852
+ attempt
853
+ });
854
+ subscriptions.set(id, subscription);
855
+ shell.send(socketSubscribedFor({
856
+ sessionId: id,
857
+ attempt
858
+ }));
859
+ runSubscription(id, subscription);
860
+ };
861
+ let controlTail = Promise.resolve();
862
+ const control = (work) => {
863
+ controlTail = controlTail.then(work).catch(() => {});
864
+ };
865
+ const handlePush = async (frame, req, sessionId) => {
866
+ const subscription = subscriptions.get(sessionId);
867
+ if (subscription === void 0) {
868
+ shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "session is not subscribed on this socket"), sessionId));
869
+ return;
870
+ }
871
+ await handleSocketPush(shell, subscription.target, sessionId, frame, req, sessionId, options?.gatePush, () => {
872
+ const current = subscriptions.get(sessionId);
873
+ if (current) streamActivities.get(current.iterator)?.activate();
874
+ });
875
+ };
876
+ const handlePresence = async (frame, sessionId) => {
877
+ const subscription = subscriptions.get(sessionId);
878
+ if (subscription === void 0) return;
879
+ await applySocketPresence(shell, subscription.target, sessionId, frame, options?.gatePush);
880
+ };
881
+ const handleFrame = (frame) => {
882
+ switch (frame["kind"]) {
883
+ case "subscribe": {
884
+ const entries = parseSubscribeEntries(frame["sessions"]);
885
+ if (entries === null) {
886
+ shell.malformedFrame("malformed subscribe frame");
887
+ return;
888
+ }
889
+ for (const entry of entries) control(() => startSubscription(entry));
890
+ return;
891
+ }
892
+ case "unsubscribe": {
893
+ const ids = frame["sessions"];
894
+ if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string")) {
895
+ shell.malformedFrame("malformed unsubscribe frame");
896
+ return;
897
+ }
898
+ for (const id of ids) control(() => {
899
+ const subscription = subscriptions.get(id);
900
+ if (subscription === void 0) return;
901
+ stopSubscription(subscription);
902
+ subscriptions.delete(id);
903
+ });
904
+ return;
905
+ }
906
+ case "push": {
907
+ const req = frame["req"];
908
+ const sessionId = frame["sessionId"];
909
+ if (shell.overCap()) {
910
+ if (typeof req === "number") shell.send(socketErrorAckFor(req, new A2Error("STORE_UNAVAILABLE", "push shed: too many in flight on this socket"), typeof sessionId === "string" ? sessionId : void 0));
911
+ else shell.malformedFrame("push frame without a numeric req");
912
+ return;
913
+ }
914
+ if (typeof req !== "number") {
915
+ shell.malformedFrame("push frame without a numeric req");
916
+ return;
917
+ }
918
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
919
+ shell.send(socketErrorAckFor(req, new A2Error("INVALID_PAYLOAD", "push frame without a sessionId")));
920
+ return;
921
+ }
922
+ shell.track(handlePush(frame, req, sessionId));
923
+ return;
924
+ }
925
+ case "presence": {
926
+ if (shell.overCap()) return;
927
+ const sessionId = frame["sessionId"];
928
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
929
+ shell.malformedFrame("presence frame without a sessionId");
930
+ return;
931
+ }
932
+ shell.track(handlePresence(frame, sessionId));
933
+ return;
934
+ }
935
+ default: return;
936
+ }
937
+ };
938
+ const shell = socketShell(socket, () => {
939
+ for (const subscription of subscriptions.values()) stopSubscription(subscription);
940
+ subscriptions.clear();
941
+ }, (frame) => handleFrame(frame), options?.deadline);
942
+ }
943
+ /**
944
+ * The SSE response protocol — framing, heartbeat, deadline, and
945
+ * teardown for the live stream lane. Internal module: `server.fetch` is
946
+ * the sanctioned caller; the framing rules stay
947
+ * documented on `sseResponse` because the client's parser (and the
948
+ * stall watchdog) depend on them.
949
+ */
950
+ /**
951
+ * Pipe a live event iterable into an SSE `Response`. Each event is one
952
+ * frame — `id:` carries the event-log index, `data:` the JSON event.
953
+ * Frames for events the iterable already holds are written together. With
954
+ * `wire: 2` those events share one frame instead: `data:` is a JSON array of
955
+ * `CompactWireEvent`s and `id:` the last one's index. A
956
+ * `stream({ presence: true })` iterable also yields presence items,
957
+ * which ride as named frames old clients skip: `event:
958
+ * presence-snapshot` first (the map, ISO dates), then `event: presence`
959
+ * per patch — no `id:`, presence never advances the resume frontier. A
960
+ * disconnecting client cancels the stream, which closes the underlying
961
+ * subscription. Two kinds of comment frames ride along: a `: connected`
962
+ * prelude that flushes headers immediately, and a `: ping` heartbeat
963
+ * every 15 seconds so clients (and proxies) can tell a quiet stream
964
+ * from a dead connection — the session client's stall watchdog counts
965
+ * on it. When the platform exposes an invocation deadline, the response
966
+ * closes cleanly one second before it so the client reconnects without
967
+ * a platform-timeout failure.
968
+ */
969
+ function sseResponse(iterable, options = {}) {
970
+ const write = options.wire === 2 ? batchedFrames : eventFrames;
971
+ const iterator = iterable[Symbol.asyncIterator]();
972
+ const encoder = new TextEncoder();
973
+ let heartbeat;
974
+ let deadlineTimer;
975
+ let closed = false;
976
+ let iteratorReturned = false;
977
+ let stopActivity;
978
+ const stopTimers = () => {
979
+ stopActivity?.();
980
+ stopActivity = void 0;
981
+ if (heartbeat !== void 0) clearInterval(heartbeat);
982
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
983
+ heartbeat = void 0;
984
+ deadlineTimer = void 0;
985
+ };
986
+ const returnIterator = async () => {
987
+ if (iteratorReturned) return;
988
+ iteratorReturned = true;
989
+ await iterator.return?.();
990
+ };
991
+ const stream = new ReadableStream({
992
+ start(controller) {
993
+ controller.enqueue(encoder.encode(": connected\n\n"));
994
+ const activity = streamActivities.get(iterator);
995
+ if (activity) {
996
+ const announce = (idle) => {
997
+ if (closed) return;
998
+ controller.enqueue(encoder.encode(`event: a2-activity\ndata: ${idle ? "idle" : "active"}\n\n`));
999
+ };
1000
+ stopActivity = activity.subscribe(announce);
1001
+ if (activity.idle) announce(true);
1002
+ }
1003
+ heartbeat = setInterval(() => {
1004
+ try {
1005
+ controller.enqueue(encoder.encode(": ping\n\n"));
1006
+ } catch {
1007
+ stopTimers();
1008
+ }
1009
+ }, STREAM_TIMINGS.sseHeartbeatMs);
1010
+ heartbeat.unref?.();
1011
+ const invocationDeadline = invocationDeadlineMs();
1012
+ if (invocationDeadline !== null) {
1013
+ const delay = Math.max(0, invocationDeadline - Date.now() - STREAM_TIMINGS.sseDeadlineGraceMs);
1014
+ deadlineTimer = setTimeout(() => {
1015
+ if (closed) return;
1016
+ closed = true;
1017
+ stopTimers();
1018
+ returnIterator().catch(() => {});
1019
+ try {
1020
+ controller.close();
1021
+ } catch {}
1022
+ }, delay);
1023
+ deadlineTimer.unref?.();
1024
+ }
1025
+ },
1026
+ async pull(controller) {
1027
+ try {
1028
+ const { value, done } = await iterator.next();
1029
+ if (closed) return;
1030
+ if (done) {
1031
+ closed = true;
1032
+ stopTimers();
1033
+ controller.close();
1034
+ return;
1035
+ }
1036
+ controller.enqueue(encoder.encode(write(value, iterator)));
1037
+ } catch (error) {
1038
+ if (closed) return;
1039
+ closed = true;
1040
+ stopTimers();
1041
+ returnIterator().catch(() => {});
1042
+ throw error;
1043
+ }
1044
+ },
1045
+ async cancel() {
1046
+ if (closed) return;
1047
+ closed = true;
1048
+ stopTimers();
1049
+ await returnIterator();
1050
+ }
1051
+ });
1052
+ return new Response(stream, {
1053
+ status: 200,
1054
+ headers: {
1055
+ "content-type": "text/event-stream",
1056
+ "cache-control": "no-cache, no-transform",
1057
+ connection: "keep-alive"
1058
+ }
1059
+ });
1060
+ }
1061
+ /** Version 1: one frame per event, then each event the iterator holds. */
1062
+ function eventFrames(first, iterator) {
1063
+ let frames = frameFor(first);
1064
+ while (frames.length < EVENT_WRITE_CHARS) {
1065
+ const event = takeBuffered(iterator);
1066
+ if (!event) break;
1067
+ frames += frameFor(event);
1068
+ }
1069
+ return frames;
1070
+ }
1071
+ /**
1072
+ * Version 2: events this write carries share one frame, a JSON array whose
1073
+ * `id:` is its last index. Held events are always events, so only `first`
1074
+ * can be a snapshot or presence frame.
1075
+ */
1076
+ function batchedFrames(first, iterator) {
1077
+ const lead = isStreamEvent(first) ? "" : frameFor(first);
1078
+ const head = isStreamEvent(first) ? first : takeBuffered(iterator);
1079
+ if (!head) return lead;
1080
+ const { events, last } = heldEventBatch({
1081
+ first: head,
1082
+ iterator,
1083
+ encode: compactJsonLine
1084
+ });
1085
+ return `${lead}id: ${last.index}\ndata: [${events.join(",")}]\n\n`;
1086
+ }
1087
+ const compactJsonLine = (event) => isSerializedEvent(event) && /[\r\n]/.test(event.payloadJson) ? compactEventJson(parseSerializedEvent(event)) : compactEventJson(event);
1088
+ function frameFor(item) {
1089
+ if ("kind" in item) return `event: a2-snapshot\ndata: ${JSON.stringify(stateSnapshotToWire(item))}\n\n`;
1090
+ if ("snapshot" in item) return `event: presence-snapshot\ndata: ${JSON.stringify(presenceSnapshotToWire(item))}\n\n`;
1091
+ if ("participant" in item) return `event: presence\ndata: ${JSON.stringify(presencePatchToWire(item))}\n\n`;
1092
+ if (isSerializedEvent(item)) return /[\r\n]/.test(item.payloadJson) ? `id: ${item.index}\ndata: ${JSON.stringify(eventToWire(parseSerializedEvent(item)))}\n\n` : `id: ${item.index}\ndata: ${serializedEventToWireJson(item)}\n\n`;
1093
+ return `id: ${item.index}\ndata: ${JSON.stringify(eventToWire(item))}\n\n`;
1094
+ }
1095
+ function bootstrapStream(options) {
1096
+ return { [Symbol.asyncIterator]() {
1097
+ let closed = false;
1098
+ let index;
1099
+ let source;
1100
+ let stopActivity;
1101
+ const abort = new AbortController();
1102
+ const activity = createStreamActivity(() => {
1103
+ if (source) streamActivities.get(source)?.activate();
1104
+ });
1105
+ const iterator = {
1106
+ async next() {
1107
+ if (closed) return {
1108
+ done: true,
1109
+ value: void 0
1110
+ };
1111
+ if (index === void 0) {
1112
+ let cancel;
1113
+ const cancelled = new Promise((resolve) => {
1114
+ cancel = () => resolve(void 0);
1115
+ abort.signal.addEventListener("abort", cancel, { once: true });
1116
+ });
1117
+ try {
1118
+ const snapshot = await Promise.race([options.snapshot(), cancelled]);
1119
+ if (closed || snapshot === void 0) return {
1120
+ done: true,
1121
+ value: void 0
1122
+ };
1123
+ index = snapshot.index;
1124
+ return {
1125
+ done: false,
1126
+ value: snapshot
1127
+ };
1128
+ } finally {
1129
+ if (cancel) abort.signal.removeEventListener("abort", cancel);
1130
+ }
1131
+ }
1132
+ if (!source) {
1133
+ source = options.stream(index)[Symbol.asyncIterator]();
1134
+ const sourceActivity = streamActivities.get(source);
1135
+ if (sourceActivity) {
1136
+ activity.setIdle(sourceActivity.idle);
1137
+ stopActivity = sourceActivity.subscribe(activity.setIdle);
1138
+ }
1139
+ }
1140
+ const result = await source.next();
1141
+ return closed ? {
1142
+ done: true,
1143
+ value: void 0
1144
+ } : result;
1145
+ },
1146
+ async return() {
1147
+ if (closed) return {
1148
+ done: true,
1149
+ value: void 0
1150
+ };
1151
+ closed = true;
1152
+ abort.abort();
1153
+ stopActivity?.();
1154
+ await source?.return?.();
1155
+ return {
1156
+ done: true,
1157
+ value: void 0
1158
+ };
1159
+ }
1160
+ };
1161
+ streamActivities.set(iterator, activity);
1162
+ bufferedEvents.set(iterator, () => closed || !source ? void 0 : takeBuffered(source));
1163
+ return iterator;
1164
+ } };
1165
+ }
1166
+ const serverFetchHooks = /* @__PURE__ */ new WeakMap();
1167
+ const parseHistoryBounds = (gte, lte) => {
1168
+ if (gte === null || lte === null) throw new A2Error("INVALID_PAYLOAD", "a history read takes both gte and lte");
1169
+ const bounds = {
1170
+ gte: Number(gte),
1171
+ lte: Number(lte)
1172
+ };
1173
+ for (const [name, value] of Object.entries(bounds)) if (!Number.isSafeInteger(value) || value < 0) throw new A2Error("INVALID_PAYLOAD", `history ${name} must be a non-negative safe integer`);
1174
+ if (bounds.gte > bounds.lte) throw new A2Error("INVALID_PAYLOAD", "history gte must be less than or equal to lte");
1175
+ return bounds;
1176
+ };
1177
+ const parseResumeIndex = (raw) => {
1178
+ if (raw === null) return 0;
1179
+ const index = Number(raw);
1180
+ if (!Number.isSafeInteger(index) || index < 0) throw new A2Error("INVALID_PAYLOAD", "stream index must be a non-negative safe integer");
1181
+ return index;
1182
+ };
1183
+ const parseSubscription = (params) => {
1184
+ const reducer = params.get("reducer");
1185
+ const bootstrap = params.get("bootstrap");
1186
+ const index = params.get("index");
1187
+ if (reducer === "") throw new A2Error("INVALID_PAYLOAD", "empty reducer name");
1188
+ if (bootstrap !== null) {
1189
+ if (bootstrap !== "1" || index !== null || reducer === null) throw new A2Error("INVALID_PAYLOAD", "bootstrap requires a reducer and no index");
1190
+ return {
1191
+ bootstrap: true,
1192
+ reducer
1193
+ };
1194
+ }
1195
+ return {
1196
+ index: parseResumeIndex(index),
1197
+ ...reducer === null ? {} : { reducer }
1198
+ };
1199
+ };
1200
+ const errorResponse = (error) => {
1201
+ const a2error = asA2Error(error);
1202
+ return Response.json(errorToWire(a2error), { status: errorStatus(a2error.code) });
1203
+ };
1204
+ const forbidden = () => new A2Error("FORBIDDEN", "the operation is not authorized");
1205
+ const freezePush = (sessionId, events, presence, transport) => {
1206
+ for (const event of events) Object.freeze(event);
1207
+ Object.freeze(events);
1208
+ if (presence !== void 0) {
1209
+ Object.freeze(presence.values);
1210
+ Object.freeze(presence);
1211
+ }
1212
+ return {
1213
+ type: "push",
1214
+ sessionId,
1215
+ events,
1216
+ ...presence === void 0 ? {} : { presence },
1217
+ transport
1218
+ };
1219
+ };
1220
+ function createServerFetch(server) {
1221
+ const presence = Object.keys(server.contract.presence).length > 0;
1222
+ const fetch = async (request, options) => {
1223
+ const authorized = async (operation) => {
1224
+ try {
1225
+ return await options?.authorize?.(Object.freeze(operation)) !== false;
1226
+ } catch (cause) {
1227
+ throw new A2Error("STORE_UNAVAILABLE", "authorization failed", { cause });
1228
+ }
1229
+ };
1230
+ const authorize = async (operation) => {
1231
+ if (!await authorized(operation)) throw forbidden();
1232
+ };
1233
+ const validateIngress = async (context) => {
1234
+ await serverFetchHooks.get(fetch)?.validateIngress?.(context);
1235
+ };
1236
+ const gateSocketPush = async (sessionId, events, pushedPresence) => {
1237
+ try {
1238
+ await authorize(freezePush(sessionId, events, pushedPresence, "websocket"));
1239
+ await validateIngress({
1240
+ sessionId,
1241
+ events,
1242
+ ...pushedPresence === void 0 ? {} : { presence: pushedPresence }
1243
+ });
1244
+ return null;
1245
+ } catch (error) {
1246
+ return asA2Error(error);
1247
+ }
1248
+ };
1249
+ const selectedSession = (sessionId, selection) => {
1250
+ const reducer = server.contract.reducer;
1251
+ if (selection.reducer !== void 0 && reducer !== void 0 && reducer.name !== selection.reducer) throw new A2Error("INVALID_PAYLOAD", "client reducer does not match the public contract reducer");
1252
+ const target = server.session(sessionId);
1253
+ const streamTarget = target;
1254
+ if (!selection.bootstrap) return streamTarget;
1255
+ if (!reducer) throw new A2Error("INVALID_PAYLOAD", "contract has no public reducer");
1256
+ return {
1257
+ ...streamTarget,
1258
+ stream: (streamOptions) => bootstrapStream({
1259
+ snapshot: async () => {
1260
+ const initial = await target.state(reducer);
1261
+ return {
1262
+ kind: "snapshot",
1263
+ sessionId,
1264
+ name: reducer.name,
1265
+ index: initial.index,
1266
+ state: encodeState({
1267
+ reducer,
1268
+ state: initial.state
1269
+ }),
1270
+ ...initial.clearIndex === void 0 ? {} : { clearIndex: initial.clearIndex }
1271
+ };
1272
+ },
1273
+ stream: (index) => {
1274
+ const bounds = {
1275
+ startAfter: index,
1276
+ presence: streamOptions.presence === true
1277
+ };
1278
+ return target.stream(bounds);
1279
+ }
1280
+ })
1281
+ };
1282
+ };
1283
+ const attachMultiplexed = (wire) => (socket) => {
1284
+ const deadline = invocationDeadlineMs();
1285
+ sessionsSocket(async (sessionId, startAfter, selection = { index: startAfter }) => {
1286
+ const operation = {
1287
+ type: "stream",
1288
+ sessionId,
1289
+ startAfter,
1290
+ ...selection.bootstrap ? { bootstrap: true } : {},
1291
+ transport: "websocket"
1292
+ };
1293
+ return await authorized(operation) ? selectedSession(sessionId, selection) : null;
1294
+ }, socket, {
1295
+ presence,
1296
+ wire,
1297
+ ...deadline === null ? {} : { deadline },
1298
+ gatePush: gateSocketPush
1299
+ });
1300
+ };
1301
+ try {
1302
+ if (request.method === "GET") {
1303
+ if (request.headers.get("upgrade")?.toLowerCase() === "websocket") {
1304
+ if (options?.upgradeWebSocket === void 0) return new Response("WebSocket upgrade requested, but server.fetch() has no upgrade implementation", { status: 426 });
1305
+ const { searchParams } = new URL(request.url);
1306
+ const wire = wireVersion(searchParams.get("wire"));
1307
+ if (options.multiplexWebSocket === true) return await options.upgradeWebSocket(attachMultiplexed(wire));
1308
+ const sessionId = searchParams.get("sessionId");
1309
+ if (sessionId === null || sessionId.length === 0) throw new A2Error("INVALID_PAYLOAD", "missing sessionId");
1310
+ const selection = parseSubscription(searchParams);
1311
+ const startAfter = selection.index ?? 0;
1312
+ await authorize({
1313
+ type: "stream",
1314
+ sessionId,
1315
+ startAfter,
1316
+ ...selection.bootstrap ? { bootstrap: true } : {},
1317
+ transport: "websocket"
1318
+ });
1319
+ const target = selectedSession(sessionId, selection);
1320
+ const attach = (socket) => {
1321
+ const deadline = invocationDeadlineMs();
1322
+ sessionSocket(sessionId, target, socket, {
1323
+ startAfter,
1324
+ presence,
1325
+ wire,
1326
+ ...deadline === null ? {} : { deadline },
1327
+ gatePush: gateSocketPush
1328
+ });
1329
+ };
1330
+ return await options.upgradeWebSocket(attach);
1331
+ }
1332
+ const { searchParams } = new URL(request.url);
1333
+ const sessionId = searchParams.get("sessionId");
1334
+ if (sessionId === null || sessionId.length === 0) throw new A2Error("INVALID_PAYLOAD", "missing sessionId");
1335
+ const gteRaw = searchParams.get("gte");
1336
+ const lteRaw = searchParams.get("lte");
1337
+ if (gteRaw !== null || lteRaw !== null) {
1338
+ const bounds = parseHistoryBounds(gteRaw, lteRaw);
1339
+ await authorize({
1340
+ type: "history",
1341
+ sessionId,
1342
+ ...bounds,
1343
+ transport: "http"
1344
+ });
1345
+ const { events, clearIndex } = await server.historyPage(sessionId, bounds);
1346
+ const first = Math.max(bounds.gte, (clearIndex ?? 0) + 1);
1347
+ const covered = events.length === Math.max(0, bounds.lte - first + 1);
1348
+ return Response.json(events.map(eventToWire), { headers: {
1349
+ "a2-history-covered": String(covered),
1350
+ ...clearIndex === void 0 ? {} : { "a2-clear-index": String(clearIndex) }
1351
+ } });
1352
+ }
1353
+ const selection = parseSubscription(searchParams);
1354
+ const startAfter = selection.index ?? 0;
1355
+ await authorize({
1356
+ type: "stream",
1357
+ sessionId,
1358
+ startAfter,
1359
+ ...selection.bootstrap ? { bootstrap: true } : {},
1360
+ transport: "http"
1361
+ });
1362
+ const target = selectedSession(sessionId, selection);
1363
+ return sseResponse(presence ? target.stream({
1364
+ startAfter,
1365
+ presence: true
1366
+ }) : target.stream({ startAfter }), { wire: wireVersion(searchParams.get("wire")) });
1367
+ }
1368
+ if (request.method === "POST") {
1369
+ const body = await parsePushBody(request);
1370
+ await authorize(freezePush(body.sessionId, body.events, body.presence, "http"));
1371
+ await validateIngress({
1372
+ sessionId: body.sessionId,
1373
+ events: body.events,
1374
+ ...body.presence === void 0 ? {} : { presence: body.presence }
1375
+ });
1376
+ const session = server.session(body.sessionId);
1377
+ if (body.presence !== void 0) {
1378
+ const target = session;
1379
+ if (typeof target.setPresence !== "function") throw invalidPushBody("presence is not declared by this contract");
1380
+ await target.setPresence(body.presence);
1381
+ }
1382
+ const appended = body.events.length === 0 ? [] : await session.append(...body.events);
1383
+ return Response.json(appended.map(eventToWire));
1384
+ }
1385
+ return new Response("Method Not Allowed", {
1386
+ status: 405,
1387
+ headers: { allow: "GET, POST" }
1388
+ });
1389
+ } catch (error) {
1390
+ return errorResponse(error);
1391
+ }
1392
+ };
1393
+ return fetch;
1394
+ }
1395
+ /**
1396
+ * Deterministic default ids for consumer `session.append` calls. A consumer
1397
+ * re-run after a crash calls `session.append` again; giving
1398
+ * each call a deterministic id — derived from the triggering event's id
1399
+ * and the caller's stable name — makes the re-run a no-op via the store's
1400
+ * per-session unique index on event ids.
1401
+ *
1402
+ * The id is a UUIDv5-shaped SHA-1 over
1403
+ * `(namespace, triggerEventId, name, itemOrdinal)`, computed with
1404
+ * WebCrypto so it runs on any platform a2 core targets.
1405
+ */
1406
+ const APPEND_NAMESPACE = "a2:handler-append:v2";
1407
+ const RETURN_NAMESPACE = "a2:handler-return:v1";
1408
+ const SCHEDULE_NAMESPACE = "a2:schedule:v1";
1409
+ const SCHEDULED_EVENT_NAMESPACE = "a2:scheduled-event:v1";
1410
+ const SCHEDULE_CLEAR_NAMESPACE = "a2:schedule-clear:v1";
1411
+ async function deterministicIdFromInput(input) {
1412
+ const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(input));
1413
+ const bytes = new Uint8Array(digest).slice(0, 16);
1414
+ bytes[6] = (bytes[6] ?? 0) & 15 | 80;
1415
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
1416
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1417
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
1418
+ }
1419
+ async function deterministicId(parts) {
1420
+ return deterministicIdFromInput(parts.join("\0"));
1421
+ }
1422
+ /**
1423
+ * `consumer` keys the id on the consumer that appends, so two consumers of
1424
+ * one event never collide. A2's own consumers pass none: their types are
1425
+ * disjoint, so the event alone keys them.
1426
+ */
1427
+ async function deterministicEventId(triggerEventId, name, itemOrdinal, consumer) {
1428
+ if (name.length === 0) throw new TypeError("append name must not be empty");
1429
+ return deterministicId([
1430
+ APPEND_NAMESPACE,
1431
+ triggerEventId,
1432
+ name,
1433
+ itemOrdinal,
1434
+ ...consumer === void 0 ? [] : [consumer]
1435
+ ]);
1436
+ }
1437
+ async function deterministicReturnedEventId(triggerEventId, itemOrdinal, consumer) {
1438
+ return deterministicId([
1439
+ RETURN_NAMESPACE,
1440
+ triggerEventId,
1441
+ itemOrdinal,
1442
+ ...consumer === void 0 ? [] : [consumer]
1443
+ ]);
1444
+ }
1445
+ /**
1446
+ * The id of a scheduled append. `clearIndex` is the lifetime the trigger was
1447
+ * claimed in; it joins the input only when positive, so a trigger id reused
1448
+ * after a clear schedules a distinct task while sessions never cleared keep
1449
+ * the ids they always had.
1450
+ */
1451
+ async function deterministicScheduleId(contract, sessionId, triggerEventId, name, clearIndex = 0, consumer) {
1452
+ return deterministicIdFromInput(JSON.stringify([
1453
+ SCHEDULE_NAMESPACE,
1454
+ contract,
1455
+ sessionId,
1456
+ triggerEventId,
1457
+ name,
1458
+ ...clearIndex > 0 ? [clearIndex] : [],
1459
+ ...consumer === void 0 ? [] : [{ consumer }]
1460
+ ]));
1461
+ }
1462
+ async function deterministicScheduleClearId({ contract, sessionId, triggerEventId, clearIndex, name, ifLastIndex, consumer }) {
1463
+ return deterministicIdFromInput(JSON.stringify([
1464
+ SCHEDULE_CLEAR_NAMESPACE,
1465
+ contract,
1466
+ sessionId,
1467
+ triggerEventId,
1468
+ clearIndex,
1469
+ name,
1470
+ ifLastIndex,
1471
+ ...consumer === void 0 ? [] : [{ consumer }]
1472
+ ]));
1473
+ }
1474
+ async function deterministicScheduledEventId(scheduleId, itemOrdinal) {
1475
+ return deterministicId([
1476
+ SCHEDULED_EVENT_NAMESPACE,
1477
+ scheduleId,
1478
+ itemOrdinal
1479
+ ]);
1480
+ }
1481
+ /**
1482
+ * The default when no telemetry is configured. Spans cost nothing, but
1483
+ * `recordError` prints: it only ever receives errors a2 swallows by
1484
+ * design, so without a configured sink the console is the one place
1485
+ * they can surface. Passing `telemetry` replaces this sink wholesale.
1486
+ */
1487
+ const CONSOLE_TELEMETRY = { span: (name, attributes, fn) => fn({
1488
+ setAttribute: () => {},
1489
+ recordError: (error) => {
1490
+ console.error(`[a2] error in ${name}`, attributes, error);
1491
+ }
1492
+ }) };
1493
+ /**
1494
+ * Deliver one authenticated scheduler append through an A2 server's ordinary
1495
+ * top-level append path. Custom scheduler adapters call this after validating
1496
+ * their transport envelope; application code normally uses `session.schedule`.
1497
+ */
1498
+ async function deliverSchedulerAppend(server, task) {
1499
+ if (server.contract.name !== task.contract) throw new TypeError(`a2 scheduler: append task for contract '${task.contract}' cannot be delivered to '${server.contract.name}'`);
1500
+ const { originIndex } = task;
1501
+ if (originIndex !== void 0 && (!Number.isSafeInteger(originIndex) || originIndex < 1)) throw new TypeError("a2 scheduler: append task originIndex must be a positive safe integer");
1502
+ const internals = serverInternals.get(server);
1503
+ if (!internals) throw new TypeError(`a2 scheduler: server for contract '${task.contract}' cannot receive scheduled appends`);
1504
+ await internals.schedulerAppend(task.sessionId, task.events, originIndex);
1505
+ }
1506
+ /**
1507
+ * Deliver one authenticated scheduler clear: a conditional
1508
+ * `clear({ ifLastIndex })` that resolves after its deletion finishes, so a
1509
+ * provider retry resumes an interrupted deletion. Custom scheduler adapters
1510
+ * call this after validating their transport envelope; application code uses
1511
+ * `session.schedule.clear`.
1512
+ */
1513
+ async function deliverSchedulerClear(server, task) {
1514
+ if (server.contract.name !== task.contract) throw new TypeError(`a2 scheduler: clear task for contract '${task.contract}' cannot be delivered to '${server.contract.name}'`);
1515
+ if (task.kind !== "clear" || !Number.isSafeInteger(task.ifLastIndex) || task.ifLastIndex < 0) throw new TypeError("a2 scheduler: a clear task needs kind \"clear\" and a non-negative safe integer ifLastIndex");
1516
+ const internals = serverInternals.get(server);
1517
+ if (!internals) throw new TypeError(`a2 scheduler: server for contract '${task.contract}' cannot receive scheduled clears`);
1518
+ await internals.schedulerClear(task.sessionId, task.ifLastIndex);
1519
+ }
1520
+ const CONSUMER_NAME = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
1521
+ /** Define a consumer: a named reader of each session's log. */
1522
+ function consumer(options) {
1523
+ return defineConsumer(options, false);
1524
+ }
1525
+ /**
1526
+ * `consumer()`, and for A2's own runtimes (`runtime`) a name under `a2.` and
1527
+ * child ids without the name: their types are disjoint, so the event alone
1528
+ * keys them, and regrouping A2's consumers never changes an id.
1529
+ */
1530
+ function defineConsumer(options, runtime) {
1531
+ const contract = options?.contract;
1532
+ if (!contract || typeof contract.name !== "string") throw new TypeError("consumer expects options with a contract");
1533
+ const consumerName = options.name;
1534
+ if (typeof consumerName !== "string" || !CONSUMER_NAME.test(consumerName)) throw new TypeError("consumer name must be 1-128 letters, digits, and . _ : - characters");
1535
+ if (consumerName.startsWith("a2.") !== runtime) throw new TypeError(runtime ? `A2's own consumers are named under 'a2.'` : `consumer names starting with 'a2.' are reserved`);
1536
+ const types = options.types === void 0 ? null : [...options.types];
1537
+ if (types?.length === 0) throw new TypeError(`consumer '${consumerName}' lists no types; leave types out to take every type`);
1538
+ for (const type of types ?? []) if (!Object.hasOwn(contract.events, type)) throw new TypeError(`contract '${contract.name}' has no event type '${String(type)}'`);
1539
+ const lane = options.lane ?? null;
1540
+ if (lane !== null && typeof lane !== "function" && (typeof lane !== "string" || lane.length === 0)) throw new TypeError(`lane for consumer '${consumerName}' must be a non-empty string or a function`);
1541
+ const backfill = options.backfill ?? false;
1542
+ if (backfill && typeof lane !== "string") throw new TypeError(`consumer '${consumerName}' backfills, so its lane must be a string`);
1543
+ if (backfill && options.abortOn !== void 0) throw new TypeError(`consumer '${consumerName}' backfills, so it can't use abortOn`);
1544
+ return { run(fn) {
1545
+ if (typeof fn !== "function") throw new TypeError(`consumer '${consumerName}' needs a run function`);
1546
+ const defined = {
1547
+ name: consumerName,
1548
+ contract: { name: contract.name },
1549
+ spec: {
1550
+ types,
1551
+ lane,
1552
+ backfill,
1553
+ abortOn: options.abortOn ?? null,
1554
+ run: fn
1555
+ }
1556
+ };
1557
+ if (runtime) runtimeConsumers.add(defined);
1558
+ return defined;
1559
+ } };
1560
+ }
1561
+ runtimeConsumerFactory.define = (options) => defineConsumer(options, true);
1562
+ /** A registered consumer as the store needs to know it. */
1563
+ const storeConsumerOf = (registered) => registered.log ? {
1564
+ name: registered.name,
1565
+ log: registered.log
1566
+ } : { name: registered.name };
1567
+ const MAX_FAILURES = 10;
1568
+ /** How long `consume` waits before looking again at a head it can't run. */
1569
+ const CONSUME_WAIT_MIN_MS = 25;
1570
+ const CONSUME_WAIT_MAX_MS = 1e3;
1571
+ /**
1572
+ * `task`, or a rejection with `signal`'s reason once it aborts. The task runs
1573
+ * on either way, and its own failure is caught, so nothing goes unhandled.
1574
+ */
1575
+ const untilAborted = (task, signal) => {
1576
+ if (!signal) return task;
1577
+ task.catch(() => {});
1578
+ if (signal.aborted) return Promise.reject(signal.reason);
1579
+ return new Promise((resolve, reject) => {
1580
+ const abort = () => reject(signal.reason);
1581
+ signal.addEventListener("abort", abort, { once: true });
1582
+ task.then(resolve, reject).finally(() => {
1583
+ signal.removeEventListener("abort", abort);
1584
+ });
1585
+ });
1586
+ };
1587
+ /** How long an event waits after its `failureCount`th failed attempt. */
1588
+ const failureRetryDelayMs = (failureCount) => Math.min(DRAIN_TIMINGS.failureRetryBaseMs * 2 ** Math.max(failureCount - 1, 0), DRAIN_TIMINGS.failureRetryMaxMs);
1589
+ /** Abort a lost attempt's consumer and release its drain slot. */
1590
+ function endSuperseded(entry, message) {
1591
+ entry.supersede.abort(new A2Error("SUPERSEDED_ATTEMPT", message));
1592
+ entry.fence({
1593
+ status: "superseded",
1594
+ opensLane: false,
1595
+ appendsEvents: false
1596
+ });
1597
+ }
1598
+ /** Pause between clear-deletion batches that found only locked rows. */
1599
+ const RECLAIM_STALL_MS = 20;
1600
+ const RECLAIM_STALL_LIMIT = 50;
1601
+ /** Default: how long a presence value survives without a refreshing set. */
1602
+ const PRESENCE_TTL_MS = 6e4;
1603
+ function createDrainSignal() {
1604
+ const listeners = /* @__PURE__ */ new Set();
1605
+ return {
1606
+ version: 0,
1607
+ closed: false,
1608
+ notify() {
1609
+ this.version += 1;
1610
+ for (const listener of listeners) listener();
1611
+ listeners.clear();
1612
+ },
1613
+ wait(version) {
1614
+ if (this.version !== version) return {
1615
+ promise: Promise.resolve(),
1616
+ cancel: () => {}
1617
+ };
1618
+ let resolve;
1619
+ const promise = new Promise((done) => {
1620
+ resolve = done;
1621
+ });
1622
+ listeners.add(resolve);
1623
+ return {
1624
+ promise,
1625
+ cancel: () => listeners.delete(resolve)
1626
+ };
1627
+ }
1628
+ };
1629
+ }
1630
+ function dispatchAbortEvent(hub, event) {
1631
+ let relevant = false;
1632
+ for (const subscription of hub.subscriptions) {
1633
+ if (!subscription.types.has(event.type)) continue;
1634
+ relevant = true;
1635
+ if (subscription.matches(event)) subscription.controller.abort();
1636
+ }
1637
+ if (relevant) hub.seen.set(event.index, event);
1638
+ }
1639
+ function pruneAbortHub(hub) {
1640
+ let minimum = Infinity;
1641
+ const types = /* @__PURE__ */ new Set();
1642
+ for (const subscription of hub.subscriptions) {
1643
+ minimum = Math.min(minimum, subscription.triggerIndex);
1644
+ for (const type of subscription.types) types.add(type);
1645
+ }
1646
+ for (const [index, event] of hub.seen) if (index <= minimum || !types.has(event.type)) hub.seen.delete(index);
1647
+ }
1648
+ /**
1649
+ * Deadlines tighten the claim/watchdog window, and a passed deadline ends
1650
+ * claiming: a claim then could not run, only lapse and be claimed again until
1651
+ * the platform ends the process. A platform timeout otherwise follows the
1652
+ * same path as any other process death: the in-flight event remains pending
1653
+ * and a fresh invocation retries it.
1654
+ */
1655
+ function nextClaimWindow() {
1656
+ const nowMs = Date.now();
1657
+ const deadlineMs = invocationDeadlineMs();
1658
+ const deadlineTtlMs = deadlineMs === null ? DRAIN_TIMINGS.claimTtlMs : deadlineMs - nowMs;
1659
+ const deadlineCapped = deadlineMs !== null && deadlineTtlMs <= DRAIN_TIMINGS.claimTtlMs;
1660
+ const ttlMs = Math.max(1, Math.min(DRAIN_TIMINGS.claimTtlMs, deadlineTtlMs));
1661
+ const expiresAtMs = nowMs + ttlMs;
1662
+ return {
1663
+ ttlMs,
1664
+ expiresAtMs,
1665
+ watchdogAtMs: expiresAtMs + DRAIN_TIMINGS.watchdogGraceMs,
1666
+ deadlineCapped,
1667
+ pastDeadline: deadlineMs !== null && deadlineTtlMs <= 0
1668
+ };
1669
+ }
1670
+ function schedulerSlot(dueAt) {
1671
+ return Math.ceil(dueAt / 1e3) * 1e3;
1672
+ }
1673
+ function currentSchedulerSlot(now) {
1674
+ return Math.floor(now / 1e3) * 1e3;
1675
+ }
1676
+ /**
1677
+ * The namespace separator between machine name and session id in
1678
+ * storage. Machines sharing one store backend (the dev-default sqlite
1679
+ * file, a shared Postgres) must not collide on session ids; the machine
1680
+ * name is what makes multi-machine apps unambiguous (a2-api.md §1), so
1681
+ * it prefixes every storage key.
1682
+ */
1683
+ const NS = "";
1684
+ const devDefaultStore = retryableLazy(() => import("./store-sqlite-Cs8dH9EX.mjs").then((m) => m.sqlite()));
1685
+ /** Waits for a scheduler arm for at most `schedulerArmTimeoutMs`. */
1686
+ async function joinSchedulerArm(arm) {
1687
+ let timeout = null;
1688
+ try {
1689
+ await Promise.race([arm, new Promise((_, reject) => {
1690
+ timeout = setTimeout(() => {
1691
+ reject(/* @__PURE__ */ new Error(`a2 scheduler arm timed out after ${DRAIN_TIMINGS.schedulerArmTimeoutMs}ms`));
1692
+ }, DRAIN_TIMINGS.schedulerArmTimeoutMs);
1693
+ })]);
1694
+ } finally {
1695
+ if (timeout) clearTimeout(timeout);
1696
+ }
1697
+ }
1698
+ function environment() {
1699
+ const env = typeof process === "undefined" ? void 0 : process.env?.["NODE_ENV"];
1700
+ if (env === "test") return "test";
1701
+ if (env === "production") return "production";
1702
+ return "development";
1703
+ }
1704
+ function describeError(err) {
1705
+ if (err instanceof Error) return err.stack ?? `${err.name}: ${err.message}`;
1706
+ return String(err);
1707
+ }
1708
+ /**
1709
+ * Comparison key for a presence value in the degraded-tier diff — an
1710
+ * LWW tie can replace a value without moving its `seen`/`at` stamp.
1711
+ */
1712
+ function fingerprint(value) {
1713
+ return JSON.stringify(value) ?? "";
1714
+ }
1715
+ function foldPresenceRows(rows) {
1716
+ const map = nullProtoRecord();
1717
+ for (const row of rows) (map[row.participant] ??= nullProtoRecord())[row.field] = {
1718
+ value: row.value,
1719
+ seen: row.seen,
1720
+ at: row.at
1721
+ };
1722
+ return map;
1723
+ }
1724
+ /** One cursor head, as a map key. */
1725
+ const headKey = (ref) => JSON.stringify([
1726
+ ref.consumer,
1727
+ ref.lane,
1728
+ ref.index
1729
+ ]);
1730
+ const headRefOf = (head) => ({
1731
+ consumer: head.consumer,
1732
+ lane: head.lane,
1733
+ index: head.index
1734
+ });
1735
+ const addSnapshotWrite = (writes, index, state, pin) => {
1736
+ let write = writes.get(index);
1737
+ if (!write) {
1738
+ write = {
1739
+ state: cloneInitial(state),
1740
+ pins: /* @__PURE__ */ new Map()
1741
+ };
1742
+ writes.set(index, write);
1743
+ }
1744
+ if (pin !== void 0) write.pins.set(headKey(pin), pin);
1745
+ };
1746
+ /** Whether a registered consumer runs events of this type. */
1747
+ const takes = (registered, type) => registered.types === null || registered.types.has(type);
1748
+ /** Implement a contract: bind its vocabulary to storage and reactions. */
1749
+ function createServer(options) {
1750
+ const serverContract = options?.contract;
1751
+ if (serverContract === null || typeof serverContract !== "object" || typeof serverContract.name !== "string" || serverContract.events === null) throw new TypeError("createServer expects options with a contract (see a2.contract)");
1752
+ if (Object.hasOwn(options, "handlers")) throw new TypeError("createServer no longer takes handlers: write each as a consumer in `consumers` (see https://www.a2.dev/upgrades/0-21)");
1753
+ const name = serverContract.name;
1754
+ const defs = serverContract.events;
1755
+ const presenceDefs = serverContract.presence;
1756
+ const declaresPresence = Object.keys(presenceDefs).length > 0;
1757
+ const presenceNotSupported = () => new A2Error("PRESENCE_NOT_SUPPORTED", `the contract '${name}' declares presence but the store backend for its server has no presence capability (A2Store.presence)`);
1758
+ if (options.presence !== void 0) {
1759
+ if (!declaresPresence) throw new TypeError(`the presence option requires a contract that declares presence fields — '${name}' has none`);
1760
+ const { ttlMs } = options.presence;
1761
+ if (ttlMs !== void 0 && (!Number.isInteger(ttlMs) || ttlMs <= 0)) throw new TypeError("presence.ttlMs must be a positive integer of milliseconds");
1762
+ }
1763
+ const presenceTtlMs = options.presence?.ttlMs ?? PRESENCE_TTL_MS;
1764
+ let makeStore;
1765
+ if (options.store) {
1766
+ const explicit = options.store;
1767
+ if (declaresPresence && !explicit.presence) throw presenceNotSupported();
1768
+ makeStore = () => Promise.resolve(explicit);
1769
+ } else {
1770
+ const env = environment();
1771
+ if (env === "production") {
1772
+ const error = () => new A2Error("STORE_NOT_CONFIGURED", `the server for '${name}' has no store configured and NODE_ENV is 'production' — pass an explicit store backend (e.g. postgres from 'experimental-a2/store-postgres')`);
1773
+ if (process.env["NEXT_PHASE"] !== "phase-production-build") throw error();
1774
+ makeStore = () => Promise.reject(error());
1775
+ } else makeStore = env === "test" ? () => import("./store-memory-XNDFHASI.mjs").then((m) => m.memory()) : devDefaultStore.get;
1776
+ }
1777
+ if (declaresPresence && !options.store) {
1778
+ const inner = makeStore;
1779
+ makeStore = async () => {
1780
+ const store = await inner();
1781
+ if (!store.presence) throw presenceNotSupported();
1782
+ return store;
1783
+ };
1784
+ }
1785
+ const resolveStore = retryableLazy(makeStore).get;
1786
+ const telemetry = options.telemetry ?? CONSOLE_TELEMETRY;
1787
+ const scheduler = options.scheduler;
1788
+ const abortMatcherOf = (spec) => {
1789
+ let abortOn = null;
1790
+ if (spec !== void 0 && spec !== null) {
1791
+ abortOn = /* @__PURE__ */ new Map();
1792
+ const pairs = Array.isArray(spec) ? spec.map((abortType) => [abortType, true]) : Object.entries(spec);
1793
+ for (const [abortType, matcher] of pairs) {
1794
+ if (matcher === void 0) continue;
1795
+ if (!Object.hasOwn(defs, abortType)) throw new TypeError(`contract '${name}' has no event type '${String(abortType)}' — cannot abort on it`);
1796
+ abortOn.set(String(abortType), matcher);
1797
+ }
1798
+ if (abortOn.size === 0) abortOn = null;
1799
+ }
1800
+ return abortOn;
1801
+ };
1802
+ const laneContext = (sessionId, event) => ({
1803
+ sessionId,
1804
+ event: {
1805
+ type: event.type,
1806
+ payload: structuredClone(event.payload),
1807
+ ...event.id === void 0 ? {} : { id: event.id }
1808
+ }
1809
+ });
1810
+ const registeredConsumers = /* @__PURE__ */ new Map();
1811
+ /** A consumer definition as the server runs it. */
1812
+ const registrationOf = (defined) => {
1813
+ const { types, lane, backfill, abortOn, run } = defined.spec;
1814
+ const matcher = abortMatcherOf(abortOn);
1815
+ return {
1816
+ name: defined.name,
1817
+ types: types === null ? null : new Set(types),
1818
+ laneOf: typeof lane === "string" ? null : lane === null ? () => null : (sessionId, event) => {
1819
+ const resolved = lane(laneContext(sessionId, event));
1820
+ if (resolved !== null && (typeof resolved !== "string" || resolved.length === 0)) throw new TypeError(`lane for consumer '${defined.name}' must resolve to a non-empty string or null`);
1821
+ return resolved;
1822
+ },
1823
+ log: typeof lane === "string" ? {
1824
+ lane,
1825
+ types: types === null ? null : [...types],
1826
+ backfill
1827
+ } : void 0,
1828
+ abortOn: () => matcher,
1829
+ run,
1830
+ anonymousIds: runtimeConsumers.has(defined)
1831
+ };
1832
+ };
1833
+ /** The definitions the server runs, so `consume` can tell its own from another. */
1834
+ const definitions = /* @__PURE__ */ new Map();
1835
+ /** A consumer written inline is `consumer()`'s options and `run`, on this contract. */
1836
+ const definitionOf = (entry) => {
1837
+ if (entry === null || typeof entry !== "object" || "spec" in entry || !("run" in entry)) return entry;
1838
+ const { run, ...rest } = entry;
1839
+ return consumer({
1840
+ ...rest,
1841
+ contract: serverContract
1842
+ }).run(run);
1843
+ };
1844
+ for (const entry of options.consumers ?? []) {
1845
+ const defined = definitionOf(entry);
1846
+ if (defined?.contract?.name !== name || !defined.spec) throw new TypeError(`createServer for '${name}' got a consumer of another contract`);
1847
+ if (registeredConsumers.has(defined.name)) throw new TypeError(`two consumers are named '${defined.name}'`);
1848
+ registeredConsumers.set(defined.name, registrationOf(defined));
1849
+ definitions.set(defined.name, defined);
1850
+ }
1851
+ const anonymousTypes = /* @__PURE__ */ new Map();
1852
+ for (const registered of registeredConsumers.values()) {
1853
+ if (!registered.anonymousIds) continue;
1854
+ for (const type of registered.types ?? Object.keys(defs)) {
1855
+ const other = anonymousTypes.get(type);
1856
+ if (other !== void 0) throw new TypeError(`A2's consumers '${other}' and '${registered.name}' both take '${type}'`);
1857
+ anonymousTypes.set(type, registered.name);
1858
+ }
1859
+ }
1860
+ /** The consumers this server serves, as the store needs to know them. */
1861
+ const storeConsumers = [...registeredConsumers.values()].map(storeConsumerOf);
1862
+ /** Whether an event starts cursor work for any consumer. */
1863
+ const startsWork = (event) => (event.targets?.length ?? 0) > 0 || [...registeredConsumers.values()].some((registered) => registered.log && takes(registered, event.type));
1864
+ const prefix = `${name}${NS}`;
1865
+ const nsId = (sessionId) => `${prefix}${sessionId}`;
1866
+ const stripNs = (stored) => stored.slice(prefix.length);
1867
+ const toPublic = (row) => ({
1868
+ id: row.id,
1869
+ type: row.type,
1870
+ payload: row.payload,
1871
+ index: row.index,
1872
+ sessionId: stripNs(row.sessionId),
1873
+ createdAt: row.createdAt
1874
+ });
1875
+ const inFlight = /* @__PURE__ */ new Set();
1876
+ const track = (p) => {
1877
+ inFlight.add(p);
1878
+ const drop = () => {
1879
+ inFlight.delete(p);
1880
+ };
1881
+ p.then(drop, drop);
1882
+ };
1883
+ const schedulerArmSlots = /* @__PURE__ */ new Map();
1884
+ /**
1885
+ * Start an optional scheduler arm without putting it on the execution path.
1886
+ * The returned raw promise lets the initial append report failure; the
1887
+ * tracked copy is always rejection-safe for heartbeat callers.
1888
+ */
1889
+ const startSchedulerArm = (sessionId, dueAt) => {
1890
+ if (!scheduler) return null;
1891
+ const slottedDueAt = schedulerSlot(dueAt);
1892
+ const slotKey = JSON.stringify([sessionId, slottedDueAt]);
1893
+ const existing = schedulerArmSlots.get(slotKey);
1894
+ if (existing) return existing.promise;
1895
+ const raw = Promise.resolve().then(() => scheduler.schedule({
1896
+ version: 1,
1897
+ kind: "drain",
1898
+ contract: name,
1899
+ sessionId,
1900
+ dueAt: slottedDueAt
1901
+ }));
1902
+ const forget = setTimeout(() => {
1903
+ if (schedulerArmSlots.get(slotKey)?.promise === raw) schedulerArmSlots.delete(slotKey);
1904
+ }, Math.max(0, slottedDueAt - Date.now()) + 1e3);
1905
+ forget.unref?.();
1906
+ schedulerArmSlots.set(slotKey, {
1907
+ promise: raw,
1908
+ forget
1909
+ });
1910
+ raw.then(void 0, () => {
1911
+ const current = schedulerArmSlots.get(slotKey);
1912
+ if (current?.promise !== raw) return;
1913
+ clearTimeout(current.forget);
1914
+ schedulerArmSlots.delete(slotKey);
1915
+ });
1916
+ const safe = raw.catch(() => {});
1917
+ track(safe);
1918
+ platformWaitUntil(safe);
1919
+ return raw;
1920
+ };
1921
+ const scheduledDrains = /* @__PURE__ */ new Map();
1922
+ const scheduleDrain = (sessionId, watchdogDueAt) => {
1923
+ const existing = scheduledDrains.get(sessionId);
1924
+ if (existing && !existing.signal.closed) {
1925
+ existing.signal.notify();
1926
+ return;
1927
+ }
1928
+ if (existing) scheduledDrains.delete(sessionId);
1929
+ const signal = createDrainSignal();
1930
+ const p = new Promise((resolve) => {
1931
+ queueMicrotask(() => {
1932
+ drainSession(sessionId, {
1933
+ watchdogDueAt,
1934
+ signal
1935
+ }).then(() => resolve()).catch(() => resolve());
1936
+ });
1937
+ }).finally(() => {
1938
+ if (scheduledDrains.get(sessionId)?.promise === p) scheduledDrains.delete(sessionId);
1939
+ });
1940
+ scheduledDrains.set(sessionId, {
1941
+ signal,
1942
+ promise: p
1943
+ });
1944
+ track(p);
1945
+ platformWaitUntil(p);
1946
+ };
1947
+ const validateEvents = (sessionId, events, resolveDispatchMetadata = true) => {
1948
+ if (events.length === 0) throw new TypeError("append requires at least one event");
1949
+ return events.map((e) => {
1950
+ const schema = Object.hasOwn(defs, e.type) ? defs[e.type] : void 0;
1951
+ if (!schema) throw new A2Error("UNKNOWN_EVENT_TYPE", `contract '${name}' has no event type '${String(e.type)}'`);
1952
+ const result = validateSync(schema, e.payload, `event '${e.type}'`);
1953
+ if (result.issues) throw new A2Error("INVALID_PAYLOAD", `invalid payload for event '${e.type}' on machine '${name}'`, { details: result.issues });
1954
+ const validated = {
1955
+ type: e.type,
1956
+ payload: result.value
1957
+ };
1958
+ if (e.id !== void 0) validated.id = e.id;
1959
+ if (!resolveDispatchMetadata) return validated;
1960
+ const targets = [];
1961
+ for (const registered of registeredConsumers.values()) {
1962
+ if (!registered.laneOf || !takes(registered, e.type)) continue;
1963
+ targets.push({
1964
+ consumer: registered.name,
1965
+ lane: registered.laneOf(sessionId, validated)
1966
+ });
1967
+ }
1968
+ if (targets.length > 0) validated.targets = targets;
1969
+ return validated;
1970
+ });
1971
+ };
1972
+ /**
1973
+ * Validate + write. `onAppended` runs inside the telemetry span, so
1974
+ * the drain it schedules is created in the append's active context —
1975
+ * with a real tracer, causal work remains connected.
1976
+ */
1977
+ const appendCore = (sessionId, events, source, mode, onAppended, cause, generatedIds, requireDurableInitialArm = false, condition = {}) => telemetry.span("a2.append", {
1978
+ "a2.contract": name,
1979
+ "a2.session_id": sessionId,
1980
+ "a2.append.source": source,
1981
+ "a2.append.mode": mode,
1982
+ "a2.append.types": events.map((e) => String(e.type)).join(","),
1983
+ "a2.append.count": events.length
1984
+ }, async (span) => {
1985
+ if (mode === "dispatch" && !scheduler) throw new TypeError("append.dispatch requires a configured scheduler adapter");
1986
+ assertSessionId(sessionId);
1987
+ const validated = validateEvents(sessionId, events);
1988
+ if (cause) for (const [index, event] of validated.entries()) event.cause = generatedIds?.[index] ? {
1989
+ ...cause,
1990
+ batchSize: events.length
1991
+ } : cause;
1992
+ const store = await resolveStore();
1993
+ let rows;
1994
+ let shouldHealSession;
1995
+ try {
1996
+ const result = await store.append(nsId(sessionId), validated, {
1997
+ consumers: storeConsumers,
1998
+ ...condition
1999
+ });
2000
+ rows = result.events;
2001
+ shouldHealSession = result.hasPending && !(source === "consumer" && !validated.some(startsWork));
2002
+ } catch (err) {
2003
+ throw asStoreUnavailable(err);
2004
+ }
2005
+ const appended = rows.map(toPublic);
2006
+ const initialWatchdogAt = shouldHealSession && scheduler && source === "external" && mode === "inline" ? schedulerSlot(nextClaimWindow().watchdogAtMs) : void 0;
2007
+ const initialArm = initialWatchdogAt !== void 0 ? startSchedulerArm(sessionId, initialWatchdogAt) : null;
2008
+ const dispatchArm = shouldHealSession && mode === "dispatch" ? startSchedulerArm(sessionId, currentSchedulerSlot(Date.now())) : null;
2009
+ if (shouldHealSession && mode === "inline") onAppended(appended, initialWatchdogAt);
2010
+ if (dispatchArm) await dispatchArm;
2011
+ if (initialArm) try {
2012
+ await joinSchedulerArm(initialArm);
2013
+ } catch (err) {
2014
+ span.setAttribute("a2.append.armed", false);
2015
+ span.recordError(err);
2016
+ if (requireDurableInitialArm) throw err;
2017
+ }
2018
+ return appended;
2019
+ });
2020
+ const readHistory = async (sessionId, bounds) => {
2021
+ const gte = bounds?.gte;
2022
+ const lte = bounds?.lte;
2023
+ assertHistoryIndex("gte", gte);
2024
+ assertHistoryIndex("lte", lte);
2025
+ if (gte !== void 0 && lte !== void 0 && gte > lte) throw new RangeError("history.gte must be less than or equal to history.lte");
2026
+ if (lte === 0) return [];
2027
+ const store = await resolveStore();
2028
+ try {
2029
+ const readOptions = gte === void 0 && lte === void 0 ? void 0 : {
2030
+ ...gte === void 0 ? {} : { afterIndex: Math.max(0, gte - 1) },
2031
+ ...lte === void 0 ? {} : { throughIndex: lte }
2032
+ };
2033
+ return (await (store.readHistory ? store.readHistory(nsId(sessionId), readOptions) : store.read(nsId(sessionId), readOptions))).filter((row) => (gte === void 0 || row.index >= gte) && (lte === void 0 || row.index <= lte));
2034
+ } catch (err) {
2035
+ throw asStoreUnavailable(err);
2036
+ }
2037
+ };
2038
+ const readStoreState = async (store, sessionId, reducerName, throughIndex, snapshotThroughIndex) => {
2039
+ try {
2040
+ return await store.readState(nsId(sessionId), reducerName, throughIndex === void 0 && snapshotThroughIndex === void 0 ? void 0 : {
2041
+ ...throughIndex === void 0 ? {} : { throughIndex },
2042
+ ...snapshotThroughIndex === void 0 ? {} : { snapshotThroughIndex }
2043
+ });
2044
+ } catch (err) {
2045
+ throw asStoreUnavailable(err);
2046
+ }
2047
+ };
2048
+ const planStateReads = (batch) => {
2049
+ const bySession = /* @__PURE__ */ new Map();
2050
+ for (const entry of batch) {
2051
+ const entries = bySession.get(entry.sessionId);
2052
+ if (entries) entries.push(entry);
2053
+ else bySession.set(entry.sessionId, [entry]);
2054
+ }
2055
+ const plans = [];
2056
+ for (const [sessionId, entries] of bySession) {
2057
+ const boundaries = entries.flatMap((entry) => entry.throughIndex === void 0 ? [] : [entry.throughIndex]);
2058
+ const plan = {
2059
+ sessionId,
2060
+ entries
2061
+ };
2062
+ if (boundaries.length === entries.length) plan.throughIndex = Math.max(...boundaries);
2063
+ if (boundaries.length > 0) plan.snapshotThroughIndex = Math.min(...boundaries);
2064
+ plans.push(plan);
2065
+ }
2066
+ return plans;
2067
+ };
2068
+ const persistSnapshots = ({ store, reducer, sessionId, snapshots }) => {
2069
+ const persistence = Promise.resolve().then(() => telemetry.span("a2.snapshot", {
2070
+ "a2.contract": name,
2071
+ "a2.session_id": sessionId,
2072
+ "a2.snapshot.reducer": reducer.name,
2073
+ "a2.snapshot.index": snapshots.at(-1).index,
2074
+ "a2.snapshot.count": snapshots.length
2075
+ }, async (span) => {
2076
+ try {
2077
+ await store.putSnapshots(nsId(sessionId), reducer.name, snapshots);
2078
+ } catch (error) {
2079
+ try {
2080
+ span.recordError(error);
2081
+ } catch (telemetryError) {
2082
+ throw new AggregateError([error, telemetryError], "Snapshot write and error reporting failed", { cause: telemetryError });
2083
+ }
2084
+ }
2085
+ })).catch((error) => {
2086
+ console.error("[a2] error in a2.snapshot telemetry", {
2087
+ sessionId,
2088
+ reducer: reducer.name,
2089
+ index: snapshots.at(-1).index
2090
+ }, error);
2091
+ });
2092
+ track(persistence);
2093
+ platformWaitUntil(persistence);
2094
+ };
2095
+ const stateCache = boundedCache(STATE_CACHE);
2096
+ const cacheState = (key, next) => {
2097
+ const current = stateCache.get(key);
2098
+ if (current?.reducer === next.reducer && (current.index > next.index || current.index === next.index && current.persistedIndex >= next.persistedIndex)) return;
2099
+ stateCache.set(key, next, next.bytes);
2100
+ };
2101
+ const writeSnapshots = ({ store, reducer, sessionId, writes }) => {
2102
+ const snapshots = [...writes].toSorted(([a], [b]) => a - b).map(([index, write]) => {
2103
+ const snapshot = {
2104
+ index,
2105
+ state: encodeState({
2106
+ reducer,
2107
+ state: write.state
2108
+ })
2109
+ };
2110
+ if (write.pins.size > 0) snapshot.pins = [...write.pins.values()];
2111
+ return snapshot;
2112
+ });
2113
+ if (snapshots.length > 0) persistSnapshots({
2114
+ store,
2115
+ reducer,
2116
+ sessionId,
2117
+ snapshots
2118
+ });
2119
+ return snapshots;
2120
+ };
2121
+ /**
2122
+ * Folds `rows` from `position` in bound order, resolving each entry with a
2123
+ * clone once the rows through its bound are folded. `visit` sees each
2124
+ * entry's state before later rows are folded into it.
2125
+ */
2126
+ const foldEntries = ({ reducer, entries, rows, position, state, index, clearIndex, snapshot, visit }) => {
2127
+ const start = position;
2128
+ const ordered = entries.toSorted((a, b) => (a.throughIndex ?? Number.POSITIVE_INFINITY) - (b.throughIndex ?? Number.POSITIVE_INFINITY));
2129
+ for (const entry of ordered) {
2130
+ const target = entry.throughIndex ?? Number.POSITIVE_INFINITY;
2131
+ while (position < rows.length && rows[position].index <= target) {
2132
+ const row = rows[position];
2133
+ state = foldEvent(reducer, state, toPublic(row));
2134
+ index = row.index;
2135
+ position += 1;
2136
+ }
2137
+ if (entry.triggerIndex !== void 0 && entry.triggerIndex <= clearIndex || entry.throughIndex !== void 0 && entry.throughIndex > 0 && entry.throughIndex < clearIndex) {
2138
+ entry.reject(sessionClearedError(`session '${entry.sessionId}' was cleared at index ${clearIndex}`));
2139
+ continue;
2140
+ }
2141
+ entry.span.setAttribute("a2.state.snapshot", snapshot);
2142
+ entry.span.setAttribute("a2.state.folded", position - start);
2143
+ entry.span.setAttribute("a2.state.index", index);
2144
+ visit(entry, state, index, position - start);
2145
+ entry.resolve({
2146
+ state: cloneInitial(state),
2147
+ index,
2148
+ ...clearIndex > 0 && index >= clearIndex ? { clearIndex } : {}
2149
+ });
2150
+ }
2151
+ return {
2152
+ state,
2153
+ index,
2154
+ position
2155
+ };
2156
+ };
2157
+ /**
2158
+ * Events from `fromIndex` (inclusive) through `throughIndex` or the newest
2159
+ * event, or null when the tail is too long to be worth folding in memory.
2160
+ */
2161
+ const readCachedTail = async (store, sessionId, fromIndex, throughIndex) => {
2162
+ const readTail = stateTailReaders.get(store);
2163
+ if (readTail) try {
2164
+ return await readTail(nsId(sessionId), fromIndex, throughIndex);
2165
+ } catch (err) {
2166
+ throw asStoreUnavailable(err);
2167
+ }
2168
+ const limit = fromIndex + STATE_CACHE.maxTail;
2169
+ const capped = throughIndex === void 0 || throughIndex > limit;
2170
+ const rows = await readHistory(sessionId, {
2171
+ gte: fromIndex,
2172
+ lte: capped ? limit : throughIndex
2173
+ });
2174
+ return capped && rows.at(-1)?.index === limit ? null : rows;
2175
+ };
2176
+ /**
2177
+ * Serves a plan from the cached state when every read is at or past the
2178
+ * cached index. A read bounded at the cached index by an event whose id
2179
+ * matches the cached one (a consumer's own trigger) needs no store request;
2180
+ * any other read fetches the tail from the cached event onward and checks
2181
+ * that event's id. Returns false when the store must answer instead.
2182
+ */
2183
+ const foldCachedPlan = async (store, reducer, plan) => {
2184
+ const key = stateCacheKey(plan.sessionId, reducer.name);
2185
+ const cached = stateCache.get(key);
2186
+ if (cached?.reducer !== reducer) return false;
2187
+ if (plan.entries.some((entry) => entry.throughIndex !== void 0 && entry.throughIndex < cached.index)) return false;
2188
+ let rows = [];
2189
+ if (plan.entries.some((entry) => entry.throughIndex !== cached.index || entry.throughEventId !== cached.lastId)) {
2190
+ const tail = await readCachedTail(store, plan.sessionId, cached.index, plan.throughIndex);
2191
+ if (!tail) return false;
2192
+ if (tail[0]?.index !== cached.index || tail[0].id !== cached.lastId || tail.some((row, position) => position > 0 && isSessionCleared(row))) {
2193
+ stateCache.delete(key);
2194
+ return false;
2195
+ }
2196
+ rows = tail;
2197
+ }
2198
+ const writes = /* @__PURE__ */ new Map();
2199
+ const folded = foldEntries({
2200
+ reducer,
2201
+ entries: plan.entries,
2202
+ rows,
2203
+ position: 1,
2204
+ state: rows.length > 1 ? cloneInitial(cached.state) : cached.state,
2205
+ index: cached.index,
2206
+ clearIndex: cached.clearIndex,
2207
+ snapshot: "memory",
2208
+ visit: (entry, state, index) => {
2209
+ if (entry.pin !== void 0) addSnapshotWrite(writes, index, state, entry.pin);
2210
+ }
2211
+ });
2212
+ const added = Math.max(0, folded.position - 1);
2213
+ const rewritesHead = folded.index - cached.persistedIndex >= STATE_CACHE.snapshotEvery;
2214
+ if (rewritesHead && !writes.has(folded.index)) writes.set(folded.index, {
2215
+ state: folded.state,
2216
+ pins: /* @__PURE__ */ new Map()
2217
+ });
2218
+ const snapshots = writeSnapshots({
2219
+ store,
2220
+ reducer,
2221
+ sessionId: plan.sessionId,
2222
+ writes
2223
+ });
2224
+ const measure = rewritesHead || cached.unmeasured + added >= STATE_CACHE.measureEvery;
2225
+ let grown = 0;
2226
+ if (!measure) for (let position = 1; position < folded.position; position += 1) grown += JSON.stringify(rows[position].payload)?.length ?? 0;
2227
+ cacheState(key, {
2228
+ reducer,
2229
+ index: folded.index,
2230
+ lastId: added > 0 ? rows[folded.position - 1].id : cached.lastId,
2231
+ state: folded.state,
2232
+ bytes: measure ? measuredBytes(reducer, folded.state, folded.index, snapshots) : cached.bytes + grown,
2233
+ unmeasured: measure ? 0 : cached.unmeasured + added,
2234
+ persistedIndex: Math.max(cached.persistedIndex, snapshots.at(-1)?.index ?? 0),
2235
+ clearIndex: cached.clearIndex
2236
+ });
2237
+ return true;
2238
+ };
2239
+ const foldStatePlan = async (store, reducer, plan, stateRead) => {
2240
+ let state = cloneInitial(reducer.initialState);
2241
+ let index = 0;
2242
+ let snapshotOutcome = "miss";
2243
+ const snap = stateRead.snapshot;
2244
+ let rows = stateRead.events;
2245
+ let clearIndex = stateRead.clearIndex ?? 0;
2246
+ if (snap) {
2247
+ let decoded;
2248
+ try {
2249
+ decoded = decodeState({
2250
+ reducer,
2251
+ state: snap.state
2252
+ });
2253
+ } catch {
2254
+ snapshotOutcome = "rejected";
2255
+ }
2256
+ if (snapshotOutcome !== "rejected" && reducer.stateSchema) {
2257
+ const result = validateSync(reducer.stateSchema, decoded, "the stateSchema");
2258
+ if (result.issues) snapshotOutcome = "rejected";
2259
+ else {
2260
+ state = result.value;
2261
+ index = snap.index;
2262
+ snapshotOutcome = "hit";
2263
+ }
2264
+ } else if (snapshotOutcome !== "rejected") {
2265
+ state = decoded;
2266
+ index = snap.index;
2267
+ snapshotOutcome = "hit";
2268
+ }
2269
+ }
2270
+ if (snapshotOutcome === "rejected") {
2271
+ try {
2272
+ rows = await store.read(nsId(plan.sessionId), plan.throughIndex === void 0 ? void 0 : { throughIndex: plan.throughIndex });
2273
+ } catch (err) {
2274
+ throw asStoreUnavailable(err);
2275
+ }
2276
+ if (rows[0] && isSessionCleared(rows[0])) clearIndex = Math.max(clearIndex, rows[0].index);
2277
+ }
2278
+ const writes = /* @__PURE__ */ new Map();
2279
+ const folded = foldEntries({
2280
+ reducer,
2281
+ entries: plan.entries,
2282
+ rows,
2283
+ position: 0,
2284
+ state,
2285
+ index,
2286
+ clearIndex,
2287
+ snapshot: snapshotOutcome,
2288
+ visit: (entry, entryState, entryIndex, count) => {
2289
+ if (entryIndex === 0) return;
2290
+ if (count === 0 && entry.pin === void 0) return;
2291
+ const advancesHead = stateRead.headIndex === null || entryIndex > stateRead.headIndex;
2292
+ const repairsHead = snapshotOutcome === "rejected" && entryIndex === stateRead.headIndex;
2293
+ if (!advancesHead && !repairsHead && entry.pin === void 0) return;
2294
+ addSnapshotWrite(writes, entryIndex, entryState, entry.pin);
2295
+ }
2296
+ });
2297
+ const snapshots = writeSnapshots({
2298
+ store,
2299
+ reducer,
2300
+ sessionId: plan.sessionId,
2301
+ writes
2302
+ });
2303
+ if (folded.position > 0 && STATE_CACHE.maxEntries > 0) cacheState(stateCacheKey(plan.sessionId, reducer.name), {
2304
+ reducer,
2305
+ index: folded.index,
2306
+ lastId: rows[folded.position - 1].id,
2307
+ state: folded.state,
2308
+ bytes: measuredBytes(reducer, folded.state, folded.index, snapshots),
2309
+ unmeasured: 0,
2310
+ persistedIndex: Math.min(Math.max(stateRead.headIndex ?? 0, ...writes.keys()), folded.index),
2311
+ clearIndex
2312
+ });
2313
+ };
2314
+ const pendingStateReads = /* @__PURE__ */ new Map();
2315
+ const flushStateReads = async (store, reducer, batch) => {
2316
+ const plans = [];
2317
+ await Promise.all(planStateReads(batch).map(async (plan) => {
2318
+ try {
2319
+ if (!await foldCachedPlan(store, reducer, plan)) plans.push(plan);
2320
+ } catch (error) {
2321
+ for (const entry of plan.entries) entry.reject(error);
2322
+ }
2323
+ }));
2324
+ if (plans.length === 0) return;
2325
+ let reads;
2326
+ try {
2327
+ reads = store.readStates ? await store.readStates(plans.map((plan) => ({
2328
+ sessionId: nsId(plan.sessionId),
2329
+ ...plan.throughIndex === void 0 ? {} : { throughIndex: plan.throughIndex },
2330
+ ...plan.snapshotThroughIndex === void 0 ? {} : { snapshotThroughIndex: plan.snapshotThroughIndex }
2331
+ })), reducer.name) : plans.map((plan) => readStoreState(store, plan.sessionId, reducer.name, plan.throughIndex, plan.snapshotThroughIndex));
2332
+ if (reads.length !== plans.length) throw new TypeError("store.readStates must return one result per request");
2333
+ } catch (error) {
2334
+ const failure = asStoreUnavailable(error);
2335
+ for (const plan of plans) for (const entry of plan.entries) entry.reject(failure);
2336
+ return;
2337
+ }
2338
+ await Promise.all(plans.map(async (plan, position) => {
2339
+ try {
2340
+ await foldStatePlan(store, reducer, plan, await reads[position]);
2341
+ } catch (error) {
2342
+ for (const entry of plan.entries) entry.reject(error);
2343
+ }
2344
+ }));
2345
+ };
2346
+ const enqueueStateRead = (store, sessionId, reducer, bounds, span) => new Promise((resolve, reject) => {
2347
+ const reducerName = reducer.name;
2348
+ let batch = pendingStateReads.get(reducerName);
2349
+ if (!batch) {
2350
+ const opened = [];
2351
+ pendingStateReads.set(reducerName, opened);
2352
+ queueMicrotask(() => {
2353
+ pendingStateReads.delete(reducerName);
2354
+ flushStateReads(store, reducer, opened);
2355
+ });
2356
+ batch = opened;
2357
+ }
2358
+ batch.push({
2359
+ sessionId,
2360
+ ...bounds,
2361
+ span,
2362
+ resolve,
2363
+ reject
2364
+ });
2365
+ });
2366
+ const readState = async (sessionId, reducer, bounds) => {
2367
+ const store = await resolveStore();
2368
+ return telemetry.span("a2.state", {
2369
+ "a2.contract": name,
2370
+ "a2.session_id": sessionId,
2371
+ "a2.state.reducer": reducer.name
2372
+ }, (span) => enqueueStateRead(store, sessionId, reducer, bounds, span));
2373
+ };
2374
+ const makeSchedule = (sessionId, trigger) => {
2375
+ const triggerEventId = trigger?.id ?? null;
2376
+ /** Timers a consumer sets key on its name, except A2's own. */
2377
+ const triggerConsumer = trigger && !registeredConsumers.get(trigger.consumer)?.anonymousIds ? trigger.consumer : void 0;
2378
+ const triggerCreatedAt = trigger?.createdAt.getTime();
2379
+ const clearIndex = trigger?.clearIndex ?? 0;
2380
+ const schedule = async (scheduleName, timing, ...events) => {
2381
+ if (!scheduler) throw new TypeError("session.schedule requires a configured scheduler adapter");
2382
+ assertScheduleName(scheduleName);
2383
+ if (events.length === 0) throw new TypeError("schedule requires at least one event");
2384
+ const dueAt = scheduleDueAt(timing, triggerCreatedAt ?? Date.now());
2385
+ const payloads = events.map((event) => cloneScheduledPayload(event.payload));
2386
+ const snapshottedEvents = events.map((event, index) => event.id === void 0 ? {
2387
+ type: event.type,
2388
+ payload: payloads[index]
2389
+ } : {
2390
+ type: event.type,
2391
+ payload: payloads[index],
2392
+ id: event.id
2393
+ });
2394
+ const validated = validateEvents(sessionId, structuredClone(snapshottedEvents), false);
2395
+ const scheduleId = await deterministicScheduleId(name, sessionId, triggerEventId, scheduleName, clearIndex, triggerConsumer);
2396
+ const scheduledEvents = await Promise.all(validated.map(async (event, item) => ({
2397
+ id: event.id ?? await deterministicScheduledEventId(scheduleId, item),
2398
+ type: event.type,
2399
+ payload: payloads[item]
2400
+ })));
2401
+ if (new Set(scheduledEvents.map((event) => event.id)).size !== scheduledEvents.length) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "scheduled batch contains the same event id more than once");
2402
+ try {
2403
+ await scheduler.schedule({
2404
+ version: 1,
2405
+ kind: "append",
2406
+ id: scheduleId,
2407
+ contract: name,
2408
+ sessionId,
2409
+ dueAt,
2410
+ events: scheduledEvents,
2411
+ ...trigger ? { originIndex: trigger.index } : {}
2412
+ });
2413
+ } catch (error) {
2414
+ throw markSchedulerSendFailure(error);
2415
+ }
2416
+ };
2417
+ const clear = async (scheduleName, clearOptions) => {
2418
+ if (!scheduler) throw new TypeError("session.schedule.clear requires a configured scheduler adapter");
2419
+ assertScheduleName(scheduleName);
2420
+ if (clearOptions === null || typeof clearOptions !== "object") throw new TypeError("schedule.clear requires an ifLastIndex");
2421
+ const { ifLastIndex, ...timing } = clearOptions;
2422
+ assertIfLastIndex(ifLastIndex);
2423
+ const dueAt = scheduleDueAt(timing, triggerCreatedAt ?? Date.now());
2424
+ const store = await resolveStore();
2425
+ if (!store.clear || !store.reclaim) throw new TypeError("session.schedule.clear requires a store that supports clearing");
2426
+ const id = await deterministicScheduleClearId({
2427
+ contract: name,
2428
+ sessionId,
2429
+ triggerEventId,
2430
+ clearIndex,
2431
+ name: scheduleName,
2432
+ ifLastIndex,
2433
+ ...triggerConsumer === void 0 ? {} : { consumer: triggerConsumer }
2434
+ });
2435
+ try {
2436
+ await scheduler.schedule({
2437
+ version: 1,
2438
+ kind: "clear",
2439
+ id,
2440
+ contract: name,
2441
+ sessionId,
2442
+ dueAt,
2443
+ ifLastIndex
2444
+ });
2445
+ } catch (error) {
2446
+ throw markSchedulerSendFailure(error);
2447
+ }
2448
+ };
2449
+ return Object.assign(schedule, { clear });
2450
+ };
2451
+ const toSessionEvent = (id, event) => ({
2452
+ id: event.id,
2453
+ type: event.type,
2454
+ payload: event.payload,
2455
+ index: event.index,
2456
+ sessionId: id,
2457
+ createdAt: event.createdAt
2458
+ });
2459
+ const streamEvents = (id, startAfter) => {
2460
+ let closed = false;
2461
+ let inner;
2462
+ let stopActivity;
2463
+ const activity = createStreamActivity(() => {
2464
+ if (inner && !closed) streamActivities.get(inner)?.activate();
2465
+ });
2466
+ let closing;
2467
+ const close = () => {
2468
+ closed = true;
2469
+ closing ??= (async () => {
2470
+ stopActivity?.();
2471
+ await inner?.return?.();
2472
+ })();
2473
+ return closing;
2474
+ };
2475
+ const outer = async function* () {
2476
+ const store = await resolveStore();
2477
+ if (closed) return;
2478
+ inner = store.stream(nsId(id), { startAfter })[Symbol.asyncIterator]();
2479
+ const sourceActivity = streamActivities.get(inner);
2480
+ if (sourceActivity) {
2481
+ stopActivity = sourceActivity.subscribe(activity.setIdle);
2482
+ activity.setIdle(sourceActivity.idle);
2483
+ }
2484
+ try {
2485
+ for (;;) {
2486
+ if (closed) return;
2487
+ const result = await inner.next();
2488
+ if (closed || result.done) return;
2489
+ yield toSessionEvent(id, result.value);
2490
+ }
2491
+ } finally {
2492
+ await close();
2493
+ }
2494
+ };
2495
+ const iterator = outer();
2496
+ return { [Symbol.asyncIterator]() {
2497
+ const stream = {
2498
+ next: () => iterator.next(),
2499
+ async return() {
2500
+ await close();
2501
+ return iterator.return(void 0);
2502
+ },
2503
+ async throw(error) {
2504
+ await close();
2505
+ return iterator.throw(error);
2506
+ }
2507
+ };
2508
+ streamActivities.set(stream, activity);
2509
+ bufferedEvents.set(stream, () => {
2510
+ const event = closed || !inner ? void 0 : takeBuffered(inner);
2511
+ if (!event) return void 0;
2512
+ if (!isSerializedEvent(event)) return toSessionEvent(id, event);
2513
+ event.sessionId = id;
2514
+ return event;
2515
+ });
2516
+ return stream;
2517
+ } };
2518
+ };
2519
+ const requirePresence = (store) => {
2520
+ if (!store.presence) throw presenceNotSupported();
2521
+ return store.presence;
2522
+ };
2523
+ const setPresence = async (sessionId, patch, fallbackSeen) => {
2524
+ if (typeof patch.participant !== "string" || patch.participant.length === 0) throw new TypeError("presence participant must be a non-empty string");
2525
+ if (RESERVED_PARTICIPANT_IDS.has(patch.participant)) throw new TypeError(`presence participant must not be '${patch.participant}'`);
2526
+ if (patch.at !== void 0 && (typeof patch.at !== "number" || !Number.isFinite(patch.at) || patch.at < 0 || patch.at > 864e13)) throw new TypeError("presence at must be non-negative epoch milliseconds within the Date range");
2527
+ const validated = nullProtoRecord();
2528
+ for (const [field, value] of Object.entries(patch.values)) {
2529
+ if (value === void 0) continue;
2530
+ const schema = Object.hasOwn(presenceDefs, field) ? presenceDefs[field] : RESERVED_PARTICIPANT_IDS.has(field) ? void 0 : presenceDefs["*"];
2531
+ if (!schema) throw new A2Error("UNKNOWN_PRESENCE_FIELD", `contract '${name}' has no presence field '${field}'`);
2532
+ if (value === null) {
2533
+ validated[field] = null;
2534
+ continue;
2535
+ }
2536
+ const result = validateSync(schema, value, `presence field '${field}'`);
2537
+ if (result.issues) throw new A2Error("INVALID_PAYLOAD", `invalid value for presence field '${field}' on machine '${name}'`, { details: result.issues });
2538
+ validated[field] = result.value;
2539
+ }
2540
+ const store = await resolveStore();
2541
+ try {
2542
+ await requirePresence(store).set(nsId(sessionId), patch.participant, validated, {
2543
+ seen: patch.seen ?? fallbackSeen,
2544
+ at: new Date(patch.at ?? Date.now()),
2545
+ ttlMs: presenceTtlMs
2546
+ });
2547
+ } catch (err) {
2548
+ throw asStoreUnavailable(err);
2549
+ }
2550
+ };
2551
+ const readPresenceMap = async (sessionId) => {
2552
+ const store = await resolveStore();
2553
+ let rows;
2554
+ try {
2555
+ rows = await requirePresence(store).read(nsId(sessionId));
2556
+ } catch (err) {
2557
+ throw asStoreUnavailable(err);
2558
+ }
2559
+ return foldPresenceRows(rows);
2560
+ };
2561
+ /**
2562
+ * The two-plane feed. Patches ride `subscribe` when the adapter has
2563
+ * the push tier; without it the map is re-read and diffed whenever
2564
+ * the event feed wakes, and at the poll idle ceiling while it is
2565
+ * silent — degraded means later, not lost while watched.
2566
+ */
2567
+ const streamWithPresence = (id, startAfter) => {
2568
+ const ns = nsId(id);
2569
+ let closed = false;
2570
+ let events;
2571
+ let pendingEvent = null;
2572
+ let unsubscribe;
2573
+ let sleeper = null;
2574
+ let wakeQueue = null;
2575
+ let presenceInterval = Math.min(POLL_TIMINGS.activeFloorMs, POLL_TIMINGS.idleCeilingMs);
2576
+ let presenceActivityVersion = 0;
2577
+ let stopActivity;
2578
+ const activity = createStreamActivity(() => {
2579
+ if (closed) return;
2580
+ presenceActivityVersion += 1;
2581
+ presenceInterval = Math.min(POLL_TIMINGS.activeFloorMs, POLL_TIMINGS.idleCeilingMs);
2582
+ sleeper?.cancel();
2583
+ if (events) streamActivities.get(events)?.activate();
2584
+ });
2585
+ let closing;
2586
+ const close = () => {
2587
+ closed = true;
2588
+ sleeper?.cancel();
2589
+ wakeQueue?.();
2590
+ closing ??= (async () => {
2591
+ try {
2592
+ stopActivity?.();
2593
+ unsubscribe?.();
2594
+ } finally {
2595
+ await events?.return?.();
2596
+ }
2597
+ })();
2598
+ return closing;
2599
+ };
2600
+ const outer = async function* () {
2601
+ const store = await resolveStore();
2602
+ if (closed) return;
2603
+ const api = requirePresence(store);
2604
+ const readRows = async () => {
2605
+ try {
2606
+ return await api.read(ns);
2607
+ } catch (err) {
2608
+ throw asStoreUnavailable(err);
2609
+ }
2610
+ };
2611
+ const painted = /* @__PURE__ */ new Map();
2612
+ const paintedDeletes = presenceTombstones();
2613
+ const diffRows = (rows) => {
2614
+ const patches = [];
2615
+ const live = /* @__PURE__ */ new Map();
2616
+ for (const row of rows) {
2617
+ let liveFields = live.get(row.participant);
2618
+ if (!liveFields) {
2619
+ liveFields = /* @__PURE__ */ new Set();
2620
+ live.set(row.participant, liveFields);
2621
+ }
2622
+ liveFields.add(row.field);
2623
+ const stamp = {
2624
+ seen: row.seen,
2625
+ atMs: row.at.getTime(),
2626
+ value: fingerprint(row.value)
2627
+ };
2628
+ const prior = painted.get(row.participant)?.get(row.field);
2629
+ if (prior && prior.seen === stamp.seen && prior.atMs === stamp.atMs && prior.value === stamp.value) continue;
2630
+ let paintedFields = painted.get(row.participant);
2631
+ if (!paintedFields) {
2632
+ paintedFields = /* @__PURE__ */ new Map();
2633
+ painted.set(row.participant, paintedFields);
2634
+ }
2635
+ paintedFields.set(row.field, stamp);
2636
+ patches.push({
2637
+ participant: row.participant,
2638
+ values: { [row.field]: row.value },
2639
+ seen: row.seen,
2640
+ at: row.at
2641
+ });
2642
+ }
2643
+ for (const [participant, fields] of painted) {
2644
+ for (const [field, prior] of fields) {
2645
+ if (live.get(participant)?.has(field)) continue;
2646
+ fields.delete(field);
2647
+ patches.push({
2648
+ participant,
2649
+ values: { [field]: null },
2650
+ seen: prior.seen,
2651
+ at: new Date(prior.atMs)
2652
+ });
2653
+ }
2654
+ if (fields.size === 0) painted.delete(participant);
2655
+ }
2656
+ return patches;
2657
+ };
2658
+ const paint = (patch) => {
2659
+ let fields = painted.get(patch.participant);
2660
+ for (const [field, value] of Object.entries(patch.values)) {
2661
+ const write = {
2662
+ participant: patch.participant,
2663
+ field,
2664
+ at: patch.at
2665
+ };
2666
+ if (value === null || value === void 0) {
2667
+ fields?.delete(field);
2668
+ if (value === null) paintedDeletes.keep(write);
2669
+ continue;
2670
+ }
2671
+ paintedDeletes.drop(write);
2672
+ if (!fields) {
2673
+ fields = /* @__PURE__ */ new Map();
2674
+ painted.set(patch.participant, fields);
2675
+ }
2676
+ fields.set(field, {
2677
+ seen: patch.seen,
2678
+ atMs: patch.at.getTime(),
2679
+ value: fingerprint(value)
2680
+ });
2681
+ }
2682
+ if (fields?.size === 0) painted.delete(patch.participant);
2683
+ };
2684
+ const queue = /* @__PURE__ */ new Map();
2685
+ const enqueue = (patch) => {
2686
+ if (closed) return;
2687
+ activity.activate();
2688
+ for (const [field, value] of Object.entries(patch.values)) {
2689
+ if (value === void 0) continue;
2690
+ let fields = queue.get(patch.participant);
2691
+ if (!fields) {
2692
+ fields = /* @__PURE__ */ new Map();
2693
+ queue.set(patch.participant, fields);
2694
+ }
2695
+ const queued = fields.get(field);
2696
+ if (queued && queued.at.getTime() > patch.at.getTime()) continue;
2697
+ fields.set(field, {
2698
+ value,
2699
+ seen: patch.seen,
2700
+ at: patch.at
2701
+ });
2702
+ }
2703
+ wakeQueue?.();
2704
+ };
2705
+ const outdated = (write) => {
2706
+ const prior = painted.get(write.participant)?.get(write.field);
2707
+ return prior !== void 0 && prior.atMs > write.at.getTime() || paintedDeletes.outranks(write);
2708
+ };
2709
+ const dequeue = () => {
2710
+ for (const [participant, fields] of queue) {
2711
+ for (const [field, stamp] of fields) {
2712
+ fields.delete(field);
2713
+ if (fields.size === 0) queue.delete(participant);
2714
+ if (outdated({
2715
+ participant,
2716
+ field,
2717
+ at: stamp.at
2718
+ })) continue;
2719
+ return {
2720
+ participant,
2721
+ values: { [field]: stamp.value },
2722
+ seen: stamp.seen,
2723
+ at: stamp.at
2724
+ };
2725
+ }
2726
+ queue.delete(participant);
2727
+ }
2728
+ return null;
2729
+ };
2730
+ try {
2731
+ unsubscribe = api.subscribe?.(ns, enqueue);
2732
+ events = store.stream(ns, { startAfter })[Symbol.asyncIterator]();
2733
+ const sourceActivity = streamActivities.get(events);
2734
+ if (sourceActivity) {
2735
+ stopActivity = sourceActivity.subscribe(activity.setIdle);
2736
+ activity.setIdle(sourceActivity.idle);
2737
+ }
2738
+ const snapshotRows = await readRows();
2739
+ if (closed) return;
2740
+ for (const row of snapshotRows) {
2741
+ let fields = painted.get(row.participant);
2742
+ if (!fields) {
2743
+ fields = /* @__PURE__ */ new Map();
2744
+ painted.set(row.participant, fields);
2745
+ }
2746
+ fields.set(row.field, {
2747
+ seen: row.seen,
2748
+ atMs: row.at.getTime(),
2749
+ value: fingerprint(row.value)
2750
+ });
2751
+ }
2752
+ yield { snapshot: foldPresenceRows(snapshotRows) };
2753
+ for (;;) {
2754
+ if (closed) return;
2755
+ for (;;) {
2756
+ const patch = dequeue();
2757
+ if (!patch) break;
2758
+ if (closed) return;
2759
+ paint(patch);
2760
+ yield patch;
2761
+ }
2762
+ pendingEvent ??= events.next();
2763
+ let woke;
2764
+ if (unsubscribe) {
2765
+ const arrival = new Promise((resolve) => {
2766
+ wakeQueue = resolve;
2767
+ });
2768
+ woke = await Promise.race([pendingEvent.then(() => "event"), arrival.then(() => "patch")]);
2769
+ wakeQueue = null;
2770
+ if (closed) return;
2771
+ if (woke === "patch") continue;
2772
+ } else {
2773
+ sleeper = defaultSleep(presenceInterval);
2774
+ woke = await Promise.race([pendingEvent.then(() => "event"), sleeper.promise.then(() => "tick")]);
2775
+ sleeper.cancel();
2776
+ sleeper = null;
2777
+ }
2778
+ if (closed) return;
2779
+ if (woke === "event") {
2780
+ const result = await pendingEvent;
2781
+ pendingEvent = null;
2782
+ if (closed || result.done) return;
2783
+ activity.activate();
2784
+ yield toSessionEvent(id, result.value);
2785
+ }
2786
+ if (!closed && !unsubscribe) {
2787
+ const version = presenceActivityVersion;
2788
+ const rows = await readRows();
2789
+ if (closed) return;
2790
+ const patches = diffRows(rows);
2791
+ if (patches.length > 0) activity.activate();
2792
+ else if (version === presenceActivityVersion) presenceInterval = Math.min(presenceInterval * 2, POLL_TIMINGS.idleCeilingMs);
2793
+ for (const patch of patches) {
2794
+ if (closed) return;
2795
+ yield patch;
2796
+ }
2797
+ }
2798
+ }
2799
+ } finally {
2800
+ pendingEvent?.catch(() => {});
2801
+ await close();
2802
+ wakeQueue = null;
2803
+ }
2804
+ };
2805
+ const iterator = outer();
2806
+ return { [Symbol.asyncIterator]() {
2807
+ const stream = {
2808
+ next: () => iterator.next(),
2809
+ async return() {
2810
+ await close();
2811
+ return iterator.return(void 0);
2812
+ },
2813
+ async throw(error) {
2814
+ await close();
2815
+ return iterator.throw(error);
2816
+ }
2817
+ };
2818
+ streamActivities.set(stream, activity);
2819
+ bufferedEvents.set(stream, () => {
2820
+ if (closed || !events || pendingEvent) return void 0;
2821
+ const event = takeBuffered(events);
2822
+ if (!event) return void 0;
2823
+ if (!isSerializedEvent(event)) return toSessionEvent(id, event);
2824
+ event.sessionId = id;
2825
+ return event;
2826
+ });
2827
+ return stream;
2828
+ } };
2829
+ };
2830
+ const reclaimAll = async (store, ns) => {
2831
+ for (let stalls = 0;;) {
2832
+ let batch;
2833
+ try {
2834
+ batch = await store.reclaim(ns);
2835
+ } catch (err) {
2836
+ throw asStoreUnavailable(err);
2837
+ }
2838
+ if (batch.done) return;
2839
+ if (batch.deleted > 0) {
2840
+ stalls = 0;
2841
+ continue;
2842
+ }
2843
+ stalls += 1;
2844
+ if (stalls === RECLAIM_STALL_LIMIT) throw new A2Error("STORE_UNAVAILABLE", `deleting the cleared history of session '${stripNs(ns)}' made no progress`);
2845
+ await defaultSleep(RECLAIM_STALL_MS).promise;
2846
+ }
2847
+ };
2848
+ const clearSession = async (sessionId, clearOptions, attempt) => {
2849
+ const ifLastIndex = clearOptions?.ifLastIndex;
2850
+ if (ifLastIndex !== void 0) assertIfLastIndex(ifLastIndex);
2851
+ const store = await resolveStore();
2852
+ if (!store.clear || !store.reclaim) throw new TypeError("session.clear requires a store that supports clearing");
2853
+ const ns = nsId(sessionId);
2854
+ let result;
2855
+ try {
2856
+ result = await store.clear({
2857
+ sessionId: ns,
2858
+ ...ifLastIndex === void 0 ? {} : { ifLastIndex },
2859
+ ...attempt ? { cause: attempt.cause } : {}
2860
+ });
2861
+ } catch (err) {
2862
+ throw asStoreUnavailable(err);
2863
+ }
2864
+ if (result.cleared) {
2865
+ const cachePrefix = stateCacheKey(sessionId, "");
2866
+ stateCache.deleteWhere((key) => key.startsWith(cachePrefix));
2867
+ }
2868
+ const deletion = reclaimAll(store, ns);
2869
+ if (attempt) {
2870
+ if (attempt.cause.index <= result.clearIndex) attempt.end();
2871
+ const kept = deletion.catch(() => void 0);
2872
+ track(kept);
2873
+ platformWaitUntil(kept);
2874
+ }
2875
+ await deletion;
2876
+ return {
2877
+ cleared: result.cleared,
2878
+ index: result.index
2879
+ };
2880
+ };
2881
+ const redrivingStore = async (method) => {
2882
+ const store = await resolveStore();
2883
+ if (!store.deadLetters || !store.redrive) throw new TypeError(`session.${method} requires a store that supports redriving dead letters`);
2884
+ return store;
2885
+ };
2886
+ const listDeadLetters = async (sessionId) => {
2887
+ const store = await redrivingStore("deadLetters");
2888
+ let rows;
2889
+ try {
2890
+ rows = await store.deadLetters(nsId(sessionId));
2891
+ } catch (err) {
2892
+ throw asStoreUnavailable(err);
2893
+ }
2894
+ return rows.flatMap((row) => row.failedAt === null ? [] : [{
2895
+ ...toPublic(row),
2896
+ consumer: row.consumer,
2897
+ lane: row.lane,
2898
+ attemptCount: row.attemptCount,
2899
+ failureCount: row.failureCount,
2900
+ lastError: row.lastError,
2901
+ failedAt: row.failedAt
2902
+ }]);
2903
+ };
2904
+ const redriveEvent = async (sessionId, target, redriveOptions) => {
2905
+ const index = target?.index;
2906
+ const redriven = target?.consumer;
2907
+ assertRedriveIndex(index);
2908
+ if (typeof redriven !== "string" || redriven.length === 0) throw new TypeError("redrive requires a consumer name");
2909
+ const action = redriveOptions?.action;
2910
+ if (action !== "retry" && action !== "skip") throw new TypeError("redrive requires action 'retry' or 'skip'");
2911
+ return telemetry.span("a2.redrive", {
2912
+ "a2.contract": name,
2913
+ "a2.session_id": sessionId,
2914
+ "a2.redrive.index": index,
2915
+ "a2.redrive.consumer": redriven,
2916
+ "a2.redrive.action": action
2917
+ }, async (span) => {
2918
+ const store = await redrivingStore("redrive");
2919
+ let result;
2920
+ try {
2921
+ result = await store.redrive({
2922
+ sessionId: nsId(sessionId),
2923
+ consumer: redriven,
2924
+ index,
2925
+ action,
2926
+ consumers: storeConsumers
2927
+ });
2928
+ } catch (err) {
2929
+ throw asStoreUnavailable(err);
2930
+ }
2931
+ span.setAttribute("a2.redrive.redriven", result.redriven);
2932
+ if (result.hasPending) {
2933
+ const watchdogAt = scheduler ? schedulerSlot(nextClaimWindow().watchdogAtMs) : void 0;
2934
+ const arm = watchdogAt === void 0 ? null : startSchedulerArm(sessionId, watchdogAt);
2935
+ scheduleDrain(sessionId, watchdogAt);
2936
+ if (arm) try {
2937
+ await joinSchedulerArm(arm);
2938
+ } catch (err) {
2939
+ span.setAttribute("a2.redrive.armed", false);
2940
+ span.recordError(err);
2941
+ }
2942
+ }
2943
+ return { redriven: result.redriven };
2944
+ });
2945
+ };
2946
+ /**
2947
+ * `session.consume`: wakes the consumer's cursor, then drains only that
2948
+ * consumer until its head lies past `through`. A head another invocation
2949
+ * holds, or one waiting out a failure, is waited for; a dead-lettered head
2950
+ * throws.
2951
+ */
2952
+ /** Per session, which consumer's running head is waiting in `consume` on which: a cycle never ends. */
2953
+ const consumeWaits = /* @__PURE__ */ new Map();
2954
+ const consumeSession = (sessionId, defined, consumeOptions = {}, trigger = null) => {
2955
+ assertSessionId(sessionId);
2956
+ if (defined?.contract?.name !== name || !defined.spec) throw new TypeError(`session.consume for '${name}' got a consumer of another contract`);
2957
+ const own = definitions.get(defined.name);
2958
+ if (own !== void 0 && own !== defined) throw new TypeError(`this server runs a different consumer named '${defined.name}'`);
2959
+ if (defined.name === trigger?.consumer) throw new TypeError(`consumer '${defined.name}' can't consume itself: its own head is running`);
2960
+ const registered = own ? registeredConsumers.get(defined.name) : registrationOf(defined);
2961
+ const log = registered.log;
2962
+ if (!log) throw new TypeError(`consumer '${defined.name}' needs a string lane to be consumed: only then does it have one position`);
2963
+ const { through: requested, signal } = consumeOptions;
2964
+ if (requested !== void 0) assertConsumeIndex(requested);
2965
+ const waiter = trigger?.consumer;
2966
+ const waits = waiter === void 0 ? void 0 : consumeWaits.get(sessionId) ?? consumeWaits.set(sessionId, /* @__PURE__ */ new Map()).get(sessionId);
2967
+ let cycle = false;
2968
+ if (waiter !== void 0 && waits) {
2969
+ for (let next = defined.name; next !== void 0 && !cycle; next = waits.get(next)) cycle = next === waiter;
2970
+ if (!cycle) waits.set(waiter, defined.name);
2971
+ }
2972
+ const storeConsumer = {
2973
+ name: registered.name,
2974
+ log
2975
+ };
2976
+ const consumed = telemetry.span("a2.consume", {
2977
+ "a2.contract": name,
2978
+ "a2.session_id": sessionId,
2979
+ "a2.consume.consumer": registered.name
2980
+ }, async (span) => {
2981
+ const store = await resolveStore();
2982
+ const ns = nsId(sessionId);
2983
+ let woken = await store.wakeLog({
2984
+ sessionId: ns,
2985
+ consumer: storeConsumer
2986
+ });
2987
+ const through = Math.min(requested ?? woken.head, woken.head);
2988
+ span.setAttribute("a2.consume.through", through);
2989
+ const done = () => woken.cursor.head === null || woken.cursor.head > through;
2990
+ if (cycle && !done()) throw new TypeError(`consumer '${waiter}' can't consume '${defined.name}' through ${through}: '${defined.name}' is waiting on it in session '${sessionId}'`);
2991
+ let drains = 0;
2992
+ let wait = CONSUME_WAIT_MIN_MS;
2993
+ while (!done()) {
2994
+ signal?.throwIfAborted();
2995
+ const { cursor } = woken;
2996
+ if (cursor.failedAt !== null) throw new A2Error("CONSUMER_DEAD_LETTERED", `consumer '${registered.name}' is dead-lettered at event ${cursor.head} in session '${sessionId}': ${cursor.lastError ?? "every attempt ended before it finished"}`);
2997
+ drains += 1;
2998
+ const drained = drainSession(sessionId, {
2999
+ only: registered,
3000
+ through
3001
+ });
3002
+ try {
3003
+ await untilAborted(drained, signal);
3004
+ } catch (error) {
3005
+ if (signal?.aborted) drained.then(() => scheduleDrain(sessionId), () => {});
3006
+ throw error;
3007
+ }
3008
+ const before = cursor;
3009
+ woken = await store.wakeLog({
3010
+ sessionId: ns,
3011
+ consumer: storeConsumer
3012
+ });
3013
+ const moved = woken.cursor.head !== before.head || woken.cursor.attemptCount !== before.attemptCount;
3014
+ if (done() || moved) {
3015
+ wait = CONSUME_WAIT_MIN_MS;
3016
+ continue;
3017
+ }
3018
+ const sleep = defaultSleep(wait);
3019
+ const abort = () => sleep.cancel();
3020
+ signal?.addEventListener("abort", abort, { once: true });
3021
+ await sleep.promise;
3022
+ signal?.removeEventListener("abort", abort);
3023
+ wait = Math.min(wait * 2, CONSUME_WAIT_MAX_MS);
3024
+ }
3025
+ if (drains > 0 || own && woken.cursor.head !== null) scheduleDrain(sessionId);
3026
+ const index = woken.cursor.head === null ? woken.head : woken.cursor.head - 1;
3027
+ span.setAttribute("a2.consume.index", index);
3028
+ span.setAttribute("a2.consume.drains", drains);
3029
+ return { index };
3030
+ });
3031
+ return waiter === void 0 || cycle ? consumed : consumed.finally(() => {
3032
+ waits?.delete(waiter);
3033
+ if (waits?.size === 0) consumeWaits.delete(sessionId);
3034
+ });
3035
+ };
3036
+ const makeSession = (id, append, trigger, attempt) => ({
3037
+ id,
3038
+ append,
3039
+ consume: (defined, consumeOptions) => consumeSession(id, defined, consumeOptions, trigger),
3040
+ schedule: makeSchedule(id, trigger),
3041
+ clear: (clearOptions) => clearSession(id, clearOptions, attempt),
3042
+ history: async (bounds) => (await readHistory(id, bounds)).filter((row) => !isSessionCleared(row)).map(toPublic),
3043
+ state: (reducer = serverContract.reducer, stateOptions) => {
3044
+ if (!reducer) throw new A2Error("INVALID_PAYLOAD", "contract has no public reducer");
3045
+ const through = stateOptions?.through ?? trigger?.index;
3046
+ if (through !== void 0 && through !== "latest") assertStateIndex(through);
3047
+ const bounds = {};
3048
+ if (through !== void 0 && through !== "latest") {
3049
+ bounds.throughIndex = through;
3050
+ if (trigger) bounds.pin = headRefOf(trigger);
3051
+ if (through === trigger?.index && !attempt?.signal.aborted) bounds.throughEventId = trigger.id;
3052
+ }
3053
+ if (trigger) bounds.triggerIndex = trigger.index;
3054
+ return readState(id, reducer, bounds);
3055
+ },
3056
+ stream: (opts) => {
3057
+ const startAfter = opts?.startAfter ?? 0;
3058
+ assertStreamIndex(startAfter);
3059
+ return opts?.presence === true ? streamWithPresence(id, startAfter) : streamEvents(id, startAfter);
3060
+ },
3061
+ ...declaresPresence ? {
3062
+ setPresence: (patch) => setPresence(id, patch, trigger?.index ?? 0),
3063
+ presence: () => readPresenceMap(id)
3064
+ } : {}
3065
+ });
3066
+ /** The consumer name a trigger's child ids key on, if any. */
3067
+ const idConsumerOf = (trigger) => registeredConsumers.get(trigger.consumer)?.anonymousIds ? void 0 : trigger.consumer;
3068
+ const makeCtx = (trigger, attempt, signal, endAttempt) => {
3069
+ const publicSessionId = stripNs(trigger.sessionId);
3070
+ const idConsumer = idConsumerOf(trigger);
3071
+ const cause = {
3072
+ consumer: trigger.consumer,
3073
+ lane: trigger.lane,
3074
+ index: trigger.index,
3075
+ attempt
3076
+ };
3077
+ const append = async (appendName, ...events) => {
3078
+ assertAppendName(appendName);
3079
+ const generatedIds = events.map((event) => event.id === void 0);
3080
+ const withIds = await Promise.all(events.map(async (event, item) => {
3081
+ if (event.id !== void 0) return event;
3082
+ const id = await deterministicEventId(trigger.id, appendName, item, idConsumer);
3083
+ return {
3084
+ ...event,
3085
+ id
3086
+ };
3087
+ }));
3088
+ return appendCore(publicSessionId, withIds, "consumer", "inline", (_rows, watchdogDueAt) => scheduleDrain(publicSessionId, watchdogDueAt), cause, generatedIds);
3089
+ };
3090
+ const ctx = {
3091
+ event: toPublic(trigger),
3092
+ attempt,
3093
+ session: makeSession(publicSessionId, append, trigger, {
3094
+ cause,
3095
+ end: endAttempt,
3096
+ signal
3097
+ }),
3098
+ signal
3099
+ };
3100
+ if (attempt > 1 && trigger.lastFailedAttempt === attempt - 1) failedPreviousAttempt.add(ctx);
3101
+ return ctx;
3102
+ };
3103
+ const abortHubs = /* @__PURE__ */ new Map();
3104
+ const createAbortHub = (store, ns, startAfter) => {
3105
+ const hub = {
3106
+ subscriptions: /* @__PURE__ */ new Set(),
3107
+ seen: /* @__PURE__ */ new Map(),
3108
+ startAfter,
3109
+ ready: Promise.resolve(),
3110
+ watch: null,
3111
+ error: null,
3112
+ iterator: null,
3113
+ stopped: false
3114
+ };
3115
+ hub.ready = (async () => {
3116
+ const existing = await store.read(ns, { afterIndex: startAfter });
3117
+ for (const event of existing) dispatchAbortEvent(hub, event);
3118
+ const tail = existing.at(-1)?.index ?? startAfter;
3119
+ const iterator = store.stream(ns, { startAfter: tail })[Symbol.asyncIterator]();
3120
+ hub.iterator = iterator;
3121
+ hub.watch = (async () => {
3122
+ for (;;) {
3123
+ const { value, done } = await iterator.next();
3124
+ if (done || value === void 0 || hub.stopped) return;
3125
+ dispatchAbortEvent(hub, value);
3126
+ }
3127
+ })().catch((error) => {
3128
+ hub.error = error;
3129
+ });
3130
+ })().catch((error) => {
3131
+ hub.error = error;
3132
+ if (abortHubs.get(ns) === hub) abortHubs.delete(ns);
3133
+ throw error;
3134
+ });
3135
+ abortHubs.set(ns, hub);
3136
+ return hub;
3137
+ };
3138
+ const subscribeAbort = async (store, ns, trigger, abortOn, attempt) => {
3139
+ let hub = abortHubs.get(ns);
3140
+ const created = hub === void 0;
3141
+ if (!hub) hub = createAbortHub(store, ns, trigger.index);
3142
+ const activeTypes = /* @__PURE__ */ new Set();
3143
+ for (const active of hub.subscriptions) for (const type of active.types) activeTypes.add(type);
3144
+ const publicTrigger = toPublic(trigger);
3145
+ const subscription = {
3146
+ controller: new AbortController(),
3147
+ triggerIndex: trigger.index,
3148
+ types: new Set(abortOn.keys()),
3149
+ matches: (event) => {
3150
+ if (event.index <= trigger.index) return false;
3151
+ const matcher = abortOn.get(event.type);
3152
+ if (matcher === void 0) return false;
3153
+ return matcher === true ? true : matcher(toPublic(event), publicTrigger, { attempt });
3154
+ }
3155
+ };
3156
+ hub.subscriptions.add(subscription);
3157
+ if (!created && (trigger.index < hub.startAfter || [...subscription.types].some((type) => !activeTypes.has(type)))) {
3158
+ const earlier = await store.read(ns, { afterIndex: trigger.index });
3159
+ hub.startAfter = Math.min(hub.startAfter, trigger.index);
3160
+ for (const event of earlier) dispatchAbortEvent(hub, event);
3161
+ }
3162
+ for (const event of hub.seen.values()) if (subscription.matches(event)) subscription.controller.abort();
3163
+ await hub.ready;
3164
+ if (hub.error !== null) throw hub.error;
3165
+ return {
3166
+ signal: subscription.controller.signal,
3167
+ monitor: async (operation) => {
3168
+ const outcome = await Promise.race([operation.then((value) => ({
3169
+ type: "completed",
3170
+ value
3171
+ }), (error) => ({
3172
+ type: "run-failed",
3173
+ error
3174
+ })), hub.watch.then(() => hub.error === null ? { type: "monitor-closed" } : {
3175
+ type: "monitor-failed",
3176
+ error: hub.error
3177
+ })]);
3178
+ if (outcome.type === "completed") return outcome.value;
3179
+ if (outcome.type === "run-failed") throw outcome.error;
3180
+ if (outcome.type === "monitor-failed") {
3181
+ for (const active of hub.subscriptions) active.controller.abort(outcome.error);
3182
+ await operation.catch(() => {});
3183
+ throw outcome.error;
3184
+ }
3185
+ await operation.catch(() => {});
3186
+ throw new Error("abort monitor closed while consumers were active");
3187
+ },
3188
+ close: async () => {
3189
+ hub.subscriptions.delete(subscription);
3190
+ if (hub.subscriptions.size > 0) {
3191
+ pruneAbortHub(hub);
3192
+ return;
3193
+ }
3194
+ hub.stopped = true;
3195
+ abortHubs.delete(ns);
3196
+ await hub.ready;
3197
+ await hub.iterator?.return?.();
3198
+ await hub.watch;
3199
+ }
3200
+ };
3201
+ };
3202
+ const returnedEvents = async (sessionId, trigger, result) => {
3203
+ if (result === void 0) return [];
3204
+ const events = Array.isArray(result) ? [...result] : [result];
3205
+ if (events.length === 0) return [];
3206
+ const idConsumer = idConsumerOf(trigger);
3207
+ const withIds = await Promise.all(events.map(async (event, item) => {
3208
+ const withId = { ...event };
3209
+ withId.id = event.id ?? await deterministicReturnedEventId(trigger.id, item, idConsumer);
3210
+ return withId;
3211
+ }));
3212
+ return validateEvents(sessionId, withIds).map((event) => Object.assign(event, {
3213
+ id: event.id,
3214
+ cause: {
3215
+ consumer: trigger.consumer,
3216
+ lane: trigger.lane,
3217
+ index: trigger.index,
3218
+ attempt: trigger.attemptCount
3219
+ }
3220
+ }));
3221
+ };
3222
+ const drainSession = async (sessionId, drainOptions = {}) => {
3223
+ const result = await runDrain(sessionId, drainOptions);
3224
+ if (result.settled && drainOptions.only === void 0) drainSettledHooks.get(self)?.(sessionId);
3225
+ return result;
3226
+ };
3227
+ const runDrain = (sessionId, { watchdogDueAt, signal, handOffFailure = false, only, through } = {}) => telemetry.span("a2.drain", {
3228
+ "a2.contract": name,
3229
+ "a2.session_id": sessionId
3230
+ }, async (span) => {
3231
+ const store = await resolveStore();
3232
+ const ns = nsId(sessionId);
3233
+ const holder = crypto.randomUUID();
3234
+ /** Running heads, keyed by `headKey`: one event can run for several consumers. */
3235
+ const active = /* @__PURE__ */ new Map();
3236
+ const excluded = /* @__PURE__ */ new Map();
3237
+ let processed = 0;
3238
+ let sawFailure = false;
3239
+ let schedulerArm;
3240
+ let heartbeat = null;
3241
+ let lapseTimer = null;
3242
+ let retryTimer = null;
3243
+ let renewal = null;
3244
+ let stopRenewing = false;
3245
+ const lapseDue = () => {
3246
+ lapseTimer = null;
3247
+ const nowMs = Date.now();
3248
+ for (const entry of active.values()) {
3249
+ if (entry.lapsed || entry.expiresAtMs > nowMs) continue;
3250
+ entry.lapsed = true;
3251
+ entry.supersede.abort(new A2Error("CLAIM_EXPIRED", `the claim on event ${entry.ref.index} for consumer '${entry.ref.consumer}' in session '${sessionId}' lapsed without renewal`));
3252
+ }
3253
+ scheduleLapse();
3254
+ };
3255
+ const scheduleLapse = () => {
3256
+ if (lapseTimer) {
3257
+ clearTimeout(lapseTimer);
3258
+ lapseTimer = null;
3259
+ }
3260
+ let next = Number.POSITIVE_INFINITY;
3261
+ for (const entry of active.values()) if (!entry.lapsed) next = Math.min(next, entry.expiresAtMs);
3262
+ if (next === Number.POSITIVE_INFINITY) return;
3263
+ lapseTimer = setTimeout(lapseDue, Math.max(0, next - Date.now()));
3264
+ lapseTimer.unref?.();
3265
+ };
3266
+ const scheduleRenewRetry = () => {
3267
+ if (stopRenewing || retryTimer) return;
3268
+ const nowMs = Date.now();
3269
+ if (![...active.values()].some((entry) => !entry.lapsed && entry.expiresAtMs > nowMs)) return;
3270
+ const delay = DRAIN_TIMINGS.renewRetryMs * (.5 + Math.random() * .5);
3271
+ retryTimer = setTimeout(() => {
3272
+ retryTimer = null;
3273
+ renew();
3274
+ }, delay);
3275
+ retryTimer.unref?.();
3276
+ };
3277
+ const alignWatchdogAt = (minimumDueAt) => {
3278
+ if (watchdogDueAt === void 0) return minimumDueAt;
3279
+ return watchdogDueAt + Math.max(0, Math.ceil((minimumDueAt - watchdogDueAt) / DRAIN_TIMINGS.claimHeartbeatMs)) * DRAIN_TIMINGS.claimHeartbeatMs;
3280
+ };
3281
+ const requestWatchdog = (dueAt) => {
3282
+ const arm = startSchedulerArm(sessionId, alignWatchdogAt(dueAt));
3283
+ if (arm) schedulerArm = arm;
3284
+ };
3285
+ const renew = () => {
3286
+ if (stopRenewing || renewal || active.size === 0) return renewal ?? Promise.resolve();
3287
+ const window = nextClaimWindow();
3288
+ requestWatchdog(window.watchdogAtMs);
3289
+ const claims = [...active.values()].map((entry) => ({
3290
+ ...entry.ref,
3291
+ attempt: entry.attempt
3292
+ }));
3293
+ const operation = store.renewClaims({
3294
+ sessionId: ns,
3295
+ holder,
3296
+ claims,
3297
+ ttlMs: window.ttlMs,
3298
+ ...window.deadlineCapped ? { expiresAtMs: window.expiresAtMs } : {}
3299
+ }).then((result) => {
3300
+ for (const ref of result.renewed) {
3301
+ const entry = active.get(headKey(ref));
3302
+ if (entry && !entry.lapsed) entry.expiresAtMs = window.expiresAtMs;
3303
+ }
3304
+ for (const ref of result.superseded) {
3305
+ const entry = active.get(headKey(ref));
3306
+ if (!entry || entry.completing) continue;
3307
+ endSuperseded(entry, `a newer attempt owns event ${ref.index} for consumer '${ref.consumer}' in session '${sessionId}'`);
3308
+ }
3309
+ if (window.deadlineCapped) stopRenewing = true;
3310
+ scheduleLapse();
3311
+ }, () => {
3312
+ scheduleRenewRetry();
3313
+ });
3314
+ let tracked;
3315
+ tracked = operation.finally(() => {
3316
+ if (renewal === tracked) renewal = null;
3317
+ });
3318
+ renewal = tracked;
3319
+ return tracked;
3320
+ };
3321
+ /** Records a head the store dead-lettered on takeover; it never runs. */
3322
+ const reportExhausted = (event) => telemetry.span("a2.event", {
3323
+ "a2.contract": name,
3324
+ "a2.session_id": sessionId,
3325
+ "a2.event.type": event.type,
3326
+ "a2.event.index": event.index,
3327
+ "a2.event.id": event.id,
3328
+ "a2.event.consumer": event.consumer,
3329
+ "a2.event.attempt": event.attemptCount,
3330
+ "a2.event.handled": registeredConsumers.has(event.consumer),
3331
+ ...event.lane === null ? {} : { "a2.event.lane": event.lane }
3332
+ }, async (eventSpan) => {
3333
+ eventSpan.setAttribute("a2.event.outcome", "dead_lettered");
3334
+ });
3335
+ const runEvent = async (event, supersedeSignal, endAttempt, beginCompleting, sessionHead) => {
3336
+ const registration = only?.name === event.consumer ? only : registeredConsumers.get(event.consumer);
3337
+ const abortOn = registration?.abortOn(event.type) ?? null;
3338
+ return telemetry.span("a2.event", {
3339
+ "a2.contract": name,
3340
+ "a2.session_id": sessionId,
3341
+ "a2.event.type": event.type,
3342
+ "a2.event.index": event.index,
3343
+ "a2.event.id": event.id,
3344
+ "a2.event.consumer": event.consumer,
3345
+ "a2.event.attempt": event.attemptCount,
3346
+ "a2.event.handled": registration !== void 0,
3347
+ "a2.event.age_ms": Math.max(0, Date.now() - event.createdAt.getTime()),
3348
+ ...sessionHead === void 0 ? {} : { "a2.event.lag": Math.max(0, sessionHead - event.index) },
3349
+ ...event.lane === null ? {} : { "a2.event.lane": event.lane }
3350
+ }, async (eventSpan) => {
3351
+ let subscription;
3352
+ let runSignal = supersedeSignal;
3353
+ let completion;
3354
+ let completing = false;
3355
+ try {
3356
+ if (abortOn) {
3357
+ subscription = await subscribeAbort(store, ns, event, abortOn, event.attemptCount);
3358
+ runSignal = AbortSignal.any([supersedeSignal, subscription.signal]);
3359
+ }
3360
+ const operation = registration?.run(makeCtx(event, event.attemptCount, runSignal, endAttempt));
3361
+ const result = operation ? await (subscription ? subscription.monitor(operation) : operation) : void 0;
3362
+ if (subscription) {
3363
+ await subscription.close();
3364
+ subscription = void 0;
3365
+ }
3366
+ const returned = await returnedEvents(sessionId, event, result);
3367
+ await renewal;
3368
+ completing = true;
3369
+ beginCompleting();
3370
+ completion = await telemetry.span("a2.commit", {
3371
+ "a2.contract": name,
3372
+ "a2.session_id": sessionId,
3373
+ "a2.commit.operation": "complete",
3374
+ "a2.commit.index": event.index,
3375
+ "a2.commit.attempt": event.attemptCount
3376
+ }, async (commitSpan) => {
3377
+ const committed = await store.completeAttempt({
3378
+ sessionId: ns,
3379
+ consumer: event.consumer,
3380
+ lane: event.lane,
3381
+ index: event.index,
3382
+ attempt: event.attemptCount,
3383
+ events: returned,
3384
+ consumers: storeConsumers
3385
+ });
3386
+ commitSpan.setAttribute("a2.commit.outcome", committed.outcome);
3387
+ return committed;
3388
+ });
3389
+ } catch (err) {
3390
+ if (supersedeSignal.aborted && err === supersedeSignal.reason) {
3391
+ eventSpan.setAttribute("a2.event.outcome", "surrendered");
3392
+ return {
3393
+ status: "surrendered",
3394
+ opensLane: false,
3395
+ appendsEvents: false
3396
+ };
3397
+ }
3398
+ const refused = completing && err instanceof A2Error && err.code === "PARTIAL_DUPLICATE_BATCH";
3399
+ if (completing && !refused) throw err;
3400
+ eventSpan.recordError(err);
3401
+ const failure = await telemetry.span("a2.commit", {
3402
+ "a2.contract": name,
3403
+ "a2.session_id": sessionId,
3404
+ "a2.commit.operation": "fail",
3405
+ "a2.commit.index": event.index,
3406
+ "a2.commit.attempt": event.attemptCount
3407
+ }, async (commitSpan) => {
3408
+ const result = await store.failAttempt({
3409
+ sessionId: ns,
3410
+ consumer: event.consumer,
3411
+ lane: event.lane,
3412
+ index: event.index,
3413
+ attempt: event.attemptCount,
3414
+ error: describeError(err),
3415
+ maxFailures: err instanceof NonRetriableError || refused ? 1 : MAX_FAILURES,
3416
+ retryAfterMs: failureRetryDelayMs(event.failureCount + 1)
3417
+ });
3418
+ commitSpan.setAttribute("a2.commit.outcome", result.outcome);
3419
+ return result;
3420
+ });
3421
+ eventSpan.setAttribute("a2.event.outcome", failure.outcome);
3422
+ return {
3423
+ status: failure.outcome,
3424
+ opensLane: false,
3425
+ appendsEvents: false
3426
+ };
3427
+ } finally {
3428
+ await subscription?.close();
3429
+ }
3430
+ eventSpan.setAttribute("a2.event.outcome", completion.outcome === "completed" ? "processed" : completion.outcome);
3431
+ if (completion.outcome === "superseded") return {
3432
+ status: "superseded",
3433
+ opensLane: false,
3434
+ appendsEvents: false
3435
+ };
3436
+ if (runSignal.aborted) eventSpan.setAttribute("a2.event.aborted", true);
3437
+ return {
3438
+ status: "processed",
3439
+ opensLane: event.lane !== null,
3440
+ appendsEvents: completion.events.length > 0
3441
+ };
3442
+ });
3443
+ };
3444
+ let claimAgain = false;
3445
+ const start = (event, expiresAtMs, sessionHead) => {
3446
+ const ref = headRefOf(event);
3447
+ const key = headKey(ref);
3448
+ const previous = active.get(key);
3449
+ if (previous) endSuperseded(previous, `a newer attempt owns event ${event.index} for consumer '${event.consumer}' in session '${sessionId}'`);
3450
+ const supersede = new AbortController();
3451
+ let fence;
3452
+ const fenced = new Promise((resolve) => {
3453
+ fence = resolve;
3454
+ });
3455
+ const endAttempt = () => endSuperseded({
3456
+ supersede,
3457
+ fence
3458
+ }, `event ${event.index} for consumer '${event.consumer}' in session '${sessionId}' was cleared`);
3459
+ let entry;
3460
+ const execution = Promise.race([runEvent(event, supersede.signal, endAttempt, () => {
3461
+ entry.completing = true;
3462
+ }, sessionHead), fenced]).then((eventOutcome) => {
3463
+ if (active.get(key) === entry) active.delete(key);
3464
+ if (eventOutcome.status === "processed") processed += 1;
3465
+ if (eventOutcome.status === "failed") {
3466
+ excluded.set(key, ref);
3467
+ sawFailure = true;
3468
+ }
3469
+ claimAgain ||= eventOutcome.opensLane || eventOutcome.appendsEvents;
3470
+ return eventOutcome;
3471
+ });
3472
+ entry = {
3473
+ ref,
3474
+ attempt: event.attemptCount,
3475
+ execution,
3476
+ supersede,
3477
+ fence,
3478
+ expiresAtMs,
3479
+ lapsed: false,
3480
+ completing: false
3481
+ };
3482
+ active.set(key, entry);
3483
+ scheduleLapse();
3484
+ if (!heartbeat && !stopRenewing) {
3485
+ heartbeat = setInterval(() => void renew(), DRAIN_TIMINGS.claimHeartbeatMs);
3486
+ heartbeat.unref?.();
3487
+ }
3488
+ };
3489
+ let outcome = "settled";
3490
+ let shouldClaim = true;
3491
+ try {
3492
+ for (;;) {
3493
+ const signalVersion = signal?.version ?? 0;
3494
+ let claim;
3495
+ if (shouldClaim) {
3496
+ const window = nextClaimWindow();
3497
+ if (window.pastDeadline) {
3498
+ outcome = "busy";
3499
+ break;
3500
+ }
3501
+ claim = await telemetry.span("a2.claim", {
3502
+ "a2.contract": name,
3503
+ "a2.session_id": sessionId
3504
+ }, async (claimSpan) => {
3505
+ const result = await store.claimAvailable({
3506
+ sessionId: ns,
3507
+ holder,
3508
+ ttlMs: window.ttlMs,
3509
+ maxFailures: MAX_FAILURES,
3510
+ ...window.deadlineCapped ? { expiresAtMs: window.expiresAtMs } : {},
3511
+ consumers: only ? [storeConsumerOf(only)] : storeConsumers,
3512
+ ...through === void 0 ? {} : { through },
3513
+ ...excluded.size === 0 ? {} : { exclude: [...excluded.values()] }
3514
+ });
3515
+ claimSpan.setAttribute("a2.claim.outcome", result.outcome);
3516
+ claimSpan.setAttribute("a2.claim.count", result.outcome === "claimed" ? result.events.length : 0);
3517
+ return result;
3518
+ });
3519
+ if (claim.outcome === "claimed") {
3520
+ const runnable = claim.events.filter((event) => event.failedAt === null);
3521
+ for (const event of claim.events) if (event.failedAt !== null) await reportExhausted(event);
3522
+ if (runnable.length > 0) requestWatchdog(window.watchdogAtMs);
3523
+ if (window.deadlineCapped) stopRenewing = true;
3524
+ for (const event of runnable) start(event, window.expiresAtMs, claim.head);
3525
+ shouldClaim = false;
3526
+ }
3527
+ }
3528
+ if (claim?.outcome === "claimed" && [...active.values()].some((entry) => entry.lapsed)) {
3529
+ shouldClaim = true;
3530
+ continue;
3531
+ }
3532
+ if (active.size > 0) {
3533
+ const wake = signal?.wait(signalVersion);
3534
+ const hasLapsed = [...active.values()].some((entry) => entry.lapsed);
3535
+ const retry = claim?.outcome === "busy" && hasLapsed ? defaultSleep(Math.max(0, claim.retryAt.getTime() - Date.now())) : void 0;
3536
+ const retryDue = await Promise.race([
3537
+ ...[...active.values()].map((entry) => entry.execution.then(() => false)),
3538
+ ...wake ? [wake.promise.then(() => false)] : [],
3539
+ ...retry ? [retry.promise.then(() => true)] : []
3540
+ ]);
3541
+ wake?.cancel();
3542
+ retry?.cancel();
3543
+ shouldClaim = retryDue || claimAgain || active.size === 0 || hasLapsed || signal !== void 0 && signal.version !== signalVersion;
3544
+ claimAgain = false;
3545
+ continue;
3546
+ }
3547
+ if (!shouldClaim) {
3548
+ shouldClaim = true;
3549
+ continue;
3550
+ }
3551
+ if (claim === void 0) continue;
3552
+ if (signal && signal.version !== signalVersion) continue;
3553
+ if (claimAgain) {
3554
+ claimAgain = false;
3555
+ continue;
3556
+ }
3557
+ if (claim.outcome === "busy") {
3558
+ requestWatchdog(claim.retryAt.getTime() + DRAIN_TIMINGS.watchdogGraceMs);
3559
+ outcome = "busy";
3560
+ } else if (sawFailure) outcome = "stalled";
3561
+ if (signal) signal.closed = true;
3562
+ break;
3563
+ }
3564
+ } catch (error) {
3565
+ if (!handOffFailure || schedulerArm === void 0) throw error;
3566
+ span.recordError(error);
3567
+ outcome = "failed";
3568
+ } finally {
3569
+ if (signal) signal.closed = true;
3570
+ stopRenewing = true;
3571
+ if (heartbeat) clearInterval(heartbeat);
3572
+ if (retryTimer) clearTimeout(retryTimer);
3573
+ await renewal;
3574
+ await Promise.allSettled([...active.values()].map((entry) => entry.execution));
3575
+ if (lapseTimer) clearTimeout(lapseTimer);
3576
+ }
3577
+ span.setAttribute("a2.drain.processed", processed);
3578
+ span.setAttribute("a2.drain.outcome", outcome);
3579
+ return {
3580
+ settled: outcome === "settled",
3581
+ outcome,
3582
+ processed,
3583
+ ...schedulerArm ? { schedulerArm } : {}
3584
+ };
3585
+ });
3586
+ const appendExternal = async (sessionId, mode, events, requireDurableInitialArm = false, condition = {}) => {
3587
+ return appendCore(sessionId, events, "external", mode, (_rows, watchdogDueAt) => scheduleDrain(sessionId, watchdogDueAt), void 0, void 0, requireDurableInitialArm, condition);
3588
+ };
3589
+ const session = (id) => {
3590
+ assertSessionId(id);
3591
+ const appendInline = async (...events) => appendExternal(id, "inline", events);
3592
+ const appendDispatch = async (...events) => appendExternal(id, "dispatch", events);
3593
+ const appendIfLastIndex = async (index, ...events) => {
3594
+ assertIfLastIndex(index);
3595
+ if (events.length === 0) throw new TypeError("append.ifLastIndex requires at least one event");
3596
+ return appendExternal(id, "inline", events, false, { ifLastIndex: index });
3597
+ };
3598
+ const append = Object.assign(appendInline, {
3599
+ dispatch: appendDispatch,
3600
+ ifLastIndex: appendIfLastIndex
3601
+ });
3602
+ return Object.assign(makeSession(id, append, null), {
3603
+ deadLetters: () => listDeadLetters(id),
3604
+ redrive: (target, redriveOptions) => redriveEvent(id, target, redriveOptions)
3605
+ });
3606
+ };
3607
+ const historyPage = async (sessionId, bounds) => {
3608
+ assertSessionId(sessionId);
3609
+ const rows = await readHistory(sessionId, bounds);
3610
+ const marker = rows[0] && isSessionCleared(rows[0]) ? rows[0] : void 0;
3611
+ return {
3612
+ events: (marker ? rows.slice(1) : rows).map(toPublic),
3613
+ ...marker ? { clearIndex: marker.index } : {}
3614
+ };
3615
+ };
3616
+ const self = {
3617
+ contract: serverContract,
3618
+ fetch: createServerFetch({
3619
+ contract: serverContract,
3620
+ session,
3621
+ historyPage
3622
+ }),
3623
+ session,
3624
+ async drain(sessionId) {
3625
+ assertSessionId(sessionId);
3626
+ const { settled } = await drainSession(sessionId);
3627
+ return { settled };
3628
+ }
3629
+ };
3630
+ serverInternals.set(self, {
3631
+ settle: async () => {
3632
+ while (inFlight.size > 0) await Promise.allSettled(inFlight);
3633
+ },
3634
+ schedulerDrain: (sessionId, opts) => {
3635
+ assertSessionId(sessionId);
3636
+ return drainSession(sessionId, {
3637
+ watchdogDueAt: opts?.watchdogDueAt,
3638
+ handOffFailure: true
3639
+ });
3640
+ },
3641
+ schedulerAppend: async (sessionId, events, originIndex) => {
3642
+ if (!scheduler) throw new TypeError("scheduled append delivery requires a configured scheduler adapter");
3643
+ assertSessionId(sessionId);
3644
+ try {
3645
+ await appendExternal(sessionId, "inline", [...events], true, originIndex === void 0 ? {} : { originIndex });
3646
+ } catch (error) {
3647
+ if (originIndex !== void 0 && error instanceof A2Error && error.code === "SESSION_CLEARED") return;
3648
+ throw error;
3649
+ }
3650
+ },
3651
+ historyWithMarkers: async (sessionId, gte) => (await readHistory(sessionId, { gte })).map(toPublic),
3652
+ schedulerClear: async (sessionId, ifLastIndex) => {
3653
+ assertSessionId(sessionId);
3654
+ assertIfLastIndex(ifLastIndex);
3655
+ await clearSession(sessionId, { ifLastIndex }, void 0);
3656
+ }
3657
+ });
3658
+ return self;
3659
+ }
3660
+ function assertSessionId(id) {
3661
+ if (typeof id !== "string" || id.length === 0) throw new TypeError("session id must be a non-empty string");
3662
+ if (id.includes(NS)) throw new TypeError("session id contains a reserved control character");
3663
+ }
3664
+ function assertHistoryIndex(name, value) {
3665
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) throw new TypeError(`history.${name} must be a non-negative safe integer`);
3666
+ }
3667
+ function assertStreamIndex(value) {
3668
+ if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("stream.startAfter must be a non-negative safe integer");
3669
+ }
3670
+ function assertStateIndex(value) {
3671
+ if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("state.through must be a non-negative safe integer");
3672
+ }
3673
+ function assertConsumeIndex(value) {
3674
+ if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("consume through must be a non-negative safe integer");
3675
+ }
3676
+ function assertRedriveIndex(value) {
3677
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("redrive requires a positive safe-integer index");
3678
+ }
3679
+ function assertIfLastIndex(value) {
3680
+ if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("ifLastIndex must be a non-negative safe integer");
3681
+ }
3682
+ function assertAppendName(name) {
3683
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("consumer append name must be a non-empty string");
3684
+ }
3685
+ function assertScheduleName(name) {
3686
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("schedule name must be a non-empty string");
3687
+ }
3688
+ const SCHEDULE_DELAY = /^(?:0|[1-9]\d*)(?:\.\d+)?(ms|s|m|h|d)$/;
3689
+ const SCHEDULE_DELAY_MULTIPLIER = {
3690
+ ms: 1,
3691
+ s: 1e3,
3692
+ m: 6e4,
3693
+ h: 36e5,
3694
+ d: 864e5
3695
+ };
3696
+ function scheduleDueAt(timing, baseTime) {
3697
+ if (timing === null || typeof timing !== "object" || Array.isArray(timing)) throw new TypeError("schedule timing must contain exactly one of 'delay' or 'at'");
3698
+ const record = timing;
3699
+ const hasDelay = Object.hasOwn(record, "delay");
3700
+ const hasAt = Object.hasOwn(record, "at");
3701
+ if (hasDelay === hasAt) throw new TypeError("schedule timing must contain exactly one of 'delay' or 'at'");
3702
+ let dueAt;
3703
+ if (hasAt) {
3704
+ const at = record["at"];
3705
+ if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new TypeError("schedule at must be a valid Date");
3706
+ dueAt = at.getTime();
3707
+ } else {
3708
+ const delay = record["delay"];
3709
+ if (typeof delay !== "string") throw new TypeError("schedule delay must use ms, s, m, h, or d (for example '30s')");
3710
+ const match = SCHEDULE_DELAY.exec(delay);
3711
+ const amount = match ? Number(delay.slice(0, -match[1].length)) : NaN;
3712
+ if (!match || !Number.isFinite(amount) || amount <= 0) throw new TypeError("schedule delay must be positive and use ms, s, m, h, or d (for example '30s')");
3713
+ dueAt = baseTime + amount * SCHEDULE_DELAY_MULTIPLIER[match[1]];
3714
+ }
3715
+ if (!Number.isFinite(dueAt)) throw new TypeError("schedule due time must be a finite epoch time");
3716
+ return dueAt;
3717
+ }
3718
+ function assertScheduledPayload(payload) {
3719
+ try {
3720
+ if (isJsonValue(payload, /* @__PURE__ */ new WeakSet())) return;
3721
+ } catch {}
3722
+ throw new TypeError("session.schedule event payload must be JSON-serializable");
3723
+ }
3724
+ function cloneScheduledPayload(payload) {
3725
+ assertScheduledPayload(payload);
3726
+ try {
3727
+ const cloned = structuredClone(payload);
3728
+ const encoded = JSON.stringify(cloned);
3729
+ if (encoded === void 0) throw new TypeError();
3730
+ return JSON.parse(encoded);
3731
+ } catch {
3732
+ throw new TypeError("session.schedule event payload must be JSON-serializable");
3733
+ }
3734
+ }
3735
+ function isJsonValue(value, ancestors) {
3736
+ if (value === null) return true;
3737
+ if (typeof value === "string" || typeof value === "boolean") return true;
3738
+ if (typeof value === "number") return Number.isFinite(value) && !Object.is(value, -0);
3739
+ if (typeof value !== "object") return false;
3740
+ if (ancestors.has(value)) return false;
3741
+ ancestors.add(value);
3742
+ try {
3743
+ if (Array.isArray(value)) {
3744
+ const keys = Reflect.ownKeys(value);
3745
+ if (keys.length !== value.length + 1 || !keys.includes("length")) return false;
3746
+ for (let index = 0; index < value.length; index += 1) {
3747
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
3748
+ if (!descriptor || !descriptor.enumerable || !("value" in descriptor) || !isJsonValue(descriptor.value, ancestors)) return false;
3749
+ }
3750
+ return true;
3751
+ }
3752
+ if (Object.getPrototypeOf(value) !== Object.prototype) return false;
3753
+ for (const key of Reflect.ownKeys(value)) {
3754
+ if (typeof key !== "string") return false;
3755
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3756
+ if (!descriptor || !descriptor.enumerable || !("value" in descriptor) || !isJsonValue(descriptor.value, ancestors)) return false;
3757
+ }
3758
+ return true;
3759
+ } finally {
3760
+ ancestors.delete(value);
3761
+ }
3762
+ }
3763
+ const measuredBytes = (reducer, state, index, snapshots) => JSON.stringify(snapshots.find((snapshot) => snapshot.index === index)?.state ?? encodeState({
3764
+ reducer,
3765
+ state
3766
+ }))?.length ?? 0;
3767
+ const stateCacheKey = (sessionId, reducerName) => `${sessionId}\u0000${reducerName}`;
3768
+ //#endregion
3769
+ export { retryableLazy as a, makeReducerBuilder as c, deliverSchedulerClear as i, reducer as l, createServer as n, platformWaitUntil as o, deliverSchedulerAppend as r, assertSyncSchema as s, consumer as t };