@relu-interactives/spatial-ecs 0.2.20 → 0.2.21

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 (41) hide show
  1. package/dist/{System-BjwOBx81.d.cts → System-me3iAcMF.d.cts} +5 -1
  2. package/dist/{System-BjwOBx81.d.ts → System-me3iAcMF.d.ts} +5 -1
  3. package/dist/{Video-B9z5AtIf.d.ts → Video-DHnxjGhW.d.ts} +1 -1
  4. package/dist/{Video-B8yVI1tF.d.cts → Video-U9hAnf9y.d.cts} +1 -1
  5. package/dist/{chunk-67MFQDHX.js → chunk-5U3YS4JD.js} +196 -33
  6. package/dist/chunk-5U3YS4JD.js.map +1 -0
  7. package/dist/{chunk-DY4ETMP2.js → chunk-AXRCGF63.js} +3 -3
  8. package/dist/{chunk-DY4ETMP2.js.map → chunk-AXRCGF63.js.map} +1 -1
  9. package/dist/{chunk-HUHN6IFD.js → chunk-K6KMKKJ6.js} +4 -4
  10. package/dist/{chunk-HUHN6IFD.js.map → chunk-K6KMKKJ6.js.map} +1 -1
  11. package/dist/{chunk-Z6OMYEXU.js → chunk-V7BNVTJW.js} +11 -3
  12. package/dist/chunk-V7BNVTJW.js.map +1 -0
  13. package/dist/components/index.cjs +9 -1
  14. package/dist/components/index.cjs.map +1 -1
  15. package/dist/components/index.d.cts +3 -3
  16. package/dist/components/index.d.ts +3 -3
  17. package/dist/components/index.js +1 -1
  18. package/dist/docs/guide/prefabs.md +24 -5
  19. package/dist/factories/index.d.cts +2 -2
  20. package/dist/factories/index.d.ts +2 -2
  21. package/dist/factories/index.js +3 -3
  22. package/dist/{index-LHLKpJhZ.d.cts → index-CZo5I5Gs.d.cts} +29 -13
  23. package/dist/{index-BBI2YdCu.d.ts → index-D7FSg0Au.d.ts} +29 -13
  24. package/dist/index.cjs +458 -40
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +108 -10
  27. package/dist/index.d.ts +108 -10
  28. package/dist/index.js +249 -11
  29. package/dist/index.js.map +1 -1
  30. package/dist/systems/index.cjs +26 -7
  31. package/dist/systems/index.cjs.map +1 -1
  32. package/dist/systems/index.d.cts +2 -2
  33. package/dist/systems/index.d.ts +2 -2
  34. package/dist/systems/index.js +3 -3
  35. package/dist/types.d.cts +1 -1
  36. package/dist/types.d.ts +1 -1
  37. package/dist/worldSnapshotUtils.d.cts +1 -1
  38. package/dist/worldSnapshotUtils.d.ts +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-67MFQDHX.js.map +0 -1
  41. package/dist/chunk-Z6OMYEXU.js.map +0 -1
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
1
- import { k as EcsSystem, C as Component, W as WorldEntityView, T as TransformComponent, l as World, S as SpawnPrefabSource, m as SpawnPrefabOptions, n as ComponentClass, o as ParentLookup, p as EcsEntityKind, O as ObjectManagementSystem, q as EntityId, r as SubtreeSnapshot, s as ExternalRefWarning } from './System-BjwOBx81.cjs';
2
- export { A as AssetInput, t as CheckboxInput, u as ColorInput, v as ComponentFactory, w as ComponentInput, x as ComponentKind, y as DropdownInput, z as DropdownOption, B as EcsComponentFactoryKind, F as EcsEntityEditorKind, G as EntityInput, H as FloatInput, I as InputSystem, J as IntersectionResult, K as KeyboardKey, L as KeyboardKeys, M as MouseButton, N as PREFAB_FILE_VERSION, Q as PrefabAsset, R as RemapSnapshotOptions, U as RenderSystem, X as SelectionListener, Y as SliderInput, Z as TextInput, _ as ToggleInput, $ as TransformSyncSystem, a0 as Vec3, a1 as Vector2Input, a2 as Vector3Input, a3 as clearPrefabCache, a4 as despawnPrefab, a5 as loadPrefab, a6 as parsePrefabAsset, a7 as remapSnapshotEntityIds, a8 as setPrefabAssetUrlResolver, a9 as spawnPrefab } from './System-BjwOBx81.cjs';
1
+ import { k as EcsSystem, C as Component, W as WorldEntityView, T as TransformComponent, l as World, S as SpawnPrefabSource, m as SpawnPrefabOptions, n as ComponentClass, o as ParentLookup, p as EcsEntityKind, O as ObjectManagementSystem, q as SubtreeSnapshot, r as EntityId, s as ExternalRefWarning } from './System-me3iAcMF.cjs';
2
+ export { A as AssetInput, t as CheckboxInput, u as ColorInput, v as ComponentFactory, w as ComponentInput, x as ComponentKind, y as DropdownInput, z as DropdownOption, B as EcsComponentFactoryKind, F as EcsEntityEditorKind, G as EntityInput, H as FloatInput, I as InputSystem, J as IntersectionResult, K as KeyboardKey, L as KeyboardKeys, M as MouseButton, N as PREFAB_FILE_VERSION, Q as PREFAB_FILE_VERSION_NESTED, R as PrefabAsset, U as RemapSnapshotOptions, X as RenderSystem, Y as SelectionListener, Z as SliderInput, _ as TextInput, $ as ToggleInput, a0 as TransformSyncSystem, a1 as Vec3, a2 as Vector2Input, a3 as Vector3Input, a4 as clearPrefabCache, a5 as despawnPrefab, a6 as loadPrefab, a7 as parsePrefabAsset, a8 as prefabFileVersionFor, a9 as remapSnapshotEntityIds, aa as setPrefabAssetUrlResolver, ab as spawnPrefab } from './System-me3iAcMF.cjs';
3
3
  import * as THREE from 'three';
4
- import { O as Object3DRef } from './Video-B8yVI1tF.cjs';
5
- export { a3 as AnimationStateCallbacks, a4 as AnimationStateMachine, a5 as AnimationStateManager, a6 as StateMachine } from './Video-B8yVI1tF.cjs';
6
- export { i as CoreComponents } from './index-LHLKpJhZ.cjs';
4
+ import { O as Object3DRef } from './Video-U9hAnf9y.cjs';
5
+ export { a3 as AnimationStateCallbacks, a4 as AnimationStateMachine, a5 as AnimationStateManager, a6 as StateMachine } from './Video-U9hAnf9y.cjs';
6
+ export { i as CoreComponents } from './index-CZo5I5Gs.cjs';
7
7
  export { AnimationSystem, AudioSystem, CameraSyncSystem, EnvironmentSyncSystem, InstancedMeshSystem, LightSyncSystem, MaterialSyncSystem, MeshGeometrySystem, ObjectVisibilitySystem, PhysicsSyncSystem, PostprocessingSyncSystem, ScriptBehaviourSystem, SelectionContext, VideoSystem } from './systems/index.cjs';
