A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(prefab): re-parent as a first-class override + apply/expand integrity
esengine4db8448fa270
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 90f6286fe..a5556c57f 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -102,6 +102,7 @@ export const projectMessages = defineMessages({'proj.createFailed': { en: 'Could not create project: {message}', zh: '无法创建项目:{message}' },'proj.sdkTypesFailed': { en: 'SDK types staging failed — the IDE cannot resolve "esengine": {message}', zh: 'SDK 类型入驻失败——IDE 将无法解析 "esengine":{message}' },'proj.prefabLoadFailed': { en: 'Could not load prefab: {name}', zh: '无法加载预制体:{name}' },+ 'proj.saveAsInPrefabMode': { en: 'Save As isn’t available while editing a prefab — use Save Prefab, or go Back to the scene first.', zh: '编辑预制体时无法使用"另存为"——请用"保存预制体",或先返回场景。' },'proj.noOverrides': { en: 'No overrides to apply', zh: '没有可应用的覆盖' },'proj.applyWriteFailed': { en: 'Apply failed: could not write {name}', zh: '应用失败:无法写入 {name}' },'proj.appliedOverride': { en: 'Applied {count} override to {name}', zh: '已将 {count} 项覆盖应用到 {name}' },@@ -110,6 +111,7 @@ export const projectMessages = defineMessages({'proj.applyPreviewLead': { en: 'These changes will be written to "{name}" and affect every instance:', zh: '以下改动将写入"{name}"并影响其所有实例:' },'proj.applyDiffName': { en: 'name', zh: '名称' },'proj.applyDiffVisibility': { en: 'visibility', zh: '可见性' },+ 'proj.applyDiffReparent': { en: 're-parented', zh: '移动父级' },'proj.applyDiffAdded': { en: 'added', zh: '新增' },'proj.applyDiffRemoved': { en: 'removed', zh: '移除' },'proj.applyLabel': { en: 'Apply', zh: '应用' },diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 02b94cb70..d5141014d 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -2198,6 +2198,14 @@ class ProjectStoreImpl {/** Write the current world to a project-relative path (explicit, no lossy guard). */async saveAs(relPath: string): Promise<void> {if (!this.state) throw new Error('no project open');+ // In Prefab Mode the world holds a flattened PREFAB tree, not a scene —+ // writing it as a `.esscene` would emit a bogus scene AND repoint+ // `lastOpenedScene` at it. Save-As isn't a prefab operation; refuse it and+ // point the user at Save Prefab / Back. (save() already routes to savePrefab.)+ if (this.prefabSession) {+ Toasts.push(t('proj.saveAsInPrefabMode'), 'warn');+ return;+ }await this.writeScene(relPath, await this.serializeCurrent());await this.persistLastScene(relPath);EditorHistory.markSaved();@@ -2253,6 +2261,10 @@ class ProjectStoreImpl {async saveAsViaDialog(): Promise<string | null> {const st = this.state;if (!st || !window.estella.project.saveSceneDialog) return null;+ if (this.prefabSession) {+ Toasts.push(t('proj.saveAsInPrefabMode'), 'warn');+ return null;+ }const rel = await window.estella.project.saveSceneDialog(st.currentScene ?? `${st.layout.scenes}/scene.esscene`,);diff --git a/desktop/src/project/applyPreview.tsx b/desktop/src/project/applyPreview.tsxindex 57c8ca5f6..bf0775802 100644--- a/desktop/src/project/applyPreview.tsx+++ b/desktop/src/project/applyPreview.tsx@@ -34,6 +34,8 @@ function overrideLabel(o: PrefabOverride): string {return t('proj.applyDiffName');case 'visibility':return t('proj.applyDiffVisibility');+ case 'parent':+ return t('proj.applyDiffReparent');default:return o.type;}@@ -98,7 +100,10 @@ export function previewApply(delta: ApplyDelta,nameOf: (id: PrefabEntityId) => string,): Promise<boolean> {- const structural = delta.added.length + delta.removed.length;+ // A re-parent rewrites the shared prefab's topology — count it structural so+ // the confirm reads as destructive, like add/remove.+ const structural =+ delta.added.length + delta.removed.length + delta.overrides.filter((o) => o.type === 'parent').length;return confirm({title: t('proj.applyPreviewTitle'),confirmLabel: t('proj.applyLabel'),diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 0b3bcb9d0..855a18ae1 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4748,7 +4748,7 @@ componentType: string | undefinedmetadataKey: string | undefinedprefabEntityId: stringpropertyName: string | undefined-type: "property" | "component_added" | "component_replaced" | "component_removed" | "name" | "visibility" | "metadata_set" | "metadata_removed"+type: "property" | "component_added" | "component_replaced" | "component_removed" | "name" | "visibility" | "parent" | "metadata_set" | "metadata_removed"value: unknown```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e4eea7e35..640050f71 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4743,7 +4743,7 @@ componentType: string | undefinedmetadataKey: string | undefinedprefabEntityId: stringpropertyName: string | undefined-type: "property" | "component_added" | "component_replaced" | "component_removed" | "name" | "visibility" | "metadata_set" | "metadata_removed"+type: "property" | "component_added" | "component_replaced" | "component_removed" | "name" | "visibility" | "parent" | "metadata_set" | "metadata_removed"value: unknown```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 49dd06a96..3d80a0498 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4750,7 +4750,7 @@ componentType: string | undefinedmetadataKey: string | undefinedprefabEntityId: stringpropertyName: string | undefined-type: "property" | "component_added" | "component_replaced" | "component_removed" | "name" | "visibility" | "metadata_set" | "metadata_removed"+type: "property" | "component_added" | "component_replaced" | "component_removed" | "name" | "visibility" | "parent" | "metadata_set" | "metadata_removed"value: unknown```diff --git a/sdk/src/prefab/diff.ts b/sdk/src/prefab/diff.tsindex cd6358a14..e882af614 100644--- a/sdk/src/prefab/diff.ts+++ b/sdk/src/prefab/diff.ts@@ -92,6 +92,23 @@ export interface DiffBaselineEntity {/** Runtime id — present on flattened baselines so their entity-ref fields* normalise to stable-id space; absent on raw source entities. */id?: number;+ /** Parent for structural (re-parent) diffing. A raw source entity carries a+ * stable `PrefabEntityId` string; a flattened baseline carries the runtime+ * number (normalised through the baseline's own id map). `undefined` means a+ * caller didn't supply it — parent diffing is then skipped for that entity. */+ parent?: PrefabEntityId | number | null;+}++/** Translate a parent link to stable-id space. Strings are already stable (raw+ * source); numbers map through the side's runtime→stable map (a target outside+ * the instance is unmapped → null). */+function toStableParent(+ parent: PrefabEntityId | number | null | undefined,+ refMap: Map<number, PrefabEntityId>,+): PrefabEntityId | null {+ if (parent === null || parent === undefined) return null;+ if (typeof parent === 'string') return parent;+ return refMap.get(parent) ?? null;}/**@@ -154,6 +171,23 @@ export function diffEntities(});}+ // Structural re-parent: compare both parents in stable-id space. Skip when+ // the baseline didn't carry a parent (legacy caller). The instance root's+ // parent points OUTSIDE the instance (unmapped → null) and the prefab root's+ // baseline parent is null, so the root never diffs — its attach point is the+ // instance entry's own `parent`, not a prefab override.+ if (base.parent !== undefined) {+ const baseParent = toStableParent(base.parent, baseRefMap);+ const instParent = toStableParent(instEntity.parent, instRefMap);+ if (baseParent !== instParent) {+ overrides.push({+ prefabEntityId: instEntity.prefabEntityId,+ type: 'parent',+ value: instParent,+ });+ }+ }+diffMetadata(base.metadata, instEntity.metadata, ignoredMeta, instEntity.prefabEntityId, overrides);diffComponents(base.components, instEntity.components, instEntity.prefabEntityId, eps, overrides, baseRefMap, instRefMap);}diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.tsindex f7a5df64c..47056543e 100644--- a/sdk/src/prefab/sceneInstance.ts+++ b/sdk/src/prefab/sceneInstance.ts@@ -97,8 +97,15 @@ export function expandInstance(loadPrefab,});+ // Structural re-parent overrides move a prefab-origin entity BEFORE the+ // removed-closure runs, so an entity re-parented OUT of a doomed subtree+ // survives the cascade (and a pure re-parent actually takes effect). This+ // pass sees only prefab entities; a re-parent whose target is an ADDED entity+ // is left in place here and resolved in the second pass below.+ applyParentOverrides(entities, delta.overrides, rootId, false);+// `removed` records the ROOTS of deleted subtrees; expand the transitive- // closure over the flattened tree so deleting a parent drops its whole+ // closure over the (re-parented) tree so deleting a parent drops its whole// subtree (no orphaned, parent-less entities survive).const removed = removedClosure(entities, delta.removed);const kept = entities.filter((e) => !removed.has(e.prefabEntityId));@@ -117,7 +124,7 @@ export function expandInstance(name: a.name,parent: rootId,children: [],- components: a.components,+ components: cloneComponents(a.components),visible: a.visible,};});@@ -126,10 +133,48 @@ export function expandInstance(});const all = [...kept, ...added];+ // Second pass over the full id space (kept + added), so a re-parent onto an+ // added entity resolves and any still-unresolved target falls back to root.+ applyParentOverrides(all, delta.overrides, rootId, true);rebuildChildren(all);return { entities: all, rootId };}+/**+ * Apply structural `parent` overrides to flattened entities in place. Each moves+ * a prefab-origin entity under the runtime id of its new stable parent (`value`),+ * or under `rootId` when `value` is null. The instance root is never re-parented.+ * When `fallbackToRoot` is false a target absent from `entities` leaves the entity+ * where it is (a two-phase caller resolves added-entity targets in a later pass);+ * when true, a missing target falls back to `rootId`.+ */+function applyParentOverrides(+ entities: ProcessedEntity[],+ overrides: readonly PrefabOverride[],+ rootId: number,+ fallbackToRoot: boolean,+): void {+ const idByPrefabId = new Map<PrefabEntityId, number>();+ const byPrefabId = new Map<PrefabEntityId, ProcessedEntity>();+ for (const e of entities) {+ idByPrefabId.set(e.prefabEntityId, e.id);+ byPrefabId.set(e.prefabEntityId, e);+ }+ for (const o of overrides) {+ if (o.type !== 'parent') continue;+ const e = byPrefabId.get(o.prefabEntityId);+ if (!e || e.id === rootId) continue; // never re-parent the instance root+ const target = o.value == null ? null : String(o.value);+ if (target === null) {+ e.parent = rootId;+ continue;+ }+ const np = idByPrefabId.get(target);+ if (np !== undefined) e.parent = np;+ else if (fallbackToRoot) e.parent = rootId;+ }+}+/** Rebuild every entity's `children` array from its `parent` link (consistency). */export function rebuildChildren(entities: ProcessedEntity[]): void {const byId = new Map(entities.map((e) => [e.id, e]));@@ -296,8 +341,34 @@ export function applyDeltaToSource(source: PrefabData, delta: SourceDelta): Pref// 1. Property / component / name / visibility / metadata overrides.let next = applyOverridesToSource(source, delta.overrides);- // 2. Removed: drop each removed subtree root + descendants (never the root),- // and unlink them from any parent's children list.+ // 2. Re-parent overrides, BEFORE the removed-closure so an entity moved out+ // of a doomed subtree survives (mirrors expandInstance). Targets among the+ // source entities are re-linked; a target that is only an `added` entity is+ // left in place (added is appended below and is a niche Apply case).+ const parentOverrides = delta.overrides.filter((o) => o.type === 'parent');+ if (parentOverrides.length > 0) {+ const entities = next.entities.map((e) => ({ ...e, children: [...e.children] }));+ const byId = new Map<PrefabEntityId, PrefabEntityData>();+ for (const e of entities) byId.set(e.prefabEntityId, e);+ for (const o of parentOverrides) {+ const e = byId.get(o.prefabEntityId);+ if (!e || e.prefabEntityId === next.rootEntityId) continue;+ const newParent = o.value == null ? next.rootEntityId : String(o.value);+ const np = byId.get(newParent);+ if (!np || newParent === e.prefabEntityId) continue;+ if (isAncestor(byId, e.prefabEntityId, newParent)) continue; // would cycle+ if (e.parent != null) {+ const op = byId.get(e.parent);+ if (op) op.children = op.children.filter((c) => c !== e.prefabEntityId);+ }+ e.parent = newParent;+ if (!np.children.includes(e.prefabEntityId)) np.children.push(e.prefabEntityId);+ }+ next = { ...next, entities };+ }++ // 3. Removed: drop each removed subtree root + descendants (never the root),+ // and unlink them from any parent's children list. Runs AFTER re-parenting.if (delta.removed.length > 0) {const childrenOf = new Map<PrefabEntityId, PrefabEntityId[]>();for (const e of next.entities) childrenOf.set(e.prefabEntityId, e.children);@@ -319,12 +390,16 @@ export function applyDeltaToSource(source: PrefabData, delta: SourceDelta): Pref}}- // 3. Added: append new entities and link each under its parent (root default).+ // 4. Added: append new entities and link each under its parent (root default).if (delta.added.length > 0) {const entities: PrefabEntityData[] = next.entities.map((e) => ({ ...e, children: [...e.children] }));const byId = new Map<PrefabEntityId, PrefabEntityData>();for (const e of entities) byId.set(e.prefabEntityId, e);for (const a of delta.added) {+ // Identity must stay unique: an added id that already exists in the+ // source (e.g. a delta applied twice without re-diffing) would mint a+ // duplicate that mis-addresses every future override. Skip it.+ if (byId.has(a.prefabEntityId)) continue;const entity: PrefabEntityData = {prefabEntityId: a.prefabEntityId,name: a.name,@@ -346,6 +421,23 @@ export function applyDeltaToSource(source: PrefabData, delta: SourceDelta): Prefreturn next;}+/** Walk `node`'s parent chain in a stable-id entity map; true if `ancestor` is on+ * it (so re-parenting `ancestor` under `node` would create a cycle). */+function isAncestor(+ byId: Map<PrefabEntityId, PrefabEntityData>,+ ancestor: PrefabEntityId,+ node: PrefabEntityId,+): boolean {+ let cur: PrefabEntityId | null = node;+ const seen = new Set<PrefabEntityId>();+ while (cur != null && !seen.has(cur)) {+ if (cur === ancestor) return true;+ seen.add(cur);+ cur = byId.get(cur)?.parent ?? null;+ }+ return false;+}+/*** Build a prefab VARIANT that inherits `baseRef` and bakes an instance delta as* the variant's own authored state — the authoring inverse of instantiating adiff --git a/sdk/src/prefab/types.ts b/sdk/src/prefab/types.tsindex 5ab69c780..ae8e30c41 100644--- a/sdk/src/prefab/types.ts+++ b/sdk/src/prefab/types.ts@@ -72,6 +72,14 @@ export interface NestedPrefabRef {* Requires: componentType, propertyName, value.* - `name` — change the entity's name. Requires: value (string).* - `visibility` — change the entity's visibility. Requires: value (boolean).+ * - `parent` — re-parent a prefab-origin entity within the instance.+ * Requires: value = the new parent's stable+ * `PrefabEntityId`, or `null` for "under the instance+ * root". Structural: applied by `expandInstance` /+ * `applyDeltaToSource` (which own the id space), not by+ * `applyOverrides`. The instance root is never re-parented+ * this way — its attach point is the instance entry's own+ * `parent`.* - `component_added` — add a component **only if not already present*** (idempotent insert). Requires: componentData.* Use this for variants that want to *augment* the@@ -97,6 +105,7 @@ export interface PrefabOverride {| 'component_removed'| 'name'| 'visibility'+ | 'parent'| 'metadata_set'| 'metadata_removed';componentType?: string;diff --git a/sdk/src/prefab/validate.ts b/sdk/src/prefab/validate.tsindex 56823b242..1c00bf713 100644--- a/sdk/src/prefab/validate.ts+++ b/sdk/src/prefab/validate.ts@@ -155,6 +155,9 @@ function reasonForOverride(case 'metadata_set':case 'name':case 'visibility':+ case 'parent':+ // A re-parent's target-existence is a topology concern the strict+ // validator's parent/child passes cover; nothing entity-local is stale.return null;}}@@ -357,6 +360,10 @@ function overrideShapeError(o: PrefabOverride): string | null {return typeof o.value === 'string' ? null : 'name value must be a string';case 'visibility':return typeof o.value === 'boolean' ? null : 'visibility value must be a boolean';+ case 'parent':+ return typeof o.value === 'string' || o.value === null+ ? null+ : 'parent value must be a stable entity id or null';case 'metadata_set':case 'metadata_removed':return typeof o.metadataKey === 'string' ? null : 'missing metadataKey';diff --git a/sdk/tests/prefab-rigor.test.ts b/sdk/tests/prefab-rigor.test.tsindex 558c77060..45fc8be61 100644--- a/sdk/tests/prefab-rigor.test.ts+++ b/sdk/tests/prefab-rigor.test.ts@@ -28,6 +28,8 @@ import {bucketOverridesByEntity,expandInstance,collapseInstance,+ rebuildChildren,+ applyDeltaToSource,} from '../src/prefab/index';import type { FlattenContext, PrefabInstanceDelta } from '../src/prefab/index';import { defineComponent } from '../src/component';@@ -413,13 +415,17 @@ describe('parent/children consistency', () => {describe('diffAgainstSource', () => {function cloneForInstance(prefab: PrefabData): ProcessedEntity[] {- let n = 0;- return prefab.entities.map(e => {+ // Runtime ids in entity order; carry the source's parent topology so the+ // diff isolates the field under test (a null-parent fixture would now+ // spuriously trip the structural re-parent diff).+ const idByPid = new Map<string, number>();+ prefab.entities.forEach((e, i) => idByPid.set(e.prefabEntityId, i));+ return prefab.entities.map((e, i) => {const out: ProcessedEntity = {- id: n++,+ id: i,prefabEntityId: e.prefabEntityId,name: e.name,- parent: null,+ parent: e.parent != null ? (idByPid.get(e.parent) ?? null) : null,children: [],components: e.components.map(c => ({type: c.type,@@ -724,14 +730,16 @@ describe('diffAgainstSource — entity-ref fields', () => {};}- // Runtime ids assigned in entity order: leader=0, ally=1, follower=2.+ // Runtime ids assigned in entity order: leader=0, ally=1, follower=2. Parents+ // mirror the source topology so only the ref field under test can diff.function instance(prefab: PrefabData, followerTarget: number): ProcessedEntity[] {- let n = 0;- return prefab.entities.map((e) => ({- id: n++,+ const idByPid = new Map<string, number>();+ prefab.entities.forEach((e, i) => idByPid.set(e.prefabEntityId, i));+ return prefab.entities.map((e, i) => ({+ id: i,prefabEntityId: e.prefabEntityId,name: e.name,- parent: null,+ parent: e.parent != null ? (idByPid.get(e.parent) ?? null) : null,children: [],components: e.components.map((c) => ({type: c.type,@@ -888,6 +896,132 @@ describe('structural deletion', () => {});});+// ─── structural re-parenting (parent override) ─────────────────────────────++describe('structural re-parenting', () => {+ /** root → mid → leaf (a flat 3-generation prefab). */+ function chainPrefab(): PrefabData {+ return {+ version: PREFAB_FORMAT_VERSION, name: 'Chain', rootEntityId: 'root',+ entities: [+ { prefabEntityId: 'root', name: 'Root', parent: null, children: ['mid'], components: [], visible: true },+ { prefabEntityId: 'mid', name: 'Mid', parent: 'root', children: ['leaf'], components: [], visible: true },+ { prefabEntityId: 'leaf', name: 'Leaf', parent: 'mid', children: [], components: [], visible: true },+ ],+ };+ }++ /** Expand a baseline instance, mutate it, then collapse it back to a delta. */+ function roundTrip(prefab: PrefabData, mutate: (e: ProcessedEntity[]) => void): PrefabInstanceDelta {+ let nid = 0;+ const { entities } = expandInstance(prefab, { prefab: '@uuid:chain', overrides: [], added: [], removed: [] }, () => nid++);+ mutate(entities);+ rebuildChildren(entities);+ return collapseInstance(prefab, '@uuid:chain', entities);+ }++ it('a pure re-parent collapses to a parent override and expands back faithfully', () => {+ const prefab = chainPrefab();+ // Drag leaf out from under mid, up to root.+ const delta = roundTrip(prefab, (es) => {+ const root = es.find((e) => e.prefabEntityId === 'root')!;+ es.find((e) => e.prefabEntityId === 'leaf')!.parent = root.id;+ });+ expect(delta.overrides).toContainEqual({ prefabEntityId: 'leaf', type: 'parent', value: 'root' });+ expect(delta.removed).toEqual([]);+ expect(delta.added).toEqual([]);++ // Re-expand: leaf is now a child of root, not mid.+ let nid = 0;+ const { entities } = expandInstance(prefab, delta, () => nid++);+ const byAddr = new Map(entities.map((e) => [e.prefabEntityId, e]));+ const leaf = byAddr.get('leaf')!;+ expect(leaf.parent).toBe(byAddr.get('root')!.id);+ expect(byAddr.get('mid')!.children).not.toContain(leaf.id);+ expect(byAddr.get('root')!.children).toContain(leaf.id);+ });++ it('re-parenting OUT of a doomed subtree keeps the moved entity (no data loss)', () => {+ const prefab = chainPrefab();+ // Move leaf up to root, THEN delete mid — leaf must survive.+ const delta: PrefabInstanceDelta = {+ prefab: '@uuid:chain',+ overrides: [{ prefabEntityId: 'leaf', type: 'parent', value: 'root' }],+ added: [],+ removed: ['mid'],+ };+ let nid = 0;+ const { entities } = expandInstance(prefab, delta, () => nid++);+ const ids = entities.map((e) => e.prefabEntityId).sort();+ expect(ids).toEqual(['leaf', 'root']); // mid gone, leaf kept under root+ const byAddr = new Map(entities.map((e) => [e.prefabEntityId, e]));+ expect(byAddr.get('leaf')!.parent).toBe(byAddr.get('root')!.id);+ });++ it('applyDeltaToSource bakes a re-parent into the prefab topology', () => {+ const prefab = chainPrefab();+ const baked = applyDeltaToSource(prefab, {+ overrides: [{ prefabEntityId: 'leaf', type: 'parent', value: 'root' }],+ added: [],+ removed: [],+ });+ const byId = new Map(baked.entities.map((e) => [e.prefabEntityId, e]));+ expect(byId.get('leaf')!.parent).toBe('root');+ expect(byId.get('root')!.children).toContain('leaf');+ expect(byId.get('mid')!.children).not.toContain('leaf');+ });++ it('a re-parent that would create a cycle is refused by applyDeltaToSource', () => {+ const prefab = chainPrefab();+ // Try to make root a child of leaf (its own descendant) — must be a no-op.+ const baked = applyDeltaToSource(prefab, {+ overrides: [{ prefabEntityId: 'root', type: 'parent', value: 'leaf' }],+ added: [],+ removed: [],+ });+ const byId = new Map(baked.entities.map((e) => [e.prefabEntityId, e]));+ expect(byId.get('root')!.parent).toBe(null); // unchanged+ });+});++// ─── added-entity integrity (clone + uniqueness) ───────────────────────────++describe('added-entity integrity', () => {+ function rootWithAdd(): { prefab: PrefabData; delta: PrefabInstanceDelta } {+ const prefab: PrefabData = {+ version: PREFAB_FORMAT_VERSION, name: 'R', rootEntityId: 'root',+ entities: [{ prefabEntityId: 'root', name: 'Root', parent: null, children: [], components: [], visible: true }],+ };+ const delta: PrefabInstanceDelta = {+ prefab: '@uuid:r', overrides: [], removed: [],+ added: [{ prefabEntityId: 'x', name: 'X', parentId: null, visible: true, components: [{ type: 'Transform', data: { x: 1 } }] }],+ };+ return { prefab, delta };+ }++ it('added components are cloned per expansion (no aliasing into the stored delta)', () => {+ const { prefab, delta } = rootWithAdd();+ let a = 0;+ const A = expandInstance(prefab, delta, () => a++);+ let b = 100;+ const B = expandInstance(prefab, delta, () => b++);+ // Mutate expansion A's added component; B and the delta must be untouched.+ (A.entities.find((e) => e.prefabEntityId === 'x')!.components[0].data as { x: number }).x = 999;+ expect((B.entities.find((e) => e.prefabEntityId === 'x')!.components[0].data as { x: number }).x).toBe(1);+ expect((delta.added[0].components[0].data as { x: number }).x).toBe(1);+ });++ it('applyDeltaToSource skips an added id that already exists (no duplicate identity)', () => {+ const { prefab } = rootWithAdd();+ const baked = applyDeltaToSource(prefab, {+ overrides: [], removed: [],+ // 'root' already exists in the source — must not be duplicated.+ added: [{ prefabEntityId: 'root', name: 'Dupe', parentId: null, visible: true, components: [] }],+ });+ expect(baked.entities.filter((e) => e.prefabEntityId === 'root')).toHaveLength(1);+ });+});+// ─── validateOverrides: identity checks ────────────────────────────────────describe('validateOverrides identity', () => {