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