@powerhousedao/reactor 6.2.3-dev.43 → 6.2.3-dev.45

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 (30) hide show
  1. package/dist/{document-indexer-B3yKal-y.js → document-indexer-lfgXu9ph.js} +13 -4
  2. package/dist/document-indexer-lfgXu9ph.js.map +1 -0
  3. package/dist/drive-container-types-CifLQjd3.js +3766 -0
  4. package/dist/drive-container-types-CifLQjd3.js.map +1 -0
  5. package/dist/entry.js +99 -3
  6. package/dist/entry.js.map +1 -1
  7. package/dist/index-81SYQKda.d.ts +6353 -0
  8. package/dist/index-81SYQKda.d.ts.map +1 -0
  9. package/dist/index.d.ts +16 -6339
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +53 -49
  12. package/dist/index.js.map +1 -1
  13. package/dist/load-spec-f2ppXyKZ.js +3848 -0
  14. package/dist/load-spec-f2ppXyKZ.js.map +1 -0
  15. package/dist/projection-entry.js +2 -3
  16. package/dist/projection-entry.js.map +1 -1
  17. package/dist/{projection-shard-manager-BZPCQK-4.js → projection-shard-manager-XMam-rTs.js} +2 -2
  18. package/dist/{projection-shard-manager-BZPCQK-4.js.map → projection-shard-manager-XMam-rTs.js.map} +1 -1
  19. package/dist/rpc.d.ts +318 -0
  20. package/dist/rpc.d.ts.map +1 -0
  21. package/dist/rpc.js +570 -0
  22. package/dist/rpc.js.map +1 -0
  23. package/dist/{worker-handle-CefOwokd.js → worker-handle-BKuaSp9T.js} +2 -2
  24. package/dist/{worker-handle-CefOwokd.js.map → worker-handle-BKuaSp9T.js.map} +1 -1
  25. package/package.json +10 -4
  26. package/dist/build-worker-executor-Bonu2jUB.js +0 -105
  27. package/dist/build-worker-executor-Bonu2jUB.js.map +0 -1
  28. package/dist/document-indexer-B3yKal-y.js.map +0 -1
  29. package/dist/forwarding-logger-BKDP4JnD.js +0 -7593
  30. package/dist/forwarding-logger-BKDP4JnD.js.map +0 -1
