@asyra/props-manager 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.
- package/LICENSE +21 -0
- package/README.md +13 -1
- package/dist/components/base.d.ts +12 -2
- package/dist/components/base.d.ts.map +1 -1
- package/dist/components/base.js +78 -4
- package/dist/components/base.js.map +1 -1
- package/dist/components/index.d.ts +4 -4
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +2 -3
- package/dist/components/index.js.map +1 -1
- package/dist/components/props-change-handler.d.ts +2 -1
- package/dist/components/props-change-handler.d.ts.map +1 -1
- package/dist/components/props-change-handler.js +2 -3
- package/dist/components/props-change-handler.js.map +1 -1
- package/dist/factories/create-property.d.ts +6 -0
- package/dist/factories/create-property.d.ts.map +1 -0
- package/dist/factories/create-property.js +24 -0
- package/dist/factories/create-property.js.map +1 -0
- package/dist/index.d.ts +19 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -3
- package/dist/index.js.map +1 -1
- package/dist/manager/component-accessor.d.ts +12 -0
- package/dist/manager/component-accessor.d.ts.map +1 -0
- package/dist/manager/component-accessor.js +23 -0
- package/dist/manager/component-accessor.js.map +1 -0
- package/dist/manager/props-manager.d.ts +209 -0
- package/dist/manager/props-manager.d.ts.map +1 -0
- package/dist/manager/props-manager.js +3840 -0
- package/dist/manager/props-manager.js.map +1 -0
- package/dist/manager/subscribes.d.ts.map +1 -0
- package/dist/manager/subscribes.js +76 -0
- package/dist/manager/subscribes.js.map +1 -0
- package/dist/registries/declarative-property-type.d.ts +39 -0
- package/dist/registries/declarative-property-type.d.ts.map +1 -0
- package/dist/registries/declarative-property-type.js +482 -0
- package/dist/registries/declarative-property-type.js.map +1 -0
- package/dist/registries/property-component.d.ts +50 -0
- package/dist/registries/property-component.d.ts.map +1 -0
- package/dist/registries/property-component.js +151 -0
- package/dist/registries/property-component.js.map +1 -0
- package/dist/registries/property-definition-value.d.ts +5 -0
- package/dist/registries/property-definition-value.d.ts.map +1 -0
- package/dist/registries/property-definition-value.js +19 -0
- package/dist/registries/property-definition-value.js.map +1 -0
- package/dist/registries/property-definition.d.ts +48 -0
- package/dist/registries/property-definition.d.ts.map +1 -0
- package/dist/registries/property-definition.js +107 -0
- package/dist/registries/property-definition.js.map +1 -0
- package/dist/registries/property-registration.d.ts +36 -0
- package/dist/registries/property-registration.d.ts.map +1 -0
- package/dist/registries/property-registration.js +61 -0
- package/dist/registries/property-registration.js.map +1 -0
- package/dist/registries/property-schema.d.ts +19 -0
- package/dist/registries/property-schema.d.ts.map +1 -0
- package/dist/registries/property-schema.js +75 -0
- package/dist/registries/property-schema.js.map +1 -0
- package/dist/registries/property-value-kind.d.ts +3 -0
- package/dist/registries/property-value-kind.d.ts.map +1 -0
- package/dist/registries/property-value-kind.js +18 -0
- package/dist/registries/property-value-kind.js.map +1 -0
- package/dist/registries/registration-options.d.ts +4 -0
- package/dist/registries/registration-options.d.ts.map +1 -0
- package/dist/registries/registration-options.js +2 -0
- package/dist/registries/registration-options.js.map +1 -0
- package/dist/registries/state.d.ts +14 -0
- package/dist/registries/state.d.ts.map +1 -0
- package/dist/registries/state.js +53 -0
- package/dist/registries/state.js.map +1 -0
- package/package.json +24 -4
- package/.turbo/turbo-test$colon$ci.log +0 -130
- package/.turbo/turbo-test$colon$local.log +0 -46
- package/.turbo/turbo-test.log +0 -0
- package/CHANGELOG.md +0 -37
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/clover.xml +0 -368
- package/coverage/coverage-final.json +0 -5904
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -131
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -196
- package/coverage/src/components/base.ts.html +0 -262
- package/coverage/src/components/dimension.ts.html +0 -253
- package/coverage/src/components/index.html +0 -176
- package/coverage/src/components/index.ts.html +0 -106
- package/coverage/src/components/position.ts.html +0 -250
- package/coverage/src/components/props-change-handler.ts.html +0 -145
- package/coverage/src/index.html +0 -161
- package/coverage/src/index.ts.html +0 -106
- package/coverage/src/props-manager.ts.html +0 -574
- package/coverage/src/subscribes.ts.html +0 -247
- package/coverage/src/utils.ts.html +0 -226
- package/dist/__tests__/props-manager.test.d.ts +0 -2
- package/dist/__tests__/props-manager.test.d.ts.map +0 -1
- package/dist/__tests__/props-manager.test.js +0 -290
- package/dist/__tests__/props-manager.test.js.map +0 -1
- package/dist/components/dimension.d.ts +0 -12
- package/dist/components/dimension.d.ts.map +0 -1
- package/dist/components/dimension.js +0 -43
- package/dist/components/dimension.js.map +0 -1
- package/dist/components/position.d.ts +0 -12
- package/dist/components/position.d.ts.map +0 -1
- package/dist/components/position.js +0 -42
- package/dist/components/position.js.map +0 -1
- package/dist/props-manager.d.ts +0 -28
- package/dist/props-manager.d.ts.map +0 -1
- package/dist/props-manager.js +0 -120
- package/dist/props-manager.js.map +0 -1
- package/dist/subscribes.d.ts.map +0 -1
- package/dist/subscribes.js +0 -35
- package/dist/subscribes.js.map +0 -1
- package/dist/utils.d.ts +0 -3
- package/dist/utils.d.ts.map +0 -1
- package/dist/utils.js +0 -31
- package/dist/utils.js.map +0 -1
- package/src/__tests__/props-manager.test.ts +0 -362
- package/src/components/base.ts +0 -59
- package/src/components/dimension.ts +0 -56
- package/src/components/index.ts +0 -7
- package/src/components/position.ts +0 -55
- package/src/components/props-change-handler.ts +0 -20
- package/src/index.ts +0 -7
- package/src/props-manager.ts +0 -163
- package/src/subscribes.ts +0 -54
- package/src/utils.ts +0 -47
- package/tsconfig.json +0 -17
- /package/dist/{subscribes.d.ts → manager/subscribes.d.ts} +0 -0
|
@@ -0,0 +1,3840 @@
|
|
|
1
|
+
import { IDTypes, PROPS_ACTIONS, SharedDataChannelNames, beginBrowserDragPhase, measureBrowserDragPhase, id, isRecord } from '@asyra/utils';
|
|
2
|
+
import { acknowledgeTransactionReplayApplied, EventTypes, getTransactionReplayMode, TransactionEventTypes, updateTransaction, updateTransactionBatch } from '@asyra/reactive-events';
|
|
3
|
+
import * as lodashModule from 'lodash';
|
|
4
|
+
import { createProperty, createPropertyWithConstructor } from '../factories/create-property.js';
|
|
5
|
+
import { arePropertyChildRelationsEqual, getPropertyComponent, getPropertyComponentBatchRebindableRelation, getPropertyComponentCanonicalChildRelation, getPropertyComponentConfigDefinition, getPropertyComponentRegistrationRevision, isPropertyComponentBatchRebindable, resolvePropertyComponentConfigRoles } from '../registries/property-component.js';
|
|
6
|
+
import { clonePropertyDefinitionValue } from '../registries/property-definition-value.js';
|
|
7
|
+
import elementPropertyRegistry from '../registries/property-definition.js';
|
|
8
|
+
import { matchesPropertyValueKind } from '../registries/property-value-kind.js';
|
|
9
|
+
import { getPropertySchemaRegistrationRevision, getRegisteredPropertySchema, runWithPropertySchemaResolver } from '../registries/property-schema.js';
|
|
10
|
+
import { runWithPropertyComponentAccessor, setComponentAccessor } from './component-accessor.js';
|
|
11
|
+
const lodash = lodashModule.default ?? lodashModule;
|
|
12
|
+
const { isEqual } = lodash;
|
|
13
|
+
const clonePropsValue = (data) => {
|
|
14
|
+
if (typeof globalThis.structuredClone === 'function') {
|
|
15
|
+
return globalThis.structuredClone(data);
|
|
16
|
+
}
|
|
17
|
+
return JSON.parse(JSON.stringify(data));
|
|
18
|
+
};
|
|
19
|
+
const beginPropertyBatchPhase = beginBrowserDragPhase;
|
|
20
|
+
export const measurePropertyBatchPhase = measureBrowserDragPhase;
|
|
21
|
+
const cloneLoadData = (data) => clonePropsValue(data);
|
|
22
|
+
const isAddPropertyChange = (change) => change.action === PROPS_ACTIONS.ADD_PROPERTY &&
|
|
23
|
+
change.eventName === EventTypes.ADD_PROPERTY;
|
|
24
|
+
const isRemovePropertyChange = (change) => change.action === PROPS_ACTIONS.REMOVE_PROPERTY &&
|
|
25
|
+
change.eventName === EventTypes.REMOVE_PROPERTY;
|
|
26
|
+
const isUpdatePropertyChange = (change) => change.action === PROPS_ACTIONS.UPDATE_PROPERTY &&
|
|
27
|
+
change.eventName === EventTypes.UPDATE_PROPERTY;
|
|
28
|
+
const reportsAcceptedPropertyMutationHandoff = (error) => error !== null &&
|
|
29
|
+
typeof error === 'object' &&
|
|
30
|
+
'batchAccepted' in error &&
|
|
31
|
+
error.batchAccepted === true;
|
|
32
|
+
const deepFreezePropertyContract = (value) => {
|
|
33
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
34
|
+
Object.values(value).forEach(deepFreezePropertyContract);
|
|
35
|
+
Object.freeze(value);
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
};
|
|
39
|
+
const snapshotPropertySchema = (schema) => schema
|
|
40
|
+
? deepFreezePropertyContract({
|
|
41
|
+
type: schema.type,
|
|
42
|
+
fields: schema.fields.map((field) => ({
|
|
43
|
+
...field,
|
|
44
|
+
allowedUnits: field.allowedUnits
|
|
45
|
+
? [...field.allowedUnits]
|
|
46
|
+
: undefined,
|
|
47
|
+
defaultValue: clonePropertyDefinitionValue(field.defaultValue)
|
|
48
|
+
}))
|
|
49
|
+
})
|
|
50
|
+
: undefined;
|
|
51
|
+
const snapshotPropertyChildRelation = (relation) => relation ? Object.freeze({ ...relation }) : undefined;
|
|
52
|
+
const isRuntimePropertyFieldValueValid = (field, value) => {
|
|
53
|
+
if (!matchesPropertyValueKind(field.kind, value)) {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
if (field.allowedUnits &&
|
|
57
|
+
field.allowedUnits.length > 0 &&
|
|
58
|
+
typeof value === 'string' &&
|
|
59
|
+
!field.allowedUnits.some((unit) => unit === value)) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
if (!field.validate) {
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
return field.validate(value);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const describeInvalidRuntimePropertyFieldValue = (value) => {
|
|
73
|
+
if (typeof value === 'number' && !Number.isFinite(value)) {
|
|
74
|
+
return 'non-finite number';
|
|
75
|
+
}
|
|
76
|
+
if (Array.isArray(value)) {
|
|
77
|
+
return 'array';
|
|
78
|
+
}
|
|
79
|
+
if (value === null) {
|
|
80
|
+
return 'null';
|
|
81
|
+
}
|
|
82
|
+
return typeof value;
|
|
83
|
+
};
|
|
84
|
+
const assertRuntimePropertyFields = (data, schema, ownerLabel, excludedKeys = new Set()) => {
|
|
85
|
+
schema?.fields.forEach((field) => {
|
|
86
|
+
if (!excludedKeys.has(field.key) &&
|
|
87
|
+
Object.prototype.hasOwnProperty.call(data, field.key) &&
|
|
88
|
+
!isRuntimePropertyFieldValueValid(field, data[field.key])) {
|
|
89
|
+
throw new Error(`[PropsManager] Invalid runtime property field "${ownerLabel}.${field.key}" (received ${describeInvalidRuntimePropertyFieldValue(data[field.key])})`);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
class PropsManager {
|
|
94
|
+
constructor() {
|
|
95
|
+
this._components = new Map();
|
|
96
|
+
this._deletedMap = new Map();
|
|
97
|
+
this.changes = [];
|
|
98
|
+
this.validatedLoadArtifacts = new WeakMap();
|
|
99
|
+
this.validatedRestoreArtifacts = new WeakMap();
|
|
100
|
+
this.validatedPropertyCreationArtifacts = new WeakMap();
|
|
101
|
+
this.validatedOrdinaryPropertyCreationArtifacts = new WeakMap();
|
|
102
|
+
this.validatedActivePropertyArtifacts = new WeakMap();
|
|
103
|
+
this.validatedPropertyMutationArtifacts = new WeakMap();
|
|
104
|
+
this.propertyCreationBatch = null;
|
|
105
|
+
this.activePropertyBatch = null;
|
|
106
|
+
this.propertyMutationStagedById = null;
|
|
107
|
+
this.propertyMutationApplyActive = false;
|
|
108
|
+
this.relationshipChildIdsByOwnerId = new Map();
|
|
109
|
+
this.relationshipOwnerIdsByChildId = new Map();
|
|
110
|
+
this.propertyStateRevision = 0;
|
|
111
|
+
this.componentAccessor = {
|
|
112
|
+
getPropertyById: (propertyId) => this.resolvePropertyForComponent(propertyId),
|
|
113
|
+
addToMap: (component) => this.addToMap(component),
|
|
114
|
+
createComponent: (data) => this.createPropertyInternal(data, 'relationship-child'),
|
|
115
|
+
addChange: (change) => this.addChange({
|
|
116
|
+
action: PROPS_ACTIONS.UPDATE_PROPERTY,
|
|
117
|
+
eventName: EventTypes.UPDATE_PROPERTY,
|
|
118
|
+
...change
|
|
119
|
+
})
|
|
120
|
+
};
|
|
121
|
+
setComponentAccessor(this.componentAccessor);
|
|
122
|
+
}
|
|
123
|
+
advancePropertyStateRevision() {
|
|
124
|
+
this.propertyStateRevision += 1;
|
|
125
|
+
}
|
|
126
|
+
prepareRelationshipIndexEntry(component, sourceSnapshot) {
|
|
127
|
+
const propertyId = component.get('id');
|
|
128
|
+
const type = component.get('type');
|
|
129
|
+
const relation = typeof type === 'string'
|
|
130
|
+
? getPropertyComponentCanonicalChildRelation(type)
|
|
131
|
+
: undefined;
|
|
132
|
+
if (!relation) {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (sourceSnapshot &&
|
|
136
|
+
(sourceSnapshot.id !== propertyId || sourceSnapshot.type !== type)) {
|
|
137
|
+
throw new Error(`[PropsManager] Property relationship index received inexact owner "${propertyId}"`);
|
|
138
|
+
}
|
|
139
|
+
const value = sourceSnapshot
|
|
140
|
+
? sourceSnapshot[relation.key]
|
|
141
|
+
: component.data[relation.key];
|
|
142
|
+
if (!Array.isArray(value) ||
|
|
143
|
+
value.some((childId) => typeof childId !== 'string') ||
|
|
144
|
+
new Set(value).size !== value.length) {
|
|
145
|
+
return Object.freeze([]);
|
|
146
|
+
}
|
|
147
|
+
return Object.freeze([...value]);
|
|
148
|
+
}
|
|
149
|
+
replaceRelationshipOwnerEdges(ownerId, nextChildIds) {
|
|
150
|
+
const hasPreviousOwner = this.relationshipChildIdsByOwnerId.has(ownerId);
|
|
151
|
+
const previousChildIds = this.relationshipChildIdsByOwnerId.get(ownerId) ?? [];
|
|
152
|
+
if ((!hasPreviousOwner && nextChildIds === undefined) ||
|
|
153
|
+
(hasPreviousOwner &&
|
|
154
|
+
nextChildIds !== undefined &&
|
|
155
|
+
previousChildIds.length === nextChildIds.length &&
|
|
156
|
+
previousChildIds.every((childId, index) => childId === nextChildIds[index]))) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
previousChildIds.forEach((childId) => {
|
|
160
|
+
const ownerIds = this.relationshipOwnerIdsByChildId.get(childId);
|
|
161
|
+
ownerIds?.delete(ownerId);
|
|
162
|
+
if (ownerIds?.size === 0) {
|
|
163
|
+
this.relationshipOwnerIdsByChildId.delete(childId);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
if (nextChildIds === undefined) {
|
|
167
|
+
this.relationshipChildIdsByOwnerId.delete(ownerId);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const retainedChildIds = Object.freeze([...nextChildIds]);
|
|
171
|
+
this.relationshipChildIdsByOwnerId.set(ownerId, retainedChildIds);
|
|
172
|
+
retainedChildIds.forEach((childId) => {
|
|
173
|
+
const ownerIds = this.relationshipOwnerIdsByChildId.get(childId) ?? new Set();
|
|
174
|
+
ownerIds.add(ownerId);
|
|
175
|
+
this.relationshipOwnerIdsByChildId.set(childId, ownerIds);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
refreshRelationshipOwnerEdges(component, sourceSnapshot) {
|
|
179
|
+
this.replaceRelationshipOwnerEdges(component.get('id'), this.prepareRelationshipIndexEntry(component, sourceSnapshot));
|
|
180
|
+
}
|
|
181
|
+
registerActiveComponent(component, relationshipChildIds) {
|
|
182
|
+
const propertyId = component.get('id');
|
|
183
|
+
this._components.set(propertyId, component);
|
|
184
|
+
this.replaceRelationshipOwnerEdges(propertyId, relationshipChildIds);
|
|
185
|
+
}
|
|
186
|
+
unregisterActiveComponent(propertyId) {
|
|
187
|
+
const component = this._components.get(propertyId);
|
|
188
|
+
this._components.delete(propertyId);
|
|
189
|
+
this.replaceRelationshipOwnerEdges(propertyId, undefined);
|
|
190
|
+
return component;
|
|
191
|
+
}
|
|
192
|
+
createLoadValidationResult(data, diagnostics) {
|
|
193
|
+
const validatedSnapshot = cloneLoadData(data);
|
|
194
|
+
const result = {
|
|
195
|
+
data: cloneLoadData(validatedSnapshot),
|
|
196
|
+
diagnostics
|
|
197
|
+
};
|
|
198
|
+
this.validatedLoadArtifacts.set(result, validatedSnapshot);
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
validateLoadData(data) {
|
|
202
|
+
const diagnostics = [];
|
|
203
|
+
const sanitized = {};
|
|
204
|
+
if (!isRecord(data)) {
|
|
205
|
+
diagnostics.push({
|
|
206
|
+
path: 'props',
|
|
207
|
+
message: 'Expected object map for props data'
|
|
208
|
+
});
|
|
209
|
+
return this.createLoadValidationResult(sanitized, diagnostics);
|
|
210
|
+
}
|
|
211
|
+
Object.entries(data).forEach(([componentId, rawComponent]) => {
|
|
212
|
+
if (!isRecord(rawComponent)) {
|
|
213
|
+
diagnostics.push({
|
|
214
|
+
path: `props.${componentId}`,
|
|
215
|
+
message: 'Skipped non-object property component during load'
|
|
216
|
+
});
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const rawType = rawComponent.type;
|
|
220
|
+
if (typeof rawType !== 'string' || rawType.length === 0) {
|
|
221
|
+
diagnostics.push({
|
|
222
|
+
path: `props.${componentId}.type`,
|
|
223
|
+
message: 'Skipped property component with invalid type during load'
|
|
224
|
+
});
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (!getPropertyComponent(rawType)) {
|
|
228
|
+
diagnostics.push({
|
|
229
|
+
path: `props.${componentId}.type`,
|
|
230
|
+
message: `Skipped unregistered property component type "${rawType}" during load`
|
|
231
|
+
});
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
const normalizedId = typeof rawComponent.id === 'string' && rawComponent.id.length > 0
|
|
235
|
+
? rawComponent.id
|
|
236
|
+
: componentId;
|
|
237
|
+
sanitized[normalizedId] = {
|
|
238
|
+
...rawComponent,
|
|
239
|
+
id: normalizedId,
|
|
240
|
+
type: rawType
|
|
241
|
+
};
|
|
242
|
+
});
|
|
243
|
+
return this.createLoadValidationResult(sanitized, diagnostics);
|
|
244
|
+
}
|
|
245
|
+
applyValidatedLoad(result) {
|
|
246
|
+
const validated = this.validatedLoadArtifacts.get(result);
|
|
247
|
+
if (!validated) {
|
|
248
|
+
throw new Error('[PropsManager] Expected an owner-issued one-shot validated load artifact');
|
|
249
|
+
}
|
|
250
|
+
this.validatedLoadArtifacts.delete(result);
|
|
251
|
+
this.dispose();
|
|
252
|
+
Object.keys(validated).forEach((componentId) => {
|
|
253
|
+
const newProperty = createProperty(validated[componentId]);
|
|
254
|
+
this.addToMap(newProperty);
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
load(data) {
|
|
258
|
+
const result = this.validateLoadData(data);
|
|
259
|
+
this.applyValidatedLoad(result);
|
|
260
|
+
}
|
|
261
|
+
save() {
|
|
262
|
+
const data = {};
|
|
263
|
+
this._components.forEach((component, componentId) => {
|
|
264
|
+
data[componentId] = component.save();
|
|
265
|
+
});
|
|
266
|
+
return data;
|
|
267
|
+
}
|
|
268
|
+
preflightElementPropertyValues(definitions, data) {
|
|
269
|
+
definitions.forEach((definition) => {
|
|
270
|
+
assertRuntimePropertyFields(data, definition.schema ?? getRegisteredPropertySchema(definition.type), definition.name);
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
addChange(change) {
|
|
274
|
+
if (isUpdatePropertyChange(change) &&
|
|
275
|
+
(Object.prototype.hasOwnProperty.call(change, 'ownerElementId') ||
|
|
276
|
+
Object.prototype.hasOwnProperty.call(change, 'ownerPropertyName'))) {
|
|
277
|
+
throw new Error('[PropsManager] Property-source evidence cannot accept an initiating owner');
|
|
278
|
+
}
|
|
279
|
+
if (this.activePropertyBatch) {
|
|
280
|
+
const activeBatch = this.activePropertyBatch;
|
|
281
|
+
if (isUpdatePropertyChange(change)) {
|
|
282
|
+
this.restoreActivePropertyBatch(activeBatch, change);
|
|
283
|
+
throw new Error(`[PropsManager] Active property reuse batch cannot update active property "${change.id}"`);
|
|
284
|
+
}
|
|
285
|
+
throw new Error('[PropsManager] Active property reuse batch cannot record property changes');
|
|
286
|
+
}
|
|
287
|
+
if (this.propertyMutationStagedById &&
|
|
288
|
+
isUpdatePropertyChange(change) &&
|
|
289
|
+
!this._components.has(change.id)) {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (this.propertyCreationBatch &&
|
|
293
|
+
isUpdatePropertyChange(change) &&
|
|
294
|
+
this.propertyCreationBatch.componentIds.has(change.id)) {
|
|
295
|
+
if (change.options !== undefined) {
|
|
296
|
+
throw new Error('[PropsManager] Canonical property creation batch received an incompatible update');
|
|
297
|
+
}
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if (this.propertyCreationBatch && isUpdatePropertyChange(change)) {
|
|
301
|
+
this.propertyCreationBatch.existingUpdates.push(change);
|
|
302
|
+
}
|
|
303
|
+
let relationshipChildIds;
|
|
304
|
+
let updatesRelationshipIndex = false;
|
|
305
|
+
if (isUpdatePropertyChange(change)) {
|
|
306
|
+
const component = this._components.get(change.id);
|
|
307
|
+
const type = component?.get('type');
|
|
308
|
+
const relation = typeof type === 'string'
|
|
309
|
+
? getPropertyComponentCanonicalChildRelation(type)
|
|
310
|
+
: undefined;
|
|
311
|
+
if (component && relation?.key === change.key) {
|
|
312
|
+
relationshipChildIds = this.prepareRelationshipIndexEntry(component);
|
|
313
|
+
updatesRelationshipIndex = true;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
this.changes.push(change);
|
|
317
|
+
if (updatesRelationshipIndex && isUpdatePropertyChange(change)) {
|
|
318
|
+
this.replaceRelationshipOwnerEdges(change.id, relationshipChildIds);
|
|
319
|
+
}
|
|
320
|
+
this.advancePropertyStateRevision();
|
|
321
|
+
}
|
|
322
|
+
cleanChanges() {
|
|
323
|
+
this.changes = [];
|
|
324
|
+
}
|
|
325
|
+
getPropertyById(propertyId) {
|
|
326
|
+
return this.resolvePropertyForComponent(propertyId);
|
|
327
|
+
}
|
|
328
|
+
resolvePropertyAncestorIds(propertyIds) {
|
|
329
|
+
const orderedIds = [];
|
|
330
|
+
const emittedIds = new Set();
|
|
331
|
+
const completedIds = new Set();
|
|
332
|
+
const visitingIds = new Set();
|
|
333
|
+
const visit = (propertyId) => {
|
|
334
|
+
if (completedIds.has(propertyId)) {
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (visitingIds.has(propertyId)) {
|
|
338
|
+
throw new Error(`[PropsManager] Property ancestor resolution found a relationship cycle at "${propertyId}"`);
|
|
339
|
+
}
|
|
340
|
+
if (!this._components.has(propertyId)) {
|
|
341
|
+
throw new Error(`[PropsManager] Property ancestor resolution requires active property "${propertyId}"`);
|
|
342
|
+
}
|
|
343
|
+
visitingIds.add(propertyId);
|
|
344
|
+
if (!emittedIds.has(propertyId)) {
|
|
345
|
+
emittedIds.add(propertyId);
|
|
346
|
+
orderedIds.push(propertyId);
|
|
347
|
+
}
|
|
348
|
+
this.relationshipOwnerIdsByChildId.get(propertyId)?.forEach((ownerId) => {
|
|
349
|
+
if (!this.relationshipChildIdsByOwnerId.get(ownerId)?.includes(propertyId)) {
|
|
350
|
+
throw new Error(`[PropsManager] Property ancestor resolution found an inconsistent relationship "${ownerId}:${propertyId}"`);
|
|
351
|
+
}
|
|
352
|
+
visit(ownerId);
|
|
353
|
+
});
|
|
354
|
+
visitingIds.delete(propertyId);
|
|
355
|
+
completedIds.add(propertyId);
|
|
356
|
+
};
|
|
357
|
+
propertyIds.forEach((propertyId) => {
|
|
358
|
+
if (typeof propertyId !== 'string' || propertyId.length === 0) {
|
|
359
|
+
throw new Error('[PropsManager] Property ancestor resolution requires valid property ids');
|
|
360
|
+
}
|
|
361
|
+
visit(propertyId);
|
|
362
|
+
});
|
|
363
|
+
return Object.freeze(orderedIds);
|
|
364
|
+
}
|
|
365
|
+
resolvePropertyForComponent(propertyId) {
|
|
366
|
+
const active = this._components.get(propertyId);
|
|
367
|
+
if (active) {
|
|
368
|
+
return active;
|
|
369
|
+
}
|
|
370
|
+
return (this.propertyMutationStagedById?.get(propertyId) ??
|
|
371
|
+
this.propertyCreationBatch?.stagedById.get(propertyId));
|
|
372
|
+
}
|
|
373
|
+
getPropertyIdsByType(type) {
|
|
374
|
+
const ids = new Set();
|
|
375
|
+
const collect = (components) => {
|
|
376
|
+
components.forEach((component, id) => {
|
|
377
|
+
if (component.get('type') === type) {
|
|
378
|
+
ids.add(id);
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
};
|
|
382
|
+
collect(this._components);
|
|
383
|
+
collect(this._deletedMap);
|
|
384
|
+
return Array.from(ids);
|
|
385
|
+
}
|
|
386
|
+
addToMap(component) {
|
|
387
|
+
const comId = component.get('id');
|
|
388
|
+
if (!component || !comId) {
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
const active = this._components.get(comId);
|
|
392
|
+
if (this.propertyMutationStagedById) {
|
|
393
|
+
if (active === component) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const staged = this.propertyMutationStagedById.get(comId);
|
|
397
|
+
if ((staged !== undefined && staged !== component) ||
|
|
398
|
+
active !== undefined ||
|
|
399
|
+
this._deletedMap.has(comId)) {
|
|
400
|
+
throw new Error(`[PropsManager] Property mutation cannot stage property "${comId}"`);
|
|
401
|
+
}
|
|
402
|
+
this.propertyMutationStagedById.set(comId, component);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
if (this.activePropertyBatch) {
|
|
406
|
+
if (!this.activePropertyBatch.componentIds.has(comId) ||
|
|
407
|
+
active !== component) {
|
|
408
|
+
throw new Error(`[PropsManager] Active property reuse batch cannot register property "${comId}"`);
|
|
409
|
+
}
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (this.propertyCreationBatch &&
|
|
413
|
+
active !== undefined &&
|
|
414
|
+
active !== component) {
|
|
415
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot replace active property "${comId}"`);
|
|
416
|
+
}
|
|
417
|
+
if (this.propertyCreationBatch &&
|
|
418
|
+
active === component &&
|
|
419
|
+
!this.propertyCreationBatch.componentIds.has(comId)) {
|
|
420
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot register active owner property "${comId}"`);
|
|
421
|
+
}
|
|
422
|
+
if (this.propertyCreationBatch) {
|
|
423
|
+
if (this.propertyCreationBatch.stagedById.get(comId) !== component) {
|
|
424
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot stage property "${comId}"`);
|
|
425
|
+
}
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const relationshipChildIds = this.prepareRelationshipIndexEntry(component);
|
|
429
|
+
this.removeFromDeletedMap(comId);
|
|
430
|
+
this.registerActiveComponent(component, relationshipChildIds);
|
|
431
|
+
if (active !== component) {
|
|
432
|
+
this.advancePropertyStateRevision();
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
removeFromMap(componentId) {
|
|
436
|
+
if (this.activePropertyBatch) {
|
|
437
|
+
throw new Error(`[PropsManager] Active property reuse batch cannot remove property "${componentId}"`);
|
|
438
|
+
}
|
|
439
|
+
const component = this.getPropertyById(componentId);
|
|
440
|
+
if (!component) {
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
this.addToDeletedMap(component);
|
|
444
|
+
this.unregisterActiveComponent(componentId);
|
|
445
|
+
this.advancePropertyStateRevision();
|
|
446
|
+
}
|
|
447
|
+
addToDeletedMap(component) {
|
|
448
|
+
this._deletedMap.set(component.get('id'), component);
|
|
449
|
+
}
|
|
450
|
+
removeFromDeletedMap(componentId) {
|
|
451
|
+
this._deletedMap.delete(componentId);
|
|
452
|
+
}
|
|
453
|
+
getRestoreComponentById(componentId) {
|
|
454
|
+
return this._deletedMap.get(componentId);
|
|
455
|
+
}
|
|
456
|
+
capturePropertyCreationTypeContract(type, registrationContractByType) {
|
|
457
|
+
const existing = registrationContractByType.get(type);
|
|
458
|
+
if (existing) {
|
|
459
|
+
return existing;
|
|
460
|
+
}
|
|
461
|
+
const constructor = getPropertyComponent(type);
|
|
462
|
+
if (!type || !constructor) {
|
|
463
|
+
throw new Error(`[PropsManager] Property creation has an unregistered type "${type}"`);
|
|
464
|
+
}
|
|
465
|
+
const componentRegistrationRevision = getPropertyComponentRegistrationRevision(type);
|
|
466
|
+
const schemaRegistrationRevision = getPropertySchemaRegistrationRevision(type);
|
|
467
|
+
const childRelation = snapshotPropertyChildRelation(getPropertyComponentCanonicalChildRelation(type));
|
|
468
|
+
const batchRebindableRelation = getPropertyComponentBatchRebindableRelation(constructor);
|
|
469
|
+
if (batchRebindableRelation &&
|
|
470
|
+
!arePropertyChildRelationsEqual(batchRebindableRelation, childRelation)) {
|
|
471
|
+
throw new Error(`[PropsManager] Property creation has incoherent relationship registration for "${type}"`);
|
|
472
|
+
}
|
|
473
|
+
const schema = snapshotPropertySchema(getRegisteredPropertySchema(type));
|
|
474
|
+
if (getPropertyComponentRegistrationRevision(type) !==
|
|
475
|
+
componentRegistrationRevision ||
|
|
476
|
+
getPropertySchemaRegistrationRevision(type) !== schemaRegistrationRevision) {
|
|
477
|
+
throw new Error(`[PropsManager] Property creation registration changed for "${type}"`);
|
|
478
|
+
}
|
|
479
|
+
const contract = Object.freeze({
|
|
480
|
+
type,
|
|
481
|
+
constructor,
|
|
482
|
+
childRelation,
|
|
483
|
+
schema,
|
|
484
|
+
componentRegistrationRevision,
|
|
485
|
+
schemaRegistrationRevision
|
|
486
|
+
});
|
|
487
|
+
registrationContractByType.set(type, contract);
|
|
488
|
+
return contract;
|
|
489
|
+
}
|
|
490
|
+
preflightOrdinaryPropertyCreationBatch(sourceOwners) {
|
|
491
|
+
return measurePropertyBatchPhase('props-manager:ordinary-creation-preflight', () => {
|
|
492
|
+
if (!Array.isArray(sourceOwners) || sourceOwners.length === 0) {
|
|
493
|
+
throw new Error('[PropsManager] Ordinary property creation requires element owners');
|
|
494
|
+
}
|
|
495
|
+
const roots = [];
|
|
496
|
+
const reservedNewComponentIds = new Set();
|
|
497
|
+
const preparedRootTypesById = new Map();
|
|
498
|
+
const relationshipDescriptors = [];
|
|
499
|
+
const registrationContractByType = new Map();
|
|
500
|
+
const capturedRelationshipContractTypes = new Set();
|
|
501
|
+
const captureRelationshipContracts = (type, visiting = new Set()) => {
|
|
502
|
+
if (capturedRelationshipContractTypes.has(type) ||
|
|
503
|
+
visiting.has(type)) {
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
visiting.add(type);
|
|
507
|
+
const contract = this.capturePropertyCreationTypeContract(type, registrationContractByType);
|
|
508
|
+
if (contract.childRelation) {
|
|
509
|
+
captureRelationshipContracts(contract.childRelation.childType, visiting);
|
|
510
|
+
}
|
|
511
|
+
visiting.delete(type);
|
|
512
|
+
capturedRelationshipContractTypes.add(type);
|
|
513
|
+
};
|
|
514
|
+
const explicitDescriptorChildTypes = new Map();
|
|
515
|
+
const preflightRelationshipDescriptor = (value, contract, ownerLabel) => {
|
|
516
|
+
const childRelation = contract.childRelation;
|
|
517
|
+
if (!childRelation) {
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const preflightDescriptorEntry = (item, label, keyedChildId) => {
|
|
521
|
+
if (typeof item === 'string' && keyedChildId === undefined) {
|
|
522
|
+
const activeChild = this._components.get(item);
|
|
523
|
+
const preparedChildType = explicitDescriptorChildTypes.get(item) ??
|
|
524
|
+
preparedRootTypesById.get(item);
|
|
525
|
+
const childType = activeChild?.get('type') ?? preparedChildType;
|
|
526
|
+
if (!childType) {
|
|
527
|
+
throw new Error(`[PropsManager] Ordinary property creation is missing relationship child "${item}"`);
|
|
528
|
+
}
|
|
529
|
+
if (childType !== childRelation.childType) {
|
|
530
|
+
throw new Error(`[PropsManager] Ordinary property creation relationship child "${item}" has the wrong type`);
|
|
531
|
+
}
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
if ((keyedChildId !== undefined && keyedChildId.length === 0) ||
|
|
535
|
+
(childRelation.mode ?? 'ids') !== 'ids-or-objects' ||
|
|
536
|
+
!isRecord(item)) {
|
|
537
|
+
throw new Error(`[PropsManager] Ordinary property creation has an invalid relationship descriptor for "${label}"`);
|
|
538
|
+
}
|
|
539
|
+
const itemChildId = typeof item.id === 'string' && item.id.length > 0
|
|
540
|
+
? item.id
|
|
541
|
+
: undefined;
|
|
542
|
+
if (keyedChildId !== undefined &&
|
|
543
|
+
itemChildId !== undefined &&
|
|
544
|
+
itemChildId !== keyedChildId) {
|
|
545
|
+
throw new Error(`[PropsManager] Ordinary property creation relationship child "${keyedChildId}" has conflicting canonical ids`);
|
|
546
|
+
}
|
|
547
|
+
let explicitChildId = keyedChildId ?? itemChildId;
|
|
548
|
+
let mappedChild;
|
|
549
|
+
try {
|
|
550
|
+
mappedChild = childRelation.toChildData
|
|
551
|
+
? childRelation.toChildData(item, explicitChildId)
|
|
552
|
+
: item;
|
|
553
|
+
}
|
|
554
|
+
catch {
|
|
555
|
+
mappedChild = null;
|
|
556
|
+
}
|
|
557
|
+
if (!isRecord(mappedChild)) {
|
|
558
|
+
throw new Error(`[PropsManager] Ordinary property creation has an invalid relationship descriptor for "${label}"`);
|
|
559
|
+
}
|
|
560
|
+
const normalizedChild = {
|
|
561
|
+
...mappedChild,
|
|
562
|
+
type: childRelation.childType
|
|
563
|
+
};
|
|
564
|
+
if (typeof normalizedChild.id === 'string' &&
|
|
565
|
+
normalizedChild.id.length > 0) {
|
|
566
|
+
if (explicitChildId && normalizedChild.id !== explicitChildId) {
|
|
567
|
+
throw new Error(`[PropsManager] Ordinary property creation relationship child "${explicitChildId}" changed its canonical id`);
|
|
568
|
+
}
|
|
569
|
+
explicitChildId = normalizedChild.id;
|
|
570
|
+
}
|
|
571
|
+
if (!explicitChildId) {
|
|
572
|
+
delete normalizedChild.id;
|
|
573
|
+
explicitChildId = undefined;
|
|
574
|
+
}
|
|
575
|
+
if (explicitChildId) {
|
|
576
|
+
const activeChild = this._components.get(explicitChildId);
|
|
577
|
+
if (activeChild) {
|
|
578
|
+
if (activeChild.get('type') !== childRelation.childType) {
|
|
579
|
+
throw new Error(`[PropsManager] Ordinary property creation relationship child "${explicitChildId}" has the wrong type`);
|
|
580
|
+
}
|
|
581
|
+
if (Object.keys(normalizedChild).some((key) => key !== 'id' && key !== 'type')) {
|
|
582
|
+
throw new Error(`[PropsManager] Ordinary property creation cannot apply an active relationship child override for "${explicitChildId}"`);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
else if (reservedNewComponentIds.has(explicitChildId)) {
|
|
586
|
+
throw new Error(`[PropsManager] Ordinary property creation relationship child "${explicitChildId}" conflicts with a reserved property id`);
|
|
587
|
+
}
|
|
588
|
+
else if (this._deletedMap.has(explicitChildId)) {
|
|
589
|
+
throw new Error(`[PropsManager] Ordinary property creation has a duplicate relationship child "${explicitChildId}"`);
|
|
590
|
+
}
|
|
591
|
+
else {
|
|
592
|
+
reservedNewComponentIds.add(explicitChildId);
|
|
593
|
+
explicitDescriptorChildTypes.set(explicitChildId, childRelation.childType);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
const childContract = registrationContractByType.get(childRelation.childType);
|
|
597
|
+
if (!childContract) {
|
|
598
|
+
throw new Error(`[PropsManager] Ordinary property creation has an unregistered relationship child type "${childRelation.childType}"`);
|
|
599
|
+
}
|
|
600
|
+
const excludedChildKeys = childContract.childRelation
|
|
601
|
+
? new Set([childContract.childRelation.key])
|
|
602
|
+
: undefined;
|
|
603
|
+
assertRuntimePropertyFields(normalizedChild, childContract.schema, label, excludedChildKeys);
|
|
604
|
+
if (childContract.childRelation &&
|
|
605
|
+
Object.prototype.hasOwnProperty.call(normalizedChild, childContract.childRelation.key)) {
|
|
606
|
+
preflightRelationshipDescriptor(normalizedChild[childContract.childRelation.key], childContract, label);
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
if (Array.isArray(value)) {
|
|
610
|
+
value.forEach((item, index) => {
|
|
611
|
+
preflightDescriptorEntry(item, `${ownerLabel}[${index}]`, undefined);
|
|
612
|
+
});
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
if (childRelation.collection === 'array-or-record' &&
|
|
616
|
+
isRecord(value)) {
|
|
617
|
+
Object.keys(value).forEach((childId) => {
|
|
618
|
+
preflightDescriptorEntry(value[childId], `${ownerLabel}.${childId}`, childId);
|
|
619
|
+
});
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
throw new Error(`[PropsManager] Ordinary property creation has an invalid relationship descriptor for "${ownerLabel}"`);
|
|
623
|
+
};
|
|
624
|
+
sourceOwners.forEach((sourceOwner, ownerIndex) => {
|
|
625
|
+
if (!isRecord(sourceOwner) ||
|
|
626
|
+
!Array.isArray(sourceOwner.definitions) ||
|
|
627
|
+
!isRecord(sourceOwner.data) ||
|
|
628
|
+
(sourceOwner.propertyIds !== undefined &&
|
|
629
|
+
!isRecord(sourceOwner.propertyIds))) {
|
|
630
|
+
throw new Error(`[PropsManager] Ordinary property creation has an invalid owner at index ${ownerIndex}`);
|
|
631
|
+
}
|
|
632
|
+
const ownerData = sourceOwner.data;
|
|
633
|
+
const ownerPropertyIds = sourceOwner.propertyIds;
|
|
634
|
+
const observedNames = new Set();
|
|
635
|
+
sourceOwner.definitions.forEach((sourceDefinition) => {
|
|
636
|
+
if (!isRecord(sourceDefinition) ||
|
|
637
|
+
typeof sourceDefinition.name !== 'string' ||
|
|
638
|
+
sourceDefinition.name.length === 0 ||
|
|
639
|
+
typeof sourceDefinition.type !== 'string' ||
|
|
640
|
+
sourceDefinition.type.length === 0 ||
|
|
641
|
+
observedNames.has(sourceDefinition.name)) {
|
|
642
|
+
throw new Error(`[PropsManager] Ordinary property creation has an invalid definition for owner ${ownerIndex}`);
|
|
643
|
+
}
|
|
644
|
+
observedNames.add(sourceDefinition.name);
|
|
645
|
+
captureRelationshipContracts(sourceDefinition.type);
|
|
646
|
+
const contract = registrationContractByType.get(sourceDefinition.type);
|
|
647
|
+
const definitionSchema = isRecord(sourceDefinition.schema) &&
|
|
648
|
+
typeof sourceDefinition.schema.type === 'string' &&
|
|
649
|
+
Array.isArray(sourceDefinition.schema.fields)
|
|
650
|
+
? snapshotPropertySchema(sourceDefinition.schema)
|
|
651
|
+
: contract.schema;
|
|
652
|
+
const relationKey = contract.childRelation?.key === sourceDefinition.name
|
|
653
|
+
? contract.childRelation.key
|
|
654
|
+
: undefined;
|
|
655
|
+
const excludedRelationKeys = relationKey
|
|
656
|
+
? new Set([relationKey])
|
|
657
|
+
: undefined;
|
|
658
|
+
assertRuntimePropertyFields(ownerData, definitionSchema, sourceDefinition.name, excludedRelationKeys);
|
|
659
|
+
let defaultCreationValue;
|
|
660
|
+
if (sourceDefinition.defaultValue !== undefined) {
|
|
661
|
+
defaultCreationValue = deepFreezePropertyContract(clonePropsValue(sourceDefinition.defaultValue));
|
|
662
|
+
const defaultData = {
|
|
663
|
+
[sourceDefinition.name]: defaultCreationValue
|
|
664
|
+
};
|
|
665
|
+
assertRuntimePropertyFields(defaultData, contract.schema, sourceDefinition.name, excludedRelationKeys);
|
|
666
|
+
if (relationKey) {
|
|
667
|
+
relationshipDescriptors.push({
|
|
668
|
+
value: defaultCreationValue,
|
|
669
|
+
contract,
|
|
670
|
+
ownerLabel: `${sourceDefinition.name}.default`
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
const requestedId = ownerPropertyIds?.[sourceDefinition.name];
|
|
675
|
+
const activeComponent = typeof requestedId === 'string'
|
|
676
|
+
? this._components.get(requestedId)
|
|
677
|
+
: undefined;
|
|
678
|
+
const activeMutationKeys = new Set([
|
|
679
|
+
sourceDefinition.name,
|
|
680
|
+
...(Array.isArray(sourceDefinition.alias)
|
|
681
|
+
? sourceDefinition.alias.filter((alias) => typeof alias === 'string')
|
|
682
|
+
: []),
|
|
683
|
+
...(definitionSchema?.fields.map(({ key }) => key) ?? [])
|
|
684
|
+
]);
|
|
685
|
+
const creationData = {};
|
|
686
|
+
if (sourceDefinition.defaultValue !== undefined) {
|
|
687
|
+
creationData[sourceDefinition.name] = defaultCreationValue;
|
|
688
|
+
}
|
|
689
|
+
activeMutationKeys.forEach((key) => {
|
|
690
|
+
if (Object.prototype.hasOwnProperty.call(ownerData, key)) {
|
|
691
|
+
creationData[key] = ownerData[key];
|
|
692
|
+
}
|
|
693
|
+
});
|
|
694
|
+
const frozenCreationData = Object.freeze(creationData);
|
|
695
|
+
if (relationKey &&
|
|
696
|
+
Object.prototype.hasOwnProperty.call(ownerData, relationKey)) {
|
|
697
|
+
relationshipDescriptors.push({
|
|
698
|
+
value: frozenCreationData[relationKey],
|
|
699
|
+
contract,
|
|
700
|
+
ownerLabel: sourceDefinition.name
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
if (requestedId !== undefined &&
|
|
704
|
+
(typeof requestedId !== 'string' ||
|
|
705
|
+
requestedId.length === 0 ||
|
|
706
|
+
this._deletedMap.has(requestedId) ||
|
|
707
|
+
(activeComponent !== undefined &&
|
|
708
|
+
activeComponent.get('type') !== sourceDefinition.type) ||
|
|
709
|
+
(activeComponent === undefined &&
|
|
710
|
+
reservedNewComponentIds.has(requestedId)))) {
|
|
711
|
+
throw new Error(`[PropsManager] Ordinary property creation has an unavailable property id for "${sourceDefinition.name}"`);
|
|
712
|
+
}
|
|
713
|
+
if (activeComponent &&
|
|
714
|
+
[...activeMutationKeys].some((key) => Object.prototype.hasOwnProperty.call(ownerData, key))) {
|
|
715
|
+
throw new Error(`[PropsManager] Ordinary property creation cannot apply an active owner override for "${sourceDefinition.name}"`);
|
|
716
|
+
}
|
|
717
|
+
if (requestedId && !activeComponent) {
|
|
718
|
+
reservedNewComponentIds.add(requestedId);
|
|
719
|
+
preparedRootTypesById.set(requestedId, sourceDefinition.type);
|
|
720
|
+
}
|
|
721
|
+
roots.push(Object.freeze({
|
|
722
|
+
name: sourceDefinition.name,
|
|
723
|
+
type: sourceDefinition.type,
|
|
724
|
+
requestedId: typeof requestedId === 'string' ? requestedId : undefined,
|
|
725
|
+
activeComponent,
|
|
726
|
+
creationData: frozenCreationData
|
|
727
|
+
}));
|
|
728
|
+
});
|
|
729
|
+
});
|
|
730
|
+
relationshipDescriptors.forEach(({ value, contract, ownerLabel }) => {
|
|
731
|
+
preflightRelationshipDescriptor(value, contract, ownerLabel);
|
|
732
|
+
});
|
|
733
|
+
const prepared = Object.freeze({
|
|
734
|
+
kind: 'prepared-ordinary-property-creation-batch',
|
|
735
|
+
ownerCount: sourceOwners.length,
|
|
736
|
+
rootPropertyCount: roots.length
|
|
737
|
+
});
|
|
738
|
+
this.validatedOrdinaryPropertyCreationArtifacts.set(prepared, {
|
|
739
|
+
roots: Object.freeze(roots),
|
|
740
|
+
registrationContracts: Object.freeze([
|
|
741
|
+
...registrationContractByType.values()
|
|
742
|
+
])
|
|
743
|
+
});
|
|
744
|
+
return prepared;
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
preflightPropertyCreationBatch(sourceComponents, sourceRootComponentIds) {
|
|
748
|
+
return measurePropertyBatchPhase('props-manager:creation-preflight', () => this.preflightPropertyCreationBatchUnmeasured(sourceComponents, sourceRootComponentIds, 'exact'));
|
|
749
|
+
}
|
|
750
|
+
preflightNormalizedPropertyCreationBatch(sourceComponents, sourceRootComponentIds) {
|
|
751
|
+
return measurePropertyBatchPhase('props-manager:creation-preflight', () => this.preflightPropertyCreationBatchUnmeasured(sourceComponents, sourceRootComponentIds, 'normalize-partial'));
|
|
752
|
+
}
|
|
753
|
+
preflightPropertyCreationBatchUnmeasured(sourceComponents, sourceRootComponentIds, sourceSemantics) {
|
|
754
|
+
if (!Array.isArray(sourceComponents) ||
|
|
755
|
+
sourceComponents.length === 0 ||
|
|
756
|
+
!Array.isArray(sourceRootComponentIds) ||
|
|
757
|
+
sourceRootComponentIds.length === 0) {
|
|
758
|
+
throw new Error('[PropsManager] Canonical property creation requires components and owner roots');
|
|
759
|
+
}
|
|
760
|
+
const components = clonePropsValue(sourceComponents);
|
|
761
|
+
const rootComponentIds = clonePropsValue(sourceRootComponentIds);
|
|
762
|
+
const componentIds = components.map(({ id }) => id);
|
|
763
|
+
if (componentIds.some((componentId) => typeof componentId !== 'string' || componentId.length === 0) ||
|
|
764
|
+
new Set(componentIds).size !== componentIds.length) {
|
|
765
|
+
throw new Error('[PropsManager] Canonical property creation has duplicate or invalid component ids');
|
|
766
|
+
}
|
|
767
|
+
if (rootComponentIds.some((componentId) => typeof componentId !== 'string' || componentId.length === 0)) {
|
|
768
|
+
throw new Error('[PropsManager] Canonical property creation has invalid owner roots');
|
|
769
|
+
}
|
|
770
|
+
const uniqueRootComponentIds = [...new Set(rootComponentIds)];
|
|
771
|
+
const componentById = new Map(components.map((component) => [component.id, component]));
|
|
772
|
+
const sourceIndexById = new Map(componentIds.map((componentId, index) => [componentId, index]));
|
|
773
|
+
const registrationContractByType = new Map();
|
|
774
|
+
components.forEach((component) => {
|
|
775
|
+
const type = isRecord(component) && typeof component.type === 'string'
|
|
776
|
+
? component.type
|
|
777
|
+
: '';
|
|
778
|
+
let registrationContract = registrationContractByType.get(type);
|
|
779
|
+
const constructor = registrationContract?.constructor ?? getPropertyComponent(type);
|
|
780
|
+
if (!isRecord(component) || !type || !constructor) {
|
|
781
|
+
throw new Error(`[PropsManager] Canonical property creation has invalid component "${component.id ?? ''}"`);
|
|
782
|
+
}
|
|
783
|
+
if (!registrationContract) {
|
|
784
|
+
const componentRegistrationRevision = getPropertyComponentRegistrationRevision(type);
|
|
785
|
+
const schemaRegistrationRevision = getPropertySchemaRegistrationRevision(type);
|
|
786
|
+
const childRelation = snapshotPropertyChildRelation(getPropertyComponentCanonicalChildRelation(type));
|
|
787
|
+
const batchRebindableRelation = getPropertyComponentBatchRebindableRelation(constructor);
|
|
788
|
+
if (batchRebindableRelation &&
|
|
789
|
+
!arePropertyChildRelationsEqual(batchRebindableRelation, childRelation)) {
|
|
790
|
+
throw new Error(`[PropsManager] Canonical property creation has incoherent relationship registration for "${type}"`);
|
|
791
|
+
}
|
|
792
|
+
const schema = snapshotPropertySchema(getRegisteredPropertySchema(type));
|
|
793
|
+
if (getPropertyComponentRegistrationRevision(type) !==
|
|
794
|
+
componentRegistrationRevision ||
|
|
795
|
+
getPropertySchemaRegistrationRevision(type) !==
|
|
796
|
+
schemaRegistrationRevision) {
|
|
797
|
+
throw new Error(`[PropsManager] Canonical property creation registration changed for "${type}"`);
|
|
798
|
+
}
|
|
799
|
+
registrationContract = {
|
|
800
|
+
type,
|
|
801
|
+
constructor,
|
|
802
|
+
childRelation,
|
|
803
|
+
schema,
|
|
804
|
+
componentRegistrationRevision,
|
|
805
|
+
schemaRegistrationRevision
|
|
806
|
+
};
|
|
807
|
+
registrationContractByType.set(type, registrationContract);
|
|
808
|
+
}
|
|
809
|
+
assertRuntimePropertyFields(component, registrationContract.schema, component.id);
|
|
810
|
+
if (this._components.has(component.id) ||
|
|
811
|
+
this._deletedMap.has(component.id)) {
|
|
812
|
+
throw new Error(`[PropsManager] Canonical property creation component "${component.id}" is already registered`);
|
|
813
|
+
}
|
|
814
|
+
});
|
|
815
|
+
uniqueRootComponentIds.forEach((componentId) => {
|
|
816
|
+
if (!componentById.has(componentId)) {
|
|
817
|
+
throw new Error(`[PropsManager] Canonical property creation is missing owner root "${componentId}"`);
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
const reachableComponentIds = new Set();
|
|
821
|
+
const visitingComponentIds = new Set();
|
|
822
|
+
const parentFirstDeclarativeComponentIds = new Set();
|
|
823
|
+
const requiresDeferredRebindById = new Map();
|
|
824
|
+
const visit = (componentId) => {
|
|
825
|
+
if (visitingComponentIds.has(componentId)) {
|
|
826
|
+
throw new Error(`[PropsManager] Canonical property creation has a relationship cycle at "${componentId}"`);
|
|
827
|
+
}
|
|
828
|
+
if (requiresDeferredRebindById.has(componentId)) {
|
|
829
|
+
return requiresDeferredRebindById.get(componentId);
|
|
830
|
+
}
|
|
831
|
+
const component = componentById.get(componentId);
|
|
832
|
+
if (!component) {
|
|
833
|
+
return false;
|
|
834
|
+
}
|
|
835
|
+
visitingComponentIds.add(componentId);
|
|
836
|
+
reachableComponentIds.add(componentId);
|
|
837
|
+
const registrationContract = registrationContractByType.get(component.type);
|
|
838
|
+
const childRelation = registrationContract?.childRelation;
|
|
839
|
+
if (!childRelation) {
|
|
840
|
+
visitingComponentIds.delete(componentId);
|
|
841
|
+
requiresDeferredRebindById.set(componentId, false);
|
|
842
|
+
return false;
|
|
843
|
+
}
|
|
844
|
+
const childIds = component[childRelation.key];
|
|
845
|
+
if (childIds === undefined && sourceSemantics === 'normalize-partial') {
|
|
846
|
+
const componentConstructor = registrationContract?.constructor;
|
|
847
|
+
const requiresDeferredRebind = Boolean(componentConstructor &&
|
|
848
|
+
isPropertyComponentBatchRebindable(componentConstructor, childRelation));
|
|
849
|
+
visitingComponentIds.delete(componentId);
|
|
850
|
+
requiresDeferredRebindById.set(componentId, requiresDeferredRebind);
|
|
851
|
+
if (requiresDeferredRebind) {
|
|
852
|
+
parentFirstDeclarativeComponentIds.add(componentId);
|
|
853
|
+
}
|
|
854
|
+
return requiresDeferredRebind;
|
|
855
|
+
}
|
|
856
|
+
if (!Array.isArray(childIds) ||
|
|
857
|
+
childIds.some((childId) => typeof childId !== 'string') ||
|
|
858
|
+
new Set(childIds).size !== childIds.length) {
|
|
859
|
+
throw new Error(`[PropsManager] Canonical property creation has malformed child relation for "${componentId}"`);
|
|
860
|
+
}
|
|
861
|
+
let requiresDeferredRebind = false;
|
|
862
|
+
childIds.forEach((childId) => {
|
|
863
|
+
const sourceChild = componentById.get(childId);
|
|
864
|
+
const childType = sourceChild?.type ?? this.getPropertyById(childId)?.get('type');
|
|
865
|
+
if (!childType) {
|
|
866
|
+
throw new Error(`[PropsManager] Canonical property creation is missing relation child "${childId}"`);
|
|
867
|
+
}
|
|
868
|
+
if (childType !== childRelation.childType) {
|
|
869
|
+
throw new Error(`[PropsManager] Canonical property creation child "${childId}" has the wrong type`);
|
|
870
|
+
}
|
|
871
|
+
if (sourceChild) {
|
|
872
|
+
const childRequiresDeferredRebind = visit(childId);
|
|
873
|
+
if (sourceIndexById.get(childId) >=
|
|
874
|
+
sourceIndexById.get(componentId) ||
|
|
875
|
+
childRequiresDeferredRebind) {
|
|
876
|
+
const componentConstructor = registrationContract?.constructor;
|
|
877
|
+
if (!componentConstructor ||
|
|
878
|
+
!isPropertyComponentBatchRebindable(componentConstructor, childRelation)) {
|
|
879
|
+
throw new Error(`[PropsManager] Canonical property creation requires child-first order for "${childId}"`);
|
|
880
|
+
}
|
|
881
|
+
requiresDeferredRebind = true;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
visitingComponentIds.delete(componentId);
|
|
886
|
+
requiresDeferredRebindById.set(componentId, requiresDeferredRebind);
|
|
887
|
+
if (requiresDeferredRebind) {
|
|
888
|
+
parentFirstDeclarativeComponentIds.add(componentId);
|
|
889
|
+
}
|
|
890
|
+
return requiresDeferredRebind;
|
|
891
|
+
};
|
|
892
|
+
uniqueRootComponentIds.forEach(visit);
|
|
893
|
+
if (reachableComponentIds.size !== components.length) {
|
|
894
|
+
throw new Error('[PropsManager] Canonical property creation contains an unowned property');
|
|
895
|
+
}
|
|
896
|
+
const prepared = Object.freeze({
|
|
897
|
+
kind: 'prepared-property-creation-batch',
|
|
898
|
+
componentIds: Object.freeze([...componentIds]),
|
|
899
|
+
rootComponentIds: Object.freeze([...uniqueRootComponentIds])
|
|
900
|
+
});
|
|
901
|
+
this.validatedPropertyCreationArtifacts.set(prepared, {
|
|
902
|
+
components: Object.freeze(components.map((component) => component)),
|
|
903
|
+
registrationContracts: Object.freeze([
|
|
904
|
+
...registrationContractByType.values()
|
|
905
|
+
]),
|
|
906
|
+
parentFirstDeclarativeComponentIds: Object.freeze([
|
|
907
|
+
...parentFirstDeclarativeComponentIds
|
|
908
|
+
]),
|
|
909
|
+
sourceSemantics
|
|
910
|
+
});
|
|
911
|
+
return prepared;
|
|
912
|
+
}
|
|
913
|
+
applyPropertyCreationBatch(prepared) {
|
|
914
|
+
if (!this.propertyCreationBatch) {
|
|
915
|
+
throw new Error('[PropsManager] Applying a prepared property creation batch requires an active property creation batch');
|
|
916
|
+
}
|
|
917
|
+
const artifact = this.validatedPropertyCreationArtifacts.get(prepared);
|
|
918
|
+
if (!artifact) {
|
|
919
|
+
throw new Error('[PropsManager] Expected an owner-issued one-shot prepared property creation batch');
|
|
920
|
+
}
|
|
921
|
+
this.validatedPropertyCreationArtifacts.delete(prepared);
|
|
922
|
+
const components = this.createAndRegisterPropertyBatch(artifact.components, artifact.registrationContracts, artifact.parentFirstDeclarativeComponentIds, artifact.sourceSemantics);
|
|
923
|
+
if (artifact.sourceSemantics === 'exact') {
|
|
924
|
+
measurePropertyBatchPhase('props-manager:creation-exact', () => {
|
|
925
|
+
components.forEach((component, index) => {
|
|
926
|
+
const sourceComponent = artifact.components[index];
|
|
927
|
+
if (!isEqual(component.save(), sourceComponent)) {
|
|
928
|
+
throw new Error('[PropsManager] Canonical property creation changed exact component data');
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
return Object.freeze(components.map((component) => component.get('id')));
|
|
934
|
+
}
|
|
935
|
+
preflightActivePropertyBatch(sourceComponents, sourceRootComponentIds) {
|
|
936
|
+
return measurePropertyBatchPhase('props-manager:active-preflight', () => this.preflightActivePropertyBatchUnmeasured(sourceComponents, sourceRootComponentIds));
|
|
937
|
+
}
|
|
938
|
+
preflightActivePropertyBatchUnmeasured(sourceComponents, sourceRootComponentIds) {
|
|
939
|
+
if (!Array.isArray(sourceComponents) ||
|
|
940
|
+
sourceComponents.length === 0 ||
|
|
941
|
+
!Array.isArray(sourceRootComponentIds) ||
|
|
942
|
+
sourceRootComponentIds.length === 0) {
|
|
943
|
+
throw new Error('[PropsManager] Active property batch requires components and owner roots');
|
|
944
|
+
}
|
|
945
|
+
const finishClone = beginPropertyBatchPhase('props-manager:active-preflight-clone');
|
|
946
|
+
const components = clonePropsValue(sourceComponents);
|
|
947
|
+
const rootComponentIds = clonePropsValue(sourceRootComponentIds);
|
|
948
|
+
finishClone();
|
|
949
|
+
const finishExact = beginPropertyBatchPhase('props-manager:active-preflight-exact');
|
|
950
|
+
if (components.some((component) => !isRecord(component))) {
|
|
951
|
+
throw new Error('[PropsManager] Active property batch has invalid component data');
|
|
952
|
+
}
|
|
953
|
+
const componentIds = components.map(({ id }) => id);
|
|
954
|
+
if (componentIds.some((componentId) => typeof componentId !== 'string' || componentId.length === 0) ||
|
|
955
|
+
new Set(componentIds).size !== componentIds.length) {
|
|
956
|
+
throw new Error('[PropsManager] Active property batch has duplicate or invalid component ids');
|
|
957
|
+
}
|
|
958
|
+
if (rootComponentIds.some((componentId) => typeof componentId !== 'string' || componentId.length === 0)) {
|
|
959
|
+
throw new Error('[PropsManager] Active property batch has invalid owner roots');
|
|
960
|
+
}
|
|
961
|
+
const uniqueRootComponentIds = [...new Set(rootComponentIds)];
|
|
962
|
+
const componentById = new Map(components.map((component) => [component.id, component]));
|
|
963
|
+
const instances = components.map((component) => {
|
|
964
|
+
if (typeof component.type !== 'string' ||
|
|
965
|
+
component.type.length === 0 ||
|
|
966
|
+
!getPropertyComponent(component.type)) {
|
|
967
|
+
throw new Error(`[PropsManager] Active property batch has invalid component "${component.id ?? ''}"`);
|
|
968
|
+
}
|
|
969
|
+
const active = this.getPropertyById(component.id);
|
|
970
|
+
if (!active ||
|
|
971
|
+
active.get('type') !== component.type ||
|
|
972
|
+
!isEqual(active.save(), component)) {
|
|
973
|
+
throw new Error(`[PropsManager] Active property batch changed exact component data for "${component.id}"`);
|
|
974
|
+
}
|
|
975
|
+
return active;
|
|
976
|
+
});
|
|
977
|
+
uniqueRootComponentIds.forEach((componentId) => {
|
|
978
|
+
if (!componentById.has(componentId)) {
|
|
979
|
+
throw new Error(`[PropsManager] Active property batch is missing owner root "${componentId}"`);
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
finishExact();
|
|
983
|
+
const finishRelations = beginPropertyBatchPhase('props-manager:active-preflight-relations');
|
|
984
|
+
const visitedComponentIds = new Set();
|
|
985
|
+
const visit = (componentId) => {
|
|
986
|
+
if (visitedComponentIds.has(componentId)) {
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
const component = componentById.get(componentId);
|
|
990
|
+
if (!component) {
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
visitedComponentIds.add(componentId);
|
|
994
|
+
const childRelation = getPropertyComponentCanonicalChildRelation(component.type);
|
|
995
|
+
if (!childRelation) {
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
const childIds = component[childRelation.key];
|
|
999
|
+
if (!Array.isArray(childIds) ||
|
|
1000
|
+
childIds.some((childId) => typeof childId !== 'string') ||
|
|
1001
|
+
new Set(childIds).size !== childIds.length) {
|
|
1002
|
+
throw new Error(`[PropsManager] Active property batch has malformed child relation for "${componentId}"`);
|
|
1003
|
+
}
|
|
1004
|
+
childIds.forEach((childId) => {
|
|
1005
|
+
const sourceChild = componentById.get(childId);
|
|
1006
|
+
const activeChild = this.getPropertyById(childId);
|
|
1007
|
+
if (!activeChild) {
|
|
1008
|
+
throw new Error(`[PropsManager] Active property batch is missing relation child "${childId}"`);
|
|
1009
|
+
}
|
|
1010
|
+
if (activeChild.get('type') !== childRelation.childType ||
|
|
1011
|
+
(sourceChild && sourceChild.type !== childRelation.childType)) {
|
|
1012
|
+
throw new Error(`[PropsManager] Active property batch child "${childId}" has the wrong type`);
|
|
1013
|
+
}
|
|
1014
|
+
if (sourceChild) {
|
|
1015
|
+
visit(childId);
|
|
1016
|
+
}
|
|
1017
|
+
});
|
|
1018
|
+
};
|
|
1019
|
+
uniqueRootComponentIds.forEach(visit);
|
|
1020
|
+
componentIds.forEach(visit);
|
|
1021
|
+
finishRelations();
|
|
1022
|
+
const prepared = Object.freeze({
|
|
1023
|
+
kind: 'prepared-active-property-batch',
|
|
1024
|
+
componentIds: Object.freeze([...componentIds]),
|
|
1025
|
+
rootComponentIds: Object.freeze([...uniqueRootComponentIds])
|
|
1026
|
+
});
|
|
1027
|
+
this.validatedActivePropertyArtifacts.set(prepared, {
|
|
1028
|
+
components: Object.freeze(components.map((component) => component)),
|
|
1029
|
+
instances: Object.freeze([...instances])
|
|
1030
|
+
});
|
|
1031
|
+
return prepared;
|
|
1032
|
+
}
|
|
1033
|
+
restoreActivePropertyBatch(batch, rejectedUpdate) {
|
|
1034
|
+
const shouldRestoreBatch = this.activePropertyBatch === batch;
|
|
1035
|
+
if (shouldRestoreBatch) {
|
|
1036
|
+
this.activePropertyBatch = null;
|
|
1037
|
+
}
|
|
1038
|
+
try {
|
|
1039
|
+
if (rejectedUpdate) {
|
|
1040
|
+
const rejectedComponent = this._components.get(rejectedUpdate.id);
|
|
1041
|
+
if (rejectedComponent) {
|
|
1042
|
+
rejectedComponent.load({
|
|
1043
|
+
...rejectedComponent.save(),
|
|
1044
|
+
[rejectedUpdate.key]: clonePropsValue(rejectedUpdate.before)
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
batch.components.forEach((component, index) => {
|
|
1049
|
+
const snapshot = batch.snapshots[index];
|
|
1050
|
+
if (!snapshot) {
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
component.load(clonePropsValue(snapshot));
|
|
1054
|
+
const relationshipChildIds = this.prepareRelationshipIndexEntry(component, snapshot);
|
|
1055
|
+
if (this._components.get(snapshot.id) !== component) {
|
|
1056
|
+
this.registerActiveComponent(component, relationshipChildIds);
|
|
1057
|
+
}
|
|
1058
|
+
else {
|
|
1059
|
+
this.replaceRelationshipOwnerEdges(snapshot.id, relationshipChildIds);
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
1062
|
+
this.changes.splice(batch.changeStart);
|
|
1063
|
+
}
|
|
1064
|
+
finally {
|
|
1065
|
+
if (shouldRestoreBatch) {
|
|
1066
|
+
this.activePropertyBatch = batch;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
assertActivePropertyBatchCanStart() {
|
|
1071
|
+
if (this.propertyCreationBatch || this.activePropertyBatch) {
|
|
1072
|
+
throw new Error('[PropsManager] Active property reuse batch cannot nest inside another property batch');
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
runWithActivePropertyBatch(sourceComponents, sourceRootComponentIds, operation) {
|
|
1076
|
+
this.assertActivePropertyBatchCanStart();
|
|
1077
|
+
const prepared = this.preflightActivePropertyBatch(sourceComponents, sourceRootComponentIds);
|
|
1078
|
+
return this.consumeActivePropertyBatch(prepared, operation, false);
|
|
1079
|
+
}
|
|
1080
|
+
runInActivePropertyBatch(prepared, operation) {
|
|
1081
|
+
return this.consumeActivePropertyBatch(prepared, operation, true);
|
|
1082
|
+
}
|
|
1083
|
+
consumeActivePropertyBatch(prepared, operation, verifyEntryExact) {
|
|
1084
|
+
this.assertActivePropertyBatchCanStart();
|
|
1085
|
+
const artifact = this.validatedActivePropertyArtifacts.get(prepared);
|
|
1086
|
+
if (!artifact) {
|
|
1087
|
+
throw new Error('[PropsManager] Expected an owner-issued one-shot prepared active property batch');
|
|
1088
|
+
}
|
|
1089
|
+
this.validatedActivePropertyArtifacts.delete(prepared);
|
|
1090
|
+
if (verifyEntryExact) {
|
|
1091
|
+
measurePropertyBatchPhase('props-manager:active-enter-exact', () => {
|
|
1092
|
+
artifact.components.forEach((snapshot, index) => {
|
|
1093
|
+
const instance = artifact.instances[index];
|
|
1094
|
+
if (!instance ||
|
|
1095
|
+
this.getPropertyById(snapshot.id) !== instance ||
|
|
1096
|
+
!isEqual(instance.save(), snapshot)) {
|
|
1097
|
+
throw new Error(`[PropsManager] Active property batch changed exact component data for "${snapshot.id}"`);
|
|
1098
|
+
}
|
|
1099
|
+
});
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
const batch = {
|
|
1103
|
+
changeStart: this.changes.length,
|
|
1104
|
+
componentIds: new Set(prepared.componentIds),
|
|
1105
|
+
components: artifact.instances,
|
|
1106
|
+
snapshots: artifact.components
|
|
1107
|
+
};
|
|
1108
|
+
this.activePropertyBatch = batch;
|
|
1109
|
+
try {
|
|
1110
|
+
measurePropertyBatchPhase('props-manager:active-rebind-relations', () => {
|
|
1111
|
+
batch.components.forEach((component, index) => {
|
|
1112
|
+
const snapshot = batch.snapshots[index];
|
|
1113
|
+
if (snapshot &&
|
|
1114
|
+
getPropertyComponentCanonicalChildRelation(snapshot.type)) {
|
|
1115
|
+
component.load(clonePropsValue(snapshot));
|
|
1116
|
+
this.refreshRelationshipOwnerEdges(component, snapshot);
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
});
|
|
1120
|
+
const result = measurePropertyBatchPhase('props-manager:active-operation', () => runWithPropertyComponentAccessor(this.componentAccessor, operation));
|
|
1121
|
+
const changed = measurePropertyBatchPhase('props-manager:active-exit-exact', () => this.changes.length !== batch.changeStart ||
|
|
1122
|
+
batch.components.some((component, index) => this.getPropertyById(prepared.componentIds[index]) !==
|
|
1123
|
+
component || !isEqual(component.save(), batch.snapshots[index])));
|
|
1124
|
+
if (changed) {
|
|
1125
|
+
this.restoreActivePropertyBatch(batch);
|
|
1126
|
+
throw new Error('[PropsManager] Active property reuse batch cannot update active property');
|
|
1127
|
+
}
|
|
1128
|
+
return result;
|
|
1129
|
+
}
|
|
1130
|
+
catch (error) {
|
|
1131
|
+
this.restoreActivePropertyBatch(batch);
|
|
1132
|
+
throw error;
|
|
1133
|
+
}
|
|
1134
|
+
finally {
|
|
1135
|
+
if (this.activePropertyBatch === batch) {
|
|
1136
|
+
this.activePropertyBatch = null;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
preflightRestoreProperties(snapshot, ownerRelations) {
|
|
1141
|
+
if (!isRecord(snapshot) ||
|
|
1142
|
+
!Array.isArray(snapshot.components) ||
|
|
1143
|
+
!Array.isArray(ownerRelations)) {
|
|
1144
|
+
throw new Error('[PropsManager] Invalid property restore: exact snapshot and owner relations are required');
|
|
1145
|
+
}
|
|
1146
|
+
const validatedSnapshot = clonePropsValue(snapshot);
|
|
1147
|
+
const validatedRelations = clonePropsValue(ownerRelations);
|
|
1148
|
+
const components = validatedSnapshot.components;
|
|
1149
|
+
const componentIds = components.map(({ id }) => id);
|
|
1150
|
+
if (componentIds.some((componentId) => typeof componentId !== 'string') ||
|
|
1151
|
+
new Set(componentIds).size !== componentIds.length) {
|
|
1152
|
+
throw new Error('[PropsManager] Invalid property restore: duplicate or invalid component id');
|
|
1153
|
+
}
|
|
1154
|
+
const componentById = new Map(components.map((component) => [component.id, component]));
|
|
1155
|
+
components.forEach((component) => {
|
|
1156
|
+
if (!isRecord(component) ||
|
|
1157
|
+
typeof component.id !== 'string' ||
|
|
1158
|
+
component.id.length === 0 ||
|
|
1159
|
+
typeof component.type !== 'string' ||
|
|
1160
|
+
component.type.length === 0) {
|
|
1161
|
+
throw new Error('[PropsManager] Invalid property restore: malformed component data');
|
|
1162
|
+
}
|
|
1163
|
+
if (!getPropertyComponent(component.type)) {
|
|
1164
|
+
throw new Error(`[PropsManager] Invalid property restore: unregistered property type "${component.type}"`);
|
|
1165
|
+
}
|
|
1166
|
+
if (this.getPropertyById(component.id)) {
|
|
1167
|
+
throw new Error(`[PropsManager] Invalid property restore: active property "${component.id}" already exists`);
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
const relationKeys = new Set();
|
|
1171
|
+
validatedRelations.forEach((relation) => {
|
|
1172
|
+
if (!isRecord(relation) ||
|
|
1173
|
+
typeof relation.ownerElementId !== 'string' ||
|
|
1174
|
+
typeof relation.ownerElementType !== 'string' ||
|
|
1175
|
+
typeof relation.ownerPropertyName !== 'string' ||
|
|
1176
|
+
typeof relation.componentId !== 'string') {
|
|
1177
|
+
throw new Error('[PropsManager] Invalid property restore: malformed owner relation');
|
|
1178
|
+
}
|
|
1179
|
+
const relationKey = `${relation.ownerElementId}:${relation.ownerPropertyName}`;
|
|
1180
|
+
if (relationKeys.has(relationKey)) {
|
|
1181
|
+
throw new Error(`[PropsManager] Invalid property restore: duplicate owner relation "${relationKey}"`);
|
|
1182
|
+
}
|
|
1183
|
+
relationKeys.add(relationKey);
|
|
1184
|
+
const component = componentById.get(relation.componentId);
|
|
1185
|
+
if (!component) {
|
|
1186
|
+
throw new Error(`[PropsManager] Invalid property restore: missing owner data for "${relation.componentId}"`);
|
|
1187
|
+
}
|
|
1188
|
+
const definition = elementPropertyRegistry.getForComponent(relation.ownerElementType, relation.ownerPropertyName);
|
|
1189
|
+
if (!definition || definition.type !== component.type) {
|
|
1190
|
+
throw new Error(`[PropsManager] Invalid property restore: malformed owner relation for "${relation.componentId}"`);
|
|
1191
|
+
}
|
|
1192
|
+
});
|
|
1193
|
+
const reachableSnapshotIds = new Set();
|
|
1194
|
+
const visit = (componentId) => {
|
|
1195
|
+
if (reachableSnapshotIds.has(componentId))
|
|
1196
|
+
return;
|
|
1197
|
+
const component = componentById.get(componentId);
|
|
1198
|
+
if (!component)
|
|
1199
|
+
return;
|
|
1200
|
+
reachableSnapshotIds.add(componentId);
|
|
1201
|
+
const childRelation = getPropertyComponentCanonicalChildRelation(component.type);
|
|
1202
|
+
if (!childRelation)
|
|
1203
|
+
return;
|
|
1204
|
+
const childIds = component[childRelation.key];
|
|
1205
|
+
if (!Array.isArray(childIds) ||
|
|
1206
|
+
childIds.some((childId) => typeof childId !== 'string') ||
|
|
1207
|
+
new Set(childIds).size !== childIds.length) {
|
|
1208
|
+
throw new Error(`[PropsManager] Invalid property restore: malformed child relation for "${componentId}"`);
|
|
1209
|
+
}
|
|
1210
|
+
childIds.forEach((childId) => {
|
|
1211
|
+
const snapshotChild = componentById.get(childId);
|
|
1212
|
+
const activeChild = this.getPropertyById(childId);
|
|
1213
|
+
const childType = snapshotChild?.type ?? activeChild?.get('type');
|
|
1214
|
+
if (!childType) {
|
|
1215
|
+
throw new Error(`[PropsManager] Invalid property restore: missing relation child "${childId}"`);
|
|
1216
|
+
}
|
|
1217
|
+
if (childType !== childRelation.childType) {
|
|
1218
|
+
throw new Error(`[PropsManager] Invalid property restore: malformed child relation type for "${childId}"`);
|
|
1219
|
+
}
|
|
1220
|
+
if (snapshotChild)
|
|
1221
|
+
visit(childId);
|
|
1222
|
+
});
|
|
1223
|
+
};
|
|
1224
|
+
validatedRelations.forEach(({ componentId }) => visit(componentId));
|
|
1225
|
+
if (reachableSnapshotIds.size !== components.length) {
|
|
1226
|
+
throw new Error('[PropsManager] Invalid property restore: missing owner relation for snapshot component data');
|
|
1227
|
+
}
|
|
1228
|
+
const preparedEntries = components.map((component) => {
|
|
1229
|
+
const tombstone = this._deletedMap.get(component.id);
|
|
1230
|
+
let strategy = 'materialize';
|
|
1231
|
+
if (tombstone) {
|
|
1232
|
+
if (tombstone.get('type') !== component.type ||
|
|
1233
|
+
!isEqual(tombstone.save(), component)) {
|
|
1234
|
+
throw new Error(`[PropsManager] Invalid property restore: incompatible tombstone for "${component.id}"`);
|
|
1235
|
+
}
|
|
1236
|
+
strategy = 'reuse';
|
|
1237
|
+
}
|
|
1238
|
+
return Object.freeze({ componentId: component.id, strategy });
|
|
1239
|
+
});
|
|
1240
|
+
const prepared = Object.freeze({
|
|
1241
|
+
kind: 'prepared-props-restore',
|
|
1242
|
+
entries: Object.freeze(preparedEntries),
|
|
1243
|
+
ownerRelations: Object.freeze(validatedRelations.map((relation) => Object.freeze(relation)))
|
|
1244
|
+
});
|
|
1245
|
+
this.validatedRestoreArtifacts.set(prepared, {
|
|
1246
|
+
snapshot: validatedSnapshot
|
|
1247
|
+
});
|
|
1248
|
+
return prepared;
|
|
1249
|
+
}
|
|
1250
|
+
applyRestoreProperties(prepared, options) {
|
|
1251
|
+
const artifact = this.validatedRestoreArtifacts.get(prepared);
|
|
1252
|
+
if (!artifact) {
|
|
1253
|
+
throw new Error('[PropsManager] Expected an owner-issued one-shot prepared property restore');
|
|
1254
|
+
}
|
|
1255
|
+
this.validatedRestoreArtifacts.delete(prepared);
|
|
1256
|
+
const snapshotById = new Map(artifact.snapshot.components.map((component) => [component.id, component]));
|
|
1257
|
+
const materialized = new Map();
|
|
1258
|
+
try {
|
|
1259
|
+
prepared.entries.forEach(({ componentId, strategy }) => {
|
|
1260
|
+
const data = snapshotById.get(componentId);
|
|
1261
|
+
if (!data || this.getPropertyById(componentId)) {
|
|
1262
|
+
throw new Error(`[PropsManager] Cannot apply property restore: stale component "${componentId}"`);
|
|
1263
|
+
}
|
|
1264
|
+
if (strategy === 'reuse') {
|
|
1265
|
+
const tombstone = this.getRestoreComponentById(componentId);
|
|
1266
|
+
if (!tombstone ||
|
|
1267
|
+
tombstone.get('type') !== data.type ||
|
|
1268
|
+
!isEqual(tombstone.save(), data)) {
|
|
1269
|
+
throw new Error(`[PropsManager] Cannot apply property restore: stale tombstone "${componentId}"`);
|
|
1270
|
+
}
|
|
1271
|
+
materialized.set(componentId, tombstone);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
if (strategy !== 'materialize') {
|
|
1275
|
+
throw new Error(`[PropsManager] Cannot apply property restore: invalid strategy for "${componentId}"`);
|
|
1276
|
+
}
|
|
1277
|
+
const component = runWithPropertyComponentAccessor(this.componentAccessor, () => createProperty(data));
|
|
1278
|
+
if (component.get('id') !== componentId ||
|
|
1279
|
+
!isEqual(component.save(), data)) {
|
|
1280
|
+
;
|
|
1281
|
+
component.dispose?.();
|
|
1282
|
+
throw new Error(`[PropsManager] Cannot apply property restore: exact materialization failed for "${componentId}"`);
|
|
1283
|
+
}
|
|
1284
|
+
materialized.set(componentId, component);
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
catch (error) {
|
|
1288
|
+
materialized.forEach((component, componentId) => {
|
|
1289
|
+
if (!this._deletedMap.has(componentId)) {
|
|
1290
|
+
;
|
|
1291
|
+
component.dispose?.();
|
|
1292
|
+
}
|
|
1293
|
+
});
|
|
1294
|
+
throw error;
|
|
1295
|
+
}
|
|
1296
|
+
const appliedIds = [];
|
|
1297
|
+
const changeStart = this.changes.length;
|
|
1298
|
+
try {
|
|
1299
|
+
prepared.entries.forEach(({ componentId }) => {
|
|
1300
|
+
const component = materialized.get(componentId);
|
|
1301
|
+
const data = snapshotById.get(componentId);
|
|
1302
|
+
if (!component || !data) {
|
|
1303
|
+
throw new Error(`[PropsManager] Cannot apply property restore: missing prepared component "${componentId}"`);
|
|
1304
|
+
}
|
|
1305
|
+
this.addToMap(component);
|
|
1306
|
+
appliedIds.push(componentId);
|
|
1307
|
+
runWithPropertyComponentAccessor(this.componentAccessor, () => component.load(data));
|
|
1308
|
+
this.refreshRelationshipOwnerEdges(component, data);
|
|
1309
|
+
if (!isEqual(component.save(), data)) {
|
|
1310
|
+
throw new Error(`[PropsManager] Cannot apply property restore: exact data changed for "${componentId}"`);
|
|
1311
|
+
}
|
|
1312
|
+
this.addChangeForAddProperty(component);
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
catch (error) {
|
|
1316
|
+
this.changes.splice(changeStart);
|
|
1317
|
+
appliedIds.reverse().forEach((componentId) => {
|
|
1318
|
+
const component = this.unregisterActiveComponent(componentId);
|
|
1319
|
+
const strategy = prepared.entries.find((entry) => entry.componentId === componentId)?.strategy;
|
|
1320
|
+
if (component && strategy === 'reuse') {
|
|
1321
|
+
this._deletedMap.set(componentId, component);
|
|
1322
|
+
}
|
|
1323
|
+
else {
|
|
1324
|
+
;
|
|
1325
|
+
component.dispose?.();
|
|
1326
|
+
}
|
|
1327
|
+
});
|
|
1328
|
+
throw error;
|
|
1329
|
+
}
|
|
1330
|
+
if (appliedIds.length > 0) {
|
|
1331
|
+
acknowledgeTransactionReplayApplied();
|
|
1332
|
+
this.commitChanges(options);
|
|
1333
|
+
}
|
|
1334
|
+
return Object.freeze([...appliedIds]);
|
|
1335
|
+
}
|
|
1336
|
+
addChangeForAddProperty(property) {
|
|
1337
|
+
this.addChange({
|
|
1338
|
+
eventName: EventTypes.ADD_PROPERTY,
|
|
1339
|
+
data: [clonePropsValue(property.save())],
|
|
1340
|
+
action: PROPS_ACTIONS.ADD_PROPERTY,
|
|
1341
|
+
undoType: EventTypes.REMOVE_PROPERTY,
|
|
1342
|
+
undoAction: EventTypes.REMOVE_PROPERTY
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
addChangeForAddProperties(properties, detachSnapshots = true) {
|
|
1346
|
+
const snapshots = measurePropertyBatchPhase('props-manager:creation-evidence-save', () => properties.map((property) => property.save()));
|
|
1347
|
+
const data = detachSnapshots
|
|
1348
|
+
? measurePropertyBatchPhase('props-manager:creation-evidence-clone', () => clonePropsValue(snapshots))
|
|
1349
|
+
: snapshots;
|
|
1350
|
+
this.addChange({
|
|
1351
|
+
eventName: EventTypes.ADD_PROPERTY,
|
|
1352
|
+
data,
|
|
1353
|
+
action: PROPS_ACTIONS.ADD_PROPERTY,
|
|
1354
|
+
undoType: EventTypes.REMOVE_PROPERTY,
|
|
1355
|
+
undoAction: EventTypes.REMOVE_PROPERTY
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
addChangeForRemoveProperty(property) {
|
|
1359
|
+
this.addChange({
|
|
1360
|
+
eventName: EventTypes.REMOVE_PROPERTY,
|
|
1361
|
+
data: [clonePropsValue(property.save())],
|
|
1362
|
+
action: PROPS_ACTIONS.REMOVE_PROPERTY,
|
|
1363
|
+
undoType: EventTypes.ADD_PROPERTY,
|
|
1364
|
+
undoAction: EventTypes.ADD_PROPERTY
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
instantiateProperty(propData, constructor) {
|
|
1368
|
+
if (!propData.type) {
|
|
1369
|
+
throw new Error('Type is required!');
|
|
1370
|
+
}
|
|
1371
|
+
const data = {
|
|
1372
|
+
...propData,
|
|
1373
|
+
type: propData.type
|
|
1374
|
+
};
|
|
1375
|
+
return constructor
|
|
1376
|
+
? createPropertyWithConstructor(data, constructor)
|
|
1377
|
+
: createProperty(data);
|
|
1378
|
+
}
|
|
1379
|
+
stagePropertyCreation(newProperty, componentAccessReady = true) {
|
|
1380
|
+
const batch = this.propertyCreationBatch;
|
|
1381
|
+
if (!batch) {
|
|
1382
|
+
throw new Error('[PropsManager] Canonical property creation requires an active property creation batch');
|
|
1383
|
+
}
|
|
1384
|
+
const propertyId = newProperty.get('id');
|
|
1385
|
+
if (typeof propertyId !== 'string' ||
|
|
1386
|
+
propertyId.length === 0 ||
|
|
1387
|
+
batch.componentIds.has(propertyId) ||
|
|
1388
|
+
this._components.has(propertyId) ||
|
|
1389
|
+
this._deletedMap.has(propertyId)) {
|
|
1390
|
+
;
|
|
1391
|
+
newProperty.dispose?.();
|
|
1392
|
+
throw new Error(`[PropsManager] Canonical property creation batch has duplicate property "${propertyId}"`);
|
|
1393
|
+
}
|
|
1394
|
+
batch.componentIds.add(propertyId);
|
|
1395
|
+
batch.components.push(newProperty);
|
|
1396
|
+
if (componentAccessReady) {
|
|
1397
|
+
batch.stagedById.set(propertyId, newProperty);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
assertPropertyCreationRegistrationReadiness(registrationContracts, deferredTypes) {
|
|
1401
|
+
registrationContracts.forEach((registrationContract) => {
|
|
1402
|
+
const currentChildRelation = snapshotPropertyChildRelation(getPropertyComponentCanonicalChildRelation(registrationContract.type));
|
|
1403
|
+
if (getPropertyComponentRegistrationRevision(registrationContract.type) !==
|
|
1404
|
+
registrationContract.componentRegistrationRevision ||
|
|
1405
|
+
getPropertySchemaRegistrationRevision(registrationContract.type) !==
|
|
1406
|
+
registrationContract.schemaRegistrationRevision ||
|
|
1407
|
+
getPropertyComponent(registrationContract.type) !==
|
|
1408
|
+
registrationContract.constructor ||
|
|
1409
|
+
!arePropertyChildRelationsEqual(currentChildRelation, registrationContract.childRelation) ||
|
|
1410
|
+
!isEqual(snapshotPropertySchema(getRegisteredPropertySchema(registrationContract.type)), registrationContract.schema) ||
|
|
1411
|
+
(deferredTypes.has(registrationContract.type) &&
|
|
1412
|
+
(!registrationContract.childRelation ||
|
|
1413
|
+
!isPropertyComponentBatchRebindable(registrationContract.constructor, registrationContract.childRelation)))) {
|
|
1414
|
+
throw new Error(`[PropsManager] Canonical property creation registration changed for "${registrationContract.type}"`);
|
|
1415
|
+
}
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
getNormalizedPropertyRelationshipRebindOrder(components, registrationContracts, deferredComponentIds) {
|
|
1419
|
+
const componentById = new Map(components.map((component) => [component.get('id'), component]));
|
|
1420
|
+
const registrationContractByType = new Map(registrationContracts.map((registrationContract) => [registrationContract.type, registrationContract]));
|
|
1421
|
+
const visiting = new Set();
|
|
1422
|
+
const visited = new Set();
|
|
1423
|
+
const ordered = [];
|
|
1424
|
+
const visit = (componentId) => {
|
|
1425
|
+
if (visited.has(componentId)) {
|
|
1426
|
+
return;
|
|
1427
|
+
}
|
|
1428
|
+
if (visiting.has(componentId)) {
|
|
1429
|
+
throw new Error(`[PropsManager] Canonical property creation has a relationship cycle at "${componentId}"`);
|
|
1430
|
+
}
|
|
1431
|
+
const component = componentById.get(componentId);
|
|
1432
|
+
if (!component) {
|
|
1433
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot rebind property "${componentId}"`);
|
|
1434
|
+
}
|
|
1435
|
+
const type = component.get('type');
|
|
1436
|
+
const childRelation = typeof type === 'string'
|
|
1437
|
+
? registrationContractByType.get(type)?.childRelation
|
|
1438
|
+
: undefined;
|
|
1439
|
+
if (!childRelation) {
|
|
1440
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot rebind property "${componentId}"`);
|
|
1441
|
+
}
|
|
1442
|
+
visiting.add(componentId);
|
|
1443
|
+
const saved = component.save();
|
|
1444
|
+
const savedChildIds = saved[childRelation.key];
|
|
1445
|
+
const childIds = savedChildIds === undefined ? [] : savedChildIds;
|
|
1446
|
+
if (!Array.isArray(childIds) ||
|
|
1447
|
+
childIds.some((childId) => typeof childId !== 'string') ||
|
|
1448
|
+
new Set(childIds).size !== childIds.length) {
|
|
1449
|
+
throw new Error(`[PropsManager] Canonical property creation has malformed child relation for "${componentId}"`);
|
|
1450
|
+
}
|
|
1451
|
+
childIds.forEach((childId) => {
|
|
1452
|
+
const sourceChild = componentById.get(childId);
|
|
1453
|
+
const childType = sourceChild?.get('type') ?? this.getPropertyById(childId)?.get('type');
|
|
1454
|
+
if (!childType) {
|
|
1455
|
+
throw new Error(`[PropsManager] Canonical property creation is missing relation child "${childId}"`);
|
|
1456
|
+
}
|
|
1457
|
+
if (childType !== childRelation.childType) {
|
|
1458
|
+
throw new Error(`[PropsManager] Canonical property creation child "${childId}" has the wrong type`);
|
|
1459
|
+
}
|
|
1460
|
+
if (sourceChild && deferredComponentIds.has(childId)) {
|
|
1461
|
+
visit(childId);
|
|
1462
|
+
}
|
|
1463
|
+
});
|
|
1464
|
+
visiting.delete(componentId);
|
|
1465
|
+
visited.add(componentId);
|
|
1466
|
+
ordered.push(componentId);
|
|
1467
|
+
};
|
|
1468
|
+
deferredComponentIds.forEach(visit);
|
|
1469
|
+
return Object.freeze(ordered);
|
|
1470
|
+
}
|
|
1471
|
+
createAndRegisterPropertyBatch(sourceComponents, registrationContracts, parentFirstDeclarativeComponentIds, sourceSemantics) {
|
|
1472
|
+
const batch = this.propertyCreationBatch;
|
|
1473
|
+
if (!batch) {
|
|
1474
|
+
throw new Error('[PropsManager] Canonical property batch requires an active property creation batch');
|
|
1475
|
+
}
|
|
1476
|
+
if (sourceComponents.length === 0) {
|
|
1477
|
+
throw new Error('[PropsManager] Canonical property batch requires property components');
|
|
1478
|
+
}
|
|
1479
|
+
const parentFirstIds = new Set(parentFirstDeclarativeComponentIds);
|
|
1480
|
+
const registrationContractByType = new Map(registrationContracts.map((registrationContract) => [registrationContract.type, registrationContract]));
|
|
1481
|
+
const resolveBatchPropertySchema = (type) => {
|
|
1482
|
+
const registrationContract = registrationContractByType.get(type);
|
|
1483
|
+
return registrationContract
|
|
1484
|
+
? registrationContract.schema
|
|
1485
|
+
: getRegisteredPropertySchema(type);
|
|
1486
|
+
};
|
|
1487
|
+
const deferredTypes = new Set(sourceComponents.flatMap((sourceComponent) => typeof sourceComponent.id === 'string' &&
|
|
1488
|
+
parentFirstIds.has(sourceComponent.id) &&
|
|
1489
|
+
typeof sourceComponent.type === 'string'
|
|
1490
|
+
? [sourceComponent.type]
|
|
1491
|
+
: []));
|
|
1492
|
+
measurePropertyBatchPhase('props-manager:creation-registry-readiness', () => this.assertPropertyCreationRegistrationReadiness(registrationContracts, deferredTypes));
|
|
1493
|
+
const components = measurePropertyBatchPhase('props-manager:creation-materialize', () => runWithPropertySchemaResolver(resolveBatchPropertySchema, () => sourceComponents.map((sourceComponent) => {
|
|
1494
|
+
const registrationContract = typeof sourceComponent.type === 'string'
|
|
1495
|
+
? registrationContractByType.get(sourceComponent.type)
|
|
1496
|
+
: undefined;
|
|
1497
|
+
if (!registrationContract) {
|
|
1498
|
+
throw new Error(`[PropsManager] Canonical property creation registration changed for "${sourceComponent.id ?? ''}"`);
|
|
1499
|
+
}
|
|
1500
|
+
const component = this.instantiateProperty(sourceComponent, registrationContract.constructor);
|
|
1501
|
+
this.stagePropertyCreation(component, typeof sourceComponent.id !== 'string' ||
|
|
1502
|
+
!parentFirstIds.has(sourceComponent.id));
|
|
1503
|
+
return component;
|
|
1504
|
+
})));
|
|
1505
|
+
measurePropertyBatchPhase('props-manager:creation-post-materialize-readiness', () => this.assertPropertyCreationRegistrationReadiness(registrationContracts, deferredTypes));
|
|
1506
|
+
measurePropertyBatchPhase('props-manager:creation-relationship-rebind', () => runWithPropertySchemaResolver(resolveBatchPropertySchema, () => {
|
|
1507
|
+
const relationshipRebindIds = sourceSemantics === 'normalize-partial'
|
|
1508
|
+
? this.getNormalizedPropertyRelationshipRebindOrder(components, registrationContracts, parentFirstIds)
|
|
1509
|
+
: parentFirstDeclarativeComponentIds;
|
|
1510
|
+
const sourceIndexById = new Map(sourceComponents.map((sourceComponent, index) => [
|
|
1511
|
+
sourceComponent.id,
|
|
1512
|
+
index
|
|
1513
|
+
]));
|
|
1514
|
+
relationshipRebindIds.forEach((componentId) => {
|
|
1515
|
+
const index = sourceIndexById.get(componentId);
|
|
1516
|
+
if (index === undefined) {
|
|
1517
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot rebind property "${componentId}"`);
|
|
1518
|
+
}
|
|
1519
|
+
const sourceComponent = sourceComponents[index];
|
|
1520
|
+
if (!sourceComponent || typeof sourceComponent.id !== 'string') {
|
|
1521
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot rebind property "${componentId}"`);
|
|
1522
|
+
}
|
|
1523
|
+
const component = components[index];
|
|
1524
|
+
if (!component || component.get('id') !== componentId) {
|
|
1525
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot rebind property "${componentId}"`);
|
|
1526
|
+
}
|
|
1527
|
+
component.load(sourceComponent);
|
|
1528
|
+
batch.stagedById.set(componentId, component);
|
|
1529
|
+
});
|
|
1530
|
+
}));
|
|
1531
|
+
measurePropertyBatchPhase('props-manager:creation-pre-register-readiness', () => this.assertPropertyCreationRegistrationReadiness(registrationContracts, deferredTypes));
|
|
1532
|
+
measurePropertyBatchPhase('props-manager:creation-register', () => this.registerMany(components));
|
|
1533
|
+
return Object.freeze([...components]);
|
|
1534
|
+
}
|
|
1535
|
+
registerMany(components, trustedStagedBatch) {
|
|
1536
|
+
const batch = this.propertyCreationBatch;
|
|
1537
|
+
const trustsStagedOwner = trustedStagedBatch !== undefined &&
|
|
1538
|
+
trustedStagedBatch === batch &&
|
|
1539
|
+
components === batch.components;
|
|
1540
|
+
if (trustedStagedBatch !== undefined && !trustsStagedOwner) {
|
|
1541
|
+
throw new Error('[PropsManager] Trusted property registration requires the active staged owner batch');
|
|
1542
|
+
}
|
|
1543
|
+
if (!trustsStagedOwner) {
|
|
1544
|
+
const observedIds = new Set();
|
|
1545
|
+
components.forEach((component) => {
|
|
1546
|
+
const propertyId = component.get('id');
|
|
1547
|
+
if (typeof propertyId !== 'string' ||
|
|
1548
|
+
propertyId.length === 0 ||
|
|
1549
|
+
observedIds.has(propertyId) ||
|
|
1550
|
+
(batch !== null && batch.stagedById.get(propertyId) !== component) ||
|
|
1551
|
+
this._components.has(propertyId) ||
|
|
1552
|
+
this._deletedMap.has(propertyId)) {
|
|
1553
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot register property "${propertyId}"`);
|
|
1554
|
+
}
|
|
1555
|
+
observedIds.add(propertyId);
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
const relationshipEntries = components.map((component) => this.prepareRelationshipIndexEntry(component));
|
|
1559
|
+
components.forEach((component, index) => {
|
|
1560
|
+
this.registerActiveComponent(component, relationshipEntries[index]);
|
|
1561
|
+
});
|
|
1562
|
+
if (components.length > 0) {
|
|
1563
|
+
this.advancePropertyStateRevision();
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
finalizeOrdinaryPropertyCreationBatch(batch) {
|
|
1567
|
+
if (batch.components.length > 0) {
|
|
1568
|
+
this.registerMany(batch.components, batch);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
createPropertyInternal(propData, source) {
|
|
1572
|
+
if (this.activePropertyBatch) {
|
|
1573
|
+
throw new Error('[PropsManager] Active property reuse batch cannot create property');
|
|
1574
|
+
}
|
|
1575
|
+
const batch = this.propertyCreationBatch;
|
|
1576
|
+
let materializationData = propData;
|
|
1577
|
+
if (batch && source === 'owner-root') {
|
|
1578
|
+
const preparedRoot = batch.ordinaryRootCreations[batch.ordinaryRootCreationIndex];
|
|
1579
|
+
if (preparedRoot) {
|
|
1580
|
+
if (propData.type !== preparedRoot.type) {
|
|
1581
|
+
throw new Error(`[PropsManager] Ordinary property creation materialized an unexpected root for "${preparedRoot.name}"`);
|
|
1582
|
+
}
|
|
1583
|
+
batch.ordinaryRootCreationIndex += 1;
|
|
1584
|
+
materializationData = {
|
|
1585
|
+
...propData,
|
|
1586
|
+
...preparedRoot.creationData,
|
|
1587
|
+
type: preparedRoot.type
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
const create = () => this.instantiateProperty(materializationData);
|
|
1592
|
+
const newProperty = this.propertyCreationBatch
|
|
1593
|
+
? create()
|
|
1594
|
+
: runWithPropertyComponentAccessor(this.componentAccessor, create);
|
|
1595
|
+
if (this.propertyCreationBatch) {
|
|
1596
|
+
this.stagePropertyCreation(newProperty);
|
|
1597
|
+
if (typeof materializationData.id === 'string') {
|
|
1598
|
+
this.propertyCreationBatch.explicitCreationIdByComponent.set(newProperty, materializationData.id);
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
else {
|
|
1602
|
+
this.addChangeForAddProperty(newProperty);
|
|
1603
|
+
}
|
|
1604
|
+
return newProperty;
|
|
1605
|
+
}
|
|
1606
|
+
createProperty(propData) {
|
|
1607
|
+
return this.createPropertyInternal(propData, 'owner-root');
|
|
1608
|
+
}
|
|
1609
|
+
rollbackPropertyCreationBatch(batch) {
|
|
1610
|
+
runWithPropertySchemaResolver((type) => batch.activeSchemaByType.has(type)
|
|
1611
|
+
? batch.activeSchemaByType.get(type)
|
|
1612
|
+
: getRegisteredPropertySchema(type), () => {
|
|
1613
|
+
batch.existingUpdates
|
|
1614
|
+
.slice()
|
|
1615
|
+
.reverse()
|
|
1616
|
+
.forEach((change) => {
|
|
1617
|
+
const component = this._components.get(change.id);
|
|
1618
|
+
if (!component) {
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
component.load({
|
|
1622
|
+
...component.save(),
|
|
1623
|
+
[change.key]: clonePropsValue(change.before)
|
|
1624
|
+
});
|
|
1625
|
+
this.refreshRelationshipOwnerEdges(component);
|
|
1626
|
+
component.emitChange({
|
|
1627
|
+
id: change.id,
|
|
1628
|
+
key: change.key,
|
|
1629
|
+
before: clonePropsValue(change.after),
|
|
1630
|
+
after: clonePropsValue(change.before)
|
|
1631
|
+
});
|
|
1632
|
+
});
|
|
1633
|
+
});
|
|
1634
|
+
batch.components
|
|
1635
|
+
.slice()
|
|
1636
|
+
.reverse()
|
|
1637
|
+
.forEach((component) => {
|
|
1638
|
+
const propertyId = component.get('id');
|
|
1639
|
+
if (this._components.get(propertyId) === component) {
|
|
1640
|
+
this.unregisterActiveComponent(propertyId);
|
|
1641
|
+
}
|
|
1642
|
+
;
|
|
1643
|
+
component.dispose?.();
|
|
1644
|
+
});
|
|
1645
|
+
this.changes.splice(batch.changeStart);
|
|
1646
|
+
}
|
|
1647
|
+
runInPropertyCreationBatch(operation, preparedOrdinaryBatch) {
|
|
1648
|
+
if (this.propertyCreationBatch) {
|
|
1649
|
+
if (preparedOrdinaryBatch) {
|
|
1650
|
+
throw new Error('[PropsManager] A prepared ordinary property creation batch cannot enter a nested creation batch');
|
|
1651
|
+
}
|
|
1652
|
+
return Object.freeze({
|
|
1653
|
+
result: operation(),
|
|
1654
|
+
rollback: () => undefined,
|
|
1655
|
+
complete: () => undefined
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
const ordinaryArtifact = preparedOrdinaryBatch
|
|
1659
|
+
? this.validatedOrdinaryPropertyCreationArtifacts.get(preparedOrdinaryBatch)
|
|
1660
|
+
: undefined;
|
|
1661
|
+
if (preparedOrdinaryBatch && !ordinaryArtifact) {
|
|
1662
|
+
throw new Error('[PropsManager] Expected an owner-issued one-shot prepared ordinary property creation batch');
|
|
1663
|
+
}
|
|
1664
|
+
if (preparedOrdinaryBatch) {
|
|
1665
|
+
this.validatedOrdinaryPropertyCreationArtifacts.delete(preparedOrdinaryBatch);
|
|
1666
|
+
}
|
|
1667
|
+
if (ordinaryArtifact) {
|
|
1668
|
+
this.assertPropertyCreationRegistrationReadiness(ordinaryArtifact.registrationContracts, new Set());
|
|
1669
|
+
ordinaryArtifact.roots.forEach(({ requestedId, activeComponent }) => {
|
|
1670
|
+
if (requestedId &&
|
|
1671
|
+
(this._components.get(requestedId) !== activeComponent ||
|
|
1672
|
+
this._deletedMap.has(requestedId))) {
|
|
1673
|
+
throw new Error(`[PropsManager] Ordinary property creation property "${requestedId}" is no longer available`);
|
|
1674
|
+
}
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
const activeSchemaByType = new Map();
|
|
1678
|
+
if (!ordinaryArtifact) {
|
|
1679
|
+
this._components.forEach((component) => {
|
|
1680
|
+
const type = component.get('type');
|
|
1681
|
+
if (typeof type === 'string' && !activeSchemaByType.has(type)) {
|
|
1682
|
+
activeSchemaByType.set(type, snapshotPropertySchema(getRegisteredPropertySchema(type)));
|
|
1683
|
+
}
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
const batch = {
|
|
1687
|
+
changeStart: this.changes.length,
|
|
1688
|
+
components: [],
|
|
1689
|
+
componentIds: new Set(),
|
|
1690
|
+
stagedById: new Map(),
|
|
1691
|
+
rootComponents: [],
|
|
1692
|
+
rootComponentIds: new Set(),
|
|
1693
|
+
explicitCreationIdByComponent: new Map(),
|
|
1694
|
+
existingUpdates: [],
|
|
1695
|
+
activeSchemaByType,
|
|
1696
|
+
ordinaryRootCreations: ordinaryArtifact?.roots.filter(({ activeComponent }) => !activeComponent) ?? Object.freeze([]),
|
|
1697
|
+
ordinaryRootCreationIndex: 0
|
|
1698
|
+
};
|
|
1699
|
+
this.propertyCreationBatch = batch;
|
|
1700
|
+
try {
|
|
1701
|
+
const result = measurePropertyBatchPhase('props-manager:creation-operation', () => runWithPropertyComponentAccessor(this.componentAccessor, operation));
|
|
1702
|
+
measurePropertyBatchPhase('props-manager:creation-finalize', () => {
|
|
1703
|
+
const operationChanges = this.changes.slice(batch.changeStart);
|
|
1704
|
+
if (operationChanges.length !== batch.existingUpdates.length ||
|
|
1705
|
+
operationChanges.some((change, index) => change !== batch.existingUpdates[index])) {
|
|
1706
|
+
throw new Error('[PropsManager] Canonical property creation batch produced incompatible pending changes');
|
|
1707
|
+
}
|
|
1708
|
+
if (ordinaryArtifact) {
|
|
1709
|
+
this.finalizeOrdinaryPropertyCreationBatch(batch);
|
|
1710
|
+
}
|
|
1711
|
+
else {
|
|
1712
|
+
const stagedComponents = batch.components.filter((component) => this._components.get(component.get('id')) !== component);
|
|
1713
|
+
if (stagedComponents.length > 0) {
|
|
1714
|
+
this.registerMany(stagedComponents);
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
batch.components.forEach((component) => {
|
|
1718
|
+
const propertyId = component.get('id');
|
|
1719
|
+
if (this._components.get(propertyId) !== component) {
|
|
1720
|
+
throw new Error(`[PropsManager] Canonical property creation batch did not register property "${propertyId}"`);
|
|
1721
|
+
}
|
|
1722
|
+
});
|
|
1723
|
+
});
|
|
1724
|
+
if (batch.components.length > 0) {
|
|
1725
|
+
measurePropertyBatchPhase('props-manager:creation-evidence', () => {
|
|
1726
|
+
this.addChangeForAddProperties(batch.components, !ordinaryArtifact);
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
let active = true;
|
|
1730
|
+
return Object.freeze({
|
|
1731
|
+
result,
|
|
1732
|
+
rollback: () => {
|
|
1733
|
+
if (!active) {
|
|
1734
|
+
return;
|
|
1735
|
+
}
|
|
1736
|
+
active = false;
|
|
1737
|
+
this.rollbackPropertyCreationBatch(batch);
|
|
1738
|
+
},
|
|
1739
|
+
complete: () => {
|
|
1740
|
+
active = false;
|
|
1741
|
+
}
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
catch (error) {
|
|
1745
|
+
this.propertyCreationBatch = null;
|
|
1746
|
+
this.rollbackPropertyCreationBatch(batch);
|
|
1747
|
+
throw error;
|
|
1748
|
+
}
|
|
1749
|
+
finally {
|
|
1750
|
+
if (this.propertyCreationBatch === batch) {
|
|
1751
|
+
this.propertyCreationBatch = null;
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
addProperty(propComponents) {
|
|
1756
|
+
if (this.propertyCreationBatch) {
|
|
1757
|
+
const components = propComponents.filter((component) => Boolean(component));
|
|
1758
|
+
components.forEach((component) => {
|
|
1759
|
+
const componentId = component.get('id');
|
|
1760
|
+
if (this.propertyCreationBatch?.stagedById.get(componentId) !==
|
|
1761
|
+
component ||
|
|
1762
|
+
this.propertyCreationBatch.rootComponentIds.has(componentId)) {
|
|
1763
|
+
throw new Error(`[PropsManager] Canonical property creation batch cannot register active owner property "${componentId}"`);
|
|
1764
|
+
}
|
|
1765
|
+
});
|
|
1766
|
+
const result = components.reduce((propertyIds, component) => {
|
|
1767
|
+
propertyIds[component.get('type')] = component.get('id');
|
|
1768
|
+
return propertyIds;
|
|
1769
|
+
}, {});
|
|
1770
|
+
components.forEach((component) => {
|
|
1771
|
+
this.propertyCreationBatch?.rootComponents.push(component);
|
|
1772
|
+
this.propertyCreationBatch?.rootComponentIds.add(component.get('id'));
|
|
1773
|
+
});
|
|
1774
|
+
return result;
|
|
1775
|
+
}
|
|
1776
|
+
return propComponents.reduce((acc, com) => {
|
|
1777
|
+
if (!com) {
|
|
1778
|
+
return acc;
|
|
1779
|
+
}
|
|
1780
|
+
this.addToMap(com);
|
|
1781
|
+
acc[com.get('type')] = com.get('id');
|
|
1782
|
+
return acc;
|
|
1783
|
+
}, {});
|
|
1784
|
+
}
|
|
1785
|
+
removeProperty(propComponentIds, _options) {
|
|
1786
|
+
propComponentIds.forEach((propComponentId) => {
|
|
1787
|
+
const component = this.getPropertyById(propComponentId);
|
|
1788
|
+
if (!component) {
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
this.addChangeForRemoveProperty(component);
|
|
1792
|
+
this.removeFromMap(propComponentId);
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
preparePropertyMutationBatch(sourceRequest) {
|
|
1796
|
+
if (!isRecord(sourceRequest) ||
|
|
1797
|
+
!Array.isArray(sourceRequest.operations) ||
|
|
1798
|
+
(sourceRequest.options !== undefined && !isRecord(sourceRequest.options))) {
|
|
1799
|
+
throw new Error('[PropsManager] Property mutation batch requires an operations request');
|
|
1800
|
+
}
|
|
1801
|
+
if (sourceRequest.operations.length > 0 && this.changes.length > 0) {
|
|
1802
|
+
throw new Error('[PropsManager] Property mutation batch cannot start with pending property evidence');
|
|
1803
|
+
}
|
|
1804
|
+
const mutations = [...sourceRequest.operations];
|
|
1805
|
+
const mutationOptions = sourceRequest.options === undefined
|
|
1806
|
+
? undefined
|
|
1807
|
+
: clonePropertyDefinitionValue(sourceRequest.options);
|
|
1808
|
+
if (mutationOptions?.history?.mode === 'replace-latest' &&
|
|
1809
|
+
mutations.some((mutation) => isRecord(mutation) && mutation.kind !== 'values')) {
|
|
1810
|
+
throw new Error('[PropsManager] Replace-latest History accepts only property value mutations');
|
|
1811
|
+
}
|
|
1812
|
+
const activeById = this._components;
|
|
1813
|
+
const originalSnapshots = new Map();
|
|
1814
|
+
const workingSnapshots = new Map();
|
|
1815
|
+
const registrationContractByType = new Map();
|
|
1816
|
+
const ownerDefinitionContractByKey = new Map();
|
|
1817
|
+
const fieldByType = new Map();
|
|
1818
|
+
const configByType = new Map();
|
|
1819
|
+
const persistKeysByType = new Map();
|
|
1820
|
+
const defaultsByType = new Map();
|
|
1821
|
+
const orderedPropertyIds = [];
|
|
1822
|
+
const requestedPropertyIds = new Set();
|
|
1823
|
+
const touchedPropertyIds = [];
|
|
1824
|
+
const touchedPropertyIdSet = new Set();
|
|
1825
|
+
const createdComponents = new Map();
|
|
1826
|
+
const reservedCreationTypesById = new Map();
|
|
1827
|
+
const reactivatedComponents = new Map();
|
|
1828
|
+
const removedCandidateIds = [];
|
|
1829
|
+
const removedCandidateIdSet = new Set();
|
|
1830
|
+
const exactOrphanCandidateIds = new Set();
|
|
1831
|
+
const retainedRootPropertyIdSet = new Set();
|
|
1832
|
+
const retainedRootIdentityReads = [];
|
|
1833
|
+
const retainedRootRelationshipReads = new Map();
|
|
1834
|
+
let hasExactOrphanRemovalMutation = false;
|
|
1835
|
+
const relationshipMutationRootIds = new Set();
|
|
1836
|
+
const updateEvidence = [];
|
|
1837
|
+
const replaceLatestHistoryEvidence = [];
|
|
1838
|
+
const orderedOwnerIds = [];
|
|
1839
|
+
const rootPropertyIdsByOwnerId = new Map();
|
|
1840
|
+
const canonicalOwnerIdSetByPropertyId = new Map();
|
|
1841
|
+
const canonicalPropertyIdsByOwnerId = new Map();
|
|
1842
|
+
const ownerRelations = [];
|
|
1843
|
+
const reserveCreationIdentity = (propertyId, propertyType) => {
|
|
1844
|
+
const reservedType = reservedCreationTypesById.get(propertyId);
|
|
1845
|
+
if (reservedType !== undefined && reservedType !== propertyType) {
|
|
1846
|
+
throw new Error(`[PropsManager] Property mutation reserves conflicting types for "${propertyId}"`);
|
|
1847
|
+
}
|
|
1848
|
+
reservedCreationTypesById.set(propertyId, propertyType);
|
|
1849
|
+
};
|
|
1850
|
+
mutations.forEach((sourceMutation) => {
|
|
1851
|
+
if (!isRecord(sourceMutation)) {
|
|
1852
|
+
return;
|
|
1853
|
+
}
|
|
1854
|
+
if (sourceMutation.kind === 'create-owner-properties' &&
|
|
1855
|
+
Array.isArray(sourceMutation.definitions) &&
|
|
1856
|
+
isRecord(sourceMutation.propertyIds)) {
|
|
1857
|
+
const propertyIds = sourceMutation.propertyIds;
|
|
1858
|
+
sourceMutation.definitions.forEach((definition) => {
|
|
1859
|
+
if (!isRecord(definition) ||
|
|
1860
|
+
typeof definition.name !== 'string' ||
|
|
1861
|
+
typeof definition.type !== 'string') {
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
const propertyId = propertyIds[definition.name];
|
|
1865
|
+
if (typeof propertyId === 'string' && propertyId.length > 0) {
|
|
1866
|
+
reserveCreationIdentity(propertyId, definition.type);
|
|
1867
|
+
}
|
|
1868
|
+
});
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
if (sourceMutation.kind === 'create-exact-property-graph' &&
|
|
1872
|
+
Array.isArray(sourceMutation.components)) {
|
|
1873
|
+
sourceMutation.components.forEach((component) => {
|
|
1874
|
+
if (isRecord(component) &&
|
|
1875
|
+
typeof component.id === 'string' &&
|
|
1876
|
+
component.id.length > 0 &&
|
|
1877
|
+
typeof component.type === 'string' &&
|
|
1878
|
+
component.type.length > 0) {
|
|
1879
|
+
reserveCreationIdentity(component.id, component.type);
|
|
1880
|
+
}
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
});
|
|
1884
|
+
const captureContract = (type) => this.capturePropertyCreationTypeContract(type, registrationContractByType);
|
|
1885
|
+
const captureOwnerDefinition = (ownerElementType, ownerPropertyName, expectedPropertyType) => {
|
|
1886
|
+
const key = `${ownerElementType}:${ownerPropertyName}`;
|
|
1887
|
+
const current = elementPropertyRegistry.getForComponent(ownerElementType, ownerPropertyName);
|
|
1888
|
+
if (!current ||
|
|
1889
|
+
current.name !== ownerPropertyName ||
|
|
1890
|
+
current.type !== expectedPropertyType) {
|
|
1891
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid owner relation for "${key}"`);
|
|
1892
|
+
}
|
|
1893
|
+
const existing = ownerDefinitionContractByKey.get(key);
|
|
1894
|
+
if (existing) {
|
|
1895
|
+
if (!isEqual(existing.definition, current)) {
|
|
1896
|
+
throw new Error(`[PropsManager] Detached property creation owner definition registration changed for "${key}"`);
|
|
1897
|
+
}
|
|
1898
|
+
return existing.definition;
|
|
1899
|
+
}
|
|
1900
|
+
const definition = deepFreezePropertyContract(clonePropertyDefinitionValue(current));
|
|
1901
|
+
ownerDefinitionContractByKey.set(key, Object.freeze({
|
|
1902
|
+
ownerElementType,
|
|
1903
|
+
ownerPropertyName,
|
|
1904
|
+
definition
|
|
1905
|
+
}));
|
|
1906
|
+
return definition;
|
|
1907
|
+
};
|
|
1908
|
+
const captureActiveSnapshot = (propertyId) => {
|
|
1909
|
+
const existing = workingSnapshots.get(propertyId);
|
|
1910
|
+
if (existing) {
|
|
1911
|
+
return existing;
|
|
1912
|
+
}
|
|
1913
|
+
const component = activeById.get(propertyId);
|
|
1914
|
+
if (!component) {
|
|
1915
|
+
return;
|
|
1916
|
+
}
|
|
1917
|
+
const snapshot = deepFreezePropertyContract(clonePropsValue(component.save()));
|
|
1918
|
+
originalSnapshots.set(propertyId, snapshot);
|
|
1919
|
+
const workingSnapshot = clonePropsValue(snapshot);
|
|
1920
|
+
workingSnapshots.set(propertyId, workingSnapshot);
|
|
1921
|
+
return workingSnapshot;
|
|
1922
|
+
};
|
|
1923
|
+
const getFieldByKey = (contract) => {
|
|
1924
|
+
const existing = fieldByType.get(contract.type);
|
|
1925
|
+
if (existing) {
|
|
1926
|
+
return existing;
|
|
1927
|
+
}
|
|
1928
|
+
const fields = new Map(contract.schema?.fields.map((field) => [field.key, field]) ??
|
|
1929
|
+
[]);
|
|
1930
|
+
fieldByType.set(contract.type, fields);
|
|
1931
|
+
return fields;
|
|
1932
|
+
};
|
|
1933
|
+
const getComponentConfig = (type) => {
|
|
1934
|
+
if (!configByType.has(type)) {
|
|
1935
|
+
configByType.set(type, getPropertyComponentConfigDefinition(type));
|
|
1936
|
+
}
|
|
1937
|
+
return configByType.get(type);
|
|
1938
|
+
};
|
|
1939
|
+
const getPersistKeys = (type) => {
|
|
1940
|
+
const existing = persistKeysByType.get(type);
|
|
1941
|
+
if (existing) {
|
|
1942
|
+
return existing;
|
|
1943
|
+
}
|
|
1944
|
+
const config = getComponentConfig(type);
|
|
1945
|
+
const keys = new Set(config ? resolvePropertyComponentConfigRoles(config).persistKeys : []);
|
|
1946
|
+
persistKeysByType.set(type, keys);
|
|
1947
|
+
return keys;
|
|
1948
|
+
};
|
|
1949
|
+
const getDefaultValues = (contract) => {
|
|
1950
|
+
const existing = defaultsByType.get(contract.type);
|
|
1951
|
+
if (existing) {
|
|
1952
|
+
return existing;
|
|
1953
|
+
}
|
|
1954
|
+
const values = {};
|
|
1955
|
+
const config = getComponentConfig(contract.type);
|
|
1956
|
+
const defaults = config?.defaults;
|
|
1957
|
+
getPersistKeys(contract.type).forEach((key) => {
|
|
1958
|
+
if (defaults &&
|
|
1959
|
+
Object.prototype.hasOwnProperty.call(defaults, key) &&
|
|
1960
|
+
defaults[key] !== undefined) {
|
|
1961
|
+
values[key] = clonePropsValue(defaults[key]);
|
|
1962
|
+
}
|
|
1963
|
+
});
|
|
1964
|
+
if (!config) {
|
|
1965
|
+
contract.schema?.fields.forEach((field) => {
|
|
1966
|
+
if (!Object.prototype.hasOwnProperty.call(values, field.key) &&
|
|
1967
|
+
field.defaultValue !== undefined) {
|
|
1968
|
+
values[field.key] = clonePropsValue(field.defaultValue);
|
|
1969
|
+
}
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
const frozen = deepFreezePropertyContract(values);
|
|
1973
|
+
defaultsByType.set(contract.type, frozen);
|
|
1974
|
+
return frozen;
|
|
1975
|
+
};
|
|
1976
|
+
const touchExisting = (propertyId) => {
|
|
1977
|
+
if (!touchedPropertyIdSet.has(propertyId)) {
|
|
1978
|
+
touchedPropertyIdSet.add(propertyId);
|
|
1979
|
+
touchedPropertyIds.push(propertyId);
|
|
1980
|
+
}
|
|
1981
|
+
};
|
|
1982
|
+
const associatePropertyWithOwner = (propertyId, orderedId) => {
|
|
1983
|
+
let ownerIdSet = canonicalOwnerIdSetByPropertyId.get(propertyId);
|
|
1984
|
+
if (!ownerIdSet) {
|
|
1985
|
+
ownerIdSet = new Set();
|
|
1986
|
+
canonicalOwnerIdSetByPropertyId.set(propertyId, ownerIdSet);
|
|
1987
|
+
}
|
|
1988
|
+
if (!ownerIdSet.has(orderedId)) {
|
|
1989
|
+
ownerIdSet.add(orderedId);
|
|
1990
|
+
const propertyIds = canonicalPropertyIdsByOwnerId.get(orderedId) ?? [];
|
|
1991
|
+
propertyIds.push(propertyId);
|
|
1992
|
+
canonicalPropertyIdsByOwnerId.set(orderedId, propertyIds);
|
|
1993
|
+
}
|
|
1994
|
+
};
|
|
1995
|
+
const captureMutationOwner = (propertyId, orderedId = propertyId) => {
|
|
1996
|
+
let rootPropertyIds = rootPropertyIdsByOwnerId.get(orderedId);
|
|
1997
|
+
if (!rootPropertyIds) {
|
|
1998
|
+
orderedOwnerIds.push(orderedId);
|
|
1999
|
+
rootPropertyIds = [];
|
|
2000
|
+
rootPropertyIdsByOwnerId.set(orderedId, rootPropertyIds);
|
|
2001
|
+
}
|
|
2002
|
+
if (!rootPropertyIds.includes(propertyId)) {
|
|
2003
|
+
rootPropertyIds.push(propertyId);
|
|
2004
|
+
}
|
|
2005
|
+
associatePropertyWithOwner(propertyId, orderedId);
|
|
2006
|
+
return orderedId;
|
|
2007
|
+
};
|
|
2008
|
+
const addRemovedCandidate = (propertyId, orderedId) => {
|
|
2009
|
+
associatePropertyWithOwner(propertyId, orderedId);
|
|
2010
|
+
if (!removedCandidateIdSet.has(propertyId)) {
|
|
2011
|
+
removedCandidateIdSet.add(propertyId);
|
|
2012
|
+
removedCandidateIds.push(propertyId);
|
|
2013
|
+
}
|
|
2014
|
+
};
|
|
2015
|
+
const readRelationIds = (snapshot, relation, ownerLabel) => {
|
|
2016
|
+
const value = snapshot[relation.key];
|
|
2017
|
+
if (!Array.isArray(value) ||
|
|
2018
|
+
value.some((childId) => typeof childId !== 'string') ||
|
|
2019
|
+
new Set(value).size !== value.length) {
|
|
2020
|
+
throw new Error(`[PropsManager] Property mutation has an invalid relationship "${ownerLabel}.${relation.key}"`);
|
|
2021
|
+
}
|
|
2022
|
+
return [...value];
|
|
2023
|
+
};
|
|
2024
|
+
const assertField = (snapshot, contract, propertyId, key, value) => {
|
|
2025
|
+
if (key === 'id' || key === 'type') {
|
|
2026
|
+
throw new Error(`[PropsManager] Property mutation cannot replace canonical field "${propertyId}.${key}"`);
|
|
2027
|
+
}
|
|
2028
|
+
const field = getFieldByKey(contract).get(key);
|
|
2029
|
+
if (!Object.prototype.hasOwnProperty.call(snapshot, key) && !field) {
|
|
2030
|
+
throw new Error(`[PropsManager] Property mutation has an unknown field "${propertyId}.${key}"`);
|
|
2031
|
+
}
|
|
2032
|
+
if (field && !isRuntimePropertyFieldValueValid(field, value)) {
|
|
2033
|
+
throw new Error(`[PropsManager] Invalid runtime property field "${propertyId}.${key}" (received ${describeInvalidRuntimePropertyFieldValue(value)})`);
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
const resolveChildSnapshot = (childId) => createdComponents.get(childId) ?? captureActiveSnapshot(childId);
|
|
2037
|
+
const assertRelationIds = (childIds, relation, ownerLabel, identityOnlyChildIds) => {
|
|
2038
|
+
childIds.forEach((childId) => {
|
|
2039
|
+
if (identityOnlyChildIds?.has(childId)) {
|
|
2040
|
+
const child = activeById.get(childId);
|
|
2041
|
+
if (!child || child.get('type') !== relation.childType) {
|
|
2042
|
+
throw new Error(`[PropsManager] Property mutation "${ownerLabel}" has an invalid relationship child "${childId}"`);
|
|
2043
|
+
}
|
|
2044
|
+
return;
|
|
2045
|
+
}
|
|
2046
|
+
const child = resolveChildSnapshot(childId);
|
|
2047
|
+
if (!child || child.type !== relation.childType) {
|
|
2048
|
+
throw new Error(`[PropsManager] Property mutation "${ownerLabel}" has an invalid relationship child "${childId}"`);
|
|
2049
|
+
}
|
|
2050
|
+
});
|
|
2051
|
+
};
|
|
2052
|
+
const addUpdateEvidence = (propertyId, key, before, after) => {
|
|
2053
|
+
if (isEqual(before, after)) {
|
|
2054
|
+
return;
|
|
2055
|
+
}
|
|
2056
|
+
updateEvidence.push({
|
|
2057
|
+
action: PROPS_ACTIONS.UPDATE_PROPERTY,
|
|
2058
|
+
eventName: EventTypes.UPDATE_PROPERTY,
|
|
2059
|
+
id: propertyId,
|
|
2060
|
+
key,
|
|
2061
|
+
before: clonePropsValue(before),
|
|
2062
|
+
after: clonePropsValue(after)
|
|
2063
|
+
});
|
|
2064
|
+
};
|
|
2065
|
+
const creationRelationsByMutationIndex = new Map();
|
|
2066
|
+
const creationOwnerRelationKeys = new Set();
|
|
2067
|
+
const reserveCreationOwnerRelation = (ownerElementId, ownerPropertyName) => {
|
|
2068
|
+
const key = JSON.stringify([ownerElementId, ownerPropertyName]);
|
|
2069
|
+
if (creationOwnerRelationKeys.has(key)) {
|
|
2070
|
+
throw new Error(`[PropsManager] Detached property creation has a duplicate owner relation "${ownerElementId}.${ownerPropertyName}"`);
|
|
2071
|
+
}
|
|
2072
|
+
creationOwnerRelationKeys.add(key);
|
|
2073
|
+
};
|
|
2074
|
+
const captureCreationActive = (propertyId) => {
|
|
2075
|
+
const component = activeById.get(propertyId);
|
|
2076
|
+
if (component) {
|
|
2077
|
+
captureActiveSnapshot(propertyId);
|
|
2078
|
+
}
|
|
2079
|
+
return component;
|
|
2080
|
+
};
|
|
2081
|
+
const prepareCreationRecord = (sourceData, expectedType, ownerLabel, exact) => {
|
|
2082
|
+
const contract = captureContract(expectedType);
|
|
2083
|
+
const data = clonePropertyDefinitionValue(sourceData);
|
|
2084
|
+
if (typeof data.type !== 'string' ||
|
|
2085
|
+
data.type !== expectedType ||
|
|
2086
|
+
(data.id !== undefined &&
|
|
2087
|
+
(typeof data.id !== 'string' || data.id.length === 0))) {
|
|
2088
|
+
throw new Error(`[PropsManager] Detached property creation has invalid canonical data for "${ownerLabel}"`);
|
|
2089
|
+
}
|
|
2090
|
+
const hasExplicitPropertyId = typeof data.id === 'string' && data.id.length > 0;
|
|
2091
|
+
let propertyId = hasExplicitPropertyId
|
|
2092
|
+
? data.id
|
|
2093
|
+
: id(IDTypes.PROPS);
|
|
2094
|
+
while (activeById.has(propertyId) ||
|
|
2095
|
+
this._deletedMap.has(propertyId) ||
|
|
2096
|
+
createdComponents.has(propertyId) ||
|
|
2097
|
+
(!hasExplicitPropertyId && reservedCreationTypesById.has(propertyId))) {
|
|
2098
|
+
if (hasExplicitPropertyId) {
|
|
2099
|
+
throw new Error(`[PropsManager] Detached property creation has duplicate or unavailable property id "${data.id}"`);
|
|
2100
|
+
}
|
|
2101
|
+
propertyId = id(IDTypes.PROPS);
|
|
2102
|
+
}
|
|
2103
|
+
data.id = propertyId;
|
|
2104
|
+
if (activeById.has(propertyId) ||
|
|
2105
|
+
this._deletedMap.has(propertyId) ||
|
|
2106
|
+
createdComponents.has(propertyId)) {
|
|
2107
|
+
throw new Error(`[PropsManager] Detached property creation has duplicate or unavailable property id "${propertyId}"`);
|
|
2108
|
+
}
|
|
2109
|
+
assertRuntimePropertyFields(data, contract.schema, propertyId);
|
|
2110
|
+
let preparedRecord = data;
|
|
2111
|
+
if (!exact) {
|
|
2112
|
+
const config = getComponentConfig(expectedType);
|
|
2113
|
+
const sourceRecord = data;
|
|
2114
|
+
preparedRecord = {
|
|
2115
|
+
...getDefaultValues(contract)
|
|
2116
|
+
};
|
|
2117
|
+
if (config) {
|
|
2118
|
+
getPersistKeys(expectedType).forEach((key) => {
|
|
2119
|
+
if (Object.prototype.hasOwnProperty.call(sourceRecord, key) &&
|
|
2120
|
+
sourceRecord[key] !== undefined) {
|
|
2121
|
+
preparedRecord[key] = sourceRecord[key];
|
|
2122
|
+
}
|
|
2123
|
+
});
|
|
2124
|
+
if (config.allowDynamicKeys === true) {
|
|
2125
|
+
const fixedKeys = new Set([
|
|
2126
|
+
...Object.keys(isRecord(config.defaults) ? config.defaults : {}),
|
|
2127
|
+
...(config.children ? [config.children.key] : [])
|
|
2128
|
+
]);
|
|
2129
|
+
const reservedKeys = new Set([
|
|
2130
|
+
'id',
|
|
2131
|
+
'type',
|
|
2132
|
+
...fixedKeys,
|
|
2133
|
+
...(config.dynamicReservedKeys ?? [])
|
|
2134
|
+
]);
|
|
2135
|
+
Object.entries(sourceRecord).forEach(([key, value]) => {
|
|
2136
|
+
if (!reservedKeys.has(key) && value !== undefined) {
|
|
2137
|
+
preparedRecord[key] = value;
|
|
2138
|
+
}
|
|
2139
|
+
});
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
else {
|
|
2143
|
+
Object.assign(preparedRecord, sourceRecord);
|
|
2144
|
+
}
|
|
2145
|
+
preparedRecord.id = propertyId;
|
|
2146
|
+
preparedRecord.type = expectedType;
|
|
2147
|
+
}
|
|
2148
|
+
const relation = contract.childRelation;
|
|
2149
|
+
if (!exact && relation && preparedRecord[relation.key] === undefined) {
|
|
2150
|
+
preparedRecord[relation.key] = [];
|
|
2151
|
+
}
|
|
2152
|
+
const preparedData = preparedRecord;
|
|
2153
|
+
const prepared = deepFreezePropertyContract(preparedData);
|
|
2154
|
+
createdComponents.set(propertyId, prepared);
|
|
2155
|
+
return prepared;
|
|
2156
|
+
};
|
|
2157
|
+
const normalizeOrdinaryRelation = (value, ownerContract, ownerLabel) => {
|
|
2158
|
+
const relation = ownerContract.childRelation;
|
|
2159
|
+
if (!relation) {
|
|
2160
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid relationship for "${ownerLabel}"`);
|
|
2161
|
+
}
|
|
2162
|
+
let entries;
|
|
2163
|
+
if (Array.isArray(value)) {
|
|
2164
|
+
entries = value.map((item, index) => ({
|
|
2165
|
+
item,
|
|
2166
|
+
keyedId: undefined,
|
|
2167
|
+
label: `${ownerLabel}[${index}]`
|
|
2168
|
+
}));
|
|
2169
|
+
}
|
|
2170
|
+
else if (relation.collection === 'array-or-record' && isRecord(value)) {
|
|
2171
|
+
entries = Object.entries(value).map(([keyedId, item]) => ({
|
|
2172
|
+
item,
|
|
2173
|
+
keyedId,
|
|
2174
|
+
label: `${ownerLabel}.${keyedId}`
|
|
2175
|
+
}));
|
|
2176
|
+
}
|
|
2177
|
+
if (!entries) {
|
|
2178
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid relationship descriptor for "${ownerLabel}"`);
|
|
2179
|
+
}
|
|
2180
|
+
const childIds = entries.map(({ item, keyedId, label }) => {
|
|
2181
|
+
if (typeof item === 'string' && keyedId === undefined) {
|
|
2182
|
+
const child = createdComponents.get(item) ?? captureActiveSnapshot(item);
|
|
2183
|
+
const reservedType = reservedCreationTypesById.get(item);
|
|
2184
|
+
if (!child && reservedType === undefined) {
|
|
2185
|
+
throw new Error(`[PropsManager] Detached property creation is missing relationship child "${item}"`);
|
|
2186
|
+
}
|
|
2187
|
+
if ((child?.type ?? reservedType) !== relation.childType) {
|
|
2188
|
+
throw new Error(`[PropsManager] Detached property creation relationship child "${item}" has the wrong type`);
|
|
2189
|
+
}
|
|
2190
|
+
return item;
|
|
2191
|
+
}
|
|
2192
|
+
if ((relation.mode ?? 'ids') !== 'ids-or-objects' ||
|
|
2193
|
+
!isRecord(item) ||
|
|
2194
|
+
(keyedId !== undefined && keyedId.length === 0)) {
|
|
2195
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid relationship descriptor for "${label}"`);
|
|
2196
|
+
}
|
|
2197
|
+
const itemId = typeof item.id === 'string' && item.id.length > 0
|
|
2198
|
+
? item.id
|
|
2199
|
+
: undefined;
|
|
2200
|
+
if (keyedId && itemId && keyedId !== itemId) {
|
|
2201
|
+
throw new Error(`[PropsManager] Detached property creation relationship child "${keyedId}" has conflicting canonical ids`);
|
|
2202
|
+
}
|
|
2203
|
+
const explicitId = keyedId ?? itemId;
|
|
2204
|
+
const existing = explicitId
|
|
2205
|
+
? (createdComponents.get(explicitId) ??
|
|
2206
|
+
captureActiveSnapshot(explicitId))
|
|
2207
|
+
: undefined;
|
|
2208
|
+
const reservedType = explicitId
|
|
2209
|
+
? reservedCreationTypesById.get(explicitId)
|
|
2210
|
+
: undefined;
|
|
2211
|
+
if (existing || reservedType !== undefined) {
|
|
2212
|
+
if ((existing?.type ?? reservedType) !== relation.childType) {
|
|
2213
|
+
throw new Error(`[PropsManager] Detached property creation relationship child "${explicitId}" has the wrong type`);
|
|
2214
|
+
}
|
|
2215
|
+
if (Object.keys(item).some((key) => key !== 'id' && key !== 'type')) {
|
|
2216
|
+
throw new Error(`[PropsManager] Detached property creation cannot override relationship child "${explicitId}"`);
|
|
2217
|
+
}
|
|
2218
|
+
return explicitId;
|
|
2219
|
+
}
|
|
2220
|
+
let mapped;
|
|
2221
|
+
try {
|
|
2222
|
+
mapped = relation.toChildData
|
|
2223
|
+
? relation.toChildData(clonePropertyDefinitionValue(item), explicitId)
|
|
2224
|
+
: clonePropertyDefinitionValue(item);
|
|
2225
|
+
}
|
|
2226
|
+
catch {
|
|
2227
|
+
mapped = null;
|
|
2228
|
+
}
|
|
2229
|
+
if (!isRecord(mapped)) {
|
|
2230
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid relationship descriptor for "${label}"`);
|
|
2231
|
+
}
|
|
2232
|
+
const mappedId = typeof mapped.id === 'string' && mapped.id.length > 0
|
|
2233
|
+
? mapped.id
|
|
2234
|
+
: undefined;
|
|
2235
|
+
if (explicitId && mappedId && explicitId !== mappedId) {
|
|
2236
|
+
throw new Error(`[PropsManager] Detached property creation relationship child "${explicitId}" changed its canonical id`);
|
|
2237
|
+
}
|
|
2238
|
+
const canonicalId = explicitId ?? mappedId;
|
|
2239
|
+
const childContract = captureContract(relation.childType);
|
|
2240
|
+
const childData = {
|
|
2241
|
+
...mapped,
|
|
2242
|
+
...(canonicalId ? { id: canonicalId } : {}),
|
|
2243
|
+
type: relation.childType
|
|
2244
|
+
};
|
|
2245
|
+
if (!canonicalId && childData.id === '') {
|
|
2246
|
+
delete childData.id;
|
|
2247
|
+
}
|
|
2248
|
+
if (childContract.childRelation &&
|
|
2249
|
+
Object.prototype.hasOwnProperty.call(childData, childContract.childRelation.key)) {
|
|
2250
|
+
childData[childContract.childRelation.key] =
|
|
2251
|
+
normalizeOrdinaryRelation(childData[childContract.childRelation.key], childContract, label);
|
|
2252
|
+
}
|
|
2253
|
+
return prepareCreationRecord(childData, relation.childType, label, false).id;
|
|
2254
|
+
});
|
|
2255
|
+
if (new Set(childIds).size !== childIds.length) {
|
|
2256
|
+
throw new Error(`[PropsManager] Detached property creation has duplicate relationship children for "${ownerLabel}"`);
|
|
2257
|
+
}
|
|
2258
|
+
return childIds;
|
|
2259
|
+
};
|
|
2260
|
+
const prepareOrdinaryCreation = (sourceMutation, mutationIndex) => {
|
|
2261
|
+
if (typeof sourceMutation.ownerElementId !== 'string' ||
|
|
2262
|
+
sourceMutation.ownerElementId.length === 0 ||
|
|
2263
|
+
typeof sourceMutation.ownerElementType !== 'string' ||
|
|
2264
|
+
sourceMutation.ownerElementType.length === 0 ||
|
|
2265
|
+
!Array.isArray(sourceMutation.definitions) ||
|
|
2266
|
+
sourceMutation.definitions.length === 0 ||
|
|
2267
|
+
!isRecord(sourceMutation.data) ||
|
|
2268
|
+
(sourceMutation.propertyIds !== undefined &&
|
|
2269
|
+
!isRecord(sourceMutation.propertyIds))) {
|
|
2270
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid owner at item ${mutationIndex}`);
|
|
2271
|
+
}
|
|
2272
|
+
const definitions = sourceMutation.definitions;
|
|
2273
|
+
const data = sourceMutation.data;
|
|
2274
|
+
const propertyIds = sourceMutation.propertyIds;
|
|
2275
|
+
const names = new Set();
|
|
2276
|
+
const preparedDefinitions = definitions.map((sourceDefinition, definitionIndex) => {
|
|
2277
|
+
if (!isRecord(sourceDefinition) ||
|
|
2278
|
+
typeof sourceDefinition.name !== 'string' ||
|
|
2279
|
+
sourceDefinition.name.length === 0 ||
|
|
2280
|
+
typeof sourceDefinition.type !== 'string' ||
|
|
2281
|
+
sourceDefinition.type.length === 0 ||
|
|
2282
|
+
names.has(sourceDefinition.name)) {
|
|
2283
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid definition at item ${mutationIndex}:${definitionIndex}`);
|
|
2284
|
+
}
|
|
2285
|
+
names.add(sourceDefinition.name);
|
|
2286
|
+
const registered = captureOwnerDefinition(sourceMutation.ownerElementType, sourceDefinition.name, sourceDefinition.type);
|
|
2287
|
+
if (!isEqual(registered, sourceDefinition)) {
|
|
2288
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid owner relation for "${sourceDefinition.name}"`);
|
|
2289
|
+
}
|
|
2290
|
+
reserveCreationOwnerRelation(sourceMutation.ownerElementId, sourceDefinition.name);
|
|
2291
|
+
const contract = captureContract(sourceDefinition.type);
|
|
2292
|
+
const schema = isRecord(sourceDefinition.schema) &&
|
|
2293
|
+
Array.isArray(sourceDefinition.schema.fields)
|
|
2294
|
+
? sourceDefinition.schema
|
|
2295
|
+
: contract.schema;
|
|
2296
|
+
const keys = new Set([
|
|
2297
|
+
sourceDefinition.name,
|
|
2298
|
+
...(Array.isArray(sourceDefinition.alias)
|
|
2299
|
+
? sourceDefinition.alias.filter((alias) => typeof alias === 'string' && alias.length > 0)
|
|
2300
|
+
: []),
|
|
2301
|
+
...(schema?.fields.map(({ key }) => key) ?? [])
|
|
2302
|
+
]);
|
|
2303
|
+
return {
|
|
2304
|
+
definition: sourceDefinition,
|
|
2305
|
+
contract,
|
|
2306
|
+
keys
|
|
2307
|
+
};
|
|
2308
|
+
});
|
|
2309
|
+
if (propertyIds &&
|
|
2310
|
+
Object.keys(propertyIds).some((name) => !names.has(name))) {
|
|
2311
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid requested property id`);
|
|
2312
|
+
}
|
|
2313
|
+
const valuesByName = new Map(preparedDefinitions.map(({ definition }) => [definition.name, {}]));
|
|
2314
|
+
Object.entries(data).forEach(([key, value]) => {
|
|
2315
|
+
const matches = preparedDefinitions.filter(({ keys }) => keys.has(key));
|
|
2316
|
+
if (matches.length > 1) {
|
|
2317
|
+
throw new Error(`[PropsManager] Detached property creation has an ambiguous owner field "${key}"`);
|
|
2318
|
+
}
|
|
2319
|
+
const match = matches[0];
|
|
2320
|
+
if (match) {
|
|
2321
|
+
;
|
|
2322
|
+
valuesByName.get(match.definition.name)[key] = clonePropertyDefinitionValue(value);
|
|
2323
|
+
}
|
|
2324
|
+
});
|
|
2325
|
+
const relations = [];
|
|
2326
|
+
preparedDefinitions.forEach(({ definition, contract }) => {
|
|
2327
|
+
const requestedId = propertyIds?.[definition.name];
|
|
2328
|
+
if (requestedId !== undefined &&
|
|
2329
|
+
(typeof requestedId !== 'string' || requestedId.length === 0)) {
|
|
2330
|
+
throw new Error(`[PropsManager] Detached property creation has an invalid requested property id for "${definition.name}"`);
|
|
2331
|
+
}
|
|
2332
|
+
const mappedValues = valuesByName.get(definition.name) ?? {};
|
|
2333
|
+
const active = requestedId
|
|
2334
|
+
? captureCreationActive(requestedId)
|
|
2335
|
+
: undefined;
|
|
2336
|
+
let propertyId;
|
|
2337
|
+
if (active) {
|
|
2338
|
+
if (active.get('type') !== definition.type ||
|
|
2339
|
+
Object.keys(mappedValues).length > 0) {
|
|
2340
|
+
throw new Error(`[PropsManager] Detached property creation cannot override active property "${requestedId}"`);
|
|
2341
|
+
}
|
|
2342
|
+
propertyId = requestedId;
|
|
2343
|
+
}
|
|
2344
|
+
else {
|
|
2345
|
+
const raw = {
|
|
2346
|
+
...(requestedId ? { id: requestedId } : {}),
|
|
2347
|
+
type: definition.type,
|
|
2348
|
+
...(definition.defaultValue !== undefined
|
|
2349
|
+
? {
|
|
2350
|
+
[definition.name]: clonePropertyDefinitionValue(definition.defaultValue)
|
|
2351
|
+
}
|
|
2352
|
+
: {}),
|
|
2353
|
+
...mappedValues
|
|
2354
|
+
};
|
|
2355
|
+
if (contract.childRelation &&
|
|
2356
|
+
Object.prototype.hasOwnProperty.call(raw, contract.childRelation.key)) {
|
|
2357
|
+
raw[contract.childRelation.key] = normalizeOrdinaryRelation(raw[contract.childRelation.key], contract, requestedId ??
|
|
2358
|
+
`${sourceMutation.ownerElementId}.${definition.name}`);
|
|
2359
|
+
}
|
|
2360
|
+
propertyId = prepareCreationRecord(raw, definition.type, requestedId ??
|
|
2361
|
+
`${sourceMutation.ownerElementId}.${definition.name}`, false).id;
|
|
2362
|
+
}
|
|
2363
|
+
if (!requestedPropertyIds.has(propertyId)) {
|
|
2364
|
+
requestedPropertyIds.add(propertyId);
|
|
2365
|
+
orderedPropertyIds.push(propertyId);
|
|
2366
|
+
}
|
|
2367
|
+
captureMutationOwner(propertyId, sourceMutation.ownerElementId);
|
|
2368
|
+
relations.push({
|
|
2369
|
+
ownerElementId: sourceMutation.ownerElementId,
|
|
2370
|
+
ownerElementType: sourceMutation.ownerElementType,
|
|
2371
|
+
ownerPropertyName: definition.name,
|
|
2372
|
+
componentId: propertyId
|
|
2373
|
+
});
|
|
2374
|
+
});
|
|
2375
|
+
creationRelationsByMutationIndex.set(mutationIndex, Object.freeze(relations));
|
|
2376
|
+
};
|
|
2377
|
+
const prepareExactCreation = (sourceMutation, mutationIndex) => {
|
|
2378
|
+
if (!Array.isArray(sourceMutation.ownerRelations) ||
|
|
2379
|
+
sourceMutation.ownerRelations.length === 0 ||
|
|
2380
|
+
!Array.isArray(sourceMutation.components)) {
|
|
2381
|
+
throw new Error(`[PropsManager] Exact property creation requires owner relations and a components array at item ${mutationIndex}`);
|
|
2382
|
+
}
|
|
2383
|
+
const relations = clonePropertyDefinitionValue(sourceMutation.ownerRelations);
|
|
2384
|
+
const sourceComponents = sourceMutation.components;
|
|
2385
|
+
if (sourceComponents.some((component) => !isRecord(component) ||
|
|
2386
|
+
typeof component.id !== 'string' ||
|
|
2387
|
+
component.id.length === 0 ||
|
|
2388
|
+
typeof component.type !== 'string' ||
|
|
2389
|
+
component.type.length === 0)) {
|
|
2390
|
+
throw new Error('[PropsManager] Exact property creation has duplicate or invalid component ids');
|
|
2391
|
+
}
|
|
2392
|
+
const components = sourceComponents;
|
|
2393
|
+
const componentIds = components.map((component) => component.id);
|
|
2394
|
+
if (new Set(componentIds).size !== componentIds.length) {
|
|
2395
|
+
throw new Error('[PropsManager] Exact property creation has duplicate or invalid component ids');
|
|
2396
|
+
}
|
|
2397
|
+
const componentById = new Map(components.map((component) => [component.id, component]));
|
|
2398
|
+
const resolveOwnerRoot = (propertyId) => {
|
|
2399
|
+
const detached = componentById.get(propertyId) ?? createdComponents.get(propertyId);
|
|
2400
|
+
if (detached) {
|
|
2401
|
+
return detached;
|
|
2402
|
+
}
|
|
2403
|
+
const active = captureCreationActive(propertyId);
|
|
2404
|
+
const activeSnapshot = active
|
|
2405
|
+
? captureActiveSnapshot(propertyId)
|
|
2406
|
+
: undefined;
|
|
2407
|
+
if (!active || !activeSnapshot) {
|
|
2408
|
+
throw new Error(`[PropsManager] Exact property creation is missing active root "${propertyId}"`);
|
|
2409
|
+
}
|
|
2410
|
+
const activeType = activeSnapshot.type;
|
|
2411
|
+
const contract = typeof activeType === 'string'
|
|
2412
|
+
? captureContract(activeType)
|
|
2413
|
+
: undefined;
|
|
2414
|
+
if (activeSnapshot.id !== propertyId ||
|
|
2415
|
+
active.get('id') !== propertyId ||
|
|
2416
|
+
active.get('type') !== activeType ||
|
|
2417
|
+
!contract ||
|
|
2418
|
+
!(active instanceof contract.constructor)) {
|
|
2419
|
+
throw new Error(`[PropsManager] Exact property creation has an invalid active root "${propertyId}"`);
|
|
2420
|
+
}
|
|
2421
|
+
return activeSnapshot;
|
|
2422
|
+
};
|
|
2423
|
+
components.forEach((component) => {
|
|
2424
|
+
if (!isRecord(component) ||
|
|
2425
|
+
typeof component.type !== 'string' ||
|
|
2426
|
+
component.type.length === 0 ||
|
|
2427
|
+
activeById.has(component.id) ||
|
|
2428
|
+
createdComponents.has(component.id)) {
|
|
2429
|
+
throw new Error(`[PropsManager] Exact property creation has duplicate or invalid component ids`);
|
|
2430
|
+
}
|
|
2431
|
+
const contract = captureContract(component.type);
|
|
2432
|
+
const inactive = this._deletedMap.get(component.id);
|
|
2433
|
+
if (!inactive) {
|
|
2434
|
+
return;
|
|
2435
|
+
}
|
|
2436
|
+
const inactiveSnapshot = clonePropsValue(inactive.save());
|
|
2437
|
+
if (inactive.get('type') !== component.type ||
|
|
2438
|
+
!(inactive instanceof contract.constructor) ||
|
|
2439
|
+
!isEqual(inactiveSnapshot, component)) {
|
|
2440
|
+
throw new Error(`[PropsManager] Exact property creation has incompatible inactive data for "${component.id}"`);
|
|
2441
|
+
}
|
|
2442
|
+
reactivatedComponents.set(component.id, Object.freeze({
|
|
2443
|
+
instance: inactive,
|
|
2444
|
+
before: deepFreezePropertyContract(inactiveSnapshot)
|
|
2445
|
+
}));
|
|
2446
|
+
});
|
|
2447
|
+
const ownerTypeById = new Map();
|
|
2448
|
+
relations.forEach((relation) => {
|
|
2449
|
+
if (!isRecord(relation) ||
|
|
2450
|
+
typeof relation.ownerElementId !== 'string' ||
|
|
2451
|
+
relation.ownerElementId.length === 0 ||
|
|
2452
|
+
typeof relation.ownerElementType !== 'string' ||
|
|
2453
|
+
relation.ownerElementType.length === 0 ||
|
|
2454
|
+
typeof relation.ownerPropertyName !== 'string' ||
|
|
2455
|
+
relation.ownerPropertyName.length === 0 ||
|
|
2456
|
+
typeof relation.componentId !== 'string' ||
|
|
2457
|
+
relation.componentId.length === 0) {
|
|
2458
|
+
throw new Error('[PropsManager] Exact property creation has an invalid owner relation');
|
|
2459
|
+
}
|
|
2460
|
+
reserveCreationOwnerRelation(relation.ownerElementId, relation.ownerPropertyName);
|
|
2461
|
+
const knownOwnerType = ownerTypeById.get(relation.ownerElementId);
|
|
2462
|
+
if (knownOwnerType !== undefined &&
|
|
2463
|
+
knownOwnerType !== relation.ownerElementType) {
|
|
2464
|
+
throw new Error(`[PropsManager] Exact property creation has an invalid owner relation for "${relation.ownerElementId}"`);
|
|
2465
|
+
}
|
|
2466
|
+
ownerTypeById.set(relation.ownerElementId, relation.ownerElementType);
|
|
2467
|
+
const root = resolveOwnerRoot(relation.componentId);
|
|
2468
|
+
captureContract(root.type);
|
|
2469
|
+
const registeredDefinition = elementPropertyRegistry.getForComponent(relation.ownerElementType, relation.ownerPropertyName);
|
|
2470
|
+
if (!registeredDefinition) {
|
|
2471
|
+
throw new Error(`[PropsManager] Exact property creation has an invalid owner relation for "${relation.componentId}"`);
|
|
2472
|
+
}
|
|
2473
|
+
const definition = captureOwnerDefinition(relation.ownerElementType, relation.ownerPropertyName, registeredDefinition.type);
|
|
2474
|
+
if (root.type !== definition.type) {
|
|
2475
|
+
throw new Error(`[PropsManager] Exact property creation owner root "${relation.componentId}" has the wrong type`);
|
|
2476
|
+
}
|
|
2477
|
+
});
|
|
2478
|
+
const visiting = new Set();
|
|
2479
|
+
const visited = new Set();
|
|
2480
|
+
const childFirstIds = [];
|
|
2481
|
+
const visit = (propertyId) => {
|
|
2482
|
+
if (visited.has(propertyId)) {
|
|
2483
|
+
return;
|
|
2484
|
+
}
|
|
2485
|
+
if (visiting.has(propertyId)) {
|
|
2486
|
+
throw new Error(`[PropsManager] Exact property creation has a relationship cycle at "${propertyId}"`);
|
|
2487
|
+
}
|
|
2488
|
+
const component = componentById.get(propertyId);
|
|
2489
|
+
if (!component) {
|
|
2490
|
+
return;
|
|
2491
|
+
}
|
|
2492
|
+
visiting.add(propertyId);
|
|
2493
|
+
const contract = captureContract(component.type);
|
|
2494
|
+
const relation = contract.childRelation;
|
|
2495
|
+
if (relation) {
|
|
2496
|
+
const childIds = component[relation.key];
|
|
2497
|
+
if (!Array.isArray(childIds) ||
|
|
2498
|
+
childIds.some((childId) => typeof childId !== 'string') ||
|
|
2499
|
+
new Set(childIds).size !== childIds.length) {
|
|
2500
|
+
throw new Error(`[PropsManager] Exact property creation has a malformed child relation for "${propertyId}"`);
|
|
2501
|
+
}
|
|
2502
|
+
;
|
|
2503
|
+
childIds.forEach((childId) => {
|
|
2504
|
+
const localChild = componentById.get(childId);
|
|
2505
|
+
const activeChild = localChild
|
|
2506
|
+
? undefined
|
|
2507
|
+
: (createdComponents.get(childId) ??
|
|
2508
|
+
captureActiveSnapshot(childId));
|
|
2509
|
+
if (!localChild && !activeChild) {
|
|
2510
|
+
throw new Error(`[PropsManager] Exact property creation is missing relation child "${childId}"`);
|
|
2511
|
+
}
|
|
2512
|
+
if ((localChild?.type ?? activeChild?.type) !== relation.childType) {
|
|
2513
|
+
throw new Error(`[PropsManager] Exact property creation child "${childId}" has the wrong type`);
|
|
2514
|
+
}
|
|
2515
|
+
if (localChild) {
|
|
2516
|
+
visit(childId);
|
|
2517
|
+
}
|
|
2518
|
+
});
|
|
2519
|
+
}
|
|
2520
|
+
visiting.delete(propertyId);
|
|
2521
|
+
visited.add(propertyId);
|
|
2522
|
+
childFirstIds.push(propertyId);
|
|
2523
|
+
};
|
|
2524
|
+
relations.forEach(({ componentId }) => visit(componentId));
|
|
2525
|
+
if (visited.size !== components.length) {
|
|
2526
|
+
throw new Error('[PropsManager] Exact property creation contains an unowned property');
|
|
2527
|
+
}
|
|
2528
|
+
childFirstIds.forEach((propertyId) => {
|
|
2529
|
+
const component = componentById.get(propertyId);
|
|
2530
|
+
if (!component) {
|
|
2531
|
+
throw new Error(`[PropsManager] Exact property creation is missing component "${propertyId}"`);
|
|
2532
|
+
}
|
|
2533
|
+
if (reactivatedComponents.has(propertyId)) {
|
|
2534
|
+
createdComponents.set(propertyId, deepFreezePropertyContract(clonePropertyDefinitionValue(component)));
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
prepareCreationRecord(component, component.type, propertyId, true);
|
|
2538
|
+
});
|
|
2539
|
+
relations.forEach((relation) => {
|
|
2540
|
+
if (!requestedPropertyIds.has(relation.componentId)) {
|
|
2541
|
+
requestedPropertyIds.add(relation.componentId);
|
|
2542
|
+
orderedPropertyIds.push(relation.componentId);
|
|
2543
|
+
}
|
|
2544
|
+
captureMutationOwner(relation.componentId, relation.ownerElementId);
|
|
2545
|
+
});
|
|
2546
|
+
creationRelationsByMutationIndex.set(mutationIndex, Object.freeze(relations));
|
|
2547
|
+
};
|
|
2548
|
+
mutations.forEach((sourceMutation, mutationIndex) => {
|
|
2549
|
+
if (!isRecord(sourceMutation)) {
|
|
2550
|
+
return;
|
|
2551
|
+
}
|
|
2552
|
+
if (sourceMutation.kind === 'create-owner-properties') {
|
|
2553
|
+
prepareOrdinaryCreation(sourceMutation, mutationIndex);
|
|
2554
|
+
}
|
|
2555
|
+
else if (sourceMutation.kind === 'create-exact-property-graph') {
|
|
2556
|
+
prepareExactCreation(sourceMutation, mutationIndex);
|
|
2557
|
+
}
|
|
2558
|
+
});
|
|
2559
|
+
mutations.forEach((sourceMutation, mutationIndex) => {
|
|
2560
|
+
if (!isRecord(sourceMutation)) {
|
|
2561
|
+
throw new Error(`[PropsManager] Property mutation item ${mutationIndex} is invalid`);
|
|
2562
|
+
}
|
|
2563
|
+
const creationRelations = creationRelationsByMutationIndex.get(mutationIndex);
|
|
2564
|
+
if (creationRelations) {
|
|
2565
|
+
ownerRelations.push(...creationRelations);
|
|
2566
|
+
return;
|
|
2567
|
+
}
|
|
2568
|
+
if (sourceMutation.kind === 'remove-exact-orphan-property-graphs') {
|
|
2569
|
+
const orphanRootPropertyIds = sourceMutation.orphanRootPropertyIds;
|
|
2570
|
+
const retainedRootPropertyIds = sourceMutation.retainedRootPropertyIds;
|
|
2571
|
+
if (hasExactOrphanRemovalMutation ||
|
|
2572
|
+
!Array.isArray(orphanRootPropertyIds) ||
|
|
2573
|
+
!Array.isArray(retainedRootPropertyIds) ||
|
|
2574
|
+
orphanRootPropertyIds.length === 0 ||
|
|
2575
|
+
orphanRootPropertyIds.some((propertyId) => typeof propertyId !== 'string' || propertyId.length === 0) ||
|
|
2576
|
+
retainedRootPropertyIds.some((propertyId) => typeof propertyId !== 'string' || propertyId.length === 0) ||
|
|
2577
|
+
new Set(orphanRootPropertyIds).size !==
|
|
2578
|
+
orphanRootPropertyIds.length ||
|
|
2579
|
+
new Set(retainedRootPropertyIds).size !==
|
|
2580
|
+
retainedRootPropertyIds.length) {
|
|
2581
|
+
throw new Error('[PropsManager] Exact orphan property graph removal requires explicit deduplicated root-id sets for orphan and retained roots');
|
|
2582
|
+
}
|
|
2583
|
+
const detachedOrphanRootPropertyIds = [...orphanRootPropertyIds];
|
|
2584
|
+
const detachedRetainedRootPropertyIds = [...retainedRootPropertyIds];
|
|
2585
|
+
const detachedOrphanRootPropertyIdSet = new Set(detachedOrphanRootPropertyIds);
|
|
2586
|
+
if (detachedRetainedRootPropertyIds.some((propertyId) => detachedOrphanRootPropertyIdSet.has(propertyId))) {
|
|
2587
|
+
throw new Error('[PropsManager] Exact orphan and retained root-id sets must be disjoint');
|
|
2588
|
+
}
|
|
2589
|
+
hasExactOrphanRemovalMutation = true;
|
|
2590
|
+
detachedRetainedRootPropertyIds.forEach((propertyId) => {
|
|
2591
|
+
const instance = activeById.get(propertyId);
|
|
2592
|
+
if (!instance) {
|
|
2593
|
+
throw new Error(`[PropsManager] Exact orphan property graph removal is missing active retained root "${propertyId}"`);
|
|
2594
|
+
}
|
|
2595
|
+
const type = instance.get('type');
|
|
2596
|
+
const contract = typeof type === 'string' ? captureContract(type) : undefined;
|
|
2597
|
+
if (!contract || !(instance instanceof contract.constructor)) {
|
|
2598
|
+
throw new Error(`[PropsManager] Exact orphan property graph removal has an invalid active retained root "${propertyId}"`);
|
|
2599
|
+
}
|
|
2600
|
+
retainedRootPropertyIdSet.add(propertyId);
|
|
2601
|
+
retainedRootIdentityReads.push(Object.freeze({
|
|
2602
|
+
propertyId,
|
|
2603
|
+
instance
|
|
2604
|
+
}));
|
|
2605
|
+
});
|
|
2606
|
+
detachedOrphanRootPropertyIds.forEach((propertyId) => {
|
|
2607
|
+
if (requestedPropertyIds.has(propertyId)) {
|
|
2608
|
+
throw new Error(`[PropsManager] Exact orphan property graph removal has a duplicate root "${propertyId}"`);
|
|
2609
|
+
}
|
|
2610
|
+
const component = activeById.get(propertyId);
|
|
2611
|
+
const snapshot = captureActiveSnapshot(propertyId);
|
|
2612
|
+
if (!component || !snapshot) {
|
|
2613
|
+
throw new Error(`[PropsManager] Exact orphan property graph removal is missing active root "${propertyId}"`);
|
|
2614
|
+
}
|
|
2615
|
+
const contract = captureContract(snapshot.type);
|
|
2616
|
+
if (!(component instanceof contract.constructor) ||
|
|
2617
|
+
component.get('type') !== snapshot.type) {
|
|
2618
|
+
throw new Error(`[PropsManager] Exact orphan property graph removal has an invalid active root "${propertyId}"`);
|
|
2619
|
+
}
|
|
2620
|
+
requestedPropertyIds.add(propertyId);
|
|
2621
|
+
orderedPropertyIds.push(propertyId);
|
|
2622
|
+
const orderedId = captureMutationOwner(propertyId);
|
|
2623
|
+
addRemovedCandidate(propertyId, orderedId);
|
|
2624
|
+
exactOrphanCandidateIds.add(propertyId);
|
|
2625
|
+
relationshipMutationRootIds.add(propertyId);
|
|
2626
|
+
});
|
|
2627
|
+
return;
|
|
2628
|
+
}
|
|
2629
|
+
const propertyId = sourceMutation.propertyId;
|
|
2630
|
+
if (typeof propertyId !== 'string' ||
|
|
2631
|
+
propertyId.length === 0 ||
|
|
2632
|
+
requestedPropertyIds.has(propertyId)) {
|
|
2633
|
+
throw new Error(`[PropsManager] Property mutation item ${mutationIndex} has a duplicate or invalid property id`);
|
|
2634
|
+
}
|
|
2635
|
+
const component = activeById.get(propertyId);
|
|
2636
|
+
const snapshot = captureActiveSnapshot(propertyId);
|
|
2637
|
+
if (!component || !snapshot) {
|
|
2638
|
+
throw new Error(`[PropsManager] Property mutation is missing active property "${propertyId}"`);
|
|
2639
|
+
}
|
|
2640
|
+
const contract = captureContract(snapshot.type);
|
|
2641
|
+
if (!(component instanceof contract.constructor) ||
|
|
2642
|
+
component.get('type') !== snapshot.type) {
|
|
2643
|
+
throw new Error(`[PropsManager] Property mutation has an invalid active instance "${propertyId}"`);
|
|
2644
|
+
}
|
|
2645
|
+
if (Object.prototype.hasOwnProperty.call(sourceMutation, 'owner') ||
|
|
2646
|
+
Object.prototype.hasOwnProperty.call(sourceMutation, 'ownerElementId') ||
|
|
2647
|
+
Object.prototype.hasOwnProperty.call(sourceMutation, 'ownerPropertyName')) {
|
|
2648
|
+
throw new Error(`[PropsManager] Property-source mutation "${propertyId}" cannot accept an initiating owner`);
|
|
2649
|
+
}
|
|
2650
|
+
const orderedId = captureMutationOwner(propertyId);
|
|
2651
|
+
requestedPropertyIds.add(propertyId);
|
|
2652
|
+
orderedPropertyIds.push(propertyId);
|
|
2653
|
+
if (sourceMutation.kind === 'values') {
|
|
2654
|
+
if (!isRecord(sourceMutation.values)) {
|
|
2655
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" requires value replacements`);
|
|
2656
|
+
}
|
|
2657
|
+
const nextSnapshot = clonePropsValue(snapshot);
|
|
2658
|
+
Object.entries(sourceMutation.values).forEach(([key, value]) => {
|
|
2659
|
+
assertField(snapshot, contract, propertyId, key, value);
|
|
2660
|
+
if (contract.childRelation?.key === key) {
|
|
2661
|
+
relationshipMutationRootIds.add(propertyId);
|
|
2662
|
+
if (!Array.isArray(value) ||
|
|
2663
|
+
value.some((childId) => typeof childId !== 'string') ||
|
|
2664
|
+
new Set(value).size !== value.length) {
|
|
2665
|
+
throw new Error(`[PropsManager] Property mutation has an invalid relationship "${propertyId}.${key}"`);
|
|
2666
|
+
}
|
|
2667
|
+
const nextChildIds = [...value];
|
|
2668
|
+
const nextChildIdSet = new Set(nextChildIds);
|
|
2669
|
+
assertRelationIds(nextChildIds, contract.childRelation, propertyId);
|
|
2670
|
+
const previousChildIds = readRelationIds(snapshot, contract.childRelation, propertyId);
|
|
2671
|
+
previousChildIds.forEach((childId) => {
|
|
2672
|
+
if (!nextChildIdSet.has(childId)) {
|
|
2673
|
+
addRemovedCandidate(childId, orderedId);
|
|
2674
|
+
}
|
|
2675
|
+
});
|
|
2676
|
+
}
|
|
2677
|
+
const before = nextSnapshot[key];
|
|
2678
|
+
nextSnapshot[key] =
|
|
2679
|
+
clonePropsValue(value);
|
|
2680
|
+
if (mutationOptions?.history?.mode === 'replace-latest') {
|
|
2681
|
+
replaceLatestHistoryEvidence.push({
|
|
2682
|
+
action: PROPS_ACTIONS.UPDATE_PROPERTY,
|
|
2683
|
+
eventName: EventTypes.UPDATE_PROPERTY,
|
|
2684
|
+
id: propertyId,
|
|
2685
|
+
key,
|
|
2686
|
+
before: clonePropsValue(before),
|
|
2687
|
+
after: clonePropsValue(value)
|
|
2688
|
+
});
|
|
2689
|
+
}
|
|
2690
|
+
addUpdateEvidence(propertyId, key, before, value);
|
|
2691
|
+
});
|
|
2692
|
+
assertRuntimePropertyFields(nextSnapshot, contract.schema, propertyId);
|
|
2693
|
+
workingSnapshots.set(propertyId, nextSnapshot);
|
|
2694
|
+
if (!isEqual(snapshot, nextSnapshot)) {
|
|
2695
|
+
touchExisting(propertyId);
|
|
2696
|
+
}
|
|
2697
|
+
return;
|
|
2698
|
+
}
|
|
2699
|
+
if (sourceMutation.kind !== 'records') {
|
|
2700
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" has an invalid kind`);
|
|
2701
|
+
}
|
|
2702
|
+
if (mutationOptions?.history?.mode === 'replace-latest') {
|
|
2703
|
+
throw new Error('[PropsManager] Replace-latest History accepts only property value mutations');
|
|
2704
|
+
}
|
|
2705
|
+
const relation = contract.childRelation;
|
|
2706
|
+
if (!relation ||
|
|
2707
|
+
typeof sourceMutation.key !== 'string' ||
|
|
2708
|
+
sourceMutation.key !== relation.key ||
|
|
2709
|
+
(relation.collection ?? 'array') !== 'array-or-record') {
|
|
2710
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" has an invalid record relationship`);
|
|
2711
|
+
}
|
|
2712
|
+
relationshipMutationRootIds.add(propertyId);
|
|
2713
|
+
const replacementValues = sourceMutation.values === undefined ? {} : sourceMutation.values;
|
|
2714
|
+
if (!isRecord(replacementValues)) {
|
|
2715
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" has invalid value replacements`);
|
|
2716
|
+
}
|
|
2717
|
+
const setRecords = sourceMutation.set === undefined ? {} : sourceMutation.set;
|
|
2718
|
+
const removeIds = sourceMutation.remove === undefined ? [] : sourceMutation.remove;
|
|
2719
|
+
if (!isRecord(setRecords) ||
|
|
2720
|
+
!Array.isArray(removeIds) ||
|
|
2721
|
+
removeIds.some((childId) => typeof childId !== 'string' || childId.length === 0) ||
|
|
2722
|
+
new Set(removeIds).size !== removeIds.length) {
|
|
2723
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" has invalid record operations`);
|
|
2724
|
+
}
|
|
2725
|
+
const setEntries = Object.entries(setRecords);
|
|
2726
|
+
const removeIdSet = new Set(removeIds);
|
|
2727
|
+
if (setEntries.some(([childId, values]) => childId.length === 0 ||
|
|
2728
|
+
!isRecord(values) ||
|
|
2729
|
+
removeIdSet.has(childId))) {
|
|
2730
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" has conflicting record operations`);
|
|
2731
|
+
}
|
|
2732
|
+
const previousChildIds = readRelationIds(snapshot, relation, propertyId);
|
|
2733
|
+
const previousChildIdSet = new Set(previousChildIds);
|
|
2734
|
+
removeIds.forEach((childId) => {
|
|
2735
|
+
if (!previousChildIdSet.has(childId)) {
|
|
2736
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" cannot unlink missing record "${childId}"`);
|
|
2737
|
+
}
|
|
2738
|
+
addRemovedCandidate(childId, orderedId);
|
|
2739
|
+
});
|
|
2740
|
+
const nextChildIds = previousChildIds.filter((childId) => !removeIdSet.has(childId));
|
|
2741
|
+
const nextChildIdSet = new Set(nextChildIds);
|
|
2742
|
+
setEntries.forEach(([childId, sourceValues]) => {
|
|
2743
|
+
const mappedValues = relation.toChildData
|
|
2744
|
+
? relation.toChildData(sourceValues, childId)
|
|
2745
|
+
: sourceValues;
|
|
2746
|
+
if (!isRecord(mappedValues)) {
|
|
2747
|
+
throw new Error(`[PropsManager] Property mutation has invalid record "${childId}"`);
|
|
2748
|
+
}
|
|
2749
|
+
if ((mappedValues.id !== undefined && mappedValues.id !== childId) ||
|
|
2750
|
+
(mappedValues.type !== undefined &&
|
|
2751
|
+
mappedValues.type !== relation.childType)) {
|
|
2752
|
+
throw new Error(`[PropsManager] Property mutation has invalid canonical record "${childId}"`);
|
|
2753
|
+
}
|
|
2754
|
+
const childContract = captureContract(relation.childType);
|
|
2755
|
+
const childValues = Object.entries(mappedValues).reduce((values, [key, value]) => {
|
|
2756
|
+
if (key !== 'id' && key !== 'type') {
|
|
2757
|
+
values[key] = clonePropsValue(value);
|
|
2758
|
+
}
|
|
2759
|
+
return values;
|
|
2760
|
+
}, {});
|
|
2761
|
+
const existingChild = resolveChildSnapshot(childId);
|
|
2762
|
+
associatePropertyWithOwner(childId, orderedId);
|
|
2763
|
+
if (existingChild) {
|
|
2764
|
+
const isCreatedChild = createdComponents.has(childId);
|
|
2765
|
+
if (existingChild.type !== relation.childType) {
|
|
2766
|
+
throw new Error(`[PropsManager] Property mutation record "${childId}" has the wrong type`);
|
|
2767
|
+
}
|
|
2768
|
+
const nextChild = clonePropsValue(existingChild);
|
|
2769
|
+
Object.entries(childValues).forEach(([key, value]) => {
|
|
2770
|
+
assertField(existingChild, childContract, childId, key, value);
|
|
2771
|
+
const before = nextChild[key];
|
|
2772
|
+
nextChild[key] =
|
|
2773
|
+
clonePropsValue(value);
|
|
2774
|
+
if (childContract.childRelation?.key === key) {
|
|
2775
|
+
relationshipMutationRootIds.add(childId);
|
|
2776
|
+
}
|
|
2777
|
+
if (!isCreatedChild) {
|
|
2778
|
+
addUpdateEvidence(childId, key, before, value);
|
|
2779
|
+
}
|
|
2780
|
+
});
|
|
2781
|
+
assertRuntimePropertyFields(nextChild, childContract.schema, childId);
|
|
2782
|
+
if (isCreatedChild) {
|
|
2783
|
+
createdComponents.set(childId, nextChild);
|
|
2784
|
+
}
|
|
2785
|
+
else {
|
|
2786
|
+
workingSnapshots.set(childId, nextChild);
|
|
2787
|
+
if (!isEqual(existingChild, nextChild)) {
|
|
2788
|
+
touchExisting(childId);
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
else {
|
|
2793
|
+
const inactiveChild = this._deletedMap.get(childId);
|
|
2794
|
+
if (createdComponents.has(childId) ||
|
|
2795
|
+
(inactiveChild && getTransactionReplayMode() === null)) {
|
|
2796
|
+
throw new Error(`[PropsManager] Property mutation record "${childId}" conflicts with an existing canonical id`);
|
|
2797
|
+
}
|
|
2798
|
+
const childConfig = getComponentConfig(relation.childType);
|
|
2799
|
+
const configuredPersistKeys = getPersistKeys(relation.childType);
|
|
2800
|
+
if (childConfig &&
|
|
2801
|
+
!childConfig.allowDynamicKeys &&
|
|
2802
|
+
Object.keys(childValues).some((key) => !configuredPersistKeys.has(key))) {
|
|
2803
|
+
throw new Error(`[PropsManager] Property mutation has an unknown field "${childId}"`);
|
|
2804
|
+
}
|
|
2805
|
+
const normalizedChildValues = clonePropsValue(getDefaultValues(childContract));
|
|
2806
|
+
Object.assign(normalizedChildValues, childValues);
|
|
2807
|
+
const created = {
|
|
2808
|
+
id: childId,
|
|
2809
|
+
type: relation.childType,
|
|
2810
|
+
...normalizedChildValues
|
|
2811
|
+
};
|
|
2812
|
+
assertRuntimePropertyFields(created, childContract.schema, childId);
|
|
2813
|
+
if (inactiveChild) {
|
|
2814
|
+
const inactiveSnapshot = clonePropsValue(inactiveChild.save());
|
|
2815
|
+
if (inactiveChild.get('type') !== relation.childType ||
|
|
2816
|
+
!(inactiveChild instanceof childContract.constructor) ||
|
|
2817
|
+
!isEqual(inactiveSnapshot, created)) {
|
|
2818
|
+
throw new Error(`[PropsManager] Property mutation record "${childId}" has incompatible inactive data`);
|
|
2819
|
+
}
|
|
2820
|
+
reactivatedComponents.set(childId, Object.freeze({
|
|
2821
|
+
instance: inactiveChild,
|
|
2822
|
+
before: deepFreezePropertyContract(inactiveSnapshot)
|
|
2823
|
+
}));
|
|
2824
|
+
}
|
|
2825
|
+
createdComponents.set(childId, created);
|
|
2826
|
+
}
|
|
2827
|
+
if (!nextChildIdSet.has(childId)) {
|
|
2828
|
+
nextChildIds.push(childId);
|
|
2829
|
+
nextChildIdSet.add(childId);
|
|
2830
|
+
}
|
|
2831
|
+
});
|
|
2832
|
+
assertRelationIds(nextChildIds, relation, propertyId);
|
|
2833
|
+
const nextParent = clonePropsValue(snapshot);
|
|
2834
|
+
Object.entries(replacementValues).forEach(([key, value]) => {
|
|
2835
|
+
if (key === relation.key) {
|
|
2836
|
+
throw new Error(`[PropsManager] Property mutation "${propertyId}" cannot replace its record relationship`);
|
|
2837
|
+
}
|
|
2838
|
+
assertField(snapshot, contract, propertyId, key, value);
|
|
2839
|
+
const before = nextParent[key];
|
|
2840
|
+
nextParent[key] =
|
|
2841
|
+
clonePropsValue(value);
|
|
2842
|
+
addUpdateEvidence(propertyId, key, before, value);
|
|
2843
|
+
});
|
|
2844
|
+
nextParent[relation.key] =
|
|
2845
|
+
clonePropsValue(nextChildIds);
|
|
2846
|
+
assertRuntimePropertyFields(nextParent, contract.schema, propertyId);
|
|
2847
|
+
addUpdateEvidence(propertyId, relation.key, previousChildIds, nextChildIds);
|
|
2848
|
+
workingSnapshots.set(propertyId, nextParent);
|
|
2849
|
+
if (!isEqual(snapshot, nextParent)) {
|
|
2850
|
+
touchExisting(propertyId);
|
|
2851
|
+
}
|
|
2852
|
+
});
|
|
2853
|
+
const workingChildIdsByOwnerId = new Map();
|
|
2854
|
+
const workingOwnerIdsByChildId = new Map();
|
|
2855
|
+
const untrackedWorkingOwnerIds = new Set();
|
|
2856
|
+
const relationshipChildrenReads = new Map();
|
|
2857
|
+
const relationshipOwnersReads = new Map();
|
|
2858
|
+
const sharedRetentionReads = new Map();
|
|
2859
|
+
const readActiveChildIds = (ownerId) => {
|
|
2860
|
+
const captured = relationshipChildrenReads.get(ownerId);
|
|
2861
|
+
if (captured) {
|
|
2862
|
+
return captured.present ? captured.childIds : undefined;
|
|
2863
|
+
}
|
|
2864
|
+
const current = this.relationshipChildIdsByOwnerId.get(ownerId);
|
|
2865
|
+
relationshipChildrenReads.set(ownerId, Object.freeze({
|
|
2866
|
+
ownerId,
|
|
2867
|
+
present: current !== undefined,
|
|
2868
|
+
childIds: Object.freeze([...(current ?? [])])
|
|
2869
|
+
}));
|
|
2870
|
+
return current;
|
|
2871
|
+
};
|
|
2872
|
+
const readActiveOwnerIds = (childId) => {
|
|
2873
|
+
const captured = relationshipOwnersReads.get(childId);
|
|
2874
|
+
if (captured) {
|
|
2875
|
+
return new Set(captured.ownerIds);
|
|
2876
|
+
}
|
|
2877
|
+
const current = this.relationshipOwnerIdsByChildId.get(childId);
|
|
2878
|
+
const ownerIds = [...(current ?? [])].sort();
|
|
2879
|
+
relationshipOwnersReads.set(childId, Object.freeze({
|
|
2880
|
+
childId,
|
|
2881
|
+
present: current !== undefined,
|
|
2882
|
+
ownerIds: Object.freeze(ownerIds)
|
|
2883
|
+
}));
|
|
2884
|
+
return new Set(ownerIds);
|
|
2885
|
+
};
|
|
2886
|
+
const getWorkingChildIds = (ownerId) => workingChildIdsByOwnerId.get(ownerId) ?? readActiveChildIds(ownerId);
|
|
2887
|
+
const getWorkingOwnerIds = (childId) => {
|
|
2888
|
+
const existing = workingOwnerIdsByChildId.get(childId);
|
|
2889
|
+
if (existing) {
|
|
2890
|
+
if (untrackedWorkingOwnerIds.has(childId)) {
|
|
2891
|
+
readActiveOwnerIds(childId);
|
|
2892
|
+
untrackedWorkingOwnerIds.delete(childId);
|
|
2893
|
+
}
|
|
2894
|
+
return existing;
|
|
2895
|
+
}
|
|
2896
|
+
return readActiveOwnerIds(childId);
|
|
2897
|
+
};
|
|
2898
|
+
const getMutableWorkingOwnerIds = (childId, captureDependency = true) => {
|
|
2899
|
+
const existing = workingOwnerIdsByChildId.get(childId);
|
|
2900
|
+
if (existing) {
|
|
2901
|
+
if (captureDependency && untrackedWorkingOwnerIds.has(childId)) {
|
|
2902
|
+
readActiveOwnerIds(childId);
|
|
2903
|
+
untrackedWorkingOwnerIds.delete(childId);
|
|
2904
|
+
}
|
|
2905
|
+
return existing;
|
|
2906
|
+
}
|
|
2907
|
+
const ownerIds = new Set(captureDependency
|
|
2908
|
+
? readActiveOwnerIds(childId)
|
|
2909
|
+
: (this.relationshipOwnerIdsByChildId.get(childId) ?? []));
|
|
2910
|
+
workingOwnerIdsByChildId.set(childId, ownerIds);
|
|
2911
|
+
if (!captureDependency) {
|
|
2912
|
+
untrackedWorkingOwnerIds.add(childId);
|
|
2913
|
+
}
|
|
2914
|
+
return ownerIds;
|
|
2915
|
+
};
|
|
2916
|
+
const replaceWorkingOwnerEdges = (ownerId, nextChildIds, captureReverseDependencies = true) => {
|
|
2917
|
+
const previousChildIds = getWorkingChildIds(ownerId) ?? [];
|
|
2918
|
+
const previousChildIdSet = new Set(previousChildIds);
|
|
2919
|
+
const nextChildIdSet = new Set(nextChildIds);
|
|
2920
|
+
previousChildIds.forEach((childId) => {
|
|
2921
|
+
if (!nextChildIdSet.has(childId)) {
|
|
2922
|
+
getMutableWorkingOwnerIds(childId, captureReverseDependencies).delete(ownerId);
|
|
2923
|
+
}
|
|
2924
|
+
});
|
|
2925
|
+
nextChildIds.forEach((childId) => {
|
|
2926
|
+
if (!previousChildIdSet.has(childId)) {
|
|
2927
|
+
getMutableWorkingOwnerIds(childId, captureReverseDependencies).add(ownerId);
|
|
2928
|
+
}
|
|
2929
|
+
});
|
|
2930
|
+
workingChildIdsByOwnerId.set(ownerId, Object.freeze([...nextChildIds]));
|
|
2931
|
+
};
|
|
2932
|
+
const indexWorkingOwner = (ownerId, snapshot, requireExactActiveIndex = false) => {
|
|
2933
|
+
const relation = captureContract(snapshot.type).childRelation;
|
|
2934
|
+
if (!relation) {
|
|
2935
|
+
return;
|
|
2936
|
+
}
|
|
2937
|
+
const isActiveOwner = activeById.has(ownerId);
|
|
2938
|
+
const hasPreparedEdges = workingChildIdsByOwnerId.has(ownerId);
|
|
2939
|
+
const requiresActiveIndexMatch = requireExactActiveIndex &&
|
|
2940
|
+
isActiveOwner &&
|
|
2941
|
+
!hasPreparedEdges &&
|
|
2942
|
+
!touchedPropertyIdSet.has(ownerId);
|
|
2943
|
+
const childIds = readRelationIds(snapshot, relation, ownerId);
|
|
2944
|
+
assertRelationIds(childIds, relation, ownerId, requireExactActiveIndex ? retainedRootPropertyIdSet : undefined);
|
|
2945
|
+
if (requiresActiveIndexMatch) {
|
|
2946
|
+
const indexedChildIds = readActiveChildIds(ownerId);
|
|
2947
|
+
if (indexedChildIds === undefined ||
|
|
2948
|
+
!isEqual(indexedChildIds, childIds)) {
|
|
2949
|
+
throw new Error(`[PropsManager] Property mutation has an inconsistent forward relationship index for "${ownerId}"`);
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
if (requiresActiveIndexMatch) {
|
|
2953
|
+
childIds.forEach((childId) => {
|
|
2954
|
+
if (!getWorkingOwnerIds(childId).has(ownerId)) {
|
|
2955
|
+
throw new Error(`[PropsManager] Property mutation has an inconsistent reverse relationship index for "${ownerId}:${childId}"`);
|
|
2956
|
+
}
|
|
2957
|
+
});
|
|
2958
|
+
}
|
|
2959
|
+
replaceWorkingOwnerEdges(ownerId, childIds, isActiveOwner);
|
|
2960
|
+
if (requireExactActiveIndex) {
|
|
2961
|
+
childIds.forEach((childId) => {
|
|
2962
|
+
if (!getWorkingOwnerIds(childId).has(ownerId)) {
|
|
2963
|
+
throw new Error(`[PropsManager] Property mutation cannot establish relationship index for "${ownerId}:${childId}"`);
|
|
2964
|
+
}
|
|
2965
|
+
});
|
|
2966
|
+
}
|
|
2967
|
+
};
|
|
2968
|
+
if (relationshipMutationRootIds.size > 0 || createdComponents.size > 0) {
|
|
2969
|
+
new Set([
|
|
2970
|
+
...relationshipMutationRootIds,
|
|
2971
|
+
...createdComponents.keys()
|
|
2972
|
+
]).forEach((propertyId) => {
|
|
2973
|
+
const snapshot = createdComponents.get(propertyId) ??
|
|
2974
|
+
workingSnapshots.get(propertyId) ??
|
|
2975
|
+
captureActiveSnapshot(propertyId);
|
|
2976
|
+
if (!snapshot) {
|
|
2977
|
+
throw new Error(`[PropsManager] Property mutation cannot snapshot relationship owner "${propertyId}"`);
|
|
2978
|
+
}
|
|
2979
|
+
indexWorkingOwner(propertyId, snapshot, exactOrphanCandidateIds.has(propertyId));
|
|
2980
|
+
});
|
|
2981
|
+
const visiting = new Set();
|
|
2982
|
+
const ordinarilyVisited = new Set();
|
|
2983
|
+
const exactlyVisited = new Set();
|
|
2984
|
+
const visitRelationshipGraph = (propertyId) => {
|
|
2985
|
+
const requiresExactRelationshipSet = exactOrphanCandidateIds.has(propertyId);
|
|
2986
|
+
if (requiresExactRelationshipSet
|
|
2987
|
+
? exactlyVisited.has(propertyId)
|
|
2988
|
+
: ordinarilyVisited.has(propertyId) ||
|
|
2989
|
+
exactlyVisited.has(propertyId)) {
|
|
2990
|
+
return;
|
|
2991
|
+
}
|
|
2992
|
+
if (visiting.has(propertyId)) {
|
|
2993
|
+
throw new Error(`[PropsManager] Property mutation has a relationship cycle at "${propertyId}"`);
|
|
2994
|
+
}
|
|
2995
|
+
const snapshot = createdComponents.get(propertyId) ??
|
|
2996
|
+
workingSnapshots.get(propertyId) ??
|
|
2997
|
+
captureActiveSnapshot(propertyId);
|
|
2998
|
+
if (!snapshot) {
|
|
2999
|
+
throw new Error(`[PropsManager] Property mutation cannot snapshot relationship graph property "${propertyId}"`);
|
|
3000
|
+
}
|
|
3001
|
+
const contract = captureContract(snapshot.type);
|
|
3002
|
+
const active = activeById.get(propertyId);
|
|
3003
|
+
if (active &&
|
|
3004
|
+
(!(active instanceof contract.constructor) ||
|
|
3005
|
+
active.get('type') !== snapshot.type)) {
|
|
3006
|
+
throw new Error(`[PropsManager] Property mutation has an invalid relationship graph instance "${propertyId}"`);
|
|
3007
|
+
}
|
|
3008
|
+
indexWorkingOwner(propertyId, snapshot, requiresExactRelationshipSet);
|
|
3009
|
+
visiting.add(propertyId);
|
|
3010
|
+
getWorkingChildIds(propertyId)?.forEach((childId) => {
|
|
3011
|
+
if (requiresExactRelationshipSet &&
|
|
3012
|
+
retainedRootPropertyIdSet.has(childId)) {
|
|
3013
|
+
return;
|
|
3014
|
+
}
|
|
3015
|
+
if (requiresExactRelationshipSet) {
|
|
3016
|
+
exactOrphanCandidateIds.add(childId);
|
|
3017
|
+
}
|
|
3018
|
+
visitRelationshipGraph(childId);
|
|
3019
|
+
});
|
|
3020
|
+
visiting.delete(propertyId);
|
|
3021
|
+
if (requiresExactRelationshipSet) {
|
|
3022
|
+
exactlyVisited.add(propertyId);
|
|
3023
|
+
}
|
|
3024
|
+
else {
|
|
3025
|
+
ordinarilyVisited.add(propertyId);
|
|
3026
|
+
}
|
|
3027
|
+
};
|
|
3028
|
+
new Set([
|
|
3029
|
+
...relationshipMutationRootIds,
|
|
3030
|
+
...removedCandidateIds,
|
|
3031
|
+
...createdComponents.keys()
|
|
3032
|
+
]).forEach(visitRelationshipGraph);
|
|
3033
|
+
}
|
|
3034
|
+
if (exactOrphanCandidateIds.size > 0) {
|
|
3035
|
+
activeById.forEach((component, ownerId) => {
|
|
3036
|
+
const type = component.get('type');
|
|
3037
|
+
const relation = typeof type === 'string'
|
|
3038
|
+
? getPropertyComponentCanonicalChildRelation(type)
|
|
3039
|
+
: undefined;
|
|
3040
|
+
const indexedChildIds = this.relationshipChildIdsByOwnerId.get(ownerId);
|
|
3041
|
+
const indexedAffected = indexedChildIds?.some((childId) => exactOrphanCandidateIds.has(childId)) ?? false;
|
|
3042
|
+
const rawChildIds = relation
|
|
3043
|
+
? component.data[relation.key]
|
|
3044
|
+
: undefined;
|
|
3045
|
+
const rawAffected = Array.isArray(rawChildIds) &&
|
|
3046
|
+
rawChildIds.some((childId) => typeof childId === 'string' &&
|
|
3047
|
+
exactOrphanCandidateIds.has(childId));
|
|
3048
|
+
if (!indexedAffected && !rawAffected) {
|
|
3049
|
+
return;
|
|
3050
|
+
}
|
|
3051
|
+
if (!relation ||
|
|
3052
|
+
!Array.isArray(rawChildIds) ||
|
|
3053
|
+
rawChildIds.some((childId) => typeof childId !== 'string') ||
|
|
3054
|
+
new Set(rawChildIds).size !== rawChildIds.length ||
|
|
3055
|
+
indexedChildIds === undefined ||
|
|
3056
|
+
!isEqual(indexedChildIds, rawChildIds)) {
|
|
3057
|
+
throw new Error(`[PropsManager] Exact orphan property graph has an inconsistent forward relationship for "${ownerId}"`);
|
|
3058
|
+
}
|
|
3059
|
+
;
|
|
3060
|
+
rawChildIds.forEach((childId) => {
|
|
3061
|
+
if (exactOrphanCandidateIds.has(childId) &&
|
|
3062
|
+
!this.relationshipOwnerIdsByChildId.get(childId)?.has(ownerId)) {
|
|
3063
|
+
throw new Error(`[PropsManager] Exact orphan property graph has an inconsistent reverse relationship for "${ownerId}:${childId}"`);
|
|
3064
|
+
}
|
|
3065
|
+
});
|
|
3066
|
+
if (retainedRootPropertyIdSet.has(ownerId)) {
|
|
3067
|
+
retainedRootRelationshipReads.set(ownerId, Object.freeze({
|
|
3068
|
+
propertyId: ownerId,
|
|
3069
|
+
instance: component,
|
|
3070
|
+
relationKey: relation.key,
|
|
3071
|
+
rawChildIds: Object.freeze([...rawChildIds]),
|
|
3072
|
+
indexedChildIds: Object.freeze([...indexedChildIds])
|
|
3073
|
+
}));
|
|
3074
|
+
return;
|
|
3075
|
+
}
|
|
3076
|
+
const ownerSnapshot = workingSnapshots.get(ownerId) ?? captureActiveSnapshot(ownerId);
|
|
3077
|
+
if (!ownerSnapshot) {
|
|
3078
|
+
throw new Error(`[PropsManager] Exact orphan property graph cannot snapshot affected owner "${ownerId}"`);
|
|
3079
|
+
}
|
|
3080
|
+
indexWorkingOwner(ownerId, ownerSnapshot, true);
|
|
3081
|
+
});
|
|
3082
|
+
}
|
|
3083
|
+
orderedOwnerIds.forEach((orderedId) => {
|
|
3084
|
+
const visited = new Set();
|
|
3085
|
+
const visitCreatedDescendants = (propertyId) => {
|
|
3086
|
+
if (visited.has(propertyId)) {
|
|
3087
|
+
return;
|
|
3088
|
+
}
|
|
3089
|
+
visited.add(propertyId);
|
|
3090
|
+
getWorkingChildIds(propertyId)?.forEach((childId) => {
|
|
3091
|
+
if (createdComponents.has(childId)) {
|
|
3092
|
+
associatePropertyWithOwner(childId, orderedId);
|
|
3093
|
+
}
|
|
3094
|
+
if (createdComponents.has(childId) ||
|
|
3095
|
+
relationshipMutationRootIds.has(childId)) {
|
|
3096
|
+
visitCreatedDescendants(childId);
|
|
3097
|
+
}
|
|
3098
|
+
});
|
|
3099
|
+
};
|
|
3100
|
+
(rootPropertyIdsByOwnerId.get(orderedId) ?? []).forEach(visitCreatedDescendants);
|
|
3101
|
+
});
|
|
3102
|
+
const removedIds = new Set();
|
|
3103
|
+
const orderedRemovedIds = [];
|
|
3104
|
+
const pendingRemovalIds = [...removedCandidateIds];
|
|
3105
|
+
const queuedRemovalIds = new Set(pendingRemovalIds);
|
|
3106
|
+
let removalIndex = 0;
|
|
3107
|
+
while (removalIndex < pendingRemovalIds.length) {
|
|
3108
|
+
const candidateId = pendingRemovalIds[removalIndex++];
|
|
3109
|
+
queuedRemovalIds.delete(candidateId);
|
|
3110
|
+
const candidateOwnerIds = canonicalOwnerIdSetByPropertyId.get(candidateId);
|
|
3111
|
+
if (!candidateOwnerIds || candidateOwnerIds.size === 0) {
|
|
3112
|
+
throw new Error(`[PropsManager] Property mutation cannot resolve canonical owner for removed record "${candidateId}"`);
|
|
3113
|
+
}
|
|
3114
|
+
const workingOwnerIds = [...getWorkingOwnerIds(candidateId)];
|
|
3115
|
+
if (exactOrphanCandidateIds.has(candidateId)) {
|
|
3116
|
+
workingOwnerIds.forEach((ownerId) => {
|
|
3117
|
+
if (retainedRootPropertyIdSet.has(ownerId)) {
|
|
3118
|
+
const retainedRelationshipRead = retainedRootRelationshipReads.get(ownerId);
|
|
3119
|
+
if (!retainedRelationshipRead ||
|
|
3120
|
+
!retainedRelationshipRead.rawChildIds.includes(candidateId)) {
|
|
3121
|
+
throw new Error(`[PropsManager] Exact orphan property graph has a missing retained owner relationship "${ownerId}:${candidateId}"`);
|
|
3122
|
+
}
|
|
3123
|
+
return;
|
|
3124
|
+
}
|
|
3125
|
+
const ownerSnapshot = createdComponents.get(ownerId) ??
|
|
3126
|
+
workingSnapshots.get(ownerId) ??
|
|
3127
|
+
captureActiveSnapshot(ownerId);
|
|
3128
|
+
if (!ownerSnapshot) {
|
|
3129
|
+
throw new Error(`[PropsManager] Exact orphan property graph has a missing retaining owner "${ownerId}"`);
|
|
3130
|
+
}
|
|
3131
|
+
indexWorkingOwner(ownerId, ownerSnapshot, true);
|
|
3132
|
+
if (!(getWorkingChildIds(ownerId) ?? []).includes(candidateId)) {
|
|
3133
|
+
throw new Error(`[PropsManager] Exact orphan property graph has an inconsistent retaining owner "${ownerId}:${candidateId}"`);
|
|
3134
|
+
}
|
|
3135
|
+
});
|
|
3136
|
+
}
|
|
3137
|
+
const hasLiveOwner = workingOwnerIds.some((ownerId) => !removedIds.has(ownerId));
|
|
3138
|
+
if (hasLiveOwner && !exactOrphanCandidateIds.has(candidateId)) {
|
|
3139
|
+
const activeOwnerRead = relationshipOwnersReads.get(candidateId);
|
|
3140
|
+
const workingOwnerIdSet = new Set(workingOwnerIds);
|
|
3141
|
+
const preparedRemovedOwnerIds = new Set((activeOwnerRead?.ownerIds ?? []).filter((ownerId) => !workingOwnerIdSet.has(ownerId)));
|
|
3142
|
+
workingOwnerIds.forEach((ownerId) => {
|
|
3143
|
+
if (removedIds.has(ownerId)) {
|
|
3144
|
+
preparedRemovedOwnerIds.add(ownerId);
|
|
3145
|
+
}
|
|
3146
|
+
});
|
|
3147
|
+
if (preparedRemovedOwnerIds.size > 0) {
|
|
3148
|
+
sharedRetentionReads.set(candidateId, Object.freeze({
|
|
3149
|
+
childId: candidateId,
|
|
3150
|
+
preparedRemovedOwnerIds: Object.freeze([...preparedRemovedOwnerIds].sort())
|
|
3151
|
+
}));
|
|
3152
|
+
}
|
|
3153
|
+
}
|
|
3154
|
+
if (removedIds.has(candidateId) ||
|
|
3155
|
+
createdComponents.has(candidateId) ||
|
|
3156
|
+
hasLiveOwner) {
|
|
3157
|
+
continue;
|
|
3158
|
+
}
|
|
3159
|
+
const candidate = activeById.get(candidateId);
|
|
3160
|
+
const candidateSnapshot = captureActiveSnapshot(candidateId);
|
|
3161
|
+
if (!candidate || !candidateSnapshot) {
|
|
3162
|
+
throw new Error(`[PropsManager] Property mutation cannot remove missing record "${candidateId}"`);
|
|
3163
|
+
}
|
|
3164
|
+
removedIds.add(candidateId);
|
|
3165
|
+
orderedRemovedIds.push(candidateId);
|
|
3166
|
+
const childIds = getWorkingChildIds(candidateId) ?? [];
|
|
3167
|
+
replaceWorkingOwnerEdges(candidateId, []);
|
|
3168
|
+
childIds.forEach((childId) => {
|
|
3169
|
+
if (retainedRootPropertyIdSet.has(childId)) {
|
|
3170
|
+
return;
|
|
3171
|
+
}
|
|
3172
|
+
if (exactOrphanCandidateIds.has(candidateId)) {
|
|
3173
|
+
exactOrphanCandidateIds.add(childId);
|
|
3174
|
+
}
|
|
3175
|
+
candidateOwnerIds.forEach((orderedId) => associatePropertyWithOwner(childId, orderedId));
|
|
3176
|
+
if (getWorkingOwnerIds(childId).size === 0 &&
|
|
3177
|
+
!queuedRemovalIds.has(childId)) {
|
|
3178
|
+
queuedRemovalIds.add(childId);
|
|
3179
|
+
pendingRemovalIds.push(childId);
|
|
3180
|
+
}
|
|
3181
|
+
});
|
|
3182
|
+
}
|
|
3183
|
+
const orderedCreatedIds = [];
|
|
3184
|
+
const orderedCreatedIdSet = new Set();
|
|
3185
|
+
const orderCreatedChildFirst = (propertyId) => {
|
|
3186
|
+
if (orderedCreatedIdSet.has(propertyId)) {
|
|
3187
|
+
return;
|
|
3188
|
+
}
|
|
3189
|
+
getWorkingChildIds(propertyId)?.forEach((childId) => {
|
|
3190
|
+
if (createdComponents.has(childId)) {
|
|
3191
|
+
orderCreatedChildFirst(childId);
|
|
3192
|
+
}
|
|
3193
|
+
});
|
|
3194
|
+
orderedCreatedIdSet.add(propertyId);
|
|
3195
|
+
orderedCreatedIds.push(propertyId);
|
|
3196
|
+
};
|
|
3197
|
+
createdComponents.forEach((_snapshot, propertyId) => orderCreatedChildFirst(propertyId));
|
|
3198
|
+
const createdSnapshots = orderedCreatedIds.map((propertyId) => {
|
|
3199
|
+
const snapshot = createdComponents.get(propertyId);
|
|
3200
|
+
if (!snapshot) {
|
|
3201
|
+
throw new Error(`[PropsManager] Property mutation cannot order created record "${propertyId}"`);
|
|
3202
|
+
}
|
|
3203
|
+
return deepFreezePropertyContract(snapshot);
|
|
3204
|
+
});
|
|
3205
|
+
const removedComponents = orderedRemovedIds.map((propertyId) => {
|
|
3206
|
+
const component = activeById.get(propertyId);
|
|
3207
|
+
if (!component) {
|
|
3208
|
+
throw new Error(`[PropsManager] Property mutation cannot resolve removed record "${propertyId}"`);
|
|
3209
|
+
}
|
|
3210
|
+
return component;
|
|
3211
|
+
});
|
|
3212
|
+
const evidence = [];
|
|
3213
|
+
if (createdSnapshots.length > 0) {
|
|
3214
|
+
evidence.push({
|
|
3215
|
+
eventName: EventTypes.ADD_PROPERTY,
|
|
3216
|
+
data: [...createdSnapshots],
|
|
3217
|
+
action: PROPS_ACTIONS.ADD_PROPERTY,
|
|
3218
|
+
undoType: EventTypes.REMOVE_PROPERTY,
|
|
3219
|
+
undoAction: EventTypes.REMOVE_PROPERTY
|
|
3220
|
+
});
|
|
3221
|
+
}
|
|
3222
|
+
evidence.push(...updateEvidence);
|
|
3223
|
+
if (removedComponents.length > 0) {
|
|
3224
|
+
evidence.push({
|
|
3225
|
+
eventName: EventTypes.REMOVE_PROPERTY,
|
|
3226
|
+
data: orderedRemovedIds.map((propertyId) => {
|
|
3227
|
+
const snapshot = workingSnapshots.get(propertyId);
|
|
3228
|
+
if (!snapshot) {
|
|
3229
|
+
throw new Error(`[PropsManager] Property mutation cannot capture removed record "${propertyId}"`);
|
|
3230
|
+
}
|
|
3231
|
+
return deepFreezePropertyContract(snapshot);
|
|
3232
|
+
}),
|
|
3233
|
+
action: PROPS_ACTIONS.REMOVE_PROPERTY,
|
|
3234
|
+
undoType: EventTypes.ADD_PROPERTY,
|
|
3235
|
+
undoAction: EventTypes.ADD_PROPERTY
|
|
3236
|
+
});
|
|
3237
|
+
}
|
|
3238
|
+
const owners = deepFreezePropertyContract(orderedOwnerIds.map((orderedId) => ({
|
|
3239
|
+
orderedId,
|
|
3240
|
+
rootPropertyIds: [...(rootPropertyIdsByOwnerId.get(orderedId) ?? [])]
|
|
3241
|
+
})));
|
|
3242
|
+
const frozenOwnerRelations = deepFreezePropertyContract(ownerRelations);
|
|
3243
|
+
const prepared = deepFreezePropertyContract({
|
|
3244
|
+
kind: 'prepared-property-mutation-batch',
|
|
3245
|
+
owners,
|
|
3246
|
+
ownerRelations: frozenOwnerRelations,
|
|
3247
|
+
orderedPropertyIds: [...orderedPropertyIds]
|
|
3248
|
+
});
|
|
3249
|
+
const readComponents = [...originalSnapshots].map(([propertyId, before]) => {
|
|
3250
|
+
const instance = activeById.get(propertyId);
|
|
3251
|
+
if (!instance) {
|
|
3252
|
+
throw new Error(`[PropsManager] Property mutation cannot retain read property "${propertyId}"`);
|
|
3253
|
+
}
|
|
3254
|
+
return Object.freeze({
|
|
3255
|
+
instance,
|
|
3256
|
+
before
|
|
3257
|
+
});
|
|
3258
|
+
});
|
|
3259
|
+
const existingComponents = touchedPropertyIds.map((propertyId) => {
|
|
3260
|
+
const instance = activeById.get(propertyId);
|
|
3261
|
+
const before = originalSnapshots.get(propertyId);
|
|
3262
|
+
const after = workingSnapshots.get(propertyId);
|
|
3263
|
+
if (!instance || !before || !after) {
|
|
3264
|
+
throw new Error(`[PropsManager] Property mutation cannot retain changed property "${propertyId}"`);
|
|
3265
|
+
}
|
|
3266
|
+
return Object.freeze({
|
|
3267
|
+
instance,
|
|
3268
|
+
before,
|
|
3269
|
+
after: deepFreezePropertyContract(after)
|
|
3270
|
+
});
|
|
3271
|
+
});
|
|
3272
|
+
const frozenEvidence = deepFreezePropertyContract(evidence);
|
|
3273
|
+
const mutableOrderedOwnerIdsByPropertyId = new Map();
|
|
3274
|
+
orderedOwnerIds.forEach((orderedId) => {
|
|
3275
|
+
;
|
|
3276
|
+
(canonicalPropertyIdsByOwnerId.get(orderedId) ?? []).forEach((propertyId) => {
|
|
3277
|
+
const ownerIds = mutableOrderedOwnerIdsByPropertyId.get(propertyId) ?? [];
|
|
3278
|
+
ownerIds.push(orderedId);
|
|
3279
|
+
mutableOrderedOwnerIdsByPropertyId.set(propertyId, ownerIds);
|
|
3280
|
+
});
|
|
3281
|
+
});
|
|
3282
|
+
const orderedCanonicalOwnerIdsByPropertyId = new Map([...mutableOrderedOwnerIdsByPropertyId].map(([propertyId, ownerIds]) => [propertyId, Object.freeze(ownerIds)]));
|
|
3283
|
+
const orderedCanonicalOwnerIds = (propertyId) => {
|
|
3284
|
+
const ownerIds = orderedCanonicalOwnerIdsByPropertyId.get(propertyId) ?? [];
|
|
3285
|
+
if (ownerIds.length === 0) {
|
|
3286
|
+
throw new Error(`[PropsManager] Property mutation cannot resolve canonical owner for evidence "${propertyId}"`);
|
|
3287
|
+
}
|
|
3288
|
+
return ownerIds;
|
|
3289
|
+
};
|
|
3290
|
+
const createLifecycleCanonicalEvidence = (change) => {
|
|
3291
|
+
const affectedOwnerIdSet = new Set();
|
|
3292
|
+
const recordsByOwnerIds = new Map();
|
|
3293
|
+
change.data.forEach((property) => {
|
|
3294
|
+
const orderedIds = orderedCanonicalOwnerIds(property.id);
|
|
3295
|
+
orderedIds.forEach((orderedId) => affectedOwnerIdSet.add(orderedId));
|
|
3296
|
+
const key = JSON.stringify(orderedIds);
|
|
3297
|
+
const record = recordsByOwnerIds.get(key);
|
|
3298
|
+
if (record) {
|
|
3299
|
+
record.data.push(property);
|
|
3300
|
+
return;
|
|
3301
|
+
}
|
|
3302
|
+
recordsByOwnerIds.set(key, {
|
|
3303
|
+
orderedIds,
|
|
3304
|
+
data: [property]
|
|
3305
|
+
});
|
|
3306
|
+
});
|
|
3307
|
+
const orderedIds = orderedOwnerIds.filter((orderedId) => affectedOwnerIdSet.has(orderedId));
|
|
3308
|
+
return {
|
|
3309
|
+
orderedIds,
|
|
3310
|
+
sharedRecords: [...recordsByOwnerIds.values()].map((record) => ({
|
|
3311
|
+
orderedIds: record.orderedIds,
|
|
3312
|
+
payload: {
|
|
3313
|
+
...change,
|
|
3314
|
+
data: record.data
|
|
3315
|
+
}
|
|
3316
|
+
}))
|
|
3317
|
+
};
|
|
3318
|
+
};
|
|
3319
|
+
const transactionOptions = {
|
|
3320
|
+
...(mutationOptions ?? {}),
|
|
3321
|
+
shared: mutationOptions?.shared ?? SharedDataChannelNames.PROPS
|
|
3322
|
+
};
|
|
3323
|
+
const createTransactionEvent = (change) => {
|
|
3324
|
+
const canonicalEvidence = isUpdatePropertyChange(change)
|
|
3325
|
+
? {
|
|
3326
|
+
orderedIds: orderedCanonicalOwnerIds(change.id)
|
|
3327
|
+
}
|
|
3328
|
+
: createLifecycleCanonicalEvidence(change);
|
|
3329
|
+
return {
|
|
3330
|
+
type: TransactionEventTypes.UPDATE_TRANSACTION,
|
|
3331
|
+
eventName: change.eventName,
|
|
3332
|
+
payload: change,
|
|
3333
|
+
options: transactionOptions,
|
|
3334
|
+
canonicalEvidence
|
|
3335
|
+
};
|
|
3336
|
+
};
|
|
3337
|
+
const replaceLatestHistoryCandidate = mutationOptions?.history?.mode === 'replace-latest' &&
|
|
3338
|
+
replaceLatestHistoryEvidence.length > 0
|
|
3339
|
+
? {
|
|
3340
|
+
key: mutationOptions.history.key,
|
|
3341
|
+
events: replaceLatestHistoryEvidence.map(createTransactionEvent)
|
|
3342
|
+
}
|
|
3343
|
+
: undefined;
|
|
3344
|
+
const transactionEvents = deepFreezePropertyContract(frozenEvidence.map((change, index) => ({
|
|
3345
|
+
...createTransactionEvent(change),
|
|
3346
|
+
...(index === 0 && replaceLatestHistoryCandidate
|
|
3347
|
+
? { historyCandidate: replaceLatestHistoryCandidate }
|
|
3348
|
+
: {})
|
|
3349
|
+
})));
|
|
3350
|
+
this.validatedPropertyMutationArtifacts.set(prepared, {
|
|
3351
|
+
owners,
|
|
3352
|
+
ownerRelations: frozenOwnerRelations,
|
|
3353
|
+
orderedPropertyIds: prepared.orderedPropertyIds,
|
|
3354
|
+
registrationContracts: Object.freeze([
|
|
3355
|
+
...registrationContractByType.values()
|
|
3356
|
+
]),
|
|
3357
|
+
ownerDefinitionContracts: Object.freeze([
|
|
3358
|
+
...ownerDefinitionContractByKey.values()
|
|
3359
|
+
]),
|
|
3360
|
+
readComponents: Object.freeze(readComponents),
|
|
3361
|
+
existingComponents: Object.freeze(existingComponents),
|
|
3362
|
+
createdComponents: Object.freeze(createdSnapshots),
|
|
3363
|
+
reactivatedComponents: Object.freeze([...reactivatedComponents.values()]),
|
|
3364
|
+
removedComponents: Object.freeze([...removedComponents]),
|
|
3365
|
+
relationshipChildrenReads: Object.freeze([
|
|
3366
|
+
...relationshipChildrenReads.values()
|
|
3367
|
+
]),
|
|
3368
|
+
relationshipOwnersReads: Object.freeze([
|
|
3369
|
+
...relationshipOwnersReads.values()
|
|
3370
|
+
]),
|
|
3371
|
+
sharedRetentionReads: Object.freeze([...sharedRetentionReads.values()]),
|
|
3372
|
+
retainedRootIdentityReads: Object.freeze(retainedRootIdentityReads),
|
|
3373
|
+
retainedRootRelationshipReads: Object.freeze([
|
|
3374
|
+
...retainedRootRelationshipReads.values()
|
|
3375
|
+
]),
|
|
3376
|
+
evidence: frozenEvidence,
|
|
3377
|
+
transactionEvents
|
|
3378
|
+
});
|
|
3379
|
+
return prepared;
|
|
3380
|
+
}
|
|
3381
|
+
applyPreparedPropertyMutationBatch(prepared) {
|
|
3382
|
+
if (this.propertyMutationApplyActive) {
|
|
3383
|
+
throw new Error('[PropsManager] Reentrant canonical property mutation apply is not allowed');
|
|
3384
|
+
}
|
|
3385
|
+
this.propertyMutationApplyActive = true;
|
|
3386
|
+
try {
|
|
3387
|
+
return this.applyOwnedPropertyMutationBatch(prepared);
|
|
3388
|
+
}
|
|
3389
|
+
finally {
|
|
3390
|
+
this.propertyMutationApplyActive = false;
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3393
|
+
applyOwnedPropertyMutationBatch(prepared) {
|
|
3394
|
+
const artifact = this.validatedPropertyMutationArtifacts.get(prepared);
|
|
3395
|
+
if (!artifact) {
|
|
3396
|
+
throw new Error('[PropsManager] Expected an owner-issued one-shot prepared property mutation batch');
|
|
3397
|
+
}
|
|
3398
|
+
this.validatedPropertyMutationArtifacts.delete(prepared);
|
|
3399
|
+
artifact.ownerDefinitionContracts.forEach(({ ownerElementType, ownerPropertyName, definition }) => {
|
|
3400
|
+
const current = elementPropertyRegistry.getForComponent(ownerElementType, ownerPropertyName);
|
|
3401
|
+
if (!current || !isEqual(current, definition)) {
|
|
3402
|
+
throw new Error(`[PropsManager] Detached property creation owner definition registration changed for "${ownerElementType}:${ownerPropertyName}"`);
|
|
3403
|
+
}
|
|
3404
|
+
});
|
|
3405
|
+
this.assertPropertyCreationRegistrationReadiness(artifact.registrationContracts, new Set());
|
|
3406
|
+
const sharedRetentionReadByChildId = new Map(artifact.sharedRetentionReads.map((read) => [read.childId, read]));
|
|
3407
|
+
const reactivatedComponentById = new Map(artifact.reactivatedComponents.map((read) => [read.before.id, read]));
|
|
3408
|
+
const relationshipIndexesMatch = artifact.relationshipChildrenReads.every(({ ownerId, present, childIds }) => {
|
|
3409
|
+
const current = this.relationshipChildIdsByOwnerId.get(ownerId);
|
|
3410
|
+
return ((current !== undefined) === present &&
|
|
3411
|
+
isEqual(current ?? [], childIds));
|
|
3412
|
+
}) &&
|
|
3413
|
+
artifact.relationshipOwnersReads.every(({ childId, present, ownerIds }) => {
|
|
3414
|
+
const current = this.relationshipOwnerIdsByChildId.get(childId);
|
|
3415
|
+
const sharedRetentionRead = sharedRetentionReadByChildId.get(childId);
|
|
3416
|
+
if (sharedRetentionRead) {
|
|
3417
|
+
const currentOwnerIds = new Set(current ?? []);
|
|
3418
|
+
const preparedRemovedOwnerIds = new Set(sharedRetentionRead.preparedRemovedOwnerIds);
|
|
3419
|
+
return (sharedRetentionRead.preparedRemovedOwnerIds.every((ownerId) => currentOwnerIds.has(ownerId)) &&
|
|
3420
|
+
[...currentOwnerIds].some((ownerId) => !preparedRemovedOwnerIds.has(ownerId)));
|
|
3421
|
+
}
|
|
3422
|
+
return ((current !== undefined) === present &&
|
|
3423
|
+
isEqual([...(current ?? [])].sort(), ownerIds));
|
|
3424
|
+
});
|
|
3425
|
+
const retainedRootRelationshipsMatch = artifact.retainedRootRelationshipReads.every(({ propertyId, instance, relationKey, rawChildIds, indexedChildIds }) => {
|
|
3426
|
+
const currentRawChildIds = instance.data[relationKey];
|
|
3427
|
+
return (this._components.get(propertyId) === instance &&
|
|
3428
|
+
Array.isArray(currentRawChildIds) &&
|
|
3429
|
+
currentRawChildIds.every((childId) => typeof childId === 'string') &&
|
|
3430
|
+
isEqual(currentRawChildIds, rawChildIds) &&
|
|
3431
|
+
isEqual(this.relationshipChildIdsByOwnerId.get(propertyId), indexedChildIds));
|
|
3432
|
+
});
|
|
3433
|
+
if (artifact.readComponents.some(({ instance, before }) => this._components.get(before.id) !== instance ||
|
|
3434
|
+
!isEqual(instance.save(), before)) ||
|
|
3435
|
+
artifact.createdComponents.some(({ id }) => {
|
|
3436
|
+
const reactivated = reactivatedComponentById.get(id);
|
|
3437
|
+
return reactivated
|
|
3438
|
+
? this._components.has(id) ||
|
|
3439
|
+
this._deletedMap.get(id) !== reactivated.instance ||
|
|
3440
|
+
!isEqual(reactivated.instance.save(), reactivated.before)
|
|
3441
|
+
: this._components.has(id) || this._deletedMap.has(id);
|
|
3442
|
+
}) ||
|
|
3443
|
+
artifact.retainedRootIdentityReads.some(({ propertyId, instance }) => this._components.get(propertyId) !== instance) ||
|
|
3444
|
+
!retainedRootRelationshipsMatch ||
|
|
3445
|
+
!relationshipIndexesMatch) {
|
|
3446
|
+
throw new Error('[PropsManager] Property mutation prepared no longer matches active state');
|
|
3447
|
+
}
|
|
3448
|
+
if (artifact.evidence.length === 0) {
|
|
3449
|
+
return deepFreezePropertyContract({
|
|
3450
|
+
owners: [...artifact.owners],
|
|
3451
|
+
ownerRelations: [...artifact.ownerRelations],
|
|
3452
|
+
orderedPropertyIds: [...artifact.orderedPropertyIds],
|
|
3453
|
+
evidence: []
|
|
3454
|
+
});
|
|
3455
|
+
}
|
|
3456
|
+
const changeStart = this.changes.length;
|
|
3457
|
+
const createdInstances = [];
|
|
3458
|
+
const reactivatedInstances = new Set();
|
|
3459
|
+
const stagedMutationInstances = new Map();
|
|
3460
|
+
const removedInstances = [];
|
|
3461
|
+
const removedPropertyIds = new Set(artifact.removedComponents.map((component) => component.get('id')));
|
|
3462
|
+
let transactionBatchHandoffStarted = false;
|
|
3463
|
+
try {
|
|
3464
|
+
const registrationContractByType = new Map(artifact.registrationContracts.map((contract) => [contract.type, contract]));
|
|
3465
|
+
this.propertyMutationStagedById = stagedMutationInstances;
|
|
3466
|
+
runWithPropertyComponentAccessor(this.componentAccessor, () => {
|
|
3467
|
+
artifact.createdComponents.forEach((snapshot) => {
|
|
3468
|
+
const contract = registrationContractByType.get(snapshot.type);
|
|
3469
|
+
if (!contract) {
|
|
3470
|
+
throw new Error(`[PropsManager] Property mutation is missing registration for "${snapshot.id}"`);
|
|
3471
|
+
}
|
|
3472
|
+
const reactivated = reactivatedComponentById.get(snapshot.id);
|
|
3473
|
+
const component = reactivated?.instance ??
|
|
3474
|
+
this.propertyMutationStagedById?.get(snapshot.id) ??
|
|
3475
|
+
this.instantiateProperty(snapshot, contract.constructor);
|
|
3476
|
+
if (reactivated) {
|
|
3477
|
+
if (this._deletedMap.get(snapshot.id) !== component ||
|
|
3478
|
+
!isEqual(component.save(), snapshot)) {
|
|
3479
|
+
throw new Error(`[PropsManager] Property mutation cannot reactivate changed record "${snapshot.id}"`);
|
|
3480
|
+
}
|
|
3481
|
+
this._deletedMap.delete(snapshot.id);
|
|
3482
|
+
reactivatedInstances.add(component);
|
|
3483
|
+
}
|
|
3484
|
+
createdInstances.push(component);
|
|
3485
|
+
this.addToMap(component);
|
|
3486
|
+
});
|
|
3487
|
+
if (this.propertyMutationStagedById?.size !== createdInstances.length ||
|
|
3488
|
+
createdInstances.some((component) => this.propertyMutationStagedById?.get(component.get('id')) !==
|
|
3489
|
+
component)) {
|
|
3490
|
+
throw new Error('[PropsManager] Property mutation materialized an inexact record graph');
|
|
3491
|
+
}
|
|
3492
|
+
if (this.changes.length !== changeStart) {
|
|
3493
|
+
throw new Error('[PropsManager] Property mutation materialization emitted property changes');
|
|
3494
|
+
}
|
|
3495
|
+
this.assertPropertyCreationRegistrationReadiness(artifact.registrationContracts, new Set());
|
|
3496
|
+
this.registerMany(createdInstances);
|
|
3497
|
+
this.propertyMutationStagedById = null;
|
|
3498
|
+
artifact.existingComponents.forEach(({ instance, after }) => {
|
|
3499
|
+
instance.load(clonePropsValue(after));
|
|
3500
|
+
if (!isEqual(instance.save(), after)) {
|
|
3501
|
+
throw new Error(`[PropsManager] Property mutation changed exact data for "${after.id}"`);
|
|
3502
|
+
}
|
|
3503
|
+
if (!removedPropertyIds.has(after.id)) {
|
|
3504
|
+
this.refreshRelationshipOwnerEdges(instance, after);
|
|
3505
|
+
}
|
|
3506
|
+
});
|
|
3507
|
+
artifact.removedComponents.forEach((component) => {
|
|
3508
|
+
const propertyId = component.get('id');
|
|
3509
|
+
if (this._components.get(propertyId) !== component) {
|
|
3510
|
+
throw new Error(`[PropsManager] Property mutation cannot remove changed record "${propertyId}"`);
|
|
3511
|
+
}
|
|
3512
|
+
this.unregisterActiveComponent(propertyId);
|
|
3513
|
+
this._deletedMap.set(propertyId, component);
|
|
3514
|
+
removedInstances.push(component);
|
|
3515
|
+
});
|
|
3516
|
+
});
|
|
3517
|
+
const evidence = artifact.evidence;
|
|
3518
|
+
transactionBatchHandoffStarted = true;
|
|
3519
|
+
updateTransactionBatch(artifact.transactionEvents);
|
|
3520
|
+
acknowledgeTransactionReplayApplied();
|
|
3521
|
+
this.changes.splice(changeStart);
|
|
3522
|
+
this.advancePropertyStateRevision();
|
|
3523
|
+
return deepFreezePropertyContract({
|
|
3524
|
+
owners: [...artifact.owners],
|
|
3525
|
+
ownerRelations: [...artifact.ownerRelations],
|
|
3526
|
+
orderedPropertyIds: [...artifact.orderedPropertyIds],
|
|
3527
|
+
evidence
|
|
3528
|
+
});
|
|
3529
|
+
}
|
|
3530
|
+
catch (error) {
|
|
3531
|
+
this.propertyMutationStagedById = null;
|
|
3532
|
+
this.changes.splice(changeStart);
|
|
3533
|
+
if (transactionBatchHandoffStarted &&
|
|
3534
|
+
reportsAcceptedPropertyMutationHandoff(error)) {
|
|
3535
|
+
this.advancePropertyStateRevision();
|
|
3536
|
+
acknowledgeTransactionReplayApplied();
|
|
3537
|
+
throw error;
|
|
3538
|
+
}
|
|
3539
|
+
const attemptCleanup = (operation) => {
|
|
3540
|
+
try {
|
|
3541
|
+
operation();
|
|
3542
|
+
}
|
|
3543
|
+
catch {
|
|
3544
|
+
// Cleanup is best-effort and cannot replace the canonical apply failure.
|
|
3545
|
+
}
|
|
3546
|
+
};
|
|
3547
|
+
removedInstances.reverse().forEach((component) => {
|
|
3548
|
+
attemptCleanup(() => {
|
|
3549
|
+
const propertyId = component.get('id');
|
|
3550
|
+
this._deletedMap.delete(propertyId);
|
|
3551
|
+
this.registerActiveComponent(component, this.prepareRelationshipIndexEntry(component));
|
|
3552
|
+
});
|
|
3553
|
+
});
|
|
3554
|
+
const restoreSnapshots = new Map();
|
|
3555
|
+
artifact.existingComponents.forEach(({ instance, before }) => {
|
|
3556
|
+
restoreSnapshots.set(instance, before);
|
|
3557
|
+
});
|
|
3558
|
+
runWithPropertyComponentAccessor(this.componentAccessor, () => {
|
|
3559
|
+
restoreSnapshots.forEach((before, instance) => {
|
|
3560
|
+
attemptCleanup(() => {
|
|
3561
|
+
instance.load(clonePropsValue(before));
|
|
3562
|
+
const propertyId = before.id;
|
|
3563
|
+
this._deletedMap.delete(propertyId);
|
|
3564
|
+
const relationshipChildIds = this.prepareRelationshipIndexEntry(instance, before);
|
|
3565
|
+
if (this._components.get(propertyId) !== instance) {
|
|
3566
|
+
this.registerActiveComponent(instance, relationshipChildIds);
|
|
3567
|
+
}
|
|
3568
|
+
else {
|
|
3569
|
+
this.replaceRelationshipOwnerEdges(propertyId, relationshipChildIds);
|
|
3570
|
+
}
|
|
3571
|
+
});
|
|
3572
|
+
});
|
|
3573
|
+
});
|
|
3574
|
+
new Set([
|
|
3575
|
+
...createdInstances,
|
|
3576
|
+
...stagedMutationInstances.values()
|
|
3577
|
+
]).forEach((component) => {
|
|
3578
|
+
attemptCleanup(() => {
|
|
3579
|
+
const propertyId = component.get('id');
|
|
3580
|
+
if (this._components.get(propertyId) === component) {
|
|
3581
|
+
this.unregisterActiveComponent(propertyId);
|
|
3582
|
+
}
|
|
3583
|
+
});
|
|
3584
|
+
if (reactivatedInstances.has(component)) {
|
|
3585
|
+
attemptCleanup(() => {
|
|
3586
|
+
this._deletedMap.set(component.get('id'), component);
|
|
3587
|
+
});
|
|
3588
|
+
}
|
|
3589
|
+
else {
|
|
3590
|
+
attemptCleanup(() => {
|
|
3591
|
+
;
|
|
3592
|
+
component.dispose?.();
|
|
3593
|
+
});
|
|
3594
|
+
}
|
|
3595
|
+
});
|
|
3596
|
+
throw error;
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
updateProperties(request) {
|
|
3600
|
+
return this.applyPreparedPropertyMutationBatch(this.preparePropertyMutationBatch(request));
|
|
3601
|
+
}
|
|
3602
|
+
updatePropsData(componentId, key, data, options) {
|
|
3603
|
+
const component = this.getPropertyById(componentId);
|
|
3604
|
+
if (!component) {
|
|
3605
|
+
return;
|
|
3606
|
+
}
|
|
3607
|
+
runWithPropertyComponentAccessor(this.componentAccessor, () => {
|
|
3608
|
+
if (options) {
|
|
3609
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3610
|
+
component.set(key, data, options);
|
|
3611
|
+
return;
|
|
3612
|
+
}
|
|
3613
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3614
|
+
component.set(key, data);
|
|
3615
|
+
});
|
|
3616
|
+
}
|
|
3617
|
+
updatePropertyById(propertyId, key, data, options) {
|
|
3618
|
+
this.updatePropsData(propertyId, key, data, options);
|
|
3619
|
+
}
|
|
3620
|
+
prepareCanonicalPropertyBatch() {
|
|
3621
|
+
if (this.changes.length < 2) {
|
|
3622
|
+
return this.changes;
|
|
3623
|
+
}
|
|
3624
|
+
const removeChanges = this.changes.filter(isRemovePropertyChange);
|
|
3625
|
+
if (removeChanges.length === this.changes.length) {
|
|
3626
|
+
const firstRemove = removeChanges[0];
|
|
3627
|
+
if (!firstRemove) {
|
|
3628
|
+
return this.changes;
|
|
3629
|
+
}
|
|
3630
|
+
const { data: _firstData, ...firstRemoveContract } = firstRemove;
|
|
3631
|
+
const removedIds = new Set();
|
|
3632
|
+
const removedData = [];
|
|
3633
|
+
for (const removeChange of removeChanges) {
|
|
3634
|
+
const { data: _data, ...removeContract } = removeChange;
|
|
3635
|
+
if (!isEqual(removeContract, firstRemoveContract)) {
|
|
3636
|
+
return this.changes;
|
|
3637
|
+
}
|
|
3638
|
+
for (const propertyData of removeChange.data) {
|
|
3639
|
+
const propertyId = propertyData.id;
|
|
3640
|
+
if (typeof propertyId !== 'string' ||
|
|
3641
|
+
propertyId.length === 0 ||
|
|
3642
|
+
removedIds.has(propertyId)) {
|
|
3643
|
+
return this.changes;
|
|
3644
|
+
}
|
|
3645
|
+
removedIds.add(propertyId);
|
|
3646
|
+
removedData.push(propertyData);
|
|
3647
|
+
}
|
|
3648
|
+
}
|
|
3649
|
+
return [
|
|
3650
|
+
{
|
|
3651
|
+
...firstRemove,
|
|
3652
|
+
data: removedData
|
|
3653
|
+
}
|
|
3654
|
+
];
|
|
3655
|
+
}
|
|
3656
|
+
const addChanges = this.changes.filter(isAddPropertyChange);
|
|
3657
|
+
if (addChanges.length === 0) {
|
|
3658
|
+
return this.changes;
|
|
3659
|
+
}
|
|
3660
|
+
const firstAdd = addChanges[0];
|
|
3661
|
+
const { data: _firstData, ...firstAddContract } = firstAdd;
|
|
3662
|
+
const orderedIds = [];
|
|
3663
|
+
const createdIds = new Set();
|
|
3664
|
+
const initialSnapshots = new Map();
|
|
3665
|
+
for (const addChange of addChanges) {
|
|
3666
|
+
const { data: _data, ...addContract } = addChange;
|
|
3667
|
+
if (!isEqual(addContract, firstAddContract)) {
|
|
3668
|
+
return this.changes;
|
|
3669
|
+
}
|
|
3670
|
+
for (const propertyData of addChange.data) {
|
|
3671
|
+
const propertyId = propertyData.id;
|
|
3672
|
+
if (typeof propertyId !== 'string' ||
|
|
3673
|
+
propertyId.length === 0 ||
|
|
3674
|
+
createdIds.has(propertyId) ||
|
|
3675
|
+
!this.getPropertyById(propertyId)) {
|
|
3676
|
+
return this.changes;
|
|
3677
|
+
}
|
|
3678
|
+
createdIds.add(propertyId);
|
|
3679
|
+
orderedIds.push(propertyId);
|
|
3680
|
+
initialSnapshots.set(propertyId, propertyData);
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
const observedAddIds = new Set();
|
|
3684
|
+
const updatedIds = new Set();
|
|
3685
|
+
const canBatch = this.changes.every((change) => {
|
|
3686
|
+
if (isAddPropertyChange(change)) {
|
|
3687
|
+
change.data.forEach(({ id }) => observedAddIds.add(id));
|
|
3688
|
+
return true;
|
|
3689
|
+
}
|
|
3690
|
+
if (!isUpdatePropertyChange(change) || !observedAddIds.has(change.id)) {
|
|
3691
|
+
return false;
|
|
3692
|
+
}
|
|
3693
|
+
updatedIds.add(change.id);
|
|
3694
|
+
return isEqual(change.options, firstAdd.options);
|
|
3695
|
+
});
|
|
3696
|
+
if (!canBatch) {
|
|
3697
|
+
return this.changes;
|
|
3698
|
+
}
|
|
3699
|
+
const finalData = orderedIds.map((propertyId) => {
|
|
3700
|
+
if (!updatedIds.has(propertyId)) {
|
|
3701
|
+
const initialSnapshot = initialSnapshots.get(propertyId);
|
|
3702
|
+
if (!initialSnapshot) {
|
|
3703
|
+
throw new Error(`[PropsManager] Canonical property batch is missing initial snapshot "${propertyId}"`);
|
|
3704
|
+
}
|
|
3705
|
+
return initialSnapshot;
|
|
3706
|
+
}
|
|
3707
|
+
const property = this.getPropertyById(propertyId);
|
|
3708
|
+
if (!property) {
|
|
3709
|
+
throw new Error(`[PropsManager] Canonical property batch is missing active property "${propertyId}"`);
|
|
3710
|
+
}
|
|
3711
|
+
return clonePropsValue(property.save());
|
|
3712
|
+
});
|
|
3713
|
+
return [
|
|
3714
|
+
{
|
|
3715
|
+
...firstAdd,
|
|
3716
|
+
data: finalData
|
|
3717
|
+
}
|
|
3718
|
+
];
|
|
3719
|
+
}
|
|
3720
|
+
prepareTransactionEvents(options) {
|
|
3721
|
+
return this.prepareCanonicalPropertyBatch().map((change) => {
|
|
3722
|
+
const changeOptions = change.options ?? options;
|
|
3723
|
+
const orderedIds = isUpdatePropertyChange(change)
|
|
3724
|
+
? [change.id]
|
|
3725
|
+
: change.data.map(({ id }) => id);
|
|
3726
|
+
return {
|
|
3727
|
+
type: EventTypes.UPDATE_TRANSACTION,
|
|
3728
|
+
eventName: change.eventName,
|
|
3729
|
+
payload: change,
|
|
3730
|
+
options: {
|
|
3731
|
+
...(changeOptions ?? {}),
|
|
3732
|
+
shared: changeOptions?.shared ?? SharedDataChannelNames.PROPS
|
|
3733
|
+
},
|
|
3734
|
+
canonicalEvidence: Object.freeze({
|
|
3735
|
+
orderedIds: Object.freeze(orderedIds)
|
|
3736
|
+
})
|
|
3737
|
+
};
|
|
3738
|
+
});
|
|
3739
|
+
}
|
|
3740
|
+
prepareCanonicalElementTransactionEvents(options) {
|
|
3741
|
+
return this.prepareTransactionEvents(options);
|
|
3742
|
+
}
|
|
3743
|
+
createCanonicalPropertyDeliveryRecords(change, owners) {
|
|
3744
|
+
const propertyById = new Map();
|
|
3745
|
+
change.data.forEach((property) => {
|
|
3746
|
+
if (typeof property.id !== 'string' ||
|
|
3747
|
+
property.id.length === 0 ||
|
|
3748
|
+
propertyById.has(property.id)) {
|
|
3749
|
+
throw new Error('[PropsManager] Canonical property delivery requires unique property ids');
|
|
3750
|
+
}
|
|
3751
|
+
propertyById.set(property.id, property);
|
|
3752
|
+
});
|
|
3753
|
+
const ownerIndexByPropertyId = new Map();
|
|
3754
|
+
const childRelationByType = new Map();
|
|
3755
|
+
owners.forEach(({ rootPropertyIds }, ownerIndex) => {
|
|
3756
|
+
const visitingPropertyIds = new Set();
|
|
3757
|
+
const visit = (propertyId) => {
|
|
3758
|
+
if (visitingPropertyIds.has(propertyId)) {
|
|
3759
|
+
throw new Error(`[PropsManager] Canonical property delivery has a relationship cycle at "${propertyId}"`);
|
|
3760
|
+
}
|
|
3761
|
+
if (ownerIndexByPropertyId.has(propertyId)) {
|
|
3762
|
+
return;
|
|
3763
|
+
}
|
|
3764
|
+
const property = propertyById.get(propertyId);
|
|
3765
|
+
if (!property) {
|
|
3766
|
+
return;
|
|
3767
|
+
}
|
|
3768
|
+
visitingPropertyIds.add(propertyId);
|
|
3769
|
+
ownerIndexByPropertyId.set(propertyId, ownerIndex);
|
|
3770
|
+
if (!childRelationByType.has(property.type)) {
|
|
3771
|
+
childRelationByType.set(property.type, getPropertyComponentCanonicalChildRelation(property.type));
|
|
3772
|
+
}
|
|
3773
|
+
const childRelation = childRelationByType.get(property.type);
|
|
3774
|
+
if (childRelation) {
|
|
3775
|
+
const childIds = property[childRelation.key];
|
|
3776
|
+
if (!Array.isArray(childIds) ||
|
|
3777
|
+
childIds.some((childId) => typeof childId !== 'string')) {
|
|
3778
|
+
throw new Error(`[PropsManager] Canonical property delivery has malformed child relation for "${propertyId}"`);
|
|
3779
|
+
}
|
|
3780
|
+
childIds.forEach(visit);
|
|
3781
|
+
}
|
|
3782
|
+
visitingPropertyIds.delete(propertyId);
|
|
3783
|
+
};
|
|
3784
|
+
rootPropertyIds.forEach(visit);
|
|
3785
|
+
});
|
|
3786
|
+
const dataByOwner = owners.map(() => []);
|
|
3787
|
+
change.data.forEach((property) => {
|
|
3788
|
+
const ownerIndex = ownerIndexByPropertyId.get(property.id);
|
|
3789
|
+
if (ownerIndex === undefined) {
|
|
3790
|
+
throw new Error(`[PropsManager] Canonical property delivery has unowned property "${property.id}"`);
|
|
3791
|
+
}
|
|
3792
|
+
dataByOwner[ownerIndex].push(property);
|
|
3793
|
+
});
|
|
3794
|
+
return owners.map(({ orderedId }, ownerIndex) => ({
|
|
3795
|
+
orderedIds: [orderedId],
|
|
3796
|
+
payload: {
|
|
3797
|
+
...change,
|
|
3798
|
+
data: dataByOwner[ownerIndex]
|
|
3799
|
+
}
|
|
3800
|
+
}));
|
|
3801
|
+
}
|
|
3802
|
+
commitChanges(options) {
|
|
3803
|
+
this.prepareTransactionEvents(options).forEach((event) => {
|
|
3804
|
+
updateTransaction(event);
|
|
3805
|
+
});
|
|
3806
|
+
this.cleanChanges();
|
|
3807
|
+
}
|
|
3808
|
+
dispose() {
|
|
3809
|
+
const hadState = this._components.size > 0 ||
|
|
3810
|
+
this._deletedMap.size > 0 ||
|
|
3811
|
+
this.changes.length > 0;
|
|
3812
|
+
const components = new Set([
|
|
3813
|
+
...this._components.values(),
|
|
3814
|
+
...this._deletedMap.values(),
|
|
3815
|
+
...(this.propertyMutationStagedById?.values() ?? [])
|
|
3816
|
+
]);
|
|
3817
|
+
components.forEach((component) => {
|
|
3818
|
+
;
|
|
3819
|
+
component.dispose?.();
|
|
3820
|
+
});
|
|
3821
|
+
this._components.clear();
|
|
3822
|
+
this._deletedMap.clear();
|
|
3823
|
+
this.relationshipChildIdsByOwnerId.clear();
|
|
3824
|
+
this.relationshipOwnerIdsByChildId.clear();
|
|
3825
|
+
this.changes = [];
|
|
3826
|
+
this.propertyCreationBatch = null;
|
|
3827
|
+
this.activePropertyBatch = null;
|
|
3828
|
+
this.propertyMutationStagedById = null;
|
|
3829
|
+
if (hadState) {
|
|
3830
|
+
this.advancePropertyStateRevision();
|
|
3831
|
+
}
|
|
3832
|
+
}
|
|
3833
|
+
reset() {
|
|
3834
|
+
this.dispose();
|
|
3835
|
+
}
|
|
3836
|
+
}
|
|
3837
|
+
const propsManager = new PropsManager();
|
|
3838
|
+
export default propsManager;
|
|
3839
|
+
export { PropsManager };
|
|
3840
|
+
//# sourceMappingURL=props-manager.js.map
|