@asyra/core 0.5.6 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +11 -5
  3. package/dist/apis/create-apis.d.ts.map +1 -1
  4. package/dist/apis/create-apis.js +103 -48
  5. package/dist/apis/create-apis.js.map +1 -1
  6. package/dist/apis/element-properties.d.ts +5 -8
  7. package/dist/apis/element-properties.d.ts.map +1 -1
  8. package/dist/apis/element-properties.js +19 -6
  9. package/dist/apis/element-properties.js.map +1 -1
  10. package/dist/apis/element-selection.d.ts.map +1 -1
  11. package/dist/apis/element-selection.js.map +1 -1
  12. package/dist/apis/property-intents.d.ts +9 -0
  13. package/dist/apis/property-intents.d.ts.map +1 -0
  14. package/dist/apis/property-intents.js +94 -0
  15. package/dist/apis/property-intents.js.map +1 -0
  16. package/dist/apis/props.d.ts +4 -1
  17. package/dist/apis/props.d.ts.map +1 -1
  18. package/dist/apis/props.js +5 -2
  19. package/dist/apis/props.js.map +1 -1
  20. package/dist/apis/render.d.ts +21 -0
  21. package/dist/apis/render.d.ts.map +1 -1
  22. package/dist/apis/render.js +15 -0
  23. package/dist/apis/render.js.map +1 -1
  24. package/dist/apis/scene-bounds.d.ts.map +1 -1
  25. package/dist/apis/scene-bounds.js +8 -1
  26. package/dist/apis/scene-bounds.js.map +1 -1
  27. package/dist/apis/scene-tree.d.ts +2 -1
  28. package/dist/apis/scene-tree.d.ts.map +1 -1
  29. package/dist/apis/scene-tree.js +23 -11
  30. package/dist/apis/scene-tree.js.map +1 -1
  31. package/dist/canvas-pipeline-debugger/debugger.d.ts.map +1 -1
  32. package/dist/canvas-pipeline-debugger/debugger.js.map +1 -1
  33. package/dist/contracts/index.d.ts +1 -0
  34. package/dist/contracts/index.d.ts.map +1 -1
  35. package/dist/contracts/index.js +1 -0
  36. package/dist/contracts/index.js.map +1 -1
  37. package/dist/core.d.ts +73 -4
  38. package/dist/core.d.ts.map +1 -1
  39. package/dist/core.js +378 -36
  40. package/dist/core.js.map +1 -1
  41. package/dist/data-channel-observer.d.ts +4 -0
  42. package/dist/data-channel-observer.d.ts.map +1 -1
  43. package/dist/data-channel-observer.js +58 -6
  44. package/dist/data-channel-observer.js.map +1 -1
  45. package/dist/define-component.d.ts.map +1 -1
  46. package/dist/define-component.js +2 -1
  47. package/dist/define-component.js.map +1 -1
  48. package/dist/define-property-component.d.ts.map +1 -1
  49. package/dist/define-property-component.js +2 -1
  50. package/dist/define-property-component.js.map +1 -1
  51. package/dist/index.d.ts +12 -5
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +5 -3
  54. package/dist/index.js.map +1 -1
  55. package/dist/runtime-lifetime.d.ts +30 -0
  56. package/dist/runtime-lifetime.d.ts.map +1 -0
  57. package/dist/runtime-lifetime.js +201 -0
  58. package/dist/runtime-lifetime.js.map +1 -0
  59. package/dist/types/canonical-changes.d.ts +10 -9
  60. package/dist/types/canonical-changes.d.ts.map +1 -1
  61. package/dist/types/element-properties.d.ts +5 -3
  62. package/dist/types/element-properties.d.ts.map +1 -1
  63. package/dist/types/history.d.ts +4 -0
  64. package/dist/types/history.d.ts.map +1 -0
  65. package/dist/types/history.js +2 -0
  66. package/dist/types/history.js.map +1 -0
  67. package/dist/types/index.d.ts +3 -1
  68. package/dist/types/index.d.ts.map +1 -1
  69. package/dist/types/index.js.map +1 -1
  70. package/dist/types/load-migration.d.ts.map +1 -1
  71. package/dist/types/load-migration.js.map +1 -1
  72. package/dist/types/property-intents.d.ts +35 -0
  73. package/dist/types/property-intents.d.ts.map +1 -0
  74. package/dist/types/property-intents.js +2 -0
  75. package/dist/types/property-intents.js.map +1 -0
  76. package/dist/types/property-mutation-receipt.d.ts +6 -0
  77. package/dist/types/property-mutation-receipt.d.ts.map +1 -0
  78. package/dist/types/property-mutation-receipt.js +2 -0
  79. package/dist/types/property-mutation-receipt.js.map +1 -0
  80. package/dist/types/props.d.ts +2 -1
  81. package/dist/types/props.d.ts.map +1 -1
  82. package/dist/types/render.d.ts +5 -0
  83. package/dist/types/render.d.ts.map +1 -1
  84. package/dist/types/scene-tree.d.ts +6 -1
  85. package/dist/types/scene-tree.d.ts.map +1 -1
  86. package/dist/types/scene-tree.js +4 -1
  87. package/dist/types/scene-tree.js.map +1 -1
  88. package/dist/types/vector.d.ts.map +1 -1
  89. package/dist/types/vector.js.map +1 -1
  90. package/package.json +17 -17
