@asyra/scene-tree 0.2.4 → 0.5.0

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 (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -1
  3. package/dist/component-registry.d.ts +24 -0
  4. package/dist/component-registry.d.ts.map +1 -0
  5. package/dist/component-registry.js +26 -0
  6. package/dist/component-registry.js.map +1 -0
  7. package/dist/components/computed.d.ts +9 -6
  8. package/dist/components/computed.d.ts.map +1 -1
  9. package/dist/components/computed.js +37 -28
  10. package/dist/components/computed.js.map +1 -1
  11. package/dist/components/element-change-handler.d.ts +4 -3
  12. package/dist/components/element-change-handler.d.ts.map +1 -1
  13. package/dist/components/element-change-handler.js +21 -9
  14. package/dist/components/element-change-handler.js.map +1 -1
  15. package/dist/components/element.d.ts +19 -11
  16. package/dist/components/element.d.ts.map +1 -1
  17. package/dist/components/element.js +61 -31
  18. package/dist/components/element.js.map +1 -1
  19. package/dist/components/group.d.ts +9 -4
  20. package/dist/components/group.d.ts.map +1 -1
  21. package/dist/components/group.js +16 -12
  22. package/dist/components/group.js.map +1 -1
  23. package/dist/components/index.d.ts +3 -5
  24. package/dist/components/index.d.ts.map +1 -1
  25. package/dist/components/index.js +3 -5
  26. package/dist/components/index.js.map +1 -1
  27. package/dist/components/props.d.ts +12 -7
  28. package/dist/components/props.d.ts.map +1 -1
  29. package/dist/components/props.js +64 -20
  30. package/dist/components/props.js.map +1 -1
  31. package/dist/components/workspace.d.ts +9 -5
  32. package/dist/components/workspace.d.ts.map +1 -1
  33. package/dist/components/workspace.js +62 -36
  34. package/dist/components/workspace.js.map +1 -1
  35. package/dist/create-dynamic-component.d.ts +5 -0
  36. package/dist/create-dynamic-component.d.ts.map +1 -0
  37. package/dist/create-dynamic-component.js +53 -0
  38. package/dist/create-dynamic-component.js.map +1 -0
  39. package/dist/create-dynamic-props.d.ts +4 -0
  40. package/dist/create-dynamic-props.d.ts.map +1 -0
  41. package/dist/create-dynamic-props.js +104 -0
  42. package/dist/create-dynamic-props.js.map +1 -0
  43. package/dist/element-mutation.d.ts +92 -0
  44. package/dist/element-mutation.d.ts.map +1 -0
  45. package/dist/element-mutation.js +2 -0
  46. package/dist/element-mutation.js.map +1 -0
  47. package/dist/entity-data.d.ts +16 -0
  48. package/dist/entity-data.d.ts.map +1 -0
  49. package/dist/{utils.js → entity-data.js} +34 -22
  50. package/dist/entity-data.js.map +1 -0
  51. package/dist/index.d.ts +9 -2
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +8 -3
  54. package/dist/index.js.map +1 -1
  55. package/dist/props-manager-context.d.ts +6 -0
  56. package/dist/props-manager-context.d.ts.map +1 -0
  57. package/dist/props-manager-context.js +26 -0
  58. package/dist/props-manager-context.js.map +1 -0
  59. package/dist/sceneTree.d.ts +105 -10
  60. package/dist/sceneTree.d.ts.map +1 -1
  61. package/dist/sceneTree.js +3308 -96
  62. package/dist/sceneTree.js.map +1 -1
  63. package/dist/subscribes.d.ts.map +1 -1
  64. package/dist/subscribes.js +188 -24
  65. package/dist/subscribes.js.map +1 -1
  66. package/dist/types.d.ts +26 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +2 -0
  69. package/dist/types.js.map +1 -0
  70. package/package.json +24 -5
  71. package/.turbo/turbo-test$colon$ci.log +0 -134
  72. package/.turbo/turbo-test$colon$local.log +0 -46
  73. package/.turbo/turbo-test.log +0 -53
  74. package/CHANGELOG.md +0 -41
  75. package/coverage/base.css +0 -224
  76. package/coverage/block-navigation.js +0 -87
  77. package/coverage/clover.xml +0 -778
  78. package/coverage/coverage-final.json +0 -10478
  79. package/coverage/favicon.png +0 -0
  80. package/coverage/index.html +0 -131
  81. package/coverage/prettify.css +0 -1
  82. package/coverage/prettify.js +0 -2
  83. package/coverage/sort-arrow-sprite.png +0 -0
  84. package/coverage/sorter.js +0 -196
  85. package/coverage/src/components/computed.ts.html +0 -313
  86. package/coverage/src/components/element-change-handler.ts.html +0 -145
  87. package/coverage/src/components/element.ts.html +0 -586
  88. package/coverage/src/components/frame.ts.html +0 -169
  89. package/coverage/src/components/group.ts.html +0 -295
  90. package/coverage/src/components/index.html +0 -236
  91. package/coverage/src/components/index.ts.html +0 -103
  92. package/coverage/src/components/props.ts.html +0 -355
  93. package/coverage/src/components/rectangle.ts.html +0 -169
  94. package/coverage/src/components/workspace.ts.html +0 -433
  95. package/coverage/src/index.html +0 -161
  96. package/coverage/src/index.ts.html +0 -103
  97. package/coverage/src/sceneTree.ts.html +0 -853
  98. package/coverage/src/subscribes.ts.html +0 -295
  99. package/coverage/src/utils.ts.html +0 -328
  100. package/dist/__tests__/sceneTree.test.d.ts +0 -2
  101. package/dist/__tests__/sceneTree.test.d.ts.map +0 -1
  102. package/dist/__tests__/sceneTree.test.js +0 -261
  103. package/dist/__tests__/sceneTree.test.js.map +0 -1
  104. package/dist/components/frame.d.ts +0 -11
  105. package/dist/components/frame.d.ts.map +0 -1
  106. package/dist/components/frame.js +0 -21
  107. package/dist/components/frame.js.map +0 -1
  108. package/dist/components/legacy-element.d.ts +0 -22
  109. package/dist/components/legacy-element.d.ts.map +0 -1
  110. package/dist/components/legacy-element.js +0 -120
  111. package/dist/components/legacy-element.js.map +0 -1
  112. package/dist/components/polygon.d.ts +0 -11
  113. package/dist/components/polygon.d.ts.map +0 -1
  114. package/dist/components/polygon.js +0 -21
  115. package/dist/components/polygon.js.map +0 -1
  116. package/dist/components/rectangle.d.ts +0 -11
  117. package/dist/components/rectangle.d.ts.map +0 -1
  118. package/dist/components/rectangle.js +0 -21
  119. package/dist/components/rectangle.js.map +0 -1
  120. package/dist/components/shape-entity.d.ts +0 -16
  121. package/dist/components/shape-entity.d.ts.map +0 -1
  122. package/dist/components/shape-entity.js +0 -42
  123. package/dist/components/shape-entity.js.map +0 -1
  124. package/dist/components/shape.d.ts +0 -40
  125. package/dist/components/shape.d.ts.map +0 -1
  126. package/dist/components/shape.js +0 -105
  127. package/dist/components/shape.js.map +0 -1
  128. package/dist/utils.d.ts +0 -19
  129. package/dist/utils.d.ts.map +0 -1
  130. package/dist/utils.js.map +0 -1
  131. package/src/__tests__/sceneTree.test.ts +0 -339
  132. package/src/components/computed.ts +0 -76
  133. package/src/components/element-change-handler.ts +0 -20
  134. package/src/components/element.ts +0 -167
  135. package/src/components/frame.ts +0 -28
  136. package/src/components/group.ts +0 -70
  137. package/src/components/index.ts +0 -6
  138. package/src/components/props.ts +0 -90
  139. package/src/components/rectangle.ts +0 -28
  140. package/src/components/workspace.ts +0 -116
  141. package/src/index.ts +0 -6
  142. package/src/sceneTree.ts +0 -256
  143. package/src/subscribes.ts +0 -70
  144. package/src/utils.ts +0 -81
  145. package/tsconfig.json +0 -17
package/dist/sceneTree.js CHANGED
@@ -1,93 +1,2833 @@
1
- import { EntityTypes, OWNER, SCENE_TREE_ACTIONS } from '@asyra/utils';
2
- import { EventTypes, updateTransaction } from '@asyra/reactive-events';
1
+ 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';
3
3
  import propsManager from '@asyra/props-manager';
4
- import { createElement, createWorkspace, stripNonRawFields } from './utils';
4
+ import * as lodashModule from 'lodash';
5
+ import componentRegistry from './component-registry.js';
6
+ import { createElement, createWorkspace, isGroupEntity } from './entity-data.js';
7
+ import { runWithSceneTreeInitialOwnerValues } from './props-manager-context.js';
8
+ const lodash = lodashModule.default ?? lodashModule;
9
+ const { isEqual } = lodash;
10
+ const measureCanonicalSceneBatchPhase = (phaseName, run) => measureBrowserDragPhase(phaseName, run);
11
+ const hasPatchChanges = (patch) => {
12
+ if (Object.keys(patch.values ?? {}).length > 0) {
13
+ return true;
14
+ }
15
+ return Object.values(patch.records ?? {}).some((recordPatch) => Object.keys(recordPatch.set ?? {}).length > 0 ||
16
+ Object.keys(recordPatch.remove ?? {}).length > 0);
17
+ };
18
+ const getOverlappingPatchKey = (patch) => {
19
+ const recordKeys = new Set(Object.keys(patch.records ?? {}));
20
+ return Object.keys(patch.values ?? {}).find((key) => recordKeys.has(key));
21
+ };
22
+ const cloneRecord = (value) => ({ ...value });
23
+ const hasOwnRecordValue = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
24
+ const getComputedSnapshot = (element) => {
25
+ const snapshot = element.getAllComputedData();
26
+ if (!isRecord(snapshot)) {
27
+ throw new Error('Computed data snapshot must be a record');
28
+ }
29
+ return snapshot;
30
+ };
31
+ const validateComputedDataRecordPatches = (patch, computedSnapshot) => {
32
+ Object.entries(patch.records ?? {}).forEach(([key, recordPatch]) => {
33
+ if (!hasOwnRecordValue(computedSnapshot, key) ||
34
+ !isRecord(computedSnapshot[key])) {
35
+ throw new Error(`Computed data patch record base "${key}" must already be a record`);
36
+ }
37
+ const removedIds = new Set(recordPatch.remove ?? []);
38
+ const overlappingRecordId = Object.keys(recordPatch.set ?? {}).find((recordId) => removedIds.has(recordId));
39
+ if (overlappingRecordId !== undefined) {
40
+ throw new Error(`Computed data patch record "${key}.${overlappingRecordId}" cannot be both set and removed`);
41
+ }
42
+ });
43
+ };
44
+ const validateComputedDataValuePatches = (patch, computedSnapshot) => {
45
+ Object.keys(patch.values ?? {}).forEach((key) => {
46
+ if (!Object.prototype.hasOwnProperty.call(computedSnapshot, key)) {
47
+ throw new Error(`Computed data patch value base "${key}" must already exist`);
48
+ }
49
+ });
50
+ };
51
+ const validateComputedDataPatch = (patch, computedSnapshot) => {
52
+ const overlappingKey = getOverlappingPatchKey(patch);
53
+ if (overlappingKey !== undefined) {
54
+ throw new Error(`Computed data patch key "${overlappingKey}" cannot be both value and record`);
55
+ }
56
+ validateComputedDataValuePatches(patch, computedSnapshot);
57
+ validateComputedDataRecordPatches(patch, computedSnapshot);
58
+ };
59
+ const LOCAL_COMPUTED_RESERVED_KEYS = new Set([
60
+ 'id',
61
+ 'type',
62
+ 'name',
63
+ 'parentId',
64
+ 'visible',
65
+ 'lock'
66
+ ]);
67
+ const canonicalBatchHandoffAccepted = Symbol('scene-tree:canonical-batch-handoff-accepted');
68
+ const canonicalBatchHandoffState = Symbol('scene-tree:canonical-batch-handoff-state');
69
+ const cloneSceneTreeValue = (data) => {
70
+ if (typeof globalThis.structuredClone === 'function') {
71
+ return globalThis.structuredClone(data);
72
+ }
73
+ return JSON.parse(JSON.stringify(data));
74
+ };
75
+ const deepFreezeSceneValue = (value, seen = new WeakSet()) => {
76
+ if (value === null ||
77
+ (typeof value !== 'object' && typeof value !== 'function')) {
78
+ return value;
79
+ }
80
+ const objectValue = value;
81
+ if (seen.has(objectValue)) {
82
+ return value;
83
+ }
84
+ seen.add(objectValue);
85
+ Reflect.ownKeys(objectValue).forEach((key) => {
86
+ deepFreezeSceneValue(objectValue[key], seen);
87
+ });
88
+ return Object.freeze(value);
89
+ };
90
+ const cloneAndFreezeSceneValue = (value) => deepFreezeSceneValue(cloneSceneTreeValue(value));
91
+ const isElementBatchChange = (change) => change.action === SCENE_TREE_ACTIONS.ADD_ELEMENTS ||
92
+ change.action === SCENE_TREE_ACTIONS.REMOVE_ELEMENTS;
93
+ const createElementBatchSharedRecords = (change) => deepFreezeSceneValue(change.entries.map((entry) => ({
94
+ orderedIds: [entry.data.id],
95
+ payload: {
96
+ ...change,
97
+ entries: [entry]
98
+ }
99
+ })));
100
+ const compareCanonicalString = (left, right) => {
101
+ if (left < right)
102
+ return -1;
103
+ if (left > right)
104
+ return 1;
105
+ return 0;
106
+ };
107
+ const compareElementPropertyRelations = (left, right) => compareCanonicalString(left.ownerElementId, right.ownerElementId) ||
108
+ compareCanonicalString(left.ownerPropertyName, right.ownerPropertyName) ||
109
+ compareCanonicalString(left.ownerElementType, right.ownerElementType) ||
110
+ compareCanonicalString(left.componentId, right.componentId);
111
+ const getElementPropertyRelationTupleKey = (relation) => JSON.stringify([relation.ownerElementId, relation.ownerPropertyName]);
112
+ const freezeElementPropertyRelations = (relations) => Object.freeze(relations
113
+ .map((relation) => Object.freeze({
114
+ ownerElementId: relation.ownerElementId,
115
+ ownerElementType: relation.ownerElementType,
116
+ ownerPropertyName: relation.ownerPropertyName,
117
+ componentId: relation.componentId
118
+ }))
119
+ .sort(compareElementPropertyRelations));
120
+ const EMPTY_ELEMENT_PROPERTY_RELATIONS = Object.freeze([]);
121
+ const collectElementPropertyRelations = (data) => {
122
+ const props = data.props ?? {};
123
+ if (typeof data.id !== 'string' ||
124
+ data.id.length === 0 ||
125
+ typeof data.type !== 'string' ||
126
+ data.type.length === 0 ||
127
+ !isRecord(props)) {
128
+ throw new Error('[SceneTree] Cannot derive element-property relations from invalid Scene data');
129
+ }
130
+ return freezeElementPropertyRelations(Object.entries(props).map(([ownerPropertyName, componentId]) => {
131
+ if (ownerPropertyName.length === 0 ||
132
+ typeof componentId !== 'string' ||
133
+ componentId.length === 0) {
134
+ throw new Error(`[SceneTree] Element "${data.id}" has an invalid property relation`);
135
+ }
136
+ return {
137
+ ownerElementId: data.id,
138
+ ownerElementType: data.type,
139
+ ownerPropertyName,
140
+ componentId
141
+ };
142
+ }));
143
+ };
144
+ const captureElementInsertionRelationDefinitions = (sourceDefinitions, elementType, owner) => {
145
+ if (sourceDefinitions === undefined) {
146
+ return;
147
+ }
148
+ if (!Array.isArray(sourceDefinitions)) {
149
+ throw new Error(`[SceneTree] Element insertion has an invalid ${owner} property owner registry for "${elementType}"`);
150
+ }
151
+ const definitionNames = new Set();
152
+ return Object.freeze(sourceDefinitions.map((definition) => {
153
+ if (!isRecord(definition) ||
154
+ typeof definition.name !== 'string' ||
155
+ definition.name.length === 0 ||
156
+ typeof definition.type !== 'string' ||
157
+ definition.type.length === 0 ||
158
+ definitionNames.has(definition.name)) {
159
+ throw new Error(`[SceneTree] Element insertion has an invalid ${owner} property owner registry for "${elementType}"`);
160
+ }
161
+ definitionNames.add(definition.name);
162
+ return Object.freeze({
163
+ name: definition.name,
164
+ type: definition.type
165
+ });
166
+ }));
167
+ };
168
+ const captureElementInsertionRegistrationContract = (registration, elementType) => {
169
+ const registrationDefinitions = captureElementInsertionRelationDefinitions(registration.properties, elementType, 'registration') ?? Object.freeze([]);
170
+ const constructorDefinitions = captureElementInsertionRelationDefinitions(registration.constructor.ordinaryPropertyDefinitions, elementType, 'constructor');
171
+ const effectiveDefinitions = registrationDefinitions.length > 0
172
+ ? registrationDefinitions
173
+ : (constructorDefinitions ?? Object.freeze([]));
174
+ return Object.freeze({
175
+ registration,
176
+ constructor: registration.constructor,
177
+ registrationDefinitions,
178
+ constructorDefinitions,
179
+ effectiveDefinitions
180
+ });
181
+ };
182
+ const isElementInsertionRegistrationContractCurrent = (contract, elementType) => {
183
+ if (componentRegistry.get(elementType) !== contract.registration ||
184
+ contract.registration.constructor !== contract.constructor) {
185
+ return false;
186
+ }
187
+ try {
188
+ const current = captureElementInsertionRegistrationContract(contract.registration, elementType);
189
+ return (current.constructor === contract.constructor &&
190
+ isEqual(current.registrationDefinitions, contract.registrationDefinitions) &&
191
+ isEqual(current.constructorDefinitions, contract.constructorDefinitions));
192
+ }
193
+ catch {
194
+ return false;
195
+ }
196
+ };
197
+ const reportsAcceptedCanonicalBatchHandoff = (error) => typeof error === 'object' &&
198
+ error !== null &&
199
+ 'batchAccepted' in error &&
200
+ error.batchAccepted === true;
201
+ const createCanonicalBatchHandoffState = () => ({
202
+ [canonicalBatchHandoffAccepted]: false
203
+ });
204
+ const markCanonicalBatchHandoffAccepted = (state) => {
205
+ state[canonicalBatchHandoffAccepted] = true;
206
+ };
207
+ const wasCanonicalBatchHandoffAccepted = (state) => state[canonicalBatchHandoffAccepted];
208
+ const runWithDeferredReplayAcknowledgement = (callback) => {
209
+ const replayMode = getTransactionReplayMode();
210
+ if (replayMode === null) {
211
+ return callback();
212
+ }
213
+ const result = runInTransactionReplayMode(replayMode, () => {
214
+ try {
215
+ return { ok: true, value: callback() };
216
+ }
217
+ catch (error) {
218
+ return { ok: false, error };
219
+ }
220
+ });
221
+ if (!result.ok) {
222
+ throw result.error;
223
+ }
224
+ return result.value;
225
+ };
226
+ const disposeElementComputed = (element) => {
227
+ ;
228
+ element.computed?.dispose?.();
229
+ };
230
+ const reactivateElementComputed = (element) => {
231
+ if (!element.computed) {
232
+ return;
233
+ }
234
+ try {
235
+ element.getAllComputedData();
236
+ }
237
+ catch (error) {
238
+ disposeElementComputed(element);
239
+ throw error;
240
+ }
241
+ };
242
+ const cloneLoadData = (data) => cloneSceneTreeValue(data);
243
+ const toStringArray = (value) => {
244
+ if (!Array.isArray(value)) {
245
+ return [];
246
+ }
247
+ return value.filter((entry) => typeof entry === 'string');
248
+ };
5
249
  class SceneTree {
6
- constructor() {
250
+ constructor(propsManagerOwner = propsManager) {
251
+ this.propsManagerOwner = propsManagerOwner;
7
252
  this._elements = new Map();
8
253
  this._deletedMap = new Map();
9
254
  this.workspace = '';
10
255
  this.workspaceList = [];
11
256
  this.changes = [];
257
+ this.validatedLoadArtifacts = new WeakMap();
258
+ this.validatedRestoreArtifacts = new WeakMap();
259
+ this.preparedElementMutationArtifacts = new WeakMap();
260
+ this.elementPropertyRelationsByComponentId = new Map();
261
+ this.elementPropertyRelationRevision = 0;
262
+ }
263
+ getElementPropertyRelations(componentId) {
264
+ return (this.elementPropertyRelationsByComponentId.get(componentId) ??
265
+ EMPTY_ELEMENT_PROPERTY_RELATIONS);
266
+ }
267
+ buildElementPropertyRelationIndex(elements) {
268
+ const relationsByComponentId = new Map();
269
+ const componentIdByTuple = new Map();
270
+ for (const element of elements) {
271
+ collectElementPropertyRelations(element.save()).forEach((relation) => {
272
+ const tupleKey = getElementPropertyRelationTupleKey(relation);
273
+ const existingComponentId = componentIdByTuple.get(tupleKey);
274
+ if (existingComponentId !== undefined &&
275
+ existingComponentId !== relation.componentId) {
276
+ throw new Error(`[SceneTree] Element property relation "${relation.ownerElementId}.${relation.ownerPropertyName}" targets multiple components`);
277
+ }
278
+ componentIdByTuple.set(tupleKey, relation.componentId);
279
+ const relations = relationsByComponentId.get(relation.componentId) ?? [];
280
+ if (relations.some((existing) => getElementPropertyRelationTupleKey(existing) === tupleKey)) {
281
+ throw new Error(`[SceneTree] Element property relation "${relation.ownerElementId}.${relation.ownerPropertyName}" is duplicated`);
282
+ }
283
+ relations.push(relation);
284
+ relationsByComponentId.set(relation.componentId, relations);
285
+ });
286
+ }
287
+ return new Map([...relationsByComponentId].map(([componentId, relations]) => [
288
+ componentId,
289
+ freezeElementPropertyRelations(relations)
290
+ ]));
291
+ }
292
+ prepareElementPropertyRelationInsertions(elements) {
293
+ return this.prepareElementPropertyRelationInsertionsFromRelations(elements.flatMap((element) => collectElementPropertyRelations(element.save())));
294
+ }
295
+ prepareElementPropertyRelationInsertionsFromRelations(relations) {
296
+ const additionsByComponentId = new Map();
297
+ relations.forEach((relation) => {
298
+ const additions = additionsByComponentId.get(relation.componentId) ?? [];
299
+ additions.push(relation);
300
+ additionsByComponentId.set(relation.componentId, additions);
301
+ });
302
+ return Object.freeze([...additionsByComponentId].map(([componentId, additions]) => {
303
+ const relationsBefore = this.getElementPropertyRelations(componentId);
304
+ const tupleKeys = new Set(relationsBefore.map(getElementPropertyRelationTupleKey));
305
+ additions.forEach((relation) => {
306
+ const tupleKey = getElementPropertyRelationTupleKey(relation);
307
+ if (tupleKeys.has(tupleKey)) {
308
+ throw new Error(`[SceneTree] Element property relation "${relation.ownerElementId}.${relation.ownerPropertyName}" is already active`);
309
+ }
310
+ tupleKeys.add(tupleKey);
311
+ });
312
+ return Object.freeze({
313
+ componentId,
314
+ relationsBefore,
315
+ relationsAfter: freezeElementPropertyRelations([
316
+ ...relationsBefore,
317
+ ...additions
318
+ ])
319
+ });
320
+ }));
321
+ }
322
+ prepareElementPropertyRelationRemovals(elements) {
323
+ return this.prepareElementPropertyRelationRemovalsFromRelations(elements.flatMap((element) => collectElementPropertyRelations(element.save())));
324
+ }
325
+ prepareElementPropertyRelationRemovalsFromRelations(relations) {
326
+ const removalsByComponentId = new Map();
327
+ relations.forEach((relation) => {
328
+ const removals = removalsByComponentId.get(relation.componentId) ?? [];
329
+ removals.push(relation);
330
+ removalsByComponentId.set(relation.componentId, removals);
331
+ });
332
+ return Object.freeze([...removalsByComponentId].map(([componentId, removals]) => {
333
+ const relationsBefore = this.getElementPropertyRelations(componentId);
334
+ const relationByTupleKey = new Map(relationsBefore.map((relation) => [
335
+ getElementPropertyRelationTupleKey(relation),
336
+ relation
337
+ ]));
338
+ const removalTupleKeys = new Set(removals.map(getElementPropertyRelationTupleKey));
339
+ removals.forEach((relation) => {
340
+ const current = relationByTupleKey.get(getElementPropertyRelationTupleKey(relation));
341
+ if (!current || !isEqual(current, relation)) {
342
+ throw new Error(`[SceneTree] Element property relation "${relation.ownerElementId}.${relation.ownerPropertyName}" is not active`);
343
+ }
344
+ });
345
+ return Object.freeze({
346
+ componentId,
347
+ relationsBefore,
348
+ relationsAfter: freezeElementPropertyRelations(relationsBefore.filter((relation) => !removalTupleKeys.has(getElementPropertyRelationTupleKey(relation))))
349
+ });
350
+ }));
351
+ }
352
+ collectRootPropertyIdsAfterRelationUpdates(updates) {
353
+ const relationsAfterByComponentId = new Map(updates.map(({ componentId, relationsAfter }) => [
354
+ componentId,
355
+ relationsAfter
356
+ ]));
357
+ return Object.freeze([...this.elementPropertyRelationsByComponentId]
358
+ .filter(([componentId, currentRelations]) => (relationsAfterByComponentId.get(componentId) ?? currentRelations)
359
+ .length > 0)
360
+ .map(([componentId]) => componentId));
361
+ }
362
+ applyElementPropertyRelationIndexUpdates(updates, direction) {
363
+ if (updates.length === 0) {
364
+ return;
365
+ }
366
+ updates.forEach(({ componentId, relationsBefore, relationsAfter }) => {
367
+ const relations = direction === 'forward' ? relationsAfter : relationsBefore;
368
+ if (relations.length === 0) {
369
+ this.elementPropertyRelationsByComponentId.delete(componentId);
370
+ }
371
+ else {
372
+ this.elementPropertyRelationsByComponentId.set(componentId, relations);
373
+ }
374
+ });
375
+ this.elementPropertyRelationRevision += 1;
376
+ }
377
+ addElementsToCanonicalMap(elements, preparedUpdates) {
378
+ const elementIds = elements.map((element) => element.get('id'));
379
+ if (elementIds.some((elementId) => typeof elementId !== 'string' ||
380
+ elementId.length === 0 ||
381
+ this._elements.has(elementId)) ||
382
+ new Set(elementIds).size !== elementIds.length) {
383
+ throw new Error('[SceneTree] Canonical element map insertion requires unique inactive ids');
384
+ }
385
+ const updates = preparedUpdates ?? this.prepareElementPropertyRelationInsertions(elements);
386
+ elements.forEach((element) => {
387
+ this._elements.set(element.get('id'), element);
388
+ });
389
+ this.applyElementPropertyRelationIndexUpdates(updates, 'forward');
390
+ return updates;
391
+ }
392
+ removeElementsFromCanonicalMap(elements, preparedUpdates) {
393
+ const elementIds = elements.map((element) => element.get('id'));
394
+ if (elementIds.some((elementId, index) => typeof elementId !== 'string' ||
395
+ elementId.length === 0 ||
396
+ this._elements.get(elementId) !== elements[index]) ||
397
+ new Set(elementIds).size !== elementIds.length) {
398
+ throw new Error('[SceneTree] Canonical element map removal requires unique active instances');
399
+ }
400
+ const updates = preparedUpdates ?? this.prepareElementPropertyRelationRemovals(elements);
401
+ elements.forEach((element) => {
402
+ this._elements.delete(element.get('id'));
403
+ });
404
+ this.applyElementPropertyRelationIndexUpdates(updates, 'forward');
405
+ return updates;
406
+ }
407
+ restoreElementsToCanonicalMap(elements, updates) {
408
+ elements.forEach((element) => {
409
+ this._elements.set(element.get('id'), element);
410
+ });
411
+ this.applyElementPropertyRelationIndexUpdates(updates, 'reverse');
412
+ }
413
+ rollbackElementsAddedToCanonicalMap(elements, updates) {
414
+ elements.forEach((element) => {
415
+ this._elements.delete(element.get('id'));
416
+ });
417
+ this.applyElementPropertyRelationIndexUpdates(updates, 'reverse');
418
+ }
419
+ replaceCanonicalElementMap(elements, preparedRelations) {
420
+ const nextRelations = preparedRelations ??
421
+ this.buildElementPropertyRelationIndex(elements.values());
422
+ this._elements = new Map(elements);
423
+ this.elementPropertyRelationsByComponentId = nextRelations;
424
+ this.elementPropertyRelationRevision += 1;
425
+ }
426
+ _init() {
427
+ if (!this.workspace && !this.workspaceList.length) {
428
+ const initWorkspace = createWorkspace(this);
429
+ if (initWorkspace) {
430
+ this.addToMap(initWorkspace);
431
+ this.workspaceList = [initWorkspace.get('id')];
432
+ this.workspace = this.workspaceList[0];
433
+ }
434
+ }
435
+ }
436
+ init() {
437
+ this._init();
438
+ }
439
+ resolveElementPropertyTargets(requests) {
440
+ const orderedElementIds = [];
441
+ const relations = [];
442
+ const relationTupleKeys = new Set();
443
+ const requestedElementIds = new Set();
444
+ const targetsByPropertyId = new Map();
445
+ const getTarget = (propertyId) => {
446
+ const existing = targetsByPropertyId.get(propertyId);
447
+ if (existing) {
448
+ return existing;
449
+ }
450
+ const target = {
451
+ propertyId,
452
+ values: {},
453
+ setRecords: {},
454
+ removeRecordIds: [],
455
+ removeRecordIdSet: new Set()
456
+ };
457
+ targetsByPropertyId.set(propertyId, target);
458
+ return target;
459
+ };
460
+ const addRelation = (relation) => {
461
+ const tupleKey = getElementPropertyRelationTupleKey(relation);
462
+ if (!relationTupleKeys.has(tupleKey)) {
463
+ relationTupleKeys.add(tupleKey);
464
+ relations.push(relation);
465
+ }
466
+ };
467
+ const throwConflict = (propertyId, key) => {
468
+ throw new Error(`[SceneTree] Conflicting shared property target "${propertyId}.${key}"`);
469
+ };
470
+ const mergeValue = (target, key, value) => {
471
+ if (hasOwnRecordValue(target.values, key)) {
472
+ if (!isEqual(target.values[key], value)) {
473
+ throwConflict(target.propertyId, key);
474
+ }
475
+ return;
476
+ }
477
+ setOwnEnumerableValue(target.values, key, cloneSceneTreeValue(value));
478
+ };
479
+ requests.forEach((request) => {
480
+ if (!isRecord(request) ||
481
+ (request.kind !== 'values' && request.kind !== 'records') ||
482
+ typeof request.elementId !== 'string' ||
483
+ request.elementId.length === 0 ||
484
+ requestedElementIds.has(request.elementId)) {
485
+ throw new Error('[SceneTree] Element-property target requests require unique active element ids');
486
+ }
487
+ requestedElementIds.add(request.elementId);
488
+ orderedElementIds.push(request.elementId);
489
+ const element = this.getElementById(request.elementId);
490
+ if (!element) {
491
+ throw new Error(`[SceneTree] Cannot resolve property targets for missing element "${request.elementId}"`);
492
+ }
493
+ const elementType = element.get('type');
494
+ const registration = typeof elementType === 'string'
495
+ ? componentRegistry.get(elementType)
496
+ : undefined;
497
+ if (!registration) {
498
+ throw new Error(`[SceneTree] Cannot resolve property targets for unregistered element type "${String(elementType ?? '')}"`);
499
+ }
500
+ const constructorPropertyDefinitions = registration.constructor.ordinaryPropertyDefinitions;
501
+ const definitions = registration.properties.length > 0
502
+ ? registration.properties
503
+ : (constructorPropertyDefinitions ?? []);
504
+ const definitionsByInputKey = new Map();
505
+ definitions.forEach((definition) => {
506
+ const keys = [definition.name, ...(definition.alias ?? [])];
507
+ keys.forEach((key) => {
508
+ if (typeof key !== 'string' ||
509
+ key.length === 0 ||
510
+ definitionsByInputKey.has(key)) {
511
+ throw new Error(`[SceneTree] Element type "${elementType}" has an ambiguous property alias "${String(key)}"`);
512
+ }
513
+ definitionsByInputKey.set(key, definition);
514
+ });
515
+ });
516
+ const resolveTarget = (requestedKey) => {
517
+ const definition = definitionsByInputKey.get(requestedKey);
518
+ if (!definition) {
519
+ throw new Error(`[SceneTree] Element "${request.elementId}" has no property target for "${requestedKey}"`);
520
+ }
521
+ const propertyId = element.props.getPropId(definition.name);
522
+ const property = propertyId
523
+ ? this.propsManagerOwner.getPropertyById(propertyId)
524
+ : undefined;
525
+ if (typeof propertyId !== 'string' ||
526
+ propertyId.length === 0 ||
527
+ !property ||
528
+ property.get('id') !== propertyId ||
529
+ property.get('type') !== definition.type) {
530
+ throw new Error(`[SceneTree] Element "${request.elementId}" has an invalid property owner relation for "${definition.name}"`);
531
+ }
532
+ return {
533
+ definition,
534
+ propertyId,
535
+ relation: {
536
+ ownerElementId: request.elementId,
537
+ ownerElementType: elementType,
538
+ ownerPropertyName: definition.name,
539
+ componentId: propertyId
540
+ }
541
+ };
542
+ };
543
+ const sourceValues = request.values ?? {};
544
+ if (!isRecord(sourceValues)) {
545
+ throw new Error(`[SceneTree] Element "${request.elementId}" property values must be a record`);
546
+ }
547
+ Object.entries(sourceValues).forEach(([key, value]) => {
548
+ const { propertyId, relation } = resolveTarget(key);
549
+ addRelation(relation);
550
+ mergeValue(getTarget(propertyId), key, value);
551
+ });
552
+ if (request.kind === 'records') {
553
+ if (!Array.isArray(request.records)) {
554
+ throw new Error(`[SceneTree] Element "${request.elementId}" record patches must be an array`);
555
+ }
556
+ const recordKeys = new Set();
557
+ request.records.forEach((recordPatch) => {
558
+ if (!isRecord(recordPatch) ||
559
+ typeof recordPatch.key !== 'string' ||
560
+ recordPatch.key.length === 0 ||
561
+ recordKeys.has(recordPatch.key)) {
562
+ throw new Error(`[SceneTree] Element "${request.elementId}" record patches require unique property keys`);
563
+ }
564
+ recordKeys.add(recordPatch.key);
565
+ if (recordPatch.set !== undefined && !isRecord(recordPatch.set)) {
566
+ throw new Error(`[SceneTree] Element "${request.elementId}" record set must be a record`);
567
+ }
568
+ if (recordPatch.remove !== undefined &&
569
+ (!Array.isArray(recordPatch.remove) ||
570
+ recordPatch.remove.some((id) => typeof id !== 'string'))) {
571
+ throw new Error(`[SceneTree] Element "${request.elementId}" record remove must contain ids`);
572
+ }
573
+ const { definition, propertyId, relation } = resolveTarget(recordPatch.key);
574
+ addRelation(relation);
575
+ const target = getTarget(propertyId);
576
+ if (target.recordKey !== undefined &&
577
+ target.recordKey !== definition.name) {
578
+ throwConflict(propertyId, definition.name);
579
+ }
580
+ target.recordKey = definition.name;
581
+ Object.entries(recordPatch.set ?? {}).forEach(([recordId, recordValues]) => {
582
+ if (target.removeRecordIdSet.has(recordId)) {
583
+ throwConflict(propertyId, recordId);
584
+ }
585
+ if (hasOwnRecordValue(target.setRecords, recordId)) {
586
+ if (!isEqual(target.setRecords[recordId], recordValues)) {
587
+ throwConflict(propertyId, recordId);
588
+ }
589
+ return;
590
+ }
591
+ setOwnEnumerableValue(target.setRecords, recordId, cloneSceneTreeValue(recordValues));
592
+ });
593
+ (recordPatch.remove ?? []).forEach((recordId) => {
594
+ if (hasOwnRecordValue(target.setRecords, recordId)) {
595
+ throwConflict(propertyId, recordId);
596
+ }
597
+ if (!target.removeRecordIdSet.has(recordId)) {
598
+ target.removeRecordIdSet.add(recordId);
599
+ target.removeRecordIds.push(recordId);
600
+ }
601
+ });
602
+ });
603
+ }
604
+ });
605
+ const mutations = [...targetsByPropertyId.values()].map((target) => {
606
+ if (target.recordKey === undefined) {
607
+ return {
608
+ kind: 'values',
609
+ propertyId: target.propertyId,
610
+ values: target.values
611
+ };
612
+ }
613
+ if (hasOwnRecordValue(target.values, target.recordKey)) {
614
+ throwConflict(target.propertyId, target.recordKey);
615
+ }
616
+ return {
617
+ kind: 'records',
618
+ propertyId: target.propertyId,
619
+ key: target.recordKey,
620
+ ...(Object.keys(target.values).length > 0
621
+ ? { values: target.values }
622
+ : {}),
623
+ ...(Object.keys(target.setRecords).length > 0
624
+ ? { set: target.setRecords }
625
+ : {}),
626
+ ...(target.removeRecordIds.length > 0
627
+ ? { remove: target.removeRecordIds }
628
+ : {})
629
+ };
630
+ });
631
+ return cloneAndFreezeSceneValue({
632
+ kind: 'resolved-element-property-targets',
633
+ orderedElementIds,
634
+ relations,
635
+ mutations
636
+ });
637
+ }
638
+ prepareElementDataMutation(requests) {
639
+ const requestedIds = new Set();
640
+ const entries = [];
641
+ const evidence = [];
642
+ requests.forEach((request) => {
643
+ if (!isRecord(request) ||
644
+ typeof request.elementId !== 'string' ||
645
+ request.elementId.length === 0 ||
646
+ requestedIds.has(request.elementId) ||
647
+ !isRecord(request.values)) {
648
+ throw new Error('[SceneTree] Element data mutations require unique active element ids and typed values');
649
+ }
650
+ requestedIds.add(request.elementId);
651
+ const element = this.getElementById(request.elementId);
652
+ if (!element) {
653
+ throw new Error(`[SceneTree] Cannot prepare element data for missing element "${request.elementId}"`);
654
+ }
655
+ const valueKeys = Object.keys(request.values);
656
+ const invalidKey = valueKeys.find((key) => key !== 'name' && key !== 'visible' && key !== 'lock');
657
+ if (invalidKey) {
658
+ throw new Error(`[SceneTree] Element data mutation cannot update "${invalidKey}"`);
659
+ }
660
+ if ((request.values.name !== undefined &&
661
+ typeof request.values.name !== 'string') ||
662
+ (request.values.visible !== undefined &&
663
+ typeof request.values.visible !== 'boolean') ||
664
+ (request.values.lock !== undefined &&
665
+ typeof request.values.lock !== 'boolean')) {
666
+ throw new Error(`[SceneTree] Element "${request.elementId}" has invalid raw element data`);
667
+ }
668
+ const before = {
669
+ name: element.get('name'),
670
+ visible: element.get('visible'),
671
+ lock: element.get('lock')
672
+ };
673
+ const after = {
674
+ name: request.values.name ?? before.name,
675
+ visible: request.values.visible ?? before.visible,
676
+ lock: request.values.lock ?? before.lock
677
+ };
678
+ const changes = [];
679
+ if (before.name !== after.name) {
680
+ changes.push({
681
+ key: 'name',
682
+ before: before.name,
683
+ after: after.name
684
+ });
685
+ }
686
+ if (before.visible !== after.visible) {
687
+ changes.push({
688
+ key: 'visible',
689
+ before: before.visible,
690
+ after: after.visible
691
+ });
692
+ }
693
+ if (before.lock !== after.lock) {
694
+ changes.push({
695
+ key: 'lock',
696
+ before: before.lock,
697
+ after: after.lock
698
+ });
699
+ }
700
+ if (changes.length === 0) {
701
+ return;
702
+ }
703
+ entries.push({
704
+ element,
705
+ before: cloneAndFreezeSceneValue(before),
706
+ after: cloneAndFreezeSceneValue(after)
707
+ });
708
+ evidence.push({
709
+ action: SCENE_TREE_ACTIONS.UPDATE_ELEMENT_DATA,
710
+ eventName: EventTypes.UPDATE_ELEMENT_DATA,
711
+ id: request.elementId,
712
+ changes
713
+ });
714
+ });
715
+ const preparedMutation = cloneAndFreezeSceneValue({
716
+ kind: 'prepared-element-data-mutation',
717
+ orderedElementIds: evidence.map(({ id }) => id),
718
+ evidence
719
+ });
720
+ this.preparedElementMutationArtifacts.set(preparedMutation, {
721
+ kind: 'element-data-mutation',
722
+ entries: Object.freeze(entries)
723
+ });
724
+ return preparedMutation;
725
+ }
726
+ prepareCanonicalElementDataMutation(changes) {
727
+ if (!Array.isArray(changes)) {
728
+ throw new Error('[SceneTree] Canonical element data mutation requires an evidence batch');
729
+ }
730
+ const requests = changes.map((change) => {
731
+ if (!isRecord(change) ||
732
+ change.action !== SCENE_TREE_ACTIONS.UPDATE_ELEMENT_DATA ||
733
+ change.eventName !== EventTypes.UPDATE_ELEMENT_DATA ||
734
+ typeof change.id !== 'string' ||
735
+ change.id.length === 0 ||
736
+ !Array.isArray(change.changes) ||
737
+ change.changes.length === 0) {
738
+ throw new Error('[SceneTree] Canonical element data mutation has invalid evidence');
739
+ }
740
+ const values = {};
741
+ const keys = new Set();
742
+ change.changes.forEach((field) => {
743
+ if (!isRecord(field) ||
744
+ (field.key !== 'name' &&
745
+ field.key !== 'visible' &&
746
+ field.key !== 'lock') ||
747
+ keys.has(field.key) ||
748
+ !Object.prototype.hasOwnProperty.call(field, 'before') ||
749
+ !Object.prototype.hasOwnProperty.call(field, 'after') ||
750
+ (field.key === 'name'
751
+ ? typeof field.before !== 'string' ||
752
+ typeof field.after !== 'string'
753
+ : typeof field.before !== 'boolean' ||
754
+ typeof field.after !== 'boolean')) {
755
+ throw new Error('[SceneTree] Canonical element data mutation has invalid field evidence');
756
+ }
757
+ keys.add(field.key);
758
+ if (field.key === 'name') {
759
+ values.name = field.after;
760
+ }
761
+ else if (field.key === 'visible') {
762
+ values.visible = field.after;
763
+ }
764
+ else {
765
+ values.lock = field.after;
766
+ }
767
+ });
768
+ return {
769
+ elementId: change.id,
770
+ values
771
+ };
772
+ });
773
+ const preparedMutation = this.prepareElementDataMutation(requests);
774
+ if (!isEqual(preparedMutation.evidence, changes)) {
775
+ throw new Error('[SceneTree] Cannot prepare stale canonical element data evidence');
776
+ }
777
+ return preparedMutation;
778
+ }
779
+ prepareElementInsertionEntries(sourceEntries, kind, sourceOwnerRelations) {
780
+ const artifactKind = kind === 'prepared-element-insertion'
781
+ ? 'element-insertion'
782
+ : 'canonical-element-insertion';
783
+ const ordinaryOwnerRelations = kind === 'prepared-element-insertion' &&
784
+ sourceOwnerRelations !== undefined
785
+ ? cloneSceneTreeValue(sourceOwnerRelations)
786
+ : undefined;
787
+ if (kind === 'prepared-element-insertion' &&
788
+ !Array.isArray(ordinaryOwnerRelations)) {
789
+ throw new Error('[SceneTree] Ordinary element insertion requires explicit owner relations');
790
+ }
791
+ const relationByOwner = new Map();
792
+ (ordinaryOwnerRelations ?? []).forEach((relation) => {
793
+ if (!isRecord(relation) ||
794
+ typeof relation.ownerElementId !== 'string' ||
795
+ relation.ownerElementId.length === 0 ||
796
+ typeof relation.ownerElementType !== 'string' ||
797
+ relation.ownerElementType.length === 0 ||
798
+ typeof relation.ownerPropertyName !== 'string' ||
799
+ relation.ownerPropertyName.length === 0 ||
800
+ typeof relation.componentId !== 'string' ||
801
+ relation.componentId.length === 0) {
802
+ throw new Error('[SceneTree] Ordinary element insertion has an invalid owner relation');
803
+ }
804
+ const relationsForOwner = relationByOwner.get(relation.ownerElementId) ?? new Map();
805
+ if (relationsForOwner.has(relation.ownerPropertyName)) {
806
+ throw new Error(`[SceneTree] Ordinary element insertion has duplicate owner relation "${relation.ownerElementId}.${relation.ownerPropertyName}"`);
807
+ }
808
+ relationsForOwner.set(relation.ownerPropertyName, relation);
809
+ relationByOwner.set(relation.ownerElementId, relationsForOwner);
810
+ });
811
+ const consumedOrdinaryRelations = new Set();
812
+ if (sourceEntries.length === 0) {
813
+ if ((ordinaryOwnerRelations?.length ?? 0) > 0) {
814
+ throw new Error('[SceneTree] Ordinary element insertion has owner relations outside the insertion batch');
815
+ }
816
+ const preparedMutation = cloneAndFreezeSceneValue({
817
+ kind,
818
+ orderedElementIds: [],
819
+ ...(kind === 'prepared-canonical-element-insertion'
820
+ ? { ownerRelations: [] }
821
+ : {}),
822
+ evidence: []
823
+ });
824
+ this.preparedElementMutationArtifacts.set(preparedMutation, {
825
+ kind: artifactKind,
826
+ entries: Object.freeze([]),
827
+ parents: new Map(),
828
+ parentChildrenBefore: new Map(),
829
+ parentChildrenAfter: new Map(),
830
+ relationIndexUpdates: Object.freeze([])
831
+ });
832
+ return preparedMutation;
833
+ }
834
+ const elementIds = new Set();
835
+ const parents = new Map();
836
+ const parentChildrenBefore = new Map();
837
+ const parentChildrenAfter = new Map();
838
+ const registrationContractByType = new Map();
839
+ const propertyNamesByType = new Map();
840
+ const registrationContracts = [];
841
+ const tombstones = [];
842
+ const propertyTypeByComponentId = new Map();
843
+ const propertyRelations = [];
844
+ const getParentChildren = (parentId) => {
845
+ const existingParent = parents.get(parentId);
846
+ const existingChildren = parentChildrenAfter.get(parentId);
847
+ if (existingParent && existingChildren) {
848
+ return {
849
+ parent: existingParent,
850
+ children: existingChildren
851
+ };
852
+ }
853
+ const parent = this.getElementById(parentId);
854
+ if (!parent || !isGroupEntity(parent.get('type'))) {
855
+ throw new Error(`[SceneTree] Element insertion requires active parent "${parentId}"`);
856
+ }
857
+ const before = Object.freeze([
858
+ ...this.getContainerChildren(parent, `Element insertion parent "${parentId}"`)
859
+ ]);
860
+ const after = [...before];
861
+ parents.set(parentId, parent);
862
+ parentChildrenBefore.set(parentId, before);
863
+ parentChildrenAfter.set(parentId, after);
864
+ return {
865
+ parent: parent,
866
+ children: after
867
+ };
868
+ };
869
+ sourceEntries.forEach((entry) => {
870
+ const source = isRecord(entry) ? entry.data : undefined;
871
+ const parentId = isRecord(entry) ? entry.parentId : undefined;
872
+ const index = isRecord(entry) ? entry.index : undefined;
873
+ const tombstone = isRecord(source) && typeof source.id === 'string'
874
+ ? this._deletedMap.get(source.id)
875
+ : undefined;
876
+ if (!isRecord(source) ||
877
+ typeof source.id !== 'string' ||
878
+ source.id.length === 0 ||
879
+ typeof source.type !== 'string' ||
880
+ source.type.length === 0 ||
881
+ typeof source.name !== 'string' ||
882
+ source.name.length === 0 ||
883
+ typeof parentId !== 'string' ||
884
+ parentId.length === 0 ||
885
+ source.parentId !== parentId ||
886
+ typeof source.visible !== 'boolean' ||
887
+ typeof source.lock !== 'boolean' ||
888
+ !isRecord(source.props) ||
889
+ !Number.isInteger(index) ||
890
+ Number(index) < 0 ||
891
+ elementIds.has(source.id) ||
892
+ this._elements.has(source.id) ||
893
+ (tombstone !== undefined &&
894
+ kind !== 'prepared-canonical-element-insertion')) {
895
+ throw new Error('[SceneTree] Element insertion requires unique exact inactive Scene data');
896
+ }
897
+ elementIds.add(source.id);
898
+ tombstones.push(tombstone);
899
+ let registrationContract = registrationContractByType.get(source.type);
900
+ if (!registrationContract) {
901
+ const registration = componentRegistry.get(source.type);
902
+ if (!registration) {
903
+ throw new Error(`[SceneTree] Element insertion has unregistered type "${source.type}"`);
904
+ }
905
+ registrationContract = captureElementInsertionRegistrationContract(registration, source.type);
906
+ registrationContractByType.set(source.type, registrationContract);
907
+ propertyNamesByType.set(source.type, new Set(registrationContract.effectiveDefinitions.map(({ name }) => name)));
908
+ }
909
+ registrationContracts.push(registrationContract);
910
+ const registration = registrationContract.registration;
911
+ if (tombstone) {
912
+ const expectedTombstoneData = {
913
+ ...source,
914
+ parentId: ''
915
+ };
916
+ if (!(tombstone instanceof registration.constructor) ||
917
+ tombstone.get('type') !== source.type ||
918
+ !isEqual(tombstone.save(), expectedTombstoneData)) {
919
+ throw new Error(`[SceneTree] Canonical insertion has incompatible tombstone "${source.id}"`);
920
+ }
921
+ }
922
+ const definitions = registrationContract.effectiveDefinitions;
923
+ const expectedPropertyNames = propertyNamesByType.get(source.type);
924
+ const sourceProps = source.props;
925
+ const sourcePropertyNames = Object.keys(sourceProps);
926
+ if (!expectedPropertyNames ||
927
+ sourcePropertyNames.some((propertyName) => !expectedPropertyNames.has(propertyName)) ||
928
+ sourcePropertyNames.length !== expectedPropertyNames.size) {
929
+ throw new Error(`[SceneTree] Element "${source.id}" requires exact property owner relations`);
930
+ }
931
+ const elementPropertyRelations = definitions.map((definition) => {
932
+ const propertyId = sourceProps[definition.name];
933
+ if (typeof propertyId !== 'string' || propertyId.length === 0) {
934
+ throw new Error(`[SceneTree] Element "${source.id}" has an invalid property owner relation for "${definition.name}"`);
935
+ }
936
+ const existingPropertyType = propertyTypeByComponentId.get(propertyId);
937
+ if (existingPropertyType !== undefined &&
938
+ existingPropertyType !== definition.type) {
939
+ throw new Error(`[SceneTree] Element insertion component "${propertyId}" has incompatible property types`);
940
+ }
941
+ propertyTypeByComponentId.set(propertyId, definition.type);
942
+ let ownerRelation;
943
+ if (kind === 'prepared-element-insertion') {
944
+ const relation = relationByOwner.get(source.id)?.get(definition.name);
945
+ if (!relation) {
946
+ throw new Error(`[SceneTree] Element "${source.id}" requires exact owner relation coverage for "${definition.name}"`);
947
+ }
948
+ if (relation.ownerElementType !== source.type ||
949
+ relation.componentId !== propertyId) {
950
+ throw new Error(`[SceneTree] Element "${source.id}" has an invalid owner relation for "${definition.name}"`);
951
+ }
952
+ consumedOrdinaryRelations.add(relation);
953
+ ownerRelation = relation;
954
+ }
955
+ else {
956
+ ownerRelation = {
957
+ ownerElementId: source.id,
958
+ ownerElementType: source.type,
959
+ ownerPropertyName: definition.name,
960
+ componentId: propertyId
961
+ };
962
+ }
963
+ return {
964
+ ownerElementId: ownerRelation.ownerElementId,
965
+ ownerElementType: ownerRelation.ownerElementType,
966
+ ownerPropertyName: ownerRelation.ownerPropertyName,
967
+ componentId: ownerRelation.componentId,
968
+ propertyType: definition.type
969
+ };
970
+ });
971
+ propertyRelations.push(elementPropertyRelations);
972
+ if ('children' in source &&
973
+ Array.isArray(source.children) &&
974
+ source.children.length > 0) {
975
+ throw new Error(`[SceneTree] Element insertion cannot materialize a populated subtree for "${source.id}"`);
976
+ }
977
+ getParentChildren(parentId);
978
+ });
979
+ if (ordinaryOwnerRelations &&
980
+ consumedOrdinaryRelations.size !== ordinaryOwnerRelations.length) {
981
+ throw new Error('[SceneTree] Ordinary element insertion has owner relations outside the insertion batch');
982
+ }
983
+ const entriesByParent = new Map();
984
+ sourceEntries.forEach((entry) => {
985
+ const entries = entriesByParent.get(entry.parentId) ?? [];
986
+ entries.push(entry);
987
+ entriesByParent.set(entry.parentId, entries);
988
+ });
989
+ entriesByParent.forEach((entries, parentId) => {
990
+ const children = parentChildrenAfter.get(parentId);
991
+ if (!children) {
992
+ throw new Error(`[SceneTree] Element insertion lost parent "${parentId}"`);
993
+ }
994
+ const sortedEntries = [...entries].sort((left, right) => left.index - right.index);
995
+ const usedIndexes = new Set();
996
+ sortedEntries.forEach(({ data, index }) => {
997
+ if (usedIndexes.has(index) || index < 0 || index > children.length) {
998
+ throw new Error('[SceneTree] Element insertion has an invalid index');
999
+ }
1000
+ usedIndexes.add(index);
1001
+ children.splice(index, 0, data.id);
1002
+ });
1003
+ });
1004
+ const preparedMutation = cloneAndFreezeSceneValue({
1005
+ kind,
1006
+ orderedElementIds: sourceEntries.map(({ data }) => data.id),
1007
+ ...(kind === 'prepared-canonical-element-insertion'
1008
+ ? {
1009
+ ownerRelations: propertyRelations
1010
+ .flat()
1011
+ .map(({ ownerElementId, ownerElementType, ownerPropertyName, componentId }) => ({
1012
+ ownerElementId,
1013
+ ownerElementType,
1014
+ ownerPropertyName,
1015
+ componentId
1016
+ }))
1017
+ }
1018
+ : {}),
1019
+ evidence: [
1020
+ {
1021
+ action: SCENE_TREE_ACTIONS.ADD_ELEMENTS,
1022
+ eventName: EventTypes.ADD_ELEMENTS,
1023
+ undoType: EventTypes.REMOVE_ELEMENTS,
1024
+ undoAction: SCENE_TREE_ACTIONS.REMOVE_ELEMENTS,
1025
+ entries: sourceEntries
1026
+ }
1027
+ ]
1028
+ });
1029
+ const frozenEntries = preparedMutation.evidence[0].entries;
1030
+ const relationIndexUpdates = this.prepareElementPropertyRelationInsertionsFromRelations(propertyRelations.flat());
1031
+ this.preparedElementMutationArtifacts.set(preparedMutation, {
1032
+ kind: artifactKind,
1033
+ entries: Object.freeze(frozenEntries.map(({ data }, index) => Object.freeze({
1034
+ data,
1035
+ ...(tombstones[index]
1036
+ ? {
1037
+ tombstone: tombstones[index]
1038
+ }
1039
+ : {}),
1040
+ registrationContract: registrationContracts[index],
1041
+ propertyRelations: Object.freeze(propertyRelations[index].map((relation) => Object.freeze({ ...relation })))
1042
+ }))),
1043
+ parents,
1044
+ parentChildrenBefore,
1045
+ parentChildrenAfter: new Map([...parentChildrenAfter].map(([parentId, children]) => [
1046
+ parentId,
1047
+ Object.freeze(children)
1048
+ ])),
1049
+ relationIndexUpdates
1050
+ });
1051
+ return preparedMutation;
1052
+ }
1053
+ prepareElementInsertion(request) {
1054
+ if (!isRecord(request) || !Array.isArray(request.elements)) {
1055
+ throw new Error('[SceneTree] Ordinary element insertion requires one typed parent batch');
1056
+ }
1057
+ if (!Array.isArray(request.ownerRelations)) {
1058
+ throw new Error('[SceneTree] Ordinary element insertion requires explicit owner relations');
1059
+ }
1060
+ if (request.elements.length === 0) {
1061
+ return this.prepareElementInsertionEntries([], 'prepared-element-insertion', request.ownerRelations);
1062
+ }
1063
+ if (typeof request.parentId !== 'string' || request.parentId.length === 0) {
1064
+ throw new Error('[SceneTree] Element insertion requires a parent id');
1065
+ }
1066
+ const parent = this.getElementById(request.parentId);
1067
+ if (!parent || !isGroupEntity(parent.get('type'))) {
1068
+ throw new Error(`[SceneTree] Element insertion requires active parent "${request.parentId}"`);
1069
+ }
1070
+ const parentChildren = this.getContainerChildren(parent, `Element insertion parent "${request.parentId}"`);
1071
+ const insertionIndex = request.index === undefined ? parentChildren.length : request.index;
1072
+ if (!Number.isInteger(insertionIndex) ||
1073
+ insertionIndex < 0 ||
1074
+ insertionIndex > parentChildren.length) {
1075
+ throw new Error('[SceneTree] Element insertion has an invalid index');
1076
+ }
1077
+ return this.prepareElementInsertionEntries(request.elements.map((data, offset) => ({
1078
+ data,
1079
+ parentId: request.parentId,
1080
+ index: insertionIndex + offset
1081
+ })), 'prepared-element-insertion', request.ownerRelations);
1082
+ }
1083
+ prepareCanonicalElementInsertion(request) {
1084
+ if (!isRecord(request) || !Array.isArray(request.entries)) {
1085
+ throw new Error('[SceneTree] Canonical element insertion requires exact ordered entries');
1086
+ }
1087
+ return this.prepareElementInsertionEntries(request.entries, 'prepared-canonical-element-insertion');
1088
+ }
1089
+ prepareElementRemovalMutation(removals, kind) {
1090
+ const relationRevisionBefore = this.elementPropertyRelationRevision;
1091
+ if (removals.length === 0) {
1092
+ const preparedMutation = cloneAndFreezeSceneValue({
1093
+ kind,
1094
+ orderedElementIds: [],
1095
+ relationReleases: [],
1096
+ orphanRootPropertyIds: [],
1097
+ retainedRootPropertyIds: this.collectRootPropertyIdsAfterRelationUpdates([]),
1098
+ evidence: []
1099
+ });
1100
+ this.preparedElementMutationArtifacts.set(preparedMutation, {
1101
+ kind: kind === 'prepared-element-removal'
1102
+ ? 'element-removal'
1103
+ : 'canonical-element-removal',
1104
+ entries: Object.freeze([]),
1105
+ relationRevisionBefore,
1106
+ relationIndexUpdates: Object.freeze([]),
1107
+ parentChildrenBefore: new Map(),
1108
+ parentChildrenAfter: new Map()
1109
+ });
1110
+ return preparedMutation;
1111
+ }
1112
+ const removalIds = new Set();
1113
+ const candidates = removals.map((source) => {
1114
+ const expected = typeof source === 'string' ? undefined : source;
1115
+ const elementId = typeof source === 'string' ? source : source.data.id;
1116
+ if (typeof elementId !== 'string' ||
1117
+ elementId.length === 0 ||
1118
+ removalIds.has(elementId)) {
1119
+ throw new Error('[SceneTree] Element removal requires unique active element ids');
1120
+ }
1121
+ removalIds.add(elementId);
1122
+ const element = this.getElementById(elementId);
1123
+ if (!element) {
1124
+ throw new Error(`[SceneTree] Cannot prepare removal for missing element "${elementId}"`);
1125
+ }
1126
+ if (element.get('type') === EntityTypes.WORKSPACE) {
1127
+ throw new Error('[SceneTree] Element removal cannot remove a workspace');
1128
+ }
1129
+ if (isGroupEntity(element.get('type')) &&
1130
+ this.getContainerChildren(element, `Element removal container "${elementId}"`).length > 0) {
1131
+ throw new Error(`[SceneTree] Element removal requires subtree lifecycle for "${elementId}"`);
1132
+ }
1133
+ const parentId = element.get('parentId');
1134
+ const parent = this.getElementById(parentId);
1135
+ if (typeof parentId !== 'string' ||
1136
+ parentId.length === 0 ||
1137
+ !parent ||
1138
+ !isGroupEntity(parent.get('type'))) {
1139
+ throw new Error(`[SceneTree] Element "${elementId}" has no active parent`);
1140
+ }
1141
+ return {
1142
+ element,
1143
+ expected,
1144
+ parentId,
1145
+ parent: parent
1146
+ };
1147
+ });
1148
+ const parentChildrenBefore = new Map();
1149
+ const parentIndexByElementId = new Map();
1150
+ candidates.forEach(({ parentId, parent }) => {
1151
+ if (parentChildrenBefore.has(parentId))
1152
+ return;
1153
+ const children = Object.freeze([
1154
+ ...this.getContainerChildren(parent, `Element removal parent "${parentId}"`)
1155
+ ]);
1156
+ parentChildrenBefore.set(parentId, children);
1157
+ parentIndexByElementId.set(parentId, new Map(children.map((elementId, index) => [elementId, index])));
1158
+ });
1159
+ const sourceEntries = candidates.map(({ element, expected, parentId }) => {
1160
+ const index = parentIndexByElementId
1161
+ .get(parentId)
1162
+ ?.get(element.get('id'));
1163
+ const data = element.save();
1164
+ if (index === undefined ||
1165
+ (expected !== undefined &&
1166
+ (expected.parentId !== parentId ||
1167
+ expected.index !== index ||
1168
+ !isEqual(expected.data, data)))) {
1169
+ throw new Error(`[SceneTree] Element removal has stale canonical evidence for "${element.get('id')}"`);
1170
+ }
1171
+ return {
1172
+ data,
1173
+ parentId,
1174
+ index
1175
+ };
1176
+ });
1177
+ const parentChildrenAfter = new Map([...parentChildrenBefore].map(([parentId, children]) => [
1178
+ parentId,
1179
+ Object.freeze(children.filter((id) => !removalIds.has(id)))
1180
+ ]));
1181
+ const relationIndexUpdates = this.prepareElementPropertyRelationRemovalsFromRelations(sourceEntries.flatMap(({ data }) => collectElementPropertyRelations(data)));
1182
+ const relationReleases = relationIndexUpdates.map(({ componentId, relationsBefore, relationsAfter }) => {
1183
+ const retainedTupleKeys = new Set(relationsAfter.map(getElementPropertyRelationTupleKey));
1184
+ return {
1185
+ componentId,
1186
+ relationsBefore,
1187
+ releasedRelations: relationsBefore.filter((relation) => !retainedTupleKeys.has(getElementPropertyRelationTupleKey(relation))),
1188
+ retainedRelations: relationsAfter
1189
+ };
1190
+ });
1191
+ const preparedMutation = cloneAndFreezeSceneValue({
1192
+ kind,
1193
+ orderedElementIds: sourceEntries.map(({ data }) => data.id),
1194
+ relationReleases,
1195
+ orphanRootPropertyIds: relationReleases
1196
+ .filter(({ retainedRelations }) => retainedRelations.length === 0)
1197
+ .map(({ componentId }) => componentId),
1198
+ retainedRootPropertyIds: this.collectRootPropertyIdsAfterRelationUpdates(relationIndexUpdates),
1199
+ evidence: [
1200
+ {
1201
+ action: SCENE_TREE_ACTIONS.REMOVE_ELEMENTS,
1202
+ eventName: EventTypes.REMOVE_ELEMENTS,
1203
+ undoType: EventTypes.ADD_ELEMENTS,
1204
+ undoAction: SCENE_TREE_ACTIONS.ADD_ELEMENTS,
1205
+ entries: sourceEntries
1206
+ }
1207
+ ]
1208
+ });
1209
+ const frozenEntries = preparedMutation.evidence[0].entries;
1210
+ this.preparedElementMutationArtifacts.set(preparedMutation, {
1211
+ kind: kind === 'prepared-element-removal'
1212
+ ? 'element-removal'
1213
+ : 'canonical-element-removal',
1214
+ entries: Object.freeze(candidates.map(({ element }, index) => Object.freeze({
1215
+ element,
1216
+ data: frozenEntries[index].data,
1217
+ parentId: frozenEntries[index].parentId,
1218
+ index: frozenEntries[index].index
1219
+ }))),
1220
+ relationRevisionBefore,
1221
+ relationIndexUpdates,
1222
+ parentChildrenBefore,
1223
+ parentChildrenAfter
1224
+ });
1225
+ return preparedMutation;
1226
+ }
1227
+ prepareElementRemoval(elementIds) {
1228
+ return this.prepareElementRemovalMutation(elementIds, 'prepared-element-removal');
1229
+ }
1230
+ prepareCanonicalElementRemoval(removals) {
1231
+ return this.prepareElementRemovalMutation(removals, 'prepared-canonical-element-removal');
1232
+ }
1233
+ prepareSubtreeRemoval(elementId) {
1234
+ this.validateCanonicalHierarchy();
1235
+ const relationRevisionBefore = this.elementPropertyRelationRevision;
1236
+ const removed = this.collectSubtreeRemovalEntries(elementId);
1237
+ const rootEntry = removed[removed.length - 1];
1238
+ const removalIds = new Set(removed.map((entry) => entry.elementId));
1239
+ const elements = removed.map((entry) => {
1240
+ const element = this.getElementById(entry.elementId);
1241
+ if (!element || !isEqual(element.save(), entry.data)) {
1242
+ throw new Error(`[SceneTree] Cannot prepare stale subtree element "${entry.elementId}"`);
1243
+ }
1244
+ return element;
1245
+ });
1246
+ const parentChildrenBefore = new Map();
1247
+ removed.forEach(({ parentId }) => {
1248
+ if (parentChildrenBefore.has(parentId)) {
1249
+ return;
1250
+ }
1251
+ const parent = this.getElementById(parentId);
1252
+ if (!parent || !isGroupEntity(parent.get('type'))) {
1253
+ throw new Error(`[SceneTree] Subtree removal requires active parent "${parentId}"`);
1254
+ }
1255
+ parentChildrenBefore.set(parentId, Object.freeze([
1256
+ ...this.getContainerChildren(parent, `Subtree removal parent "${parentId}"`)
1257
+ ]));
1258
+ });
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
+ const parentChildrenAfter = new Map([...parentChildrenBefore].map(([parentId, children]) => [
1265
+ parentId,
1266
+ Object.freeze(children.filter((id) => !removalIds.has(id)))
1267
+ ]));
1268
+ const rootParentChildrenAfter = parentChildrenAfter.get(rootEntry.parentId);
1269
+ if (!rootParentChildrenAfter) {
1270
+ throw new Error(`[SceneTree] Cannot prepare subtree parent order for "${rootEntry.elementId}"`);
1271
+ }
1272
+ const relationIndexUpdates = this.prepareElementPropertyRelationRemovalsFromRelations(removed.flatMap(({ data }) => collectElementPropertyRelations(data)));
1273
+ const relationReleases = relationIndexUpdates.map(({ componentId, relationsBefore, relationsAfter }) => {
1274
+ const retainedTupleKeys = new Set(relationsAfter.map(getElementPropertyRelationTupleKey));
1275
+ return {
1276
+ componentId,
1277
+ relationsBefore,
1278
+ releasedRelations: relationsBefore.filter((relation) => !retainedTupleKeys.has(getElementPropertyRelationTupleKey(relation))),
1279
+ retainedRelations: relationsAfter
1280
+ };
1281
+ });
1282
+ const preparedMutation = cloneAndFreezeSceneValue({
1283
+ kind: 'prepared-subtree-removal',
1284
+ orderedElementIds: removed.map(({ elementId: id }) => id),
1285
+ relationReleases,
1286
+ orphanRootPropertyIds: relationReleases
1287
+ .filter(({ retainedRelations }) => retainedRelations.length === 0)
1288
+ .map(({ componentId }) => componentId),
1289
+ 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
+ ]
1300
+ });
1301
+ const frozenRemoved = preparedMutation.evidence[0].removed;
1302
+ this.preparedElementMutationArtifacts.set(preparedMutation, {
1303
+ kind: 'subtree-removal',
1304
+ entries: Object.freeze(elements.map((element, index) => Object.freeze({
1305
+ element,
1306
+ data: frozenRemoved[index].data,
1307
+ parentId: frozenRemoved[index].parentId,
1308
+ index: frozenRemoved[index].index
1309
+ }))),
1310
+ relationRevisionBefore,
1311
+ relationIndexUpdates,
1312
+ parentChildrenBefore,
1313
+ parentChildrenAfter
1314
+ });
1315
+ return preparedMutation;
1316
+ }
1317
+ prepareCanonicalSubtreeRemoval(change) {
1318
+ if (!isRecord(change) ||
1319
+ change.action !== SCENE_TREE_ACTIONS.REMOVE_SUBTREE ||
1320
+ change.undoAction !== SCENE_TREE_ACTIONS.RESTORE_SUBTREE ||
1321
+ change.eventName !== EventTypes.CHANGE_SUBTREE ||
1322
+ typeof change.elementId !== 'string' ||
1323
+ change.elementId.length === 0) {
1324
+ throw new Error('[SceneTree] Canonical subtree removal has invalid evidence');
1325
+ }
1326
+ const preparedMutation = this.prepareSubtreeRemoval(change.elementId);
1327
+ if (!isEqual(preparedMutation.evidence[0], change)) {
1328
+ throw new Error(`[SceneTree] Cannot prepare stale canonical subtree removal for "${change.elementId}"`);
1329
+ }
1330
+ return preparedMutation;
1331
+ }
1332
+ applyPreparedElementMutation(preparedMutation, options) {
1333
+ const artifact = this.preparedElementMutationArtifacts.get(preparedMutation);
1334
+ if (!artifact) {
1335
+ throw new Error('[SceneTree] Expected an owner-issued one-shot prepared element mutation');
1336
+ }
1337
+ this.preparedElementMutationArtifacts.delete(preparedMutation);
1338
+ if (preparedMutation.evidence.length === 0) {
1339
+ return Object.freeze({
1340
+ orderedElementIds: preparedMutation.orderedElementIds,
1341
+ evidence: preparedMutation.evidence
1342
+ });
1343
+ }
1344
+ const transactionOwner = getTransactionOwner();
1345
+ if (!transactionOwner) {
1346
+ throw new Error('[SceneTree] Applying a prepared element mutation requires an active transaction owner');
1347
+ }
1348
+ const resolvedOptions = Object.freeze({
1349
+ ...(options ?? {}),
1350
+ shared: options?.shared ?? SharedDataChannelNames.SCENE_TREE
1351
+ });
1352
+ 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;
1356
+ const canonicalEvidence = Object.freeze({
1357
+ orderedIds,
1358
+ ...(isElementBatchChange(payload)
1359
+ ? { sharedRecords: createElementBatchSharedRecords(payload) }
1360
+ : {})
1361
+ });
1362
+ return Object.freeze({
1363
+ type: EventTypes.UPDATE_TRANSACTION,
1364
+ eventName: payload.eventName,
1365
+ payload,
1366
+ options: resolvedOptions,
1367
+ canonicalEvidence
1368
+ });
1369
+ }));
1370
+ if (artifact.kind === 'element-data-mutation') {
1371
+ artifact.entries.forEach(({ element, before }) => {
1372
+ if (this.getElementById(element.get('id')) !== element ||
1373
+ element.get('name') !== before.name ||
1374
+ element.get('visible') !== before.visible ||
1375
+ element.get('lock') !== before.lock) {
1376
+ throw new Error(`[SceneTree] Cannot apply stale prepared element data mutation for "${element.get('id')}"`);
1377
+ }
1378
+ });
1379
+ artifact.entries.forEach(({ element, after }) => {
1380
+ ;
1381
+ element.assignCanonicalElementData(after);
1382
+ });
1383
+ try {
1384
+ transactionOwner.updateTransactionBatch(events);
1385
+ acknowledgeTransactionReplayApplied();
1386
+ }
1387
+ catch (error) {
1388
+ if (reportsAcceptedCanonicalBatchHandoff(error)) {
1389
+ acknowledgeTransactionReplayApplied();
1390
+ }
1391
+ else {
1392
+ artifact.entries.forEach(({ element, before }) => {
1393
+ ;
1394
+ element.assignCanonicalElementData(before);
1395
+ });
1396
+ }
1397
+ throw error;
1398
+ }
1399
+ }
1400
+ if (artifact.kind === 'element-insertion' ||
1401
+ artifact.kind === 'canonical-element-insertion') {
1402
+ artifact.parents.forEach((parent, parentId) => {
1403
+ const before = artifact.parentChildrenBefore.get(parentId);
1404
+ if (!before ||
1405
+ this.getElementById(parentId) !== parent ||
1406
+ !isEqual(this.getContainerChildren(parent, `Element insertion parent "${parentId}"`), before)) {
1407
+ throw new Error(`[SceneTree] Cannot apply stale element insertion parent "${parentId}"`);
1408
+ }
1409
+ });
1410
+ artifact.entries.forEach(({ data, tombstone, registrationContract }) => {
1411
+ if (this._elements.has(data.id) ||
1412
+ !isElementInsertionRegistrationContractCurrent(registrationContract, data.type) ||
1413
+ (tombstone
1414
+ ? this._deletedMap.get(data.id) !== tombstone
1415
+ : this._deletedMap.has(data.id))) {
1416
+ throw new Error(`[SceneTree] Cannot apply stale prepared element insertion for "${data.id}"`);
1417
+ }
1418
+ });
1419
+ artifact.entries.forEach(({ data, propertyRelations: expectedRelations }) => {
1420
+ expectedRelations.forEach(({ ownerElementId, ownerElementType, ownerPropertyName, componentId, propertyType }) => {
1421
+ const property = this.propsManagerOwner.getPropertyById(componentId);
1422
+ if (!property ||
1423
+ property.get('id') !== componentId ||
1424
+ property.get('type') !== propertyType ||
1425
+ ownerElementId !== data.id ||
1426
+ ownerElementType !== data.type ||
1427
+ data.props?.[ownerPropertyName] !== componentId) {
1428
+ throw new Error(`[SceneTree] Cannot apply stale property relation "${data.id}.${ownerPropertyName}"`);
1429
+ }
1430
+ });
1431
+ });
1432
+ artifact.relationIndexUpdates.forEach(({ componentId, relationsBefore }) => {
1433
+ if (!isEqual(this.getElementPropertyRelations(componentId), relationsBefore)) {
1434
+ throw new Error(`[SceneTree] Cannot apply stale element property relation index for "${componentId}"`);
1435
+ }
1436
+ });
1437
+ const elements = [];
1438
+ const changedParentIds = [];
1439
+ let elementMapChanged = false;
1440
+ let relationIndexUpdates;
1441
+ try {
1442
+ artifact.entries.forEach(({ data, tombstone }) => {
1443
+ const element = tombstone ?? this.createElement(data, false);
1444
+ if (!element) {
1445
+ throw new Error(`[SceneTree] Element insertion could not materialize exact Scene data for "${data.id}"`);
1446
+ }
1447
+ elements.push(element);
1448
+ if (tombstone) {
1449
+ ;
1450
+ element.assignCanonicalParentId(data.parentId ?? '');
1451
+ reactivateElementComputed(element);
1452
+ }
1453
+ if (element.get('id') !== data.id ||
1454
+ element.get('type') !== data.type) {
1455
+ throw new Error(`[SceneTree] Element insertion could not materialize exact Scene data for "${data.id}"`);
1456
+ }
1457
+ });
1458
+ elements.forEach((element, index) => {
1459
+ const parentId = artifact.entries[index].data.parentId;
1460
+ if (!parentId || !artifact.parents.has(parentId)) {
1461
+ throw new Error(`[SceneTree] Element insertion lost parent for "${element.get('id')}"`);
1462
+ }
1463
+ ;
1464
+ element.assignCanonicalParentId(parentId);
1465
+ });
1466
+ elements.forEach((element) => {
1467
+ this._deletedMap.delete(element.get('id'));
1468
+ });
1469
+ relationIndexUpdates = this.addElementsToCanonicalMap(elements, artifact.relationIndexUpdates);
1470
+ elementMapChanged = true;
1471
+ artifact.parentChildrenAfter.forEach((children, parentId) => {
1472
+ const parent = artifact.parents.get(parentId);
1473
+ if (!parent) {
1474
+ throw new Error(`[SceneTree] Element insertion lost parent "${parentId}"`);
1475
+ }
1476
+ changedParentIds.push(parentId);
1477
+ this.currentWorkspace.replaceBatchParentChildren(parent, children);
1478
+ });
1479
+ transactionOwner.updateTransactionBatch(events);
1480
+ acknowledgeTransactionReplayApplied();
1481
+ }
1482
+ catch (error) {
1483
+ if (reportsAcceptedCanonicalBatchHandoff(error)) {
1484
+ acknowledgeTransactionReplayApplied();
1485
+ }
1486
+ else {
1487
+ changedParentIds.reverse().forEach((parentId) => {
1488
+ const parent = artifact.parents.get(parentId);
1489
+ const before = artifact.parentChildrenBefore.get(parentId);
1490
+ if (!parent || !before)
1491
+ return;
1492
+ try {
1493
+ ;
1494
+ this.currentWorkspace.replaceBatchParentChildren(parent, before);
1495
+ }
1496
+ catch {
1497
+ // Keep attempting cleanup while preserving the primary failure.
1498
+ }
1499
+ });
1500
+ if (elementMapChanged || elements.length > 0) {
1501
+ if (elementMapChanged && relationIndexUpdates) {
1502
+ this.rollbackElementsAddedToCanonicalMap(elements, relationIndexUpdates);
1503
+ }
1504
+ elements.forEach((element, index) => {
1505
+ const tombstone = artifact.entries[index]?.tombstone;
1506
+ try {
1507
+ ;
1508
+ element.assignCanonicalParentId('');
1509
+ }
1510
+ catch {
1511
+ // Keep attempting cleanup while preserving the primary failure.
1512
+ }
1513
+ try {
1514
+ disposeElementComputed(element);
1515
+ }
1516
+ catch {
1517
+ // Keep attempting cleanup while preserving the primary failure.
1518
+ }
1519
+ if (tombstone) {
1520
+ this._deletedMap.set(element.get('id'), tombstone);
1521
+ }
1522
+ else {
1523
+ this._deletedMap.delete(element.get('id'));
1524
+ }
1525
+ });
1526
+ }
1527
+ }
1528
+ throw error;
1529
+ }
1530
+ }
1531
+ if (artifact.kind === 'element-removal' ||
1532
+ artifact.kind === 'canonical-element-removal' ||
1533
+ artifact.kind === 'subtree-removal') {
1534
+ if (preparedMutation.kind !== 'prepared-element-removal' &&
1535
+ preparedMutation.kind !== 'prepared-canonical-element-removal' &&
1536
+ preparedMutation.kind !== 'prepared-subtree-removal') {
1537
+ throw new Error('[SceneTree] Element removal artifact does not match its owner-issued preparation');
1538
+ }
1539
+ const removalElements = artifact.entries.map(({ element }) => element);
1540
+ if (this.elementPropertyRelationRevision !== artifact.relationRevisionBefore) {
1541
+ throw new Error('[SceneTree] Cannot apply stale element property relation set');
1542
+ }
1543
+ const relationIndexUpdates = artifact.relationIndexUpdates;
1544
+ artifact.parentChildrenBefore.forEach((children, parentId) => {
1545
+ const parent = this.getElementById(parentId);
1546
+ if (!parent ||
1547
+ !isGroupEntity(parent.get('type')) ||
1548
+ !isEqual(this.getContainerChildren(parent, `Element removal parent "${parentId}"`), children)) {
1549
+ throw new Error(`[SceneTree] Cannot apply stale element removal parent "${parentId}"`);
1550
+ }
1551
+ });
1552
+ artifact.entries.forEach(({ element, data, parentId, index }) => {
1553
+ const parentChildren = artifact.parentChildrenBefore.get(parentId);
1554
+ if (this.getElementById(data.id) !== element ||
1555
+ !isEqual(element.save(), data) ||
1556
+ parentChildren?.[index] !== data.id) {
1557
+ throw new Error(`[SceneTree] Cannot apply stale prepared element removal for "${data.id}"`);
1558
+ }
1559
+ });
1560
+ const changedParentIds = [];
1561
+ let elementMapChanged = false;
1562
+ const handoffState = createCanonicalBatchHandoffState();
1563
+ let disposalAttempted = false;
1564
+ const disposeRemoved = () => {
1565
+ artifact.entries.forEach(({ element }) => {
1566
+ disposeElementComputed(element);
1567
+ });
1568
+ };
1569
+ try {
1570
+ artifact.parentChildrenAfter.forEach((children, parentId) => {
1571
+ const parent = this.getElementById(parentId);
1572
+ changedParentIds.push(parentId);
1573
+ this.currentWorkspace.replaceBatchParentChildren(parent, children);
1574
+ });
1575
+ this.removeElementsFromCanonicalMap(removalElements, relationIndexUpdates);
1576
+ elementMapChanged = true;
1577
+ artifact.entries.forEach(({ element }) => {
1578
+ ;
1579
+ element.assignCanonicalParentId('');
1580
+ this._deletedMap.set(element.get('id'), element);
1581
+ });
1582
+ transactionOwner.updateTransactionBatch(events);
1583
+ markCanonicalBatchHandoffAccepted(handoffState);
1584
+ acknowledgeTransactionReplayApplied();
1585
+ disposalAttempted = true;
1586
+ disposeRemoved();
1587
+ }
1588
+ catch (error) {
1589
+ if (wasCanonicalBatchHandoffAccepted(handoffState) ||
1590
+ reportsAcceptedCanonicalBatchHandoff(error)) {
1591
+ markCanonicalBatchHandoffAccepted(handoffState);
1592
+ acknowledgeTransactionReplayApplied();
1593
+ if (!disposalAttempted) {
1594
+ disposalAttempted = true;
1595
+ disposeRemoved();
1596
+ }
1597
+ }
1598
+ else {
1599
+ if (elementMapChanged) {
1600
+ this.restoreElementsToCanonicalMap(removalElements, relationIndexUpdates);
1601
+ artifact.entries.forEach(({ element, parentId }) => {
1602
+ this._deletedMap.delete(element.get('id'));
1603
+ element.assignCanonicalParentId(parentId);
1604
+ });
1605
+ }
1606
+ changedParentIds.reverse().forEach((parentId) => {
1607
+ const children = artifact.parentChildrenBefore.get(parentId);
1608
+ if (!children)
1609
+ return;
1610
+ const parent = this.getElementById(parentId);
1611
+ this.currentWorkspace.replaceBatchParentChildren(parent, children);
1612
+ });
1613
+ }
1614
+ throw error;
1615
+ }
1616
+ }
1617
+ return Object.freeze({
1618
+ orderedElementIds: preparedMutation.orderedElementIds,
1619
+ evidence: preparedMutation.evidence
1620
+ });
1621
+ }
1622
+ captureElementPropertyContract(elements) {
1623
+ const registrationContractByType = new Map();
1624
+ const propertyTypeByComponentId = new Map();
1625
+ const relations = [];
1626
+ for (const elementData of elements) {
1627
+ if (elementData.type === EntityTypes.WORKSPACE) {
1628
+ continue;
1629
+ }
1630
+ let registrationContract = registrationContractByType.get(elementData.type);
1631
+ if (!registrationContract) {
1632
+ const registration = componentRegistry.get(elementData.type);
1633
+ if (!registration) {
1634
+ throw new Error(`[SceneTree] Element "${elementData.id}" has an unregistered type`);
1635
+ }
1636
+ registrationContract = captureElementInsertionRegistrationContract(registration, elementData.type);
1637
+ registrationContractByType.set(elementData.type, registrationContract);
1638
+ }
1639
+ const sourceProps = elementData.props ?? {};
1640
+ if (!isRecord(sourceProps)) {
1641
+ throw new Error(`[SceneTree] Element "${elementData.id}" has invalid property relations`);
1642
+ }
1643
+ const definitionByName = new Map(registrationContract.effectiveDefinitions.map((definition) => [
1644
+ definition.name,
1645
+ definition
1646
+ ]));
1647
+ const propertyNames = Object.keys(sourceProps);
1648
+ if (propertyNames.length !== definitionByName.size ||
1649
+ propertyNames.some((propertyName) => !definitionByName.has(propertyName))) {
1650
+ throw new Error(`[SceneTree] Element "${elementData.id}" requires exact registered property slots`);
1651
+ }
1652
+ registrationContract.effectiveDefinitions.forEach((definition) => {
1653
+ const componentId = sourceProps[definition.name];
1654
+ if (typeof componentId !== 'string' || componentId.length === 0) {
1655
+ throw new Error(`[SceneTree] Element "${elementData.id}" has an invalid property relation for "${definition.name}"`);
1656
+ }
1657
+ const existingPropertyType = propertyTypeByComponentId.get(componentId);
1658
+ if (existingPropertyType !== undefined &&
1659
+ existingPropertyType !== definition.type) {
1660
+ throw new Error(`[SceneTree] Property "${componentId}" has incompatible registered property slots`);
1661
+ }
1662
+ propertyTypeByComponentId.set(componentId, definition.type);
1663
+ relations.push(Object.freeze({
1664
+ ownerElementId: elementData.id,
1665
+ ownerElementType: elementData.type,
1666
+ ownerPropertyName: definition.name,
1667
+ componentId,
1668
+ propertyType: definition.type
1669
+ }));
1670
+ });
1671
+ }
1672
+ return Object.freeze({
1673
+ relations: Object.freeze(relations),
1674
+ registrationContracts: Object.freeze([...registrationContractByType.entries()].map(([elementType, contract]) => Object.freeze({
1675
+ elementType,
1676
+ contract
1677
+ })))
1678
+ });
1679
+ }
1680
+ assertElementPropertyContractActive(contract) {
1681
+ this.assertElementPropertyRegistrationContractsCurrent(contract);
1682
+ contract.relations.forEach(({ ownerElementId, ownerPropertyName, componentId, propertyType }) => {
1683
+ const property = this.propsManagerOwner.getPropertyById(componentId);
1684
+ if (!property ||
1685
+ property.get('id') !== componentId ||
1686
+ property.get('type') !== propertyType) {
1687
+ throw new Error(`[SceneTree] Element "${ownerElementId}" has an invalid active property relation "${ownerPropertyName}" to "${componentId}"`);
1688
+ }
1689
+ });
1690
+ }
1691
+ assertElementPropertyRegistrationContractsCurrent(contract) {
1692
+ contract.registrationContracts.forEach(({ elementType, contract }) => {
1693
+ if (!isElementInsertionRegistrationContractCurrent(contract, elementType)) {
1694
+ throw new Error(`[SceneTree] Element type "${elementType}" has stale registered property slots`);
1695
+ }
1696
+ });
1697
+ }
1698
+ preflightLoadPropertyRelations(sceneValidation, propsData) {
1699
+ const artifact = this.validatedLoadArtifacts.get(sceneValidation);
1700
+ if (!artifact) {
1701
+ throw new Error('[SceneTree] Expected an owner-issued validated load artifact for property relation preflight');
1702
+ }
1703
+ if (!artifact.valid) {
1704
+ throw new Error('[SceneTree] Cannot preflight property relations for an invalid hierarchy');
1705
+ }
1706
+ if (artifact.propertyContractError || !artifact.propertyContract) {
1707
+ throw new Error(artifact.propertyContractError ??
1708
+ '[SceneTree] Validated load is missing exact property relation evidence');
1709
+ }
1710
+ if (!isRecord(propsData)) {
1711
+ throw new Error('[SceneTree] Detached Props validated data must be an exact component map');
1712
+ }
1713
+ this.assertElementPropertyRegistrationContractsCurrent(artifact.propertyContract);
1714
+ artifact.propertyContract.relations.forEach(({ ownerElementId, ownerPropertyName, componentId, propertyType }) => {
1715
+ const propertyData = propsData[componentId];
1716
+ if (!isRecord(propertyData) ||
1717
+ propertyData.id !== componentId ||
1718
+ propertyData.type !== propertyType) {
1719
+ throw new Error(`[SceneTree] Element "${ownerElementId}" has an invalid detached property relation "${ownerPropertyName}" to "${componentId}"`);
1720
+ }
1721
+ });
1722
+ }
1723
+ createLoadValidationResult(data, diagnostics, valid = true) {
1724
+ const validatedSnapshot = cloneLoadData(data);
1725
+ let propertyContract;
1726
+ let propertyContractError;
1727
+ try {
1728
+ propertyContract = this.captureElementPropertyContract(Object.values(validatedSnapshot.elements));
1729
+ }
1730
+ catch (error) {
1731
+ propertyContractError =
1732
+ error instanceof Error ? error.message : String(error);
1733
+ }
1734
+ const result = {
1735
+ data: cloneLoadData(validatedSnapshot),
1736
+ diagnostics,
1737
+ valid
1738
+ };
1739
+ this.validatedLoadArtifacts.set(result, {
1740
+ data: validatedSnapshot,
1741
+ valid,
1742
+ propertyContract,
1743
+ propertyContractError
1744
+ });
1745
+ return result;
1746
+ }
1747
+ validateNormalizedLoadHierarchy(data, diagnostics) {
1748
+ let valid = true;
1749
+ const reject = (path, message) => {
1750
+ diagnostics.push({ path, message });
1751
+ valid = false;
1752
+ };
1753
+ const entries = Object.entries(data.elements);
1754
+ const workspaceIds = entries
1755
+ .filter(([, element]) => element.type === EntityTypes.WORKSPACE)
1756
+ .map(([elementId]) => elementId);
1757
+ const nonWorkspaceIds = entries
1758
+ .filter(([, element]) => element.type !== EntityTypes.WORKSPACE)
1759
+ .map(([elementId]) => elementId);
1760
+ if (workspaceIds.length === 0) {
1761
+ if (nonWorkspaceIds.length > 0) {
1762
+ reject('sceneTree.workspace', 'Hierarchy with elements requires an existing workspace root');
1763
+ }
1764
+ if (data.workspace.length > 0 || data.workspaceList.length > 0) {
1765
+ reject('sceneTree.workspace', 'Workspace metadata cannot reference missing workspace roots');
1766
+ }
1767
+ }
1768
+ else {
1769
+ if (!workspaceIds.includes(data.workspace)) {
1770
+ reject('sceneTree.workspace', 'Active workspace must reference an existing workspace element');
1771
+ }
1772
+ if (new Set(data.workspaceList).size !== data.workspaceList.length) {
1773
+ reject('sceneTree.workspaceList', 'Workspace list cannot contain duplicate roots');
1774
+ }
1775
+ data.workspaceList.forEach((workspaceId, index) => {
1776
+ if (!workspaceIds.includes(workspaceId)) {
1777
+ reject(`sceneTree.workspaceList.${index}`, `Workspace root "${workspaceId}" is missing or has the wrong type`);
1778
+ }
1779
+ });
1780
+ workspaceIds.forEach((workspaceId) => {
1781
+ if (!data.workspaceList.includes(workspaceId)) {
1782
+ reject('sceneTree.workspaceList', `Workspace root "${workspaceId}" is missing from workspaceList`);
1783
+ }
1784
+ });
1785
+ }
1786
+ const membership = new Map();
1787
+ entries.forEach(([parentId, parent]) => {
1788
+ if (!isGroupEntity(parent.type)) {
1789
+ return;
1790
+ }
1791
+ const children = parent.children;
1792
+ if (!Array.isArray(children)) {
1793
+ reject(`sceneTree.elements.${parentId}.children`, 'Registered containers require a children array');
1794
+ return;
1795
+ }
1796
+ const localChildren = new Set();
1797
+ children.forEach((childId, index) => {
1798
+ const childPath = `sceneTree.elements.${parentId}.children.${index}`;
1799
+ if (localChildren.has(childId) || membership.has(childId)) {
1800
+ reject(childPath, `Element "${childId}" has duplicate hierarchy membership`);
1801
+ return;
1802
+ }
1803
+ localChildren.add(childId);
1804
+ membership.set(childId, parentId);
1805
+ const child = data.elements[childId];
1806
+ if (!child) {
1807
+ reject(childPath, `Hierarchy child "${childId}" is missing`);
1808
+ return;
1809
+ }
1810
+ if (child.type === EntityTypes.WORKSPACE) {
1811
+ reject(childPath, 'Workspace roots cannot be hierarchy children');
1812
+ }
1813
+ if (child.parentId !== parentId) {
1814
+ reject(childPath, `Hierarchy child "${childId}" disagrees with parentId`);
1815
+ }
1816
+ });
1817
+ });
1818
+ nonWorkspaceIds.forEach((elementId) => {
1819
+ const element = data.elements[elementId];
1820
+ const parentId = element.parentId ?? '';
1821
+ const parent = data.elements[parentId];
1822
+ if (!parent || !isGroupEntity(parent.type)) {
1823
+ reject(`sceneTree.elements.${elementId}.parentId`, `Element "${elementId}" requires an existing registered container parent`);
1824
+ }
1825
+ if (membership.get(elementId) !== parentId) {
1826
+ reject(`sceneTree.elements.${elementId}.parentId`, `Element "${elementId}" must appear exactly once in its parent children`);
1827
+ }
1828
+ const visited = new Set([elementId]);
1829
+ let ancestorId = parentId;
1830
+ while (ancestorId) {
1831
+ if (visited.has(ancestorId)) {
1832
+ reject(`sceneTree.elements.${elementId}.parentId`, `Hierarchy cycle detected at "${elementId}"`);
1833
+ break;
1834
+ }
1835
+ visited.add(ancestorId);
1836
+ const ancestor = data.elements[ancestorId];
1837
+ if (!ancestor || ancestor.type === EntityTypes.WORKSPACE) {
1838
+ break;
1839
+ }
1840
+ ancestorId = ancestor.parentId ?? '';
1841
+ }
1842
+ });
1843
+ return valid;
1844
+ }
1845
+ validateLoadData(data) {
1846
+ const diagnostics = [];
1847
+ const fallback = {
1848
+ workspace: '',
1849
+ workspaceList: [],
1850
+ elements: {}
1851
+ };
1852
+ if (!isRecord(data)) {
1853
+ diagnostics.push({
1854
+ path: 'sceneTree',
1855
+ message: 'Expected object payload for scene tree load'
1856
+ });
1857
+ return this.createLoadValidationResult(fallback, diagnostics, false);
1858
+ }
1859
+ const workspace = typeof data.workspace === 'string' ? data.workspace : '';
1860
+ if (data.workspace !== undefined && typeof data.workspace !== 'string') {
1861
+ diagnostics.push({
1862
+ path: 'sceneTree.workspace',
1863
+ message: 'Invalid workspace id type, fallback to empty workspace id'
1864
+ });
1865
+ }
1866
+ const workspaceList = toStringArray(data.workspaceList);
1867
+ if (data.workspaceList !== undefined &&
1868
+ !Array.isArray(data.workspaceList)) {
1869
+ diagnostics.push({
1870
+ path: 'sceneTree.workspaceList',
1871
+ message: 'Invalid workspace list type, fallback to empty workspace list'
1872
+ });
1873
+ }
1874
+ const elements = {};
1875
+ let hasDuplicateElementIds = false;
1876
+ if (data.elements === undefined) {
1877
+ diagnostics.push({
1878
+ path: 'sceneTree.elements',
1879
+ message: 'Missing elements map, fallback to empty map'
1880
+ });
1881
+ }
1882
+ else if (!isRecord(data.elements)) {
1883
+ diagnostics.push({
1884
+ path: 'sceneTree.elements',
1885
+ message: 'Invalid elements map type, fallback to empty map'
1886
+ });
1887
+ }
1888
+ else {
1889
+ Object.entries(data.elements).forEach(([entryId, rawElement]) => {
1890
+ if (!isRecord(rawElement)) {
1891
+ diagnostics.push({
1892
+ path: `sceneTree.elements.${entryId}`,
1893
+ message: 'Skipped non-object element during load'
1894
+ });
1895
+ return;
1896
+ }
1897
+ const rawType = rawElement.type;
1898
+ if (typeof rawType !== 'string' || rawType.length === 0) {
1899
+ diagnostics.push({
1900
+ path: `sceneTree.elements.${entryId}.type`,
1901
+ message: 'Skipped element with invalid type during load'
1902
+ });
1903
+ return;
1904
+ }
1905
+ if (rawType !== EntityTypes.WORKSPACE &&
1906
+ !componentRegistry.has(rawType)) {
1907
+ diagnostics.push({
1908
+ path: `sceneTree.elements.${entryId}.type`,
1909
+ message: `Skipped unregistered element type "${rawType}" during load`
1910
+ });
1911
+ return;
1912
+ }
1913
+ const normalizedId = typeof rawElement.id === 'string' && rawElement.id.length > 0
1914
+ ? rawElement.id
1915
+ : entryId;
1916
+ const normalizedName = typeof rawElement.name === 'string' && rawElement.name.length > 0
1917
+ ? rawElement.name
1918
+ : normalizedId;
1919
+ const visible = typeof rawElement.visible === 'boolean' ? rawElement.visible : true;
1920
+ const lock = typeof rawElement.lock === 'boolean' ? rawElement.lock : false;
1921
+ const parentId = typeof rawElement.parentId === 'string' ? rawElement.parentId : '';
1922
+ const normalized = {
1923
+ ...rawElement,
1924
+ id: normalizedId,
1925
+ type: rawType,
1926
+ name: normalizedName,
1927
+ parentId,
1928
+ visible,
1929
+ lock
1930
+ };
1931
+ if (rawElement.parentId !== undefined &&
1932
+ typeof rawElement.parentId !== 'string') {
1933
+ diagnostics.push({
1934
+ path: `sceneTree.elements.${entryId}.parentId`,
1935
+ message: 'Invalid parent id type, fallback to empty parent id'
1936
+ });
1937
+ }
1938
+ if (isGroupEntity(rawType)) {
1939
+ normalized.children = toStringArray(rawElement.children);
1940
+ }
1941
+ if (rawElement.props !== undefined) {
1942
+ if (!isRecord(rawElement.props)) {
1943
+ diagnostics.push({
1944
+ path: `sceneTree.elements.${entryId}.props`,
1945
+ message: 'Invalid props map type, fallback to empty props map'
1946
+ });
1947
+ normalized.props = {};
1948
+ }
1949
+ else {
1950
+ const propsMap = {};
1951
+ Object.entries(rawElement.props).forEach(([key, value]) => {
1952
+ if (typeof value === 'string') {
1953
+ propsMap[key] = value;
1954
+ }
1955
+ else {
1956
+ diagnostics.push({
1957
+ path: `sceneTree.elements.${entryId}.props.${key}`,
1958
+ message: 'Skipped non-string prop reference during load'
1959
+ });
1960
+ }
1961
+ });
1962
+ normalized.props = propsMap;
1963
+ }
1964
+ }
1965
+ if (Object.prototype.hasOwnProperty.call(elements, normalizedId)) {
1966
+ diagnostics.push({
1967
+ path: `sceneTree.elements.${entryId}.id`,
1968
+ message: `Duplicate normalized element id "${normalizedId}"`
1969
+ });
1970
+ hasDuplicateElementIds = true;
1971
+ return;
1972
+ }
1973
+ elements[normalizedId] = normalized;
1974
+ });
1975
+ }
1976
+ const normalizedData = {
1977
+ workspace,
1978
+ workspaceList,
1979
+ elements
1980
+ };
1981
+ const hierarchyValid = this.validateNormalizedLoadHierarchy(normalizedData, diagnostics);
1982
+ return this.createLoadValidationResult(normalizedData, diagnostics, hierarchyValid && !hasDuplicateElementIds);
1983
+ }
1984
+ applyValidatedLoad(result) {
1985
+ const artifact = this.validatedLoadArtifacts.get(result);
1986
+ if (!artifact) {
1987
+ throw new Error('[SceneTree] Expected an owner-issued one-shot validated load artifact');
1988
+ }
1989
+ this.validatedLoadArtifacts.delete(result);
1990
+ if (!artifact.valid) {
1991
+ throw new Error('[SceneTree] Cannot apply invalid hierarchy from validated load artifact');
1992
+ }
1993
+ if (artifact.propertyContractError || !artifact.propertyContract) {
1994
+ throw new Error(artifact.propertyContractError ??
1995
+ '[SceneTree] Validated load is missing exact property relation evidence');
1996
+ }
1997
+ this.assertElementPropertyContractActive(artifact.propertyContract);
1998
+ const validated = artifact.data;
1999
+ const nextElements = new Map();
2000
+ let nextRelations;
2001
+ try {
2002
+ for (const [elementId, elementData] of Object.entries(validated.elements)) {
2003
+ const element = elementData.type === EntityTypes.WORKSPACE
2004
+ ? createWorkspace(this, elementData)
2005
+ : createElement(elementData, this.propsManagerOwner);
2006
+ if (!element) {
2007
+ throw new Error(`[SceneTree] Validated hierarchy element "${elementId}" could not be constructed`);
2008
+ }
2009
+ nextElements.set(elementId, element);
2010
+ if (!isEqual(element.save(), elementData)) {
2011
+ throw new Error(`[SceneTree] Validated hierarchy element "${elementId}" changed exact load data`);
2012
+ }
2013
+ }
2014
+ nextRelations = this.buildElementPropertyRelationIndex(nextElements.values());
2015
+ }
2016
+ catch (error) {
2017
+ nextElements.forEach((element) => {
2018
+ try {
2019
+ disposeElementComputed(element);
2020
+ }
2021
+ catch {
2022
+ // Preserve the first load owner failure while attempting all cleanup.
2023
+ }
2024
+ });
2025
+ throw error;
2026
+ }
2027
+ const previousElements = [
2028
+ ...this._elements.values(),
2029
+ ...this._deletedMap.values()
2030
+ ];
2031
+ this.replaceCanonicalElementMap(nextElements, nextRelations);
2032
+ this._deletedMap.clear();
2033
+ this.changes = [];
2034
+ this.workspaceList = [...validated.workspaceList];
2035
+ this.workspace = validated.workspace;
2036
+ if (nextElements.size === 0)
2037
+ this._init();
2038
+ this.projectLocalComputedDataFromPropertyIds([...nextRelations.keys()]);
2039
+ previousElements.forEach((element) => {
2040
+ try {
2041
+ disposeElementComputed(element);
2042
+ }
2043
+ catch {
2044
+ // Canonical load already succeeded; stale cleanup cannot reverse it.
2045
+ }
2046
+ });
2047
+ }
2048
+ load(data) {
2049
+ const result = this.validateLoadData(data);
2050
+ this.applyValidatedLoad(result);
2051
+ }
2052
+ save() {
2053
+ this.validateCanonicalHierarchy();
2054
+ const data = {
2055
+ workspace: this.workspace,
2056
+ workspaceList: this.workspaceList,
2057
+ elements: {}
2058
+ };
2059
+ this._elements.forEach((element, id) => {
2060
+ data.elements[id] = element.save();
2061
+ });
2062
+ return data;
2063
+ }
2064
+ addChange(change) {
2065
+ this.changes.push(change);
2066
+ }
2067
+ cleanChanges() {
2068
+ this.changes = [];
2069
+ }
2070
+ getAllElements() {
2071
+ return this._elements;
2072
+ }
2073
+ getElementById(elementId) {
2074
+ return this._elements.get(elementId);
2075
+ }
2076
+ getContainerChildren(element, context) {
2077
+ if (!isGroupEntity(element.get('type'))) {
2078
+ throw new Error(`[SceneTree] ${context} must be a registered container`);
2079
+ }
2080
+ const children = element.get('children');
2081
+ if (!Array.isArray(children) ||
2082
+ children.some((childId) => typeof childId !== 'string')) {
2083
+ throw new Error(`[SceneTree] ${context} must expose a valid children list`);
2084
+ }
2085
+ return [...children];
2086
+ }
2087
+ validateCanonicalHierarchy() {
2088
+ const membership = new Map();
2089
+ this._elements.forEach((parent, parentId) => {
2090
+ if (!isGroupEntity(parent.get('type'))) {
2091
+ return;
2092
+ }
2093
+ const children = this.getContainerChildren(parent, `Container "${parentId}"`);
2094
+ const localChildren = new Set();
2095
+ children.forEach((childId) => {
2096
+ if (localChildren.has(childId) || membership.has(childId)) {
2097
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: duplicate membership for "${childId}"`);
2098
+ }
2099
+ localChildren.add(childId);
2100
+ membership.set(childId, parentId);
2101
+ const child = this.getElementById(childId);
2102
+ if (!child) {
2103
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: missing child "${childId}"`);
2104
+ }
2105
+ if (child.get('parentId') !== parentId) {
2106
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: parent mismatch for "${childId}"`);
2107
+ }
2108
+ });
2109
+ });
2110
+ this._elements.forEach((element, elementId) => {
2111
+ if (element.get('type') === EntityTypes.WORKSPACE) {
2112
+ return;
2113
+ }
2114
+ const parentId = element.get('parentId');
2115
+ const parent = this.getElementById(parentId);
2116
+ if (!parent || !isGroupEntity(parent.get('type'))) {
2117
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: missing container parent for "${elementId}"`);
2118
+ }
2119
+ if (membership.get(elementId) !== parentId) {
2120
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: missing membership for "${elementId}"`);
2121
+ }
2122
+ const visited = new Set([elementId]);
2123
+ let ancestorId = parentId;
2124
+ while (ancestorId) {
2125
+ if (visited.has(ancestorId)) {
2126
+ throw new Error(`[SceneTree] Invalid canonical hierarchy: cycle at "${elementId}"`);
2127
+ }
2128
+ visited.add(ancestorId);
2129
+ const ancestor = this.getElementById(ancestorId);
2130
+ if (!ancestor || ancestor.get('type') === EntityTypes.WORKSPACE) {
2131
+ break;
2132
+ }
2133
+ ancestorId = ancestor.get('parentId');
2134
+ }
2135
+ });
12
2136
  }
13
- _init() {
14
- if (!this.workspace && !this.workspaceList.length) {
15
- const initWorkspace = createWorkspace();
16
- if (initWorkspace) {
17
- this.addToMap(initWorkspace);
18
- this.workspaceList = [initWorkspace.get('id')];
19
- this.workspace = this.workspaceList[0];
2137
+ assertMoveDoesNotCreateCycle(elementIds, targetParentId) {
2138
+ const movedIds = new Set(elementIds);
2139
+ let ancestorId = targetParentId;
2140
+ while (ancestorId) {
2141
+ if (movedIds.has(ancestorId)) {
2142
+ throw new Error('[SceneTree] Invalid hierarchy request: self-parenting or descendant cycle');
20
2143
  }
2144
+ const ancestor = this.getElementById(ancestorId);
2145
+ if (!ancestor || ancestor.get('type') === EntityTypes.WORKSPACE) {
2146
+ return;
2147
+ }
2148
+ ancestorId = ancestor.get('parentId');
21
2149
  }
22
2150
  }
23
- init() {
24
- this._init();
25
- }
26
- load(data) {
27
- if (!data)
28
- return;
29
- if (data.elements) {
30
- for (const elementId in data.elements) {
31
- const elementData = data.elements[elementId];
32
- let element;
33
- if (elementData.type === EntityTypes.WORKSPACE) {
34
- element = createWorkspace(elementData);
35
- }
36
- else {
37
- element = createElement(elementData);
2151
+ applyValidatedHierarchyMoves(moves) {
2152
+ const movedIds = new Set(moves.map(({ elementId }) => elementId));
2153
+ const affectedParentIds = new Set();
2154
+ const originalChildren = new Map();
2155
+ moves.forEach(({ before, after }) => {
2156
+ affectedParentIds.add(before.parentId);
2157
+ affectedParentIds.add(after.parentId);
2158
+ });
2159
+ const nextChildren = new Map();
2160
+ affectedParentIds.forEach((parentId) => {
2161
+ const parent = this.getElementById(parentId);
2162
+ if (!parent) {
2163
+ throw new Error(`[SceneTree] Cannot apply hierarchy move: missing parent "${parentId}"`);
2164
+ }
2165
+ const children = this.getContainerChildren(parent, `Hierarchy parent "${parentId}"`);
2166
+ originalChildren.set(parentId, children);
2167
+ nextChildren.set(parentId, children.filter((childId) => !movedIds.has(childId)));
2168
+ });
2169
+ moves
2170
+ .slice()
2171
+ .sort((left, right) => left.after.parentId.localeCompare(right.after.parentId) ||
2172
+ left.after.index - right.after.index)
2173
+ .forEach(({ elementId, after }) => {
2174
+ const children = nextChildren.get(after.parentId);
2175
+ if (!children || after.index < 0 || after.index > children.length) {
2176
+ throw new Error(`[SceneTree] Cannot apply hierarchy move: invalid exact index for "${elementId}"`);
2177
+ }
2178
+ children.splice(after.index, 0, elementId);
2179
+ });
2180
+ const operationChangeStart = this.changes.length;
2181
+ try {
2182
+ nextChildren.forEach((children, parentId) => {
2183
+ const parent = this.getElementById(parentId);
2184
+ parent.set('children', children);
2185
+ });
2186
+ moves.forEach(({ elementId, after }) => {
2187
+ const element = this.getElementById(elementId);
2188
+ if (!element) {
2189
+ throw new Error(`[SceneTree] Cannot apply hierarchy move: missing element "${elementId}"`);
38
2190
  }
39
- this.addToMap(element);
2191
+ element.set('parentId', after.parentId, { undoable: false });
2192
+ });
2193
+ }
2194
+ catch (error) {
2195
+ originalChildren.forEach((children, parentId) => {
2196
+ const parent = this.getElementById(parentId);
2197
+ parent.set('children', children, { undoable: false });
2198
+ });
2199
+ moves.forEach(({ elementId, before }) => {
2200
+ this.getElementById(elementId)?.set('parentId', before.parentId, {
2201
+ undoable: false
2202
+ });
2203
+ });
2204
+ this.changes.splice(operationChangeStart);
2205
+ throw error;
2206
+ }
2207
+ }
2208
+ moveElements(request, options) {
2209
+ this.validateCanonicalHierarchy();
2210
+ if (!request ||
2211
+ !Array.isArray(request.elementIds) ||
2212
+ request.elementIds.length === 0 ||
2213
+ request.elementIds.some((elementId) => typeof elementId !== 'string' || elementId.length === 0)) {
2214
+ throw new Error('[SceneTree] Invalid hierarchy request: elementIds must be a non-empty string array');
2215
+ }
2216
+ const requestedIds = [...request.elementIds];
2217
+ if (new Set(requestedIds).size !== requestedIds.length) {
2218
+ throw new Error('[SceneTree] Invalid hierarchy request: elementIds must be unique');
2219
+ }
2220
+ const elements = requestedIds.map((elementId) => {
2221
+ const element = this.getElementById(elementId);
2222
+ if (!element) {
2223
+ throw new Error(`[SceneTree] Invalid hierarchy request: missing element "${elementId}"`);
2224
+ }
2225
+ if (element.get('type') === EntityTypes.WORKSPACE) {
2226
+ throw new Error('[SceneTree] Invalid hierarchy request: workspace movement is forbidden');
2227
+ }
2228
+ return element;
2229
+ });
2230
+ const sourceParentId = elements[0].get('parentId');
2231
+ if (elements.some((element) => element.get('parentId') !== sourceParentId)) {
2232
+ throw new Error('[SceneTree] Invalid hierarchy request: elementIds must share one parent');
2233
+ }
2234
+ const sourceParent = this.getElementById(sourceParentId);
2235
+ if (!sourceParent) {
2236
+ throw new Error(`[SceneTree] Invalid hierarchy request: missing source parent "${sourceParentId}"`);
2237
+ }
2238
+ const sourceChildren = this.getContainerChildren(sourceParent, `Source parent "${sourceParentId}"`);
2239
+ const requestedIdSet = new Set(requestedIds);
2240
+ const canonicalIds = sourceChildren.filter((childId) => requestedIdSet.has(childId));
2241
+ if (canonicalIds.length !== requestedIds.length) {
2242
+ throw new Error('[SceneTree] Invalid hierarchy request: source membership is incomplete');
2243
+ }
2244
+ const targetParent = this.getElementById(request.targetParentId);
2245
+ if (!targetParent) {
2246
+ throw new Error(`[SceneTree] Invalid hierarchy request: missing target "${request.targetParentId}"`);
2247
+ }
2248
+ const targetChildren = this.getContainerChildren(targetParent, `Target "${request.targetParentId}"`);
2249
+ const targetBase = targetChildren.filter((childId) => !requestedIdSet.has(childId));
2250
+ if (!Number.isInteger(request.targetIndex) ||
2251
+ request.targetIndex < 0 ||
2252
+ request.targetIndex > targetBase.length) {
2253
+ throw new Error('[SceneTree] Invalid hierarchy request: targetIndex is outside the final target insertion range');
2254
+ }
2255
+ this.assertMoveDoesNotCreateCycle(canonicalIds, request.targetParentId);
2256
+ const nextTargetChildren = [...targetBase];
2257
+ nextTargetChildren.splice(request.targetIndex, 0, ...canonicalIds);
2258
+ if (sourceParentId === request.targetParentId &&
2259
+ isEqual(nextTargetChildren, sourceChildren)) {
2260
+ return { elementIds: canonicalIds, moves: [] };
2261
+ }
2262
+ const moves = canonicalIds.map((elementId, offset) => ({
2263
+ elementId,
2264
+ before: {
2265
+ parentId: sourceParentId,
2266
+ index: sourceChildren.indexOf(elementId)
2267
+ },
2268
+ after: {
2269
+ parentId: request.targetParentId,
2270
+ index: request.targetIndex + offset
40
2271
  }
2272
+ }));
2273
+ const operationChangeStart = this.changes.length;
2274
+ this.applyValidatedHierarchyMoves(moves);
2275
+ this.changes.splice(operationChangeStart);
2276
+ this.addChange({
2277
+ action: SCENE_TREE_ACTIONS.MOVE_ELEMENTS,
2278
+ eventName: EventTypes.MOVE_ELEMENTS,
2279
+ moves
2280
+ });
2281
+ acknowledgeTransactionReplayApplied();
2282
+ this.commitSceneTreeTransaction(options);
2283
+ return { elementIds: canonicalIds, moves };
2284
+ }
2285
+ applyHierarchyMoves(moves, options) {
2286
+ this.validateCanonicalHierarchy();
2287
+ if (!Array.isArray(moves) || moves.length === 0) {
2288
+ return false;
41
2289
  }
42
- if (data.workspace) {
43
- this.workspace = data.workspace;
2290
+ const elementIds = moves.map(({ elementId }) => elementId);
2291
+ if (new Set(elementIds).size !== elementIds.length) {
2292
+ throw new Error('[SceneTree] Cannot apply hierarchy move: duplicate element evidence');
44
2293
  }
45
- if (data.workspaceList) {
46
- this.workspaceList = data.workspaceList;
2294
+ const sourceParentId = moves[0].before.parentId;
2295
+ const targetParentId = moves[0].after.parentId;
2296
+ const targetStartIndex = moves[0].after.index;
2297
+ const sourceIndices = new Set();
2298
+ const targetIndices = new Set();
2299
+ for (const [index, { before, after }] of moves.entries()) {
2300
+ if (before.parentId !== sourceParentId ||
2301
+ after.parentId !== targetParentId ||
2302
+ !Number.isInteger(before.index) ||
2303
+ before.index < 0 ||
2304
+ sourceIndices.has(before.index) ||
2305
+ !Number.isInteger(after.index) ||
2306
+ after.index < 0 ||
2307
+ targetIndices.has(after.index) ||
2308
+ after.index !== targetStartIndex + index) {
2309
+ throw new Error('[SceneTree] Cannot apply hierarchy move: invalid canonical target batch');
2310
+ }
2311
+ sourceIndices.add(before.index);
2312
+ targetIndices.add(after.index);
47
2313
  }
2314
+ moves.forEach(({ elementId, before, after }) => {
2315
+ const element = this.getElementById(elementId);
2316
+ if (!element ||
2317
+ element.get('parentId') !== before.parentId ||
2318
+ this.getContainerChildren(this.getElementById(before.parentId), `Replay source "${before.parentId}"`)[before.index] !== elementId) {
2319
+ throw new Error(`[SceneTree] Cannot apply hierarchy move: stale before image for "${elementId}"`);
2320
+ }
2321
+ if (!this.getElementById(after.parentId)) {
2322
+ throw new Error(`[SceneTree] Cannot apply hierarchy move: missing target "${after.parentId}"`);
2323
+ }
2324
+ });
2325
+ this.getContainerChildren(this.getElementById(targetParentId), `Replay target "${targetParentId}"`);
2326
+ this.assertMoveDoesNotCreateCycle(elementIds, targetParentId);
2327
+ const operationChangeStart = this.changes.length;
2328
+ this.applyValidatedHierarchyMoves(moves);
2329
+ this.changes.splice(operationChangeStart);
2330
+ this.addChange({
2331
+ action: SCENE_TREE_ACTIONS.MOVE_ELEMENTS,
2332
+ eventName: EventTypes.MOVE_ELEMENTS,
2333
+ moves: moves.map((move) => ({
2334
+ elementId: move.elementId,
2335
+ before: { ...move.before },
2336
+ after: { ...move.after }
2337
+ }))
2338
+ });
2339
+ acknowledgeTransactionReplayApplied();
2340
+ this.commitSceneTreeTransaction(options);
2341
+ return true;
48
2342
  }
49
- save() {
50
- const data = {
51
- workspace: this.workspace,
52
- workspaceList: this.workspaceList,
53
- elements: {}
2343
+ collectSubtreeRemovalEntries(elementId) {
2344
+ const root = this.getElementById(elementId);
2345
+ if (!root) {
2346
+ throw new Error(`[SceneTree] Invalid subtree request: missing element "${elementId}"`);
2347
+ }
2348
+ if (root.get('type') === EntityTypes.WORKSPACE) {
2349
+ throw new Error('[SceneTree] Invalid subtree request: workspace removal is forbidden');
2350
+ }
2351
+ const removed = [];
2352
+ const visit = (current) => {
2353
+ if (isGroupEntity(current.get('type'))) {
2354
+ this.getContainerChildren(current, `Subtree container "${current.get('id')}"`).forEach((childId) => {
2355
+ const child = this.getElementById(childId);
2356
+ if (!child) {
2357
+ throw new Error(`[SceneTree] Invalid subtree request: missing child "${childId}"`);
2358
+ }
2359
+ visit(child);
2360
+ });
2361
+ }
2362
+ const currentId = current.get('id');
2363
+ const parentId = current.get('parentId');
2364
+ const parent = this.getElementById(parentId);
2365
+ const index = parent
2366
+ ? this.getContainerChildren(parent, `Subtree parent "${parentId}"`).indexOf(currentId)
2367
+ : -1;
2368
+ if (index < 0) {
2369
+ throw new Error(`[SceneTree] Invalid subtree request: missing membership for "${currentId}"`);
2370
+ }
2371
+ removed.push({
2372
+ elementId: currentId,
2373
+ parentId,
2374
+ index,
2375
+ data: current.save()
2376
+ });
54
2377
  };
55
- this._elements.forEach((element, id) => {
56
- data.elements[id] = element.save();
2378
+ visit(root);
2379
+ return removed;
2380
+ }
2381
+ removeSubtree(elementId, options) {
2382
+ const preparedMutation = this.prepareSubtreeRemoval(elementId);
2383
+ const change = preparedMutation.evidence[0];
2384
+ this.applyPreparedElementMutation(preparedMutation, options);
2385
+ return Object.freeze({
2386
+ elementId: change.elementId,
2387
+ removed: change.removed,
2388
+ rootParentChildrenAfter: change.rootParentChildrenAfter
57
2389
  });
58
- return data;
59
2390
  }
60
- addChange(change) {
61
- this.changes.push(change);
2391
+ preflightRestoreSubtree(snapshot, options) {
2392
+ this.validateCanonicalHierarchy();
2393
+ if (!isRecord(snapshot)) {
2394
+ throw new Error('[SceneTree] Invalid subtree restore: snapshot must be a record');
2395
+ }
2396
+ if (typeof snapshot.elementId !== 'string' ||
2397
+ snapshot.elementId.length === 0 ||
2398
+ !Array.isArray(snapshot.removed) ||
2399
+ snapshot.removed.length === 0 ||
2400
+ !Array.isArray(snapshot.rootParentChildrenAfter) ||
2401
+ snapshot.rootParentChildrenAfter.some((childId) => typeof childId !== 'string')) {
2402
+ throw new Error('[SceneTree] Invalid subtree restore: exact hierarchy evidence is required');
2403
+ }
2404
+ const validated = cloneSceneTreeValue(snapshot);
2405
+ const rootParentChildrenAfter = [...validated.rootParentChildrenAfter];
2406
+ if (new Set(rootParentChildrenAfter).size !== rootParentChildrenAfter.length) {
2407
+ throw new Error('[SceneTree] Invalid subtree restore: duplicate root-parent order evidence');
2408
+ }
2409
+ const entries = validated.removed;
2410
+ const entryIds = entries.map(({ elementId }) => elementId);
2411
+ if (entryIds.some((elementId) => typeof elementId !== 'string') ||
2412
+ new Set(entryIds).size !== entryIds.length) {
2413
+ throw new Error('[SceneTree] Invalid subtree restore: duplicate or invalid element evidence');
2414
+ }
2415
+ entries.forEach((entry) => {
2416
+ if (this.getElementById(entry.elementId)) {
2417
+ throw new Error(`[SceneTree] Invalid subtree restore: active element "${entry.elementId}" already exists`);
2418
+ }
2419
+ if (typeof entry.parentId !== 'string' ||
2420
+ !Number.isInteger(entry.index) ||
2421
+ entry.index < 0 ||
2422
+ !isRecord(entry.data) ||
2423
+ entry.data.id !== entry.elementId ||
2424
+ entry.data.parentId !== entry.parentId ||
2425
+ typeof entry.data.type !== 'string') {
2426
+ throw new Error(`[SceneTree] Invalid subtree restore: malformed element evidence for "${entry.elementId}"`);
2427
+ }
2428
+ if (!componentRegistry.has(entry.data.type)) {
2429
+ throw new Error(`[SceneTree] Invalid subtree restore: unregistered element type "${entry.data.type}"`);
2430
+ }
2431
+ if (typeof entry.data.name !== 'string' ||
2432
+ typeof entry.data.visible !== 'boolean' ||
2433
+ typeof entry.data.lock !== 'boolean' ||
2434
+ (entry.data.props !== undefined &&
2435
+ (!isRecord(entry.data.props) ||
2436
+ Object.values(entry.data.props).some((propertyId) => typeof propertyId !== 'string')))) {
2437
+ throw new Error(`[SceneTree] Invalid subtree restore: malformed raw data for "${entry.elementId}"`);
2438
+ }
2439
+ });
2440
+ const entryById = new Map(entries.map((entry) => [entry.elementId, entry]));
2441
+ const rootEntry = entries[entries.length - 1];
2442
+ if (rootEntry.elementId !== validated.elementId) {
2443
+ throw new Error('[SceneTree] Invalid subtree restore: root evidence must be the final post-order entry');
2444
+ }
2445
+ const rootParent = this.getElementById(rootEntry.parentId);
2446
+ if (!rootParent || !isGroupEntity(rootParent.get('type'))) {
2447
+ throw new Error(`[SceneTree] Invalid subtree restore: missing container parent "${rootEntry.parentId}"`);
2448
+ }
2449
+ const currentRootParentChildren = this.getContainerChildren(rootParent, `Restore root parent "${rootEntry.parentId}"`);
2450
+ if (!isEqual(currentRootParentChildren, rootParentChildrenAfter)) {
2451
+ throw new Error('[SceneTree] Invalid subtree restore: stale post-delete root-parent order evidence');
2452
+ }
2453
+ if (rootEntry.index > rootParentChildrenAfter.length ||
2454
+ rootParentChildrenAfter.includes(rootEntry.elementId)) {
2455
+ throw new Error(`[SceneTree] Invalid subtree restore: root index for "${rootEntry.elementId}" is outside the exact parent range`);
2456
+ }
2457
+ const childrenByParent = new Map();
2458
+ entries.forEach((entry) => {
2459
+ if (entry.elementId === rootEntry.elementId)
2460
+ return;
2461
+ if (!entryById.has(entry.parentId)) {
2462
+ throw new Error(`[SceneTree] Invalid subtree restore: missing snapshot parent "${entry.parentId}"`);
2463
+ }
2464
+ const children = childrenByParent.get(entry.parentId) ?? [];
2465
+ children.push(entry);
2466
+ childrenByParent.set(entry.parentId, children);
2467
+ });
2468
+ entries.forEach((entry) => {
2469
+ const declaredChildren = isGroupEntity(entry.data.type)
2470
+ ? entry.data.children
2471
+ : undefined;
2472
+ const childEntries = (childrenByParent.get(entry.elementId) ?? []).sort((left, right) => left.index - right.index);
2473
+ if (!isGroupEntity(entry.data.type)) {
2474
+ if (childEntries.length > 0 || declaredChildren !== undefined) {
2475
+ throw new Error(`[SceneTree] Invalid subtree restore: inconsistent child order for "${entry.elementId}"`);
2476
+ }
2477
+ return;
2478
+ }
2479
+ if (!Array.isArray(declaredChildren) ||
2480
+ declaredChildren.some((childId) => typeof childId !== 'string') ||
2481
+ new Set(declaredChildren).size !== declaredChildren.length ||
2482
+ childEntries.some((child, index) => child.index !== index) ||
2483
+ !isEqual(declaredChildren, childEntries.map(({ elementId }) => elementId))) {
2484
+ throw new Error(`[SceneTree] Invalid subtree restore: inconsistent child order for "${entry.elementId}"`);
2485
+ }
2486
+ });
2487
+ const postOrder = [];
2488
+ const visiting = new Set();
2489
+ const visited = new Set();
2490
+ const visit = (elementId) => {
2491
+ if (visiting.has(elementId)) {
2492
+ throw new Error(`[SceneTree] Invalid subtree restore: cycle at "${elementId}"`);
2493
+ }
2494
+ if (visited.has(elementId))
2495
+ return;
2496
+ const entry = entryById.get(elementId);
2497
+ if (!entry) {
2498
+ throw new Error(`[SceneTree] Invalid subtree restore: inconsistent child order at "${elementId}"`);
2499
+ }
2500
+ visiting.add(elementId);
2501
+ if (isGroupEntity(entry.data.type)) {
2502
+ ;
2503
+ entry.data.children.forEach(visit);
2504
+ }
2505
+ visiting.delete(elementId);
2506
+ visited.add(elementId);
2507
+ postOrder.push(elementId);
2508
+ };
2509
+ visit(rootEntry.elementId);
2510
+ if (visited.size !== entries.length || !isEqual(postOrder, entryIds)) {
2511
+ throw new Error('[SceneTree] Invalid subtree restore: inconsistent child order or disconnected hierarchy');
2512
+ }
2513
+ const propertyContract = this.captureElementPropertyContract(entries.map(({ data }) => data));
2514
+ if (options?.propertyState !== 'pending-restore') {
2515
+ this.assertElementPropertyContractActive(propertyContract);
2516
+ }
2517
+ const preparedEntries = entries.map((entry) => {
2518
+ const tombstone = this._deletedMap.get(entry.elementId);
2519
+ let strategy = 'materialize';
2520
+ if (tombstone) {
2521
+ const tombstoneData = cloneSceneTreeValue(tombstone.save());
2522
+ const expectedTombstoneData = cloneSceneTreeValue(entry.data);
2523
+ expectedTombstoneData.parentId = '';
2524
+ if (isGroupEntity(entry.data.type)) {
2525
+ ;
2526
+ expectedTombstoneData.children = [];
2527
+ }
2528
+ if (tombstone.get('type') !== entry.data.type ||
2529
+ !isEqual(tombstoneData, expectedTombstoneData)) {
2530
+ throw new Error(`[SceneTree] Invalid subtree restore: incompatible tombstone for "${entry.elementId}"`);
2531
+ }
2532
+ strategy = 'reuse';
2533
+ }
2534
+ return Object.freeze({ elementId: entry.elementId, strategy });
2535
+ });
2536
+ const propertyOwnerRelations = propertyContract.relations.map(({ ownerElementId, ownerElementType, ownerPropertyName, componentId }) => Object.freeze({
2537
+ ownerElementId,
2538
+ ownerElementType,
2539
+ ownerPropertyName,
2540
+ componentId
2541
+ }));
2542
+ const preparedRestore = Object.freeze({
2543
+ kind: 'prepared-scene-tree-restore',
2544
+ elementId: rootEntry.elementId,
2545
+ entries: Object.freeze(preparedEntries),
2546
+ propertyOwnerRelations: Object.freeze(propertyOwnerRelations)
2547
+ });
2548
+ this.validatedRestoreArtifacts.set(preparedRestore, {
2549
+ snapshot: validated,
2550
+ propertyContract
2551
+ });
2552
+ return preparedRestore;
62
2553
  }
63
- cleanChanges() {
64
- this.changes = [];
2554
+ applyRestoreSubtree(preparedRestore, options) {
2555
+ const artifact = this.validatedRestoreArtifacts.get(preparedRestore);
2556
+ if (!artifact) {
2557
+ throw new Error('[SceneTree] Expected an owner-issued one-shot prepared subtree restore');
2558
+ }
2559
+ this.validatedRestoreArtifacts.delete(preparedRestore);
2560
+ this.assertElementPropertyContractActive(artifact.propertyContract);
2561
+ const revalidatedRestore = this.preflightRestoreSubtree(artifact.snapshot);
2562
+ const verificationArtifact = this.validatedRestoreArtifacts.get(revalidatedRestore);
2563
+ this.validatedRestoreArtifacts.delete(revalidatedRestore);
2564
+ if (!verificationArtifact ||
2565
+ !isEqual(revalidatedRestore.entries, preparedRestore.entries) ||
2566
+ !isEqual(revalidatedRestore.propertyOwnerRelations, preparedRestore.propertyOwnerRelations)) {
2567
+ throw new Error('[SceneTree] Cannot apply subtree restore: prepared restore is stale');
2568
+ }
2569
+ const snapshot = verificationArtifact.snapshot;
2570
+ const strategyByElementId = new Map(preparedRestore.entries.map(({ elementId, strategy }) => [
2571
+ elementId,
2572
+ strategy
2573
+ ]));
2574
+ const entryById = new Map(snapshot.removed.map((entry) => [entry.elementId, entry]));
2575
+ const prepared = new Map();
2576
+ try {
2577
+ preparedRestore.entries.forEach(({ elementId, strategy }) => {
2578
+ const entry = entryById.get(elementId);
2579
+ if (!entry) {
2580
+ throw new Error(`[SceneTree] Cannot apply subtree restore: missing prepared evidence for "${elementId}"`);
2581
+ }
2582
+ if (strategy === 'reuse') {
2583
+ const tombstone = this._deletedMap.get(elementId);
2584
+ if (!tombstone) {
2585
+ throw new Error(`[SceneTree] Cannot apply subtree restore: stale tombstone "${elementId}"`);
2586
+ }
2587
+ prepared.set(elementId, tombstone);
2588
+ return;
2589
+ }
2590
+ if (strategy !== 'materialize') {
2591
+ throw new Error(`[SceneTree] Cannot apply subtree restore: invalid strategy for "${elementId}"`);
2592
+ }
2593
+ const constructorData = cloneSceneTreeValue(entry.data);
2594
+ if (isGroupEntity(constructorData.type)) {
2595
+ ;
2596
+ constructorData.children = [];
2597
+ }
2598
+ const element = createElement(constructorData, this.propsManagerOwner);
2599
+ if (!element || element.get('id') !== elementId) {
2600
+ if (element) {
2601
+ try {
2602
+ disposeElementComputed(element);
2603
+ }
2604
+ catch {
2605
+ // Preserve the exact materialization failure.
2606
+ }
2607
+ }
2608
+ throw new Error(`[SceneTree] Cannot apply subtree restore: exact materialization failed for "${elementId}"`);
2609
+ }
2610
+ const expectedPreparedData = cloneSceneTreeValue(entry.data);
2611
+ if (isGroupEntity(expectedPreparedData.type)) {
2612
+ ;
2613
+ expectedPreparedData.children = [];
2614
+ }
2615
+ if (!isEqual(element.save(), expectedPreparedData)) {
2616
+ try {
2617
+ disposeElementComputed(element);
2618
+ }
2619
+ catch {
2620
+ // Preserve the exact raw-data failure.
2621
+ }
2622
+ throw new Error(`[SceneTree] Cannot apply subtree restore: exact data changed for "${elementId}"`);
2623
+ }
2624
+ prepared.set(elementId, element);
2625
+ });
2626
+ }
2627
+ catch (error) {
2628
+ prepared.forEach((element, elementId) => {
2629
+ if (!this._deletedMap.has(elementId)) {
2630
+ try {
2631
+ disposeElementComputed(element);
2632
+ }
2633
+ catch {
2634
+ // Preserve the first restore preparation failure while cleaning all attempts.
2635
+ }
2636
+ }
2637
+ });
2638
+ throw error;
2639
+ }
2640
+ const restoreOrder = [...snapshot.removed].reverse();
2641
+ const restoredElements = restoreOrder.map(({ elementId }) => {
2642
+ const element = prepared.get(elementId);
2643
+ if (!element) {
2644
+ throw new Error(`[SceneTree] Cannot apply subtree restore: missing prepared hierarchy for "${elementId}"`);
2645
+ }
2646
+ return element;
2647
+ });
2648
+ const relationIndexUpdates = this.prepareElementPropertyRelationInsertions(restoredElements);
2649
+ const rootEntry = snapshot.removed[snapshot.removed.length - 1];
2650
+ const rootParent = this.getElementById(rootEntry.parentId);
2651
+ const rootParentChildrenBefore = this.getContainerChildren(rootParent, `Restore root parent "${rootEntry.parentId}"`);
2652
+ const restoredRootParentChildren = [...rootParentChildrenBefore];
2653
+ restoredRootParentChildren.splice(rootEntry.index, 0, rootEntry.elementId);
2654
+ const operationChangeStart = this.changes.length;
2655
+ let canonicalMapApplied = false;
2656
+ try {
2657
+ restoredElements.forEach((element) => {
2658
+ reactivateElementComputed(element);
2659
+ });
2660
+ snapshot.removed.forEach(({ elementId, parentId }) => {
2661
+ const element = prepared.get(elementId);
2662
+ element.assignCanonicalParentId(parentId);
2663
+ this._deletedMap.delete(elementId);
2664
+ });
2665
+ this.addElementsToCanonicalMap(restoredElements, relationIndexUpdates);
2666
+ canonicalMapApplied = true;
2667
+ this.currentWorkspace.replaceBatchParentChildren(rootParent, restoredRootParentChildren);
2668
+ snapshot.removed.forEach(({ elementId, data }) => {
2669
+ if (!isGroupEntity(data.type))
2670
+ return;
2671
+ const group = prepared.get(elementId);
2672
+ this.currentWorkspace.replaceBatchParentChildren(group, data.children);
2673
+ });
2674
+ this.validateCanonicalHierarchy();
2675
+ snapshot.removed.forEach(({ elementId, data }) => {
2676
+ if (!isEqual(this.getElementById(elementId)?.save(), data)) {
2677
+ throw new Error(`[SceneTree] Cannot apply subtree restore: final raw data changed for "${elementId}"`);
2678
+ }
2679
+ });
2680
+ }
2681
+ catch (error) {
2682
+ this.changes.splice(operationChangeStart);
2683
+ try {
2684
+ ;
2685
+ this.currentWorkspace.replaceBatchParentChildren(rootParent, rootParentChildrenBefore);
2686
+ }
2687
+ catch {
2688
+ // Preserve the primary apply failure and continue every rollback stage.
2689
+ }
2690
+ snapshot.removed.forEach(({ elementId, data }) => {
2691
+ if (!isGroupEntity(data.type))
2692
+ return;
2693
+ const group = prepared.get(elementId);
2694
+ try {
2695
+ ;
2696
+ this.currentWorkspace.replaceBatchParentChildren(group, []);
2697
+ }
2698
+ catch {
2699
+ // Preserve the primary apply failure and continue every rollback stage.
2700
+ }
2701
+ });
2702
+ if (canonicalMapApplied) {
2703
+ try {
2704
+ this.rollbackElementsAddedToCanonicalMap(restoredElements, relationIndexUpdates);
2705
+ }
2706
+ catch {
2707
+ // Preserve the primary apply failure and continue every rollback stage.
2708
+ }
2709
+ }
2710
+ restoredElements.forEach((element) => {
2711
+ const elementId = element.get('id');
2712
+ const strategy = strategyByElementId.get(elementId);
2713
+ try {
2714
+ ;
2715
+ element.assignCanonicalParentId('');
2716
+ }
2717
+ catch {
2718
+ // Preserve the primary apply failure and continue every rollback stage.
2719
+ }
2720
+ if (strategy === 'reuse') {
2721
+ try {
2722
+ this._deletedMap.set(elementId, element);
2723
+ }
2724
+ catch {
2725
+ // Preserve the primary apply failure and continue every rollback stage.
2726
+ }
2727
+ }
2728
+ else {
2729
+ try {
2730
+ this._deletedMap.delete(elementId);
2731
+ }
2732
+ catch {
2733
+ // Preserve the primary apply failure and continue every rollback stage.
2734
+ }
2735
+ }
2736
+ try {
2737
+ disposeElementComputed(element);
2738
+ }
2739
+ catch {
2740
+ // Preserve the primary apply failure and continue every rollback stage.
2741
+ }
2742
+ });
2743
+ throw error;
2744
+ }
2745
+ this.changes.splice(operationChangeStart);
2746
+ this.addChange({
2747
+ eventName: EventTypes.CHANGE_SUBTREE,
2748
+ elementId: snapshot.elementId,
2749
+ removed: cloneSceneTreeValue([...snapshot.removed]),
2750
+ rootParentChildrenAfter: cloneSceneTreeValue([
2751
+ ...snapshot.rootParentChildrenAfter
2752
+ ]),
2753
+ action: SCENE_TREE_ACTIONS.RESTORE_SUBTREE,
2754
+ undoAction: SCENE_TREE_ACTIONS.REMOVE_SUBTREE
2755
+ });
2756
+ acknowledgeTransactionReplayApplied();
2757
+ this.commitSceneTreeTransaction(options);
2758
+ return cloneSceneTreeValue(snapshot);
65
2759
  }
66
- getAllElements() {
67
- return this._elements;
2760
+ restoreSubtree(entries, options) {
2761
+ if (!Array.isArray(entries) || entries.length === 0) {
2762
+ throw new Error('[SceneTree] Invalid subtree restore: exact removal evidence is required');
2763
+ }
2764
+ const removed = cloneSceneTreeValue(entries);
2765
+ const rootEntry = removed[removed.length - 1];
2766
+ const rootParentChildrenAfter = this.getContainerChildren(this.getElementById(rootEntry.parentId), `Restore root parent "${rootEntry.parentId}"`);
2767
+ const snapshot = {
2768
+ elementId: rootEntry.elementId,
2769
+ removed,
2770
+ rootParentChildrenAfter: cloneSceneTreeValue(rootParentChildrenAfter)
2771
+ };
2772
+ return this.applyRestoreSubtree(this.preflightRestoreSubtree(snapshot), options);
68
2773
  }
69
- getElementById(elementId) {
70
- return this._elements.get(elementId);
2774
+ applySubtreeChange(change, options) {
2775
+ if (change.action === SCENE_TREE_ACTIONS.RESTORE_SUBTREE) {
2776
+ this.restoreSubtree(change.removed, options);
2777
+ return true;
2778
+ }
2779
+ if (change.action !== SCENE_TREE_ACTIONS.REMOVE_SUBTREE) {
2780
+ throw new Error(`[SceneTree] Invalid subtree replay action "${change.action}"`);
2781
+ }
2782
+ const preparedMutation = this.prepareCanonicalSubtreeRemoval(change);
2783
+ this.applyPreparedElementMutation(preparedMutation, options);
2784
+ return true;
71
2785
  }
72
2786
  addToMap(element) {
73
2787
  const elId = element.get('id');
74
2788
  if (!element || !elId) {
75
2789
  return;
76
2790
  }
2791
+ this.addElementsToCanonicalMap([element]);
77
2792
  this.removeFromDeleteMap(elId);
78
- this._elements.set(elId, element);
2793
+ }
2794
+ addManyToMap(elements, parentId) {
2795
+ const parent = this._elements.get(parentId);
2796
+ if (!parent || !isGroupEntity(parent.get('type'))) {
2797
+ throw new Error('[SceneTree] Canonical element registration requires an active container parent');
2798
+ }
2799
+ const elementIds = elements.map((element) => element.get('id'));
2800
+ if (elementIds.some((elementId) => typeof elementId !== 'string' ||
2801
+ elementId.length === 0 ||
2802
+ this._elements.has(elementId) ||
2803
+ this._deletedMap.has(elementId)) ||
2804
+ new Set(elementIds).size !== elementIds.length) {
2805
+ throw new Error('[SceneTree] Canonical element registration requires unique inactive ids');
2806
+ }
2807
+ const relationIndexUpdates = this.prepareElementPropertyRelationInsertions(elements);
2808
+ elements.forEach((element) => {
2809
+ ;
2810
+ element.assignCanonicalParentId(parentId);
2811
+ });
2812
+ elements.forEach((element, index) => {
2813
+ const elementId = elementIds[index];
2814
+ this._deletedMap.delete(elementId);
2815
+ });
2816
+ this.addElementsToCanonicalMap(elements, relationIndexUpdates);
79
2817
  }
80
2818
  removeFromMap(element) {
81
2819
  const elId = element.get('id');
82
2820
  if (!element || !elId) {
83
2821
  return;
84
2822
  }
2823
+ this.removeElementsFromCanonicalMap([element]);
85
2824
  this.addToDeleteMap(element);
86
- this._elements.delete(elId);
87
2825
  }
88
- getRestoreElementById(elementId) {
2826
+ getRestoreElementById(elementId, recordChange = true) {
89
2827
  const restoredElement = this._deletedMap.get(elementId);
90
- this.addChangeForAddElement(restoredElement);
2828
+ if (recordChange) {
2829
+ this.addChangeForAddElement(restoredElement);
2830
+ }
91
2831
  return restoredElement;
92
2832
  }
93
2833
  addToDeleteMap(element) {
@@ -96,88 +2836,560 @@ class SceneTree {
96
2836
  removeFromDeleteMap(elementId) {
97
2837
  this._deletedMap.delete(elementId);
98
2838
  }
99
- addChangeForAddElement(element) {
2839
+ addChangeForAddElement(element, parentId = element.get('parentId'), index) {
100
2840
  this.addChange({
101
2841
  eventName: EventTypes.ADD_ELEMENT,
102
2842
  data: element.save(),
2843
+ ...(parentId ? { parentId } : {}),
2844
+ ...(index !== undefined ? { index } : {}),
103
2845
  action: SCENE_TREE_ACTIONS.ADD_ELEMENT,
104
- owner: OWNER.SCENE_TREE,
105
2846
  undoType: EventTypes.REMOVE_ELEMENT,
106
2847
  undoAction: EventTypes.REMOVE_ELEMENT
107
2848
  });
108
2849
  }
109
- addChangeForRemoveElement(element) {
110
- this.addChange({
111
- eventName: EventTypes.REMOVE_ELEMENT,
112
- data: element.save(),
113
- action: SCENE_TREE_ACTIONS.REMOVE_ELEMENT,
114
- owner: OWNER.SCENE_TREE,
115
- undoType: EventTypes.ADD_ELEMENT,
116
- undoAction: EventTypes.ADD_ELEMENT
117
- });
118
- }
119
2850
  get currentWorkspace() {
120
2851
  return this.getElementById(this.workspace);
121
2852
  }
122
- createElement(elementData) {
2853
+ createElement(elementData, recordChange = true) {
123
2854
  if (elementData.type === EntityTypes.WORKSPACE) {
124
2855
  return null;
125
2856
  }
126
- const newElement = createElement(elementData);
127
- this.addChangeForAddElement(newElement);
2857
+ const newElement = createElement(elementData, this.propsManagerOwner);
2858
+ if (recordChange) {
2859
+ this.addChangeForAddElement(newElement);
2860
+ }
128
2861
  return newElement;
129
2862
  }
130
- addNewElement(elementData, parent, index = -1, inUndoRedo = false) {
2863
+ addNewElement(elementData, parent, index = -1, options) {
2864
+ return (this.addNewElementBatch([elementData], parent, index, options)[0] ?? '');
2865
+ }
2866
+ addNewElements(elementData, parent, index = -1, options) {
2867
+ return this.addNewElementBatch(elementData, parent, index, options);
2868
+ }
2869
+ resolveElementBatchTarget(parent) {
131
2870
  const workspace = this.currentWorkspace;
132
2871
  if (!workspace) {
133
- return '';
2872
+ return undefined;
2873
+ }
2874
+ return (parent ?? workspace.firstFrame ?? workspace);
2875
+ }
2876
+ preflightElementBatch(elementData, parent, index) {
2877
+ const target = this.resolveElementBatchTarget(parent);
2878
+ if (!target ||
2879
+ this.getElementById(target.get('id')) !== target ||
2880
+ !isGroupEntity(target.get('type'))) {
2881
+ throw new Error('[SceneTree] Element batch requires an active container parent');
134
2882
  }
135
- let newElement = null;
136
- const propOverrides = stripNonRawFields(elementData);
137
- if (inUndoRedo) {
138
- newElement = this.getRestoreElementById(elementData.id);
2883
+ const targetChildren = target.get('children');
2884
+ if (!Array.isArray(targetChildren)) {
2885
+ throw new Error('[SceneTree] Element batch requires an ordered parent child list');
139
2886
  }
140
- else {
141
- newElement = this.createElement(elementData);
2887
+ const insertionIndex = index > -1 ? index : targetChildren.length;
2888
+ if (!Number.isInteger(index) ||
2889
+ index < -1 ||
2890
+ insertionIndex < 0 ||
2891
+ insertionIndex > targetChildren.length) {
2892
+ throw new Error('[SceneTree] Element batch index is outside parent order');
142
2893
  }
143
- if (newElement) {
144
- // Override props after finish creating new instance
145
- Object.keys(propOverrides).forEach((propKey) => {
146
- newElement.updateComputedData(propKey, propOverrides[propKey]);
2894
+ const sourceIds = [];
2895
+ const ordinaryPropertyOwners = [];
2896
+ elementData.forEach((source) => {
2897
+ if (!isRecord(source)) {
2898
+ throw new Error('[SceneTree] Element batch has invalid data');
2899
+ }
2900
+ const sourceId = source.id;
2901
+ if (typeof sourceId !== 'string' || sourceId.length === 0) {
2902
+ throw new Error('[SceneTree] Element batch requires unique inactive ids');
2903
+ }
2904
+ sourceIds.push(sourceId);
2905
+ const sourceType = source.type;
2906
+ const registration = typeof sourceType === 'string'
2907
+ ? componentRegistry.get(sourceType)
2908
+ : undefined;
2909
+ if (!registration) {
2910
+ throw new Error(`No component registered for type: ${String(sourceType ?? '')}`);
2911
+ }
2912
+ const propertyIds = source.props;
2913
+ if (propertyIds !== undefined && !isRecord(propertyIds)) {
2914
+ throw new Error(`[SceneTree] Element "${sourceId}" has invalid property owners`);
2915
+ }
2916
+ const constructorPropertyDefinitions = registration.constructor.ordinaryPropertyDefinitions;
2917
+ const definitions = registration.properties.length > 0
2918
+ ? registration.properties
2919
+ : (constructorPropertyDefinitions ?? []);
2920
+ ordinaryPropertyOwners.push({
2921
+ definitions,
2922
+ data: source,
2923
+ ...(propertyIds
2924
+ ? {
2925
+ propertyIds: propertyIds
2926
+ }
2927
+ : {})
2928
+ });
2929
+ });
2930
+ if (new Set(sourceIds).size !== sourceIds.length ||
2931
+ sourceIds.some((sourceId) => this._elements.has(sourceId) || this._deletedMap.has(sourceId))) {
2932
+ throw new Error('[SceneTree] Element batch requires unique inactive ids');
2933
+ }
2934
+ return Object.freeze({
2935
+ target,
2936
+ sourceIds: Object.freeze(sourceIds),
2937
+ insertionIndex,
2938
+ tombstones: new Map(sourceIds.map((sourceId) => [sourceId, this._deletedMap.get(sourceId)])),
2939
+ preparedOrdinaryProperties: this.propsManagerOwner.preflightOrdinaryPropertyCreationBatch(ordinaryPropertyOwners)
2940
+ });
2941
+ }
2942
+ addNewElementBatch(elementData, parent, index = -1, options) {
2943
+ const workspace = this.currentWorkspace;
2944
+ if (!workspace || elementData.length === 0) {
2945
+ return [];
2946
+ }
2947
+ const preflight = this.preflightElementBatch(elementData, parent, index);
2948
+ const { target, sourceIds, insertionIndex, tombstones, preparedOrdinaryProperties } = preflight;
2949
+ const originalChildren = [...target.get('children')];
2950
+ const elements = [];
2951
+ const operationChangeStart = this.changes.length;
2952
+ const canonicalHandoffState = createCanonicalBatchHandoffState();
2953
+ let rollbackPreparedProperties;
2954
+ let completePreparedProperties;
2955
+ let parentMembershipMayHaveChanged = false;
2956
+ const materializeElementBatch = () => {
2957
+ measureCanonicalSceneBatchPhase('scene-tree:element-batch:materialize', () => {
2958
+ elementData.forEach((source) => {
2959
+ const constructorData = { ...source };
2960
+ const element = runWithSceneTreeInitialOwnerValues(source, () => this.createElement(constructorData, false));
2961
+ if (!element) {
2962
+ throw new Error('[SceneTree] Canonical batch element creation failed');
2963
+ }
2964
+ elements.push(element);
2965
+ });
2966
+ });
2967
+ };
2968
+ const projectElementBatch = () => {
2969
+ measureCanonicalSceneBatchPhase('scene-tree:element-batch:parent-membership', () => {
2970
+ parentMembershipMayHaveChanged = true;
2971
+ workspace.addNewElements(elements, target, insertionIndex);
2972
+ });
2973
+ measureCanonicalSceneBatchPhase('scene-tree:element-batch:record-evidence', () => {
2974
+ this.changes.splice(operationChangeStart);
2975
+ elements.forEach((element, offset) => {
2976
+ this.addChangeForAddElement(element, target.get('id'), insertionIndex + offset);
2977
+ });
2978
+ });
2979
+ };
2980
+ try {
2981
+ let propsEvents = [];
2982
+ runWithDeferredReplayAcknowledgement(() => {
2983
+ const propertyBatch = this.propsManagerOwner.runInPropertyCreationBatch(materializeElementBatch, preparedOrdinaryProperties);
2984
+ rollbackPreparedProperties = propertyBatch.rollback;
2985
+ completePreparedProperties = propertyBatch.complete;
2986
+ projectElementBatch();
2987
+ measureCanonicalSceneBatchPhase('scene-tree:element-batch:commit-props', () => {
2988
+ propsEvents =
2989
+ this.propsManagerOwner.prepareTransactionEvents(options);
2990
+ });
147
2991
  });
148
- propsManager.commitChanges();
149
- workspace.addNewElement(newElement, parent, index);
150
- this.commitSceneTreeTransaction();
151
- return newElement.get('id');
2992
+ measureCanonicalSceneBatchPhase('scene-tree:element-batch:commit-scene', () => {
2993
+ this.commitSceneTreeTransaction(options, {
2994
+ elements,
2995
+ propsEvents,
2996
+ [canonicalBatchHandoffState]: canonicalHandoffState
2997
+ });
2998
+ });
2999
+ completePreparedProperties?.();
3000
+ return Object.freeze(elements.map((element) => element.get('id')));
3001
+ }
3002
+ catch (error) {
3003
+ if (wasCanonicalBatchHandoffAccepted(canonicalHandoffState)) {
3004
+ completePreparedProperties?.();
3005
+ this.propsManagerOwner.cleanChanges();
3006
+ this.cleanChanges();
3007
+ throw error;
3008
+ }
3009
+ rollbackPreparedProperties?.();
3010
+ if (parentMembershipMayHaveChanged) {
3011
+ workspace.replaceBatchParentChildren(target, originalChildren);
3012
+ }
3013
+ const activeElements = elements.filter((element) => this._elements.get(element.get('id')) === element);
3014
+ if (activeElements.length > 0) {
3015
+ this.removeElementsFromCanonicalMap(activeElements);
3016
+ }
3017
+ elements.forEach((element) => {
3018
+ disposeElementComputed(element);
3019
+ });
3020
+ sourceIds.forEach((sourceId) => {
3021
+ const tombstone = tombstones.get(sourceId);
3022
+ if (tombstone) {
3023
+ this._deletedMap.set(sourceId, tombstone);
3024
+ }
3025
+ else {
3026
+ this._deletedMap.delete(sourceId);
3027
+ }
3028
+ });
3029
+ this.changes.splice(operationChangeStart);
3030
+ throw error;
152
3031
  }
153
- return '';
154
3032
  }
155
- removeElement(data, index, parent) {
3033
+ removeElement(data, parent, options) {
156
3034
  const workspace = this.currentWorkspace;
157
3035
  if (!workspace) {
158
- return;
3036
+ return false;
159
3037
  }
160
3038
  const elementId = data.id;
161
3039
  const element = this.getElementById(elementId);
162
3040
  if (!element) {
163
- return;
3041
+ return false;
164
3042
  }
165
- this.addChangeForRemoveElement(element);
166
- workspace.removeElement(element, index, parent);
3043
+ const resolvedParentId = parent?.get('id') ??
3044
+ data.parentId ??
3045
+ element.get('parentId');
3046
+ const resolvedParent = resolvedParentId
3047
+ ? this.getElementById(resolvedParentId)
3048
+ : undefined;
3049
+ const container = resolvedParent ?? workspace;
3050
+ if (!isGroupEntity(container.get('type'))) {
3051
+ return false;
3052
+ }
3053
+ const children = this.getContainerChildren(container, `Remove parent "${resolvedParentId}"`);
3054
+ if (resolvedParentId !== element.get('parentId') ||
3055
+ !children.includes(elementId)) {
3056
+ return false;
3057
+ }
3058
+ const index = children.indexOf(elementId);
3059
+ const preparedMutation = this.prepareCanonicalElementRemoval([
3060
+ {
3061
+ data: element.save(),
3062
+ parentId: resolvedParentId,
3063
+ index
3064
+ }
3065
+ ]);
3066
+ return (this.applyPreparedElementMutation(preparedMutation, options)
3067
+ .orderedElementIds.length === 1);
167
3068
  }
168
- updateComputedData(elementId, key, data) {
169
- const element = this.getElementById(elementId);
170
- if (!element) {
171
- return;
3069
+ updateLocalComputedData(updates) {
3070
+ const seenElementIds = new Set();
3071
+ const prepared = updates.map((update) => {
3072
+ if (!isRecord(update) ||
3073
+ typeof update.elementId !== 'string' ||
3074
+ update.elementId.length === 0 ||
3075
+ seenElementIds.has(update.elementId) ||
3076
+ !isRecord(update.values)) {
3077
+ throw new Error('[SceneTree] Local computed values require unique active element batches');
3078
+ }
3079
+ seenElementIds.add(update.elementId);
3080
+ const element = this.getElementById(update.elementId);
3081
+ if (!element || element.get('type') === EntityTypes.WORKSPACE) {
3082
+ throw new Error(`[SceneTree] Local computed values require active element "${update.elementId}"`);
3083
+ }
3084
+ const computedSnapshot = getComputedSnapshot(element);
3085
+ const invalidKey = Object.keys(update.values).find((key) => LOCAL_COMPUTED_RESERVED_KEYS.has(key));
3086
+ if (invalidKey) {
3087
+ throw new Error(`[SceneTree] Local computed values cannot update canonical key "${invalidKey}"`);
3088
+ }
3089
+ const changes = [];
3090
+ Object.entries(update.values).forEach(([key, sourceAfter]) => {
3091
+ if (sourceAfter === undefined) {
3092
+ return;
3093
+ }
3094
+ const before = computedSnapshot[key];
3095
+ const after = cloneSceneTreeValue(sourceAfter);
3096
+ if (!isEqual(before, after)) {
3097
+ changes.push({
3098
+ owner: 'computed',
3099
+ key,
3100
+ before,
3101
+ after
3102
+ });
3103
+ }
3104
+ });
3105
+ return {
3106
+ element,
3107
+ elementId: update.elementId,
3108
+ changes
3109
+ };
3110
+ });
3111
+ prepared.forEach(({ element, changes }) => {
3112
+ changes.forEach(({ key, after }) => {
3113
+ element.updateComputedData(key, after);
3114
+ });
3115
+ });
3116
+ const events = cloneAndFreezeSceneValue(prepared.flatMap(({ elementId, changes }) => changes.length === 0
3117
+ ? []
3118
+ : [
3119
+ {
3120
+ type: EventTypes.UPDATE_COMPUTED_DATA,
3121
+ payload: {
3122
+ action: SCENE_TREE_ACTIONS.UPDATE_ELEMENT_COMPUTED_DATA_BATCH,
3123
+ eventName: EventTypes.UPDATE_COMPUTED_DATA,
3124
+ id: elementId,
3125
+ changes
3126
+ }
3127
+ }
3128
+ ]));
3129
+ if (events.length > 0) {
3130
+ publishLocalComputedDataEvents(events);
3131
+ }
3132
+ }
3133
+ patchLocalComputedData(updates) {
3134
+ const seenElementIds = new Set();
3135
+ const prepared = updates.map((update) => {
3136
+ if (!isRecord(update) ||
3137
+ typeof update.elementId !== 'string' ||
3138
+ update.elementId.length === 0 ||
3139
+ seenElementIds.has(update.elementId) ||
3140
+ !isRecord(update.patch)) {
3141
+ throw new Error('[SceneTree] Local computed patches require unique active element batches');
3142
+ }
3143
+ seenElementIds.add(update.elementId);
3144
+ const element = this.getElementById(update.elementId);
3145
+ if (!element || element.get('type') === EntityTypes.WORKSPACE) {
3146
+ throw new Error(`[SceneTree] Local computed patches require active element "${update.elementId}"`);
3147
+ }
3148
+ const patch = update.patch;
3149
+ const invalidKey = [
3150
+ ...Object.keys(patch.values ?? {}),
3151
+ ...Object.keys(patch.records ?? {})
3152
+ ].find((key) => LOCAL_COMPUTED_RESERVED_KEYS.has(key));
3153
+ if (invalidKey) {
3154
+ throw new Error(`[SceneTree] Local computed patches cannot update canonical key "${invalidKey}"`);
3155
+ }
3156
+ const computedSnapshot = getComputedSnapshot(element);
3157
+ validateComputedDataPatch(patch, computedSnapshot);
3158
+ const patchChange = {};
3159
+ const assignments = [];
3160
+ Object.entries(patch.values ?? {}).forEach(([key, sourceAfter]) => {
3161
+ const before = computedSnapshot[key];
3162
+ const after = cloneSceneTreeValue(sourceAfter);
3163
+ if (isEqual(before, after)) {
3164
+ return;
3165
+ }
3166
+ assignments.push({ key, after });
3167
+ patchChange.values ?? (patchChange.values = {});
3168
+ setOwnEnumerableValue(patchChange.values, key, { before, after });
3169
+ });
3170
+ Object.entries(patch.records ?? {}).forEach(([key, recordPatch]) => {
3171
+ const currentRecord = cloneRecord(computedSnapshot[key]);
3172
+ let nextRecord = { ...currentRecord };
3173
+ const nextRecordPatch = {};
3174
+ Object.entries(recordPatch.set ?? {}).forEach(([recordId, sourceAfter]) => {
3175
+ const recordExists = hasOwnRecordValue(currentRecord, recordId);
3176
+ const before = currentRecord[recordId];
3177
+ const after = cloneSceneTreeValue(sourceAfter);
3178
+ if (recordExists && isEqual(before, after)) {
3179
+ return;
3180
+ }
3181
+ setOwnEnumerableValue(nextRecord, recordId, after);
3182
+ nextRecordPatch.set ?? (nextRecordPatch.set = {});
3183
+ setOwnEnumerableValue(nextRecordPatch.set, recordId, recordExists ? { before, after } : { after });
3184
+ });
3185
+ (recordPatch.remove ?? []).forEach((recordId) => {
3186
+ if (!hasOwnRecordValue(currentRecord, recordId)) {
3187
+ return;
3188
+ }
3189
+ nextRecordPatch.remove ?? (nextRecordPatch.remove = {});
3190
+ setOwnEnumerableValue(nextRecordPatch.remove, recordId, {
3191
+ before: currentRecord[recordId]
3192
+ });
3193
+ const { [recordId]: _removed, ...withoutRecord } = nextRecord;
3194
+ nextRecord = withoutRecord;
3195
+ });
3196
+ if (Object.keys(nextRecordPatch.set ?? {}).length === 0 &&
3197
+ Object.keys(nextRecordPatch.remove ?? {}).length === 0) {
3198
+ return;
3199
+ }
3200
+ assignments.push({
3201
+ key,
3202
+ after: nextRecord
3203
+ });
3204
+ patchChange.records ?? (patchChange.records = {});
3205
+ setOwnEnumerableValue(patchChange.records, key, nextRecordPatch);
3206
+ });
3207
+ return {
3208
+ element,
3209
+ elementId: update.elementId,
3210
+ assignments,
3211
+ patch: patchChange
3212
+ };
3213
+ });
3214
+ prepared.forEach(({ element, assignments }) => {
3215
+ assignments.forEach(({ key, after }) => {
3216
+ element.updateComputedData(key, after);
3217
+ });
3218
+ });
3219
+ const events = cloneAndFreezeSceneValue(prepared.flatMap(({ elementId, patch }) => hasPatchChanges(patch)
3220
+ ? [
3221
+ {
3222
+ type: EventTypes.UPDATE_COMPUTED_DATA_PATCH,
3223
+ payload: {
3224
+ id: elementId,
3225
+ patch
3226
+ }
3227
+ }
3228
+ ]
3229
+ : []));
3230
+ if (events.length > 0) {
3231
+ publishLocalComputedDataEvents(events);
3232
+ }
3233
+ }
3234
+ projectLocalComputedDataFromPropertyIds(sourcePropertyIds) {
3235
+ const valuesByElementId = new Map();
3236
+ this.propsManagerOwner
3237
+ .resolvePropertyAncestorIds(sourcePropertyIds)
3238
+ .forEach((sourcePropertyId) => {
3239
+ this.getElementPropertyRelations(sourcePropertyId).forEach((relation) => {
3240
+ const property = this.propsManagerOwner.getPropertyById(relation.componentId);
3241
+ if (!property) {
3242
+ return;
3243
+ }
3244
+ const values = valuesByElementId.get(relation.ownerElementId) ??
3245
+ {};
3246
+ Object.entries(property.getValue()).forEach(([key, value]) => {
3247
+ if (value !== undefined) {
3248
+ setOwnEnumerableValue(values, key, cloneSceneTreeValue(value));
3249
+ }
3250
+ });
3251
+ valuesByElementId.set(relation.ownerElementId, values);
3252
+ });
3253
+ });
3254
+ if (valuesByElementId.size > 0) {
3255
+ this.updateLocalComputedData([...valuesByElementId].map(([elementId, values]) => ({
3256
+ elementId,
3257
+ values
3258
+ })));
3259
+ }
3260
+ }
3261
+ prepareSceneTreeTransactionEvents(options) {
3262
+ return this.changes.map((change) => {
3263
+ const changeOptions = change.options ?? options;
3264
+ const routedOptions = Object.freeze({
3265
+ ...(changeOptions ?? {}),
3266
+ shared: changeOptions?.shared ?? SharedDataChannelNames.SCENE_TREE
3267
+ });
3268
+ return Object.freeze({
3269
+ type: EventTypes.UPDATE_TRANSACTION,
3270
+ eventName: change.eventName,
3271
+ payload: deepFreezeSceneValue(change),
3272
+ options: routedOptions
3273
+ });
3274
+ });
3275
+ }
3276
+ createCanonicalPropertyDeliveryOwners(elements) {
3277
+ return elements.map((element) => {
3278
+ const elementType = element.get('type');
3279
+ if (!componentRegistry.get(elementType)) {
3280
+ throw new Error(`[SceneTree] Canonical delivery has unregistered type "${elementType}"`);
3281
+ }
3282
+ const props = element.props;
3283
+ const rootPropertyIds = props.getCanonicalRootPropertyIds?.();
3284
+ if (!rootPropertyIds) {
3285
+ throw new Error(`[SceneTree] Canonical delivery is missing property owner evidence for "${element.get('id')}"`);
3286
+ }
3287
+ return Object.freeze({
3288
+ orderedId: element.get('id'),
3289
+ rootPropertyIds: Object.freeze([...rootPropertyIds])
3290
+ });
3291
+ });
3292
+ }
3293
+ commitCanonicalElementBatch(options, canonical) {
3294
+ const handoffState = canonical[canonicalBatchHandoffState] ??
3295
+ createCanonicalBatchHandoffState();
3296
+ const transactionOwner = getTransactionOwner();
3297
+ const preparedPropsEvents = canonical.propsEvents;
3298
+ const propertyOwners = this.createCanonicalPropertyDeliveryOwners(canonical.elements);
3299
+ const propertyOrderedIds = Object.freeze(propertyOwners.map(({ orderedId }) => orderedId));
3300
+ const propsEvents = preparedPropsEvents.map(({ eventName, payload, options: eventOptions }) => {
3301
+ if (payload.action !== PROPS_ACTIONS.ADD_PROPERTY) {
3302
+ throw new Error('[SceneTree] Canonical element batch requires additive Props evidence');
3303
+ }
3304
+ const addPayload = payload;
3305
+ Object.freeze(addPayload.data);
3306
+ const ownerPayload = Object.freeze({
3307
+ ...addPayload,
3308
+ data: addPayload.data
3309
+ });
3310
+ const ownerOptions = Object.freeze({ ...eventOptions });
3311
+ const sharedRecords = this.propsManagerOwner.createCanonicalPropertyDeliveryRecords(ownerPayload, propertyOwners);
3312
+ sharedRecords.forEach((record) => {
3313
+ Object.freeze(record.orderedIds);
3314
+ Object.freeze(record.payload.data);
3315
+ Object.freeze(record.payload);
3316
+ Object.freeze(record);
3317
+ });
3318
+ Object.freeze(sharedRecords);
3319
+ return Object.freeze({
3320
+ type: EventTypes.UPDATE_TRANSACTION,
3321
+ eventName,
3322
+ payload: ownerPayload,
3323
+ options: ownerOptions,
3324
+ canonicalEvidence: Object.freeze({
3325
+ orderedIds: propertyOrderedIds,
3326
+ sharedRecords
3327
+ })
3328
+ });
3329
+ });
3330
+ const preparedSceneEvents = this.prepareSceneTreeTransactionEvents(options);
3331
+ if (preparedSceneEvents.length !== canonical.elements.length) {
3332
+ throw new Error('[SceneTree] Canonical element batch requires one ordered Scene evidence event per element');
3333
+ }
3334
+ const sceneEvents = preparedSceneEvents.map((event) => {
3335
+ const change = event.payload;
3336
+ const elementId = 'data' in change ? change.data.id : undefined;
3337
+ if (!elementId) {
3338
+ throw new Error('[SceneTree] Canonical element batch requires exact Scene delivery evidence');
3339
+ }
3340
+ return Object.freeze({
3341
+ ...event,
3342
+ canonicalEvidence: Object.freeze({
3343
+ orderedIds: Object.freeze([elementId])
3344
+ })
3345
+ });
3346
+ });
3347
+ const events = issueDetachedTransactionOwnerBatch(Object.freeze([...propsEvents, ...sceneEvents]));
3348
+ if (transactionOwner) {
3349
+ try {
3350
+ transactionOwner.updateTransactionBatch(events);
3351
+ markCanonicalBatchHandoffAccepted(handoffState);
3352
+ acknowledgeTransactionReplayApplied();
3353
+ }
3354
+ catch (error) {
3355
+ if (reportsAcceptedCanonicalBatchHandoff(error)) {
3356
+ markCanonicalBatchHandoffAccepted(handoffState);
3357
+ acknowledgeTransactionReplayApplied();
3358
+ }
3359
+ throw error;
3360
+ }
3361
+ }
3362
+ else {
3363
+ events.forEach((event) => {
3364
+ updateTransaction(event);
3365
+ });
3366
+ acknowledgeTransactionReplayApplied();
172
3367
  }
173
- element.updateComputedData(key, data);
3368
+ this.propsManagerOwner.cleanChanges();
3369
+ this.cleanChanges();
174
3370
  }
175
- commitSceneTreeTransaction(options) {
176
- this.changes.forEach((change) => {
177
- updateTransaction(change.eventName, change, options);
3371
+ commitSceneTreeTransaction(options, canonical) {
3372
+ if (canonical) {
3373
+ this.commitCanonicalElementBatch(options, canonical);
3374
+ return;
3375
+ }
3376
+ this.prepareSceneTreeTransactionEvents(options).forEach((event) => {
3377
+ updateTransaction(event);
178
3378
  });
179
3379
  this.cleanChanges();
180
3380
  }
3381
+ dispose() {
3382
+ this._elements.clear();
3383
+ this.elementPropertyRelationsByComponentId.clear();
3384
+ this.elementPropertyRelationRevision += 1;
3385
+ this._deletedMap.clear();
3386
+ this.changes = [];
3387
+ this.workspace = '';
3388
+ this.workspaceList = [];
3389
+ }
3390
+ reset() {
3391
+ this.dispose();
3392
+ }
181
3393
  }
182
3394
  export { SceneTree };
183
3395
  const sceneTree = new SceneTree();