8
8
  export { createAnimationComponent, createAudioComponent, createCameraComponent, createEntityTypeComponent, createEnvironmentComponent, createImageComponent, createImageTargetAnchorComponent, createImageTargetComponent, createInstanceSlotComponent, createInstancedMeshComponent, createLightComponent, createMaterialComponent, createMeshComponent, createMeshGeometryComponent, createModelComponent, createNameComponent, createObject3DRefComponent, createParentIdComponent, createPhysicsComponent, createPostprocessingComponent, createScriptComponent, createSelectableComponent, createSelectionTransformStateComponent, createSpriteComponent, createTransformComponent, createVideoComponent, registerDefaultComponentFactories, registerDefaultFactories } from './factories/index.cjs';
9
9
  import { GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js';
@@ -390,6 +390,30 @@ declare function loadSharedGltf(url: string, load: () => Promise<GLTF>): Promise
390
390
  */
391
391
  declare function clearModelCache(url?: string): void;
392
392
 
393
+ /**
394
+ * Pure JSON-space prefab patching: apply a nested prefab's NEW definition to
395
+ * every top-level-relative instance region inside a HOST document snapshot,
396
+ * honoring the region's stored per-property overrides. This is how edits to
397
+ * a child prefab cascade through the `.prefab` files that nest it (no live
398
+ * world exists for files). Reused later by `.scene` assets.
399
+ *
400
+ * Trust model: the region's stored override list (refreshed at every host
401
+ * save with `+node` addition markers) IS the user state — no old base is
402
+ * needed. Consequently the operation is idempotent: re-applying the same
403
+ * definition yields `changed: false`.
404
+ */
405
+
406
+ type ApplyPrefabToSnapshotResult = {
407
+ snapshot: SubtreeSnapshot;
408
+ changed: boolean;
409
+ };
410
+ /**
411
+ * Patch every top-level-relative nested instance of `nestedUrl` inside
412
+ * `hostSnapshot` with `newNestedSnapshot`. Deeper nesting (B inside C inside
413
+ * A) is NOT touched here — it cascades through C's own file.
414
+ */
415
+ declare function applyPrefabToSnapshotInstances(hostSnapshot: SubtreeSnapshot, nestedUrl: string, newNestedSnapshot: SubtreeSnapshot): ApplyPrefabToSnapshotResult;
416
+
393
417
  /**
394
418
  * Collect the given roots plus every descendant, BFS parent-first, using the
395
419
  * `ParentId` component edges. Parent-first ordering matters: serialization
@@ -398,6 +422,71 @@ declare function clearModelCache(url?: string): void;
398
422
  */
399
423
  declare function collectEntitySubtree(world: World, rootIds: EntityId[]): EntityId[];
400
424
 
425
+ /**
426
+ * Direct (top-level-relative) prefab urls a document depends on — the edges
427
+ * of the nesting graph. Deeper nesting is reached transitively through each
428
+ * dependency's own file, never directly.
429
+ */
430
+ declare function collectDirectPrefabDependencies(snapshot: SubtreeSnapshot): string[];
431
+
432
+ /**
433
+ * Scoped node identity for (possibly nested) prefab documents.
434
+ *
435
+ * A nodeKey identifies an entity within one prefab document even when the
436
+ * document contains nested instances of other prefabs (whose nodeIds repeat
437
+ * per instance). Formula (parent-first walk from the scope root, inherited
438
+ * `prefix`; the scope root's prefix is "" even if it carries PrefabInstance):
439
+ *
440
+ * - entity WITHOUT PrefabInstance: key = prefix + nodeId, children inherit
441
+ * the same prefix;
442
+ * - entity WITH PrefabInstance (non-scope-root): childPrefix = prefix +
443
+ * instanceId + "/"; key = childPrefix + nodeId (self-inclusive — sibling
444
+ * instances of the SAME prefab get distinct keys); children inherit
445
+ * childPrefix.
446
+ *
447
+ * Documents with no nested instances degenerate to bare nodeIds, so v1 files
448
+ * and override lists keep their exact meaning.
449
+ */
450
+
451
+ declare const NODE_KEY_SEPARATOR = "/";
452
+ /**
453
+ * Reserved override "component" marking a node ADDED by the host document
454
+ * inside a nested instance region (`"<nodeKey>|+node|"`). File patching
455
+ * trusts stored overrides (the old base is unavailable), so without the
456
+ * marker a host-authored node inside the region would be indistinguishable
457
+ * from a node the child prefab removed — and get deleted.
458
+ */
459
+ declare const ADDED_NODE_MARKER_COMPONENT = "+node";
460
+ type NodeKeyMaps = {
461
+ idToKey: Map<number, string>;
462
+ keyToId: Map<string, number>;
463
+ /** nodeKey of the scope root (bare nodeId), or null when it has none. */
464
+ rootKey: string | null;
465
+ /** Entity ids of NESTED instance roots (non-scope-root PrefabInstance). */
466
+ boundaryIds: Map<number, {
467
+ url: string;
468
+ instanceId: string;
469
+ }>;
470
+ };
471
+ declare function buildNodeKeyMapsFromSnapshot(snapshot: SubtreeSnapshot, options?: {
472
+ scopeRootEntityId?: number;
473
+ }): NodeKeyMaps;
474
+ /** JSON-space subtree ids (root first, BFS) via ParentId edges. */
475
+ declare function collectSnapshotSubtreeIds(snapshot: SubtreeSnapshot, rootEntityId: number): number[];
476
+ type NestedRegion = {
477
+ rootEntityId: number;
478
+ url: string;
479
+ instanceId: string;
480
+ overrides: string[];
481
+ };
482
+ /**
483
+ * TOP-LEVEL-RELATIVE nested instance regions of a document: instance roots
484
+ * that are not the scope root and not themselves inside another region.
485
+ * Deeper nesting is reached by cascading through the intermediate prefab's
486
+ * own file, never directly.
487
+ */
488
+ declare function findTopLevelNestedRegions(snapshot: SubtreeSnapshot): NestedRegion[];
489
+
401
490
  type InstantiateSubtreeResult = {
402
491
  /** Live entity id of the subtree root, or null when nothing hydrated. */
403
492
  rootId: EntityId | null;
@@ -485,11 +574,20 @@ declare function collectDiffPaths(base: unknown, current: unknown, prefix?: stri
485
574
  * subtree snapshots carrying PrefabNode identity) and return the encoded
486
575
  * override list: every path where the instance deviates from the base.
487
576
  *
488
- * v1 policies: components missing on the instance produce no override
489
- * (apply re-adds them); components/nodes only on the instance are local
490
- * additions and produce no override (apply never touches them).
577
+ * Identity is nodeKey-scoped ({@link buildNodeKeyMapsFromSnapshot}), so
578
+ * nested instance regions diff correctly; for nested-free documents the
579
+ * keys degenerate to bare nodeIds (v1 behavior unchanged).
580
+ *
581
+ * Policies: components missing on the instance produce no override (apply
582
+ * re-adds them); components/nodes only on the instance are local additions
583
+ * and produce no override — EXCEPT when `emitAdditionMarkers` is set
584
+ * (file-space callers), which records `"<key>|+node|"` for instance nodes
585
+ * absent from the base so pure-JSON patching never deletes host-authored
586
+ * nodes inside nested regions.
491
587
  */
492
- declare function computeInstanceOverrides(baseSnapshot: SubtreeSnapshot, instanceSnapshot: SubtreeSnapshot): string[];
588
+ declare function computeInstanceOverrides(baseSnapshot: SubtreeSnapshot, instanceSnapshot: SubtreeSnapshot, options?: {
589
+ emitAdditionMarkers?: boolean;
590
+ }): string[];
493
591
  /**
494
592
  * Merge a component's NEW canonical file value with an instance's canonical
495
593
  * value, preserving the instance side at every overridden path. An empty
@@ -519,4 +617,4 @@ declare function serializeEntitySubtree(world: World, rootId: EntityId, options?
519
617
  maxDepth?: number;
520
618
  }): SerializeEntitySubtreeResult;
521
619
 
522
- export { Behaviour, Component, type ComponentValueMaps, EcsEntityKind, EcsSystem, type EcsWorldComponentSnapshot, type EcsWorldStateSnapshotLike, EntityId, ExternalRefWarning, HYDRATABLE_ENTITY_KINDS, type HydrateOptions, type HydrateWorldFromSnapshotResult, type InstantiateSubtreeResult, type NodeMaps, OVERRIDE_DIFF_EXCLUDED_COMPONENTS, OVERRIDE_ROOT_EXCLUDED_COMPONENTS, ObjectManagementSystem, ParentLookup, SHARED_MODEL_RESOURCE_FLAG, type SerializeEntitySubtreeResult, SpawnPrefabOptions, SpawnPrefabSource, SubtreeSnapshot, World, WorldEntityView, buildComponentValueMaps, buildNodeMapsFromSnapshot, canonicalizeComponentValue, clearModelCache, collectDiffPaths, collectEntitySubtree, computeInstanceOverrides, decanonicalizeComponentValue, encodeOverride, findSnapshotRootEntityIds, groupOverridePaths, hydrateWorldFromSnapshot, hydrateWorldFromSnapshotDetailed, indexSnapshotByEntity, instantiateSubtree, loadSharedGltf, mergeComponentValue, parseOverride, resolveDracoDecoderPath, restoreComponentState, restorePostCreateComponents, serializeEntitySubtree, setDracoDecoderPath };
620
+ export { ADDED_NODE_MARKER_COMPONENT, type ApplyPrefabToSnapshotResult, Behaviour, Component, type ComponentValueMaps, EcsEntityKind, EcsSystem, type EcsWorldComponentSnapshot, type EcsWorldStateSnapshotLike, EntityId, ExternalRefWarning, HYDRATABLE_ENTITY_KINDS, type HydrateOptions, type HydrateWorldFromSnapshotResult, type InstantiateSubtreeResult, NODE_KEY_SEPARATOR, type NestedRegion, type NodeKeyMaps, type NodeMaps, OVERRIDE_DIFF_EXCLUDED_COMPONENTS, OVERRIDE_ROOT_EXCLUDED_COMPONENTS, ObjectManagementSystem, ParentLookup, SHARED_MODEL_RESOURCE_FLAG, type SerializeEntitySubtreeResult, SpawnPrefabOptions, SpawnPrefabSource, SubtreeSnapshot, World, WorldEntityView, applyPrefabToSnapshotInstances, buildComponentValueMaps, buildNodeKeyMapsFromSnapshot, buildNodeMapsFromSnapshot, canonicalizeComponentValue, clearModelCache, collectDiffPaths, collectDirectPrefabDependencies, collectEntitySubtree, collectSnapshotSubtreeIds, computeInstanceOverrides, decanonicalizeComponentValue, encodeOverride, findSnapshotRootEntityIds, findTopLevelNestedRegions, groupOverridePaths, hydrateWorldFromSnapshot, hydrateWorldFromSnapshotDetailed, indexSnapshotByEntity, instantiateSubtree, loadSharedGltf, mergeComponentValue, parseOverride, resolveDracoDecoderPath, restoreComponentState, restorePostCreateComponents, serializeEntitySubtree, setDracoDecoderPath };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { k as EcsSystem, C as Component, W as WorldEntityView, T as TransformComponent, l as World, S as SpawnPrefabSource, m as SpawnPrefabOptions, n as ComponentClass, o as ParentLookup, p as EcsEntityKind, O as ObjectManagementSystem, q as EntityId, r as SubtreeSnapshot, s as ExternalRefWarning } from './System-BjwOBx81.js';
2
- export { A as AssetInput, t as CheckboxInput, u as ColorInput, v as ComponentFactory, w as ComponentInput, x as ComponentKind, y as DropdownInput, z as DropdownOption, B as EcsComponentFactoryKind, F as EcsEntityEditorKind, G as EntityInput, H as FloatInput, I as InputSystem, J as IntersectionResult, K as KeyboardKey, L as KeyboardKeys, M as MouseButton, N as PREFAB_FILE_VERSION, Q as PrefabAsset, R as RemapSnapshotOptions, U as RenderSystem, X as SelectionListener, Y as SliderInput, Z as TextInput, _ as ToggleInput, $ as TransformSyncSystem, a0 as Vec3, a1 as Vector2Input, a2 as Vector3Input, a3 as clearPrefabCache, a4 as despawnPrefab, a5 as loadPrefab, a6 as parsePrefabAsset, a7 as remapSnapshotEntityIds, a8 as setPrefabAssetUrlResolver, a9 as spawnPrefab } from './System-BjwOBx81.js';
1
+ import { k as EcsSystem, C as Component, W as WorldEntityView, T as TransformComponent, l as World, S as SpawnPrefabSource, m as SpawnPrefabOptions, n as ComponentClass, o as ParentLookup, p as EcsEntityKind, O as ObjectManagementSystem, q as SubtreeSnapshot, r as EntityId, s as ExternalRefWarning } from './System-me3iAcMF.js';
2
+ export { A as AssetInput, t as CheckboxInput, u as ColorInput, v as ComponentFactory, w as ComponentInput, x as ComponentKind, y as DropdownInput, z as DropdownOption, B as EcsComponentFactoryKind, F as EcsEntityEditorKind, G as EntityInput, H as FloatInput, I as InputSystem, J as IntersectionResult, K as KeyboardKey, L as KeyboardKeys, M as MouseButton, N as PREFAB_FILE_VERSION, Q as PREFAB_FILE_VERSION_NESTED, R as PrefabAsset, U as RemapSnapshotOptions, X as RenderSystem, Y as SelectionListener, Z as SliderInput, _ as TextInput, $ as ToggleInput, a0 as TransformSyncSystem, a1 as Vec3, a2 as Vector2Input, a3 as Vector3Input, a4 as clearPrefabCache, a5 as despawnPrefab, a6 as loadPrefab, a7 as parsePrefabAsset, a8 as prefabFileVersionFor, a9 as remapSnapshotEntityIds, aa as setPrefabAssetUrlResolver, ab as spawnPrefab } from './System-me3iAcMF.js';
3
3
  import * as THREE from 'three';
4
- import { O as Object3DRef } from './Video-B9z5AtIf.js';
5
- export { a3 as AnimationStateCallbacks, a4 as AnimationStateMachine, a5 as AnimationStateManager, a6 as StateMachine } from './Video-B9z5AtIf.js';
6
- export { i as CoreComponents } from './index-BBI2YdCu.js';
4
+ import { O as Object3DRef } from './Video-DHnxjGhW.js';
5
+ export { a3 as AnimationStateCallbacks, a4 as AnimationStateMachine, a5 as AnimationStateManager, a6 as StateMachine } from './Video-DHnxjGhW.js';
6
+ export { i as CoreComponents } from './index-D7FSg0Au.js';
7
7
  export { AnimationSystem, AudioSystem, CameraSyncSystem, EnvironmentSyncSystem, InstancedMeshSystem, LightSyncSystem, MaterialSyncSystem, MeshGeometrySystem, ObjectVisibilitySystem, PhysicsSyncSystem, PostprocessingSyncSystem, ScriptBehaviourSystem, SelectionContext, VideoSystem } from './systems/index.js';
8
8
  export { createAnimationComponent, createAudioComponent, createCameraComponent, createEntityTypeComponent, createEnvironmentComponent, createImageComponent, createImageTargetAnchorComponent, createImageTargetComponent, createInstanceSlotComponent, createInstancedMeshComponent, createLightComponent, createMaterialComponent, createMeshComponent, createMeshGeometryComponent, createModelComponent, createNameComponent, createObject3DRefComponent, createParentIdComponent, createPhysicsComponent, createPostprocessingComponent, createScriptComponent, createSelectableComponent, createSelectionTransformStateComponent, createSpriteComponent, createTransformComponent, createVideoComponent, registerDefaultComponentFactories, registerDefaultFactories } from './factories/index.js';
9
9
  import { GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js';
@@ -390,6 +390,30 @@ declare function loadSharedGltf(url: string, load: () => Promise<GLTF>): Promise
390
390
  */
391
391
  declare function clearModelCache(url?: string): void;
392
392
 
393
+ /**
394
+ * Pure JSON-space prefab patching: apply a nested prefab's NEW definition to
395
+ * every top-level-relative instance region inside a HOST document snapshot,
396
+ * honoring the region's stored per-property overrides. This is how edits to
397
+ * a child prefab cascade through the `.prefab` files that nest it (no live
398
+ * world exists for files). Reused later by `.scene` assets.
399
+ *
400
+ * Trust model: the region's stored override list (refreshed at every host
401
+ * save with `+node` addition markers) IS the user state — no old base is
402
+ * needed. Consequently the operation is idempotent: re-applying the same
403
+ * definition yields `changed: false`.
404
+ */
405
+
406
+ type ApplyPrefabToSnapshotResult = {
407
+ snapshot: SubtreeSnapshot;
408
+ changed: boolean;
409
+ };
410
+ /**
411
+ * Patch every top-level-relative nested instance of `nestedUrl` inside
412
+ * `hostSnapshot` with `newNestedSnapshot`. Deeper nesting (B inside C inside
413
+ * A) is NOT touched here — it cascades through C's own file.
414
+ */
415
+ declare function applyPrefabToSnapshotInstances(hostSnapshot: SubtreeSnapshot, nestedUrl: string, newNestedSnapshot: SubtreeSnapshot): ApplyPrefabToSnapshotResult;
416
+
393
417
  /**
394
418
  * Collect the given roots plus every descendant, BFS parent-first, using the
395
419
  * `ParentId` component edges. Parent-first ordering matters: serialization
@@ -398,6 +422,71 @@ declare function clearModelCache(url?: string): void;
398
422
  */
399
423
  declare function collectEntitySubtree(world: World, rootIds: EntityId[]): EntityId[];
400
424
 
425
+ /**
426
+ * Direct (top-level-relative) prefab urls a document depends on — the edges
427
+ * of the nesting graph. Deeper nesting is reached transitively through each
428
+ * dependency's own file, never directly.
429
+ */
430
+ declare function collectDirectPrefabDependencies(snapshot: SubtreeSnapshot): string[];
431
+
432
+ /**
433
+ * Scoped node identity for (possibly nested) prefab documents.
434
+ *
435
+ * A nodeKey identifies an entity within one prefab document even when the
436
+ * document contains nested instances of other prefabs (whose nodeIds repeat
437
+ * per instance). Formula (parent-first walk from the scope root, inherited
438
+ * `prefix`; the scope root's prefix is "" even if it carries PrefabInstance):
439
+ *
440
+ * - entity WITHOUT PrefabInstance: key = prefix + nodeId, children inherit
441
+ * the same prefix;
442
+ * - entity WITH PrefabInstance (non-scope-root): childPrefix = prefix +
443
+ * instanceId + "/"; key = childPrefix + nodeId (self-inclusive — sibling
444
+ * instances of the SAME prefab get distinct keys); children inherit
445
+ * childPrefix.
446
+ *
447
+ * Documents with no nested instances degenerate to bare nodeIds, so v1 files
448
+ * and override lists keep their exact meaning.
449
+ */
450
+
451
+ declare const NODE_KEY_SEPARATOR = "/";
452
+ /**
453
+ * Reserved override "component" marking a node ADDED by the host document
454
+ * inside a nested instance region (`"<nodeKey>|+node|"`). File patching
455
+ * trusts stored overrides (the old base is unavailable), so without the
456
+ * marker a host-authored node inside the region would be indistinguishable
457
+ * from a node the child prefab removed — and get deleted.
458
+ */
459
+ declare const ADDED_NODE_MARKER_COMPONENT = "+node";
460
+ type NodeKeyMaps = {
461
+ idToKey: Map<number, string>;
462
+ keyToId: Map<string, number>;
463
+ /** nodeKey of the scope root (bare nodeId), or null when it has none. */
464
+ rootKey: string | null;
465
+ /** Entity ids of NESTED instance roots (non-scope-root PrefabInstance). */
466
+ boundaryIds: Map<number, {
467
+ url: string;
468
+ instanceId: string;
469
+ }>;
470
+ };
471
+ declare function buildNodeKeyMapsFromSnapshot(snapshot: SubtreeSnapshot, options?: {
472
+ scopeRootEntityId?: number;
473
+ }): NodeKeyMaps;
474
+ /** JSON-space subtree ids (root first, BFS) via ParentId edges. */
475
+ declare function collectSnapshotSubtreeIds(snapshot: SubtreeSnapshot, rootEntityId: number): number[];
476
+ type NestedRegion = {
477
+ rootEntityId: number;
478
+ url: string;
479
+ instanceId: string;
480
+ overrides: string[];
481
+ };
482
+ /**
483
+ * TOP-LEVEL-RELATIVE nested instance regions of a document: instance roots
484
+ * that are not the scope root and not themselves inside another region.
485
+ * Deeper nesting is reached by cascading through the intermediate prefab's
486
+ * own file, never directly.
487
+ */
488
+ declare function findTopLevelNestedRegions(snapshot: SubtreeSnapshot): NestedRegion[];
489
+
401
490
  type InstantiateSubtreeResult = {
402
491
  /** Live entity id of the subtree root, or null when nothing hydrated. */
403
492
  rootId: EntityId | null;
@@ -485,11 +574,20 @@ declare function collectDiffPaths(base: unknown, current: unknown, prefix?: stri
485
574
  * subtree snapshots carrying PrefabNode identity) and return the encoded
486
575
  * override list: every path where the instance deviates from the base.
487
576
  *
488
- * v1 policies: components missing on the instance produce no override
489
- * (apply re-adds them); components/nodes only on the instance are local
490
- * additions and produce no override (apply never touches them).
577
+ * Identity is nodeKey-scoped ({@link buildNodeKeyMapsFromSnapshot}), so
578
+ * nested instance regions diff correctly; for nested-free documents the
579
+ * keys degenerate to bare nodeIds (v1 behavior unchanged).
580
+ *
581
+ * Policies: components missing on the instance produce no override (apply
582
+ * re-adds them); components/nodes only on the instance are local additions
583
+ * and produce no override — EXCEPT when `emitAdditionMarkers` is set
584
+ * (file-space callers), which records `"<key>|+node|"` for instance nodes
585
+ * absent from the base so pure-JSON patching never deletes host-authored
586
+ * nodes inside nested regions.
491
587
  */
492
- declare function computeInstanceOverrides(baseSnapshot: SubtreeSnapshot, instanceSnapshot: SubtreeSnapshot): string[];
588
+ declare function computeInstanceOverrides(baseSnapshot: SubtreeSnapshot, instanceSnapshot: SubtreeSnapshot, options?: {
589
+ emitAdditionMarkers?: boolean;
590
+ }): string[];
493
591
  /**
494
592
  * Merge a component's NEW canonical file value with an instance's canonical
495
593
  * value, preserving the instance side at every overridden path. An empty
@@ -519,4 +617,4 @@ declare function serializeEntitySubtree(world: World, rootId: EntityId, options?
519
617
  maxDepth?: number;
520
618
  }): SerializeEntitySubtreeResult;
521
619
 
522
- export { Behaviour, Component, type ComponentValueMaps, EcsEntityKind, EcsSystem, type EcsWorldComponentSnapshot, type EcsWorldStateSnapshotLike, EntityId, ExternalRefWarning, HYDRATABLE_ENTITY_KINDS, type HydrateOptions, type HydrateWorldFromSnapshotResult, type InstantiateSubtreeResult, type NodeMaps, OVERRIDE_DIFF_EXCLUDED_COMPONENTS, OVERRIDE_ROOT_EXCLUDED_COMPONENTS, ObjectManagementSystem, ParentLookup, SHARED_MODEL_RESOURCE_FLAG, type SerializeEntitySubtreeResult, SpawnPrefabOptions, SpawnPrefabSource, SubtreeSnapshot, World, WorldEntityView, buildComponentValueMaps, buildNodeMapsFromSnapshot, canonicalizeComponentValue, clearModelCache, collectDiffPaths, collectEntitySubtree, computeInstanceOverrides, decanonicalizeComponentValue, encodeOverride, findSnapshotRootEntityIds, groupOverridePaths, hydrateWorldFromSnapshot, hydrateWorldFromSnapshotDetailed, indexSnapshotByEntity, instantiateSubtree, loadSharedGltf, mergeComponentValue, parseOverride, resolveDracoDecoderPath, restoreComponentState, restorePostCreateComponents, serializeEntitySubtree, setDracoDecoderPath };
620
+ export { ADDED_NODE_MARKER_COMPONENT, type ApplyPrefabToSnapshotResult, Behaviour, Component, type ComponentValueMaps, EcsEntityKind, EcsSystem, type EcsWorldComponentSnapshot, type EcsWorldStateSnapshotLike, EntityId, ExternalRefWarning, HYDRATABLE_ENTITY_KINDS, type HydrateOptions, type HydrateWorldFromSnapshotResult, type InstantiateSubtreeResult, NODE_KEY_SEPARATOR, type NestedRegion, type NodeKeyMaps, type NodeMaps, OVERRIDE_DIFF_EXCLUDED_COMPONENTS, OVERRIDE_ROOT_EXCLUDED_COMPONENTS, ObjectManagementSystem, ParentLookup, SHARED_MODEL_RESOURCE_FLAG, type SerializeEntitySubtreeResult, SpawnPrefabOptions, SpawnPrefabSource, SubtreeSnapshot, World, WorldEntityView, applyPrefabToSnapshotInstances, buildComponentValueMaps, buildNodeKeyMapsFromSnapshot, buildNodeMapsFromSnapshot, canonicalizeComponentValue, clearModelCache, collectDiffPaths, collectDirectPrefabDependencies, collectEntitySubtree, collectSnapshotSubtreeIds, computeInstanceOverrides, decanonicalizeComponentValue, encodeOverride, findSnapshotRootEntityIds, findTopLevelNestedRegions, groupOverridePaths, hydrateWorldFromSnapshot, hydrateWorldFromSnapshotDetailed, indexSnapshotByEntity, instantiateSubtree, loadSharedGltf, mergeComponentValue, parseOverride, resolveDracoDecoderPath, restoreComponentState, restorePostCreateComponents, serializeEntitySubtree, setDracoDecoderPath };
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import { MeshGeometrySystem, InstancedMeshSystem, EnvironmentSyncSystem, PostprocessingSyncSystem, LightSyncSystem, MaterialSyncSystem, PhysicsSyncSystem, AnimationSystem, AudioSystem, VideoSystem, CameraSyncSystem, TransformSyncSystem, ObjectVisibilitySystem, RenderSystem, spawnPrefab, despawnPrefab, collectEntitySubtree } from './chunk-67MFQDHX.js';
2
- export { AnimationSystem, AudioSystem, Behaviour, CameraSyncSystem, EnvironmentSyncSystem, HYDRATABLE_ENTITY_KINDS, InputSystem, InstancedMeshSystem, KeyboardKeys, LightSyncSystem, MaterialSyncSystem, MeshGeometrySystem, OVERRIDE_DIFF_EXCLUDED_COMPONENTS, OVERRIDE_ROOT_EXCLUDED_COMPONENTS, ObjectVisibilitySystem, PREFAB_FILE_VERSION, PhysicsSyncSystem, PostprocessingSyncSystem, RenderSystem, ScriptBehaviourSystem, TransformSyncSystem, VideoSystem, buildComponentValueMaps, buildNodeMapsFromSnapshot, canonicalizeComponentValue, clearPrefabCache, collectDiffPaths, collectEntitySubtree, computeInstanceOverrides, decanonicalizeComponentValue, despawnPrefab, encodeOverride, findSnapshotRootEntityIds, groupOverridePaths, hydrateWorldFromSnapshot, hydrateWorldFromSnapshotDetailed, indexSnapshotByEntity, instantiateSubtree, loadPrefab, mergeComponentValue, parseOverride, parsePrefabAsset, restoreComponentState, restorePostCreateComponents, setPrefabAssetUrlResolver, spawnPrefab } from './chunk-67MFQDHX.js';
3
- import { registerDefaultFactories } from './chunk-HUHN6IFD.js';
4
- export { createAnimationComponent, createAudioComponent, createCameraComponent, createEntityTypeComponent, createEnvironmentComponent, createImageComponent, createImageTargetAnchorComponent, createImageTargetComponent, createInstanceSlotComponent, createInstancedMeshComponent, createLightComponent, createMaterialComponent, createMeshComponent, createMeshGeometryComponent, createModelComponent, createNameComponent, createObject3DRefComponent, createParentIdComponent, createPhysicsComponent, createPostprocessingComponent, createScriptComponent, createSelectableComponent, createSelectionTransformStateComponent, createSpriteComponent, createTransformComponent, createVideoComponent, registerDefaultComponentFactories, registerDefaultFactories } from './chunk-HUHN6IFD.js';
5
- import { ObjectManagementSystem } from './chunk-DY4ETMP2.js';
6
- export { ObjectManagementSystem, SHARED_MODEL_RESOURCE_FLAG, clearModelCache, loadSharedGltf, resolveDracoDecoderPath, setDracoDecoderPath } from './chunk-DY4ETMP2.js';
7
- import { SelectionTransformState, Object3DRef, Name, EntityType, ParentId, Environment, Postprocessing, ScriptComponent } from './chunk-Z6OMYEXU.js';
8
- export { AnimationStateMachine, AnimationStateManager, components_exports as CoreComponents } from './chunk-Z6OMYEXU.js';
1
+ import { MeshGeometrySystem, InstancedMeshSystem, EnvironmentSyncSystem, PostprocessingSyncSystem, LightSyncSystem, MaterialSyncSystem, PhysicsSyncSystem, AnimationSystem, AudioSystem, VideoSystem, CameraSyncSystem, TransformSyncSystem, ObjectVisibilitySystem, RenderSystem, spawnPrefab, despawnPrefab, buildNodeKeyMapsFromSnapshot, indexSnapshotByEntity, findTopLevelNestedRegions, collectSnapshotSubtreeIds, groupOverridePaths, OVERRIDE_DIFF_EXCLUDED_COMPONENTS, OVERRIDE_ROOT_EXCLUDED_COMPONENTS, canonicalizeComponentValue, mergeComponentValue, decanonicalizeComponentValue, computeInstanceOverrides, collectEntitySubtree, ADDED_NODE_MARKER_COMPONENT } from './chunk-5U3YS4JD.js';
2
+ export { ADDED_NODE_MARKER_COMPONENT, AnimationSystem, AudioSystem, Behaviour, CameraSyncSystem, EnvironmentSyncSystem, HYDRATABLE_ENTITY_KINDS, InputSystem, InstancedMeshSystem, KeyboardKeys, LightSyncSystem, MaterialSyncSystem, MeshGeometrySystem, NODE_KEY_SEPARATOR, OVERRIDE_DIFF_EXCLUDED_COMPONENTS, OVERRIDE_ROOT_EXCLUDED_COMPONENTS, ObjectVisibilitySystem, PREFAB_FILE_VERSION, PREFAB_FILE_VERSION_NESTED, PhysicsSyncSystem, PostprocessingSyncSystem, RenderSystem, ScriptBehaviourSystem, TransformSyncSystem, VideoSystem, buildComponentValueMaps, buildNodeKeyMapsFromSnapshot, buildNodeMapsFromSnapshot, canonicalizeComponentValue, clearPrefabCache, collectDiffPaths, collectEntitySubtree, collectSnapshotSubtreeIds, computeInstanceOverrides, decanonicalizeComponentValue, despawnPrefab, encodeOverride, findSnapshotRootEntityIds, findTopLevelNestedRegions, groupOverridePaths, hydrateWorldFromSnapshot, hydrateWorldFromSnapshotDetailed, indexSnapshotByEntity, instantiateSubtree, loadPrefab, mergeComponentValue, parseOverride, parsePrefabAsset, prefabFileVersionFor, restoreComponentState, restorePostCreateComponents, setPrefabAssetUrlResolver, spawnPrefab } from './chunk-5U3YS4JD.js';
3
+ import { registerDefaultFactories } from './chunk-K6KMKKJ6.js';
4
+ export { createAnimationComponent, createAudioComponent, createCameraComponent, createEntityTypeComponent, createEnvironmentComponent, createImageComponent, createImageTargetAnchorComponent, createImageTargetComponent, createInstanceSlotComponent, createInstancedMeshComponent, createLightComponent, createMaterialComponent, createMeshComponent, createMeshGeometryComponent, createModelComponent, createNameComponent, createObject3DRefComponent, createParentIdComponent, createPhysicsComponent, createPostprocessingComponent, createScriptComponent, createSelectableComponent, createSelectionTransformStateComponent, createSpriteComponent, createTransformComponent, createVideoComponent, registerDefaultComponentFactories, registerDefaultFactories } from './chunk-K6KMKKJ6.js';
5
+ import { ObjectManagementSystem } from './chunk-AXRCGF63.js';
6
+ export { ObjectManagementSystem, SHARED_MODEL_RESOURCE_FLAG, clearModelCache, loadSharedGltf, resolveDracoDecoderPath, setDracoDecoderPath } from './chunk-AXRCGF63.js';
7
+ import { SelectionTransformState, Object3DRef, Name, EntityType, ParentId, Environment, Postprocessing, ScriptComponent } from './chunk-V7BNVTJW.js';
8
+ export { AnimationStateMachine, AnimationStateManager, components_exports as CoreComponents } from './chunk-V7BNVTJW.js';
9
9
  import './chunk-QHILSPT4.js';
10
10
  import { normalizeDebugValue, DEBUG_CHANGE_IGNORED_SYSTEMS, cloneHistoryValue } from './chunk-ZXGHKX7N.js';
11
11
  import { __name } from './chunk-OY7ZODZP.js';
@@ -1078,12 +1078,237 @@ function remapSnapshotEntityIds(snapshot, idMap, options) {
1078
1078
  }
1079
1079
  __name(remapSnapshotEntityIds, "remapSnapshotEntityIds");
1080
1080
 
1081
+ // core/prefab/applyPrefabToSnapshot.ts
1082
+ var asRecord2 = /* @__PURE__ */ __name((value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : null, "asRecord");
1083
+ var clone = /* @__PURE__ */ __name((value) => structuredClone(value), "clone");
1084
+ var stableStringify = /* @__PURE__ */ __name((value) => {
1085
+ try {
1086
+ return JSON.stringify(value);
1087
+ } catch {
1088
+ return "";
1089
+ }
1090
+ }, "stableStringify");
1091
+ function getBlock(snapshot, component) {
1092
+ let block = snapshot.components.find((b) => b.component === component);
1093
+ if (!block) {
1094
+ block = { component, entries: [] };
1095
+ snapshot.components.push(block);
1096
+ }
1097
+ return block;
1098
+ }
1099
+ __name(getBlock, "getBlock");
1100
+ function setEntry(snapshot, component, entityId, value) {
1101
+ const block = getBlock(snapshot, component);
1102
+ const entry = block.entries.find((e) => e.entityId === entityId);
1103
+ if (entry) {
1104
+ entry.value = value;
1105
+ } else {
1106
+ block.entries.push({ entityId, value });
1107
+ block.entries.sort((a, b) => a.entityId - b.entityId);
1108
+ }
1109
+ }
1110
+ __name(setEntry, "setEntry");
1111
+ function deleteEntities(snapshot, entityIds) {
1112
+ snapshot.entities = snapshot.entities.filter((id) => !entityIds.has(id));
1113
+ snapshot.components = snapshot.components.map((block) => ({
1114
+ component: block.component,
1115
+ entries: block.entries.filter((e) => !entityIds.has(e.entityId))
1116
+ })).filter((block) => block.entries.length > 0);
1117
+ }
1118
+ __name(deleteEntities, "deleteEntities");
1119
+ function extractRegionDoc(hostSnapshot, regionIds) {
1120
+ const idSet = new Set(regionIds);
1121
+ return {
1122
+ entities: regionIds.slice(),
1123
+ components: hostSnapshot.components.map((block) => ({
1124
+ component: block.component,
1125
+ entries: block.entries.filter((e) => idSet.has(e.entityId))
1126
+ })).filter((block) => block.entries.length > 0)
1127
+ };
1128
+ }
1129
+ __name(extractRegionDoc, "extractRegionDoc");
1130
+ function applyPrefabToSnapshotInstances(hostSnapshot, nestedUrl, newNestedSnapshot) {
1131
+ const host = clone(hostSnapshot);
1132
+ const newMaps = buildNodeKeyMapsFromSnapshot(newNestedSnapshot);
1133
+ const newByEntity = indexSnapshotByEntity(newNestedSnapshot);
1134
+ if (!newMaps.rootKey) {
1135
+ return { snapshot: host, changed: false };
1136
+ }
1137
+ let changed = false;
1138
+ const regions = findTopLevelNestedRegions(host).filter(
1139
+ (region) => region.url === nestedUrl
1140
+ );
1141
+ for (const region of regions) {
1142
+ const before = stableStringify(
1143
+ extractRegionDoc(host, collectSnapshotSubtreeIds(host, region.rootEntityId))
1144
+ );
1145
+ patchRegion(host, region.rootEntityId, region.overrides, {
1146
+ newSnapshot: newNestedSnapshot,
1147
+ newMaps,
1148
+ newByEntity
1149
+ });
1150
+ const after = stableStringify(
1151
+ extractRegionDoc(host, collectSnapshotSubtreeIds(host, region.rootEntityId))
1152
+ );
1153
+ if (before !== after) {
1154
+ changed = true;
1155
+ }
1156
+ }
1157
+ return { snapshot: host, changed };
1158
+ }
1159
+ __name(applyPrefabToSnapshotInstances, "applyPrefabToSnapshotInstances");
1160
+ function patchRegion(host, regionRootId, storedOverrides, file) {
1161
+ const { newSnapshot, newMaps, newByEntity } = file;
1162
+ const regionIds = collectSnapshotSubtreeIds(host, regionRootId);
1163
+ const regionDoc = extractRegionDoc(host, regionIds);
1164
+ const regionMaps = buildNodeKeyMapsFromSnapshot(regionDoc, {
1165
+ scopeRootEntityId: regionRootId
1166
+ });
1167
+ const regionByEntity = indexSnapshotByEntity(regionDoc);
1168
+ const grouped = groupOverridePaths(storedOverrides);
1169
+ const overridePathsFor = /* @__PURE__ */ __name((key, component) => grouped.get(key)?.get(component), "overridePathsFor");
1170
+ const isMarkedAddition = /* @__PURE__ */ __name((key) => Boolean(grouped.get(key)?.get(ADDED_NODE_MARKER_COMPONENT)), "isMarkedAddition");
1171
+ const parentBlockNew = newSnapshot.components.find(
1172
+ (b) => b.component === "ParentId"
1173
+ );
1174
+ const keyToHostId = /* @__PURE__ */ new Map();
1175
+ for (const [hostId, key] of regionMaps.idToKey) {
1176
+ keyToHostId.set(key, hostId);
1177
+ }
1178
+ const addedFileIds = [...newMaps.keyToId.entries()].filter(([key]) => !keyToHostId.has(key)).map(([, fileId]) => fileId);
1179
+ if (addedFileIds.length > 0) {
1180
+ let nextHostId = Math.max(0, ...host.entities) + 1;
1181
+ const addedSet = new Set(addedFileIds);
1182
+ const idMap = /* @__PURE__ */ new Map();
1183
+ for (const [key, fileId] of newMaps.keyToId) {
1184
+ const hostId = keyToHostId.get(key);
1185
+ if (hostId !== void 0) {
1186
+ idMap.set(fileId, hostId);
1187
+ }
1188
+ }
1189
+ for (const fileId of addedFileIds) {
1190
+ idMap.set(fileId, nextHostId);
1191
+ nextHostId += 1;
1192
+ }
1193
+ const addedSub = {
1194
+ entities: newSnapshot.entities.filter((id) => addedSet.has(id)),
1195
+ components: newSnapshot.components.map((block) => ({
1196
+ component: block.component,
1197
+ entries: block.entries.filter((e) => addedSet.has(e.entityId))
1198
+ })).filter((block) => block.entries.length > 0)
1199
+ };
1200
+ const { snapshot: remapped } = remapSnapshotEntityIds(addedSub, idMap, {
1201
+ externalRefPolicy: "null"
1202
+ });
1203
+ host.entities = [...host.entities, ...remapped.entities];
1204
+ for (const block of remapped.components) {
1205
+ for (const entry of block.entries) {
1206
+ setEntry(host, block.component, entry.entityId, entry.value);
1207
+ }
1208
+ }
1209
+ for (const fileId of addedFileIds) {
1210
+ const hostId = idMap.get(fileId);
1211
+ const parentValue = asRecord2(
1212
+ parentBlockNew?.entries.find((e) => e.entityId === fileId)?.value
1213
+ )?.value;
1214
+ if (typeof parentValue === "number" && !addedSet.has(parentValue)) {
1215
+ const parentKey = newMaps.idToKey.get(parentValue);
1216
+ const parentHost = parentKey ? keyToHostId.get(parentKey) : void 0;
1217
+ setEntry(host, "ParentId", hostId, {
1218
+ __type: "ParentId",
1219
+ value: parentHost ?? regionRootId
1220
+ });
1221
+ }
1222
+ const key = newMaps.idToKey.get(fileId);
1223
+ if (key) {
1224
+ keyToHostId.set(key, hostId);
1225
+ }
1226
+ }
1227
+ }
1228
+ for (const [key, fileId] of newMaps.keyToId) {
1229
+ const hostId = keyToHostId.get(key);
1230
+ if (hostId === void 0) continue;
1231
+ const isRegionRoot = key === newMaps.rootKey;
1232
+ const fileComponents = newByEntity.get(fileId);
1233
+ if (!fileComponents) continue;
1234
+ const regionEntityComponents = regionByEntity.get(hostId);
1235
+ for (const [componentName, fileRaw] of fileComponents) {
1236
+ if (OVERRIDE_DIFF_EXCLUDED_COMPONENTS.has(componentName)) continue;
1237
+ if (isRegionRoot && OVERRIDE_ROOT_EXCLUDED_COMPONENTS.has(componentName))
1238
+ continue;
1239
+ const fileCanonical = canonicalizeComponentValue(
1240
+ componentName,
1241
+ fileRaw,
1242
+ newMaps.idToKey
1243
+ );
1244
+ const regionRaw = regionEntityComponents?.get(componentName);
1245
+ const regionCanonical = regionRaw === void 0 ? void 0 : canonicalizeComponentValue(
1246
+ componentName,
1247
+ regionRaw,
1248
+ regionMaps.idToKey
1249
+ );
1250
+ const merged = regionCanonical === void 0 ? fileCanonical : mergeComponentValue(
1251
+ fileCanonical,
1252
+ regionCanonical,
1253
+ overridePathsFor(key, componentName)
1254
+ );
1255
+ if (regionCanonical !== void 0 && stableStringify(merged) === stableStringify(regionCanonical)) {
1256
+ continue;
1257
+ }
1258
+ const hostValue = decanonicalizeComponentValue(merged, keyToHostId);
1259
+ setEntry(host, componentName, hostId, hostValue);
1260
+ }
1261
+ }
1262
+ const removedHostIds = /* @__PURE__ */ new Set();
1263
+ for (const [key, hostId] of keyToHostId) {
1264
+ if (newMaps.keyToId.has(key)) continue;
1265
+ if (isMarkedAddition(key)) continue;
1266
+ removedHostIds.add(hostId);
1267
+ }
1268
+ if (removedHostIds.size > 0) {
1269
+ const regionIdSet = new Set(regionIds);
1270
+ const parentBlockHost = host.components.find(
1271
+ (b) => b.component === "ParentId"
1272
+ );
1273
+ for (const entry of parentBlockHost?.entries ?? []) {
1274
+ const record = asRecord2(entry.value);
1275
+ if (!removedHostIds.has(entry.entityId) && regionIdSet.has(entry.entityId) && record && typeof record.value === "number" && removedHostIds.has(record.value)) {
1276
+ record.value = regionRootId;
1277
+ }
1278
+ }
1279
+ deleteEntities(host, removedHostIds);
1280
+ }
1281
+ const refreshedRegionIds = collectSnapshotSubtreeIds(host, regionRootId);
1282
+ const refreshedDoc = extractRegionDoc(host, refreshedRegionIds);
1283
+ const refreshedOverrides = computeInstanceOverrides(
1284
+ newSnapshot,
1285
+ refreshedDoc,
1286
+ { emitAdditionMarkers: true }
1287
+ );
1288
+ const instanceEntry = asRecord2(
1289
+ host.components.find((b) => b.component === "PrefabInstance")?.entries.find((e) => e.entityId === regionRootId)?.value
1290
+ );
1291
+ if (instanceEntry) {
1292
+ instanceEntry.overrides = refreshedOverrides;
1293
+ }
1294
+ }
1295
+ __name(patchRegion, "patchRegion");
1296
+
1297
+ // core/prefab/dependencies.ts
1298
+ function collectDirectPrefabDependencies(snapshot) {
1299
+ const urls = /* @__PURE__ */ new Set();
1300
+ for (const region of findTopLevelNestedRegions(snapshot)) {
1301
+ urls.add(region.url);
1302
+ }
1303
+ return [...urls];
1304
+ }
1305
+ __name(collectDirectPrefabDependencies, "collectDirectPrefabDependencies");
1306
+
1081
1307
  // core/prefab/serializeEntitySubtree.ts
1082
1308
  var SUBTREE_EXCLUDED_COMPONENTS = /* @__PURE__ */ new Set([
1083
1309
  "Environment",
1084
1310
  "Postprocessing",
1085
- "SelectionTransformState",
1086
- "PrefabInstance"
1311
+ "SelectionTransformState"
1087
1312
  ]);
1088
1313
  function serializeEntitySubtree(world, rootId, options) {
1089
1314
  const orderedIds = collectEntitySubtree(world, [rootId]);
@@ -1115,6 +1340,19 @@ function serializeEntitySubtree(world, rootId, options) {
1115
1340
  if (rootParentEntry && rootParentEntry.value !== null && typeof rootParentEntry.value === "object") {
1116
1341
  rootParentEntry.value.value = null;
1117
1342
  }
1343
+ const prefabInstanceBlock = snapshot.components.find(
1344
+ (block) => block.component === "PrefabInstance"
1345
+ );
1346
+ if (prefabInstanceBlock) {
1347
+ prefabInstanceBlock.entries = prefabInstanceBlock.entries.filter(
1348
+ (entry) => entry.entityId !== rootFileId
1349
+ );
1350
+ if (prefabInstanceBlock.entries.length === 0) {
1351
+ snapshot.components = snapshot.components.filter(
1352
+ (block) => block !== prefabInstanceBlock
1353
+ );
1354
+ }
1355
+ }
1118
1356
  const filteredWarnings = warnings.filter(
1119
1357
  (warning) => !(warning.component === "ParentId" && warning.entityId === rootId)
1120
1358
  );
@@ -1122,6 +1360,6 @@ function serializeEntitySubtree(world, rootId, options) {
1122
1360
  }
1123
1361
  __name(serializeEntitySubtree, "serializeEntitySubtree");
1124
1362
 
1125
- export { World, remapSnapshotEntityIds, serializeEntitySubtree };
1363
+ export { World, applyPrefabToSnapshotInstances, collectDirectPrefabDependencies, remapSnapshotEntityIds, serializeEntitySubtree };
1126
1364
  //# sourceMappingURL=index.js.map
1127
1365
  //# sourceMappingURL=index.js.map