package/dist/core.js CHANGED
@@ -1,14 +1,15 @@
1
- import { isRecord } from '@asyra/utils';
1
+ import { isRecord, idCounter } from '@asyra/utils';
2
2
  import factory from '@asyra/factory';
3
3
  import inputSystem from '@asyra/input-system';
4
4
  import sceneTree, { componentRegistry } from '@asyra/scene-tree';
5
5
  import props, { commitDeclarativePropertyTypeDefinition, getDeclarativePropertyTypeDefinition, getPropertyComponent, getPropertySchema, registerPropertySchema, registerPropertyComponent, unregisterPropertyRegistration, PropertyTypeDefinitionError } from '@asyra/props-manager';
6
- import { defineFeature as defineFeatureRuntime, getFeature as getFeatureRuntime, unregisterFeature as unregisterFeatureRuntime, getFeatureRegistry } from '@asyra/feature-system';
6
+ import { defineFeature as defineFeatureRuntime, getFeature as getFeatureRuntime, unregisterFeature as unregisterFeatureRuntime, getFeatureRegistry, disposeFeatureSystem, beginFeatureSystemRuntime } from '@asyra/feature-system';
7
7
  import selection from '@asyra/selection';
8
8
  import systemContext from '@asyra/system-context';
9
- import render, { RenderAdapter, MissingRenderEngineProviderError, renderStrategyRegistry } from '@asyra/render';
9
+ import render, { RenderAdapter, MissingRenderEngineProviderError, renderStrategyRegistry, resetSharedRenderRuntime, beginSharedRenderRuntime } from '@asyra/render';
10
10
  import { propertyRegistry } from '@asyra/ui-context';
11
11
  import { eventRegistry, fileLoadComplete, runInTransactionReplayMode, settleCooperativeRenderSlice } from '@asyra/reactive-events';
12
+ import { CoreRuntimeLifetime, CoreRuntimeResetError } from './runtime-lifetime.js';
12
13
  import { createAPIs } from './apis/index.js';
13
14
  import { LOAD_HOOK_EXECUTION_ERROR_CODES, LoadHookExecutionError } from './types/load-migration.js';
14
15
  import * as dataChannelObserver from './data-channel-observer.js';
@@ -52,6 +53,12 @@ class Core {
52
53
  });
53
54
  this.collaborationSession = null;
54
55
  this.collaborationDestroyPromise = null;
56
+ this.lifetime = new CoreRuntimeLifetime();
57
+ this.runtimeResetPromise = null;
58
+ this.runtimeCleanups = new Map();
59
+ this.ownedEvents = new Map();
60
+ this.ownedEventSubscriptions = new Set();
61
+ this.attachedCanvas = null;
55
62
  this.deps = deps;
56
63
  this.defaultRenderer = new RenderAdapter(deps.render);
57
64
  this.renderer = this.defaultRenderer;
@@ -96,6 +103,174 @@ class Core {
96
103
  this.ensureUIPropertyNode(key, config.registration);
97
104
  this.defineRegistrationRelations(source, config.registration);
98
105
  });
