@asyra/scene-tree 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.
Files changed (52) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/component-registry.d.ts.map +1 -1
  3. package/dist/component-registry.js.map +1 -1
  4. package/dist/components/computed.d.ts +3 -1
  5. package/dist/components/computed.d.ts.map +1 -1
  6. package/dist/components/computed.js +9 -6
  7. package/dist/components/computed.js.map +1 -1
  8. package/dist/components/element-change-handler.d.ts.map +1 -1
  9. package/dist/components/element-change-handler.js.map +1 -1
  10. package/dist/components/element.d.ts +3 -1
  11. package/dist/components/element.d.ts.map +1 -1
  12. package/dist/components/element.js +2 -2
  13. package/dist/components/element.js.map +1 -1
  14. package/dist/components/group.d.ts +4 -0
  15. package/dist/components/group.d.ts.map +1 -1
  16. package/dist/components/group.js +61 -3
  17. package/dist/components/group.js.map +1 -1
  18. package/dist/components/props.d.ts +1 -0
  19. package/dist/components/props.d.ts.map +1 -1
  20. package/dist/components/props.js +6 -0
  21. package/dist/components/props.js.map +1 -1
  22. package/dist/components/workspace.d.ts.map +1 -1
  23. package/dist/components/workspace.js +2 -4
  24. package/dist/components/workspace.js.map +1 -1
  25. package/dist/create-dynamic-component.d.ts.map +1 -1
  26. package/dist/create-dynamic-component.js +2 -1
  27. package/dist/create-dynamic-component.js.map +1 -1
  28. package/dist/create-dynamic-props.d.ts.map +1 -1
  29. package/dist/create-dynamic-props.js +6 -0
  30. package/dist/create-dynamic-props.js.map +1 -1
  31. package/dist/element-mutation.d.ts +32 -4
  32. package/dist/element-mutation.d.ts.map +1 -1
  33. package/dist/element-property-input-error.d.ts +8 -0
  34. package/dist/element-property-input-error.d.ts.map +1 -0
  35. package/dist/element-property-input-error.js +11 -0
  36. package/dist/element-property-input-error.js.map +1 -0
  37. package/dist/entity-data.d.ts.map +1 -1
  38. package/dist/entity-data.js.map +1 -1
  39. package/dist/index.d.ts +1 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -0
  42. package/dist/index.js.map +1 -1
  43. package/dist/props-manager-context.d.ts.map +1 -1
  44. package/dist/props-manager-context.js.map +1 -1
  45. package/dist/sceneTree.d.ts +11 -2
  46. package/dist/sceneTree.d.ts.map +1 -1
  47. package/dist/sceneTree.js +529 -94
  48. package/dist/sceneTree.js.map +1 -1
  49. package/dist/subscribes.d.ts.map +1 -1
  50. package/dist/subscribes.js +20 -9
  51. package/dist/subscribes.js.map +1 -1
  52. package/package.json +6 -6
package/dist/sceneTree.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { ElementPropertyInputError } from './element-property-input-error.js';
2
+ import { MutationRecoveryError } from '@asyra/utils';
1
3
  import { EntityTypes, PROPS_ACTIONS, SCENE_TREE_ACTIONS, SharedDataChannelNames, isRecord, measureBrowserDragPhase, setOwnEnumerableValue } from '@asyra/utils';
2
- import { acknowledgeTransactionReplayApplied, EventTypes, getTransactionReplayMode, getTransactionOwner, issueDetachedTransactionOwnerBatch, publishLocalComputedDataEvents, runInTransactionReplayMode, updateTransaction } from '@asyra/reactive-events';
4
+ import { acknowledgeTransactionReplayApplied, EventTypes, getTransactionReplayMode, getTransactionOwner, issueDetachedTransactionOwnerBatch, publishLocalComputedDataEvents, publishLocalSceneTreeChanges, runInTransactionReplayMode, updateTransactionBatch } from '@asyra/reactive-events';
3
5
  import propsManager from '@asyra/props-manager';
4
6
  import * as lodashModule from 'lodash';
5
7
  import componentRegistry from './component-registry.js';
@@ -98,10 +100,12 @@ const createElementBatchSharedRecords = (change) => deepFreezeSceneValue(change.
98
100
  }
99
101
  })));
100
102
  const compareCanonicalString = (left, right) => {
101
- if (left < right)
103
+ if (left < right) {
102
104
  return -1;
103
- if (left > right)
105
+ }
106
+ if (left > right) {
104
107
  return 1;
108
+ }
105
109
  return 0;
106
110
  };
107
111
  const compareElementPropertyRelations = (left, right) => compareCanonicalString(left.ownerElementId, right.ownerElementId) ||
@@ -249,6 +253,8 @@ const toStringArray = (value) => {
249
253
  class SceneTree {
250
254
  constructor(propsManagerOwner = propsManager) {
251
255
  this.propsManagerOwner = propsManagerOwner;
256
+ /** Local projection identity; never persisted or included in shared data. */
257
+ this.projectionOwner = Symbol('SceneTree projection');
252
258
  this._elements = new Map();
253
259
  this._deletedMap = new Map();
254
260
  this.workspace = '';
@@ -354,10 +360,14 @@ class SceneTree {
354
360
  componentId,
355
361
  relationsAfter
356
362
  ]));
357
- return Object.freeze([...this.elementPropertyRelationsByComponentId]
358
- .filter(([componentId, currentRelations]) => (relationsAfterByComponentId.get(componentId) ?? currentRelations)
359
- .length > 0)
360
- .map(([componentId]) => componentId));
363
+ return Object.freeze([
364
+ ...new Set([
365
+ ...this.elementPropertyRelationsByComponentId.keys(),
366
+ ...relationsAfterByComponentId.keys()
367
+ ])
368
+ ].filter((componentId) => (relationsAfterByComponentId.get(componentId) ??
369
+ this.elementPropertyRelationsByComponentId.get(componentId) ??
370
+ []).length > 0));
361
371
  }