@@ -0,0 +1,3766 @@
1
+ import { $ as relationshipTarget, B as TouchedStreams, Dt as UpgradePreconditionFailedError, H as applyUpgradeDocumentAction$1, I as DOCUMENT_SCOPE_ACTIONS, J as createOperation, K as createDocumentFromAction, L as FencedWriteCache, Nt as yieldToMain, Q as refusalError, R as GATED_DOCUMENT_ACTIONS, St as PurgeTooLargeError, Tt as UnsupportedProtocolVersionError, U as buildErrorResult, V as applyDeleteDocumentAction$1, W as buildSuccessResult, X as isGenesisOperation, Y as getNextIndexForScope, Z as jobWriteIds, _t as DocumentPurgedError, at as AppendConditionFailedError, b as acquirePurgeLocks, bt as InvalidOperationTimestampError, et as submittedActionIds, ft as AuthTimestampNotMonotonicError, gt as DocumentNotFoundError, ht as DocumentNotDeletedError, kt as ReactorEventTypes, mt as DocumentDeletedError, nt as targetDocumentId, pt as AuthorizationDeniedError, rt as updateDocumentRevision, vt as ExcessiveReshuffleError, wt as ReservedActionError, x as findPurged, xt as InvalidSignatureError, yt as GroupInUseError, z as PurgeFence } from "./load-spec-f2ppXyKZ.js";
2
+ import { AUTH_ACTION_TYPES, AUTH_DENIED_BY_GRANT_REASON, AUTH_NO_GRANT_REASON, AUTH_VERSION_UNSUPPORTED_REASON, DOCUMENT_DELETED_REASON, PEER_CAPABILITIES, actionSignerIdentity, actionSigningTarget, applyAuthAction, applyDeleteDocumentAction, base58Decode, baseReducerVersion, buildOperationSignatureMessage, buildOperationSignatureParams, canonicalJson, decide, deriveDocumentId, deriveOperationId, evaluate, garbageCollect, groupDocumentType, groupMembershipActionTypes, hashActionV2, hashBrowser, hashDocumentStateForScope, isDenied, isDerivedDocumentId, isPurgeMarker, isUndoRedo, isV2ActionHash, localSupports, mentionedGroupIds, normalizeDocumentModelVersion, purgeDocumentAction, purgeMarkerOperation, referencedGroupIds, signaturePolicyOf, sortOperations, v2TupleProblem, withProtocolVersions } from "@powerhousedao/shared/document-model";
3
+ import { sql } from "kysely";
4
+ //#region src/cache/operation-index-types.ts
5
+ const DRIVE_COLLECTION_PREFIX = "drive.";
6
+ /**
7
+ * Identifies the collection a remote synchronizes. Collections are drive-level
8
+ * abstractions (document-drive and reactor-drive), so a collection id is the
9
+ * drive document id plus the branch it scopes to rather than an opaque string.
10
+ *
11
+ * The canonical string form (`drive.${branch}.${driveId}`) is produced only by
12
+ * `key` and parsed only by `fromKey`; that string is the wire and storage
13
+ * representation and is byte-for-byte identical to the legacy
14
+ * `driveCollectionId(branch, driveId)` output, so existing `document_collections`
15
+ * rows and persisted remotes remain valid without migration.
16
+ */
17
+ var DriveCollectionId = class DriveCollectionId {
18
+ driveId;
19
+ branch;
20
+ constructor(driveId, branch) {
21
+ this.driveId = driveId;
22
+ this.branch = branch;
23
+ }
24
+ static forDrive(driveId, branch = "main") {
25
+ return new DriveCollectionId(driveId, branch);
26
+ }
27
+ /**
28
+ * The single deserializer for the wire/storage form. `branch` may contain
29
+ * dots, while `driveId` is a dot-free document id, so the drive id is the
30
+ * final dot-delimited segment.
31
+ */
32
+ static fromKey(key) {
33
+ if (!key.startsWith(DRIVE_COLLECTION_PREFIX)) throw new Error(`Unsupported collection id: ${key}`);
34
+ const rest = key.slice(6);
35
+ const lastDot = rest.lastIndexOf(".");
36
+ if (lastDot === -1 || lastDot === rest.length - 1) throw new Error(`Malformed drive collection id: ${key}`);
37
+ return new DriveCollectionId(rest.slice(lastDot + 1), rest.slice(0, lastDot));
38
+ }
39
+ get key() {
40
+ return `${DRIVE_COLLECTION_PREFIX}${this.branch}.${this.driveId}`;
41
+ }
42
+ toString() {
43
+ return this.key;
44
+ }
45
+ equals(other) {
46
+ return this.driveId === other.driveId && this.branch === other.branch;
47
+ }
48
+ };
49
+ //#endregion
50
+ //#region src/decision/build-decision-model.ts
51
+ /**
52
+ * Reads each projection's stream through the supplied reader, recording the
53
+ * revision observed. Static projections resolve first; derived projections
54
+ * see only those and contribute a map from document id to state. Each
55
+ * distinct stream is read once and yields one append condition entry.
56
+ */
57
+ async function buildDecisionModel(reader, definition, target, signal) {
58
+ const decisionModel = definition(target);
59
+ const projections = Object.entries(decisionModel.projections);
60
+ const reads = /* @__PURE__ */ new Map();
61
+ const model = {};
62
+ for (const [key, projection] of projections) {
63
+ if (typeof projection.query === "function") continue;
64
+ model[key] = (await readStream(reader, projection.query, reads, signal)).state;
65
+ }
66
+ const staticModel = { ...model };
67
+ const derived = [];
68
+ for (const [key, projection] of projections) {
69
+ if (typeof projection.query !== "function") continue;
70
+ derived.push([key, projection.query(staticModel)]);
71
+ }
72
+ if (derived.length > 0 && reader.fence) await reader.fence(derived.flatMap(([, queries]) => queries.map((q) => q.documentId)));
73
+ for (const [key, queries] of derived) {
74
+ const value = {};
75
+ for (const query of queries) {
76
+ let read;
77
+ try {
78
+ read = await readStream(reader, query, reads, signal);
79
+ } catch (error) {
80
+ if (error instanceof DocumentNotFoundError) {
81
+ recordEmptyStream(query, reads);
82
+ continue;
83
+ }
84
+ throw error;
85
+ }
86
+ value[query.documentId] = read.state;
87
+ }
88
+ model[key] = value;
89
+ }
90
+ return {
91
+ model,
92
+ appendCondition: { streams: [...reads.values()].map((read) => read.stream) }
93
+ };
94
+ }
95
+ /** Guards a stream that holds nothing yet: any operation appearing is growth. */
96
+ function recordEmptyStream(query, reads) {
97
+ const key = `${query.documentId}:${query.scope}:${query.branch}`;
98
+ if (reads.has(key)) return;
99
+ reads.set(key, {
100
+ state: void 0,
101
+ stream: {
102
+ documentId: query.documentId,
103
+ scope: query.scope,
104
+ branch: query.branch,
105
+ revision: -1
106
+ }
107
+ });
108
+ }
109
+ async function readStream(reader, query, reads, signal) {
110
+ const key = `${query.documentId}:${query.scope}:${query.branch}`;
111
+ const existing = reads.get(key);
112
+ if (existing) return existing;
113
+ const document = await reader.getState(query.documentId, query.scope, query.branch, void 0, signal);
114
+ const read = {
115
+ state: document.state[query.scope],
116
+ stream: {
117
+ documentId: query.documentId,
118
+ scope: query.scope,
119
+ branch: query.branch,
120
+ revision: observedRevision(document, query.scope)
121
+ }
122
+ };
123
+ reads.set(key, read);
124
+ return read;
125
+ }
126
+ /**
127
+ * The highest operation index the document reflects for the scope, or -1 if
128
+ * empty. `header.revision` is authoritative, not the rebuilt operation list.
129
+ */
130
+ function observedRevision(document, scope) {
131
+ if (scope in document.header.revision) return document.header.revision[scope] - 1;
132
+ if (scope in document.operations) {
133
+ const operations = document.operations[scope];
134
+ if (operations.length > 0) return operations[operations.length - 1].index;
135
+ }
136
+ if (!(scope in document.header.revision)) return -1;
137
+ return document.header.revision[scope] - 1;
138
+ }
139
+ /**
140
+ * The projections whose queries depend on folded state. A positional walk
141
+ * resolves their streams through `queryOverHistory`; a projection without one
142
+ * contributes no streams to a walk.
143
+ */
144
+ function derivedReadSet(definition) {
145
+ const projections = [];
146
+ for (const [name, projection] of Object.entries(definition.projections)) {
147
+ if (typeof projection.query !== "function") continue;
148
+ projections.push({
149
+ name,
150
+ decidingActions: projection.decidingActions,
151
+ apply: projection.apply,
152
+ queryOverHistory: projection.queryOverHistory
153
+ });
154
+ }
155
+ return projections;
156
+ }
157
+ /**
158
+ * The streams a model reads whose queries are known before it is built. A
159
+ * derived query needs the statically-queried projections first, so it is not
160
+ * included here.
161
+ */
162
+ function staticReadSet(definition) {
163
+ const streams = [];
164
+ for (const [name, projection] of Object.entries(definition.projections)) {
165
+ if (typeof projection.query === "function") continue;
166
+ streams.push({
167
+ name,
168
+ query: projection.query,
169
+ decidingActions: projection.decidingActions,
170
+ apply: projection.apply
171
+ });
172
+ }
173
+ return streams;
174
+ }
175
+ //#endregion
176
+ //#region src/decision/auth-decision-model.ts
177
+ function refusalReason(refusal) {
178
+ switch (refusal) {
179
+ case "version-unsupported": return AUTH_VERSION_UNSUPPORTED_REASON;
180
+ case "denied-by-grant": return AUTH_DENIED_BY_GRANT_REASON;
181
+ case "no-applicable-grant": return AUTH_NO_GRANT_REASON;
182
+ }
183
+ }
184
+ function decideAuthModel(model, subject, request, groups, conditions) {
185
+ if (request.verb === "execute" && model.document.isDeleted) return {
186
+ decision: "deny",
187
+ reason: DOCUMENT_DELETED_REASON
188
+ };
189
+ const evaluation = evaluate(model.auth, subject, request, groups, conditions);
190
+ if (evaluation.decision === "allow") return { decision: "allow" };
191
+ return {
192
+ decision: "deny",
193
+ reason: refusalReason(evaluation.refusal)
194
+ };
195
+ }
196
+ function documentProjection(target) {
197
+ return {
198
+ decidingActions: ["DELETE_DOCUMENT"],
199
+ apply: (document, operation) => operation.action.type === "DELETE_DOCUMENT" ? applyDeleteDocumentAction({
200
+ ...document,
201
+ state: { ...document.state }
202
+ }, operation.action) : document,
203
+ query: {
204
+ documentId: target.documentId,
205
+ branch: target.branch,
206
+ scope: "document"
207
+ }
208
+ };
209
+ }
210
+ function authProjection(target) {
211
+ return {
212
+ decidingActions: [...AUTH_ACTION_TYPES],
213
+ apply: (document, operation) => applyAuthAction(document, operation.action),
214
+ query: {
215
+ documentId: target.documentId,
216
+ branch: target.branch,
217
+ scope: "auth"
218
+ }
219
+ };
220
+ }
221
+ /** This decision model uses both the document and the auth streams. */
222
+ function authDecisionModel(target) {
223
+ return {
224
+ projections: {
225
+ document: documentProjection(target),
226
+ auth: authProjection(target)
227
+ },
228
+ evaluatesScope() {
229
+ return true;
230
+ },
231
+ decide(model, subject, request) {
232
+ return decideAuthModel(model, subject, request);
233
+ }
234
+ };
235
+ }
236
+ /**
237
+ * Folds one group-stream operation with the registered group model's reducer.
238
+ * A reactor without the module registered folds nothing, so the member list
239
+ * stays as read and a missing reducer never widens access.
240
+ */
241
+ function applyGroupOperation(registry, document, operation) {
242
+ let reducer;
243
+ try {
244
+ reducer = registry.getModule(groupDocumentType).reducer;
245
+ } catch {
246
+ return document;
247
+ }
248
+ return reducer(document, operation.action);
249
+ }
250
+ /**
251
+ * Folds one evaluated-scope operation with the reducer registered for the
252
+ * document's own type, at the document's stamped version. A reactor without
253
+ * that module folds nothing, so conditions read the base state and an
254
+ * unresolvable reducer never widens access.
255
+ */
256
+ function applyModelOperation(registry, document, operation) {
257
+ let reducer;
258
+ try {
259
+ const version = normalizeDocumentModelVersion(document.state.document?.version);
260
+ reducer = registry.getModule(document.header.documentType, version).reducer;
261
+ } catch {
262
+ return document;
263
+ }
264
+ return reducer(document, operation.action);
265
+ }
266
+ /**
267
+ * The auth model extended with a derived groups projection: the streams it
268
+ * reads are the group documents the folded grant list names, so adding a
269
+ * grant that names a new group pulls that group's stream into the read-set.
270
+ * Group queries pin the main branch, because a group's member list lives on
271
+ * its main branch no matter which branch the referencing document is on.
272
+ */
273
+ function groupsProjection(registry) {
274
+ return {
275
+ decidingActions: [...groupMembershipActionTypes],
276
+ apply: (document, operation) => applyGroupOperation(registry, document, operation),
277
+ query: (model) => referencedGroupIds(model.auth?.grants ?? []).map((id) => ({
278
+ documentId: id,
279
+ branch: "main",
280
+ scope: "global"
281
+ })),
282
+ queryOverHistory: (reads) => {
283
+ const ids = [];
284
+ for (const read of reads) {
285
+ if (read.name !== "auth") continue;
286
+ for (const operation of read.operations) for (const id of mentionedGroupIds(operation.action)) if (!ids.includes(id)) ids.push(id);
287
+ }
288
+ return ids.map((id) => ({
289
+ documentId: id,
290
+ branch: "main",
291
+ scope: "global"
292
+ }));
293
+ }
294
+ };
295
+ }
296
+ function authGroupsDecisionModel(registry) {
297
+ return (target) => ({
298
+ projections: {
299
+ document: documentProjection(target),
300
+ auth: authProjection(target),
301
+ groups: groupsProjection(registry)
302
+ },
303
+ evaluatesScope() {
304
+ return true;
305
+ },
306
+ decide(model, subject, request) {
307
+ return decideAuthModel(model, subject, request, model.groups);
308
+ }
309
+ });
310
+ }
311
+ /**
312
+ * The groups model with conditions live: decide hands the executing scope's
313
+ * state and the action input through to the evaluator, so `where` clauses
314
+ * and { match } principals apply. The model folds the evaluated scope during
315
+ * a positional walk, so a condition reads the state as it stood at each
316
+ * operation's position.
317
+ */
318
+ function authConditionsDecisionModel(registry) {
319
+ return (target) => ({
320
+ projections: {
321
+ document: documentProjection(target),
322
+ auth: authProjection(target),
323
+ groups: groupsProjection(registry)
324
+ },
325
+ foldEvaluatedScope: (document, operation) => applyModelOperation(registry, document, operation),
326
+ evaluatesScope() {
327
+ return true;
328
+ },
329
+ decide(model, subject, request, ctx) {
330
+ return decideAuthModel(model, subject, request, model.groups, {
331
+ scopeState: ctx.scopeState,
332
+ actionInput: ctx.actionInput
333
+ });
334
+ }
335
+ });
336
+ }
337
+ //#endregion
338
+ //#region src/decision/document-decision-model.ts
339
+ /**
340
+ * The simplest decision model: one projection over the document scope, which
341
+ * rejects on a deleted document.
342
+ */
343
+ function documentDecisionModel(target) {
344
+ return {
345
+ projections: { document: {
346
+ decidingActions: ["DELETE_DOCUMENT"],
347
+ apply: (document, operation) => operation.action.type === "DELETE_DOCUMENT" ? applyDeleteDocumentAction({
348
+ ...document,
349
+ state: { ...document.state }
350
+ }, operation.action) : document,
351
+ query: {
352
+ documentId: target.documentId,
353
+ branch: target.branch,
354
+ scope: "document"
355
+ }
356
+ } },
357
+ evaluatesScope() {
358
+ return true;
359
+ },
360
+ decide(model, subject, request) {
361
+ return request.verb === "execute" && model.document.isDeleted ? {
362
+ decision: "deny",
363
+ reason: DOCUMENT_DELETED_REASON
364
+ } : { decision: "allow" };
365
+ }
366
+ };
367
+ }
368
+ //#endregion
369
+ //#region src/decision/registered-model.ts
370
+ /**
371
+ * Builds the model at the stream heads and decides one request against it. The
372
+ * append condition it returns is the read-set the store enforces at write time.
373
+ *
374
+ * With `conditions` supplied, the executing scope's state is read at the head
375
+ * for `doc.<scope>.*` paths, or taken from the run's carried document when the
376
+ * caller has already reduced earlier writes into it. That read carries no
377
+ * append-condition entry of its own: the written stream's expected-revision
378
+ * check already refuses a write whose scope grew between the read and the
379
+ * append.
380
+ */
381
+ async function decideAtHead(model, cache, target, subject, request, signal, conditions) {
382
+ const built = await buildDecisionModel(cache, model, target, signal);
383
+ let scopeState;
384
+ if (conditions !== void 0) scopeState = (conditions.carriedDocument ?? await cache.getState(target.documentId, request.scope, target.branch, void 0, signal)).state[request.scope];
385
+ return {
386
+ evaluation: model(target).decide(built.model, subject, request, {
387
+ scopeState,
388
+ actionInput: conditions?.actionInput
389
+ }),
390
+ appendCondition: built.appendCondition,
391
+ documentVersion: built.model.document.version,
392
+ deletedAtUtcIso: built.model.document.deletedAtUtcIso ?? null
393
+ };
394
+ }
395
+ /**
396
+ * The model this reactor enforces. With `authEnforcement` off the auth scope is
397
+ * absent from every append condition and no load walks it; with `authGroups`
398
+ * on, the group documents the grant list names join the read-set and the
399
+ * registry supplies the reducer that folds them.
400
+ */
401
+ function selectDecisionModel(flags, registry) {
402
+ if (flags.authConditions) return authConditionsDecisionModel(registry);
403
+ if (flags.authGroups) return authGroupsDecisionModel(registry);
404
+ return flags.authEnforcement ? authDecisionModel : documentDecisionModel;
405
+ }
406
+ //#endregion
407
+ //#region src/executor/types.ts
408
+ /** 200k operations purge in 1.6 s on local Postgres; jobs time out at 30 s. */
409
+ const DEFAULT_MAX_PURGE_OPERATIONS = 2e5;
410
+ /** How long a deferred job waits for its document before it fails. */
411
+ const DEFAULT_DEFERRED_JOB_TTL_MS = 3e4;
412
+ /**
413
+ * Event types for the job executor
414
+ */
415
+ const JobExecutorEventTypes = {
416
+ JOB_STARTED: 2e4,
417
+ JOB_COMPLETED: 20001,
418
+ JOB_FAILED: 20002,
419
+ EXECUTOR_STARTED: 20003,
420
+ EXECUTOR_STOPPED: 20004
421
+ };
422
+ //#endregion
423
+ //#region src/core/feature-flags.ts
424
+ /**
425
+ * Every flag this reactor knows, with the flags it requires. A stage adds its
426
+ * flag here when it ships, so asking an older reactor for a later stage's flag
427
+ * is an unrecognized name rather than a flag that quietly does nothing.
428
+ */
429
+ const FLAG_PREREQUISITES = {
430
+ documentDecisions: [],
431
+ authEnforcement: ["documentDecisions"],
432
+ authGroups: ["authEnforcement"],
433
+ authConditions: ["authGroups"]
434
+ };
435
+ /**
436
+ * The flags as plain booleans, with anything unset off, validated. Callers hold
437
+ * a partial set, because that is what crosses to a pooled worker, and every
438
+ * consumer needs the same resolution of it.
439
+ */
440
+ function resolveFeatureFlags(flags = {}) {
441
+ const resolved = {
442
+ documentDecisions: flags.documentDecisions ?? false,
443
+ authEnforcement: flags.authEnforcement ?? false,
444
+ authGroups: flags.authGroups ?? false,
445
+ authConditions: flags.authConditions ?? false
446
+ };
447
+ validateFeatureFlags(flags, FLAG_PREREQUISITES);
448
+ return resolved;
449
+ }
450
+ /**
451
+ * Throws when the flags ask for enforcement the reactor cannot deliver. Either
452
+ * failure would otherwise read as enforcement being on while the reactor
453
+ * applies less than the caller asked for.
454
+ */
455
+ function validateFeatureFlags(flags, prerequisites) {
456
+ const known = Object.keys(prerequisites);
457
+ const unrecognized = Object.keys(flags).filter((name) => !known.includes(name));
458
+ if (unrecognized.length > 0) throw new Error(`Unrecognized reactor feature flag: ${unrecognized.join(", ")}. This reactor knows: ${known.join(", ")}.`);
459
+ for (const name of known) {
460
+ if (flags[name] !== true) continue;
461
+ const missing = prerequisites[name].filter((required) => flags[required] !== true);
462
+ if (missing.length > 0) throw new Error(`Reactor feature flag ${name} requires ${missing.join(", ")}.`);
463
+ }
464
+ }
465
+ //#endregion
466
+ //#region src/storage/kysely/document-purger.ts
467
+ /** An `Operation` row whose DELETE_DOCUMENT applied: not errored, not denied. */
468
+ const appliedDelete = sql`action->>'type' = 'DELETE_DOCUMENT' and coalesce(error, '') = '' and coalesce("deniedReason", '') = ''`;
469
+ /** Rows removed per statement from the tables a document can fill. */
470
+ const DEFAULT_PURGE_DELETE_BATCH = 5e3;
471
+ /** A purge transaction's statements; bound to the job's transaction. */
472
+ var KyselyDocumentPurger = class {
473
+ batchSize;
474
+ db;
475
+ constructor(db, batchSize = DEFAULT_PURGE_DELETE_BATCH) {
476
+ this.batchSize = batchSize;
477
+ this.db = db;
478
+ }
479
+ /** Every stream the document holds operations in. */
480
+ async streams(documentId) {
481
+ return this.db.selectFrom("Operation").select(["scope", "branch"]).distinct().where("documentId", "=", documentId).orderBy("scope").orderBy("branch").execute();
482
+ }
483
+ async operationCount(documentId) {
484
+ const row = await this.db.selectFrom("operation_index_operations").select((eb) => eb.fn.countAll().as("count")).where("documentId", "=", documentId).executeTakeFirst();
485
+ return Number(row?.count ?? 0);
486
+ }
487
+ /** Untombstoned documents group_references records as naming the group. */
488
+ async groupReferencers(groupId) {
489
+ const ids = (await this.db.selectFrom("group_references").select("documentId").where("groupId", "=", groupId).where("documentId", "<>", groupId).orderBy("documentId").execute()).map((row) => row.documentId);
490
+ const purged = await findPurged(this.db, ids);
491
+ return ids.filter((id) => !purged.has(id));
492
+ }
493
+ /** Survivors whose accepted auth history names the group; refusals do not. */
494
+ async groupReferencersInHistory(groupId) {
495
+ const referencing = [];
496
+ for (const documentId of await this.groupReferencers(groupId)) if ([...(await this.authOperations(documentId)).values()].some((operations) => garbageCollect(sortOperations(operations)).some((operation) => operation.deniedReason === void 0 && operation.error === void 0 && mentionedGroupIds(operation.action).includes(groupId)))) referencing.push(documentId);
497
+ return referencing;
498
+ }
499
+ /** The document's auth-scope operations, per branch, in index order. */
500
+ async authOperations(documentId) {
501
+ const rows = await this.db.selectFrom("Operation").selectAll().where("documentId", "=", documentId).where("scope", "=", "auth").orderBy("branch").orderBy("index").execute();
502
+ const byBranch = /* @__PURE__ */ new Map();
503
+ for (const row of rows) {
504
+ const operations = byBranch.get(row.branch) ?? [];
505
+ operations.push({
506
+ index: row.index,
507
+ timestampUtcMs: row.timestampUtcMs.toISOString(),
508
+ hash: row.hash,
509
+ skip: row.skip,
510
+ error: row.error || void 0,
511
+ deniedReason: row.deniedReason || void 0,
512
+ id: row.opId,
513
+ action: row.action
514
+ });
515
+ byBranch.set(row.branch, operations);
516
+ }
517
+ return byBranch;
518
+ }
519
+ /** Every document ever in the collection, but its owner and its own row. */
520
+ async collectionMembers(collectionId, ownerId, branch) {
521
+ return (await this.db.selectFrom("document_collections as dc").select("dc.documentId").select(sql`dc."leftOrdinal" is null`.as("openHere")).select((eb) => eb.exists(eb.selectFrom("Operation as op").select("op.opId").whereRef("op.documentId", "=", "dc.documentId").where("op.branch", "=", branch).where("op.scope", "=", "document").where(appliedDelete)).as("deleted")).select((eb) => eb.exists(eb.selectFrom("document_collections as other").select("other.documentId").whereRef("other.documentId", "=", "dc.documentId").where("other.collectionId", "<>", collectionId).where("other.leftOrdinal", "is", null)).as("openElsewhere")).where("dc.collectionId", "=", collectionId).where("dc.documentId", "not in", [ownerId, collectionId]).orderBy("dc.documentId").execute()).map((row) => {
522
+ const openElsewhere = Boolean(row.openElsewhere);
523
+ return {
524
+ documentId: row.documentId,
525
+ openElsewhere,
526
+ required: !openElsewhere && (Boolean(row.openHere) || Boolean(row.deleted))
527
+ };
528
+ });
529
+ }
530
+ async remoteCollection(remoteName) {
531
+ return (await this.db.selectFrom("sync_remotes").select("collection_id").where("name", "=", remoteName).executeTakeFirst())?.collection_id;
532
+ }
533
+ /** Deletes every row about the document; the counts are per table. */
534
+ async deleteRows(documentId) {
535
+ const removed = {};
536
+ removed.Operation = await this.deleteBatched(async () => {
537
+ const result = await this.db.deleteFrom("Operation").where("id", "in", (eb) => eb.selectFrom("Operation").select("id").where("documentId", "=", documentId).limit(this.batchSize)).executeTakeFirst();
538
+ return Number(result.numDeletedRows);
539
+ });
540
+ removed.operation_index_operations = await this.deleteBatched(async () => {
541
+ const result = await this.db.deleteFrom("operation_index_operations").where("ordinal", "in", (eb) => eb.selectFrom("operation_index_operations").select("ordinal").where("documentId", "=", documentId).limit(this.batchSize)).executeTakeFirst();
542
+ return Number(result.numDeletedRows);
543
+ });
544
+ removed.Keyframe = await this.deleteBatched(async () => {
545
+ const result = await this.db.deleteFrom("Keyframe").where("id", "in", (eb) => eb.selectFrom("Keyframe").select("id").where("documentId", "=", documentId).limit(this.batchSize)).executeTakeFirst();
546
+ return Number(result.numDeletedRows);
547
+ });
548
+ removed.DocumentSnapshot = await this.deleteBatched(async () => {
549
+ const result = await this.db.deleteFrom("DocumentSnapshot").where("id", "in", (eb) => eb.selectFrom("DocumentSnapshot").select("id").where("documentId", "=", documentId).limit(this.batchSize)).executeTakeFirst();
550
+ return Number(result.numDeletedRows);
551
+ });
552
+ removed.SlugMapping = await this.deleteWhere("SlugMapping", "documentId", documentId);
553
+ const relationships = await this.db.selectFrom("DocumentRelationship").select((eb) => eb.fn.countAll().as("count")).where((eb) => eb.or([eb("sourceId", "=", documentId), eb("targetId", "=", documentId)])).executeTakeFirst();
554
+ removed.DocumentRelationship = Number(relationships?.count ?? 0);
555
+ removed.Document = await this.deleteWhere("Document", "id", documentId);
556
+ removed.group_references = await this.deleteWhere("group_references", "documentId", documentId);
557
+ removed.sync_dead_letters = await this.deleteWhere("sync_dead_letters", "document_id", documentId);
558
+ removed.sync_holds = await this.deleteWhere("sync_holds", "document_id", documentId);
559
+ return removed;
560
+ }
561
+ async writeTombstone(tombstone) {
562
+ const values = {
563
+ documentId: tombstone.documentId,
564
+ ordinal: tombstone.ordinal,
565
+ removedRows: JSON.stringify(tombstone.removedRows),
566
+ purgedAtUtc: tombstone.purgedAtUtc,
567
+ requestId: tombstone.requestId
568
+ };
569
+ await this.db.insertInto("document_purges").values(values).onConflict((oc) => oc.column("documentId").doUpdateSet({
570
+ ordinal: values.ordinal,
571
+ removedRows: values.removedRows,
572
+ purgedAtUtc: values.purgedAtUtc,
573
+ requestId: values.requestId
574
+ })).execute();
575
+ }
576
+ /** Reopens every membership at the marker ordinal, plus `collectionIds`. */
577
+ async reopenMemberships(documentId, ordinal, collectionIds = []) {
578
+ await this.db.updateTable("document_collections").set({
579
+ joinedOrdinal: BigInt(ordinal),
580
+ leftOrdinal: null
581
+ }).where("documentId", "=", documentId).execute();
582
+ for (const collectionId of new Set(collectionIds)) await this.db.insertInto("document_collections").values({
583
+ documentId,
584
+ collectionId,
585
+ joinedOrdinal: BigInt(ordinal),
586
+ leftOrdinal: null
587
+ }).onConflict((oc) => oc.columns(["documentId", "collectionId"]).doUpdateSet({
588
+ joinedOrdinal: BigInt(ordinal),
589
+ leftOrdinal: null
590
+ })).execute();
591
+ return (await this.db.selectFrom("document_collections").select("collectionId").where("documentId", "=", documentId).orderBy("collectionId").execute()).map((row) => row.collectionId);
592
+ }
593
+ async deleteBatched(step) {
594
+ let total = 0;
595
+ for (;;) {
596
+ const deleted = await step();
597
+ total += deleted;
598
+ if (deleted < this.batchSize) return total;
599
+ }
600
+ }
601
+ async deleteWhere(table, column, documentId) {
602
+ const result = await this.db.deleteFrom(table).where(column, "=", documentId).executeTakeFirst();
603
+ return Number(result.numDeletedRows);
604
+ }
605
+ };
606
+ //#endregion
607
+ //#region src/executor/execution-scope.ts
608
+ /** For scopes without a transaction to hold a lock in. */
609
+ const NOOP_DOCUMENT_LOCKS = {
610
+ shared: () => Promise.resolve(),
611
+ exclusive: () => Promise.resolve(),
612
+ purged: () => Promise.resolve(/* @__PURE__ */ new Set())
613
+ };
614
+ var DefaultExecutionScope = class {
615
+ operationStore;
616
+ operationIndex;
617
+ writeCache;
618
+ documentMetaCache;
619
+ collectionMembershipCache;
620
+ constructor(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache) {
621
+ this.operationStore = operationStore;
622
+ this.operationIndex = operationIndex;
623
+ this.writeCache = writeCache;
624
+ this.documentMetaCache = documentMetaCache;
625
+ this.collectionMembershipCache = collectionMembershipCache;
626
+ }
627
+ async run(fn, signal) {
628
+ signal?.throwIfAborted();
629
+ return fn({
630
+ operationStore: this.operationStore,
631
+ operationIndex: this.operationIndex,
632
+ writeCache: this.writeCache,
633
+ documentMetaCache: this.documentMetaCache,
634
+ collectionMembershipCache: this.collectionMembershipCache,
635
+ documentLocks: NOOP_DOCUMENT_LOCKS
636
+ });
637
+ }
638
+ };
639
+ var KyselyExecutionScope = class {
640
+ db;
641
+ operationStore;
642
+ operationIndex;
643
+ keyframeStore;
644
+ writeCache;
645
+ documentMetaCache;
646
+ collectionMembershipCache;
647
+ constructor(db, operationStore, operationIndex, keyframeStore, writeCache, documentMetaCache, collectionMembershipCache) {
648
+ this.db = db;
649
+ this.operationStore = operationStore;
650
+ this.operationIndex = operationIndex;
651
+ this.keyframeStore = keyframeStore;
652
+ this.writeCache = writeCache;
653
+ this.documentMetaCache = documentMetaCache;
654
+ this.collectionMembershipCache = collectionMembershipCache;
655
+ }
656
+ async run(fn, signal) {
657
+ signal?.throwIfAborted();
658
+ return this.db.transaction().execute(async (trx) => {
659
+ const sharedLocked = /* @__PURE__ */ new Set();
660
+ const liveIds = /* @__PURE__ */ new Set();
661
+ const scopedOperationStore = this.operationStore.withTransaction(trx, liveIds);
662
+ const scopedOperationIndex = this.operationIndex.withTransaction(trx, liveIds);
663
+ const scopedKeyframeStore = this.keyframeStore.withTransaction(trx);
664
+ return fn({
665
+ operationStore: scopedOperationStore,
666
+ operationIndex: scopedOperationIndex,
667
+ writeCache: this.writeCache.withScopedStores(scopedOperationStore, scopedKeyframeStore),
668
+ documentMetaCache: this.documentMetaCache.withScopedStore(scopedOperationStore),
669
+ collectionMembershipCache: this.collectionMembershipCache.withScopedIndex(scopedOperationIndex),
670
+ documentLocks: {
671
+ shared: async (ids) => {
672
+ const list = [...ids];
673
+ await acquirePurgeLocks(trx, list, "shared");
674
+ for (const id of list) sharedLocked.add(id);
675
+ },
676
+ exclusive: (id) => acquirePurgeLocks(trx, [id], "exclusive"),
677
+ purged: async (ids) => {
678
+ const list = [...ids];
679
+ const found = await findPurged(trx, list);
680
+ for (const id of list) if (sharedLocked.has(id) && !found.has(id)) liveIds.add(id);
681
+ return found;
682
+ }
683
+ },
684
+ purger: new KyselyDocumentPurger(trx)
685
+ });
686
+ });
687
+ }
688
+ };
689
+ //#endregion
690
+ //#region src/utils/reshuffle.ts
691
+ const STRICT_ORDER_ACTION_TYPES = /* @__PURE__ */ new Set([
692
+ "CREATE_DOCUMENT",
693
+ "DELETE_DOCUMENT",
694
+ "UPGRADE_DOCUMENT",
695
+ "ADD_RELATIONSHIP",
696
+ "REMOVE_RELATIONSHIP",
697
+ "UPDATE_RELATIONSHIP",
698
+ "PURGE_DOCUMENT",
699
+ "ADD_FOLDER",
700
+ "UPDATE_FOLDER",
701
+ "REMOVE_FOLDER"
702
+ ]);
703
+ /**
704
+ * Reshuffles operations by timestamp, then applies deterministic tie-breaking.
705
+ * Used for merging concurrent operations from different branches.
706
+ *
707
+ * For strict document-structure actions (e.g., CREATE_DOCUMENT/UPGRADE_DOCUMENT),
708
+ * logical index (index - skip) is prioritized to preserve causal replay order.
709
+ *
710
+ * For other actions, action ID is prioritized to ensure a canonical cross-reactor order
711
+ * for concurrent operations that may have diverged local indices due to prior reshuffles.
712
+ * Logical index and operation ID are then used as deterministic tie-breakers.
713
+ *
714
+ * Example:
715
+ * [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]
716
+ * GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]
717
+ * Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]
718
+ * Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]
719
+ * merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]
720
+ */
721
+ function reshuffleByTimestamp(startIndex, opsA, opsB) {
722
+ return [...opsA, ...opsB].sort((a, b) => {
723
+ const timestampDiff = new Date(a.timestampUtcMs).getTime() - new Date(b.timestampUtcMs).getTime();
724
+ if (timestampDiff !== 0) return timestampDiff;
725
+ const rank = (op) => STRICT_ORDER_ACTION_TYPES.has(op.action?.type ?? "") ? 0 : 1;
726
+ const rankDiff = rank(a) - rank(b);
727
+ if (rankDiff !== 0) return rankDiff;
728
+ if (rank(a) === 0) {
729
+ const logicalIndexDiff = a.index - a.skip - (b.index - b.skip);
730
+ if (logicalIndexDiff !== 0) return logicalIndexDiff;
731
+ }
732
+ const actionIdDiff = (a.action?.id ?? "").localeCompare(b.action?.id ?? "");
733
+ if (actionIdDiff !== 0) return actionIdDiff;
734
+ return a.id.localeCompare(b.id);
735
+ }).map((op, i) => ({
736
+ ...op,
737
+ index: startIndex.index + i,
738
+ skip: i === 0 ? startIndex.skip : 0
739
+ }));
740
+ }
741
+ //#endregion
742
+ //#region src/decision/merged-order.ts
743
+ /** Identifies a stream within a walk. */
744
+ function streamKey(query) {
745
+ return `${query.documentId}:${query.scope}:${query.branch}`;
746
+ }
747
+ /**
748
+ * Orders two operations from different streams by position. Timestamp decides;
749
+ * an equal timestamp puts an auth operation first, and otherwise falls to the
750
+ * action id and then the operation id, so that two replicas holding the same
751
+ * operations agree on the order whatever order they happen to store them in.
752
+ */
753
+ function comparePositions(a, b) {
754
+ const aTime = Date.parse(a.operation.timestampUtcMs);
755
+ const bTime = Date.parse(b.operation.timestampUtcMs);
756
+ if (aTime !== bTime) return aTime - bTime;
757
+ if (a.streamKey === b.streamKey) return a.operation.index - b.operation.index;
758
+ const aAuth = a.scope === "auth";
759
+ if (aAuth !== (b.scope === "auth")) return aAuth ? -1 : 1;
760
+ const actionIds = (a.operation.action.id ?? "").localeCompare(b.operation.action.id ?? "");
761
+ if (actionIds !== 0) return actionIds;
762
+ return (a.operation.id ?? "").localeCompare(b.operation.id ?? "");
763
+ }
764
+ /**
765
+ * Merges the read-set streams into one sequence by position. An operation's
766
+ * place in the result is the bound a decision at that operation reads to: every
767
+ * operation before it has been applied, and it has not.
768
+ */
769
+ function mergeByPosition(streams) {
770
+ const merged = [];
771
+ for (const stream of streams) for (const operation of stream.operations) merged.push({
772
+ streamKey: stream.streamKey,
773
+ scope: stream.scope,
774
+ operation
775
+ });
776
+ return merged.sort(comparePositions);
777
+ }
778
+ /**
779
+ * The skip that retracts everything from `firstRetractedIndex` up to where the
780
+ * re-appended operation lands. It spans the indexes rather than counting the
781
+ * operations, because a stream with a gap in it makes those differ.
782
+ */
783
+ function retractionSkip(nextIndex, firstRetractedIndex) {
784
+ return nextIndex - firstRetractedIndex;
785
+ }
786
+ //#endregion
787
+ //#region src/decision/walk.ts
788
+ /**
789
+ * A single forward pass is only correct while a stream's effective operations
790
+ * are ordered.
791
+ */
792
+ function assertPositionOrder(streamKey, scope, operations) {
793
+ for (let i = 1; i < operations.length; i++) {
794
+ const previous = operations[i - 1];
795
+ const current = operations[i];
796
+ if (comparePositions({
797
+ streamKey,
798
+ scope,
799
+ operation: previous
800
+ }, {
801
+ streamKey,
802
+ scope,
803
+ operation: current
804
+ }) > 0) throw new Error(`Stream ${streamKey} is out of position order: index ${previous.index} at ${previous.timestampUtcMs} precedes index ${current.index} at ${current.timestampUtcMs}`);
805
+ }
806
+ }
807
+ /**
808
+ * Visits every operation in the read-set once, in the order their positions
809
+ * fall, and hands back the state each stream held just before it. That state is
810
+ * what a decision at that operation reads.
811
+ *
812
+ * Skips are resolved first (i.e. this is performed on a garbage collected
813
+ * stream), which means we can do a single forward pass.
814
+ *
815
+ * An operation that contributes no state, whether denied or holding a reducer
816
+ * error, is visited but not applied (this matches the write cache's rebuild).
817
+ *
818
+ * The consumer sends back whether it refused the operation it was handed: a
819
+ * refusal this pass produced must suppress it the same way a stored one does.
820
+ */
821
+ function* walkByPosition(streams) {
822
+ const merged = mergeByPosition(streams.map((stream) => {
823
+ const operations = garbageCollect(sortOperations([...stream.operations]));
824
+ assertPositionOrder(stream.streamKey, stream.scope, operations);
825
+ return {
826
+ streamKey: stream.streamKey,
827
+ scope: stream.scope,
828
+ operations
829
+ };
830
+ }));
831
+ const byKey = new Map(streams.map((stream) => [stream.streamKey, stream]));
832
+ const states = new Map(streams.map((stream) => [stream.streamKey, stream.document]));
833
+ for (const { streamKey, operation } of merged) {
834
+ if ((yield {
835
+ streamKey,
836
+ operation,
837
+ states: new Map(states)
838
+ }) || operation.error !== void 0 || isDenied(operation)) continue;
839
+ const stream = byKey.get(streamKey);
840
+ const before = states.get(streamKey);
841
+ if (before === void 0 || stream === void 0) throw new Error(`No state for stream ${streamKey}`);
842
+ states.set(streamKey, stream.apply(before, operation));
843
+ }
844
+ }
845
+ //#endregion
846
+ //#region src/decision/evaluation.ts
847
+ /** The stream key for evaluated operations whose scope no projection reads. */
848
+ const EVALUATED_ONLY = "evaluated";
849
+ /**
850
+ * Whether any stream the model reads declares this operation's action type as
851
+ * one that can change an evaluation.
852
+ */
853
+ function isDecidingAction(operation, readSet) {
854
+ return readSet.some((stream) => stream.decidingActions.includes(operation.action.type));
855
+ }
856
+ /**
857
+ * Who an operation acts as. A replayed operation is evaluated as its own signer,
858
+ * so an address-scoped policy does not deny its own author's history.
859
+ */
860
+ function subjectOf(operation) {
861
+ const signer = operation.action.context?.signer;
862
+ return {
863
+ address: signer?.user.address,
864
+ key: signer?.app.key
865
+ };
866
+ }
867
+ /**
868
+ * The model as the walk reached this operation: each static projection's value
869
+ * is its own scope's state, and each derived projection's value maps document
870
+ * id to that document's state, holding only the streams this replica walked. A
871
+ * derived stream it does not hold stays out of the map, which fails closed.
872
+ */
873
+ function modelAt(readSet, derivedNames, derived, states) {
874
+ const model = {};
875
+ for (const stream of readSet) {
876
+ const document = states.get(streamKey(stream.query));
877
+ if (document === void 0) throw new Error(`No state walked for projection ${stream.name}`);
878
+ model[stream.name] = document.state[stream.query.scope];
879
+ }
880
+ for (const name of derivedNames) model[name] = {};
881
+ for (const entry of derived) {
882
+ const map = model[entry.name];
883
+ const document = states.get(streamKey(entry.query));
884
+ if (document !== void 0) map[entry.query.documentId] = document.state[entry.query.scope];
885
+ }
886
+ return model;
887
+ }
888
+ /**
889
+ * Evaluates each operation at its own position and returns the refusals in an
890
+ * array parallel to the operations, where undefined means allowed.
891
+ *
892
+ * A position is a timestamp, so an operation refused by a delete is one that
893
+ * sorts after it, and the operations before it are left alone. That holds
894
+ * whether the delete is already stored or is among the operations passed in.
895
+ */
896
+ async function evaluateByPosition(model, target, subject, stores, signal) {
897
+ const { scope, operations } = subject;
898
+ const { writeCache, operationStore } = stores;
899
+ const definition = model(target);
900
+ const readSet = staticReadSet(definition);
901
+ const derivedSet = derivedReadSet(definition);
902
+ if (!definition.evaluatesScope(scope)) return operations.map(() => void 0);
903
+ const evaluating = new Set(operations.map((operation) => operation.id));
904
+ const creation = operations.find((operation) => operation.action.type === "CREATE_DOCUMENT" && operation.action.input.documentId === target.documentId);
905
+ async function stateBefore(query) {
906
+ try {
907
+ return await writeCache.getState(query.documentId, query.scope, query.branch, -1, signal);
908
+ } catch (error) {
909
+ if (creation !== void 0 && query.documentId === target.documentId && error instanceof DocumentNotFoundError && !(error instanceof DocumentPurgedError)) return createDocumentFromAction(creation.action);
910
+ throw error;
911
+ }
912
+ }
913
+ const readStreams = await Promise.all(readSet.map(async (stream) => ({
914
+ stream,
915
+ operations: (await operationStore.getSince(stream.query.documentId, stream.query.scope, stream.query.branch, -1, { actionTypes: stream.decidingActions }, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id))
916
+ })));
917
+ const decidingOperations = operations.filter((operation) => isDecidingAction(operation, readSet));
918
+ if (readStreams.every((read) => read.operations.length === 0) && decidingOperations.length === 0) return operations.map(() => void 0);
919
+ if (readStreams.length === 0) throw new Error(`Decision model for ${target.documentId} reads no stream whose query is known before it is built`);
920
+ const writtenProjection = readSet.find((stream) => stream.query.scope === scope);
921
+ const walked = [];
922
+ const histories = [];
923
+ for (const read of readStreams) {
924
+ const streamOperations = read.stream === writtenProjection ? [...read.operations, ...operations] : read.operations;
925
+ const before = await stateBefore(read.stream.query);
926
+ walked.push({
927
+ streamKey: streamKey(read.stream.query),
928
+ scope: read.stream.query.scope,
929
+ document: before,
930
+ operations: streamOperations,
931
+ apply: read.stream.apply
932
+ });
933
+ histories.push({
934
+ name: read.stream.name,
935
+ operations: streamOperations
936
+ });
937
+ }
938
+ let evaluatedStateKey;
939
+ if (writtenProjection !== void 0) evaluatedStateKey = streamKey(writtenProjection.query);
940
+ else if (definition.foldEvaluatedScope !== void 0) {
941
+ const query = {
942
+ documentId: target.documentId,
943
+ scope,
944
+ branch: target.branch
945
+ };
946
+ const storedOperations = (await operationStore.getSince(query.documentId, query.scope, query.branch, -1, void 0, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id));
947
+ const before = await stateBefore(query);
948
+ evaluatedStateKey = streamKey(query);
949
+ walked.push({
950
+ streamKey: evaluatedStateKey,
951
+ scope,
952
+ document: before,
953
+ operations: [...storedOperations, ...operations],
954
+ apply: definition.foldEvaluatedScope
955
+ });
956
+ } else walked.push({
957
+ streamKey: EVALUATED_ONLY,
958
+ scope,
959
+ document: walked[0].document,
960
+ operations,
961
+ apply: (document) => document
962
+ });
963
+ const derivedEntries = [];
964
+ const walkedKeys = new Set(walked.map((stream) => stream.streamKey));
965
+ for (const projection of derivedSet) {
966
+ const queries = projection.queryOverHistory?.(histories) ?? [];
967
+ for (const query of queries) {
968
+ const key = streamKey(query);
969
+ if (walkedKeys.has(key)) continue;
970
+ let before;
971
+ try {
972
+ before = await writeCache.getState(query.documentId, query.scope, query.branch, -1, signal);
973
+ } catch (error) {
974
+ if (error instanceof DocumentNotFoundError) continue;
975
+ throw error;
976
+ }
977
+ const streamOperations = (await operationStore.getSince(query.documentId, query.scope, query.branch, -1, { actionTypes: projection.decidingActions }, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id));
978
+ walkedKeys.add(key);
979
+ walked.push({
980
+ streamKey: key,
981
+ scope: query.scope,
982
+ document: before,
983
+ operations: streamOperations,
984
+ apply: projection.apply
985
+ });
986
+ derivedEntries.push({
987
+ name: projection.name,
988
+ query
989
+ });
990
+ }
991
+ }
992
+ const reasons = /* @__PURE__ */ new Map();
993
+ const walk = walkByPosition(walked);
994
+ let step = walk.next(false);
995
+ while (!step.done) {
996
+ const position = step.value;
997
+ if (!evaluating.has(position.operation.id)) {
998
+ step = walk.next(false);
999
+ continue;
1000
+ }
1001
+ const evaluatedDocument = evaluatedStateKey === void 0 ? void 0 : position.states.get(evaluatedStateKey);
1002
+ const scopeState = evaluatedDocument === void 0 ? void 0 : evaluatedDocument.state[scope];
1003
+ const evaluation = definition.decide(modelAt(readSet, derivedSet.map((projection) => projection.name), derivedEntries, position.states), subjectOf(position.operation), {
1004
+ verb: "execute",
1005
+ scope: position.operation.action.scope,
1006
+ operation: position.operation.action.type
1007
+ }, {
1008
+ scopeState,
1009
+ actionInput: position.operation.action.input
1010
+ });
1011
+ const denied = evaluation.decision === "deny";
1012
+ reasons.set(position.operation.id, denied ? evaluation.reason : void 0);
1013
+ step = walk.next(denied);
1014
+ }
1015
+ return operations.map((operation) => reasons.get(operation.id));
1016
+ }
1017
+ //#endregion
1018
+ //#region src/executor/document-action-handler.ts
1019
+ var DocumentActionHandler = class {
1020
+ registry;
1021
+ logger;
1022
+ driveContainerTypes;
1023
+ featureFlags;
1024
+ decisionModel;
1025
+ protocolSupport;
1026
+ loggedUnregisteredProtocols = /* @__PURE__ */ new Set();
1027
+ constructor(registry, logger, driveContainerTypes, featureFlags, decisionModel, protocolSupport) {
1028
+ this.registry = registry;
1029
+ this.logger = logger;
1030
+ this.driveContainerTypes = driveContainerTypes;
1031
+ this.featureFlags = featureFlags;
1032
+ this.decisionModel = decisionModel;
1033
+ this.protocolSupport = protocolSupport;
1034
+ }
1035
+ /** Keys this reactor does not register are admitted: it cannot judge them. */
1036
+ unsupportedProtocol(documentId, protocolVersions) {
1037
+ for (const [protocol, version] of Object.entries(protocolVersions ?? {})) {
1038
+ const supported = this.protocolSupport[protocol];
1039
+ if (supported === void 0) {
1040
+ if (!this.loggedUnregisteredProtocols.has(protocol)) {
1041
+ this.loggedUnregisteredProtocols.add(protocol);
1042
+ this.logger.info("Admitting document @documentId with unregistered protocol @protocol @version", documentId, protocol, version);
1043
+ }
1044
+ continue;
1045
+ }
1046
+ if (!supported.includes(version)) return new UnsupportedProtocolVersionError(documentId, protocol, version);
1047
+ }
1048
+ }
1049
+ /** Whether the write arrives with its evaluation already decided. */
1050
+ alreadyEvaluated(executing) {
1051
+ return this.featureFlags.documentDecisions && (executing.replayingAcceptedHistory || executing.evaluatedByPosition);
1052
+ }
1053
+ async execute(write, executing) {
1054
+ const { action } = write;
1055
+ if (write.deniedReason !== void 0) return this.writeDenied(write, executing);
1056
+ const refusal = await this.refuseIfPolicyDenies(write, executing);
1057
+ if (refusal) return refusal;
1058
+ switch (action.type) {
1059
+ case "CREATE_DOCUMENT": return this.executeCreate(write, executing);
1060
+ case "DELETE_DOCUMENT": return this.executeDelete(write, executing);
1061
+ case "UPGRADE_DOCUMENT": return this.executeUpgrade(write, executing);
1062
+ case "ADD_RELATIONSHIP": return this.executeAddRelationship(write, executing);
1063
+ case "REMOVE_RELATIONSHIP": return this.executeRemoveRelationship(write, executing);
1064
+ case "UPDATE_RELATIONSHIP": return this.executeUpdateRelationship(write, executing);
1065
+ case "PURGE_DOCUMENT": return buildErrorResult(executing.job, new ReservedActionError(executing.job.documentId, action.type), executing.startTime);
1066
+ default: return buildErrorResult(executing.job, /* @__PURE__ */ new Error(`Unknown document action type: ${action.type}`), executing.startTime);
1067
+ }
1068
+ }
1069
+ /**
1070
+ * Refuses a document-scope write the policy denies, or undefined to proceed.
1071
+ * Without this an `execute`-on-`document` grant is unenforceable.
1072
+ */
1073
+ async refuseIfPolicyDenies(write, executing) {
1074
+ const { action } = write;
1075
+ const { job, startTime, stores, signal } = executing;
1076
+ if (!this.featureFlags.documentDecisions || !this.featureFlags.authEnforcement || this.alreadyEvaluated(executing) || !GATED_DOCUMENT_ACTIONS.has(action.type)) return;
1077
+ const documentId = targetDocumentId(action, job.documentId);
1078
+ let admission;
1079
+ try {
1080
+ admission = await decideAtHead(this.decisionModel, stores.writeCache, {
1081
+ documentId,
1082
+ branch: job.branch
1083
+ }, {
1084
+ address: action.context?.signer?.user.address,
1085
+ key: action.context?.signer?.app.key
1086
+ }, {
1087
+ verb: "execute",
1088
+ scope: action.scope,
1089
+ operation: action.type
1090
+ }, signal, this.featureFlags.authConditions ? { actionInput: action.input } : void 0);
1091
+ } catch (error) {
1092
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
1093
+ }
1094
+ if (admission.evaluation.decision === "allow") return;
1095
+ return buildErrorResult(job, refusalError(admission.evaluation.reason, documentId, admission.deletedAtUtcIso, action), startTime);
1096
+ }
1097
+ /** A refused operation holds a position in the stream but changes nothing. */
1098
+ async writeDenied(write, executing) {
1099
+ const { action, skip, sourceRemote, deniedReason } = write;
1100
+ const { job, startTime, indexTxn, stores, signal } = executing;
1101
+ let document;
1102
+ try {
1103
+ document = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);
1104
+ } catch (error) {
1105
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
1106
+ }
1107
+ const index = getNextIndexForScope(document, job.scope);
1108
+ let standing = document;
1109
+ if (skip > 0) try {
1110
+ standing = await stores.writeCache.getState(job.documentId, job.scope, job.branch, index - skip - 1, signal);
1111
+ } catch (error) {
1112
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
1113
+ }
1114
+ let operation = createOperation(action, index, skip, {
1115
+ documentId: job.documentId,
1116
+ scope: job.scope,
1117
+ branch: job.branch
1118
+ });
1119
+ operation.deniedReason = deniedReason;
1120
+ operation.hash = hashDocumentStateForScope(standing, job.scope);
1121
+ const writeResult = await this.writeOperationToStore({
1122
+ documentId: job.documentId,
1123
+ documentType: document.header.documentType,
1124
+ scope: job.scope,
1125
+ branch: job.branch
1126
+ }, operation, executing);
1127
+ if (!Array.isArray(writeResult)) return writeResult;
1128
+ operation = writeResult[0];
1129
+ updateDocumentRevision(standing, job.scope, operation.index);
1130
+ standing.operations = {
1131
+ ...standing.operations,
1132
+ [job.scope]: [...standing.operations[job.scope] ?? [], operation]
1133
+ };
1134
+ executing.touchedStreams.add(job.documentId, job.scope, job.branch);
1135
+ stores.writeCache.putState(job.documentId, job.scope, job.branch, operation.index, standing, "head");
1136
+ indexTxn.write([{
1137
+ ...operation,
1138
+ documentId: job.documentId,
1139
+ documentType: document.header.documentType,
1140
+ branch: job.branch,
1141
+ scope: job.scope,
1142
+ sourceRemote
1143
+ }]);
1144
+ stores.documentMetaCache.putDocumentMeta(job.documentId, job.branch, {
1145
+ state: standing.state.document,
1146
+ documentType: standing.header.documentType,
1147
+ protocolVersions: standing.header.protocolVersions,
1148
+ documentScopeRevision: operation.index + 1
1149
+ });
1150
+ return buildSuccessResult(job, operation, job.documentId, standing.header.documentType, JSON.stringify({
1151
+ header: standing.header,
1152
+ document: standing.state.document
1153
+ }), startTime);
1154
+ }
1155
+ async executeCreate(write, executing) {
1156
+ const { action, skip, sourceRemote } = write;
1157
+ const { job, startTime, indexTxn, stores, signal } = executing;
1158
+ if (job.scope !== "document") return {
1159
+ job,
1160
+ success: false,
1161
+ error: /* @__PURE__ */ new Error(`CREATE_DOCUMENT must be in "document" scope, got "${job.scope}"`),
1162
+ duration: Date.now() - startTime
1163
+ };
1164
+ const input = action.input;
1165
+ const unsupported = this.unsupportedProtocol(input.documentId, input.protocolVersions);
1166
+ if (unsupported) return buildErrorResult(job, unsupported, startTime);
1167
+ const document = createDocumentFromAction(action);
1168
+ let operation = createOperation(action, 0, skip, {
1169
+ documentId: document.header.id,
1170
+ scope: job.scope,
1171
+ branch: job.branch
1172
+ });
1173
+ const resultingStateObj = {
1174
+ ...document.state,
1175
+ header: document.header
1176
+ };
1177
+ const resultingState = JSON.stringify(resultingStateObj);
1178
+ const writeResult = await this.writeOperationToStore({
1179
+ documentId: document.header.id,
1180
+ documentType: document.header.documentType,
1181
+ scope: job.scope,
1182
+ branch: job.branch
1183
+ }, operation, executing);
1184
+ if (!Array.isArray(writeResult)) return writeResult;
1185
+ operation = writeResult[0];
1186
+ updateDocumentRevision(document, job.scope, operation.index);
1187
+ document.operations = {
1188
+ ...document.operations,
1189
+ [job.scope]: [...document.operations[job.scope] ?? [], operation]
1190
+ };
1191
+ executing.touchedStreams.add(document.header.id, job.scope, job.branch);
1192
+ stores.writeCache.putState(document.header.id, job.scope, job.branch, operation.index, document, "head");
1193
+ indexTxn.write([{
1194
+ ...operation,
1195
+ documentId: document.header.id,
1196
+ documentType: document.header.documentType,
1197
+ branch: job.branch,
1198
+ scope: job.scope,
1199
+ sourceRemote
1200
+ }]);
1201
+ if (this.driveContainerTypes.has(document.header.documentType)) {
1202
+ const collectionId = DriveCollectionId.forDrive(document.header.id, job.branch).key;
1203
+ indexTxn.createCollection(collectionId);
1204
+ indexTxn.addToCollection(collectionId, document.header.id);
1205
+ }
1206
+ stores.documentMetaCache.putDocumentMeta(document.header.id, job.branch, {
1207
+ state: document.state.document,
1208
+ documentType: document.header.documentType,
1209
+ protocolVersions: document.header.protocolVersions,
1210
+ documentScopeRevision: 1
1211
+ });
1212
+ return buildSuccessResult(job, operation, document.header.id, document.header.documentType, resultingState, startTime);
1213
+ }
1214
+ async executeDelete(write, executing) {
1215
+ const { action, skip, sourceRemote } = write;
1216
+ const { job, startTime, indexTxn, stores, signal } = executing;
1217
+ const input = action.input;
1218
+ if (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error("DELETE_DOCUMENT action requires a documentId in input"), startTime);
1219
+ const documentId = input.documentId;
1220
+ let document;
1221
+ try {
1222
+ document = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);
1223
+ } catch (error) {
1224
+ return buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document before deletion: ${error instanceof Error ? error.message : String(error)}`), startTime);
1225
+ }
1226
+ const documentState = document.state.document;
1227
+ if (documentState.isDeleted && !this.alreadyEvaluated(executing)) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);
1228
+ const nextIndex = getNextIndexForScope(document, job.scope);
1229
+ let operation = createOperation(action, nextIndex, skip, {
1230
+ documentId,
1231
+ scope: job.scope,
1232
+ branch: job.branch
1233
+ });
1234
+ applyDeleteDocumentAction$1(document, action);
1235
+ const resultingStateObj = {
1236
+ header: document.header,
1237
+ document: document.state.document
1238
+ };
1239
+ const resultingState = JSON.stringify(resultingStateObj);
1240
+ const writeResult = await this.writeOperationToStore({
1241
+ documentId,
1242
+ documentType: document.header.documentType,
1243
+ scope: job.scope,
1244
+ branch: job.branch
1245
+ }, operation, executing);
1246
+ if (!Array.isArray(writeResult)) return writeResult;
1247
+ operation = writeResult[0];
1248
+ updateDocumentRevision(document, job.scope, operation.index);
1249
+ document.operations = {
1250
+ ...document.operations,
1251
+ [job.scope]: [...document.operations[job.scope] ?? [], operation]
1252
+ };
1253
+ executing.touchedStreams.add(documentId, job.scope, job.branch);
1254
+ stores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document, "head");
1255
+ indexTxn.write([{
1256
+ ...operation,
1257
+ documentId,
1258
+ documentType: document.header.documentType,
1259
+ branch: job.branch,
1260
+ scope: job.scope,
1261
+ sourceRemote
1262
+ }]);
1263
+ stores.documentMetaCache.putDocumentMeta(documentId, job.branch, {
1264
+ state: document.state.document,
1265
+ documentType: document.header.documentType,
1266
+ protocolVersions: document.header.protocolVersions,
1267
+ documentScopeRevision: operation.index + 1
1268
+ });
1269
+ return buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);
1270
+ }
1271
+ async executeUpgrade(write, executing) {
1272
+ const { action, skip, sourceRemote } = write;
1273
+ const { job, startTime, indexTxn, stores, signal } = executing;
1274
+ const input = action.input;
1275
+ if (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error("UPGRADE_DOCUMENT action requires a documentId in input"), startTime);
1276
+ const documentId = input.documentId;
1277
+ const fromVersion = input.fromVersion;
1278
+ const toVersion = input.toVersion;
1279
+ let document;
1280
+ try {
1281
+ document = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);
1282
+ } catch (error) {
1283
+ return buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);
1284
+ }
1285
+ const documentState = document.state.document;
1286
+ if (documentState.isDeleted && !this.alreadyEvaluated(executing)) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);
1287
+ if (fromVersion === toVersion && fromVersion > 0) return {
1288
+ job,
1289
+ success: true,
1290
+ operations: [],
1291
+ operationsWithContext: [],
1292
+ duration: Date.now() - startTime
1293
+ };
1294
+ const arrivesDecided = executing.replayingAcceptedHistory || executing.evaluatedByPosition;
1295
+ if (fromVersion > 0 && !arrivesDecided) {
1296
+ const stampedVersion = normalizeDocumentModelVersion(documentState.version);
1297
+ if (fromVersion !== stampedVersion) return buildErrorResult(job, new UpgradePreconditionFailedError(documentId, `fromVersion ${fromVersion} does not match the document's version ${stampedVersion}`), startTime);
1298
+ if (input.revision !== void 0) {
1299
+ let actualRevisions;
1300
+ try {
1301
+ actualRevisions = (await stores.operationStore.getRevisions(documentId, job.branch, signal)).revision;
1302
+ } catch (error) {
1303
+ return buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch revisions for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);
1304
+ }
1305
+ const revisionScopes = /* @__PURE__ */ new Set([...Object.keys(input.revision), ...Object.keys(actualRevisions)]);
1306
+ for (const revisionScope of revisionScopes) {
1307
+ const snapshot = input.revision[revisionScope] ?? 0;
1308
+ const actual = actualRevisions[revisionScope] ?? 0;
1309
+ if (snapshot !== actual) return buildErrorResult(job, new UpgradePreconditionFailedError(documentId, `revision snapshot for scope "${revisionScope}" is ${snapshot} but the document is at ${actual}`), startTime);
1310
+ }
1311
+ }
1312
+ }
1313
+ let upgradePath;
1314
+ if (fromVersion > 0 && fromVersion < toVersion) try {
1315
+ upgradePath = this.registry.computeUpgradePath(document.header.documentType, fromVersion, toVersion);
1316
+ } catch (error) {
1317
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
1318
+ }
1319
+ const otherScopes = Object.keys(document.state).filter((scope) => scope !== job.scope);
1320
+ if (fromVersion > 0) for (const scope of otherScopes) {
1321
+ let scopedDocument;
1322
+ try {
1323
+ scopedDocument = await stores.writeCache.getState(documentId, scope, job.branch, void 0, signal);
1324
+ } catch (error) {
1325
+ return buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch ${scope} scope for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);
1326
+ }
1327
+ document = {
1328
+ ...document,
1329
+ state: {
1330
+ ...document.state,
1331
+ [scope]: scopedDocument.state[scope]
1332
+ }
1333
+ };
1334
+ }
1335
+ const nextIndex = getNextIndexForScope(document, job.scope);
1336
+ try {
1337
+ document = applyUpgradeDocumentAction$1(document, action, upgradePath);
1338
+ } catch (error) {
1339
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
1340
+ }
1341
+ let operation = createOperation(action, nextIndex, skip, {
1342
+ documentId,
1343
+ scope: job.scope,
1344
+ branch: job.branch
1345
+ });
1346
+ const resultingStateObj = {
1347
+ ...document.state,
1348
+ header: document.header
1349
+ };
1350
+ if (fromVersion > 0) resultingStateObj.__migrated = true;
1351
+ const resultingState = JSON.stringify(resultingStateObj);
1352
+ const writeResult = await this.writeOperationToStore({
1353
+ documentId,
1354
+ documentType: document.header.documentType,
1355
+ scope: job.scope,
1356
+ branch: job.branch
1357
+ }, operation, executing);
1358
+ if (!Array.isArray(writeResult)) return writeResult;
1359
+ operation = writeResult[0];
1360
+ updateDocumentRevision(document, job.scope, operation.index);
1361
+ document.operations = {
1362
+ ...document.operations,
1363
+ [job.scope]: [...document.operations[job.scope] ?? [], operation]
1364
+ };
1365
+ executing.touchedStreams.add(documentId, job.scope, job.branch);
1366
+ stores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document, "head");
1367
+ for (const scope of otherScopes) executing.postCommitInvalidations.push({
1368
+ documentId,
1369
+ scope,
1370
+ branch: job.branch
1371
+ });
1372
+ indexTxn.write([{
1373
+ ...operation,
1374
+ documentId,
1375
+ documentType: document.header.documentType,
1376
+ branch: job.branch,
1377
+ scope: job.scope,
1378
+ sourceRemote
1379
+ }]);
1380
+ stores.documentMetaCache.putDocumentMeta(documentId, job.branch, {
1381
+ state: document.state.document,
1382
+ documentType: document.header.documentType,
1383
+ protocolVersions: document.header.protocolVersions,
1384
+ documentScopeRevision: operation.index + 1
1385
+ });
1386
+ return buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);
1387
+ }
1388
+ /** A submitted write naming a purged target was refused at job start. */
1389
+ async isTargetPurged(write, executing) {
1390
+ const target = relationshipTarget(write.action);
1391
+ if (target === void 0 || !executing.purgeFence) return false;
1392
+ return executing.purgeFence.isPurged(target);
1393
+ }
1394
+ async executeAddRelationship(write, executing) {
1395
+ let targetPurged;
1396
+ try {
1397
+ targetPurged = await this.isTargetPurged(write, executing);
1398
+ } catch (error) {
1399
+ return buildErrorResult(executing.job, error instanceof Error ? error : new Error(String(error)), executing.startTime);
1400
+ }
1401
+ return this.withRelationshipAction("ADD_RELATIONSHIP", write, executing, (input) => input.sourceId === input.targetId ? /* @__PURE__ */ new Error("ADD_RELATIONSHIP: sourceId and targetId cannot be the same (self-relationships not allowed)") : null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {
1402
+ if (!targetPurged && this.driveContainerTypes.has(sourceDoc.header.documentType)) {
1403
+ const collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;
1404
+ txn.addToCollection(collectionId, input.targetId);
1405
+ s.collectionMembershipCache.invalidate(input.targetId);
1406
+ }
1407
+ });
1408
+ }
1409
+ async executeRemoveRelationship(write, executing) {
1410
+ let targetPurged;
1411
+ try {
1412
+ targetPurged = await this.isTargetPurged(write, executing);
1413
+ } catch (error) {
1414
+ return buildErrorResult(executing.job, error instanceof Error ? error : new Error(String(error)), executing.startTime);
1415
+ }
1416
+ return this.withRelationshipAction("REMOVE_RELATIONSHIP", write, executing, null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {
1417
+ if (!targetPurged && this.driveContainerTypes.has(sourceDoc.header.documentType)) {
1418
+ const collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;
1419
+ txn.removeFromCollection(collectionId, input.targetId);
1420
+ s.collectionMembershipCache.invalidate(input.targetId);
1421
+ }
1422
+ });
1423
+ }
1424
+ executeUpdateRelationship(write, executing) {
1425
+ return this.withRelationshipAction("UPDATE_RELATIONSHIP", write, executing, null, null);
1426
+ }
1427
+ async withRelationshipAction(actionTypeName, write, executing, preValidate, postWrite) {
1428
+ const { action, skip, sourceRemote } = write;
1429
+ const { job, startTime, indexTxn, stores, signal } = executing;
1430
+ if (job.scope !== "document") return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} must be in "document" scope, got "${job.scope}"`), startTime);
1431
+ const input = action.input;
1432
+ if (!input.sourceId || !input.targetId || !input.relationshipType) return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} action requires sourceId, targetId, and relationshipType in input`), startTime);
1433
+ if (preValidate !== null) {
1434
+ const validationError = preValidate(input);
1435
+ if (validationError !== null) return buildErrorResult(job, validationError, startTime);
1436
+ }
1437
+ let sourceDoc;
1438
+ try {
1439
+ sourceDoc = await stores.writeCache.getState(input.sourceId, "document", job.branch, void 0, signal);
1440
+ } catch (error) {
1441
+ if (DocumentPurgedError.isError(error)) return buildErrorResult(job, error, startTime);
1442
+ if (DocumentNotFoundError.isError(error)) return buildErrorResult(job, new DocumentNotFoundError(input.sourceId, `${actionTypeName}: source document ${input.sourceId} not found`), startTime);
1443
+ return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName}: source document ${input.sourceId} not found: ${error instanceof Error ? error.message : String(error)}`), startTime);
1444
+ }
1445
+ const nextIndex = getNextIndexForScope(sourceDoc, job.scope);
1446
+ let operation = createOperation(action, nextIndex, skip, {
1447
+ documentId: input.sourceId,
1448
+ scope: job.scope,
1449
+ branch: job.branch
1450
+ });
1451
+ const writeResult = await this.writeOperationToStore({
1452
+ documentId: input.sourceId,
1453
+ documentType: sourceDoc.header.documentType,
1454
+ scope: job.scope,
1455
+ branch: job.branch
1456
+ }, operation, executing);
1457
+ if (!Array.isArray(writeResult)) return writeResult;
1458
+ operation = writeResult[0];
1459
+ sourceDoc.header.lastModifiedAtUtcIso = operation.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString();
1460
+ updateDocumentRevision(sourceDoc, job.scope, operation.index);
1461
+ sourceDoc.operations = {
1462
+ ...sourceDoc.operations,
1463
+ [job.scope]: [...sourceDoc.operations[job.scope] ?? [], operation]
1464
+ };
1465
+ const scopeState = sourceDoc.state[job.scope];
1466
+ const resultingStateObj = {
1467
+ header: structuredClone(sourceDoc.header),
1468
+ [job.scope]: scopeState === void 0 ? {} : structuredClone(scopeState)
1469
+ };
1470
+ const resultingState = JSON.stringify(resultingStateObj);
1471
+ executing.touchedStreams.add(input.sourceId, job.scope, job.branch);
1472
+ executing.touchedStreams.add(input.targetId, job.scope, job.branch);
1473
+ stores.writeCache.putState(input.sourceId, job.scope, job.branch, operation.index, sourceDoc, "head");
1474
+ indexTxn.write([{
1475
+ ...operation,
1476
+ documentId: input.sourceId,
1477
+ documentType: sourceDoc.header.documentType,
1478
+ branch: job.branch,
1479
+ scope: job.scope,
1480
+ sourceRemote
1481
+ }]);
1482
+ if (postWrite !== null) postWrite({
1483
+ indexTxn,
1484
+ stores,
1485
+ sourceDoc,
1486
+ input,
1487
+ job
1488
+ });
1489
+ stores.documentMetaCache.putDocumentMeta(input.sourceId, job.branch, {
1490
+ state: sourceDoc.state.document,
1491
+ documentType: sourceDoc.header.documentType,
1492
+ protocolVersions: sourceDoc.header.protocolVersions,
1493
+ documentScopeRevision: operation.index + 1
1494
+ });
1495
+ return buildSuccessResult(job, operation, input.sourceId, sourceDoc.header.documentType, resultingState, startTime);
1496
+ }
1497
+ async writeOperationToStore(target, operation, executing) {
1498
+ const { documentId, documentType, scope, branch } = target;
1499
+ const { job, startTime, stores, signal } = executing;
1500
+ executing.touchedStreams.add(documentId, scope, branch);
1501
+ let storedOperations;
1502
+ try {
1503
+ storedOperations = await stores.operationStore.apply(documentId, documentType, scope, branch, operation.index, (txn) => {
1504
+ txn.addOperations(operation);
1505
+ }, signal);
1506
+ } catch (error) {
1507
+ this.logger.error("Failed to write operation to IOperationStore (@documentId @scope @branch): @Operation @Error", documentId, scope, branch, operation, error);
1508
+ stores.writeCache.invalidate(documentId, scope, branch);
1509
+ if (AppendConditionFailedError.isError(error)) for (const stream of error.condition.streams) stores.writeCache.invalidate(stream.documentId, stream.scope, stream.branch);
1510
+ return {
1511
+ job,
1512
+ success: false,
1513
+ error: error instanceof Error ? error : /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${String(error)}`),
1514
+ duration: Date.now() - startTime
1515
+ };
1516
+ }
1517
+ return storedOperations;
1518
+ }
1519
+ };
1520
+ //#endregion
1521
+ //#region src/signer/passthrough-signer.ts
1522
+ /**
1523
+ * A no-op signer that returns empty values for all methods.
1524
+ * Used when signing is not required.
1525
+ */
1526
+ var PassthroughSigner = class {
1527
+ publicKey = {};
1528
+ sign() {
1529
+ return Promise.resolve(/* @__PURE__ */ new Uint8Array(0));
1530
+ }
1531
+ verify() {
1532
+ return Promise.resolve();
1533
+ }
1534
+ signAction() {
1535
+ return Promise.resolve([
1536
+ "",
1537
+ "",
1538
+ "",
1539
+ "",
1540
+ ""
1541
+ ]);
1542
+ }
1543
+ };
1544
+ //#endregion
1545
+ //#region src/signer/trust-policy.ts
1546
+ /**
1547
+ * The policy admission asks: the reactor's own key signing as its own user is
1548
+ * accepted, then the host's policy decides, else the default does. `own` is
1549
+ * read on every ask, since its user changes on login.
1550
+ */
1551
+ function admissionTrustPolicy(own, authEnforcement, policy) {
1552
+ return { authorizeSigner(signer, key, documentId) {
1553
+ const identity = actionSignerIdentity(own);
1554
+ if (identity.app.key !== "" && key === identity.app.key) {
1555
+ if (sameUser(actionSignerIdentity(signer).user, identity.user)) return Promise.resolve(true);
1556
+ }
1557
+ if (policy) return policy.authorizeSigner(signer, key, documentId);
1558
+ return Promise.resolve(!authEnforcement);
1559
+ } };
1560
+ }
1561
+ function sameUser(a, b) {
1562
+ return a.address.toLowerCase() === b.address.toLowerCase() && a.networkId === b.networkId && a.chainId === b.chainId;
1563
+ }
1564
+ //#endregion
1565
+ //#region src/signer/did-key.ts
1566
+ const DID_KEY_PREFIX = "did:key:z";
1567
+ const P256_MULTICODEC = [128, 36];
1568
+ const MAX_CACHED_KEYS = 1024;
1569
+ const P = BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff");
1570
+ const A = BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc");
1571
+ const B = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");
1572
+ /** A did:key that is not a compressed P-256 public key. */
1573
+ var MalformedDidKeyError = class extends Error {
1574
+ constructor(did, detail) {
1575
+ super(`Malformed did:key ${did}: ${detail}`);
1576
+ this.name = "MalformedDidKeyError";
1577
+ }
1578
+ };
1579
+ const keyCache = /* @__PURE__ */ new Map();
1580
+ /** Cached per process: decompressing the point costs a BigInt modPow. */
1581
+ async function importDidKey(did) {
1582
+ const cached = keyCache.get(did);
1583
+ if (cached) {
1584
+ keyCache.delete(did);
1585
+ keyCache.set(did, cached);
1586
+ return cached;
1587
+ }
1588
+ const raw = decompressP256(compressedPointFromDid(did), did);
1589
+ const key = await crypto.subtle.importKey("raw", raw.buffer, {
1590
+ name: "ECDSA",
1591
+ namedCurve: "P-256"
1592
+ }, false, ["verify"]);
1593
+ keyCache.set(did, key);
1594
+ if (keyCache.size > MAX_CACHED_KEYS) {
1595
+ const oldest = keyCache.keys().next().value;
1596
+ if (oldest !== void 0) keyCache.delete(oldest);
1597
+ }
1598
+ return key;
1599
+ }
1600
+ function compressedPointFromDid(did) {
1601
+ if (!did.startsWith(DID_KEY_PREFIX)) throw new MalformedDidKeyError(did, "not a base58btc did:key");
1602
+ const decoded = base58Decode(did.slice(9));
1603
+ if (!decoded || decoded.length !== 35) throw new MalformedDidKeyError(did, "not a compressed P-256 key");
1604
+ if (decoded[0] !== P256_MULTICODEC[0] || decoded[1] !== P256_MULTICODEC[1]) throw new MalformedDidKeyError(did, "not a P-256 multicodec");
1605
+ return decoded.subarray(2);
1606
+ }
1607
+ function decompressP256(compressed, did) {
1608
+ const prefix = compressed[0];
1609
+ if (prefix !== 2 && prefix !== 3) throw new MalformedDidKeyError(did, `compression prefix ${prefix}`);
1610
+ let x = BigInt(0);
1611
+ for (let i = 1; i < compressed.length; i++) x = x << BigInt(8) | BigInt(compressed[i]);
1612
+ if (x >= P) throw new MalformedDidKeyError(did, "x outside the field");
1613
+ const ySquared = (modPow(x, BigInt(3), P) + A * x + B) % P;
1614
+ let y = modPow(ySquared, (P + BigInt(1)) / BigInt(4), P);
1615
+ if (y * y % P !== ySquared) throw new MalformedDidKeyError(did, "x is not on the curve");
1616
+ if (y % BigInt(2) === BigInt(0) !== (prefix === 2)) y = P - y;
1617
+ const uncompressed = /* @__PURE__ */ new Uint8Array(65);
1618
+ uncompressed[0] = 4;
1619
+ uncompressed.set(bigIntToBytes(x), 1);
1620
+ uncompressed.set(bigIntToBytes(y), 33);
1621
+ return uncompressed;
1622
+ }
1623
+ function modPow(base, exp, mod) {
1624
+ let result = BigInt(1);
1625
+ let b = base % mod;
1626
+ let e = exp;
1627
+ while (e > BigInt(0)) {
1628
+ if (e & BigInt(1)) result = result * b % mod;
1629
+ e >>= BigInt(1);
1630
+ b = b * b % mod;
1631
+ }
1632
+ return result;
1633
+ }
1634
+ function bigIntToBytes(value) {
1635
+ const bytes = /* @__PURE__ */ new Uint8Array(32);
1636
+ let v = value;
1637
+ for (let i = 31; i >= 0; i--) {
1638
+ bytes[i] = Number(v & BigInt(255));
1639
+ v >>= BigInt(8);
1640
+ }
1641
+ return bytes;
1642
+ }
1643
+ //#endregion
1644
+ //#region src/signer/verify-action-signature.ts
1645
+ const RENOWN_HASH_LENGTH = 44;
1646
+ const SHARED_HASH_LENGTH = 28;
1647
+ const HEX_SIGNATURE = /^(0x)?([0-9a-fA-F]{2})+$/;
1648
+ /**
1649
+ * Integrity only: identity binding and the live-id check sit with the caller.
1650
+ * `operation` is the incoming operation at load admission.
1651
+ */
1652
+ async function verifyActionSignature(action, target, path, operation) {
1653
+ const policy = target.policy ?? "legacy";
1654
+ const refusal = policyRefusal(action, policy);
1655
+ if (refusal) return refusal;
1656
+ const shape = signerShape(action.context?.signer);
1657
+ if (shape.kind === "unsigned") return policy === "v2-required" ? refuse("unsigned", "UNSIGNED_REQUIRED", `action ${action.id} is unsigned but ${target.documentId} requires v2 signatures`) : {
1658
+ ok: true,
1659
+ scheme: "unsigned"
1660
+ };
1661
+ if (shape.kind === "malformed") return refuse("legacy-unknown", "MALFORMED_TUPLE", `action ${action.id} ${shape.reason}`);
1662
+ const { signer, tuple } = shape;
1663
+ const scheme = schemeOf(tuple[2]);
1664
+ if (tuple[1] !== signer.app.key) return refuse(scheme, "KEY_MISMATCH", `action ${action.id} tuple key does not match signer.app.key`);
1665
+ if (scheme !== "v2" && policy === "v2-required") return refuse(scheme, "SCHEME_BELOW_POLICY", `action ${action.id} carries a legacy tuple but ${target.documentId} requires v2 signatures`);
1666
+ if (scheme === "legacy-unknown" && path === "mutation") return refuse(scheme, "MALFORMED_TUPLE", `action ${action.id} carries a hash of unknown length ${tuple[2].length}`);
1667
+ if (scheme === "v2") {
1668
+ const refusal = await checkV2(action, tuple, target, operation);
1669
+ if (refusal) return refusal;
1670
+ } else if (path === "mutation") {
1671
+ if (await legacyHash(scheme, action, target) !== tuple[2]) return refuse(scheme, "HASH_MISMATCH", `action ${action.id} does not match the hash its signature covers`);
1672
+ }
1673
+ return verifyEcdsa(tuple, scheme, action.id);
1674
+ }
1675
+ /** Refusals a document's policy makes before any tuple is read. */
1676
+ function policyRefusal(action, policy) {
1677
+ if (action.type !== "CREATE_DOCUMENT") return;
1678
+ const scheme = schemeOfAction(action);
1679
+ const input = action.input;
1680
+ const documentId = input?.documentId ?? "";
1681
+ if (policy === "legacy") return isDerivedDocumentId(documentId) ? refuse(scheme, "ID_MISMATCH", `action ${action.id}: a legacy document cannot take the content-addressed id ${documentId}`) : void 0;
1682
+ const expected = derivedCreateId(input);
1683
+ if (expected === documentId) return;
1684
+ return refuse(scheme, "ID_MISMATCH", expected === void 0 ? `action ${action.id} creates v2-required ${documentId} without the header params its id is derived from` : `action ${action.id} creates v2-required ${documentId}, but its header params derive ${expected}`);
1685
+ }
1686
+ function derivedCreateId(input) {
1687
+ if (!input?.signing || !input.protocolVersions) return;
1688
+ try {
1689
+ return deriveDocumentId({
1690
+ documentType: input.model,
1691
+ createdAtUtcIso: input.signing.createdAtUtcIso,
1692
+ nonce: input.signing.nonce,
1693
+ protocolVersions: input.protocolVersions
1694
+ });
1695
+ } catch {
1696
+ return;
1697
+ }
1698
+ }
1699
+ function schemeOfAction(action) {
1700
+ const shape = signerShape(action.context?.signer);
1701
+ if (shape.kind === "unsigned") return "unsigned";
1702
+ return shape.kind === "signed" ? schemeOf(shape.tuple[2]) : "legacy-unknown";
1703
+ }
1704
+ /** Peers send arbitrary JSON, so nothing past `context` is assumed. */
1705
+ function signerShape(value) {
1706
+ if (value === void 0 || value === null) return { kind: "unsigned" };
1707
+ if (!isRecord(value)) return {
1708
+ kind: "malformed",
1709
+ reason: "has a signer that is not an object"
1710
+ };
1711
+ const { app, user, signatures } = value;
1712
+ if (app !== void 0 && app !== null && !isRecord(app)) return {
1713
+ kind: "malformed",
1714
+ reason: "has a signer.app that is not an object"
1715
+ };
1716
+ const key = isRecord(app) ? app.key : void 0;
1717
+ if (key !== void 0 && key !== null && typeof key !== "string") return {
1718
+ kind: "malformed",
1719
+ reason: "has a signer.app.key that is not a string"
1720
+ };
1721
+ if (!key) return { kind: "unsigned" };
1722
+ if (!isRecord(user) || typeof user.address !== "string") return {
1723
+ kind: "malformed",
1724
+ reason: "has a signer without a user address"
1725
+ };
1726
+ if (!Array.isArray(signatures)) return {
1727
+ kind: "malformed",
1728
+ reason: "has a signer whose signatures are not a list"
1729
+ };
1730
+ const tuple = signatures.at(-1);
1731
+ if (!isTuple(tuple)) return {
1732
+ kind: "malformed",
1733
+ reason: signatures.length === 0 ? "has a signer but no signatures" : "carries a malformed signature tuple"
1734
+ };
1735
+ return {
1736
+ kind: "signed",
1737
+ signer: value,
1738
+ tuple
1739
+ };
1740
+ }
1741
+ function isRecord(value) {
1742
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1743
+ }
1744
+ async function checkV2(action, tuple, target, operation) {
1745
+ const problem = v2TupleProblem(tuple);
1746
+ if (problem) return refuse("v2", "MALFORMED_TUPLE", `action ${action.id}: ${problem}`);
1747
+ if (operation && !sameInstant(operation.timestampUtcMs, action.timestampUtcMs)) return refuse("v2", "TIMESTAMP_MISMATCH", `action ${action.id} is stamped ${action.timestampUtcMs} but its operation ${operation.timestampUtcMs}`);
1748
+ let expected;
1749
+ try {
1750
+ expected = await hashActionV2(action, target, action.context.signer);
1751
+ } catch (error) {
1752
+ return refuse("v2", "HASH_MISMATCH", `action ${action.id} has no v2 hash: ${error instanceof Error ? error.message : String(error)}`);
1753
+ }
1754
+ if (expected !== tuple[2]) return refuse("v2", "HASH_MISMATCH", `action ${action.id} does not match the hash its signature covers`);
1755
+ }
1756
+ function sameInstant(a, b) {
1757
+ const left = Date.parse(a);
1758
+ return !Number.isNaN(left) && left === Date.parse(b);
1759
+ }
1760
+ function schemeOf(hash) {
1761
+ if (isV2ActionHash(hash)) return "v2";
1762
+ if (hash.length === RENOWN_HASH_LENGTH) return "legacy-renown";
1763
+ if (hash.length === SHARED_HASH_LENGTH) return "legacy-shared";
1764
+ return "legacy-unknown";
1765
+ }
1766
+ async function legacyHash(scheme, action, target) {
1767
+ if (scheme === "legacy-renown") {
1768
+ const payload = [
1769
+ action.scope,
1770
+ action.type,
1771
+ JSON.stringify(action.input)
1772
+ ].join("");
1773
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(payload));
1774
+ return bytesToBase64(new Uint8Array(digest));
1775
+ }
1776
+ const signer = action.context.signer;
1777
+ return buildOperationSignatureParams({
1778
+ documentId: target.documentId,
1779
+ signer,
1780
+ action,
1781
+ previousStateHash: ""
1782
+ })[2];
1783
+ }
1784
+ async function verifyEcdsa(tuple, scheme, actionId) {
1785
+ const [timestamp, key, hash, prevStateHash, signatureHex] = tuple;
1786
+ if (!HEX_SIGNATURE.test(signatureHex)) return refuse(scheme, "MALFORMED_TUPLE", `action ${actionId} signature is not hex`);
1787
+ let cryptoKey;
1788
+ try {
1789
+ cryptoKey = await importDidKey(key);
1790
+ } catch (error) {
1791
+ return refuse(scheme, "MALFORMED_TUPLE", `action ${actionId}: ${error instanceof Error ? error.message : String(error)}`);
1792
+ }
1793
+ const message = buildOperationSignatureMessage([
1794
+ timestamp,
1795
+ key,
1796
+ hash,
1797
+ prevStateHash
1798
+ ]);
1799
+ let valid;
1800
+ try {
1801
+ valid = await crypto.subtle.verify({
1802
+ name: "ECDSA",
1803
+ hash: "SHA-256"
1804
+ }, cryptoKey, hexToBytes(signatureHex).buffer, message.buffer);
1805
+ } catch {
1806
+ valid = false;
1807
+ }
1808
+ if (!valid) return refuse(scheme, "BAD_SIGNATURE", `action ${actionId} signature does not verify under its key`);
1809
+ return {
1810
+ ok: true,
1811
+ scheme
1812
+ };
1813
+ }
1814
+ function isTuple(value) {
1815
+ return Array.isArray(value) && value.length === 5 && value.every((element) => typeof element === "string");
1816
+ }
1817
+ function refuse(scheme, code, reason) {
1818
+ return {
1819
+ ok: false,
1820
+ scheme,
1821
+ code,
1822
+ reason
1823
+ };
1824
+ }
1825
+ function hexToBytes(hex) {
1826
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
1827
+ const bytes = new Uint8Array(clean.length / 2);
1828
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);
1829
+ return bytes;
1830
+ }
1831
+ function bytesToBase64(bytes) {
1832
+ let binary = "";
1833
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1834
+ return btoa(binary);
1835
+ }
1836
+ //#endregion
1837
+ //#region src/executor/synthesized-signing.ts
1838
+ /** Submitted types whose stored action the reducer writes in their place. */
1839
+ const SYNTHESIZING_TYPES = /* @__PURE__ */ new Set(["UNDO", "REDO"]);
1840
+ /**
1841
+ * The id of the action synthesized from `submittedId`. Derived, so the stored
1842
+ * operation answers for the submitted id at the live-id check.
1843
+ */
1844
+ function synthesizedActionId(submittedId) {
1845
+ return hashBrowser(`synthesized:${submittedId}`, "sha1", "hex").slice(0, 32);
1846
+ }
1847
+ /**
1848
+ * Whether `operation` stores an action the reducer made from `submitted`
1849
+ * rather than `submitted` itself or an operation already in `history`.
1850
+ */
1851
+ function isSynthesized(submitted, operation, history) {
1852
+ if (!SYNTHESIZING_TYPES.has(submitted.type)) return false;
1853
+ const id = operation.action.id;
1854
+ if (!id) return true;
1855
+ if (id === submitted.id) return false;
1856
+ return !history.some((existing) => existing.action.id === id);
1857
+ }
1858
+ /**
1859
+ * Signs the synthesized action of `operation` in place as `signer`, under the
1860
+ * id {@link synthesizedActionId} derives from the submitted one. A REDO's
1861
+ * rebuilt action has no timestamp, so it takes the submitted one; the
1862
+ * operation timestamp is set to the action's, which a peer requires of a v2
1863
+ * tuple.
1864
+ */
1865
+ async function signSynthesized(operation, submitted, target, signer, signal) {
1866
+ const synthesized = operation.action;
1867
+ const id = synthesizedActionId(submitted.id);
1868
+ const timestampUtcMs = operation.timestampUtcMs || synthesized.timestampUtcMs || submitted.timestampUtcMs;
1869
+ const action = {
1870
+ id,
1871
+ timestampUtcMs,
1872
+ type: synthesized.type,
1873
+ input: synthesized.input,
1874
+ scope: synthesized.scope
1875
+ };
1876
+ const signature = await signer.signAction(action, {
1877
+ documentId: target.documentId,
1878
+ branch: target.branch
1879
+ }, signal);
1880
+ operation.action = {
1881
+ ...action,
1882
+ context: { signer: {
1883
+ ...actionSignerIdentity(signer),
1884
+ signatures: [signature]
1885
+ } }
1886
+ };
1887
+ operation.id = deriveOperationId(target.documentId, target.scope, target.branch, id);
1888
+ operation.timestampUtcMs = timestampUtcMs;
1889
+ }
1890
+ //#endregion
1891
+ //#region src/executor/signature-admission.ts
1892
+ const DEFAULT_TRUST_TIMEOUT_MS = 1e4;
1893
+ /** Runs once per write, when this reactor first stores it; never on re-appends. */
1894
+ var SignatureAdmission = class {
1895
+ mode;
1896
+ logger;
1897
+ eventBus;
1898
+ policySource;
1899
+ trustPolicy;
1900
+ trustTimeoutMs;
1901
+ constructor(mode, logger, eventBus, policySource = "meta", trust = {
1902
+ authEnforcement: false,
1903
+ timeoutMs: DEFAULT_TRUST_TIMEOUT_MS
1904
+ }) {
1905
+ this.mode = mode;
1906
+ this.logger = logger;
1907
+ this.eventBus = eventBus;
1908
+ this.policySource = policySource;
1909
+ this.trustPolicy = admissionTrustPolicy(trust.signer ?? new PassthroughSigner(), trust.authEnforcement, trust.policy);
1910
+ this.trustTimeoutMs = trust.timeoutMs;
1911
+ }
1912
+ /** The first refusal of a mutation's submitted actions, when enforcing. */
1913
+ async admitMutation(job, stores, signal) {
1914
+ const { operationStore } = stores;
1915
+ const candidates = job.actions.map((action) => candidate(action, mutationStream(action, job)));
1916
+ const live = await this.liveOperationIds(candidates, operationStore, signal);
1917
+ const committed = await this.storedAsSubmitted(candidates, live, isRetry(job), operationStore, signal);
1918
+ await resolvePolicies(candidates, job.actions, (documentId, branch) => storedPolicy(stores, this.policySource, documentId, branch, signal));
1919
+ const submitted = /* @__PURE__ */ new Set();
1920
+ for (const entry of candidates) {
1921
+ if (committed.has(entry)) continue;
1922
+ const verdict = await this.verdict(entry, live, submitted, "mutation", signal);
1923
+ submitted.add(entry.opId);
1924
+ if (verdict.ok) continue;
1925
+ const refusal = this.record(job, entry, verdict, "mutation");
1926
+ if (refusal) return {
1927
+ kind: "refused",
1928
+ error: refusal
1929
+ };
1930
+ }
1931
+ return {
1932
+ kind: "admitted",
1933
+ committed: [...committed.values()]
1934
+ };
1935
+ }
1936
+ /** The incoming operations a load drops, empty unless enforcing. */
1937
+ async admitLoad(job, operations, stores, signal) {
1938
+ const { operationStore } = stores;
1939
+ const stream = {
1940
+ documentId: job.documentId,
1941
+ scope: job.scope,
1942
+ branch: job.branch
1943
+ };
1944
+ const candidates = operations.map((operation) => ({
1945
+ ...candidate(operation.action, stream),
1946
+ operation
1947
+ }));
1948
+ const live = await this.liveOperationIds(candidates, operationStore, signal);
1949
+ const redelivered = await this.redelivered(candidates, live, operationStore, signal);
1950
+ await resolvePolicies(candidates, job.operations.map((operation) => operation.action), (documentId, branch) => storedPolicy(stores, this.policySource, documentId, branch, signal));
1951
+ const dropped = /* @__PURE__ */ new Set();
1952
+ for (let i = 0; i < candidates.length; i++) {
1953
+ const verdict = await this.verdict(candidates[i], live, void 0, "load", signal, redelivered.has(candidates[i]));
1954
+ if (verdict.ok) continue;
1955
+ if (this.record(job, candidates[i], verdict, "load")) dropped.add(operations[i]);
1956
+ }
1957
+ return dropped;
1958
+ }
1959
+ /** A marker is held to v2 and enforced whatever the policy and mode. */
1960
+ async admitMarker(job, marker, signal) {
1961
+ const entry = {
1962
+ ...candidate(marker.action, {
1963
+ documentId: job.documentId,
1964
+ scope: "document",
1965
+ branch: job.branch
1966
+ }),
1967
+ operation: marker,
1968
+ policy: "v2-required"
1969
+ };
1970
+ const verdict = await this.verdict(entry, /* @__PURE__ */ new Set(), void 0, "load", signal);
1971
+ if (verdict.ok) return;
1972
+ return this.record(job, entry, verdict, "load", true);
1973
+ }
1974
+ async verdict(entry, live, submitted, path, signal, known = false) {
1975
+ const verdict = await verifyActionSignature(entry.action, {
1976
+ documentId: entry.stream.documentId,
1977
+ branch: entry.stream.branch,
1978
+ policy: entry.policy
1979
+ }, path, entry.operation);
1980
+ if (!verdict.ok) return verdict;
1981
+ if (!known && (isLive(entry, live) || submitted?.has(entry.opId))) return {
1982
+ ok: false,
1983
+ scheme: verdict.scheme,
1984
+ code: "DUPLICATE_ACTION",
1985
+ reason: `action ${entry.action.id} is already in the stream`
1986
+ };
1987
+ if (verdict.scheme === "unsigned") {
1988
+ const address = entry.action.context?.signer?.user?.address;
1989
+ return address ? {
1990
+ ok: false,
1991
+ scheme: "unsigned",
1992
+ code: "UNSIGNED_IDENTITY",
1993
+ reason: `action ${entry.action.id} is unsigned but claims to act as ${address}`
1994
+ } : verdict;
1995
+ }
1996
+ if (known) return verdict;
1997
+ const signer = entry.action.context.signer;
1998
+ if (!await this.authorize(signer, entry.stream.documentId, signal)) return {
1999
+ ok: false,
2000
+ scheme: verdict.scheme,
2001
+ code: "SIGNER_UNAUTHORIZED",
2002
+ reason: `action ${entry.action.id}: key ${signer.app.key} may not sign as ${signer.user.address}`
2003
+ };
2004
+ return verdict;
2005
+ }
2006
+ /** Throws when the policy does, times out or the job is aborted. */
2007
+ async authorize(signer, documentId, signal) {
2008
+ signal?.throwIfAborted();
2009
+ let timer;
2010
+ let onAbort;
2011
+ const stop = new Promise((_, reject) => {
2012
+ timer = setTimeout(() => {
2013
+ reject(/* @__PURE__ */ new Error(`signature trust policy did not answer for ${signer.app.key} within ${this.trustTimeoutMs}ms`));
2014
+ }, this.trustTimeoutMs);
2015
+ if (signal) {
2016
+ onAbort = () => reject(signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason)));
2017
+ signal.addEventListener("abort", onAbort, { once: true });
2018
+ }
2019
+ });
2020
+ try {
2021
+ return await Promise.race([this.trustPolicy.authorizeSigner(signer, signer.app.key, documentId), stop]);
2022
+ } finally {
2023
+ clearTimeout(timer);
2024
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
2025
+ }
2026
+ }
2027
+ /**
2028
+ * The live candidates stored exactly as submitted and still standing: one
2029
+ * an undo or a reshuffle has since superseded is refused, not re-emitted with
2030
+ * the state it once produced. A synthesized operation
2031
+ * holds another action, so it cannot be compared; only a retry, whose first
2032
+ * attempt this job was, takes it as committed.
2033
+ */
2034
+ async storedAsSubmitted(candidates, live, retry, operationStore, signal) {
2035
+ const committed = /* @__PURE__ */ new Map();
2036
+ const toCompare = [];
2037
+ for (const entry of candidates) if (entry.synthesizedOpId && live.has(entry.synthesizedOpId)) {
2038
+ if (retry) committed.set(entry, committedWrite(entry, entry.synthesizedOpId));
2039
+ } else if (live.has(entry.opId)) toCompare.push(entry);
2040
+ for (const [stream, entries] of byStream(toCompare)) {
2041
+ const stored = await operationStore.getOperationsByIds(stream.documentId, stream.scope, stream.branch, entries.map((entry) => entry.opId), signal);
2042
+ const byId = new Map(stored.map((operation) => [operation.id, operation]));
2043
+ const matching = entries.filter((entry) => {
2044
+ const operation = byId.get(entry.opId);
2045
+ return operation && sameContent(operation.action, entry.action);
2046
+ });
2047
+ if (matching.length === 0) continue;
2048
+ const later = await operationStore.getSince(stream.documentId, stream.scope, stream.branch, Math.min(...matching.map((entry) => byId.get(entry.opId).index)), void 0, void 0, signal);
2049
+ for (const entry of matching) if (!isSuperseded(byId.get(entry.opId), later.results)) committed.set(entry, committedWrite(entry, entry.opId));
2050
+ }
2051
+ return committed;
2052
+ }
2053
+ /**
2054
+ * The load candidates stored exactly as they arrive, timestamp included: a
2055
+ * peer re-sending what this stream holds, not a replay of its action.
2056
+ */
2057
+ async redelivered(candidates, live, operationStore, signal) {
2058
+ const found = /* @__PURE__ */ new Set();
2059
+ const toCompare = candidates.filter((entry) => live.has(entry.opId) && !(entry.synthesizedOpId && live.has(entry.synthesizedOpId)));
2060
+ for (const [stream, entries] of byStream(toCompare)) {
2061
+ const stored = await operationStore.getOperationsByIds(stream.documentId, stream.scope, stream.branch, entries.map((entry) => entry.opId), signal);
2062
+ for (const entry of entries) if (stored.some((operation) => operation.id === entry.opId && Date.parse(operation.timestampUtcMs) === Date.parse(entry.operation?.timestampUtcMs ?? "") && sameContent(operation.action, entry.action))) found.add(entry);
2063
+ }
2064
+ return found;
2065
+ }
2066
+ async liveOperationIds(candidates, operationStore, signal) {
2067
+ const live = /* @__PURE__ */ new Set();
2068
+ for (const [stream, entries] of byStream(candidates)) {
2069
+ const found = await operationStore.findOperationIds(stream.documentId, stream.scope, stream.branch, entries.flatMap((entry) => entry.synthesizedOpId ? [entry.opId, entry.synthesizedOpId] : [entry.opId]), signal);
2070
+ for (const opId of found) live.add(opId);
2071
+ }
2072
+ return live;
2073
+ }
2074
+ /** Logs and counts a refusal; returns the error only when enforcing. */
2075
+ record(job, entry, refusal, path, enforced = this.mode === "enforce") {
2076
+ const event = {
2077
+ jobId: job.id,
2078
+ documentId: entry.stream.documentId,
2079
+ scope: entry.stream.scope,
2080
+ branch: entry.stream.branch,
2081
+ actionId: entry.action.id,
2082
+ code: refusal.code,
2083
+ scheme: refusal.scheme,
2084
+ path,
2085
+ enforced,
2086
+ reason: refusal.reason
2087
+ };
2088
+ this.logger.warn(enforced ? "Signature refused: @Refusal" : "Signature refusal logged, write admitted: @Refusal", event);
2089
+ this.eventBus.emit(ReactorEventTypes.SIGNATURE_REFUSED, event).catch((error) => {
2090
+ this.logger.error("Failed to emit SIGNATURE_REFUSED: @Error", error);
2091
+ });
2092
+ return enforced ? new InvalidSignatureError(entry.stream.documentId, refusal.code, refusal.reason) : void 0;
2093
+ }
2094
+ };
2095
+ /**
2096
+ * A CREATE_DOCUMENT is verified under its own input. Anything else takes the
2097
+ * stored document's policy, or, for a document this job creates, that CREATE's.
2098
+ */
2099
+ async function resolvePolicies(candidates, jobActions, stored) {
2100
+ const resolved = /* @__PURE__ */ new Map();
2101
+ for (const entry of candidates) {
2102
+ if (entry.action.type === "CREATE_DOCUMENT") {
2103
+ entry.policy = createPolicy(entry.action);
2104
+ continue;
2105
+ }
2106
+ const { documentId, branch } = entry.stream;
2107
+ const key = `${documentId}\u0000${branch}`;
2108
+ let policy = resolved.get(key);
2109
+ if (policy === void 0) {
2110
+ policy = await stored(documentId, branch) ?? createdPolicy(jobActions, documentId) ?? "legacy";
2111
+ resolved.set(key, policy);
2112
+ }
2113
+ entry.policy = policy;
2114
+ }
2115
+ }
2116
+ async function storedPolicy(stores, source, documentId, branch, signal) {
2117
+ try {
2118
+ if (source === "write-cache") {
2119
+ const document = await stores.writeCache.getState(documentId, "document", branch, void 0, signal);
2120
+ return signaturePolicyOf(document.header);
2121
+ }
2122
+ const meta = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);
2123
+ return signaturePolicyOf(meta.protocolVersions);
2124
+ } catch (error) {
2125
+ if (DocumentNotFoundError.isError(error)) return;
2126
+ throw error;
2127
+ }
2128
+ }
2129
+ function createdPolicy(actions, documentId) {
2130
+ const create = actions.find((action) => action.type === "CREATE_DOCUMENT" && action.input?.documentId === documentId);
2131
+ return create ? createPolicy(create) : void 0;
2132
+ }
2133
+ function createPolicy(action) {
2134
+ return signaturePolicyOf(action.input);
2135
+ }
2136
+ function candidate(action, stream) {
2137
+ const opId = (actionId) => deriveOperationId(stream.documentId, stream.scope, stream.branch, actionId);
2138
+ return {
2139
+ action,
2140
+ stream,
2141
+ opId: opId(action.id),
2142
+ synthesizedOpId: SYNTHESIZING_TYPES.has(action.type) ? opId(synthesizedActionId(action.id)) : void 0
2143
+ };
2144
+ }
2145
+ function isLive(entry, live) {
2146
+ return live.has(entry.opId) || entry.synthesizedOpId !== void 0 && live.has(entry.synthesizedOpId);
2147
+ }
2148
+ function mutationStream(action, job) {
2149
+ return {
2150
+ ...actionSigningTarget(action, job.documentId, job.branch),
2151
+ scope: job.scope
2152
+ };
2153
+ }
2154
+ function byStream(candidates) {
2155
+ const groups = /* @__PURE__ */ new Map();
2156
+ for (const entry of candidates) {
2157
+ const key = `${entry.stream.documentId}\u0000${entry.stream.scope}\u0000${entry.stream.branch}`;
2158
+ const group = groups.get(key) ?? [entry.stream, []];
2159
+ group[1].push(entry);
2160
+ groups.set(key, group);
2161
+ }
2162
+ return [...groups.values()];
2163
+ }
2164
+ function isRetry(job) {
2165
+ return job.errorHistory.length > 0 || (job.retryCount ?? 0) > 0;
2166
+ }
2167
+ function committedWrite(entry, opId) {
2168
+ return {
2169
+ ...entry.stream,
2170
+ actionId: entry.action.id,
2171
+ opId
2172
+ };
2173
+ }
2174
+ function isSuperseded(operation, later) {
2175
+ return later.some((next) => next.index > operation.index && next.skip > 0 && next.index - next.skip <= operation.index);
2176
+ }
2177
+ function sameContent(stored, submitted) {
2178
+ try {
2179
+ return canonicalJson(stored) === canonicalJson(submitted);
2180
+ } catch {
2181
+ return false;
2182
+ }
2183
+ }
2184
+ //#endregion
2185
+ //#region src/executor/simple-job-executor.ts
2186
+ const MAX_SKIP_THRESHOLD = 1e3;
2187
+ const ISO_TIMESTAMP_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
2188
+ function isValidISOTimestamp(value) {
2189
+ if (!ISO_TIMESTAMP_REGEX.test(value)) return false;
2190
+ return !isNaN(new Date(value).getTime());
2191
+ }
2192
+ /**
2193
+ * Carries a failed job out of the execution scope so its transaction rolls
2194
+ * back. A scope callback that returns commits, whatever result it returns, so
2195
+ * a returned failure would leave the writes the job made before it failed
2196
+ * standing. Never escapes executeJob: the failure goes back to being a
2197
+ * returned JobResult there, which is what the queue, the worker protocol and
2198
+ * every test expect a failed job to look like.
2199
+ */
2200
+ /** The ids of a purge job's request, which a drive purge may precede. */
2201
+ function purgeRequestDocumentIds(job) {
2202
+ const ids = job.meta.purgeRequestDocumentIds;
2203
+ return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
2204
+ }
2205
+ const MARKER_INPUT_KEYS = /* @__PURE__ */ new Set([
2206
+ "documentId",
2207
+ "documentType",
2208
+ "purgedAtUtcIso",
2209
+ "requestId"
2210
+ ]);
2211
+ /** A peer's marker must name this job's id on main and carry nothing else. */
2212
+ function malformedMarker(job) {
2213
+ const action = job.operations.find((operation) => isPurgeMarker(operation))?.action;
2214
+ const input = action?.input;
2215
+ const refuse = (reason) => new InvalidSignatureError(job.documentId, "ID_MISMATCH", `marker ${action?.id ?? "?"} ${reason}`);
2216
+ if (typeof input !== "object" || input === null) return refuse("carries no input");
2217
+ const extra = Object.keys(input).filter((key) => !MARKER_INPUT_KEYS.has(key));
2218
+ if (extra.length > 0) return refuse(`carries unexpected input ${extra.join(", ")}`);
2219
+ for (const key of MARKER_INPUT_KEYS) if (typeof input[key] !== "string" || input[key] === "") return refuse(`input.${key} is not a non-empty string`);
2220
+ const purgedAt = Date.parse(input.purgedAtUtcIso);
2221
+ if (Number.isNaN(purgedAt) || new Date(purgedAt).toISOString() !== input.purgedAtUtcIso) return refuse("input.purgedAtUtcIso is not an ISO timestamp");
2222
+ if (input.documentId !== job.documentId || job.branch !== "main" || action?.scope !== "document") return refuse(`does not purge ${job.documentId} on document/main`);
2223
+ }
2224
+ var JobRollbackSignal = class extends Error {
2225
+ result;
2226
+ constructor(result) {
2227
+ super("job rolled back");
2228
+ this.result = result;
2229
+ this.name = "JobRollbackSignal";
2230
+ }
2231
+ };
2232
+ var SimpleJobExecutor = class {
2233
+ logger;
2234
+ registry;
2235
+ operationStore;
2236
+ eventBus;
2237
+ writeCache;
2238
+ operationIndex;
2239
+ documentMetaCache;
2240
+ collectionMembershipCache;
2241
+ driveContainerTypes;
2242
+ config;
2243
+ featureFlags;
2244
+ decisionModel;
2245
+ signatureAdmission;
2246
+ documentActionHandler;
2247
+ executionScope;
2248
+ signer;
2249
+ /**
2250
+ * `signer` signs the operations the reducer synthesizes; unsigned if omitted.
2251
+ * `trustPolicy` decides which keys may sign as which users at admission.
2252
+ */
2253
+ constructor(logger, registry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, driveContainerTypes, config, executionScope, signer, trustPolicy) {
2254
+ this.logger = logger;
2255
+ this.registry = registry;
2256
+ this.operationStore = operationStore;
2257
+ this.eventBus = eventBus;
2258
+ this.writeCache = writeCache;
2259
+ this.operationIndex = operationIndex;
2260
+ this.documentMetaCache = documentMetaCache;
2261
+ this.collectionMembershipCache = collectionMembershipCache;
2262
+ this.driveContainerTypes = driveContainerTypes;
2263
+ this.signer = signer ?? new PassthroughSigner();
2264
+ this.featureFlags = resolveFeatureFlags(config.featureFlags);
2265
+ this.config = {
2266
+ featureFlags: config.featureFlags ?? {},
2267
+ maxSkipThreshold: config.maxSkipThreshold ?? MAX_SKIP_THRESHOLD,
2268
+ maxConcurrency: config.maxConcurrency ?? 1,
2269
+ jobTimeoutMs: config.jobTimeoutMs ?? 3e4,
2270
+ deferredJobTtlMs: config.deferredJobTtlMs ?? 3e4,
2271
+ retryBaseDelayMs: config.retryBaseDelayMs ?? 100,
2272
+ retryMaxDelayMs: config.retryMaxDelayMs ?? 5e3,
2273
+ yieldDeadlineMs: config.yieldDeadlineMs ?? 50,
2274
+ batchApplies: config.batchApplies ?? true,
2275
+ signatureVerification: config.signatureVerification ?? "enforce",
2276
+ protocolSupport: config.protocolSupport ?? localSupports(PEER_CAPABILITIES, this.featureFlags).protocols,
2277
+ maxPurgeOperations: config.maxPurgeOperations ?? 2e5
2278
+ };
2279
+ this.decisionModel = selectDecisionModel(this.featureFlags, registry);
2280
+ this.signatureAdmission = new SignatureAdmission(this.config.signatureVerification, logger, eventBus, this.featureFlags.documentDecisions ? "write-cache" : "meta", {
2281
+ signer: this.signer,
2282
+ authEnforcement: this.featureFlags.authEnforcement,
2283
+ policy: trustPolicy,
2284
+ timeoutMs: Math.min(DEFAULT_TRUST_TIMEOUT_MS, this.config.jobTimeoutMs / 2)
2285
+ });
2286
+ this.documentActionHandler = new DocumentActionHandler(registry, logger, driveContainerTypes, this.featureFlags, this.decisionModel, this.config.protocolSupport);
2287
+ this.executionScope = executionScope ?? new DefaultExecutionScope(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache);
2288
+ }
2289
+ /**
2290
+ * Execute a single job by applying all its actions through the appropriate reducers.
2291
+ * Actions are processed sequentially in order.
2292
+ *
2293
+ * The whole job runs inside one execution scope, and a scope callback that
2294
+ * returns commits. A failed job must therefore leave the scope by throwing,
2295
+ * or the writes it made before it failed would be durable: JobRollbackSignal
2296
+ * carries the failure out through the transaction and this method turns it
2297
+ * back into the returned JobResult every caller expects. A job either fully
2298
+ * applies or leaves nothing durable behind.
2299
+ *
2300
+ * Durable is the whole of the guarantee. The caches are shared with the
2301
+ * copies the scope hands the job, so a failed job's writes sit in them from
2302
+ * the moment it makes them until the eviction below, and a concurrent read
2303
+ * in that window sees a write that is never going to commit. The window is
2304
+ * not new -- it has always been there for a job that failed by throwing --
2305
+ * but nothing here closes it, and a caller that needs to know a write is
2306
+ * real has the job status to ask.
2307
+ */
2308
+ async executeJob(job, signal) {
2309
+ const startTime = Date.now();
2310
+ const touchedStreams = new TouchedStreams();
2311
+ const postCommitInvalidations = [];
2312
+ const postCommitMembershipInvalidations = [];
2313
+ const postCommitMetaInvalidations = [];
2314
+ let outcome;
2315
+ try {
2316
+ outcome = await this.executionScope.run(async (stores) => {
2317
+ const scoped = await this.executeInScope({
2318
+ job,
2319
+ startTime,
2320
+ stores,
2321
+ signal,
2322
+ touchedStreams,
2323
+ postCommitInvalidations,
2324
+ postCommitMembershipInvalidations,
2325
+ postCommitMetaInvalidations
2326
+ });
2327
+ if (!scoped.result.success) throw new JobRollbackSignal(scoped.result);
2328
+ return scoped;
2329
+ }, signal);
2330
+ } catch (error) {
2331
+ this.evictTouchedStreams(touchedStreams);
2332
+ if (error instanceof JobRollbackSignal) return error.result;
2333
+ throw error;
2334
+ }
2335
+ for (const entry of postCommitInvalidations) this.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);
2336
+ for (const documentId of postCommitMembershipInvalidations) this.collectionMembershipCache.invalidate(documentId);
2337
+ for (const documentId of postCommitMetaInvalidations) this.documentMetaCache.invalidate(documentId);
2338
+ const { pendingEvent } = outcome;
2339
+ if (pendingEvent) this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY, pendingEvent).catch((error) => {
2340
+ this.logger.error("Failed to emit JOB_WRITE_READY event: @Event : @Error", pendingEvent, error);
2341
+ });
2342
+ return outcome.result;
2343
+ }
2344
+ /**
2345
+ * The body of a job, run inside the execution scope's transaction.
2346
+ *
2347
+ * The stores and caches it works through are the copies scoped to that
2348
+ * transaction, so nothing it does is durable until the scope commits. The
2349
+ * write-ready event is handed back rather than emitted, because a job that
2350
+ * has not committed yet has nothing to announce.
2351
+ */
2352
+ async executeInScope(params) {
2353
+ const { job, startTime, stores: scopeStores, signal, touchedStreams, postCommitInvalidations, postCommitMembershipInvalidations } = params;
2354
+ let pendingEvent;
2355
+ if (job.kind === "mutation") {
2356
+ const reserved = job.actions.find((action) => isPurgeMarker(action));
2357
+ if (reserved) return { result: buildErrorResult(job, new ReservedActionError(job.documentId, reserved.type), startTime) };
2358
+ }
2359
+ if (job.kind === "purge" || job.kind === "load" && job.operations.some((op) => isPurgeMarker(op))) return this.executePurge(params);
2360
+ const lockedIds = jobWriteIds(job);
2361
+ const lockFailure = (error) => ({ result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) });
2362
+ try {
2363
+ await scopeStores.documentLocks.shared(lockedIds);
2364
+ } catch (error) {
2365
+ return lockFailure(error);
2366
+ }
2367
+ let purged;
2368
+ try {
2369
+ purged = await scopeStores.documentLocks.purged(lockedIds);
2370
+ } catch (error) {
2371
+ return lockFailure(error);
2372
+ }
2373
+ const purgedRefusal = this.purgedRefusal(job, purged);
2374
+ if (purgedRefusal) return { result: buildErrorResult(job, purgedRefusal, startTime) };
2375
+ const purgeFence = new PurgeFence(scopeStores.documentLocks, new Set(lockedIds), purged);
2376
+ const stores = {
2377
+ ...scopeStores,
2378
+ writeCache: new FencedWriteCache(scopeStores.writeCache, purgeFence, (documentId) => {
2379
+ scopeStores.writeCache.invalidate(documentId);
2380
+ scopeStores.documentMetaCache.invalidate(documentId);
2381
+ })
2382
+ };
2383
+ const unsupported = await this.unsupportedStoredProtocol(job, stores, signal);
2384
+ if (unsupported) return { result: buildErrorResult(job, unsupported, startTime) };
2385
+ const indexTxn = stores.operationIndex.start();
2386
+ if (job.kind === "load") {
2387
+ const loadResult = await this.executeLoadJob({
2388
+ job,
2389
+ startTime,
2390
+ indexTxn,
2391
+ stores,
2392
+ signal,
2393
+ replayingAcceptedHistory: true,
2394
+ evaluatedByPosition: false,
2395
+ postCommitInvalidations,
2396
+ postCommitMembershipInvalidations,
2397
+ touchedStreams,
2398
+ purgeFence
2399
+ });
2400
+ if (loadResult.success && loadResult.operationsWithContext) {
2401
+ const ordinals = await stores.operationIndex.commit(indexTxn, signal);
2402
+ postCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());
2403
+ for (let i = 0; i < loadResult.operationsWithContext.length; i++) loadResult.operationsWithContext[i].context.ordinal = ordinals[i];
2404
+ const collectionMemberships = loadResult.operationsWithContext.length > 0 ? await this.getCollectionMembershipsForOperations(loadResult.operationsWithContext, stores) : {};
2405
+ pendingEvent = {
2406
+ jobId: job.id,
2407
+ operations: loadResult.operationsWithContext,
2408
+ jobMeta: job.meta,
2409
+ collectionMemberships
2410
+ };
2411
+ }
2412
+ return {
2413
+ result: loadResult,
2414
+ pendingEvent
2415
+ };
2416
+ }
2417
+ if (job.kind === "reevaluation") {
2418
+ const reevalResult = await this.executeReevaluationJob({
2419
+ job,
2420
+ startTime,
2421
+ indexTxn,
2422
+ stores,
2423
+ signal,
2424
+ replayingAcceptedHistory: false,
2425
+ evaluatedByPosition: false,
2426
+ postCommitInvalidations,
2427
+ postCommitMembershipInvalidations,
2428
+ touchedStreams,
2429
+ purgeFence
2430
+ });
2431
+ if (reevalResult.success && reevalResult.operationsWithContext) {
2432
+ const ordinals = await stores.operationIndex.commit(indexTxn, signal);
2433
+ postCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());
2434
+ for (let i = 0; i < reevalResult.operationsWithContext.length; i++) reevalResult.operationsWithContext[i].context.ordinal = ordinals[i];
2435
+ if (reevalResult.operationsWithContext.length > 0) {
2436
+ const collectionMemberships = await this.getCollectionMembershipsForOperations(reevalResult.operationsWithContext, stores);
2437
+ pendingEvent = {
2438
+ jobId: job.id,
2439
+ operations: reevalResult.operationsWithContext,
2440
+ jobMeta: job.meta,
2441
+ collectionMemberships
2442
+ };
2443
+ }
2444
+ }
2445
+ return {
2446
+ result: reevalResult,
2447
+ pendingEvent
2448
+ };
2449
+ }
2450
+ let admission;
2451
+ try {
2452
+ admission = await this.signatureAdmission.admitMutation(job, stores, signal);
2453
+ } catch (error) {
2454
+ return { result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) };
2455
+ }
2456
+ if (admission.kind === "refused") return { result: buildErrorResult(job, admission.error, startTime) };
2457
+ let committed;
2458
+ try {
2459
+ committed = await this.reloadCommitted(admission.committed, stores, signal);
2460
+ } catch (error) {
2461
+ return { result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) };
2462
+ }
2463
+ const committedIds = new Set(admission.committed.map((write) => write.actionId));
2464
+ const fresh = committedIds.size === 0 ? job : {
2465
+ ...job,
2466
+ actions: job.actions.filter((action) => !committedIds.has(action.id))
2467
+ };
2468
+ if (fresh.actions.length === 0) return this.committedOutcome(job, committed, [], [], stores, startTime);
2469
+ const positioned = await this.positionByTimestamp(fresh, stores, signal);
2470
+ if (positioned.error) return { result: buildErrorResult(job, positioned.error, startTime) };
2471
+ const executing = {
2472
+ job: fresh,
2473
+ startTime,
2474
+ indexTxn,
2475
+ stores,
2476
+ signal,
2477
+ replayingAcceptedHistory: false,
2478
+ evaluatedByPosition: positioned.evaluatedByPosition,
2479
+ postCommitInvalidations,
2480
+ postCommitMembershipInvalidations,
2481
+ touchedStreams,
2482
+ purgeFence
2483
+ };
2484
+ const actionResult = await this.processActions(positioned.writes, executing);
2485
+ if (!actionResult.success) return { result: {
2486
+ job,
2487
+ success: false,
2488
+ error: actionResult.error,
2489
+ duration: Date.now() - startTime
2490
+ } };
2491
+ const reevaluationError = await this.reevaluateIfCriteriaMet({
2492
+ scope: job.scope,
2493
+ operations: actionResult.generatedOperations
2494
+ }, executing);
2495
+ if (reevaluationError) return { result: {
2496
+ job,
2497
+ success: false,
2498
+ error: reevaluationError,
2499
+ duration: Date.now() - startTime
2500
+ } };
2501
+ const ordinals = await stores.operationIndex.commit(indexTxn, signal);
2502
+ postCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());
2503
+ for (let i = 0; i < actionResult.operationsWithContext.length; i++) actionResult.operationsWithContext[i].context.ordinal = ordinals[i];
2504
+ return this.committedOutcome(job, committed, actionResult.operationsWithContext, actionResult.generatedOperations, stores, startTime);
2505
+ }
2506
+ /** A load names only its own id purged; a foreign one is ID_MISMATCH. */
2507
+ purgedRefusal(job, purged) {
2508
+ if (purged.size === 0) return;
2509
+ if (purged.has(job.documentId)) return new DocumentPurgedError(job.documentId);
2510
+ const actions = [...job.actions, ...job.operations.map((operation) => operation.action)];
2511
+ for (const action of actions) {
2512
+ if (!DOCUMENT_SCOPE_ACTIONS.has(action.type)) continue;
2513
+ const target = targetDocumentId(action, job.documentId);
2514
+ if (!purged.has(target)) continue;
2515
+ if (job.kind === "mutation") return new DocumentPurgedError(target);
2516
+ return new InvalidSignatureError(job.documentId, "ID_MISMATCH", `${action.type} ${action.id} in ${job.documentId} writes purged ${target}`);
2517
+ }
2518
+ if (job.kind !== "mutation") return;
2519
+ for (const action of job.actions) {
2520
+ const target = relationshipTarget(action);
2521
+ if (action.type === "ADD_RELATIONSHIP" && target !== void 0 && purged.has(target)) return new DocumentPurgedError(target, `${action.type} target ${target} was purged`);
2522
+ if (action.scope !== "auth") continue;
2523
+ const group = mentionedGroupIds(action).find((id) => purged.has(id));
2524
+ if (group !== void 0) return new DocumentPurgedError(group, `${action.type} names purged group ${group}`);
2525
+ }
2526
+ }
2527
+ /** A purge job or a marker load: the exclusive lock is the job's only lock. */
2528
+ async executePurge(params) {
2529
+ const { job, startTime, stores } = params;
2530
+ const fail = (error) => ({ result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) });
2531
+ if (job.kind === "load") {
2532
+ const malformed = malformedMarker(job);
2533
+ if (malformed) return fail(malformed);
2534
+ }
2535
+ const purger = stores.purger;
2536
+ if (!purger) return fail(/* @__PURE__ */ new Error(`Purge of ${job.documentId} needs a transactional scope`));
2537
+ try {
2538
+ await stores.documentLocks.exclusive(job.documentId);
2539
+ } catch (error) {
2540
+ return fail(error);
2541
+ }
2542
+ let alreadyPurged;
2543
+ try {
2544
+ alreadyPurged = (await stores.documentLocks.purged([job.documentId])).has(job.documentId);
2545
+ } catch (error) {
2546
+ return fail(error);
2547
+ }
2548
+ if (alreadyPurged) return {
2549
+ result: {
2550
+ job,
2551
+ success: true,
2552
+ operations: [],
2553
+ operationsWithContext: [],
2554
+ duration: Date.now() - startTime
2555
+ },
2556
+ pendingEvent: {
2557
+ jobId: job.id,
2558
+ operations: [],
2559
+ jobMeta: job.meta,
2560
+ collectionMemberships: {}
2561
+ }
2562
+ };
2563
+ let commit;
2564
+ try {
2565
+ commit = job.kind === "purge" ? await this.preparePurgeJob(params, purger) : await this.preparePurgeLoad(params, purger);
2566
+ } catch (error) {
2567
+ return fail(error);
2568
+ }
2569
+ if (commit instanceof Error) return fail(commit);
2570
+ try {
2571
+ return await this.commitPurge(params, commit);
2572
+ } catch (error) {
2573
+ return fail(error);
2574
+ }
2575
+ }
2576
+ /** Preconditions 1-5, then the marker this host signs. */
2577
+ async preparePurgeJob(params, purger) {
2578
+ const { job, stores, signal } = params;
2579
+ const documentId = job.documentId;
2580
+ if (!job.purge) return /* @__PURE__ */ new Error(`Purge job ${job.id} carries no purge options`);
2581
+ const held = await this.heldStreams(purger, documentId);
2582
+ if (held.branches.length === 0) return new DocumentNotDeletedError(documentId, `Document ${documentId} is not held here`);
2583
+ let documentType;
2584
+ for (const branch of held.branches) {
2585
+ let meta;
2586
+ try {
2587
+ meta = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);
2588
+ } catch (error) {
2589
+ return new DocumentNotDeletedError(documentId, `Document ${documentId} has no readable state on ${branch}: ${error instanceof Error ? error.message : String(error)}`);
2590
+ }
2591
+ if (!meta.state.isDeleted) return new DocumentNotDeletedError(documentId, `Document ${documentId} is not deleted on branch ${branch}`);
2592
+ documentType ??= meta.documentType;
2593
+ }
2594
+ if (documentType === void 0) return new DocumentNotDeletedError(documentId);
2595
+ if (documentType === groupDocumentType) {
2596
+ const referencers = await purger.groupReferencersInHistory(documentId);
2597
+ if (referencers.length > 0) return new GroupInUseError(documentId, referencers);
2598
+ }
2599
+ let survivors = [];
2600
+ if (this.driveContainerTypes.has(documentType)) {
2601
+ const requested = new Set(purgeRequestDocumentIds(job));
2602
+ const members = await this.driveMembers(purger, stores, documentId, held.branches);
2603
+ const blocking = members.required.filter((id) => !requested.has(id));
2604
+ if (blocking.length > 0) return new DocumentNotDeletedError(documentId, `Drive ${documentId} cannot be purged: ${blocking.join(", ")} neither purged nor in the request`);
2605
+ survivors = members.survivors;
2606
+ }
2607
+ const operationCount = await purger.operationCount(documentId);
2608
+ if (operationCount > this.config.maxPurgeOperations && !job.purge.allowLarge) return new PurgeTooLargeError(documentId, operationCount, this.config.maxPurgeOperations);
2609
+ return {
2610
+ purger,
2611
+ marker: await this.signMarker(documentId, documentType, job.purge.requestId, signal),
2612
+ documentType,
2613
+ held,
2614
+ sourceRemote: "",
2615
+ collectionIds: [],
2616
+ survivors
2617
+ };
2618
+ }
2619
+ /** A peer's marker, admitted alone; a receiver cannot refuse an erasure. */
2620
+ async preparePurgeLoad(params, purger) {
2621
+ const { job, stores, signal } = params;
2622
+ const documentId = job.documentId;
2623
+ const marker = job.operations.find((operation) => isPurgeMarker(operation));
2624
+ const refusal = await this.signatureAdmission.admitMarker(job, marker, signal);
2625
+ if (refusal) return refusal;
2626
+ const held = await this.heldStreams(purger, documentId);
2627
+ let documentType = marker.action.input.documentType;
2628
+ let appliedDeletion = held.branches.length > 0;
2629
+ if (held.branches.length > 0) try {
2630
+ const meta = await stores.documentMetaCache.getDocumentMeta(documentId, held.branches.includes("main") ? "main" : held.branches[0], signal);
2631
+ documentType = meta.documentType;
2632
+ appliedDeletion = !meta.state.isDeleted;
2633
+ } catch {}
2634
+ let survivors = [];
2635
+ if (this.driveContainerTypes.has(documentType)) {
2636
+ const members = await this.driveMembers(purger, stores, documentId, held.branches);
2637
+ survivors = [...members.required, ...members.survivors];
2638
+ }
2639
+ const sourceRemote = typeof job.meta.sourceRemote === "string" ? job.meta.sourceRemote : "";
2640
+ const collectionId = sourceRemote ? await purger.remoteCollection(sourceRemote) : void 0;
2641
+ return {
2642
+ purger,
2643
+ marker: purgeMarkerOperation(marker.action),
2644
+ documentType,
2645
+ held,
2646
+ sourceRemote,
2647
+ collectionIds: collectionId === void 0 ? [] : [collectionId],
2648
+ survivors,
2649
+ ...appliedDeletion ? { appliedDeletion: true } : {}
2650
+ };
2651
+ }
2652
+ /** Execution: delete, write the marker and its twin, tombstone, reopen. */
2653
+ async commitPurge(params, commit) {
2654
+ const { job, startTime, stores, signal, touchedStreams } = params;
2655
+ const { purger, marker, documentType, held, sourceRemote } = commit;
2656
+ const documentId = job.documentId;
2657
+ const streams = [...held.streams, {
2658
+ scope: "document",
2659
+ branch: "main"
2660
+ }];
2661
+ for (const stream of streams) {
2662
+ touchedStreams.add(documentId, stream.scope, stream.branch);
2663
+ params.postCommitInvalidations.push({
2664
+ documentId,
2665
+ ...stream
2666
+ });
2667
+ }
2668
+ params.postCommitMetaInvalidations.push(documentId);
2669
+ const removedRows = await purger.deleteRows(documentId);
2670
+ const [stored] = await stores.operationStore.apply(documentId, documentType, "document", "main", 0, (txn) => {
2671
+ txn.addOperations(marker);
2672
+ }, signal);
2673
+ const indexTxn = stores.operationIndex.start();
2674
+ indexTxn.write([{
2675
+ ...stored,
2676
+ documentId,
2677
+ documentType,
2678
+ scope: "document",
2679
+ branch: "main",
2680
+ sourceRemote
2681
+ }]);
2682
+ const [ordinal] = await stores.operationIndex.commit(indexTxn, signal);
2683
+ await purger.writeTombstone({
2684
+ documentId,
2685
+ ordinal,
2686
+ removedRows,
2687
+ purgedAtUtc: marker.action.input.purgedAtUtcIso,
2688
+ requestId: marker.action.input.requestId
2689
+ });
2690
+ const collections = await purger.reopenMemberships(documentId, ordinal, commit.collectionIds);
2691
+ params.postCommitMembershipInvalidations.push(documentId, ...commit.survivors, ...indexTxn.getMembershipInvalidations());
2692
+ const operationWithContext = {
2693
+ operation: stored,
2694
+ context: {
2695
+ documentId,
2696
+ scope: "document",
2697
+ branch: "main",
2698
+ documentType,
2699
+ ordinal,
2700
+ ...commit.appliedDeletion ? { appliedDeletion: true } : {}
2701
+ }
2702
+ };
2703
+ return {
2704
+ result: {
2705
+ job,
2706
+ success: true,
2707
+ operations: [stored],
2708
+ operationsWithContext: [operationWithContext],
2709
+ duration: Date.now() - startTime
2710
+ },
2711
+ pendingEvent: {
2712
+ jobId: job.id,
2713
+ operations: [operationWithContext],
2714
+ jobMeta: job.meta,
2715
+ collectionMemberships: { [documentId]: collections }
2716
+ }
2717
+ };
2718
+ }
2719
+ async heldStreams(purger, documentId) {
2720
+ const streams = await purger.streams(documentId);
2721
+ return {
2722
+ streams,
2723
+ branches: [...new Set(streams.filter((stream) => stream.scope === "document").map((stream) => stream.branch))]
2724
+ };
2725
+ }
2726
+ /** Members a drive purge needs gone, and those living on elsewhere. */
2727
+ async driveMembers(purger, stores, driveId, branches) {
2728
+ const required = /* @__PURE__ */ new Set();
2729
+ const survivors = /* @__PURE__ */ new Set();
2730
+ for (const branch of branches.length > 0 ? branches : ["main"]) {
2731
+ const collectionId = DriveCollectionId.forDrive(driveId, branch).key;
2732
+ const members = await purger.collectionMembers(collectionId, driveId, branch);
2733
+ const purged = await stores.documentLocks.purged(members.map((member) => member.documentId));
2734
+ for (const member of members) {
2735
+ if (purged.has(member.documentId)) continue;
2736
+ if (member.required) required.add(member.documentId);
2737
+ else survivors.add(member.documentId);
2738
+ }
2739
+ }
2740
+ return {
2741
+ required: [...required],
2742
+ survivors: [...survivors]
2743
+ };
2744
+ }
2745
+ /** The marker, signed by this executor's signer as any peer admits it. */
2746
+ async signMarker(documentId, documentType, requestId, signal) {
2747
+ const action = purgeDocumentAction({
2748
+ documentId,
2749
+ documentType,
2750
+ requestId
2751
+ });
2752
+ const signature = await this.signer.signAction(action, {
2753
+ documentId,
2754
+ branch: "main"
2755
+ }, signal);
2756
+ return purgeMarkerOperation({
2757
+ ...action,
2758
+ context: { signer: {
2759
+ ...actionSignerIdentity(this.signer),
2760
+ signatures: [signature]
2761
+ } }
2762
+ });
2763
+ }
2764
+ /** A stored document at a version this reactor does not run is read-only here. */
2765
+ async unsupportedStoredProtocol(job, stores, signal) {
2766
+ let versions;
2767
+ try {
2768
+ versions = this.featureFlags.documentDecisions && job.kind !== "load" ? (await stores.writeCache.getState(job.documentId, "document", job.branch, void 0, signal)).header.protocolVersions : (await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal)).protocolVersions;
2769
+ } catch {
2770
+ return;
2771
+ }
2772
+ return this.documentActionHandler.unsupportedProtocol(job.documentId, versions);
2773
+ }
2774
+ /**
2775
+ * A successful mutation's result and the write-ready event it owes, carrying
2776
+ * what earlier attempts committed ahead of what this one wrote.
2777
+ */
2778
+ async committedOutcome(job, reloaded, written, generated, stores, startTime) {
2779
+ const operationsWithContext = [...reloaded, ...written];
2780
+ let pendingEvent;
2781
+ if (operationsWithContext.length > 0) {
2782
+ const collectionMemberships = await this.getCollectionMembershipsForOperations(operationsWithContext, stores);
2783
+ pendingEvent = {
2784
+ jobId: job.id,
2785
+ operations: operationsWithContext,
2786
+ jobMeta: job.meta,
2787
+ submittedActionIds: submittedActionIds(job),
2788
+ collectionMemberships
2789
+ };
2790
+ }
2791
+ return {
2792
+ result: {
2793
+ job,
2794
+ success: true,
2795
+ operations: [...reloaded.map((entry) => entry.operation), ...generated],
2796
+ operationsWithContext,
2797
+ duration: Date.now() - startTime
2798
+ },
2799
+ pendingEvent
2800
+ };
2801
+ }
2802
+ /**
2803
+ * The stored operations of writes an earlier attempt committed, as a fresh
2804
+ * write would report them. State is rebuilt from the write cache, and left
2805
+ * out when it cannot be.
2806
+ */
2807
+ async reloadCommitted(writes, stores, signal) {
2808
+ const streams = /* @__PURE__ */ new Map();
2809
+ for (const write of writes) {
2810
+ const key = `${write.documentId}\u0000${write.scope}\u0000${write.branch}`;
2811
+ streams.set(key, [...streams.get(key) ?? [], write]);
2812
+ }
2813
+ const reloaded = [];
2814
+ for (const group of streams.values()) {
2815
+ const { documentId, scope, branch } = group[0];
2816
+ const opIds = [...new Set(group.map((write) => write.opId))];
2817
+ const operations = await stores.operationStore.getOperationsByIds(documentId, scope, branch, opIds, signal);
2818
+ const ordinals = await stores.operationIndex.getOrdinalsByOpIds(documentId, scope, branch, opIds, signal);
2819
+ const { documentType } = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);
2820
+ for (const operation of operations.sort((a, b) => a.index - b.index)) reloaded.push({
2821
+ operation,
2822
+ context: {
2823
+ documentId,
2824
+ scope,
2825
+ branch,
2826
+ documentType,
2827
+ resultingState: await this.rebuiltState(stores, {
2828
+ documentId,
2829
+ scope,
2830
+ branch
2831
+ }, operation, signal),
2832
+ ordinal: ordinals.get(operation.id) ?? 0
2833
+ }
2834
+ });
2835
+ }
2836
+ return reloaded;
2837
+ }
2838
+ async rebuiltState(stores, stream, operation, signal) {
2839
+ try {
2840
+ const document = await stores.writeCache.getState(stream.documentId, stream.scope, stream.branch, operation.index, signal);
2841
+ return JSON.stringify({
2842
+ ...document.state,
2843
+ header: document.header
2844
+ });
2845
+ } catch (error) {
2846
+ this.logger.warn("No state for committed operation @OperationId in @Stream: @Error", operation.id, stream, error);
2847
+ return;
2848
+ }
2849
+ }
2850
+ /**
2851
+ * Drops the cached state of every stream a job wrote, after its transaction
2852
+ * did not commit.
2853
+ *
2854
+ * The caches are shared by reference with the copies the scope hands the job,
2855
+ * so a rollback undoes nothing in them: what the job put there survives, as
2856
+ * does anything a read filled from the store while the job's own writes were
2857
+ * still uncommitted. An eviction that throws is swallowed rather than allowed
2858
+ * to replace the failure the caller is owed, and the remaining streams are
2859
+ * still evicted.
2860
+ */
2861
+ evictTouchedStreams(touchedStreams) {
2862
+ for (const entry of touchedStreams) try {
2863
+ this.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);
2864
+ this.documentMetaCache.invalidate(entry.documentId, entry.branch);
2865
+ this.collectionMembershipCache.invalidate(entry.documentId);
2866
+ } catch (error) {
2867
+ this.logger.error("Failed to evict cached state for rolled back @Stream : @Error", entry, error);
2868
+ }
2869
+ }
2870
+ async getCollectionMembershipsForOperations(operations, stores) {
2871
+ const documentIds = [...new Set(operations.map((op) => op.context.documentId))];
2872
+ return stores.collectionMembershipCache.getCollectionsForDocuments(documentIds);
2873
+ }
2874
+ async processActions(writes, executing) {
2875
+ const { job, signal } = executing;
2876
+ const actions = writes.map((write) => write.action);
2877
+ const generatedOperations = [];
2878
+ const operationsWithContext = [];
2879
+ for (const action of actions) if (action.timestampUtcMs && !isValidISOTimestamp(action.timestampUtcMs)) return {
2880
+ success: false,
2881
+ generatedOperations,
2882
+ operationsWithContext,
2883
+ error: new InvalidOperationTimestampError(job.documentId, action.scope, action.timestampUtcMs, `action ${action.type} (id: ${action.id})`)
2884
+ };
2885
+ let lastYield = performance.now();
2886
+ if (this.config.batchApplies && this.canBatch(writes, executing)) {
2887
+ const batched = await this.executeRegularActionsBatched(writes, executing);
2888
+ const error = this.accumulateResultOrReturnError(batched, generatedOperations, operationsWithContext);
2889
+ if (error !== null) return {
2890
+ success: false,
2891
+ generatedOperations,
2892
+ operationsWithContext,
2893
+ error: error.error
2894
+ };
2895
+ return {
2896
+ success: true,
2897
+ generatedOperations,
2898
+ operationsWithContext
2899
+ };
2900
+ }
2901
+ for (const write of writes) {
2902
+ const result = DOCUMENT_SCOPE_ACTIONS.has(write.action.type) ? await this.documentActionHandler.execute(write, executing) : await this.executeRegularAction(write, executing);
2903
+ const error = this.accumulateResultOrReturnError(result, generatedOperations, operationsWithContext);
2904
+ if (error !== null) return {
2905
+ success: false,
2906
+ generatedOperations,
2907
+ operationsWithContext,
2908
+ error: error.error
2909
+ };
2910
+ if (performance.now() - lastYield > this.config.yieldDeadlineMs) {
2911
+ await yieldToMain();
2912
+ lastYield = performance.now();
2913
+ if (signal?.aborted) return {
2914
+ success: false,
2915
+ generatedOperations,
2916
+ operationsWithContext,
2917
+ error: /* @__PURE__ */ new Error("Aborted")
2918
+ };
2919
+ }
2920
+ }
2921
+ return {
2922
+ success: true,
2923
+ generatedOperations,
2924
+ operationsWithContext
2925
+ };
2926
+ }
2927
+ /**
2928
+ * Decides a write and reduces it, without persisting anything.
2929
+ *
2930
+ * Split from the commit so one write and a batch of them share this logic
2931
+ * rather than keeping two copies of it. `baseDocument` lets a batch thread
2932
+ * the previous action's result forward instead of reading its own write back
2933
+ * out of the cache, which is the only reason the reduce has to be sequential.
2934
+ */
2935
+ async prepareRegularWrite(write, executing, baseDocument) {
2936
+ const { action, skip, sourceOperation, sourceRemote, deniedReason } = write;
2937
+ const { job, startTime, indexTxn, stores, signal } = executing;
2938
+ let appendCondition;
2939
+ let documentVersion;
2940
+ const alreadyEvaluated = this.featureFlags.documentDecisions && (executing.replayingAcceptedHistory || executing.evaluatedByPosition);
2941
+ if (this.featureFlags.documentDecisions && !alreadyEvaluated) {
2942
+ const target = {
2943
+ documentId: job.documentId,
2944
+ branch: job.branch
2945
+ };
2946
+ let admission;
2947
+ try {
2948
+ admission = await decideAtHead(this.decisionModel, stores.writeCache, target, {
2949
+ address: action.context?.signer?.user.address,
2950
+ key: action.context?.signer?.app.key
2951
+ }, {
2952
+ verb: "execute",
2953
+ scope: action.scope,
2954
+ operation: action.type
2955
+ }, signal, this.featureFlags.authConditions ? {
2956
+ actionInput: action.input,
2957
+ carriedDocument: baseDocument
2958
+ } : void 0);
2959
+ } catch (error) {
2960
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
2961
+ }
2962
+ if (admission.evaluation.decision === "deny") return buildErrorResult(job, refusalError(admission.evaluation.reason, job.documentId, admission.deletedAtUtcIso, action), startTime);
2963
+ appendCondition = admission.appendCondition;
2964
+ documentVersion = admission.documentVersion;
2965
+ } else if (alreadyEvaluated) documentVersion = (await stores.writeCache.getState(job.documentId, "document", job.branch, void 0, signal)).state.document.version;
2966
+ else {
2967
+ let docMeta;
2968
+ try {
2969
+ docMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);
2970
+ } catch (error) {
2971
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
2972
+ }
2973
+ if (docMeta.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);
2974
+ documentVersion = docMeta.state.version;
2975
+ }
2976
+ if (isUndoRedo(action) || skip > 0) stores.writeCache.invalidate(job.documentId, job.scope, job.branch);
2977
+ let document;
2978
+ if (baseDocument !== void 0) document = baseDocument;
2979
+ else try {
2980
+ document = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);
2981
+ } catch (error) {
2982
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
2983
+ }
2984
+ if (!this.featureFlags.authEnforcement && !executing.replayingAcceptedHistory) {
2985
+ const subject = {
2986
+ address: write.action.context?.signer?.user.address,
2987
+ key: write.action.context?.signer?.app.key
2988
+ };
2989
+ if (decide(document.state.auth, subject, {
2990
+ verb: "execute",
2991
+ scope: action.scope,
2992
+ operation: action.type
2993
+ }) === "deny") return buildErrorResult(job, new AuthorizationDeniedError(job.documentId, action.scope, action.type, subject.address), startTime);
2994
+ }
2995
+ let module;
2996
+ try {
2997
+ module = this.registry.getModule(document.header.documentType, normalizeDocumentModelVersion(documentVersion));
2998
+ } catch (error) {
2999
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
3000
+ }
3001
+ let updatedDocument;
3002
+ if (deniedReason !== void 0) {
3003
+ const index = getNextIndexForScope(document, job.scope);
3004
+ const denied = createOperation(action, index, skip, {
3005
+ documentId: job.documentId,
3006
+ scope: job.scope,
3007
+ branch: job.branch
3008
+ });
3009
+ denied.deniedReason = deniedReason;
3010
+ let standing = document;
3011
+ if (skip > 0) try {
3012
+ standing = await stores.writeCache.getState(job.documentId, job.scope, job.branch, index - skip - 1, signal);
3013
+ } catch (error) {
3014
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
3015
+ }
3016
+ denied.hash = hashDocumentStateForScope(standing, job.scope);
3017
+ updatedDocument = {
3018
+ ...standing,
3019
+ operations: {
3020
+ ...standing.operations,
3021
+ [job.scope]: [...standing.operations[job.scope] ?? [], denied]
3022
+ }
3023
+ };
3024
+ } else try {
3025
+ const protocolVersion = baseReducerVersion(document.header);
3026
+ const reducerOptions = sourceOperation ? {
3027
+ skip,
3028
+ branch: job.branch,
3029
+ replayOptions: { operation: sourceOperation },
3030
+ protocolVersion
3031
+ } : {
3032
+ skip,
3033
+ branch: job.branch,
3034
+ protocolVersion
3035
+ };
3036
+ updatedDocument = withProtocolVersions(module.reducer(document, action, void 0, reducerOptions), document.header.protocolVersions);
3037
+ } catch (error) {
3038
+ const contextMessage = `Failed to apply action to document:\n Action type: ${action.type}\n Document ID: ${job.documentId}\n Document type: ${document.header.documentType}\n Scope: ${job.scope}\n Original error: ${error instanceof Error ? error.message : String(error)}`;
3039
+ const enhancedError = new Error(contextMessage);
3040
+ if (error instanceof Error && error.stack) enhancedError.stack = `${contextMessage}\n\nOriginal stack trace:\n${error.stack}`;
3041
+ return buildErrorResult(job, enhancedError, startTime);
3042
+ }
3043
+ const scope = job.scope;
3044
+ const operations = updatedDocument.operations[scope];
3045
+ if (operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error("No operation generated from action"), startTime);
3046
+ const newOperation = operations[operations.length - 1];
3047
+ if (!isUndoRedo(action)) newOperation.skip = skip;
3048
+ if (deniedReason === void 0 && sourceOperation === void 0 && !executing.replayingAcceptedHistory && isSynthesized(action, newOperation, document.operations[scope] ?? [])) try {
3049
+ await signSynthesized(newOperation, action, {
3050
+ documentId: job.documentId,
3051
+ scope,
3052
+ branch: job.branch
3053
+ }, this.signer, signal);
3054
+ } catch (error) {
3055
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
3056
+ }
3057
+ const resultingState = JSON.stringify({
3058
+ ...updatedDocument.state,
3059
+ header: updatedDocument.header
3060
+ });
3061
+ return {
3062
+ action,
3063
+ sourceRemote,
3064
+ scope,
3065
+ document,
3066
+ updatedDocument,
3067
+ operation: newOperation,
3068
+ resultingState,
3069
+ appendCondition,
3070
+ denied: deniedReason !== void 0
3071
+ };
3072
+ }
3073
+ /**
3074
+ * Persists a run of prepared writes in one store transaction.
3075
+ *
3076
+ * The store has always accepted many operations per apply; the executor only
3077
+ * ever handed it one. Passing the whole run means one advisory lock over the
3078
+ * read set and one guarded insert for the batch, instead of one of each per
3079
+ * operation.
3080
+ *
3081
+ * The append condition is taken from the first write. Every write in a run
3082
+ * reads the same streams at the same revisions, because nothing outside the
3083
+ * run can change them mid-batch, and the caller has already refused to batch
3084
+ * the scopes where that does not hold.
3085
+ */
3086
+ async commitPreparedWrites(prepared, executing) {
3087
+ const { job, startTime, indexTxn, stores, signal } = executing;
3088
+ const first = prepared[0];
3089
+ const last = prepared[prepared.length - 1];
3090
+ const scope = first.scope;
3091
+ const documentType = first.document.header.documentType;
3092
+ const operations = prepared.map((write) => write.operation);
3093
+ executing.touchedStreams.add(job.documentId, scope, job.branch);
3094
+ let storedOperations;
3095
+ try {
3096
+ storedOperations = await stores.operationStore.apply(job.documentId, documentType, scope, job.branch, first.operation.index, (txn) => {
3097
+ txn.addOperations(...operations);
3098
+ }, signal, first.appendCondition);
3099
+ } catch (error) {
3100
+ this.logger.error("Failed to write operation to IOperationStore (@documentId @scope @branch): @Operation @Error", job.documentId, scope, job.branch, operations, error);
3101
+ stores.writeCache.invalidate(job.documentId, scope, job.branch);
3102
+ if (AppendConditionFailedError.isError(error)) for (const stream of error.condition.streams) stores.writeCache.invalidate(stream.documentId, stream.scope, stream.branch);
3103
+ return {
3104
+ job,
3105
+ success: false,
3106
+ error: error instanceof Error ? error : /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${String(error)}`),
3107
+ duration: Date.now() - startTime
3108
+ };
3109
+ }
3110
+ const head = storedOperations[storedOperations.length - 1];
3111
+ last.updatedDocument.header.revision = {
3112
+ ...last.updatedDocument.header.revision,
3113
+ [scope]: head.index + 1
3114
+ };
3115
+ stores.writeCache.putRun(job.documentId, scope, job.branch, storedOperations.map((operation, position) => ({
3116
+ revision: operation.index,
3117
+ document: prepared[position].updatedDocument
3118
+ })));
3119
+ indexTxn.write(storedOperations.map((operation, position) => ({
3120
+ ...operation,
3121
+ documentId: job.documentId,
3122
+ documentType,
3123
+ branch: job.branch,
3124
+ scope,
3125
+ sourceRemote: prepared[position].sourceRemote
3126
+ })));
3127
+ if (scope === "auth") for (const write of prepared) indexTxn.recordGroupReferences(job.documentId, mentionedGroupIds(write.action));
3128
+ return {
3129
+ job,
3130
+ success: true,
3131
+ operations: storedOperations,
3132
+ operationsWithContext: storedOperations.map((operation, position) => ({
3133
+ operation,
3134
+ context: {
3135
+ documentId: job.documentId,
3136
+ scope,
3137
+ branch: job.branch,
3138
+ documentType,
3139
+ resultingState: prepared[position].resultingState,
3140
+ ordinal: 0
3141
+ }
3142
+ })),
3143
+ duration: Date.now() - startTime
3144
+ };
3145
+ }
3146
+ /**
3147
+ * Whether a job's writes may share one store transaction.
3148
+ *
3149
+ * Deliberately narrow. Batching changes only how many transactions the
3150
+ * operations arrive in, and every condition below is a case where that would
3151
+ * change something else as well:
3152
+ *
3153
+ * - A document-scope action goes through its own handler, which has its own
3154
+ * apply and its own reasons for it.
3155
+ * - A positional or replayed run carries skips and re-appended operations,
3156
+ * whose indices are not a simple ascending run from the head.
3157
+ * - UNDO, REDO and NOOP-with-skip each invalidate the write cache to
3158
+ * force a full-history rebuild, so they cannot be reduced against state
3159
+ * threaded from the write before them.
3160
+ * - The auth scope decides later writes against the policy earlier ones
3161
+ * install, so a batch would decide them all against the policy as it stood
3162
+ * before the batch.
3163
+ * - The document scope is read by every decision model, so writing it is
3164
+ * writing part of the read set; the per-write conditions would not agree.
3165
+ *
3166
+ * A run that fails any of these is executed one write at a time, unchanged.
3167
+ */
3168
+ canBatch(writes, executing) {
3169
+ if (writes.length < 2) return false;
3170
+ if (executing.evaluatedByPosition || executing.replayingAcceptedHistory) return false;
3171
+ const scope = executing.job.scope;
3172
+ if (scope === "auth" || scope === "document") return false;
3173
+ return writes.every((write) => {
3174
+ const type = write.action.type;
3175
+ return write.skip === 0 && write.deniedReason === void 0 && write.sourceOperation === void 0 && !DOCUMENT_SCOPE_ACTIONS.has(type) && !isUndoRedo(write.action) && type !== "NOOP";
3176
+ });
3177
+ }
3178
+ /**
3179
+ * Decides and reduces a run of writes, then persists them together.
3180
+ *
3181
+ * The reduce stays sequential - each action needs the state the one before it
3182
+ * produced - but the result is threaded in memory rather than read back from
3183
+ * the cache, and the whole run reaches the store in a single apply.
3184
+ *
3185
+ * A write that turns out to be denied abandons the batch and replays the run
3186
+ * one write at a time, because a denied write holds a position of its own and
3187
+ * that is the path where the per-write behaviour is load-bearing. A write
3188
+ * that cannot be prepared fails the job outright: preparing is a read, so the
3189
+ * replay would only reach the same failure, and the job leaves nothing behind
3190
+ * either way.
3191
+ */
3192
+ async executeRegularActionsBatched(writes, executing) {
3193
+ const prepared = [];
3194
+ let carried;
3195
+ let lastYield = performance.now();
3196
+ for (const write of writes) {
3197
+ const outcome = await this.prepareRegularWrite(write, executing, carried);
3198
+ if ("success" in outcome) return outcome;
3199
+ if (outcome.denied) return this.executeRegularActionsSequentially(writes, executing);
3200
+ prepared.push(outcome);
3201
+ carried = outcome.updatedDocument;
3202
+ if (performance.now() - lastYield > this.config.yieldDeadlineMs) {
3203
+ await yieldToMain();
3204
+ lastYield = performance.now();
3205
+ if (executing.signal?.aborted) return buildErrorResult(executing.job, /* @__PURE__ */ new Error("Aborted"), executing.startTime);
3206
+ }
3207
+ }
3208
+ if (!this.conditionsAgree(prepared)) return this.executeRegularActionsSequentially(writes, executing);
3209
+ return this.commitPreparedWrites(prepared, executing);
3210
+ }
3211
+ /** Whether every prepared write carries the same read-set condition. */
3212
+ conditionsAgree(prepared) {
3213
+ const shape = (write) => write.appendCondition === void 0 ? "none" : JSON.stringify([...write.appendCondition.streams].map((stream) => [
3214
+ stream.documentId,
3215
+ stream.scope,
3216
+ stream.branch,
3217
+ stream.revision
3218
+ ]).sort());
3219
+ const first = shape(prepared[0]);
3220
+ return prepared.every((write) => shape(write) === first);
3221
+ }
3222
+ /**
3223
+ * The unbatched path, for a run that turned out not to qualify after its
3224
+ * writes were prepared. Nothing has been persisted at that point, so
3225
+ * replaying the whole run per write is safe.
3226
+ */
3227
+ async executeRegularActionsSequentially(writes, executing) {
3228
+ const operations = [];
3229
+ const contexts = [];
3230
+ let lastYield = performance.now();
3231
+ for (const write of writes) {
3232
+ const result = await this.executeRegularAction(write, executing);
3233
+ if (!result.success) return result;
3234
+ operations.push(...result.operations ?? []);
3235
+ contexts.push(...result.operationsWithContext ?? []);
3236
+ if (performance.now() - lastYield > this.config.yieldDeadlineMs) {
3237
+ await yieldToMain();
3238
+ lastYield = performance.now();
3239
+ if (executing.signal?.aborted) return buildErrorResult(executing.job, /* @__PURE__ */ new Error("Aborted"), executing.startTime);
3240
+ }
3241
+ }
3242
+ return {
3243
+ job: executing.job,
3244
+ success: true,
3245
+ operations,
3246
+ operationsWithContext: contexts,
3247
+ duration: Date.now() - executing.startTime
3248
+ };
3249
+ }
3250
+ /** Decides, reduces and persists one write. */
3251
+ async executeRegularAction(write, executing) {
3252
+ const prepared = await this.prepareRegularWrite(write, executing);
3253
+ if ("success" in prepared) return prepared;
3254
+ return this.commitPreparedWrites([prepared], executing);
3255
+ }
3256
+ /**
3257
+ * Orders a write by timestamp and decides it where it lands. The caller
3258
+ * supplies the timestamp, so a write can belong before operations already
3259
+ * stored; those are re-appended alongside it, the way a load reshuffles.
3260
+ *
3261
+ * Deciding a backdated write at the stream heads instead of at its position
3262
+ * would overwrite the verdict every other replica computes for it.
3263
+ */
3264
+ async positionByTimestamp(job, stores, signal) {
3265
+ const plain = () => ({
3266
+ writes: job.actions.map((action) => ({
3267
+ action,
3268
+ skip: 0,
3269
+ sourceRemote: ""
3270
+ })),
3271
+ evaluatedByPosition: false
3272
+ });
3273
+ if (!this.featureFlags.documentDecisions || job.actions.length === 0) return plain();
3274
+ let earliest = job.actions[0].timestampUtcMs;
3275
+ let earliestAt = Date.parse(earliest);
3276
+ for (const action of job.actions) {
3277
+ const at = Date.parse(action.timestampUtcMs);
3278
+ if (at < earliestAt) {
3279
+ earliest = action.timestampUtcMs;
3280
+ earliestAt = at;
3281
+ }
3282
+ }
3283
+ const revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);
3284
+ const backdated = earliestAt < Date.parse(revisions.latestTimestamp);
3285
+ if (this.featureFlags.authEnforcement && job.scope === "auth") {
3286
+ const newest = await stores.operationStore.getStreamLatestTimestamp(job.documentId, "auth", job.branch, signal);
3287
+ const violation = this.firstNonMonotonicTimestamp(job.actions, newest, job.documentId, job.branch);
3288
+ if (violation) return {
3289
+ writes: [],
3290
+ evaluatedByPosition: false,
3291
+ error: violation
3292
+ };
3293
+ if (!backdated) return plain();
3294
+ return this.evaluatePositioned(job, stores, this.appendedOperations(job, revisions.revision[job.scope] ?? 0), signal);
3295
+ }
3296
+ if (!backdated) return plain();
3297
+ const conflicting = (await stores.operationStore.getConflicting(job.documentId, job.scope, job.branch, earliest, void 0, signal)).results.filter((operation) => !isGenesisOperation(operation));
3298
+ const nothingToMove = async () => {
3299
+ if (!this.featureFlags.authEnforcement) return plain();
3300
+ return this.evaluatePositioned(job, stores, this.appendedOperations(job, revisions.revision[job.scope] ?? 0), signal);
3301
+ };
3302
+ if (conflicting.length === 0) return nothingToMove();
3303
+ const nextIndex = revisions.revision[job.scope] ?? 0;
3304
+ let firstConflicting = conflicting[0].index;
3305
+ for (const operation of conflicting) if (operation.index < firstConflicting) firstConflicting = operation.index;
3306
+ const stored = (await stores.operationStore.getSince(job.documentId, job.scope, job.branch, firstConflicting - 1, void 0, void 0, signal)).results;
3307
+ const conflictingIds = new Set(conflicting.map((operation) => operation.id));
3308
+ const effective = garbageCollect(sortOperations(stored)).filter((operation) => !isGenesisOperation(operation));
3309
+ const firstMoving = effective.findIndex((operation) => conflictingIds.has(operation.id));
3310
+ const moving = firstMoving === -1 ? [] : effective.slice(firstMoving);
3311
+ if (moving.length === 0) return nothingToMove();
3312
+ let firstRetracted = moving[0].index;
3313
+ for (const operation of moving) firstRetracted = Math.min(firstRetracted, operation.index - operation.skip);
3314
+ const incoming = job.actions.map((action, i) => ({
3315
+ id: action.id,
3316
+ index: nextIndex + i,
3317
+ skip: 0,
3318
+ hash: "",
3319
+ timestampUtcMs: action.timestampUtcMs,
3320
+ action
3321
+ }));
3322
+ const merged = reshuffleByTimestamp({
3323
+ index: nextIndex,
3324
+ skip: retractionSkip(nextIndex, firstRetracted)
3325
+ }, moving, incoming);
3326
+ stores.writeCache.invalidate(job.documentId, job.scope, job.branch);
3327
+ if (!this.featureFlags.authEnforcement) return {
3328
+ writes: merged.map((operation) => ({
3329
+ action: operation.action,
3330
+ skip: operation.skip,
3331
+ sourceRemote: ""
3332
+ })),
3333
+ evaluatedByPosition: false
3334
+ };
3335
+ return this.evaluatePositioned(job, stores, merged, signal);
3336
+ }
3337
+ /**
3338
+ * Decides each operation where it lands and carries the verdict on it. A
3339
+ * refused submitted action is reported to the caller and nothing is stored; a
3340
+ * refused operation the reshuffle merely moved keeps its verdict, because it
3341
+ * already holds a position.
3342
+ *
3343
+ * The operations carry the indexes and skips they will be stored at, because
3344
+ * the walk resolves skips before it orders them.
3345
+ */
3346
+ async evaluatePositioned(job, stores, operations, signal) {
3347
+ const reasons = await evaluateByPosition(this.decisionModel, {
3348
+ documentId: job.documentId,
3349
+ branch: job.branch
3350
+ }, {
3351
+ scope: job.scope,
3352
+ operations
3353
+ }, stores, signal);
3354
+ const submitted = new Set(job.actions.map((action) => action.id));
3355
+ for (let i = 0; i < operations.length; i++) {
3356
+ const reason = reasons[i];
3357
+ if (reason !== void 0 && submitted.has(operations[i].action.id)) return {
3358
+ writes: [],
3359
+ evaluatedByPosition: false,
3360
+ error: refusalError(reason, job.documentId, null, operations[i].action)
3361
+ };
3362
+ }
3363
+ return {
3364
+ writes: operations.map((operation, i) => ({
3365
+ action: operation.action,
3366
+ skip: operation.skip,
3367
+ sourceRemote: "",
3368
+ deniedReason: reasons[i]
3369
+ })),
3370
+ evaluatedByPosition: true
3371
+ };
3372
+ }
3373
+ /**
3374
+ * The scopes a re-evaluation pass visits, in a fixed order.
3375
+ *
3376
+ * The revisions map comes from a query with no ORDER BY, and the order is
3377
+ * load-bearing: each scope's pass re-reads the auth stream, and the walk skips
3378
+ * an operation by its stored denial, so a denial this pass just wrote is
3379
+ * visible to a later-visited scope and invisible to an earlier one. The model's
3380
+ * own projection order leads, then the rest sorted, so the pass is reproducible
3381
+ * across replicas and across runs.
3382
+ */
3383
+ evaluationOrder(target, revision) {
3384
+ const definition = this.decisionModel(target);
3385
+ const evaluated = Object.keys(revision).filter((scope) => definition.evaluatesScope(scope));
3386
+ const leading = [];
3387
+ for (const stream of staticReadSet(definition)) {
3388
+ const scope = stream.query.scope;
3389
+ if (evaluated.includes(scope) && !leading.includes(scope)) leading.push(scope);
3390
+ }
3391
+ const rest = evaluated.filter((scope) => !leading.includes(scope)).sort((a, b) => a.localeCompare(b));
3392
+ return [...leading, ...rest];
3393
+ }
3394
+ /**
3395
+ * The first timestamp in the batch that does not strictly exceed everything
3396
+ * ahead of it, or undefined when the whole batch is monotonic.
3397
+ *
3398
+ * The bound is carried forward rather than compared against one stored maximum,
3399
+ * because a single execute can carry several auth actions stamped in the same
3400
+ * millisecond. Letting a tie through would store a stream the position walk
3401
+ * then refuses to read, with no repair path.
3402
+ */
3403
+ firstNonMonotonicTimestamp(entries, newest, documentId, branch) {
3404
+ let boundIso = newest;
3405
+ let bound = newest === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(newest);
3406
+ for (const entry of entries) {
3407
+ if (!isValidISOTimestamp(entry.timestampUtcMs)) return new InvalidOperationTimestampError(documentId, "auth", entry.timestampUtcMs, "auth operation");
3408
+ const at = Date.parse(entry.timestampUtcMs);
3409
+ if (boundIso !== void 0 && at <= bound) return new AuthTimestampNotMonotonicError(documentId, branch, entry.timestampUtcMs, boundIso);
3410
+ bound = at;
3411
+ boundIso = entry.timestampUtcMs;
3412
+ }
3413
+ }
3414
+ /** The operations a batch of submitted actions appends at the scope's tail. */
3415
+ appendedOperations(job, nextIndex) {
3416
+ return job.actions.map((action, i) => ({
3417
+ id: action.id,
3418
+ index: nextIndex + i,
3419
+ skip: 0,
3420
+ hash: "",
3421
+ timestampUtcMs: action.timestampUtcMs,
3422
+ action
3423
+ }));
3424
+ }
3425
+ /**
3426
+ * Re-evaluates the document when a write meets both criteria: it was written
3427
+ * to a stream the model reads, and it is timestamped before an operation
3428
+ * already stored. The caller supplies the timestamp and the reactor does not replace
3429
+ * it, so a mutation job can write such an operation just as a load job can,
3430
+ * which is why both executeJob and executeLoadJob call this.
3431
+ */
3432
+ async reevaluateIfCriteriaMet(criteria, executing) {
3433
+ if (!this.featureFlags.documentDecisions) return;
3434
+ const { job, stores, signal } = executing;
3435
+ const target = {
3436
+ documentId: job.documentId,
3437
+ branch: job.branch
3438
+ };
3439
+ if (!staticReadSet(this.decisionModel(target)).some((stream) => stream.query.documentId === job.documentId && stream.query.scope === criteria.scope && stream.query.branch === job.branch)) return;
3440
+ const revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);
3441
+ const latest = Date.parse(revisions.latestTimestamp);
3442
+ if (!criteria.operations.some((operation) => Date.parse(operation.timestampUtcMs) < latest)) return;
3443
+ return (await this.reevaluateDocument(executing)).error;
3444
+ }
3445
+ /**
3446
+ * Re-evaluates every scope the model evaluates. Where an operation's
3447
+ * evaluation differs from what is stored, the tail from that operation is
3448
+ * re-appended, carrying a skip that spans the indices it supersedes.
3449
+ */
3450
+ async reevaluateDocument(executing) {
3451
+ const { job, stores, signal } = executing;
3452
+ const target = {
3453
+ documentId: job.documentId,
3454
+ branch: job.branch
3455
+ };
3456
+ const reappended = [];
3457
+ const revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);
3458
+ for (const scope of this.evaluationOrder(target, revisions.revision)) {
3459
+ const stored = (await stores.operationStore.getSince(job.documentId, scope, job.branch, -1, void 0, void 0, signal)).results;
3460
+ const effective = garbageCollect(sortOperations([...stored]));
3461
+ if (effective.length === 0) continue;
3462
+ const reevaluated = await evaluateByPosition(this.decisionModel, target, {
3463
+ scope,
3464
+ operations: effective
3465
+ }, stores, signal);
3466
+ const firstChange = effective.findIndex((operation, i) => operation.deniedReason !== reevaluated[i]);
3467
+ if (firstChange === -1) continue;
3468
+ const tail = effective.slice(firstChange);
3469
+ const nextIndex = revisions.revision[scope];
3470
+ stores.writeCache.invalidate(job.documentId, scope, job.branch);
3471
+ const result = await this.processActions(tail.map((operation, i) => ({
3472
+ action: operation.action,
3473
+ skip: i === 0 ? retractionSkip(nextIndex, tail[0].index - tail[0].skip) : 0,
3474
+ sourceRemote: "",
3475
+ deniedReason: reevaluated[firstChange + i]
3476
+ })), {
3477
+ ...executing,
3478
+ job: {
3479
+ ...job,
3480
+ scope
3481
+ },
3482
+ replayingAcceptedHistory: true,
3483
+ evaluatedByPosition: true
3484
+ });
3485
+ if (!result.success) return {
3486
+ error: result.error ?? /* @__PURE__ */ new Error(`Re-evaluation of ${job.documentId} ${scope} failed`),
3487
+ operationsWithContext: reappended
3488
+ };
3489
+ reappended.push(...result.operationsWithContext);
3490
+ }
3491
+ return { operationsWithContext: reappended };
3492
+ }
3493
+ /**
3494
+ * Re-judges a document's stored operations because a read-set stream in
3495
+ * another document (a group) gained an operation. The trigger timestamp
3496
+ * bounds the work: an operation later than everything this document holds
3497
+ * cannot change any evaluation, so the pass is skipped.
3498
+ */
3499
+ async executeReevaluationJob(executing) {
3500
+ const { job, startTime, stores, signal } = executing;
3501
+ if (!this.featureFlags.documentDecisions) return {
3502
+ job,
3503
+ success: true,
3504
+ operations: [],
3505
+ operationsWithContext: [],
3506
+ duration: Date.now() - startTime
3507
+ };
3508
+ const trigger = job.meta.triggerTimestampUtcMs;
3509
+ if (typeof trigger === "string") {
3510
+ let latestTimestamp;
3511
+ try {
3512
+ latestTimestamp = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).latestTimestamp;
3513
+ } catch {
3514
+ return {
3515
+ job,
3516
+ success: true,
3517
+ operations: [],
3518
+ operationsWithContext: [],
3519
+ duration: Date.now() - startTime
3520
+ };
3521
+ }
3522
+ if (Date.parse(trigger) > Date.parse(latestTimestamp)) return {
3523
+ job,
3524
+ success: true,
3525
+ operations: [],
3526
+ operationsWithContext: [],
3527
+ duration: Date.now() - startTime
3528
+ };
3529
+ }
3530
+ const outcome = await this.reevaluateDocument(executing);
3531
+ if (outcome.error) return buildErrorResult(job, outcome.error, startTime);
3532
+ return {
3533
+ job,
3534
+ success: true,
3535
+ operations: outcome.operationsWithContext.map((owc) => owc.operation),
3536
+ operationsWithContext: outcome.operationsWithContext,
3537
+ duration: Date.now() - startTime
3538
+ };
3539
+ }
3540
+ async executeLoadJob(executing) {
3541
+ const { job, startTime, indexTxn, stores, signal } = executing;
3542
+ if (job.operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error("Load job must include at least one operation"), startTime);
3543
+ let docMeta;
3544
+ try {
3545
+ docMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);
3546
+ } catch {}
3547
+ if (docMeta?.state.isDeleted && !this.featureFlags.documentDecisions) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);
3548
+ const scope = job.scope;
3549
+ const monotonicAuthStream = this.featureFlags.authEnforcement && scope === "auth";
3550
+ let latestRevision;
3551
+ try {
3552
+ latestRevision = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).revision[scope] ?? 0;
3553
+ } catch {
3554
+ latestRevision = 0;
3555
+ }
3556
+ for (const operation of job.operations) if (operation.timestampUtcMs && !isValidISOTimestamp(operation.timestampUtcMs)) return {
3557
+ job,
3558
+ success: false,
3559
+ error: new InvalidOperationTimestampError(job.documentId, scope, operation.timestampUtcMs, `operation (index: ${operation.index})`),
3560
+ duration: Date.now() - startTime
3561
+ };
3562
+ const dropped = /* @__PURE__ */ new Set();
3563
+ const admitted = /* @__PURE__ */ new Set();
3564
+ let selection = await this.selectLoadWrites(job, job.operations, stores, signal);
3565
+ for (;;) {
3566
+ const unadmitted = selection.incomingOpsToApply.filter((operation) => !admitted.has(operation));
3567
+ if (unadmitted.length === 0) break;
3568
+ let refused;
3569
+ try {
3570
+ refused = await this.signatureAdmission.admitLoad(job, unadmitted, stores, signal);
3571
+ } catch (error) {
3572
+ return buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);
3573
+ }
3574
+ for (const operation of unadmitted) if (refused.has(operation)) dropped.add(operation);
3575
+ else admitted.add(operation);
3576
+ if (refused.size === 0) break;
3577
+ const remaining = job.operations.filter((operation) => !dropped.has(operation));
3578
+ if (remaining.length === 0) return {
3579
+ job,
3580
+ success: true,
3581
+ operations: [],
3582
+ operationsWithContext: [],
3583
+ duration: Date.now() - startTime
3584
+ };
3585
+ selection = await this.selectLoadWrites(job, remaining, stores, signal);
3586
+ }
3587
+ const { nonSupersededOps, allOpsFromMinConflictingIndex, incomingOpsToApply } = selection;
3588
+ const existingOpsToReshuffle = monotonicAuthStream ? [] : nonSupersededOps.filter((operation) => !isGenesisOperation(operation));
3589
+ const actionIdCounts = /* @__PURE__ */ new Map();
3590
+ for (const operation of allOpsFromMinConflictingIndex) actionIdCounts.set(operation.action.id, (actionIdCounts.get(operation.action.id) ?? 0) + 1);
3591
+ const reshuffleCost = existingOpsToReshuffle.filter((operation) => (actionIdCounts.get(operation.action.id) ?? 0) < 2).length;
3592
+ if (reshuffleCost > this.config.maxSkipThreshold) return {
3593
+ job,
3594
+ success: false,
3595
+ error: new ExcessiveReshuffleError(job.documentId, scope, reshuffleCost, this.config.maxSkipThreshold),
3596
+ duration: Date.now() - startTime
3597
+ };
3598
+ let skipCount = existingOpsToReshuffle.length;
3599
+ if (existingOpsToReshuffle.length > 0) {
3600
+ let minLogicalIndex = Number.POSITIVE_INFINITY;
3601
+ for (const op of existingOpsToReshuffle) {
3602
+ const logical = op.index - op.skip;
3603
+ if (logical < minLogicalIndex) minLogicalIndex = logical;
3604
+ }
3605
+ const logicalSkip = latestRevision - minLogicalIndex;
3606
+ if (logicalSkip > skipCount) skipCount = logicalSkip;
3607
+ }
3608
+ if (incomingOpsToApply.length === 0) return {
3609
+ job,
3610
+ success: true,
3611
+ operations: [],
3612
+ operationsWithContext: [],
3613
+ duration: Date.now() - startTime
3614
+ };
3615
+ if (monotonicAuthStream) {
3616
+ const newest = await stores.operationStore.getStreamLatestTimestamp(job.documentId, "auth", job.branch, signal);
3617
+ const violation = this.firstNonMonotonicTimestamp([...incomingOpsToApply].sort((a, b) => a.index - b.index), newest, job.documentId, job.branch);
3618
+ if (violation) return {
3619
+ job,
3620
+ success: false,
3621
+ error: violation,
3622
+ duration: Date.now() - startTime
3623
+ };
3624
+ }
3625
+ const reshuffledOperations = existingOpsToReshuffle.length === 0 && skipCount === 0 ? incomingOpsToApply.slice().sort((a, b) => a.index - b.index).map((operation, i) => ({
3626
+ ...operation,
3627
+ index: latestRevision + i
3628
+ })) : reshuffleByTimestamp({
3629
+ index: latestRevision,
3630
+ skip: skipCount
3631
+ }, existingOpsToReshuffle, incomingOpsToApply.map((operation) => ({
3632
+ ...operation,
3633
+ id: operation.id
3634
+ })));
3635
+ const incomingIds = new Set(incomingOpsToApply.map((operation) => operation.action.id));
3636
+ for (const operation of reshuffledOperations) if (operation.action.type === "NOOP" && operation.skip === 0 && incomingIds.has(operation.action.id)) operation.skip = 1;
3637
+ let deniedReasons;
3638
+ if (this.featureFlags.documentDecisions) try {
3639
+ deniedReasons = await evaluateByPosition(this.decisionModel, {
3640
+ documentId: job.documentId,
3641
+ branch: job.branch
3642
+ }, {
3643
+ scope,
3644
+ operations: reshuffledOperations
3645
+ }, stores, signal);
3646
+ } catch (error) {
3647
+ return {
3648
+ job,
3649
+ success: false,
3650
+ error: error instanceof Error ? error : new Error(String(error)),
3651
+ duration: Date.now() - startTime
3652
+ };
3653
+ }
3654
+ const effectiveSourceRemote = skipCount > 0 ? "" : job.meta.sourceRemote || "";
3655
+ const result = await this.processActions(reshuffledOperations.map((operation, i) => ({
3656
+ action: operation.action,
3657
+ skip: operation.skip,
3658
+ sourceOperation: operation,
3659
+ sourceRemote: effectiveSourceRemote,
3660
+ deniedReason: deniedReasons?.[i]
3661
+ })), executing);
3662
+ if (!result.success) return {
3663
+ job,
3664
+ success: false,
3665
+ error: result.error,
3666
+ duration: Date.now() - startTime
3667
+ };
3668
+ stores.writeCache.invalidate(job.documentId, scope, job.branch);
3669
+ if (scope === "document") stores.documentMetaCache.invalidate(job.documentId, job.branch);
3670
+ const reevaluationError = await this.reevaluateIfCriteriaMet({
3671
+ scope,
3672
+ operations: result.generatedOperations
3673
+ }, executing);
3674
+ if (reevaluationError) return {
3675
+ job,
3676
+ success: false,
3677
+ error: reevaluationError,
3678
+ duration: Date.now() - startTime
3679
+ };
3680
+ return {
3681
+ job,
3682
+ success: true,
3683
+ operations: result.generatedOperations,
3684
+ operationsWithContext: result.operationsWithContext,
3685
+ duration: Date.now() - startTime
3686
+ };
3687
+ }
3688
+ /** The conflicting window a load opens, and which of its operations are new. */
3689
+ async selectLoadWrites(job, operations, stores, signal) {
3690
+ const scope = job.scope;
3691
+ let minIncomingIndex = Number.POSITIVE_INFINITY;
3692
+ let minIncomingTimestamp = operations[0]?.timestampUtcMs || "";
3693
+ for (const operation of operations) {
3694
+ minIncomingIndex = Math.min(minIncomingIndex, operation.index);
3695
+ const ts = operation.timestampUtcMs || "";
3696
+ if (Date.parse(ts) < Date.parse(minIncomingTimestamp)) minIncomingTimestamp = ts;
3697
+ }
3698
+ let conflictingOps;
3699
+ try {
3700
+ conflictingOps = (await stores.operationStore.getConflicting(job.documentId, scope, job.branch, minIncomingTimestamp, void 0, signal)).results;
3701
+ } catch {
3702
+ conflictingOps = [];
3703
+ }
3704
+ let allOpsFromMinConflictingIndex = conflictingOps;
3705
+ if (conflictingOps.length > 0) {
3706
+ const minConflictingIndex = Math.min(...conflictingOps.map((op) => op.index));
3707
+ try {
3708
+ allOpsFromMinConflictingIndex = (await stores.operationStore.getSince(job.documentId, scope, job.branch, minConflictingIndex - 1, void 0, void 0, signal)).results;
3709
+ } catch {
3710
+ allOpsFromMinConflictingIndex = conflictingOps;
3711
+ }
3712
+ }
3713
+ const incomingActionIds = new Set(operations.map((op) => op.action.id));
3714
+ const supersededBy = (op) => {
3715
+ let nearest;
3716
+ for (const laterOp of allOpsFromMinConflictingIndex) if (laterOp.index > op.index && laterOp.skip > 0 && laterOp.index - laterOp.skip <= op.index && (nearest === void 0 || laterOp.index < nearest.index)) nearest = laterOp;
3717
+ return nearest;
3718
+ };
3719
+ const undoneActionIds = /* @__PURE__ */ new Set();
3720
+ let predecessorBound = minIncomingIndex;
3721
+ const rowsByActionId = /* @__PURE__ */ new Map();
3722
+ for (const op of conflictingOps) if (incomingActionIds.has(op.action.id)) rowsByActionId.set(op.action.id, [...rowsByActionId.get(op.action.id) ?? [], op]);
3723
+ const liveOps = /* @__PURE__ */ new Set();
3724
+ for (const op of conflictingOps) if (supersededBy(op) === void 0) liveOps.add(op);
3725
+ for (const [actionId, rows] of rowsByActionId) {
3726
+ if (rows.some((row) => liveOps.has(row))) continue;
3727
+ if (rows.some((row) => supersededBy(row)?.action.type === "NOOP")) undoneActionIds.add(actionId);
3728
+ else predecessorBound = Math.min(predecessorBound, Math.max(...rows.map((row) => row.index)));
3729
+ }
3730
+ const nonSupersededOps = conflictingOps.filter((op) => {
3731
+ if (op.index < predecessorBound && !incomingActionIds.has(op.action.id)) return false;
3732
+ return liveOps.has(op);
3733
+ });
3734
+ let rewoundFrom = Number.POSITIVE_INFINITY;
3735
+ for (const op of nonSupersededOps) if (!isGenesisOperation(op)) rewoundFrom = Math.min(rewoundFrom, op.index - op.skip);
3736
+ const reappended = new Set(nonSupersededOps.map((op) => op.index));
3737
+ for (const op of allOpsFromMinConflictingIndex) if (op.index >= rewoundFrom && !reappended.has(op.index) && supersededBy(op) === void 0) nonSupersededOps.push(op);
3738
+ const existingActionIds = new Set(nonSupersededOps.map((op) => op.action.id));
3739
+ const seenIncomingActionIds = /* @__PURE__ */ new Set();
3740
+ const incomingOpsToApply = operations.filter((op) => {
3741
+ if (existingActionIds.has(op.action.id)) return false;
3742
+ if (undoneActionIds.has(op.action.id)) return false;
3743
+ if (seenIncomingActionIds.has(op.action.id)) return false;
3744
+ seenIncomingActionIds.add(op.action.id);
3745
+ return true;
3746
+ });
3747
+ return {
3748
+ nonSupersededOps,
3749
+ allOpsFromMinConflictingIndex,
3750
+ incomingOpsToApply
3751
+ };
3752
+ }
3753
+ accumulateResultOrReturnError(result, generatedOperations, operationsWithContext) {
3754
+ if (!result.success) return result;
3755
+ if (result.operations && result.operations.length > 0) generatedOperations.push(...result.operations);
3756
+ if (result.operationsWithContext) operationsWithContext.push(...result.operationsWithContext);
3757
+ return null;
3758
+ }
3759
+ };
3760
+ //#endregion
3761
+ //#region src/core/drive-container-types.ts
3762
+ const DEFAULT_DRIVE_CONTAINER_TYPES = /* @__PURE__ */ new Set(["powerhouse/document-drive", "powerhouse/reactor-drive"]);
3763
+ //#endregion
3764
+ export { buildDecisionModel as _, KyselyExecutionScope as a, appliedDelete as c, DEFAULT_MAX_PURGE_OPERATIONS as d, JobExecutorEventTypes as f, authDecisionModel as g, documentDecisionModel as h, PassthroughSigner as i, resolveFeatureFlags as l, selectDecisionModel as m, SimpleJobExecutor as n, DEFAULT_PURGE_DELETE_BATCH as o, decideAtHead as p, verifyActionSignature as r, KyselyDocumentPurger as s, DEFAULT_DRIVE_CONTAINER_TYPES as t, DEFAULT_DEFERRED_JOB_TTL_MS as u, DriveCollectionId as v };
3765
+
3766
+ //# sourceMappingURL=drive-container-types-CifLQjd3.js.map