106
+ this.runtimeFacade = this.lifetime.facade(this);
107
+ return this.runtimeFacade;
108
+ }
109
+ getRuntimeState() {
110
+ return this.lifetime.state;
111
+ }
112
+ registerRuntimeCleanup(key, cleanup) {
113
+ this.lifetime.assertActive();
114
+ if (!key.trim() || this.runtimeCleanups.has(key)) {
115
+ throw new Error(`Core runtime cleanup key is empty or already registered: "${key}"`);
116
+ }
117
+ this.runtimeCleanups.set(key, cleanup);
118
+ let registered = true;
119
+ return () => {
120
+ if (!registered) {
121
+ return;
122
+ }
123
+ registered = false;
124
+ if (this.runtimeCleanups.get(key) === cleanup) {
125
+ this.runtimeCleanups.delete(key);
126
+ }
127
+ };
128
+ }
129
+ /** Terminal handoff; the App must stop admission and call outside Feature work. */
130
+ resetRuntime() {
131
+ if (this.runtimeResetPromise) {
132
+ return this.runtimeResetPromise;
133
+ }
134
+ try {
135
+ this.lifetime.assertResetReady();
136
+ }
137
+ catch (error) {
138
+ return Promise.reject(error);
139
+ }
140
+ this.lifetime.state = 'quiescing';
141
+ let complete = () => undefined;
142
+ let fail = () => undefined;
143
+ this.runtimeResetPromise = new Promise((resolve, reject) => {
144
+ complete = resolve;
145
+ fail = reject;
146
+ });
147
+ // Install the shared result before abort/disposal callbacks can reenter.
148
+ void this.performRuntimeReset().then(complete, fail);
149
+ return this.runtimeResetPromise;
150
+ }
151
+ async performRuntimeReset() {
152
+ let phase = 'quiescence';
153
+ try {
154
+ const settle = (operation) => {
155
+ try {
156
+ return Promise.resolve(operation());
157
+ }
158
+ catch (error) {
159
+ return Promise.reject(error);
160
+ }
161
+ };
162
+ const session = this.collaborationSession;
163
+ this.collaborationSession = null;
164
+ const quiescence = await Promise.allSettled([
165
+ settle(() => disposeFeatureSystem(() => this.getSystemContextSnapshot())),
166
+ settle(() => this.collaborationDestroyPromise ?? session?.dispose())
167
+ ]);
168
+ await this.lifetime.drain();
169
+ for (const result of quiescence) {
170
+ if (result.status === 'rejected') {
171
+ throw result.reason;
172
+ }
173
+ }
174
+ this.lifetime.state = 'retiring';
175
+ this.renderEngineProviderToken = null;
176
+ const retire = (owner, operation) => {
177
+ phase = owner;
178
+ operation();
179
+ };
180
+ retire('observers', () => this.dataChannelObservers.resetRuntime());
181
+ retire('events', () => this.retireOwnedEvents());
182
+ retire('input', () => this.deps.inputSystem.resetRuntime());
183
+ retire('render', () => {
184
+ if (this.renderer !== this.defaultRenderer) {
185
+ this.renderer.destroy();
186
+ }
187
+ this.deps.render.resetRuntime();
188
+ this.attachedCanvas?.remove();
189
+ this.attachedCanvas = null;
190
+ });
191
+ retire('shared-render', resetSharedRenderRuntime);
192
+ retire('factory', () => this.deps.factory.resetRuntime());
193
+ retire('scene', () => this.deps.sceneTree.resetRuntime());
194
+ retire('props', () => this.deps.props.resetRuntime());
195
+ retire('selection', () => this.deps.selection.resetRuntime());
196
+ retire('system-context', () => this.deps.systemContext.resetRuntime());
197
+ retire('ui-context', () => propertyRegistry.resetRuntime());
198
+ retire('registrations', () => this.registrationGraph.disposeRuntime());
199
+ phase = 'composition';
200
+ const cleanups = [...this.runtimeCleanups.values()].reverse();
201
+ this.runtimeCleanups.clear();
202
+ const failures = [];
203
+ this.lifetime.cleanupActive = true;
204
+ try {
205
+ for (const cleanup of cleanups) {
206
+ try {
207
+ await cleanup();
208
+ }
209
+ catch (error) {
210
+ failures.push(error);
211
+ }
212
+ }
213
+ }
214
+ finally {
215
+ this.lifetime.cleanupActive = false;
216
+ }
217
+ if (failures.length > 0) {
218
+ throw failures[0];
219
+ }
220
+ this.loadSource = null;
221
+ this.saveHooks = [];
222
+ this.loadHooks = [];
223
+ this.loadDiagnosticsHooks = [];
224
+ this.redefinedPropertyTypes.clear();
225
+ phase = 'successor';
226
+ const successor = new Core({
227
+ ...this.deps,
228
+ dataChannelObservers: this.dataChannelObservers
229
+ });
230
+ beginFeatureSystemRuntime();
231
+ beginSharedRenderRuntime();
232
+ this.lifetime.state = 'retired';
233
+ if (core === this.runtimeFacade) {
234
+ core = successor;
235
+ }
236
+ return successor;
237
+ }
238
+ catch (cause) {
239
+ this.lifetime.state = 'failed';
240
+ if (phase === 'successor') {
241
+ // A failed begin must not leave a newly opened Feature queue accepting work.
242
+ await Promise.resolve(disposeFeatureSystem(() => this.getSystemContextSnapshot())).catch(() => undefined);
243
+ }
244
+ throw new CoreRuntimeResetError(phase, cause);
245
+ }
246
+ }
247
+ retireOwnedEvents() {
248
+ const subscriptions = [...this.ownedEventSubscriptions];
249
+ this.ownedEventSubscriptions.clear();
250
+ const events = [...this.ownedEvents];
251
+ this.ownedEvents.clear();
252
+ const failures = [];
253
+ for (const subscription of subscriptions) {
254
+ try {
255
+ subscription.unsubscribe();
256
+ }
257
+ catch (error) {
258
+ failures.push(error);
259
+ }
260
+ }
261
+ for (const [name, registration] of events) {
262
+ try {
263
+ if (eventRegistry.get(name) === registration) {
264
+ eventRegistry.unregister(name);
265
+ }
266
+ }
267
+ catch (error) {
268
+ failures.push(error);
269
+ }
270
+ }
271
+ if (failures.length > 0) {
272
+ throw failures[0];
273
+ }
99
274
  }