362
372
  applyElementPropertyRelationIndexUpdates(updates, direction) {
363
373
  if (updates.length === 0) {
@@ -441,9 +451,11 @@ class SceneTree {
441
451
  const relations = [];
442
452
  const relationTupleKeys = new Set();
443
453
  const requestedElementIds = new Set();
444
- const targetsByPropertyId = new Map();
445
- const getTarget = (propertyId) => {
446
- const existing = targetsByPropertyId.get(propertyId);
454
+ const targetsByOwner = new Map();
455
+ const getTarget = (relation) => {
456
+ const propertyId = relation.componentId;
457
+ const ownerKey = getElementPropertyRelationTupleKey(relation);
458
+ const existing = targetsByOwner.get(ownerKey);
447
459
  if (existing) {
448
460
  return existing;
449
461
  }
@@ -454,7 +466,7 @@ class SceneTree {
454
466
  removeRecordIds: [],
455
467
  removeRecordIdSet: new Set()
456
468
  };
457
- targetsByPropertyId.set(propertyId, target);
469
+ targetsByOwner.set(ownerKey, target);
458
470
  return target;
459
471
  };
460
472
  const addRelation = (relation) => {
@@ -516,7 +528,7 @@ class SceneTree {
516
528
  const resolveTarget = (requestedKey) => {
517
529
  const definition = definitionsByInputKey.get(requestedKey);
518
530
  if (!definition) {
519
- throw new Error(`[SceneTree] Element "${request.elementId}" has no property target for "${requestedKey}"`);
531
+ throw new ElementPropertyInputError(request.elementId, requestedKey);
520
532
  }
521
533
  const propertyId = element.props.getPropId(definition.name);
522
534
  const property = propertyId
@@ -545,9 +557,9 @@ class SceneTree {
545
557
  throw new Error(`[SceneTree] Element "${request.elementId}" property values must be a record`);
546
558
  }
547
559
  Object.entries(sourceValues).forEach(([key, value]) => {
548
- const { propertyId, relation } = resolveTarget(key);
560
+ const { relation } = resolveTarget(key);
549
561
  addRelation(relation);
550
- mergeValue(getTarget(propertyId), key, value);
562
+ mergeValue(getTarget(relation), key, value);
551
563
  });
552
564
  if (request.kind === 'records') {
553
565
  if (!Array.isArray(request.records)) {
@@ -572,7 +584,7 @@ class SceneTree {
572
584
  }
573
585
  const { definition, propertyId, relation } = resolveTarget(recordPatch.key);
574
586
  addRelation(relation);
575
- const target = getTarget(propertyId);
587
+ const target = getTarget(relation);
576
588
  if (target.recordKey !== undefined &&
577
589
  target.recordKey !== definition.name) {
578
590
  throwConflict(propertyId, definition.name);
@@ -602,7 +614,7 @@ class SceneTree {
602
614
  });
603
615
  }
604
616
  });
605
- const mutations = [...targetsByPropertyId.values()].map((target) => {
617
+ const mutations = [...targetsByOwner.values()].map((target) => {
606
618
  if (target.recordKey === undefined) {
607
619
  return {
608
620
  kind: 'values',
@@ -635,6 +647,173 @@ class SceneTree {
635
647
  mutations
636
648
  });
637
649
  }
650
+ resolveElementPropertyBindings(requests) {
651
+ if (!Array.isArray(requests)) {
652
+ throw new Error('[SceneTree] Expected a root binding request batch');
653
+ }
654
+ return cloneAndFreezeSceneValue(requests.map((request) => {
655
+ if (!isRecord(request) ||
656
+ typeof request.elementId !== 'string' ||
657
+ typeof request.propertyName !== 'string') {
658
+ throw new Error('[SceneTree] Invalid root binding request');
659
+ }
660
+ const element = this.getElementById(request.elementId);
661
+ const registration = element && componentRegistry.get(element.get('type'));
662
+ if (!element || !registration) {
663
+ throw new Error('[SceneTree] Missing registered element');
664
+ }
665
+ const componentId = element.props.getPropId(request.propertyName);
666
+ if (!componentId ||
667
+ (request.expectedRootId !== undefined &&
668
+ request.expectedRootId !== componentId)) {
669
+ throw new Error('[SceneTree] Missing or stale element property root');
670
+ }
671
+ const contract = captureElementInsertionRegistrationContract(registration, element.get('type'));
672
+ const definition = contract.effectiveDefinitions.find((definition) => definition.name === request.propertyName);
673
+ if (!definition ||
674
+ this.propsManagerOwner.getPropertyById(componentId)?.get('type') !==
675
+ definition.type) {
676
+ throw new Error('[SceneTree] Invalid registered property binding');
677
+ }
678
+ const relations = this.getElementPropertyRelations(componentId);
679
+ const relation = relations.find((relation) => relation.ownerElementId === request.elementId &&
680
+ relation.ownerPropertyName === request.propertyName);
681
+ if (!relation) {
682
+ throw new Error('[SceneTree] Missing canonical property relation');
683
+ }
684
+ return { relation, shared: relations.length > 1 };
685
+ }));
686
+ }
687
+ prepareElementPropertyBindingMutation(requests) {
688
+ if (!Array.isArray(requests)) {
689
+ throw new Error('[SceneTree] Property binding mutation requires an exact target batch');
690
+ }
691
+ const keys = new Set();
692
+ const entries = [];
693
+ const changesByElement = new Map();
694
+ const relationsBefore = new Map();
695
+ const relationsAfter = new Map();
696
+ const mutableRelations = (id) => {
697
+ let relations = relationsAfter.get(id);
698
+ if (!relations) {
699
+ const current = this.getElementPropertyRelations(id);
700
+ relationsBefore.set(id, current);
701
+ relations = [...current];
702
+ relationsAfter.set(id, relations);
703
+ }
704
+ return relations;
705
+ };
706
+ requests.forEach((request) => {
707
+ if (!isRecord(request) ||
708
+ [
709
+ request.elementId,
710
+ request.propertyName,
711
+ request.propertyType,
712
+ request.before,
713
+ request.after
714
+ ].some((value) => typeof value !== 'string' || value.length === 0)) {
715
+ throw new Error('[SceneTree] Invalid property binding target');
716
+ }
717
+ const tuple = JSON.stringify([request.elementId, request.propertyName]);
718
+ if (keys.has(tuple)) {
719
+ throw new Error('[SceneTree] Duplicate property binding target');
720
+ }
721
+ keys.add(tuple);
722
+ const element = this.getElementById(request.elementId);
723
+ const registration = element && componentRegistry.get(element.get('type'));
724
+ if (!element ||
725
+ !registration ||
726
+ element.props.getPropId(request.propertyName) !== request.before) {
727
+ throw new Error(`[SceneTree] Missing or stale property binding "${request.elementId}.${request.propertyName}"`);
728
+ }
729
+ const contract = captureElementInsertionRegistrationContract(registration, element.get('type'));
730
+ const definition = contract.effectiveDefinitions.find((item) => item.name === request.propertyName);
731
+ const current = this.propsManagerOwner.getPropertyById(request.before);
732
+ const next = this.propsManagerOwner.getPropertyById(request.after);
733
+ if (!definition ||
734
+ definition.type !== request.propertyType ||
735
+ current?.get('type') !== definition.type ||
736
+ (next && next.get('type') !== definition.type)) {
737
+ throw new Error('[SceneTree] Property binding must match its registered root type');
738
+ }
739
+ if (request.before === request.after) {
740
+ return;
741
+ }
742
+ const beforeRelations = mutableRelations(request.before);
743
+ const index = beforeRelations.findIndex((relation) => relation.ownerElementId === request.elementId &&
744
+ relation.ownerPropertyName === request.propertyName);
745
+ if (index < 0) {
746
+ throw new Error('[SceneTree] Missing canonical property relation');
747
+ }
748
+ const [relation] = beforeRelations.splice(index, 1);
749
+ mutableRelations(request.after).push({
750
+ ...relation,
751
+ componentId: request.after
752
+ });
753
+ const changes = changesByElement.get(request.elementId) ?? [];
754
+ changes.push({
755
+ key: request.propertyName,
756
+ before: request.before,
757
+ after: request.after
758
+ });
759
+ changesByElement.set(request.elementId, changes);
760
+ entries.push({
761
+ element,
762
+ request: cloneAndFreezeSceneValue(request),
763
+ registration: contract
764
+ });
765
+ });
766
+ const evidence = [...changesByElement].map(([id, changes]) => ({
767
+ action: SCENE_TREE_ACTIONS.UPDATE_ELEMENT_PROPERTY_BINDINGS,
768
+ eventName: EventTypes.UPDATE_ELEMENT_PROPERTY_BINDINGS,
769
+ id,
770
+ changes
771
+ }));
772
+ const relationIndexUpdates = [...relationsAfter].map(([componentId, after]) => ({
773
+ componentId,
774
+ relationsBefore: relationsBefore.get(componentId) ?? EMPTY_ELEMENT_PROPERTY_RELATIONS,
775
+ relationsAfter: freezeElementPropertyRelations(after)
776
+ }));
777
+ const prepared = cloneAndFreezeSceneValue({
778
+ kind: 'prepared-element-property-binding-mutation',
779
+ orphanRootPropertyIds: relationIndexUpdates
780
+ .filter((update) => update.relationsBefore.length > 0 &&
781
+ update.relationsAfter.length === 0)
782
+ .map((update) => update.componentId),
783
+ retainedRootPropertyIds: this.collectRootPropertyIdsAfterRelationUpdates(relationIndexUpdates),
784
+ orderedElementIds: [...changesByElement.keys()],
785
+ evidence
786
+ });
787
+ this.preparedElementMutationArtifacts.set(prepared, {
788
+ kind: 'element-property-binding-mutation',
789
+ entries,
790
+ relationIndexUpdates
791
+ });
792
+ return prepared;
793
+ }
794
+ prepareCanonicalElementPropertyBindingMutation(changes) {
795
+ if (!Array.isArray(changes)) {
796
+ throw new Error('[SceneTree] Expected canonical binding evidence');
797
+ }
798
+ return this.prepareElementPropertyBindingMutation(changes.flatMap((change) => {
799
+ if (change.action !==
800
+ SCENE_TREE_ACTIONS.UPDATE_ELEMENT_PROPERTY_BINDINGS ||
801
+ change.eventName !== EventTypes.UPDATE_ELEMENT_PROPERTY_BINDINGS ||
802
+ !Array.isArray(change.changes)) {
803
+ throw new Error('[SceneTree] Invalid canonical binding evidence');
804
+ }
805
+ return change.changes.map(({ key, before, after }) => {
806
+ const current = this.propsManagerOwner.getPropertyById(before);
807
+ return {
808
+ elementId: change.id,
809
+ propertyName: key,
810
+ before,
811
+ after,
812
+ propertyType: current?.get('type') ?? ''
813
+ };
814
+ });
815
+ }));
816
+ }
638
817
  prepareElementDataMutation(requests) {
639
818
  const requestedIds = new Set();
640
819
  const entries = [];
@@ -771,7 +950,12 @@ class SceneTree {
771
950
  };
772
951
  });
773
952
  const preparedMutation = this.prepareElementDataMutation(requests);
774
- if (!isEqual(preparedMutation.evidence, changes)) {
953
+ const semanticChanges = changes.map((change) => {
954
+ const semanticChange = { ...change };
955
+ delete semanticChange.options;
956
+ return semanticChange;
957
+ });
958
+ if (!isEqual(preparedMutation.evidence, semanticChanges)) {
775
959
  throw new Error('[SceneTree] Cannot prepare stale canonical element data evidence');
776
960
  }
777
961
  return preparedMutation;
@@ -1148,8 +1332,9 @@ class SceneTree {
1148
1332
  const parentChildrenBefore = new Map();
1149
1333
  const parentIndexByElementId = new Map();
1150
1334
  candidates.forEach(({ parentId, parent }) => {
1151
- if (parentChildrenBefore.has(parentId))
1335
+ if (parentChildrenBefore.has(parentId)) {
1152
1336
  return;
1337
+ }
1153
1338
  const children = Object.freeze([
1154
1339
  ...this.getContainerChildren(parent, `Element removal parent "${parentId}"`)
1155
1340
  ]);
@@ -1231,10 +1416,41 @@ class SceneTree {
1231
1416
  return this.prepareElementRemovalMutation(removals, 'prepared-canonical-element-removal');
1232
1417
  }
1233
1418
  prepareSubtreeRemoval(elementId) {
1419
+ return this.prepareSubtreeRootsRemoval([elementId], false);
1420
+ }
1421
+ prepareSubtreesRemoval(elementIds) {
1422
+ return this.prepareSubtreeRootsRemoval(elementIds, true);
1423
+ }
1424
+ prepareSubtreeRootsRemoval(elementIds, batchLeaves) {
1425
+ if (!Array.isArray(elementIds) ||
1426
+ elementIds.some((id) => typeof id !== 'string' || !id) ||
1427
+ new Set(elementIds).size !== elementIds.length) {
1428
+ throw new Error('[SceneTree] Subtree removal requires unique active element ids');
1429
+ }
1234
1430
  this.validateCanonicalHierarchy();
1431
+ const selected = new Set(elementIds);
1432
+ const roots = elementIds
1433
+ .map((id) => {
1434
+ const element = this.getElementById(id);
1435
+ if (!element || element.get('type') === EntityTypes.WORKSPACE) {
1436
+ throw new Error('[SceneTree] Subtree removal requires active non-Workspace elements');
1437
+ }
1438
+ return element;
1439
+ })
1440
+ .filter((element) => {
1441
+ let parentId = element.get('parentId');
1442
+ while (parentId) {
1443
+ if (selected.has(parentId)) {
1444
+ return false;
1445
+ }
1446
+ parentId = this.getElementById(parentId)?.get('parentId') ?? '';
1447
+ }
1448
+ return true;
1449
+ });
1450
+ const parentIndexes = new Map();
1451
+ const subtrees = roots.map((root) => this.collectSubtreeRemovalEntries(root.get('id'), parentIndexes));
1235
1452
  const relationRevisionBefore = this.elementPropertyRelationRevision;
1236
- const removed = this.collectSubtreeRemovalEntries(elementId);
1237
- const rootEntry = removed[removed.length - 1];
1453
+ const removed = subtrees.flat();
1238
1454
  const removalIds = new Set(removed.map((entry) => entry.elementId));
1239
1455
  const elements = removed.map((entry) => {
1240
1456
  const element = this.getElementById(entry.elementId);
@@ -1256,19 +1472,73 @@ class SceneTree {
1256
1472
  ...this.getContainerChildren(parent, `Subtree removal parent "${parentId}"`)
1257
1473
  ]));
1258
1474
  });
1259
- const rootParentChildrenBefore = parentChildrenBefore.get(rootEntry.parentId);
1260
- if (!rootParentChildrenBefore ||
1261
- rootParentChildrenBefore[rootEntry.index] !== rootEntry.elementId) {
1262
- throw new Error(`[SceneTree] Cannot prepare stale subtree root "${rootEntry.elementId}"`);
1263
- }
1264
1475
  const parentChildrenAfter = new Map([...parentChildrenBefore].map(([parentId, children]) => [
1265
1476
  parentId,
1266
1477
  Object.freeze(children.filter((id) => !removalIds.has(id)))
1267
1478
  ]));
1268
- const rootParentChildrenAfter = parentChildrenAfter.get(rootEntry.parentId);
1269
- if (!rootParentChildrenAfter) {
1270
- throw new Error(`[SceneTree] Cannot prepare subtree parent order for "${rootEntry.elementId}"`);
1479
+ // Evidence follows sequential command semantics, while canonical apply shares
1480
+ // one final parent/relation mutation. Leaf runs use existing batch evidence.
1481
+ const evidence = [];
1482
+ const currentChildren = new Map([...parentChildrenBefore].map(([id, children]) => [id, [...children]]));
1483
+ const currentSiblings = (parentId) => {
1484
+ const children = currentChildren.get(parentId);
1485
+ if (!children) {
1486
+ throw new Error('[SceneTree] Missing prepared parent children');
1487
+ }
1488
+ return children;
1489
+ };
1490
+ let leaves = [];
1491
+ const flushLeaves = () => {
1492
+ if (!leaves.length) {
1493
+ return;
1494
+ }
1495
+ const indexes = new Map();
1496
+ leaves.forEach(({ parentId }) => {
1497
+ if (!indexes.has(parentId)) {
1498
+ indexes.set(parentId, new Map(currentSiblings(parentId).map((id, index) => [id, index])));
1499
+ }
1500
+ });
1501
+ const entries = leaves.map(({ data, parentId, elementId }) => {
1502
+ const index = indexes.get(parentId)?.get(elementId);
1503
+ if (index === undefined) {
1504
+ throw new Error('[SceneTree] Missing prepared removal index');
1505
+ }
1506
+ return { data, parentId, index };
1507
+ });
1508
+ const ids = new Set(leaves.map(({ elementId }) => elementId));
1509
+ new Set(leaves.map(({ parentId }) => parentId)).forEach((parentId) => {
1510
+ currentChildren.set(parentId, currentSiblings(parentId).filter((id) => !ids.has(id)));
1511
+ });
1512
+ evidence.push({
1513
+ action: SCENE_TREE_ACTIONS.REMOVE_ELEMENTS,
1514
+ eventName: EventTypes.REMOVE_ELEMENTS,
1515
+ undoType: EventTypes.ADD_ELEMENTS,
1516
+ undoAction: SCENE_TREE_ACTIONS.ADD_ELEMENTS,
1517
+ entries
1518
+ });
1519
+ leaves = [];
1520
+ };
1521
+ for (const entries of subtrees) {
1522
+ if (batchLeaves && entries.length === 1) {
1523
+ leaves.push(entries[0]);
1524
+ continue;
1525
+ }
1526
+ flushLeaves();
1527
+ const root = entries[entries.length - 1];
1528
+ const siblings = currentSiblings(root.parentId);
1529
+ const index = siblings.indexOf(root.elementId);
1530
+ const after = siblings.filter((id) => id !== root.elementId);
1531
+ currentChildren.set(root.parentId, after);
1532
+ evidence.push({
1533
+ eventName: EventTypes.CHANGE_SUBTREE,
1534
+ elementId: root.elementId,
1535
+ removed: [...entries.slice(0, -1), { ...root, index }],
1536
+ rootParentChildrenAfter: after,
1537
+ action: SCENE_TREE_ACTIONS.REMOVE_SUBTREE,
1538
+ undoAction: SCENE_TREE_ACTIONS.RESTORE_SUBTREE
1539
+ });
1271
1540
  }
1541
+ flushLeaves();
1272
1542
  const relationIndexUpdates = this.prepareElementPropertyRelationRemovalsFromRelations(removed.flatMap(({ data }) => collectElementPropertyRelations(data)));
1273
1543
  const relationReleases = relationIndexUpdates.map(({ componentId, relationsBefore, relationsAfter }) => {
1274
1544
  const retainedTupleKeys = new Set(relationsAfter.map(getElementPropertyRelationTupleKey));
@@ -1280,25 +1550,18 @@ class SceneTree {
1280
1550
  };
1281
1551
  });
1282
1552
  const preparedMutation = cloneAndFreezeSceneValue({
1283
- kind: 'prepared-subtree-removal',
1553
+ kind: batchLeaves
1554
+ ? 'prepared-subtrees-removal'
1555
+ : 'prepared-subtree-removal',
1284
1556
  orderedElementIds: removed.map(({ elementId: id }) => id),
1285
1557
  relationReleases,
1286
1558
  orphanRootPropertyIds: relationReleases
1287
1559
  .filter(({ retainedRelations }) => retainedRelations.length === 0)
1288
1560
  .map(({ componentId }) => componentId),
1289
1561
  retainedRootPropertyIds: this.collectRootPropertyIdsAfterRelationUpdates(relationIndexUpdates),
1290
- evidence: [
1291
- {
1292
- eventName: EventTypes.CHANGE_SUBTREE,
1293
- elementId: rootEntry.elementId,
1294
- removed,
1295
- rootParentChildrenAfter,
1296
- action: SCENE_TREE_ACTIONS.REMOVE_SUBTREE,
1297
- undoAction: SCENE_TREE_ACTIONS.RESTORE_SUBTREE
1298
- }
1299
- ]
1562
+ evidence
1300
1563
  });
1301
- const frozenRemoved = preparedMutation.evidence[0].removed;
1564
+ const frozenRemoved = cloneAndFreezeSceneValue(removed);
1302
1565
  this.preparedElementMutationArtifacts.set(preparedMutation, {
1303
1566
  kind: 'subtree-removal',
1304
1567
  entries: Object.freeze(elements.map((element, index) => Object.freeze({
@@ -1350,9 +1613,17 @@ class SceneTree {
1350
1613
  shared: options?.shared ?? SharedDataChannelNames.SCENE_TREE
1351
1614
  });
1352
1615
  const events = Object.freeze(preparedMutation.evidence.map((payload) => {
1353
- const orderedIds = preparedMutation.kind === 'prepared-element-data-mutation'
1354
- ? Object.freeze([payload.id])
1355
- : preparedMutation.orderedElementIds;
1616
+ let orderedIds = preparedMutation.orderedElementIds;
1617
+ if (preparedMutation.kind === 'prepared-element-data-mutation' ||
1618
+ preparedMutation.kind === 'prepared-element-property-binding-mutation') {
1619
+ orderedIds = Object.freeze([payload.id]);
1620
+ }
1621
+ else if (isElementBatchChange(payload)) {
1622
+ orderedIds = Object.freeze(payload.entries.map(({ data }) => data.id));
1623
+ }
1624
+ else if (payload.eventName === EventTypes.CHANGE_SUBTREE) {
1625
+ orderedIds = Object.freeze(payload.removed.map(({ elementId }) => elementId));
1626
+ }
1356
1627
  const canonicalEvidence = Object.freeze({
1357
1628
  orderedIds,
1358
1629
  ...(isElementBatchChange(payload)
@@ -1367,6 +1638,74 @@ class SceneTree {
1367
1638
  canonicalEvidence
1368
1639
  });
1369
1640
  }));
1641
+ if (artifact.kind === 'element-property-binding-mutation') {
1642
+ artifact.entries.forEach(({ element, request, registration }) => {
1643
+ if (this.getElementById(request.elementId) !== element ||
1644
+ element.props.getPropId(request.propertyName) !== request.before ||
1645
+ !isElementInsertionRegistrationContractCurrent(registration, element.get('type')) ||
1646
+ this.propsManagerOwner.getPropertyById(request.after)?.get('type') !==
1647
+ request.propertyType) {
1648
+ throw new Error(`[SceneTree] Cannot apply missing or stale property binding "${request.elementId}.${request.propertyName}"`);
1649
+ }
1650
+ });
1651
+ artifact.relationIndexUpdates.forEach(({ componentId, relationsBefore }) => {
1652
+ if (this.getElementPropertyRelations(componentId) !== relationsBefore) {
1653
+ throw new Error('[SceneTree] Cannot apply stale property binding relations');
1654
+ }
1655
+ });
1656
+ const restorationEvents = getTransactionReplayMode()
1657
+ ? preparedMutation.evidence.map((change) => {
1658
+ const binding = change;
1659
+ return {
1660
+ type: EventTypes.UPDATE_ELEMENT_PROPERTY_BINDINGS,
1661
+ payload: {
1662
+ id: binding.id,
1663
+ changes: binding.changes.map(({ key, before, after }) => ({
1664
+ key,
1665
+ before: after,
1666
+ after: before
1667
+ }))
1668
+ }
1669
+ };
1670
+ })
1671
+ : undefined;
1672
+ artifact.entries.forEach(({ element, request }) => {
1673
+ element.props.assignCanonicalPropertyBinding(request.propertyName, request.after);
1674
+ });
1675
+ this.applyElementPropertyRelationIndexUpdates(artifact.relationIndexUpdates, 'forward');
1676
+ try {
1677
+ this.handoffSceneTreeChanges(events, () => transactionOwner.updateTransactionBatch(events));
1678
+ acknowledgeTransactionReplayApplied(restorationEvents);
1679
+ }
1680
+ catch (error) {
1681
+ if (reportsAcceptedCanonicalBatchHandoff(error)) {
1682
+ acknowledgeTransactionReplayApplied(restorationEvents);
1683
+ }
1684
+ else {
1685
+ artifact.entries.forEach(({ element, request }) => {
1686
+ element.props.assignCanonicalPropertyBinding(request.propertyName, request.before);
1687
+ });
1688
+ this.applyElementPropertyRelationIndexUpdates(artifact.relationIndexUpdates, 'reverse');
1689
+ }
1690
+ throw error;
1691
+ }
1692
+ }
1693
+ if (artifact.kind === 'element-property-binding-mutation') {
1694
+ const valuesByElement = new Map();
1695
+ artifact.entries.forEach(({ request }) => {
1696
+ const values = valuesByElement.get(request.elementId) ?? {};
1697
+ const property = this.propsManagerOwner.getPropertyById(request.after);
1698
+ if (!property) {
1699
+ throw new Error('[SceneTree] Accepted binding lost its active property before projection');
1700
+ }
1701
+ Object.assign(values, property.getValue());
1702
+ valuesByElement.set(request.elementId, values);
1703
+ });
1704
+ this.updateLocalComputedData([...valuesByElement].map(([elementId, values]) => ({
1705
+ elementId,
1706
+ values
1707
+ })));
1708
+ }
1370
1709
  if (artifact.kind === 'element-data-mutation') {
1371
1710
  artifact.entries.forEach(({ element, before }) => {
1372
1711
  if (this.getElementById(element.get('id')) !== element ||
@@ -1376,17 +1715,29 @@ class SceneTree {
1376
1715
  throw new Error(`[SceneTree] Cannot apply stale prepared element data mutation for "${element.get('id')}"`);
1377
1716
  }
1378
1717
  });
1718
+ const restorationEvents = getTransactionReplayMode()
1719
+ ? preparedMutation.evidence.map((change) => {
1720
+ const rawChange = change;
1721
+ return Object.freeze({
1722
+ type: EventTypes.UPDATE_ELEMENT_DATA,
1723
+ payload: Object.freeze({
1724
+ id: rawChange.id,
1725
+ changes: Object.freeze(rawChange.changes.map(({ key, before, after }) => Object.freeze({ key, before: after, after: before })))
1726
+ })
1727
+ });
1728
+ })
1729
+ : undefined;
1379
1730
  artifact.entries.forEach(({ element, after }) => {
1380
1731
  ;
1381
1732
  element.assignCanonicalElementData(after);
1382
1733
  });
1383
1734
  try {
1384
- transactionOwner.updateTransactionBatch(events);
1385
- acknowledgeTransactionReplayApplied();
1735
+ this.handoffSceneTreeChanges(events, () => transactionOwner.updateTransactionBatch(events));
1736
+ acknowledgeTransactionReplayApplied(restorationEvents);
1386
1737
  }
1387
1738
  catch (error) {
1388
1739
  if (reportsAcceptedCanonicalBatchHandoff(error)) {
1389
- acknowledgeTransactionReplayApplied();
1740
+ acknowledgeTransactionReplayApplied(restorationEvents);
1390
1741
  }
1391
1742
  else {
1392
1743
  artifact.entries.forEach(({ element, before }) => {
@@ -1476,7 +1827,7 @@ class SceneTree {
1476
1827
  changedParentIds.push(parentId);
1477
1828
  this.currentWorkspace.replaceBatchParentChildren(parent, children);
1478
1829
  });
1479
- transactionOwner.updateTransactionBatch(events);
1830
+ this.handoffSceneTreeChanges(events, () => transactionOwner.updateTransactionBatch(events));
1480
1831
  acknowledgeTransactionReplayApplied();
1481
1832
  }
1482
1833
  catch (error) {
@@ -1487,8 +1838,9 @@ class SceneTree {
1487
1838
  changedParentIds.reverse().forEach((parentId) => {
1488
1839
  const parent = artifact.parents.get(parentId);
1489
1840
  const before = artifact.parentChildrenBefore.get(parentId);
1490
- if (!parent || !before)
1841
+ if (!parent || !before) {
1491
1842
  return;
1843
+ }
1492
1844
  try {
1493
1845
  ;
1494
1846
  this.currentWorkspace.replaceBatchParentChildren(parent, before);
@@ -1533,7 +1885,8 @@ class SceneTree {
1533
1885
  artifact.kind === 'subtree-removal') {
1534
1886
  if (preparedMutation.kind !== 'prepared-element-removal' &&
1535
1887
  preparedMutation.kind !== 'prepared-canonical-element-removal' &&
1536
- preparedMutation.kind !== 'prepared-subtree-removal') {
1888
+ preparedMutation.kind !== 'prepared-subtree-removal' &&
1889
+ preparedMutation.kind !== 'prepared-subtrees-removal') {
1537
1890
  throw new Error('[SceneTree] Element removal artifact does not match its owner-issued preparation');
1538
1891
  }
1539
1892
  const removalElements = artifact.entries.map(({ element }) => element);
@@ -1579,7 +1932,7 @@ class SceneTree {
1579
1932
  element.assignCanonicalParentId('');
1580
1933
  this._deletedMap.set(element.get('id'), element);
1581
1934
  });
1582
- transactionOwner.updateTransactionBatch(events);
1935
+ this.handoffSceneTreeChanges(events, () => transactionOwner.updateTransactionBatch(events));
1583
1936
  markCanonicalBatchHandoffAccepted(handoffState);
1584
1937
  acknowledgeTransactionReplayApplied();
1585
1938
  disposalAttempted = true;
@@ -1605,8 +1958,9 @@ class SceneTree {
1605
1958
  }
1606
1959
  changedParentIds.reverse().forEach((parentId) => {
1607
1960
  const children = artifact.parentChildrenBefore.get(parentId);
1608
- if (!children)
1961
+ if (!children) {
1609
1962
  return;
1963
+ }
1610
1964
  const parent = this.getElementById(parentId);
1611
1965
  this.currentWorkspace.replaceBatchParentChildren(parent, children);
1612
1966
  });
@@ -2033,8 +2387,9 @@ class SceneTree {
2033
2387
  this.changes = [];
2034
2388
  this.workspaceList = [...validated.workspaceList];
2035
2389
  this.workspace = validated.workspace;
2036
- if (nextElements.size === 0)
2390
+ if (nextElements.size === 0) {
2037
2391
  this._init();
2392
+ }
2038
2393
  this.projectLocalComputedDataFromPropertyIds([...nextRelations.keys()]);
2039
2394
  previousElements.forEach((element) => {
2040
2395
  try {
@@ -2107,6 +2462,7 @@ class SceneTree {
2107
2462
  }
2108
2463
  });
2109
2464
  });
2465
+ const parentIds = new Map();
2110
2466
  this._elements.forEach((element, elementId) => {
2111
2467
  if (element.get('type') === EntityTypes.WORKSPACE) {
2112
2468
  return;
@@ -2119,20 +2475,72 @@ class SceneTree {
2119
2475
  if (membership.get(elementId) !== parentId) {
2120
2476
  throw new Error(`[SceneTree] Invalid canonical hierarchy: missing membership for "${elementId}"`);
2121
2477
  }
2122
- const visited = new Set([elementId]);
2123
- let ancestorId = parentId;
2124
- while (ancestorId) {
2125
- if (visited.has(ancestorId)) {
2478
+ parentIds.set(elementId, parentId);
2479
+ });
2480
+ // Each parent edge is walked once within this validation. No result survives
2481
+ // a subsequent mutation, so corrupt or changed hierarchies are still checked.
2482
+ const verified = new Set();
2483
+ for (const elementId of parentIds.keys()) {
2484
+ if (verified.has(elementId)) {
2485
+ continue;
2486
+ }
2487
+ const path = new Set();
2488
+ let currentId = elementId;
2489
+ while (currentId &&
2490
+ parentIds.has(currentId) &&
2491
+ !verified.has(currentId)) {
2492
+ if (path.has(currentId)) {
2126
2493
  throw new Error(`[SceneTree] Invalid canonical hierarchy: cycle at "${elementId}"`);
2127
2494
  }
2128
- visited.add(ancestorId);
2495
+ path.add(currentId);
2496
+ currentId = parentIds.get(currentId);
2497
+ }
2498
+ path.forEach((id) => verified.add(id));
2499
+ }
2500
+ }
2501
+ validateHierarchyMoveScope(parentIds) {
2502
+ const checkedParents = new Set();
2503
+ for (const parentId of parentIds) {
2504
+ if (checkedParents.has(parentId)) {
2505
+ continue;
2506
+ }
2507
+ checkedParents.add(parentId);
2508
+ const parent = this.getElementById(parentId);
2509
+ if (!parent) {
2510
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: missing parent "${parentId}"`);
2511
+ }
2512
+ const children = this.getContainerChildren(parent, `Move parent "${parentId}"`);
2513
+ const membership = new Set();
2514
+ for (const childId of children) {
2515
+ const child = this.getElementById(childId);
2516
+ if (membership.has(childId) ||
2517
+ !child ||
2518
+ child.get('parentId') !== parentId) {
2519
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: invalid membership for "${childId}"`);
2520
+ }
2521
+ membership.add(childId);
2522
+ }
2523
+ const ancestors = new Set();
2524
+ let current = parent;
2525
+ while (current.get('type') !== EntityTypes.WORKSPACE) {
2526
+ const currentId = current.get('id');
2527
+ if (ancestors.has(currentId)) {
2528
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: cycle at "${currentId}"`);
2529
+ }
2530
+ ancestors.add(currentId);
2531
+ const ancestorId = current.get('parentId');
2129
2532
  const ancestor = this.getElementById(ancestorId);
2130
- if (!ancestor || ancestor.get('type') === EntityTypes.WORKSPACE) {
2131
- break;
2533
+ if (!ancestor) {
2534
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: missing parent "${ancestorId}"`);
2132
2535
  }
2133
- ancestorId = ancestor.get('parentId');
2536
+ const siblings = this.getContainerChildren(ancestor, `Move ancestor "${ancestorId}"`);
2537
+ if (siblings.indexOf(currentId) < 0 ||
2538
+ siblings.indexOf(currentId) !== siblings.lastIndexOf(currentId)) {
2539
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: invalid membership for "${currentId}"`);
2540
+ }
2541
+ current = ancestor;
2134
2542
  }
2135
- });
2543
+ }
2136
2544
  }
2137
2545
  assertMoveDoesNotCreateCycle(elementIds, targetParentId) {
2138
2546
  const movedIds = new Set(elementIds);
@@ -2206,7 +2614,6 @@ class SceneTree {
2206
2614
  }
2207
2615
  }
2208
2616
  moveElements(request, options) {
2209
- this.validateCanonicalHierarchy();
2210
2617
  if (!request ||
2211
2618
  !Array.isArray(request.elementIds) ||
2212
2619
  request.elementIds.length === 0 ||
@@ -2246,6 +2653,7 @@ class SceneTree {
2246
2653
  throw new Error(`[SceneTree] Invalid hierarchy request: missing target "${request.targetParentId}"`);
2247
2654
  }
2248
2655
  const targetChildren = this.getContainerChildren(targetParent, `Target "${request.targetParentId}"`);
2656
+ this.validateHierarchyMoveScope([sourceParentId, request.targetParentId]);
2249
2657
  const targetBase = targetChildren.filter((childId) => !requestedIdSet.has(childId));
2250
2658
  if (!Number.isInteger(request.targetIndex) ||
2251
2659
  request.targetIndex < 0 ||
@@ -2283,7 +2691,6 @@ class SceneTree {
2283
2691
  return { elementIds: canonicalIds, moves };
2284
2692
  }
2285
2693
  applyHierarchyMoves(moves, options) {
2286
- this.validateCanonicalHierarchy();
2287
2694
  if (!Array.isArray(moves) || moves.length === 0) {
2288
2695
  return false;
2289
2696
  }
@@ -2323,6 +2730,7 @@ class SceneTree {
2323
2730
  }
2324
2731
  });
2325
2732
  this.getContainerChildren(this.getElementById(targetParentId), `Replay target "${targetParentId}"`);
2733
+ this.validateHierarchyMoveScope([sourceParentId, targetParentId]);
2326
2734
  this.assertMoveDoesNotCreateCycle(elementIds, targetParentId);
2327
2735
  const operationChangeStart = this.changes.length;
2328
2736
  this.applyValidatedHierarchyMoves(moves);
@@ -2340,7 +2748,7 @@ class SceneTree {
2340
2748
  this.commitSceneTreeTransaction(options);
2341
2749
  return true;
2342
2750
  }
2343
- collectSubtreeRemovalEntries(elementId) {
2751
+ collectSubtreeRemovalEntries(elementId, parentIndexes = new Map()) {
2344
2752
  const root = this.getElementById(elementId);
2345
2753
  if (!root) {
2346
2754
  throw new Error(`[SceneTree] Invalid subtree request: missing element "${elementId}"`);
@@ -2362,9 +2770,10 @@ class SceneTree {
2362
2770
  const currentId = current.get('id');
2363
2771
  const parentId = current.get('parentId');
2364
2772
  const parent = this.getElementById(parentId);
2365
- const index = parent
2366
- ? this.getContainerChildren(parent, `Subtree parent "${parentId}"`).indexOf(currentId)
2367
- : -1;
2773
+ if (parent && !parentIndexes.has(parentId)) {
2774
+ parentIndexes.set(parentId, new Map(this.getContainerChildren(parent, `Subtree parent "${parentId}"`).map((id, index) => [id, index])));
2775
+ }
2776
+ const index = parentIndexes.get(parentId)?.get(currentId) ?? -1;
2368
2777
  if (index < 0) {
2369
2778
  throw new Error(`[SceneTree] Invalid subtree request: missing membership for "${currentId}"`);
2370
2779
  }
@@ -2456,8 +2865,9 @@ class SceneTree {
2456
2865
  }
2457
2866
  const childrenByParent = new Map();
2458
2867
  entries.forEach((entry) => {
2459
- if (entry.elementId === rootEntry.elementId)
2868
+ if (entry.elementId === rootEntry.elementId) {
2460
2869
  return;
2870
+ }
2461
2871
  if (!entryById.has(entry.parentId)) {
2462
2872
  throw new Error(`[SceneTree] Invalid subtree restore: missing snapshot parent "${entry.parentId}"`);
2463
2873
  }
@@ -2491,8 +2901,9 @@ class SceneTree {
2491
2901
  if (visiting.has(elementId)) {
2492
2902
  throw new Error(`[SceneTree] Invalid subtree restore: cycle at "${elementId}"`);
2493
2903
  }
2494
- if (visited.has(elementId))
2904
+ if (visited.has(elementId)) {
2495
2905
  return;
2906
+ }
2496
2907
  const entry = entryById.get(elementId);
2497
2908
  if (!entry) {
2498
2909
  throw new Error(`[SceneTree] Invalid subtree restore: inconsistent child order at "${elementId}"`);
@@ -2666,8 +3077,9 @@ class SceneTree {
2666
3077
  canonicalMapApplied = true;
2667
3078
  this.currentWorkspace.replaceBatchParentChildren(rootParent, restoredRootParentChildren);
2668
3079
  snapshot.removed.forEach(({ elementId, data }) => {
2669
- if (!isGroupEntity(data.type))
3080
+ if (!isGroupEntity(data.type)) {
2670
3081
  return;
3082
+ }
2671
3083
  const group = prepared.get(elementId);
2672
3084
  this.currentWorkspace.replaceBatchParentChildren(group, data.children);
2673
3085
  });
@@ -2688,8 +3100,9 @@ class SceneTree {
2688
3100
  // Preserve the primary apply failure and continue every rollback stage.
2689
3101
  }
2690
3102
  snapshot.removed.forEach(({ elementId, data }) => {
2691
- if (!isGroupEntity(data.type))
3103
+ if (!isGroupEntity(data.type)) {
2692
3104
  return;
3105
+ }
2693
3106
  const group = prepared.get(elementId);
2694
3107
  try {
2695
3108
  ;
@@ -2880,15 +3293,12 @@ class SceneTree {
2880
3293
  !isGroupEntity(target.get('type'))) {
2881
3294
  throw new Error('[SceneTree] Element batch requires an active container parent');
2882
3295
  }
2883
- const targetChildren = target.get('children');
2884
- if (!Array.isArray(targetChildren)) {
2885
- throw new Error('[SceneTree] Element batch requires an ordered parent child list');
2886
- }
2887
- const insertionIndex = index > -1 ? index : targetChildren.length;
3296
+ const childCount = target.getCanonicalChildCount();
3297
+ const insertionIndex = index > -1 ? index : childCount;
2888
3298
  if (!Number.isInteger(index) ||
2889
3299
  index < -1 ||
2890
3300
  insertionIndex < 0 ||
2891
- insertionIndex > targetChildren.length) {
3301
+ insertionIndex > childCount) {
2892
3302
  throw new Error('[SceneTree] Element batch index is outside parent order');
2893
3303
  }
2894
3304
  const sourceIds = [];
@@ -2946,7 +3356,6 @@ class SceneTree {
2946
3356
  }
2947
3357
  const preflight = this.preflightElementBatch(elementData, parent, index);
2948
3358
  const { target, sourceIds, insertionIndex, tombstones, preparedOrdinaryProperties } = preflight;
2949
- const originalChildren = [...target.get('children')];
2950
3359
  const elements = [];
2951
3360
  const operationChangeStart = this.changes.length;
2952
3361
  const canonicalHandoffState = createCanonicalBatchHandoffState();
@@ -3006,18 +3415,25 @@ class SceneTree {
3006
3415
  this.cleanChanges();
3007
3416
  throw error;
3008
3417
  }
3009
- rollbackPreparedProperties?.();
3418
+ const recoveryFailures = [];
3419
+ const recover = (operation) => {
3420
+ try {
3421
+ operation();
3422
+ }
3423
+ catch (failure) {
3424
+ recoveryFailures.push(failure);
3425
+ }
3426
+ };
3427
+ recover(() => rollbackPreparedProperties?.());
3010
3428
  if (parentMembershipMayHaveChanged) {
3011
- workspace.replaceBatchParentChildren(target, originalChildren);
3429
+ recover(() => target.removeChildrenFromCanonicalBatch(sourceIds));
3012
3430
  }
3013
3431
  const activeElements = elements.filter((element) => this._elements.get(element.get('id')) === element);
3014
3432
  if (activeElements.length > 0) {
3015
- this.removeElementsFromCanonicalMap(activeElements);
3433
+ recover(() => this.removeElementsFromCanonicalMap(activeElements));
3016
3434
  }
3017
- elements.forEach((element) => {
3018
- disposeElementComputed(element);
3019
- });
3020
- sourceIds.forEach((sourceId) => {
3435
+ elements.forEach((element) => recover(() => disposeElementComputed(element)));
3436
+ sourceIds.forEach((sourceId) => recover(() => {
3021
3437
  const tombstone = tombstones.get(sourceId);
3022
3438
  if (tombstone) {
3023
3439
  this._deletedMap.set(sourceId, tombstone);
@@ -3025,8 +3441,13 @@ class SceneTree {
3025
3441
  else {
3026
3442
  this._deletedMap.delete(sourceId);
3027
3443
  }
3444
+ }));
3445
+ recover(() => {
3446
+ this.changes.splice(operationChangeStart);
3028
3447
  });
3029
- this.changes.splice(operationChangeStart);
3448
+ if (recoveryFailures.length) {
3449
+ throw new MutationRecoveryError(error, recoveryFailures);
3450
+ }
3030
3451
  throw error;
3031
3452
  }
3032
3453
  }
@@ -3258,6 +3679,22 @@ class SceneTree {
3258
3679
  })));
3259
3680
  }
3260
3681
  }
3682
+ handoffSceneTreeChanges(events, handoff) {
3683
+ const changes = events.map((event) => event.payload);
3684
+ const immediate = events.some((event) => event.options?.sharedDelivery === 'immediate');
3685
+ try {
3686
+ handoff();
3687
+ }
3688
+ catch (error) {
3689
+ // Accepted journals are undone through the same owner path. Rejected
3690
+ // preparations restore internally and must never reach the projection.
3691
+ if (reportsAcceptedCanonicalBatchHandoff(error)) {
3692
+ publishLocalSceneTreeChanges(changes, this.projectionOwner, immediate);
3693
+ }
3694
+ throw error;
3695
+ }
3696
+ publishLocalSceneTreeChanges(changes, this.projectionOwner, immediate);
3697
+ }
3261
3698
  prepareSceneTreeTransactionEvents(options) {
3262
3699
  return this.changes.map((change) => {
3263
3700
  const changeOptions = change.options ?? options;
@@ -3347,7 +3784,7 @@ class SceneTree {
3347
3784
  const events = issueDetachedTransactionOwnerBatch(Object.freeze([...propsEvents, ...sceneEvents]));
3348
3785
  if (transactionOwner) {
3349
3786
  try {
3350
- transactionOwner.updateTransactionBatch(events);
3787
+ this.handoffSceneTreeChanges(sceneEvents, () => transactionOwner.updateTransactionBatch(events));
3351
3788
  markCanonicalBatchHandoffAccepted(handoffState);
3352
3789
  acknowledgeTransactionReplayApplied();
3353
3790
  }
@@ -3360,9 +3797,7 @@ class SceneTree {
3360
3797
  }
3361
3798
  }
3362
3799
  else {
3363
- events.forEach((event) => {
3364
- updateTransaction(event);
3365
- });
3800
+ this.handoffSceneTreeChanges(sceneEvents, () => updateTransactionBatch(events));
3366
3801
  acknowledgeTransactionReplayApplied();
3367
3802
  }
3368
3803
  this.propsManagerOwner.cleanChanges();
@@ -3373,9 +3808,8 @@ class SceneTree {
3373
3808
  this.commitCanonicalElementBatch(options, canonical);
3374
3809
  return;
3375
3810
  }
3376
- this.prepareSceneTreeTransactionEvents(options).forEach((event) => {
3377
- updateTransaction(event);
3378
- });
3811
+ const events = this.prepareSceneTreeTransactionEvents(options);
3812
+ this.handoffSceneTreeChanges(events, () => updateTransactionBatch(events));
3379
3813
  this.cleanChanges();
3380
3814
  }
3381
3815
  /** Full runtime retirement; definitions and Props remain separate owners. */
@@ -3401,8 +3835,9 @@ class SceneTree {
3401
3835
  }
3402
3836
  }
3403
3837
  });
3404
- if (failed)
3838
+ if (failed) {
3405
3839
  throw firstError;
3840
+ }
3406
3841
  }
3407
3842
  dispose() {
3408
3843
  this._elements.clear();