@asyra/factory 0.5.4 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
- import { UNDO, measureBrowserDragPhase } from '@asyra/utils';
2
- import { acknowledgeTransactionReplayApplied, applyEventBatchToSynchronousOwners, EventTypes, endTransaction, hasSynchronousEventBatchHandler, isDetachedTransactionValue, isTransactionReplayApplied, publishEvent, publishEventsToObservers, publishEventToObservers, resolveCooperativeRenderMaxItemsPerSlice, runInTransactionReplayMode, startTransaction, userActionCompleted, wasTransactionReplayApplied, updateUndoRedoStatus } from '@asyra/reactive-events';
1
+ import * as localEvents from './transaction-events.js';
2
+ import { UNDO, measureBrowserDragPhase, MutationRecoveryError } from '@asyra/utils';
3
+ import { EventTypes, resolveCooperativeRenderMaxItemsPerSlice } from '@asyra/reactive-events';
3
4
  import { pushFactoryOwnedBatchToSharedChannel, SharedDataChannelRegistry } from './shared-data-channel.js';
4
5
  import { TransactionRollbackError, TransactionValidationError } from './transaction.js';
5
6
  import { FactoryMutationBatchAcceptanceError } from './mutation-batch.js';
@@ -12,6 +13,7 @@ const BUILT_IN_INVERTIBLE_EVENT_TYPES = new Set([
12
13
  EventTypes.MOVE_ELEMENTS,
13
14
  EventTypes.CHANGE_SUBTREE,
14
15
  EventTypes.UPDATE_ELEMENT_DATA,
16
+ EventTypes.UPDATE_ELEMENT_PROPERTY_BINDINGS,
15
17
  EventTypes.ADD_PROPERTY,
16
18
  EventTypes.REMOVE_PROPERTY,
17
19
  EventTypes.UPDATE_PROPERTY,
@@ -26,8 +28,9 @@ const LOCAL_ONLY_COMPUTED_EVENT_TYPES = new Set([
26
28
  const MAX_CANONICAL_REPLAY_OWNER_BATCH_ITEMS = 32;
27
29
  const DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS = 512;
28
30
  const toDefinedMutationOptions = (options) => {
29
- if (!options)
31
+ if (!options) {
30
32
  return;
33
+ }
31
34
  const definedOptions = {};
32
35
  if (options.undoable !== undefined) {
33
36
  definedOptions.undoable = options.undoable;
@@ -41,8 +44,9 @@ const toDefinedMutationOptions = (options) => {
41
44
  if (options.sharedDelivery !== undefined) {
42
45
  definedOptions.sharedDelivery = options.sharedDelivery;
43
46
  }
44
- if (Object.keys(definedOptions).length === 0)
47
+ if (Object.keys(definedOptions).length === 0) {
45
48
  return;
49
+ }
46
50
  return definedOptions;
47
51
  };
48
52
  const toSharedChannelPayload = (payload, options) => {
@@ -97,11 +101,13 @@ const freezeReplayEvents = (events, trustedOwnerValues) => {
97
101
  if (payload && typeof payload === 'object') {
98
102
  ;
99
103
  ['changes', 'moves'].forEach((key) => {
100
- if (!(key in payload))
104
+ if (!(key in payload)) {
101
105
  return;
106
+ }
102
107
  const values = payload[key];
103
- if (!Array.isArray(values))
108
+ if (!Array.isArray(values)) {
104
109
  return;
110
+ }
105
111
  values.forEach((value) => {
106
112
  if (value && typeof value === 'object') {
107
113
  freezeTrustedValue(value);
@@ -131,16 +137,18 @@ const isPlainRecord = (value) => {
131
137
  return prototype === Object.prototype || prototype === null;
132
138
  };
133
139
  const areHistoryValuesEqual = (left, right) => {
134
- if (Object.is(left, right))
140
+ if (Object.is(left, right)) {
135
141
  return true;
142
+ }
136
143
  if (Array.isArray(left) || Array.isArray(right)) {
137
144
  return (Array.isArray(left) &&
138
145
  Array.isArray(right) &&
139
146
  left.length === right.length &&
140
147
  left.every((value, index) => areHistoryValuesEqual(value, right[index])));
141
148
  }
142
- if (!isPlainRecord(left) || !isPlainRecord(right))
149
+ if (!isPlainRecord(left) || !isPlainRecord(right)) {
143
150
  return false;
151
+ }
144
152
  const leftRecord = left;
145
153
  const rightRecord = right;
146
154
  const leftKeys = Reflect.ownKeys(leftRecord);
@@ -156,9 +164,12 @@ const toReplayFailure = (cause) => ({
156
164
  });
157
165
  class DataTransact {
158
166
  constructor(sharedDataChannelRegistry, callbacks) {
167
+ this.events = localEvents;
159
168
  this.journal = [];
160
169
  this.replaceLatestHistoryStages = new Map();
161
170
  this.preparedActionHistoryEntries = null;
171
+ this.historyGroups = new WeakMap();
172
+ this.notifyingHistoryGroup = false;
162
173
  this.undoStack = [];
163
174
  this.redoStack = [];
164
175
  this.isTransacting = 0;
@@ -183,6 +194,7 @@ class DataTransact {
183
194
  this.pendingImmediatePublicationEntries = [];
184
195
  this.pendingImmediatePublicationRecords = [];
185
196
  this.pendingImmediatePublicationWorkItemKeys = new Set();
197
+ this.nextImmediateDeliveryJournalIndex = 0;
186
198
  this.immediatePublicationToken = 0;
187
199
  this.scheduledImmediatePublicationToken = null;
188
200
  this.publicationSequence = 0;
@@ -214,12 +226,149 @@ class DataTransact {
214
226
  this.onStatus = callbacks?.onStatus;
215
227
  this.onUserActionCompleted = callbacks
216
228
  ? callbacks.onUserActionCompleted
217
- : userActionCompleted;
229
+ : localEvents.userActionCompleted;
218
230
  this.onReplayEvent = callbacks?.onReplayEvent;
219
231
  this.canReplayEventBatch = callbacks?.canReplayEventBatch;
220
232
  this.onSharedDeliveryBatch = callbacks?.onSharedDeliveryBatch;
221
233
  this.onSharedPublication = callbacks?.onSharedPublication;
222
234
  }
235
+ isTransactionBoundaryIdle() {
236
+ return (this.isTransacting === 0 &&
237
+ this.transactionSettlementDepth === 0 &&
238
+ !this.inUndo &&
239
+ !this.inRedo &&
240
+ !this.enrollingHistoryGroup &&
241
+ !this.notifyingHistoryGroup);
242
+ }
243
+ assertHistoryGroupBoundaryIdle() {
244
+ if (!this.isTransactionBoundaryIdle()) {
245
+ throw new Error('History group lifecycle requires an idle transaction owner');
246
+ }
247
+ this.assertSharedEvidenceCanonicalControlAllowed();
248
+ }
249
+ requireHistoryGroup(handle, open = true) {
250
+ const group = this.historyGroups.get(handle);
251
+ if (!group || (open && group.status.state !== 'open')) {
252
+ throw new Error('History group handle is foreign, closed or retired');
253
+ }
254
+ return group;
255
+ }
256
+ startHistoryGroup(options = {}) {
257
+ this.assertHistoryGroupBoundaryIdle();
258
+ const threshold = options.warningChangeCount;
259
+ if (threshold !== undefined &&
260
+ (!Number.isSafeInteger(threshold) || threshold <= 0)) {
261
+ throw new Error('History group warningChangeCount must be a positive safe integer');
262
+ }
263
+ const handle = Object.freeze({});
264
+ this.historyGroups.set(handle, {
265
+ members: [],
266
+ options: { ...options },
267
+ status: Object.freeze({
268
+ state: 'open',
269
+ memberCount: 0,
270
+ changeCount: 0,
271
+ warningReached: false
272
+ })
273
+ });
274
+ return handle;
275
+ }
276
+ getHistoryGroupStatus(handle) {
277
+ return this.requireHistoryGroup(handle, false).status;
278
+ }
279
+ notifyHistoryGroup(group) {
280
+ this.notifyingHistoryGroup = true;
281
+ try {
282
+ group.options.onChange?.(group.status);
283
+ }
284
+ catch {
285
+ // Advisory observers cannot change a committed outcome.
286
+ }
287
+ finally {
288
+ this.notifyingHistoryGroup = false;
289
+ }
290
+ }
291
+ withHistoryGroup(handle, runMember) {
292
+ this.assertHistoryGroupBoundaryIdle();
293
+ const group = this.requireHistoryGroup(handle);
294
+ const before = group.status;
295
+ this.enrollingHistoryGroup = group;
296
+ try {
297
+ return runMember();
298
+ }
299
+ finally {
300
+ this.enrollingHistoryGroup = undefined;
301
+ if (group.status !== before) {
302
+ this.notifyHistoryGroup(group);
303
+ }
304
+ }
305
+ }
306
+ createGroupedHistory(members) {
307
+ const sourceBatches = [];
308
+ const sourceSliceIds = new Map();
309
+ const slices = [];
310
+ members.forEach((member, memberIndex) => {
311
+ const batches = this.orderHistorySourceBatchesByDeliverySequence(member, this.historySourceBatches(this.deliveredHistoryRecords(member)));
312
+ const memberSlices = new Map();
313
+ let atomicSliceId;
314
+ batches.forEach((batch) => {
315
+ const sourceSliceId = `${memberIndex}:${batch.sliceId}`;
316
+ const isAtomicMemberBatch = !member.progressiveDeliverySequence &&
317
+ batch.sharedDelivery === 'transaction-end';
318
+ if (isAtomicMemberBatch) {
319
+ atomicSliceId ?? (atomicSliceId = sourceSliceId);
320
+ }
321
+ else {
322
+ atomicSliceId = undefined;
323
+ }
324
+ const sliceId = atomicSliceId ?? sourceSliceId;
325
+ sourceSliceIds.set(batch.batchId, sliceId);
326
+ const ids = memberSlices.get(sliceId) ?? [];
327
+ ids.push(...batch.deliveries.map(({ deliveryId }) => deliveryId));
328
+ memberSlices.set(sliceId, ids);
329
+ sourceBatches.push(batch);
330
+ });
331
+ memberSlices.forEach((orderedIds, sliceId) => slices.push({ sliceId, orderedIds }));
332
+ });
333
+ return {
334
+ // Reuse immutable owner evidence. Only the index of references is joined.
335
+ entries: members.flatMap((member) => member.entries),
336
+ sourceBatches: Object.freeze(sourceBatches),
337
+ sourceSliceIds,
338
+ ...(slices.length > 0
339
+ ? {
340
+ progressiveDeliverySequence: deepFreezeValue({
341
+ mode: 'progressive',
342
+ ...(members.some((member) => member.progressiveDeliverySequence?.batchPublications ===
343
+ false)
344
+ ? { batchPublications: false }
345
+ : {}),
346
+ slices
347
+ })
348
+ }
349
+ : {})
350
+ };
351
+ }
352
+ endHistoryGroup(handle) {
353
+ this.assertHistoryGroupBoundaryIdle();
354
+ const group = this.requireHistoryGroup(handle);
355
+ const history = this.createGroupedHistory(group.members);
356
+ group.members = [];
357
+ group.status = Object.freeze({ ...group.status, state: 'closed' });
358
+ if (group.status.memberCount > 0) {
359
+ this.undoStack.push(history);
360
+ this.redoStack = [];
361
+ this.actionId += 1;
362
+ this.onUserActionCompleted?.({
363
+ actionId: this.actionId,
364
+ changeCount: group.status.changeCount,
365
+ timestamp: Date.now()
366
+ });
367
+ }
368
+ this.notifyHistoryGroup(group);
369
+ group.options = {};
370
+ return group.status;
371
+ }
223
372
  start(origin) {
224
373
  if (this.sharedEvidenceNotificationDepth > 0) {
225
374
  throw new Error('Factory shared evidence observers cannot start a canonical transaction');
@@ -235,6 +384,7 @@ class DataTransact {
235
384
  }
236
385
  this.activeOrigin = origin ?? 'action';
237
386
  this.journal = [];
387
+ this.nextImmediateDeliveryJournalIndex = 0;
238
388
  this.replaceLatestHistoryStages.clear();
239
389
  this.preparedActionHistoryEntries = null;
240
390
  this.pendingImmediatePublicationEntries.length = 0;
@@ -367,7 +517,7 @@ class DataTransact {
367
517
  }
368
518
  const deliveryHandle = this.activeDeliveryHandle ?? null;
369
519
  const journalStart = this.journal.length;
370
- const trustedOwnerValues = isDetachedTransactionValue(events);
520
+ const trustedOwnerValues = this.events.isDetachedTransactionValue(events);
371
521
  let batchAccepted = false;
372
522
  try {
373
523
  const ownerHandoff = measureBrowserDragPhase('factory:owner-batch-clone', () => isDeeplyFrozenValue(events)
@@ -399,12 +549,30 @@ class DataTransact {
399
549
  recordedEntries.some((entry) => entry.source === 'action')) {
400
550
  throw new Error('Nested undo or redo cannot accept a new action mutation');
401
551
  }
402
- const immediateEntries = this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence
403
- ? []
404
- : recordedEntries.filter((entry) => entry.shared && entry.options.sharedDelivery === 'immediate');
405
- this.deliverSharedEntries(immediateEntries, immediateEntries.length > 0
406
- ? `${this.currentArtifactId}:owner-batch:${journalStart}`
407
- : undefined);
552
+ let lastImmediateEntry;
553
+ for (const entry of recordedEntries) {
554
+ if (entry.shared && entry.options.sharedDelivery === 'immediate') {
555
+ lastImmediateEntry = entry;
556
+ }
557
+ }
558
+ const immediateEntries = [];
559
+ if (lastImmediateEntry &&
560
+ !(this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence)) {
561
+ // Immediate delivery is an ordered journal frontier, not a priority lane.
562
+ // Earlier deferred writes may be prerequisites of this completed mutation.
563
+ for (let index = this.nextImmediateDeliveryJournalIndex; index <= lastImmediateEntry.index; index += 1) {
564
+ const entry = this.journal[index];
565
+ if (!entry?.shared) {
566
+ continue;
567
+ }
568
+ if (entry.shared.records.some((record) => !record.delivered)) {
569
+ entry.options.sharedDelivery = 'immediate';
570
+ immediateEntries.push(entry);
571
+ }
572
+ }
573
+ this.nextImmediateDeliveryJournalIndex = lastImmediateEntry.index + 1;
574
+ }
575
+ this.deliverSharedEntries(immediateEntries);
408
576
  this.queueImmediatePublicationEntries(immediateEntries.filter((entry) => entry.shared?.records.some((record) => record.delivered)));
409
577
  return recordedEntries.length > 0 ? deliveryHandle : null;
410
578
  }
@@ -419,14 +587,17 @@ class DataTransact {
419
587
  }
420
588
  stageReplaceLatestHistory(events, journalIndexes) {
421
589
  const firstEvent = events[0];
422
- if (!firstEvent)
590
+ if (!firstEvent) {
423
591
  return;
592
+ }
424
593
  const history = firstEvent.options?.history;
425
594
  const candidate = firstEvent.historyCandidate;
426
- if (!history && !candidate)
595
+ if (!history && !candidate) {
427
596
  return;
428
- if (history?.mode !== 'replace-latest' || !candidate)
597
+ }
598
+ if (history?.mode !== 'replace-latest' || !candidate) {
429
599
  return;
600
+ }
430
601
  let stage = this.replaceLatestHistoryStages.get(history.key);
431
602
  if (!stage) {
432
603
  stage = {
@@ -473,8 +644,9 @@ class DataTransact {
473
644
  evidence.sharedRecords.length === 0) {
474
645
  throw new Error(`Factory mutation delivery evidence ${eventIndex} requires at least one shared record`);
475
646
  }
476
- if (!evidence.sharedRecords)
647
+ if (!evidence.sharedRecords) {
477
648
  return;
649
+ }
478
650
  const firstOccurrences = [];
479
651
  const seenOccurrences = new Set();
480
652
  evidence.sharedRecords.forEach((record, recordIndex) => {
@@ -606,8 +778,9 @@ class DataTransact {
606
778
  const firstEvent = stage.firstEventsByKey.get(eventKey);
607
779
  const latestEvent = stage.latestEventsByKey.get(eventKey);
608
780
  const payload = this.mergeReplaceLatestHistoryPayload(firstEvent.payload, latestEvent.payload);
609
- if (!payload)
781
+ if (!payload) {
610
782
  return;
783
+ }
611
784
  const { history: _history, ...options } = latestEvent.options ?? {};
612
785
  entries.push(this.createJournalEntry({
613
786
  type: latestEvent.type,
@@ -621,8 +794,9 @@ class DataTransact {
621
794
  }
622
795
  prepareReplaceLatestHistorySourceBatches(entries) {
623
796
  const sharedEntries = entries.filter((entry) => entry.shared);
624
- if (sharedEntries.length === 0)
797
+ if (sharedEntries.length === 0) {
625
798
  return;
799
+ }
626
800
  const unsupportedEntry = sharedEntries.find((entry) => entry.options.sharedDelivery !== 'immediate');
627
801
  if (unsupportedEntry) {
628
802
  throw new Error('Factory replace-latest shared History requires immediate delivery');
@@ -654,8 +828,9 @@ class DataTransact {
654
828
  entries.push(entry);
655
829
  return;
656
830
  }
657
- if (emittedKeys.has(history.key))
831
+ if (emittedKeys.has(history.key)) {
658
832
  return;
833
+ }
659
834
  emittedKeys.add(history.key);
660
835
  const materialized = this.materializeReplaceLatestHistoryStage(stage, nextSyntheticIndex);
661
836
  nextSyntheticIndex += materialized.length;
@@ -749,11 +924,13 @@ class DataTransact {
749
924
  return;
750
925
  }
751
926
  const sharedInverseEvents = entry.shared?.inverseEvents;
752
- if (sharedInverseEvents?.length !== 1)
927
+ if (sharedInverseEvents?.length !== 1) {
753
928
  return;
929
+ }
754
930
  const inverseEvent = sharedInverseEvents[0];
755
- if (!inverseEvent)
931
+ if (!inverseEvent) {
756
932
  return;
933
+ }
757
934
  const inversePayload = inverseEvent.payload;
758
935
  const recordPayload = record.change;
759
936
  let projectedCollection;
@@ -801,8 +978,9 @@ class DataTransact {
801
978
  })
802
979
  };
803
980
  }
804
- if (!projectedCollection)
981
+ if (!projectedCollection) {
805
982
  return;
983
+ }
806
984
  return freezeReplayEvents([
807
985
  {
808
986
  ...inverseEvent,
@@ -833,11 +1011,13 @@ class DataTransact {
833
1011
  }
834
1012
  createForwardSharedDelivery({ entry, record }, batchId) {
835
1013
  const shared = entry.shared;
836
- if (!shared)
1014
+ if (!shared) {
837
1015
  return;
1016
+ }
838
1017
  const evidence = record.evidence;
839
- if (!evidence)
1018
+ if (!evidence) {
840
1019
  return;
1020
+ }
841
1021
  return deepFreezeValue({
842
1022
  deliveryId: evidence.deliveryId,
843
1023
  artifactId: this.currentArtifactId,
@@ -959,13 +1139,15 @@ class DataTransact {
959
1139
  return this.activeDeliverySequence.slices.flatMap(({ sliceId }) => recordsBySlice.get(sliceId) ?? []);
960
1140
  }
961
1141
  deliverySliceIdForRecord({ entry, record }) {
962
- if (entry.options.sharedDelivery === 'immediate')
963
- return;
1142
+ if (entry.options.sharedDelivery === 'immediate') {
1143
+ return `${this.currentArtifactId}:immediate:${this.immediatePublicationToken}`;
1144
+ }
964
1145
  if (this.activeDeliverySequence?.mode === 'atomic') {
965
1146
  return this.activeDeliverySequence.slices[0]?.sliceId;
966
1147
  }
967
- if (this.activeDeliverySequence?.mode !== 'progressive')
1148
+ if (this.activeDeliverySequence?.mode !== 'progressive') {
968
1149
  return;
1150
+ }
969
1151
  if (record.orderedIds.length === 0) {
970
1152
  throw new Error(`Factory mutation shared record ${this.sharedRecordId(entry, record)} is not assigned to a progressive delivery slice`);
971
1153
  }
@@ -982,17 +1164,17 @@ class DataTransact {
982
1164
  }
983
1165
  return [...sliceIds][0];
984
1166
  }
985
- prepareSharedDeliveryBatches(entries, orderedRecords, deliverySliceIdOverride) {
1167
+ prepareSharedDeliveryBatches(entries, orderedRecords) {
986
1168
  const records = orderedRecords ?? this.sharedRecordRefs(entries);
987
1169
  const preparedBatches = [];
988
1170
  const seenBatchIds = new Set();
989
1171
  const deliverySliceIds = new Map();
990
1172
  records.forEach((recordRef) => {
991
1173
  const sliceId = recordRef.record.batch?.sliceId ??
992
- deliverySliceIdOverride ??
993
1174
  this.deliverySliceIdForRecord(recordRef);
994
- if (!sliceId)
1175
+ if (!sliceId) {
995
1176
  return;
1177
+ }
996
1178
  if (this.activeDeliverySequence &&
997
1179
  recordRef.entry.options.sharedDelivery !== 'immediate' &&
998
1180
  !this.activeDeliverySliceOrder.has(sliceId)) {
@@ -1068,8 +1250,9 @@ class DataTransact {
1068
1250
  deliverPreparedSharedBatch(batch) {
1069
1251
  const historyReplayState = this.historyReplaySharedState?.batchStateById.get(batch.batchId);
1070
1252
  if (historyReplayState) {
1071
- if (historyReplayState.delivered)
1253
+ if (historyReplayState.delivered) {
1072
1254
  return true;
1255
+ }
1073
1256
  if (historyReplayState.readyReadinessKeys.size !==
1074
1257
  historyReplayState.requiredReadinessKeys.size) {
1075
1258
  return false;
@@ -1077,8 +1260,9 @@ class DataTransact {
1077
1260
  this.sharedEvidenceNotificationDepth += 1;
1078
1261
  try {
1079
1262
  const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
1080
- if (!delivered)
1263
+ if (!delivered) {
1081
1264
  return false;
1265
+ }
1082
1266
  historyReplayState.delivered = true;
1083
1267
  if (this.transactionOrigin() !== 'remote') {
1084
1268
  this.onSharedDeliveryBatch?.(batch);
@@ -1090,13 +1274,15 @@ class DataTransact {
1090
1274
  }
1091
1275
  }
1092
1276
  const records = (this.preparedSharedBatchRecords.get(batch.batchId) ?? []).filter(({ record }) => !record.delivered);
1093
- if (records.length === 0)
1277
+ if (records.length === 0) {
1094
1278
  return true;
1279
+ }
1095
1280
  this.sharedEvidenceNotificationDepth += 1;
1096
1281
  try {
1097
1282
  const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
1098
- if (!delivered)
1283
+ if (!delivered) {
1099
1284
  return false;
1285
+ }
1100
1286
  records.forEach(({ record }) => {
1101
1287
  record.delivered = true;
1102
1288
  });
@@ -1109,8 +1295,8 @@ class DataTransact {
1109
1295
  this.sharedEvidenceNotificationDepth -= 1;
1110
1296
  }
1111
1297
  }
1112
- deliverSharedEntries(entries, deliverySliceIdOverride) {
1113
- this.prepareSharedDeliveryBatches(entries, undefined, deliverySliceIdOverride).forEach((batch) => this.deliverPreparedSharedBatch(batch));
1298
+ deliverSharedEntries(entries) {
1299
+ this.prepareSharedDeliveryBatches(entries).forEach((batch) => this.deliverPreparedSharedBatch(batch));
1114
1300
  }
1115
1301
  prepareTransactionEndDeliveryIndex() {
1116
1302
  if (this.transactionEndDeliveryBatches) {
@@ -1186,12 +1372,14 @@ class DataTransact {
1186
1372
  : [`delivery:${deliveryId}`]));
1187
1373
  }
1188
1374
  publicationWindowWouldExceedTarget(pendingWorkItemKeys, currentWorkItemKeys, maxItemsPerPublication = DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS) {
1189
- if (pendingWorkItemKeys.size === 0)
1375
+ if (pendingWorkItemKeys.size === 0) {
1190
1376
  return false;
1377
+ }
1191
1378
  let distinctCount = pendingWorkItemKeys.size;
1192
1379
  for (const workItemKey of currentWorkItemKeys) {
1193
- if (!pendingWorkItemKeys.has(workItemKey))
1380
+ if (!pendingWorkItemKeys.has(workItemKey)) {
1194
1381
  distinctCount += 1;
1382
+ }
1195
1383
  }
1196
1384
  return distinctCount > maxItemsPerPublication;
1197
1385
  }
@@ -1203,8 +1391,9 @@ class DataTransact {
1203
1391
  flushPendingProgressivePublication() {
1204
1392
  const records = this.pendingProgressivePublicationRecords.splice(0);
1205
1393
  this.pendingProgressivePublicationWorkItemKeys.clear();
1206
- if (records.length === 0)
1394
+ if (records.length === 0) {
1207
1395
  return;
1396
+ }
1208
1397
  this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
1209
1398
  this.flushSharedPublications();
1210
1399
  }
@@ -1250,16 +1439,18 @@ class DataTransact {
1250
1439
  }
1251
1440
  }
1252
1441
  nextPublicationId() {
1442
+ this.publicationNamespace ?? (this.publicationNamespace = Array.from(globalThis.crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(16).padStart(8, '0')).join(''));
1253
1443
  this.publicationSequence += 1;
1254
- return `${this.currentTransactionId}:publication:${this.publicationSequence}`;
1444
+ return `${this.publicationNamespace}:${this.currentTransactionId}:publication:${this.publicationSequence}`;
1255
1445
  }
1256
1446
  createSharedPublication(entries, origin = this.transactionOrigin()) {
1257
1447
  return this.createSharedPublicationFromRecords(this.sharedRecordRefs(entries), origin);
1258
1448
  }
1259
1449
  createSharedPublicationFromRecords(records, origin = this.transactionOrigin()) {
1260
1450
  return measureBrowserDragPhase('factory:create-shared-publication', () => {
1261
- if (this.transactionOrigin() === 'remote' || origin === 'remote')
1451
+ if (this.transactionOrigin() === 'remote' || origin === 'remote') {
1262
1452
  return;
1453
+ }
1263
1454
  const publishableRecords = records.filter(({ record }) => {
1264
1455
  if (!record.delivered || record.publicationId !== undefined) {
1265
1456
  return false;
@@ -1270,16 +1461,19 @@ class DataTransact {
1270
1461
  const seenBatchIds = new Set();
1271
1462
  publishableRecords.forEach(({ record }) => {
1272
1463
  const batch = record.batch;
1273
- if (!batch || seenBatchIds.has(batch.batchId))
1464
+ if (!batch || seenBatchIds.has(batch.batchId)) {
1274
1465
  return;
1466
+ }
1275
1467
  seenBatchIds.add(batch.batchId);
1276
1468
  batches.push(batch);
1277
1469
  });
1278
- if (batches.length === 0)
1470
+ if (batches.length === 0) {
1279
1471
  return;
1472
+ }
1280
1473
  const publication = this.createSharedPublicationFromBatches(batches, origin);
1281
- if (!publication)
1474
+ if (!publication) {
1282
1475
  return;
1476
+ }
1283
1477
  publishableRecords.forEach(({ record }) => {
1284
1478
  record.publicationId = publication.publicationId;
1285
1479
  record.compensationPublicationId = `${publication.publicationId}:compensation`;
@@ -1349,19 +1543,22 @@ class DataTransact {
1349
1543
  }
1350
1544
  createHistoryReplaySharedPublication(batches) {
1351
1545
  const state = this.historyReplaySharedState;
1352
- if (!state)
1546
+ if (!state) {
1353
1547
  return;
1548
+ }
1354
1549
  const publishableBatches = batches.filter((batch) => {
1355
1550
  const batchState = state.batchStateById.get(batch.batchId);
1356
1551
  return (batchState?.delivered === true && batchState.publicationId === undefined);
1357
1552
  });
1358
1553
  const publication = this.createSharedPublicationFromBatches(publishableBatches, this.transactionOrigin());
1359
- if (!publication)
1554
+ if (!publication) {
1360
1555
  return;
1556
+ }
1361
1557
  publishableBatches.forEach((batch) => {
1362
1558
  const batchState = state.batchStateById.get(batch.batchId);
1363
- if (!batchState)
1559
+ if (!batchState) {
1364
1560
  return;
1561
+ }
1365
1562
  batchState.publicationId = publication.publicationId;
1366
1563
  batchState.compensationPublicationId = `${publication.publicationId}:compensation`;
1367
1564
  });
@@ -1401,14 +1598,16 @@ class DataTransact {
1401
1598
  this.activeDeliverySequence.slices.length > 0 &&
1402
1599
  options.includeActiveSequence !== false &&
1403
1600
  (batches.length === 0 || activeSequenceBatches.length > 0)) {
1404
- if (batches.length === 0)
1601
+ if (batches.length === 0) {
1405
1602
  return this.activeDeliverySequence;
1603
+ }
1406
1604
  return measureBrowserDragPhase('factory:select-delivery-sequence-boundaries', () => {
1407
1605
  const seenSliceIds = new Set();
1408
1606
  const slices = [];
1409
1607
  activeSequenceBatches.forEach((batch) => {
1410
- if (seenSliceIds.has(batch.sliceId))
1608
+ if (seenSliceIds.has(batch.sliceId)) {
1411
1609
  return;
1610
+ }
1412
1611
  const boundary = this.activeDeliveryBoundaryBySliceId.get(batch.sliceId);
1413
1612
  if (!boundary) {
1414
1613
  throw new Error(`Factory mutation delivery slice is unknown: ${batch.sliceId}`);
@@ -1429,8 +1628,9 @@ class DataTransact {
1429
1628
  if (options.orderedIdsFromRecords) {
1430
1629
  const seenOrderedIds = seenSliceOrderedIds.get(batch.sliceId) ?? new Set();
1431
1630
  batch.records.forEach((record) => [...record.orderedIds].reverse().forEach((orderedId) => {
1432
- if (seenOrderedIds.has(orderedId))
1631
+ if (seenOrderedIds.has(orderedId)) {
1433
1632
  return;
1633
+ }
1434
1634
  seenOrderedIds.add(orderedId);
1435
1635
  orderedIds.push(orderedId);
1436
1636
  }));
@@ -1456,16 +1656,18 @@ class DataTransact {
1456
1656
  if (this.activeDeliverySequence?.mode === 'progressive') {
1457
1657
  return this.activeDeliverySequence;
1458
1658
  }
1459
- if (this.activeDeliverySequence?.batchPublications !== false)
1659
+ if (this.activeDeliverySequence?.batchPublications !== false) {
1460
1660
  return;
1661
+ }
1461
1662
  const deliveryIdsBySlice = new Map();
1462
1663
  this.currentSharedDeliveryBatches.forEach((batch) => {
1463
1664
  const deliveryIds = deliveryIdsBySlice.get(batch.sliceId) ?? [];
1464
1665
  deliveryIds.push(...batch.deliveries.map((delivery) => delivery.deliveryId));
1465
1666
  deliveryIdsBySlice.set(batch.sliceId, deliveryIds);
1466
1667
  });
1467
- if (deliveryIdsBySlice.size === 0)
1668
+ if (deliveryIdsBySlice.size === 0) {
1468
1669
  return;
1670
+ }
1469
1671
  return deepFreezeValue({
1470
1672
  mode: 'progressive',
1471
1673
  batchPublications: false,
@@ -1476,19 +1678,22 @@ class DataTransact {
1476
1678
  });
1477
1679
  }
1478
1680
  queueImmediatePublicationEntries(entries) {
1479
- if (entries.length === 0)
1681
+ if (entries.length === 0) {
1480
1682
  return;
1683
+ }
1481
1684
  this.pendingImmediatePublicationEntries.push(...entries);
1482
1685
  const token = this.immediatePublicationToken;
1483
- if (this.scheduledImmediatePublicationToken === token)
1686
+ if (this.scheduledImmediatePublicationToken === token) {
1484
1687
  return;
1688
+ }
1485
1689
  this.scheduledImmediatePublicationToken = token;
1486
1690
  queueMicrotask(() => {
1487
1691
  if (this.scheduledImmediatePublicationToken === token) {
1488
1692
  this.scheduledImmediatePublicationToken = null;
1489
1693
  }
1490
- if (token !== this.immediatePublicationToken)
1694
+ if (token !== this.immediatePublicationToken) {
1491
1695
  return;
1696
+ }
1492
1697
  this.queuePendingImmediatePublication();
1493
1698
  this.flushSharedPublications();
1494
1699
  });
@@ -1497,8 +1702,9 @@ class DataTransact {
1497
1702
  this.scheduledImmediatePublicationToken = null;
1498
1703
  this.immediatePublicationToken += 1;
1499
1704
  const entries = this.pendingImmediatePublicationEntries.splice(0);
1500
- if (entries.length === 0)
1705
+ if (entries.length === 0) {
1501
1706
  return;
1707
+ }
1502
1708
  const records = this.sharedRecordRefs(entries).filter(({ record }) => record.delivered && record.publicationId === undefined);
1503
1709
  const workItemKeys = this.sharedRecordPublicationWorkItemKeys(records);
1504
1710
  if (records.length > 0 &&
@@ -1518,8 +1724,9 @@ class DataTransact {
1518
1724
  flushPendingImmediatePublication() {
1519
1725
  const records = this.pendingImmediatePublicationRecords.splice(0);
1520
1726
  this.pendingImmediatePublicationWorkItemKeys.clear();
1521
- if (records.length === 0)
1727
+ if (records.length === 0) {
1522
1728
  return;
1729
+ }
1523
1730
  this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
1524
1731
  this.flushSharedPublications();
1525
1732
  }
@@ -1531,8 +1738,9 @@ class DataTransact {
1531
1738
  this.pendingImmediatePublicationWorkItemKeys.clear();
1532
1739
  }
1533
1740
  queueSharedPublication(publication) {
1534
- if (!publication)
1741
+ if (!publication) {
1535
1742
  return;
1743
+ }
1536
1744
  this.pendingSharedPublications.push(publication);
1537
1745
  }
1538
1746
  queueUnacknowledgedSharedPublications() {
@@ -1549,8 +1757,9 @@ class DataTransact {
1549
1757
  }
1550
1758
  }
1551
1759
  flushSharedPublications() {
1552
- if (this.emittingSharedPublications)
1760
+ if (this.emittingSharedPublications) {
1553
1761
  return;
1762
+ }
1554
1763
  this.emittingSharedPublications = true;
1555
1764
  try {
1556
1765
  let publication;
@@ -1581,12 +1790,14 @@ class DataTransact {
1581
1790
  }
1582
1791
  }
1583
1792
  emitCompensationSharedDelivery({ entry, record }, eventName, payload, compensationIndex, batchId) {
1584
- if (this.transactionOrigin() === 'remote')
1793
+ if (this.transactionOrigin() === 'remote') {
1585
1794
  return;
1795
+ }
1586
1796
  const shared = entry.shared;
1587
1797
  const evidence = record.evidence;
1588
- if (!shared || !evidence)
1798
+ if (!shared || !evidence) {
1589
1799
  return;
1800
+ }
1590
1801
  const forwardDelivery = record.delivery;
1591
1802
  const deliveryId = forwardDelivery?.compensationDeliveryIds?.[compensationIndex] ??
1592
1803
  this.compensationDeliveryId(entry, record, compensationIndex);
@@ -1789,20 +2000,23 @@ class DataTransact {
1789
2000
  const previousApplyingReplayEvent = this.applyingReplayEvent;
1790
2001
  this.applyingReplayEvent = true;
1791
2002
  try {
1792
- return runInTransactionReplayMode(mode, () => {
2003
+ return this.events.runInTransactionReplayMode(mode, () => {
1793
2004
  const result = this.onReplayEvent?.(event, mode);
1794
2005
  const handled = typeof result === 'object' ? result.handled : result === true;
1795
2006
  const applied = typeof result === 'object' ? result.applied : result === true;
1796
2007
  if (handled) {
1797
2008
  if (applied) {
1798
- acknowledgeTransactionReplayApplied();
2009
+ this.events.acknowledgeTransactionReplayApplied();
1799
2010
  }
1800
- publishEventToObservers(event);
2011
+ this.events.publishEventToObservers(event);
1801
2012
  }
1802
2013
  else {
1803
- publishEvent(event);
2014
+ this.events.publishEvent(event);
1804
2015
  }
1805
- return isTransactionReplayApplied();
2016
+ return {
2017
+ applied: this.events.isTransactionReplayApplied(),
2018
+ restorationEvents: this.events.getTransactionReplayRestorationEvents()
2019
+ };
1806
2020
  });
1807
2021
  }
1808
2022
  finally {
@@ -1813,10 +2027,13 @@ class DataTransact {
1813
2027
  const previousApplyingReplayEvent = this.applyingReplayEvent;
1814
2028
  this.applyingReplayEvent = true;
1815
2029
  try {
1816
- return runInTransactionReplayMode(mode, () => {
1817
- applyEventBatchToSynchronousOwners(events);
1818
- publishEventsToObservers(events);
1819
- return isTransactionReplayApplied();
2030
+ return this.events.runInTransactionReplayMode(mode, () => {
2031
+ this.events.applyEventBatchToSynchronousOwners(events);
2032
+ this.events.publishEventsToObservers(events);
2033
+ return {
2034
+ applied: this.events.isTransactionReplayApplied(),
2035
+ restorationEvents: this.events.getTransactionReplayRestorationEvents()
2036
+ };
1820
2037
  });
1821
2038
  }
1822
2039
  finally {
@@ -1824,8 +2041,9 @@ class DataTransact {
1824
2041
  }
1825
2042
  }
1826
2043
  replayStepSourceSliceId(step) {
1827
- if (!step.shared || 'suppress' in step.shared)
2044
+ if (!step.shared || 'suppress' in step.shared) {
1828
2045
  return;
2046
+ }
1829
2047
  const sliceIds = new Set();
1830
2048
  step.shared.records.forEach(({ readinessKey }) => {
1831
2049
  const states = this.historyReplaySharedState?.batchStatesByReadinessKey.get(readinessKey) ?? [];
@@ -1857,8 +2075,9 @@ class DataTransact {
1857
2075
  }
1858
2076
  for (let replayOutputIndex = 0; replayOutputIndex < replayEvents.length; replayOutputIndex += 1) {
1859
2077
  const replayEvent = replayEvents[replayOutputIndex];
1860
- if (!replayEvent)
2078
+ if (!replayEvent) {
1861
2079
  continue;
2080
+ }
1862
2081
  const shared = sharedOutputs?.[replayOutputIndex];
1863
2082
  let restorationEvents;
1864
2083
  const mustValidateReplayOutput = restorationBatches !== undefined ||
@@ -1894,11 +2113,12 @@ class DataTransact {
1894
2113
  }
1895
2114
  for (let stepIndex = 0; stepIndex < preparedSteps.length; stepIndex += 1) {
1896
2115
  const firstStep = preparedSteps[stepIndex];
1897
- if (!firstStep)
2116
+ if (!firstStep) {
1898
2117
  continue;
2118
+ }
1899
2119
  const firstEventType = firstStep.replayEvent.type;
1900
2120
  const firstSourceSliceId = this.replayStepSourceSliceId(firstStep);
1901
- const mayUseOwnerBatch = hasSynchronousEventBatchHandler(firstEventType) &&
2121
+ const mayUseOwnerBatch = this.events.hasSynchronousEventBatchHandler(firstEventType) &&
1902
2122
  (this.canReplayEventBatch?.(firstEventType) ??
1903
2123
  this.onReplayEvent === undefined);
1904
2124
  const ownerBatch = [firstStep];
@@ -1918,38 +2138,53 @@ class DataTransact {
1918
2138
  const previousRetainingHistoryReplaySharedEvidence = this.retainingHistoryReplaySharedEvidence;
1919
2139
  const isRetainedHistoryReplay = this.historyReplaySharedState?.ownsReplayEvidence === true;
1920
2140
  this.retainingHistoryReplaySharedEvidence = isRetainedHistoryReplay;
2141
+ let restorationRecorded = false;
2142
+ const retainRestoration = (events) => {
2143
+ if (restorationRecorded) {
2144
+ return;
2145
+ }
2146
+ restorationRecorded = true;
2147
+ if (events) {
2148
+ restorationBatches?.push([...events]);
2149
+ }
2150
+ else {
2151
+ appliedSteps.forEach(({ restorationEvents }) => {
2152
+ if (restorationEvents) {
2153
+ restorationBatches?.push(restorationEvents);
2154
+ }
2155
+ });
2156
+ }
2157
+ };
1921
2158
  try {
1922
- const applied = appliedSteps.length > 1
2159
+ const result = appliedSteps.length > 1
1923
2160
  ? this.applyReplayEventBatch(appliedSteps.map(({ replayEvent }) => replayEvent), mode)
1924
2161
  : this.applyReplayEvent(firstStep.replayEvent, mode);
1925
2162
  const recordedEntries = this.journal.slice(journalStart);
1926
2163
  if (isRetainedHistoryReplay) {
1927
2164
  this.suppressHistoryReplayOwnerSharedEntries(recordedEntries);
1928
2165
  }
1929
- if (applied) {
1930
- appliedSteps.forEach(({ restorationEvents }) => {
1931
- if (restorationEvents) {
1932
- restorationBatches?.push(restorationEvents);
2166
+ if (result.applied) {
2167
+ retainRestoration(result.restorationEvents);
2168
+ }
2169
+ // Successful replay settles retained shared evidence even when the local
2170
+ // owner already has the requested value. Only actual mutation needs rollback.
2171
+ if (isRetainedHistoryReplay) {
2172
+ appliedSteps.forEach(({ shared }) => {
2173
+ if (shared && !('suppress' in shared)) {
2174
+ this.markHistoryReplaySharedReady(shared);
1933
2175
  }
1934
2176
  });
1935
- if (isRetainedHistoryReplay) {
1936
- appliedSteps.forEach(({ shared }) => {
1937
- if (shared && !('suppress' in shared)) {
1938
- this.markHistoryReplaySharedReady(shared);
1939
- }
1940
- });
1941
- let settlement = this.flushNextReadyHistoryReplaySlice();
1942
- while (settlement !== 'none') {
1943
- hasPendingSlicePublication = true;
1944
- settlement.workItemKeys.forEach((workItemKey) => pendingSliceWorkItemKeys.add(workItemKey));
1945
- if (settlement.explicitBoundary ||
1946
- pendingSliceWorkItemKeys.size >= maxItemsPerSlice) {
1947
- hasPendingSlicePublication = false;
1948
- pendingSliceWorkItemKeys.clear();
1949
- yield;
1950
- }
1951
- settlement = this.flushNextReadyHistoryReplaySlice();
2177
+ let settlement = this.flushNextReadyHistoryReplaySlice();
2178
+ while (settlement !== 'none') {
2179
+ hasPendingSlicePublication = true;
2180
+ settlement.workItemKeys.forEach((workItemKey) => pendingSliceWorkItemKeys.add(workItemKey));
2181
+ if (settlement.explicitBoundary ||
2182
+ pendingSliceWorkItemKeys.size >= maxItemsPerSlice) {
2183
+ hasPendingSlicePublication = false;
2184
+ pendingSliceWorkItemKeys.clear();
2185
+ yield;
1952
2186
  }
2187
+ settlement = this.flushNextReadyHistoryReplaySlice();
1953
2188
  }
1954
2189
  }
1955
2190
  }
@@ -1957,12 +2192,8 @@ class DataTransact {
1957
2192
  if (isRetainedHistoryReplay) {
1958
2193
  this.suppressHistoryReplayOwnerSharedEntries(this.journal.slice(journalStart));
1959
2194
  }
1960
- if (wasTransactionReplayApplied(error)) {
1961
- appliedSteps.forEach(({ restorationEvents }) => {
1962
- if (restorationEvents) {
1963
- restorationBatches?.push(restorationEvents);
1964
- }
1965
- });
2195
+ if (this.events.wasTransactionReplayApplied(error)) {
2196
+ retainRestoration(this.events.getFailedTransactionReplayRestorationEvents(error));
1966
2197
  }
1967
2198
  failures.push(error);
1968
2199
  }
@@ -2037,8 +2268,9 @@ class DataTransact {
2037
2268
  }
2038
2269
  compensateDeliveredHistoryReplayBatches() {
2039
2270
  const sharedState = this.historyReplaySharedState;
2040
- if (!sharedState)
2271
+ if (!sharedState) {
2041
2272
  return [];
2273
+ }
2042
2274
  const failures = [];
2043
2275
  const acknowledgedCompensationBatches = [];
2044
2276
  [...sharedState.batchStates]
@@ -2239,8 +2471,9 @@ class DataTransact {
2239
2471
  this.pendingTransactionStatuses.push(payload);
2240
2472
  }
2241
2473
  flushStatuses() {
2242
- if (this.emittingTransactionStatuses)
2474
+ if (this.emittingTransactionStatuses) {
2243
2475
  return;
2476
+ }
2244
2477
  this.emittingTransactionStatuses = true;
2245
2478
  try {
2246
2479
  let payload;
@@ -2307,6 +2540,9 @@ class DataTransact {
2307
2540
  }
2308
2541
  settleRollback(failure, precedingFailures = []) {
2309
2542
  this.discardPendingImmediatePublication();
2543
+ if (failure?.cause instanceof MutationRecoveryError) {
2544
+ precedingFailures = [...precedingFailures, failure.cause];
2545
+ }
2310
2546
  if (this.nestedReplaySourceEvents) {
2311
2547
  this.restoringNestedReplay = true;
2312
2548
  let failures;
@@ -2333,6 +2569,11 @@ class DataTransact {
2333
2569
  return;
2334
2570
  }
2335
2571
  if (this.journal.length === 0) {
2572
+ if (precedingFailures.length) {
2573
+ const rollbackError = new TransactionRollbackError(precedingFailures);
2574
+ this.emitStatus('rollback-failed', failure, rollbackError);
2575
+ throw rollbackError;
2576
+ }
2336
2577
  this.emitStatus('discarded', failure);
2337
2578
  return;
2338
2579
  }
@@ -2418,6 +2659,26 @@ class DataTransact {
2418
2659
  return null;
2419
2660
  }
2420
2661
  const previousRedoStack = this.redoStack;
2662
+ const group = this.enrollingHistoryGroup;
2663
+ if (group) {
2664
+ this.redoStack = [];
2665
+ return {
2666
+ complete: () => {
2667
+ group.members.push(history);
2668
+ const changeCount = group.status.changeCount + committedChanges.length;
2669
+ group.status = Object.freeze({
2670
+ state: 'open',
2671
+ memberCount: group.status.memberCount + 1,
2672
+ changeCount,
2673
+ warningReached: group.options.warningChangeCount !== undefined &&
2674
+ changeCount >= group.options.warningChangeCount
2675
+ });
2676
+ },
2677
+ rollback: () => {
2678
+ this.redoStack = previousRedoStack;
2679
+ }
2680
+ };
2681
+ }
2421
2682
  this.undoStack.push(history);
2422
2683
  this.redoStack = [];
2423
2684
  return {
@@ -2526,8 +2787,9 @@ class DataTransact {
2526
2787
  .length
2527
2788
  ? this.createHistoryReplaySharedPublication(transactionEndBatches)
2528
2789
  : this.createSharedPublication(transactionEndEntries);
2529
- if (publication)
2790
+ if (publication) {
2530
2791
  sharedPublications.push(publication);
2792
+ }
2531
2793
  });
2532
2794
  }
2533
2795
  catch (error) {
@@ -2563,6 +2825,7 @@ class DataTransact {
2563
2825
  this.unacknowledgedSharedPublications.length = 0;
2564
2826
  this.publicationAcknowledgements.clear();
2565
2827
  this.journal = [];
2828
+ this.nextImmediateDeliveryJournalIndex = 0;
2566
2829
  this.replaceLatestHistoryStages.clear();
2567
2830
  this.preparedActionHistoryEntries = null;
2568
2831
  this.rollbackOnly = false;
@@ -2622,17 +2885,22 @@ class DataTransact {
2622
2885
  const seenBatchIds = new Set();
2623
2886
  records.forEach(({ record }) => {
2624
2887
  const batch = record.batch;
2625
- if (!batch || seenBatchIds.has(batch.batchId))
2888
+ if (!batch || seenBatchIds.has(batch.batchId)) {
2626
2889
  return;
2890
+ }
2627
2891
  seenBatchIds.add(batch.batchId);
2628
2892
  batches.push(batch);
2629
2893
  });
2630
2894
  return batches;
2631
2895
  }
2632
2896
  orderHistorySourceBatchesByDeliverySequence(history, batches) {
2897
+ if (history.sourceBatches) {
2898
+ return history.sourceBatches;
2899
+ }
2633
2900
  const sequence = history.progressiveDeliverySequence;
2634
- if (!sequence)
2901
+ if (!sequence) {
2635
2902
  return batches;
2903
+ }
2636
2904
  const batchesBySlice = new Map();
2637
2905
  batches.forEach((batch) => {
2638
2906
  const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
@@ -2701,8 +2969,9 @@ class DataTransact {
2701
2969
  const sourceDeliveries = (direction === 'forward'
2702
2970
  ? sourceBatch.deliveries
2703
2971
  : [...sourceBatch.deliveries].reverse()).filter((delivery) => deliveredSourceIds.has(delivery.deliveryId));
2704
- if (sourceDeliveries.length === 0)
2972
+ if (sourceDeliveries.length === 0) {
2705
2973
  return;
2974
+ }
2706
2975
  const batchId = this.nextDeliveryBatchId();
2707
2976
  let replayRecordOccurrence = 0;
2708
2977
  const replayRecords = sourceDeliveries.flatMap((sourceDelivery) => {
@@ -2776,11 +3045,10 @@ class DataTransact {
2776
3045
  sharedDelivery: sourceBatch.sharedDelivery,
2777
3046
  compensationDeliveryIds: deepFreezeValue(record.inverseEvents.map((_event, inverseIndex) => `${record.deliveryId}:compensation:${inverseIndex}`))
2778
3047
  })));
3048
+ const sourceSliceId = history.sourceSliceIds?.get(sourceBatch.batchId) ?? sourceBatch.sliceId;
2779
3049
  const batch = deepFreezeValue({
2780
3050
  batchId,
2781
- sliceId: direction === 'forward'
2782
- ? sourceBatch.sliceId
2783
- : `${sourceBatch.sliceId}:inverse`,
3051
+ sliceId: direction === 'forward' ? sourceSliceId : `${sourceSliceId}:inverse`,
2784
3052
  artifactId: this.currentArtifactId,
2785
3053
  transactionId: this.currentTransactionId,
2786
3054
  origin: this.transactionOrigin(),
@@ -2822,14 +3090,17 @@ class DataTransact {
2822
3090
  }
2823
3091
  flushNextReadyHistoryReplaySlice() {
2824
3092
  const sharedState = this.historyReplaySharedState;
2825
- if (!sharedState)
3093
+ if (!sharedState) {
2826
3094
  return 'none';
3095
+ }
2827
3096
  const firstUndeliveredIndex = sharedState.batchStates.findIndex((state) => !state.delivered);
2828
- if (firstUndeliveredIndex < 0)
3097
+ if (firstUndeliveredIndex < 0) {
2829
3098
  return 'none';
3099
+ }
2830
3100
  const firstUndeliveredState = sharedState.batchStates[firstUndeliveredIndex];
2831
- if (!firstUndeliveredState)
3101
+ if (!firstUndeliveredState) {
2832
3102
  return 'none';
3103
+ }
2833
3104
  const isProgressive = this.activeDeliverySequence?.mode === 'progressive';
2834
3105
  if (!isProgressive &&
2835
3106
  firstUndeliveredState.batch.sharedDelivery !== 'immediate' &&
@@ -2889,16 +3160,18 @@ class DataTransact {
2889
3160
  flushPendingHistoryReplayPublication() {
2890
3161
  const batches = this.pendingHistoryReplayPublicationBatches.splice(0);
2891
3162
  this.pendingHistoryReplayPublicationWorkItemKeys.clear();
2892
- if (batches.length === 0)
3163
+ if (batches.length === 0) {
2893
3164
  return;
3165
+ }
2894
3166
  const publication = this.createHistoryReplaySharedPublication(batches);
2895
3167
  this.queueSharedPublication(publication);
2896
3168
  this.flushSharedPublications();
2897
3169
  }
2898
3170
  markHistoryReplaySharedReady(sharedReplay) {
2899
3171
  const sharedState = this.historyReplaySharedState;
2900
- if (!sharedState)
3172
+ if (!sharedState) {
2901
3173
  return;
3174
+ }
2902
3175
  sharedReplay.records.forEach(({ readinessKey }) => {
2903
3176
  const states = sharedState.batchStatesByReadinessKey.get(readinessKey) ?? [];
2904
3177
  states.forEach((state) => state.readyReadinessKeys.add(readinessKey));
@@ -2913,13 +3186,15 @@ class DataTransact {
2913
3186
  historySharedReplay(history, direction) {
2914
3187
  const historyChanges = this.historyChanges(history);
2915
3188
  const deliveredRecordsByChange = historyChanges.map((change) => {
2916
- if (!change.shared)
3189
+ if (!change.shared) {
2917
3190
  return [];
3191
+ }
2918
3192
  return change.shared.records.filter((record) => record.delivered && record.delivery && record.evidence);
2919
3193
  });
2920
3194
  return historyChanges.map((change, changeIndex) => {
2921
- if (!change.shared)
3195
+ if (!change.shared) {
2922
3196
  return;
3197
+ }
2923
3198
  const deliveredRecords = deliveredRecordsByChange[changeIndex] ?? [];
2924
3199
  const outputCount = direction === 'forward' ? 1 : (change.inverseEvents?.length ?? 0);
2925
3200
  if (deliveredRecords.length === 0) {
@@ -2941,8 +3216,9 @@ class DataTransact {
2941
3216
  const orderedIds = [];
2942
3217
  const seenOrderedIds = new Set();
2943
3218
  records.forEach((record) => record.orderedIds.forEach((orderedId) => {
2944
- if (seenOrderedIds.has(orderedId))
3219
+ if (seenOrderedIds.has(orderedId)) {
2945
3220
  return;
3221
+ }
2946
3222
  seenOrderedIds.add(orderedId);
2947
3223
  orderedIds.push(orderedId);
2948
3224
  }));
@@ -2970,18 +3246,19 @@ class DataTransact {
2970
3246
  throw new Error(`${direction === 'inverse' ? 'Undo' : 'Redo'} cannot join a non-empty transaction journal`);
2971
3247
  }
2972
3248
  const sourceHistory = sourceStack[sourceStack.length - 1];
2973
- if (!sourceHistory)
3249
+ if (!sourceHistory) {
2974
3250
  return;
3251
+ }
2975
3252
  const maxItemsPerSlice = resolveCooperativeRenderMaxItemsPerSlice(options);
2976
3253
  const sourceChanges = this.historyChanges(sourceHistory);
2977
3254
  const lastChanges = sourceChanges.map(({ event }) => event);
2978
3255
  if (direction === 'inverse') {
2979
3256
  this.inUndo = true;
2980
- updateUndoRedoStatus(UNDO.UNDO);
3257
+ this.events.updateUndoRedoStatus(UNDO.UNDO);
2981
3258
  }
2982
3259
  else {
2983
3260
  this.inRedo = true;
2984
- updateUndoRedoStatus(UNDO.REDO);
3261
+ this.events.updateUndoRedoStatus(UNDO.REDO);
2985
3262
  }
2986
3263
  try {
2987
3264
  this.ensureReplayTransactionId();
@@ -3002,7 +3279,7 @@ class DataTransact {
3002
3279
  throw error;
3003
3280
  }
3004
3281
  finally {
3005
- updateUndoRedoStatus(UNDO.NONE);
3282
+ this.events.updateUndoRedoStatus(UNDO.NONE);
3006
3283
  }
3007
3284
  }
3008
3285
  undoProgressively(yieldAfterSlice, options) {
@@ -3012,6 +3289,9 @@ class DataTransact {
3012
3289
  return this.replayHistoryProgressively('forward', yieldAfterSlice, options);
3013
3290
  }
3014
3291
  undo() {
3292
+ if (this.enrollingHistoryGroup) {
3293
+ throw new Error('Cannot replay history inside a group member');
3294
+ }
3015
3295
  if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
3016
3296
  throw new Error('Remote transaction cannot consume local undo history');
3017
3297
  }
@@ -3024,16 +3304,17 @@ class DataTransact {
3024
3304
  throw new Error('Undo cannot join a non-empty transaction journal');
3025
3305
  }
3026
3306
  const sourceHistory = this.undoStack[this.undoStack.length - 1];
3027
- if (!sourceHistory)
3307
+ if (!sourceHistory) {
3028
3308
  return;
3309
+ }
3029
3310
  const sourceChanges = this.historyChanges(sourceHistory);
3030
3311
  const lastChanges = sourceChanges.map(({ event }) => event);
3031
3312
  let openedBoundary = false;
3032
3313
  this.inUndo = true;
3033
- updateUndoRedoStatus(UNDO.UNDO);
3314
+ this.events.updateUndoRedoStatus(UNDO.UNDO);
3034
3315
  try {
3035
3316
  if (!hasOuterBoundary) {
3036
- startTransaction();
3317
+ this.events.startTransaction();
3037
3318
  openedBoundary = true;
3038
3319
  }
3039
3320
  this.ensureReplayTransactionId();
@@ -3046,7 +3327,7 @@ class DataTransact {
3046
3327
  throw new TransactionRollbackError(failures);
3047
3328
  }
3048
3329
  if (!hasOuterBoundary) {
3049
- endTransaction();
3330
+ this.events.endTransaction();
3050
3331
  openedBoundary = false;
3051
3332
  }
3052
3333
  }
@@ -3057,20 +3338,24 @@ class DataTransact {
3057
3338
  this.rollbackFailure ?? (this.rollbackFailure = failure);
3058
3339
  }
3059
3340
  else if (openedBoundary) {
3060
- endTransaction({ outcome: 'rollback', failure });
3341
+ this.events.endTransaction({ outcome: 'rollback', failure });
3061
3342
  openedBoundary = false;
3062
3343
  }
3063
3344
  throw error;
3064
3345
  }
3065
3346
  finally {
3066
- updateUndoRedoStatus(UNDO.NONE);
3347
+ this.events.updateUndoRedoStatus(UNDO.NONE);
3067
3348
  if (!hasOuterBoundary) {
3068
3349
  this.journal = [];
3350
+ this.nextImmediateDeliveryJournalIndex = 0;
3069
3351
  this.inUndo = false;
3070
3352
  }
3071
3353
  }
3072
3354
  }
3073
3355
  redo() {
3356
+ if (this.enrollingHistoryGroup) {
3357
+ throw new Error('Cannot replay history inside a group member');
3358
+ }
3074
3359
  if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
3075
3360
  throw new Error('Remote transaction cannot consume local redo history');
3076
3361
  }
@@ -3083,16 +3368,17 @@ class DataTransact {
3083
3368
  throw new Error('Redo cannot join a non-empty transaction journal');
3084
3369
  }
3085
3370
  const sourceHistory = this.redoStack[this.redoStack.length - 1];
3086
- if (!sourceHistory)
3371
+ if (!sourceHistory) {
3087
3372
  return;
3373
+ }
3088
3374
  const sourceChanges = this.historyChanges(sourceHistory);
3089
3375
  const lastChanges = sourceChanges.map(({ event }) => event);
3090
3376
  let openedBoundary = false;
3091
3377
  this.inRedo = true;
3092
- updateUndoRedoStatus(UNDO.REDO);
3378
+ this.events.updateUndoRedoStatus(UNDO.REDO);
3093
3379
  try {
3094
3380
  if (!hasOuterBoundary) {
3095
- startTransaction();
3381
+ this.events.startTransaction();
3096
3382
  openedBoundary = true;
3097
3383
  }
3098
3384
  this.ensureReplayTransactionId();
@@ -3105,7 +3391,7 @@ class DataTransact {
3105
3391
  throw new TransactionRollbackError(failures);
3106
3392
  }
3107
3393
  if (!hasOuterBoundary) {
3108
- endTransaction();
3394
+ this.events.endTransaction();
3109
3395
  openedBoundary = false;
3110
3396
  }
3111
3397
  }
@@ -3116,15 +3402,16 @@ class DataTransact {
3116
3402
  this.rollbackFailure ?? (this.rollbackFailure = failure);
3117
3403
  }
3118
3404
  else if (openedBoundary) {
3119
- endTransaction({ outcome: 'rollback', failure });
3405
+ this.events.endTransaction({ outcome: 'rollback', failure });
3120
3406
  openedBoundary = false;
3121
3407
  }
3122
3408
  throw error;
3123
3409
  }
3124
3410
  finally {
3125
- updateUndoRedoStatus(UNDO.NONE);
3411
+ this.events.updateUndoRedoStatus(UNDO.NONE);
3126
3412
  if (!hasOuterBoundary) {
3127
3413
  this.journal = [];
3414
+ this.nextImmediateDeliveryJournalIndex = 0;
3128
3415
  this.inRedo = false;
3129
3416
  }
3130
3417
  }
@@ -3159,6 +3446,8 @@ class DataTransact {
3159
3446
  this.validators.clear();
3160
3447
  }
3161
3448
  dispose() {
3449
+ this.historyGroups = new WeakMap();
3450
+ this.enrollingHistoryGroup = undefined;
3162
3451
  this.discardPendingImmediatePublication();
3163
3452
  this.pendingSharedPublications.length = 0;
3164
3453
  this.unacknowledgedSharedPublications.length = 0;
@@ -3166,6 +3455,7 @@ class DataTransact {
3166
3455
  this.transactionSettlementDepth = 0;
3167
3456
  this.publicationSequence = 0;
3168
3457
  this.journal = [];
3458
+ this.nextImmediateDeliveryJournalIndex = 0;
3169
3459
  this.undoStack = [];
3170
3460
  this.redoStack = [];
3171
3461
  this.isTransacting = 0;