100
275
  /** Set an advanced full renderer replacement before startup. */
101
276
  setRenderer(renderer) {
@@ -140,22 +315,64 @@ class Core {
140
315
  this.deps.inputSystem.registry.registerKeyCombinations(combinations);
141
316
  const eventNames = Object.keys(combinations);
142
317
  let disposed = false;
143
- return () => {
144
- if (disposed)
318
+ return this.lifetime.cleanup(() => {
319
+ if (disposed) {
145
320
  return;
321
+ }
146
322
  disposed = true;
147
323
  eventNames.forEach((eventName) => {
148
324
  this.deps.inputSystem.registry.unregister(eventName);
149
325
  });
150
- };
326
+ });
151
327
  }
152
328
  getElementData(elementId) {
153
329
  const data = this.deps.sceneTree.getElementById(elementId)?.save();
154
330
  return data === undefined ? undefined : cloneLoadObservation(data);
155
331
  }
332
+ getElementMetadata(elementId) {
333
+ const element = this.deps.sceneTree.getElementById(elementId);
334
+ if (!element) {
335
+ return undefined;
336
+ }
337
+ const type = element.get('type');
338
+ const childCount = this.isContainerType(type)
339
+ ? element.getCanonicalChildCount()
340
+ : 0;
341
+ return {
342
+ id: element.get('id'),
343
+ type,
344
+ name: element.get('name'),
345
+ parentId: element.get('parentId'),
346
+ visible: element.get('visible'),
347
+ lock: element.get('lock'),
348
+ childCount
349
+ };
350
+ }
351
+ getElementChildren(elementId, offset = 0, limit = 50) {
352
+ if (!Number.isSafeInteger(offset) ||
353
+ offset < 0 ||
354
+ !Number.isSafeInteger(limit) ||
355
+ limit < 1) {
356
+ throw new Error('Child page requires a nonnegative offset and positive limit');
357
+ }
358
+ const element = this.deps.sceneTree.getElementById(elementId);
359
+ const children = element && this.isContainerType(element.get('type'))
360
+ ? element.get('children')
361
+ : [];
362
+ return {
363
+ available: Boolean(element),
364
+ elementIds: children.slice(offset, offset + limit),
365
+ total: children.length,
366
+ nextOffset: offset + limit < children.length ? offset + limit : null
367
+ };
368
+ }
156
369
  getCurrentWorkspaceId() {
157
370
  return this.deps.sceneTree.workspace;
158
371
  }
372
+ /** Reserves identities only; does not create elements or document history. */
373
+ allocateIds(types) {
374
+ return idCounter.allocate(types);
375
+ }
159
376
  getAllElementData() {
160
377
  return Object.freeze([...this.deps.sceneTree.getAllElements().entries()].map(([elementId, element]) => Object.freeze({
161
378
  elementId,
@@ -173,6 +390,23 @@ class Core {
173
390
  sceneTree: this.deps.sceneTree.save()
174
391
  });
175
392
  }
393
+ /** Resolve affected elements through canonical nested/shared property indexes. */
394
+ getPropertyOwnerElementIds(propertyIds, options) {
395
+ const elementIds = new Set();
396
+ const componentIds = new Set(propertyIds);
397
+ const activeIds = options?.includeRetired
398
+ ? [...componentIds].filter((id) => this.deps.props.getPropertyById(id))
399
+ : [...componentIds];
400
+ for (const id of this.deps.props.resolvePropertyAncestorIds(activeIds)) {
401
+ componentIds.add(id);
402
+ }
403
+ for (const propertyId of componentIds) {
404
+ for (const relation of this.deps.sceneTree.getElementPropertyRelations(propertyId)) {
405
+ elementIds.add(relation.ownerElementId);
406
+ }
407
+ }
408
+ return [...elementIds];
409
+ }
176
410
  projectLocalComputedDataForElements(elementIds) {
177
411
  const propertyIds = new Set();
178
412
  elementIds.forEach((elementId) => {
@@ -206,13 +440,23 @@ class Core {
206
440
  getSystemContextSnapshot() {
207
441
  return cloneLoadObservation(this.deps.systemContext.getSystemContextSnapshot());
208
442
  }
443
+ resizeRenderer(width, height) {
444
+ if (!Number.isFinite(width) ||
445
+ !Number.isFinite(height) ||
446
+ width <= 0 ||
447
+ height <= 0) {
448
+ throw new RangeError('Renderer size must be finite and positive');
449
+ }
450
+ this.renderer.resize(width, height);
451
+ }
209
452
  getCanvas() {
210
453
  return this.renderer.getCanvas();
211
454
  }
212
455
  setCanvasCursor(cursor) {
213
456
  const canvas = this.getCanvas();
214
- if (!canvas)
457
+ if (!canvas) {
215
458
  return false;
459
+ }
216
460
  canvas.style.cursor = cursor;
217
461
  return true;
218
462
  }
@@ -220,7 +464,10 @@ class Core {
220
464
  return this.getCanvas()?.getBoundingClientRect() ?? null;
221
465
  }
222
466
  getViewportPosition() {
223
- return cloneLoadObservation(this.deps.render.getViewportPosition());
467
+ const position = this.deps.render.getViewportPosition();
468
+ // Engine positions may carry callbacks. The public contract is coordinate
469
+ // data only, detached from the live engine object on every read.
470
+ return { x: position.x, y: position.y };
224
471
  }
225
472
  getViewportScale() {
226
473
  return this.deps.render.getViewportScale();
@@ -231,6 +478,24 @@ class Core {
231
478
  workspaceToCanvas(workspacePosition) {
232
479
  return cloneLoadObservation(this.deps.render.workspaceToCanvas(workspacePosition));
233
480
  }
481
+ projectSpatialPoint(point) {
482
+ return this.deps.render.projectSpatialPoint(point);
483
+ }
484
+ getSpatialRayAtClientPoint(point) {
485
+ return this.deps.render.getSpatialRayAtClientPoint(point);
486
+ }
487
+ raycastSpatial(ray) {
488
+ return this.deps.render.raycastSpatial(ray);
489
+ }
490
+ convertSpatialPoint(visualId, point, to, instanceIndex) {
491
+ return this.deps.render.convertSpatialPoint(visualId, point, to, instanceIndex);
492
+ }
493
+ getSpatialBounds(visualId, space, instanceIndex) {
494
+ return this.deps.render.getSpatialBounds(visualId, space, instanceIndex);
495
+ }
496
+ pickSpatialAtClientPoint(point) {
497
+ return this.deps.render.pickSpatialAtClientPoint(point);
498
+ }
234
499
  getElementIdAtClientPos(clientPos) {
235
500
  return this.deps.render.getElementIdAtClientPos(clientPos);
236
501
  }
@@ -253,19 +518,38 @@ class Core {
253
518
  return this.deps.render.getElementById(elementId) !== undefined;
254
519
  }
255
520
  subscribeToFrameComplete(subscriber) {
256
- return this.deps.render.subscribeToFrameComplete(subscriber);
521
+ return this.lifetime.cleanup(this.deps.render.subscribeToFrameComplete(() => {
522
+ if (this.lifetime.isUsable()) {
523
+ subscriber();
524
+ }
525
+ }));
526
+ }
527
+ isInUndoRedo() {
528
+ return this.deps.factory.isInUndoRedo();
257
529
  }
258
530
  getUndoHistoryDepth() {
259
531
  return this.deps.factory.getUndoHistoryDepth();
260
532
  }
261
533
  subscribeToSharedPublication(subscriber) {
262
- return this.deps.factory.subscribeToSharedPublication(subscriber);
534
+ return this.lifetime.cleanup(this.deps.factory.subscribeToSharedPublication((publication) => {
535
+ if (this.lifetime.isUsable()) {
536
+ subscriber(publication);
537
+ }
538
+ }));
263
539
  }
264
540
  subscribeToTransactionStatus(subscriber) {
265
- return this.deps.factory.subscribeToTransactionStatus(subscriber);
541
+ return this.lifetime.cleanup(this.deps.factory.subscribeToTransactionStatus((status) => {
542
+ if (this.lifetime.isUsable()) {
543
+ subscriber(status);
544
+ }
545
+ }));
266
546
  }
267
547
  observeSharedDataChannel(channel, subscriber) {
268
- return this.deps.factory.observeSharedDataChannel(channel, subscriber);
548
+ return this.lifetime.cleanup(this.deps.factory.observeSharedDataChannel(channel, (change) => {
549
+ if (this.lifetime.isUsable()) {
550
+ subscriber(change);
551
+ }
552
+ }));
269
553
  }
270
554
  configureSharedDeliverySequence(sequence) {
271
555
  const controller = this.deps.factory.getActiveStagedDeliveryController();
@@ -275,8 +559,9 @@ class Core {
275
559
  controller.setDeliverySequence(sequence);
276
560
  }
277
561
  async applyRemoteCanonicalChangeSlices({ origin, slices }) {
278
- if (slices.length === 0)
562
+ if (slices.length === 0) {
279
563
  return;
564
+ }
280
565
  let replayMode = null;
281
566
  if (origin === 'undo' || origin === 'redo') {
282
567
  replayMode = origin;
@@ -301,9 +586,9 @@ class Core {
301
586
  }
302
587
  createCollaborationBridge() {
303
588
  const bridge = {
304
- applyRemoteCanonicalChangeSlices: (input) => this.applyRemoteCanonicalChangeSlices(input),
305
- load: (data) => this.load(data),
306
- subscribeToSharedPublication: (subscriber) => this.subscribeToSharedPublication(subscriber)
589
+ applyRemoteCanonicalChangeSlices: (input) => this.runtimeFacade.applyRemoteCanonicalChangeSlices(input),
590
+ load: (data) => this.runtimeFacade.load(data),
591
+ subscribeToSharedPublication: (subscriber) => this.runtimeFacade.subscribeToSharedPublication(subscriber)
307
592
  };
308
593
  return Object.freeze(bridge);
309
594
  }
@@ -430,7 +715,10 @@ class Core {
430
715
  result = { canvas: null, instance: null };
431
716
  }
432
717
  if (result.canvas && container) {
433
- container.appendChild(result.canvas);
718
+ if (container !== result.canvas) {
719
+ container.appendChild(result.canvas);
720
+ this.attachedCanvas = result.canvas;
721
+ }
434
722
  // Setup input system to watch the canvas
435
723
  this.setupInputSystem(result.canvas);
436
724
  }
@@ -464,18 +752,41 @@ class Core {
464
752
  this.load(data);
465
753
  }
466
754
  registerEvent(event) {
467
- return eventRegistry.register(event);
755
+ const registration = eventRegistry.register(event);
756
+ this.ownedEvents.set(registration.eventName, registration);
757
+ return {
758
+ eventName: registration.eventName,
759
+ publish: (payload, options) => {
760
+ this.lifetime.assertActive();
761
+ registration.publish(payload, options);
762
+ },
763
+ subscribe: (handler) => {
764
+ this.lifetime.assertActive();
765
+ return this.subscribeOwnedEvent(registration, handler);
766
+ }
767
+ };
468
768
  }
469
769
  unregisterEvent(event) {
770
+ this.ownedEvents.delete(typeof event === 'string' ? event : event.eventName);
470
771
  return eventRegistry.unregister(event);
471
772
  }
773
+ subscribeOwnedEvent(registration, handler) {
774
+ const subscription = registration.subscribe((payload, options) => {
775
+ if (this.lifetime.isUsable()) {
776
+ handler(payload, options);
777
+ }
778
+ });
779
+ this.ownedEventSubscriptions.add(subscription);
780
+ subscription.add(() => this.ownedEventSubscriptions.delete(subscription));
781
+ return subscription;
782
+ }
472
783
  subscribeEvent(event, handler) {
473
784
  const eventName = typeof event === 'string' ? event : event.eventName;
474
785
  const registration = eventRegistry.get(event);
475
786
  if (!registration) {
476
787
  throw new Error(`[Core] Event "${eventName}" is not registered. Register it before subscribing.`);
477
788
  }
478
- const subscription = registration.subscribe(handler);
789
+ const subscription = this.subscribeOwnedEvent(registration, handler);
479
790
  return () => subscription.unsubscribe();
480
791
  }
481
792
  registerPropertySchema(schema, options, registration) {
@@ -719,12 +1030,12 @@ class Core {
719
1030
  this.ensureFeatureNode(name, definition.registration);
720
1031
  this.defineRegistrationRelations(source, definition.registration);
721
1032
  return {
722
- api: registration.api,
723
- dispose: () => this.unregisterFeature(name)
1033
+ api: this.lifetime.featureAPI(registration.api),
1034
+ dispose: () => this.lifetime.isUsable() ? this.unregisterFeature(name) : false
724
1035
  };
725
1036
  }
726
1037
  getFeature(featureName) {
727
- return getFeatureRuntime(featureName);
1038
+ return this.lifetime.featureAPI(getFeatureRuntime(featureName));
728
1039
  }
729
1040
  unregisterFeature(featureName) {
730
1041
  this.assertCompositionOpen('unregister-registration');
@@ -850,29 +1161,33 @@ class Core {
850
1161
  ]);
851
1162
  const aliasIsProjected = (alias) => {
852
1163
  const field = fieldsByKey.get(alias);
853
- if (field)
1164
+ if (field) {
854
1165
  return field.project;
1166
+ }
855
1167
  return definition.allowDynamicKeys && !dynamicReservedKeys.has(alias);
856
1168
  };
857
1169
  this.registrationGraph
858
1170
  .getIncomingRelations(target)
859
1171
  .forEach((relation) => {
860
- if (relation.source.kind !== 'component')
1172
+ if (relation.source.kind !== 'component') {
861
1173
  return;
1174
+ }
862
1175
  const componentRelation = getComponentPropertyRelationsRuntime(relation.source.key).find((candidate) => candidate.name === relation.name &&
863
1176
  candidate.property.type === type);
864
1177
  if (!componentRelation) {
865
1178
  this.failStructuralPropertyRelation(relation.source, relation.name, target, `Component property relation "${relation.source.key}/${relation.name}" no longer resolves to "${type}"`);
866
1179
  }
867
1180
  componentRelation.property.alias?.forEach((alias) => {
868
- if (aliasIsProjected(alias))
1181
+ if (aliasIsProjected(alias)) {
869
1182
  return;
1183
+ }
870
1184
  this.failStructuralPropertyRelation(relation.source, relation.name, target, `Component property alias "${relation.source.key}/${relation.name}.${alias}" is not projected by "${type}"`);
871
1185
  });
872
1186
  });
873
1187
  getPropertyChildRelationsRuntime(type).forEach((relation) => {
874
- if (fieldsByKey.get(relation.key)?.project)
1188
+ if (fieldsByKey.get(relation.key)?.project) {
875
1189
  return;
1190
+ }
876
1191
  this.failStructuralPropertyRelation(relation.source, relation.name, relation.target, `Property child key "${type}.${relation.key}" is not projected by its redefined type`);
877
1192
  });
878
1193
  });
@@ -962,8 +1277,9 @@ class Core {
962
1277
  }
963
1278
  }
964
1279
  preflightRegistrationDefinition(source, registration, reservedRelationNames = []) {
965
- if (!registration?.relations?.length)
1280
+ if (!registration?.relations?.length) {
966
1281
  return;
1282
+ }
967
1283
  const relationNames = new Set([
968
1284
  ...reservedRelationNames,
969
1285
  ...this.registrationGraph
@@ -998,8 +1314,9 @@ class Core {
998
1314
  });
999
1315
  }
1000
1316
  assertRelationEndpointNotPending(ref, operation, source, relationName, target) {
1001
- if (!this.registrationGraph.hasPendingCleanup(ref))
1317
+ if (!this.registrationGraph.hasPendingCleanup(ref)) {
1002
1318
  return;
1319
+ }
1003
1320
  throw new RegistrationRelationError({
1004
1321
  ok: false,
1005
1322
  code: 'UNREGISTER_FAILED',
@@ -1116,8 +1433,9 @@ class Core {
1116
1433
  }
1117
1434
  assertPropertyTypeUnused(type) {
1118
1435
  const propertyIds = this.deps.props.getPropertyIdsByType(type);
1119
- if (propertyIds.length === 0)
1436
+ if (propertyIds.length === 0) {
1120
1437
  return;
1438
+ }
1121
1439
  throw new RegistrationRelationError({
1122
1440
  ok: false,
1123
1441
  code: 'REGISTRATION_IN_USE',
@@ -1129,11 +1447,13 @@ class Core {
1129
1447
  assertComponentTypeUnused(type) {
1130
1448
  const activeIds = [];
1131
1449
  this.deps.sceneTree.getAllElements().forEach((element) => {
1132
- if (element.get('type') === type)
1450
+ if (element.get('type') === type) {
1133
1451
  activeIds.push(element.get('id'));
1452
+ }
1134
1453
  });
1135
- if (activeIds.length === 0)
1454
+ if (activeIds.length === 0) {
1136
1455
  return;
1456
+ }
1137
1457
  throw new RegistrationRelationError({
1138
1458
  ok: false,
1139
1459
  code: 'REGISTRATION_IN_USE',
@@ -1148,8 +1468,17 @@ class Core {
1148
1468
  }
1149
1469
  this.applyLoadedData(data);
1150
1470
  }
1471
+ /** Validate against the current composition without applying a document. */
1472
+ preflightLoad(data) {
1473
+ if (data == null) {
1474
+ return Object.freeze([]);
1475
+ }
1476
+ const { diagnostics } = this.prepareLoadedData(data);
1477
+ return Object.freeze(diagnostics.map((item) => Object.freeze({ ...item })));
1478
+ }
1151
1479
  async save() {
1152
- const sceneTreeData = await this.sceneTreeSaveData();
1480
+ // Capture the document in the calling turn, including during pagehide.
1481
+ const sceneTreeData = this.sceneTreeSaveData();
1153
1482
  const systemContextData = this.deps.systemContext.saveManagedProperties();
1154
1483
  let data = {
1155
1484
  version: this.version,
@@ -1232,7 +1561,7 @@ class Core {
1232
1561
  }
1233
1562
  return nextData;
1234
1563
  }
1235
- applyLoadedData(rawData) {
1564
+ prepareLoadedData(rawData) {
1236
1565
  const diagnostics = [];
1237
1566
  const migrated = this.runLoadHooks(rawData);
1238
1567
  const normalizedAfterHooks = this.normalizeLoadData(migrated, diagnostics, this.loadHooks.length > 0 ? 'core.hooks' : 'core.input');
@@ -1255,9 +1584,22 @@ class Core {
1255
1584
  message: item.message
1256
1585
  })));
1257
1586
  if (sceneValidation.valid === false) {
1258
- throw new Error('[Core] Scene Tree rejected invalid hierarchy before package apply');
1587
+ throw new Error('[Core] Scene Tree rejected invalid hierarchy before package apply: ' +
1588
+ sceneValidation.diagnostics
1589
+ .map(({ path, message }) => `${path}: ${message}`)
1590
+ .join('; '));
1259
1591
  }
1260
1592
  this.deps.sceneTree.preflightLoadPropertyRelations(sceneValidation, propsValidation.data);
1593
+ return {
1594
+ normalizedAfterHooks,
1595
+ diagnostics,
1596
+ propsValidation,
1597
+ sceneValidation,
1598
+ systemValidation
1599
+ };
1600
+ }
1601
+ applyLoadedData(rawData) {
1602
+ const { normalizedAfterHooks, diagnostics, propsValidation, sceneValidation, systemValidation } = this.prepareLoadedData(rawData);
1261
1603
  this.deps.props.applyValidatedLoad(propsValidation);
1262
1604
  this.deps.sceneTree.applyValidatedLoad(sceneValidation);
1263
1605
  this.deps.systemContext.applyValidatedManagedProperties(systemValidation);
@@ -1300,7 +1642,7 @@ class Core {
1300
1642
  }
1301
1643
  }
1302
1644
  export { Core };
1303
- const core = new Core({
1645
+ let core = new Core({
1304
1646
  inputSystem,
1305
1647
  factory,
1306
1648
  dataChannelObservers: dataChannelObserver.getDefaultDataChannelObserverRegistry(),
@@ -1310,5 +1652,5 @@ const core = new Core({
1310
1652
  selection,
1311
1653
  systemContext
1312
1654
  });
1313
- export default core;
1655
+ export { core as default };
1314
1656
  //# sourceMappingURL=core.js.map