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
feat(prefab): hierarchical stable identity + structural deletion (P0)
yhhb2f1cd61023d
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex c6f5423a2..66615fe5c 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -7414,6 +7414,8 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef## ValidateResult — interface```+duplicateIds: string[]+invalidIds: string[]orphanedChildren: string[]stale: StaleOverride[]```@@ -8040,12 +8042,12 @@ BtPlugin## collapseEntry — function```-(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], rootId: number, sceneParent: number | null): PrefabInstanceEntry+(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], rootId: number, sceneParent: number | null, loadPrefab?: SyncPrefabResolver): PrefabInstanceEntry```## collapseInstance — function```-(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[]): PrefabInstanceDelta+(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```## collectNestedPrefabPaths — function@@ -8400,7 +8402,7 @@ DragPlugin## extractPrefab — function```-(entities: readonly ExtractEntity[], rootId: number, name: string): PrefabData+(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: () => PrefabEntityId): PrefabData```## facingFromQuat — functiondiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 20b3394d2..ad97552bf 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -7409,6 +7409,8 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef## ValidateResult — interface```+duplicateIds: string[]+invalidIds: string[]orphanedChildren: string[]stale: StaleOverride[]```@@ -8035,12 +8037,12 @@ BtPlugin## collapseEntry — function```-(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], rootId: number, sceneParent: number | null): PrefabInstanceEntry+(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], rootId: number, sceneParent: number | null, loadPrefab?: SyncPrefabResolver): PrefabInstanceEntry```## collapseInstance — function```-(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[]): PrefabInstanceDelta+(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```## collectNestedPrefabPaths — function@@ -8395,7 +8397,7 @@ DragPlugin## extractPrefab — function```-(entities: readonly ExtractEntity[], rootId: number, name: string): PrefabData+(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: () => PrefabEntityId): PrefabData```## facingFromQuat — functiondiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex df51ac5d6..0a8f76967 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -7416,6 +7416,8 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef## ValidateResult — interface```+duplicateIds: string[]+invalidIds: string[]orphanedChildren: string[]stale: StaleOverride[]```@@ -8059,12 +8061,12 @@ BtPlugin## collapseEntry — function```-(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], rootId: number, sceneParent: number | null): PrefabInstanceEntry+(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], rootId: number, sceneParent: number | null, loadPrefab?: SyncPrefabResolver): PrefabInstanceEntry```## collapseInstance — function```-(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[]): PrefabInstanceDelta+(prefab: PrefabData, prefabRef: string, expanded: readonly ProcessedEntity[], loadPrefab?: SyncPrefabResolver): PrefabInstanceDelta```## collectNestedPrefabPaths — function@@ -8419,7 +8421,7 @@ DragPlugin## extractPrefab — function```-(entities: readonly ExtractEntity[], rootId: number, name: string): PrefabData+(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: () => PrefabEntityId): PrefabData```## facingFromQuat — functiondiff --git a/sdk/src/prefab/diff.ts b/sdk/src/prefab/diff.tsindex 86bb26e52..cd6358a14 100644--- a/sdk/src/prefab/diff.ts+++ b/sdk/src/prefab/diff.ts@@ -3,7 +3,6 @@import type {ComponentData,PrefabData,- PrefabEntityData,PrefabEntityId,PrefabOverride,ProcessedEntity,@@ -74,16 +73,55 @@ export function diffAgainstSource(untracked: ProcessedEntity[];orphanedSourceIds: PrefabEntityId[];} {- const sourceById = new Map<PrefabEntityId, PrefabEntityData>();- for (const e of source.entities) sourceById.set(e.prefabEntityId, e);+ // A flat prefab's own `entities` list IS its pristine baseline (entity-ref+ // fields already in prefab-local id space). Nested prefabs must diff against+ // a flattened baseline instead — {@link diffEntities} — since their children+ // are not present in `source.entities`.+ return diffEntities(source.entities, instance, options);+}++/** The subset of an entity {@link diffEntities} reads. `PrefabEntityData` (raw+ * source, string entity-refs, no `id`) and `ProcessedEntity` (flattened+ * baseline / instance, numeric entity-refs + `id`) both satisfy it. */+export interface DiffBaselineEntity {+ prefabEntityId: PrefabEntityId;+ name: string;+ visible: boolean;+ components: ComponentData[];+ metadata?: Record<string, unknown>;+ /** Runtime id — present on flattened baselines so their entity-ref fields+ * normalise to stable-id space; absent on raw source entities. */+ id?: number;+}++/**+ * Diff an `instance` against a `baseline` (both keyed by the stable+ * `prefabEntityId` — a composed `slot/localId` address once nesting is+ * involved). Entity-ref component fields are normalised on BOTH sides to their+ * own runtime-id→stable-id space, so an unchanged cross-reference diffs equal+ * regardless of which side carries volatile runtime numbers.+ */+export function diffEntities(+ baseline: readonly DiffBaselineEntity[],+ instance: readonly ProcessedEntity[],+ options?: DiffOptions,+): {+ overrides: PrefabOverride[];+ untracked: ProcessedEntity[];+ orphanedSourceIds: PrefabEntityId[];+} {+ const baselineById = new Map<PrefabEntityId, DiffBaselineEntity>();+ for (const e of baseline) baselineById.set(e.prefabEntityId, e);const instanceByPrefabId = new Map<PrefabEntityId, ProcessedEntity>();for (const e of instance) instanceByPrefabId.set(e.prefabEntityId, e);- // Runtime entity id → its prefab-local id, so entity-ref fields can be diffed- // in the prefab's own id space instead of against volatile runtime numbers.- const runtimeToPrefabId = new Map<number, PrefabEntityId>();- for (const e of instance) runtimeToPrefabId.set(e.id, e.prefabEntityId);+ // Each side's runtime id → its stable id, so entity-ref fields diff in+ // stable-id space instead of against volatile runtime numbers.+ const baseRefMap = new Map<number, PrefabEntityId>();+ for (const e of baseline) if (e.id !== undefined) baseRefMap.set(e.id, e.prefabEntityId);+ const instRefMap = new Map<number, PrefabEntityId>();+ for (const e of instance) instRefMap.set(e.id, e.prefabEntityId);const ignoredMeta = new Set(options?.ignoreMetadataKeys ?? []);const ignoredNames = new Set(options?.ignoreEntityNames ?? []);@@ -95,20 +133,20 @@ export function diffAgainstSource(for (const instEntity of instance) {if (ignoredNames.has(instEntity.name)) continue;- const src = sourceById.get(instEntity.prefabEntityId);- if (!src) {+ const base = baselineById.get(instEntity.prefabEntityId);+ if (!base) {untracked.push(instEntity);continue;}- if (instEntity.name !== src.name) {+ if (instEntity.name !== base.name) {overrides.push({prefabEntityId: instEntity.prefabEntityId,type: 'name',value: instEntity.name,});}- if (instEntity.visible !== src.visible) {+ if (instEntity.visible !== base.visible) {overrides.push({prefabEntityId: instEntity.prefabEntityId,type: 'visibility',@@ -116,11 +154,11 @@ export function diffAgainstSource(});}- diffMetadata(src.metadata, instEntity.metadata, ignoredMeta, instEntity.prefabEntityId, overrides);- diffComponents(src.components, instEntity.components, instEntity.prefabEntityId, eps, overrides, runtimeToPrefabId);+ diffMetadata(base.metadata, instEntity.metadata, ignoredMeta, instEntity.prefabEntityId, overrides);+ diffComponents(base.components, instEntity.components, instEntity.prefabEntityId, eps, overrides, baseRefMap, instRefMap);}- for (const [id] of sourceById) {+ for (const [id] of baselineById) {if (!instanceByPrefabId.has(id)) orphanedSourceIds.push(id);}@@ -152,27 +190,28 @@ function diffMetadata(}function diffComponents(- srcComps: readonly ComponentData[],+ baseComps: readonly ComponentData[],instComps: readonly ComponentData[],entityId: PrefabEntityId,eps: number,out: PrefabOverride[],- runtimeToPrefabId: Map<number, PrefabEntityId>,+ baseRefMap: Map<number, PrefabEntityId>,+ instRefMap: Map<number, PrefabEntityId>,): void {- const srcByType = new Map<string, ComponentData>();- for (const c of srcComps) srcByType.set(c.type, c);+ const baseByType = new Map<string, ComponentData>();+ for (const c of baseComps) baseByType.set(c.type, c);const instByType = new Map<string, ComponentData>();for (const c of instComps) instByType.set(c.type, c);- for (const [type, srcComp] of srcByType) {+ for (const [type] of baseByType) {if (!instByType.has(type)) {out.push({ prefabEntityId: entityId, type: 'component_removed', componentType: type });}}for (const [type, instComp] of instByType) {- const srcComp = srcByType.get(type);- if (!srcComp) {+ const baseComp = baseByType.get(type);+ if (!baseComp) {out.push({prefabEntityId: entityId,type: 'component_added',@@ -186,15 +225,18 @@ function diffComponents(// whole component along.const entityFields = new Set(getComponent(type)?.entityFields ?? []);const keys = new Set<string>([- ...Object.keys(srcComp.data),+ ...Object.keys(baseComp.data),...Object.keys(instComp.data),]);for (const key of keys) {- const a = srcComp.data[key];- // Entity refs diff (and store) in prefab-local id space so an- // unchanged sibling ref isn't logged as a dangling numeric override.+ // Entity refs diff (and store) in stable-id space so an unchanged+ // cross-reference isn't logged as a dangling numeric override — both+ // sides normalise through their own runtime-id→stable-id map.+ const a = entityFields.has(key)+ ? normalizeEntityRef(baseComp.data[key], baseRefMap)+ : baseComp.data[key];const b = entityFields.has(key)- ? normalizeEntityRef(instComp.data[key], runtimeToPrefabId)+ ? normalizeEntityRef(instComp.data[key], instRefMap): instComp.data[key];if (!deepEqual(a, b, eps)) {out.push({diff --git a/sdk/src/prefab/flatten.ts b/sdk/src/prefab/flatten.tsindex 2a1aef598..09a766723 100644--- a/sdk/src/prefab/flatten.ts+++ b/sdk/src/prefab/flatten.ts@@ -9,12 +9,18 @@ import type {FlattenContext,FlattenResult,} from './types';+import { PREFAB_ADDRESS_SEP } from './types';import { cloneComponents, cloneMetadata } from './clone';import { remapComponentEntityRefs } from './entityRef';import { applyOverrides, bucketOverridesByEntity } from './override';const MAX_PREFAB_NESTING_DEPTH = 10;+/** Prefix a nested entity's stable id with the slot it was mounted through. */+function joinAddress(slotId: PrefabEntityId, localId: PrefabEntityId): PrefabEntityId {+ return `${slotId}${PREFAB_ADDRESS_SEP}${localId}`;+}+export function flattenPrefab(prefab: PrefabData,overrides: PrefabOverride[],@@ -65,16 +71,40 @@ export function flattenPrefab();}- // Once a prefab path is on the chain it stays on — cheaper than- // tracking a per-DFS-branch stack and matches the behaviour the- // test suite pins. A legitimate need for sibling repeats is best- // expressed with distinct prefab files.+ // Route overrides that address entities INSIDE this slot down into the+ // nested flatten. Instance deltas target nested entities by their+ // composed address (`slot/localId`); strip the slot prefix so they+ // apply in the nested prefab's own id space, and layer them after the+ // slot's authored overrides. This is what makes an instance override+ // on a nested entity survive the collapse→expand round trip.+ const slotPrefix = pe.prefabEntityId + PREFAB_ADDRESS_SEP;+ const routed = overrides+ .filter(o => o.prefabEntityId.startsWith(slotPrefix))+ .map(o => ({ ...o, prefabEntityId: o.prefabEntityId.slice(slotPrefix.length) }));+ const nestedOverrides = routed.length+ ? [...pe.nestedPrefab.overrides, ...routed]+ : pe.nestedPrefab.overrides;++ // DFS ancestor stack: a path counts as "visited" only while it is an+ // ancestor of the entity being flattened, so a genuine cycle still+ // throws but the SAME prefab may be mounted in several sibling slots+ // (e.g. four turrets on one ship). Pop once the branch returns.visited.add(nestedPath);const nested = flattenPrefab(nestedPrefab,- pe.nestedPrefab.overrides,+ nestedOverrides,{ ...ctx, visited, depth: depth + 1 },);+ visited.delete(nestedPath);++ // Namespace the nested subtree's stable ids by this slot so two+ // instantiations of the same prefab — or two prefabs reusing the same+ // local ids — never collide in the flattened set. Runtime `id`,+ // component data, and entity refs are untouched; only the identity+ // string used for diff/override/tag addressing is composed.+ for (const ne of nested.entities) {+ ne.prefabEntityId = joinAddress(pe.prefabEntityId, ne.prefabEntityId);+ }idMapping.set(pe.prefabEntityId, nested.rootId);@@ -169,11 +199,13 @@ function flattenVariant(const variantOverrides = variant.overrides ?? [];const combinedOverrides = [...variantOverrides, ...instanceOverrides];- return flattenPrefab(+ const result = flattenPrefab(merged,combinedOverrides,{ ...ctx, visited, depth: depth + 1 },);+ visited.delete(basePath); // pop the ancestor stack (see nested branch)+ return result;}function resolveVariantChain(@@ -204,7 +236,9 @@ function resolveVariantChain(const resolvedBase = base.basePrefab? resolveVariantChain(base, ctx, depth + 1, visited): base;- return mergeVariantEntities(resolvedBase, variant);+ const merged = mergeVariantEntities(resolvedBase, variant);+ visited.delete(basePath); // pop after the chain is merged (DFS stack)+ return merged;}function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabData {@@ -302,6 +336,15 @@ function validateParentChildConsistency(prefab: PrefabData): void {for (const e of prefab.entities) byId.set(e.prefabEntityId, e);for (const e of prefab.entities) {+ // The address separator is reserved so flatten can compose `slot/localId`+ // paths unambiguously — an authored id must never contain it.+ if (e.prefabEntityId.includes(PREFAB_ADDRESS_SEP)) {+ throw new Error(+ `Prefab "${prefab.name}" entity id "${e.prefabEntityId}" contains the ` ++ `reserved separator "${PREFAB_ADDRESS_SEP}". Authored prefab entity ids ` ++ `must not contain it.`,+ );+ }if (e.parent !== null) {const parent = byId.get(e.parent);if (!parent) {diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.tsindex b9da16e23..4a93fcd60 100644--- a/sdk/src/prefab/sceneInstance.ts+++ b/sdk/src/prefab/sceneInstance.ts@@ -27,7 +27,8 @@*/import { flattenPrefab } from './flatten';-import { diffAgainstSource } from './diff';+import { diffEntities } from './diff';+import type { DiffBaselineEntity } from './diff';import { cloneComponents } from './clone';import { getComponent } from '../component';import { PREFAB_FORMAT_VERSION } from './migrate';@@ -94,7 +95,10 @@ export function expandInstance(loadPrefab,});- const removed = new Set(delta.removed);+ // `removed` records the ROOTS of deleted subtrees; expand the transitive+ // closure over the flattened 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));// prefabEntityId → runtime id, for both kept prefab entities and added ones.@@ -133,6 +137,36 @@ export function rebuildChildren(entities: ProcessedEntity[]): void {}}+/**+ * The full set of stable ids to drop for a `removed` list of subtree roots:+ * each root plus every descendant, walked over the flattened entities' parent+ * links (in composed-address space, so it cascades through nested boundaries).+ */+function removedClosure(+ entities: readonly ProcessedEntity[],+ removedRoots: readonly PrefabEntityId[],+): Set<PrefabEntityId> {+ const addrById = new Map(entities.map((e) => [e.id, e.prefabEntityId]));+ const childrenByAddr = new Map<PrefabEntityId, PrefabEntityId[]>();+ for (const e of entities) {+ if (e.parent == null) continue;+ const parentAddr = addrById.get(e.parent);+ if (parentAddr === undefined) continue;+ const list = childrenByAddr.get(parentAddr);+ if (list) list.push(e.prefabEntityId);+ else childrenByAddr.set(parentAddr, [e.prefabEntityId]);+ }+ const closure = new Set<PrefabEntityId>();+ const queue = [...removedRoots];+ while (queue.length > 0) {+ const cur = queue.shift()!;+ if (closure.has(cur)) continue;+ closure.add(cur);+ for (const child of childrenByAddr.get(cur) ?? []) queue.push(child);+ }+ return closure;+}+/*** Collapse expanded instance entities back to a delta. `diffAgainstSource`* yields the override list + the structural buckets (`untracked` → added,@@ -142,8 +176,10 @@ export function collapseInstance(prefab: PrefabData,prefabRef: string,expanded: readonly ProcessedEntity[],+ loadPrefab: SyncPrefabResolver = NO_NESTED,): PrefabInstanceDelta {- const { overrides, untracked, orphanedSourceIds } = diffAgainstSource(prefab, expanded);+ const { entities: baseline, parentOf } = collapseBaseline(prefab, loadPrefab);+ const { overrides, untracked, orphanedSourceIds } = diffEntities(baseline, expanded);const byId = new Map(expanded.map((e) => [e.id, e]));const added: AddedEntity[] = untracked.map((u) => ({prefabEntityId: u.prefabEntityId,@@ -152,7 +188,42 @@ export function collapseInstance(visible: u.visible,parentId: u.parent != null ? (byId.get(u.parent)?.prefabEntityId ?? null) : null,}));- return { prefab: prefabRef, overrides, added, removed: orphanedSourceIds };+ // Record only the ROOTS of removed subtrees (a deleted entity whose baseline+ // parent is still present); expand recomputes the descendant closure.+ const removedSet = new Set(orphanedSourceIds);+ const removed = orphanedSourceIds.filter((id) => {+ const p = parentOf.get(id);+ return p == null || !removedSet.has(p);+ });+ return { prefab: prefabRef, overrides, added, removed };+}++/**+ * The pristine baseline to diff a collapsed instance against, plus each baseline+ * entity's parent (in stable-id space) for subtree-root minimisation. A FLAT+ * prefab's own `entities` list already IS that baseline (entity refs in+ * prefab-local id space); a nested prefab is flattened so its children exist in+ * composed-address space — `loadPrefab` resolves the nested refs synchronously,+ * so callers with nested prefabs must preload them.+ */+function collapseBaseline(+ prefab: PrefabData,+ loadPrefab: SyncPrefabResolver,+): { entities: DiffBaselineEntity[]; parentOf: Map<PrefabEntityId, PrefabEntityId | null> } {+ const hasNested = !!prefab.basePrefab || prefab.entities.some((e) => e.nestedPrefab);+ if (!hasNested) {+ const parentOf = new Map<PrefabEntityId, PrefabEntityId | null>();+ for (const e of prefab.entities) parentOf.set(e.prefabEntityId, e.parent);+ return { entities: prefab.entities, parentOf };+ }+ let nid = 0;+ const flat = flattenPrefab(prefab, [], { allocateId: () => nid++, loadPrefab }).entities;+ const addrById = new Map(flat.map((e) => [e.id, e.prefabEntityId]));+ const parentOf = new Map<PrefabEntityId, PrefabEntityId | null>();+ for (const e of flat) {+ parentOf.set(e.prefabEntityId, e.parent != null ? (addrById.get(e.parent) ?? null) : null);+ }+ return { entities: flat, parentOf };}// ── Scene-entry boundary ────────────────────────────────────────────────────@@ -195,8 +266,9 @@ export function collapseEntry(expanded: readonly ProcessedEntity[],rootId: number,sceneParent: number | null,+ loadPrefab: SyncPrefabResolver = NO_NESTED,): PrefabInstanceEntry {- return { id: rootId, parent: sceneParent, ...collapseInstance(prefab, prefabRef, expanded) };+ return { id: rootId, parent: sceneParent, ...collapseInstance(prefab, prefabRef, expanded, loadPrefab) };}// ── Authoring: live entities → a new prefab asset ───────────────────────────@@ -246,11 +318,15 @@ export function extractPrefab(entities: readonly ExtractEntity[],rootId: number,name: string,+ makeId: () => PrefabEntityId = () => crypto.randomUUID(),): PrefabData {- // Root first so it gets a deterministic id and reads first in the file.+ // Root first so it reads first in the file. Ids are minted by `makeId`+ // (UUIDs by default) so a newly authored prefab's entity identities are+ // globally unique — two prefabs, or two instantiations of one, never share+ // a `prefabEntityId` and so never collide when nested (see PREFAB_ADDRESS_SEP).const ordered = [...entities].sort((a, b) => (a.id === rootId ? -1 : b.id === rootId ? 1 : 0));const idMap = new Map<number, string>();- ordered.forEach((e, i) => idMap.set(e.id, String(i)));+ ordered.forEach((e) => idMap.set(e.id, makeId()));const inSubtree = (sid: number | null): boolean => sid != null && idMap.has(sid);const prefabEntities: PrefabEntityData[] = ordered.map((e) => ({diff --git a/sdk/src/prefab/types.ts b/sdk/src/prefab/types.tsindex 59b3ca443..5ab69c780 100644--- a/sdk/src/prefab/types.ts+++ b/sdk/src/prefab/types.ts@@ -16,6 +16,18 @@ export interface ComponentData {*/export type PrefabEntityId = string;+/**+ * Reserved separator that composes a flattened entity's HIERARCHICAL address.+ *+ * A nested prefab's entities are namespaced by the slot they were mounted+ * through, so `flattenPrefab` yields `slotId/…/localId` for anything reached+ * across a nesting boundary (top-level entities keep their bare id). This makes+ * the stable `prefabEntityId` on a flattened `ProcessedEntity` globally unique+ * within one instance — even when the same prefab is mounted in several sibling+ * slots. Authored `prefabEntityId`s must not contain this character.+ */+export const PREFAB_ADDRESS_SEP = '/';+export interface PrefabData {version: string;name: string;diff --git a/sdk/src/prefab/validate.ts b/sdk/src/prefab/validate.tsindex dad12192f..9bce3932f 100644--- a/sdk/src/prefab/validate.ts+++ b/sdk/src/prefab/validate.ts@@ -6,6 +6,7 @@ import type {PrefabEntityId,PrefabOverride,} from './types';+import { PREFAB_ADDRESS_SEP } from './types';export interface StaleOverride {override: PrefabOverride;@@ -25,6 +26,18 @@ export interface ValidateResult {* diagnostic the editor can surface before flatten.*/orphanedChildren: PrefabEntityId[];+ /**+ * Entity ids that appear on more than one entry. Identity must be unique+ * within a prefab or overrides/diff address the wrong target; the editor+ * must never mint a colliding id (it uses UUIDs).+ */+ duplicateIds: PrefabEntityId[];+ /**+ * Entity ids containing the reserved address separator (`/`). Flatten+ * composes `slot/localId` addresses with it, so an authored id must not+ * contain it — flatten rejects these hard; this is the soft pre-check.+ */+ invalidIds: PrefabEntityId[];}/**@@ -47,9 +60,17 @@ export function validateOverrides(): ValidateResult {const stale: StaleOverride[] = [];const orphanedChildren: PrefabEntityId[] = [];+ const duplicateIds: PrefabEntityId[] = [];+ const invalidIds: PrefabEntityId[] = [];const byId = new Map<PrefabEntityId, PrefabEntityData>();- for (const e of prefab.entities) byId.set(e.prefabEntityId, e);+ const seenIds = new Set<PrefabEntityId>();+ for (const e of prefab.entities) {+ if (e.prefabEntityId.includes(PREFAB_ADDRESS_SEP)) invalidIds.push(e.prefabEntityId);+ if (seenIds.has(e.prefabEntityId)) duplicateIds.push(e.prefabEntityId);+ else seenIds.add(e.prefabEntityId);+ byId.set(e.prefabEntityId, e);+ }for (const e of prefab.entities) {for (const childId of e.children) {@@ -105,7 +126,7 @@ export function validateOverrides(}}- return { stale, orphanedChildren };+ return { stale, orphanedChildren, duplicateIds, invalidIds };}function reasonForOverride(diff --git a/sdk/src/ui/widgets/toPrefab.ts b/sdk/src/ui/widgets/toPrefab.tsindex f23207d7a..c2575fd8f 100644--- a/sdk/src/ui/widgets/toPrefab.ts+++ b/sdk/src/ui/widgets/toPrefab.ts@@ -110,5 +110,9 @@ export function widgetToPrefab(build: (world: World) => Entity, name: string): Pvisible: true,};});- return extractPrefab(entities, root, name);+ // Deterministic sequential ids ('0','1',…) — these prefabs are committed+ // codegen output, so their identities must be byte-stable across runs (a+ // UUID default would drift the generated `.esprefab` files every build).+ let n = 0;+ return extractPrefab(entities, root, name, () => String(n++));}diff --git a/sdk/tests/prefab-rigor.test.ts b/sdk/tests/prefab-rigor.test.tsindex 04b82f345..f3f5b1dd0 100644--- a/sdk/tests/prefab-rigor.test.ts+++ b/sdk/tests/prefab-rigor.test.ts@@ -26,10 +26,49 @@ import {import {flattenPrefab,bucketOverridesByEntity,+ expandInstance,+ collapseInstance,} from '../src/prefab/index';-import type { FlattenContext } from '../src/prefab/index';+import type { FlattenContext, PrefabInstanceDelta } from '../src/prefab/index';import { defineComponent } from '../src/component';+// ─── Shared fixtures for hierarchical-address / structural-deletion suites ───++/** A tiny 2-entity prefab: root '0' + child '1' (ids two prefabs will reuse). */+function leafPrefab(name: string): PrefabData {+ return {+ version: PREFAB_FORMAT_VERSION,+ name,+ rootEntityId: '0',+ entities: [+ { prefabEntityId: '0', name: `${name}Root`, parent: null, children: ['1'], components: [{ type: 'Transform', data: { x: 0 } }], visible: true },+ { prefabEntityId: '1', name: `${name}Child`, parent: '0', children: [], components: [], visible: true },+ ],+ };+}++/** An outer prefab mounting `slots` as nested-prefab children under its root. */+function shipWithSlots(slots: Array<{ id: string; path: string }>): PrefabData {+ return {+ version: PREFAB_FORMAT_VERSION,+ name: 'Ship',+ rootEntityId: 'ship',+ entities: [+ { prefabEntityId: 'ship', name: 'Ship', parent: null, children: slots.map((s) => s.id), components: [], visible: true },+ ...slots.map((s) => ({+ prefabEntityId: s.id, name: `Slot_${s.id}`, parent: 'ship', children: [], components: [], visible: true,+ nestedPrefab: { prefabPath: s.path, overrides: [] },+ })),+ ],+ };+}++function ctxWith(prefabs: Record<string, PrefabData>): FlattenContext {+ let n = 0;+ return { allocateId: () => n++, loadPrefab: (p) => prefabs[p] ?? null, visited: new Set() };+}+const loaderFor = (prefabs: Record<string, PrefabData>) => (p: string) => prefabs[p] ?? null;+function uuidPrefab(): PrefabData {return {version: PREFAB_FORMAT_VERSION,@@ -710,6 +749,154 @@ describe('diffAgainstSource — entity-ref fields', () => {});});+// ─── Hierarchical addressing (nested identity, sibling repeats) ────────────++describe('hierarchical addressing', () => {+ it('mounts the SAME prefab in two sibling slots — distinct composed addresses, no throw', () => {+ const turret = leafPrefab('Turret');+ const ship = shipWithSlots([{ id: 'a', path: 'turret' }, { id: 'b', path: 'turret' }]);+ const { entities } = flattenPrefab(ship, [], ctxWith({ turret }));+ const ids = entities.map((e) => e.prefabEntityId);+ // Each slot namespaces the turret's local ids by the slot it mounted through.+ expect(ids).toEqual(expect.arrayContaining(['ship', 'a/0', 'a/1', 'b/0', 'b/1']));+ // No duplicate stable ids across the whole flattened set (the old global+ // `visited` set forbade this repeat entirely).+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('two DIFFERENT nested prefabs that both use "0"/"1" do not collide', () => {+ const engine = leafPrefab('Engine');+ const wing = leafPrefab('Wing');+ const ship = shipWithSlots([{ id: 'e', path: 'engine' }, { id: 'w', path: 'wing' }]);+ const { entities } = flattenPrefab(ship, [], ctxWith({ engine, wing }));+ const ids = entities.map((e) => e.prefabEntityId);+ expect(new Set(ids).size).toBe(ids.length);+ expect(ids).toEqual(expect.arrayContaining(['e/0', 'e/1', 'w/0', 'w/1']));+ });++ it('still detects a genuine self-cycle (a prefab nesting itself)', () => {+ const self: PrefabData = {+ version: PREFAB_FORMAT_VERSION, name: 'Self', rootEntityId: '0',+ entities: [+ { prefabEntityId: '0', name: 'Root', parent: null, children: ['1'], components: [], visible: true },+ { prefabEntityId: '1', name: 'Slot', parent: '0', children: [], components: [], visible: true, nestedPrefab: { prefabPath: 'self', overrides: [] } },+ ],+ };+ expect(() => flattenPrefab(self, [], ctxWith({ self }))).toThrow(/Circular reference/);+ });++ it('rejects an authored id containing the reserved address separator', () => {+ const bad: PrefabData = {+ version: PREFAB_FORMAT_VERSION, name: 'Bad', rootEntityId: 'a/b',+ entities: [{ prefabEntityId: 'a/b', name: 'X', parent: null, children: [], components: [], visible: true }],+ };+ expect(() => flattenPrefab(bad, [], freshCtx())).toThrow(/reserved separator/);+ });+});++// ─── Nested-instance delta round-trip (override on a nested entity) ─────────++describe('nested-instance delta', () => {+ it('routes an override onto a nested entity and round-trips it through collapse', () => {+ const turret = leafPrefab('Turret');+ const ship = shipWithSlots([{ id: 'a', path: 'turret' }]);+ const load = loaderFor({ turret });+ const delta: PrefabInstanceDelta = {+ prefab: '@uuid:ship',+ overrides: [{ prefabEntityId: 'a/1', type: 'name', value: 'CustomChild' }],+ added: [],+ removed: [],+ };+ let nid = 0;+ const { entities } = expandInstance(ship, delta, () => nid++, load);+ // The composed-address override was routed down into the nested flatten.+ expect(entities.find((e) => e.prefabEntityId === 'a/1')?.name).toBe('CustomChild');++ const back = collapseInstance(ship, '@uuid:ship', entities, load);+ expect(back.overrides).toContainEqual({ prefabEntityId: 'a/1', type: 'name', value: 'CustomChild' });+ expect(back.added).toEqual([]);+ expect(back.removed).toEqual([]);+ });+});++// ─── Structural deletion: subtree cascade + minimal recording ──────────────++describe('structural deletion', () => {+ /** 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 },+ ],+ };+ }++ it('removing a parent drops its whole subtree; collapse records only the subtree root', () => {+ const prefab = chainPrefab();+ const delta: PrefabInstanceDelta = { prefab: '@uuid:chain', overrides: [], added: [], removed: ['mid'] };+ let nid = 0;+ const { entities } = expandInstance(prefab, delta, () => nid++);+ const ids = entities.map((e) => e.prefabEntityId);+ expect(ids).toEqual(['root']); // mid + its descendant leaf both gone+ // Collapse: both mid and leaf are absent from the instance, but only the+ // subtree root `mid` is recorded (leaf's parent is itself removed).+ const back = collapseInstance(prefab, '@uuid:chain', entities);+ expect(back.removed).toEqual(['mid']);+ });++ it('a leaf deletion still records just the leaf', () => {+ const prefab = chainPrefab();+ const delta: PrefabInstanceDelta = { prefab: '@uuid:chain', overrides: [], added: [], removed: ['leaf'] };+ let nid = 0;+ const { entities } = expandInstance(prefab, delta, () => nid++);+ expect(entities.map((e) => e.prefabEntityId).sort()).toEqual(['mid', 'root']);+ const back = collapseInstance(prefab, '@uuid:chain', entities);+ expect(back.removed).toEqual(['leaf']);+ });++ it('cascades across a nested boundary (remove the nested root)', () => {+ const turret = leafPrefab('Turret');+ const ship = shipWithSlots([{ id: 'a', path: 'turret' }]);+ const load = loaderFor({ turret });+ const delta: PrefabInstanceDelta = { prefab: '@uuid:ship', overrides: [], added: [], removed: ['a/0'] };+ let nid = 0;+ const { entities } = expandInstance(ship, delta, () => nid++, load);+ const ids = entities.map((e) => e.prefabEntityId);+ expect(ids).not.toContain('a/0');+ expect(ids).not.toContain('a/1'); // nested child cascaded away+ expect(ids).toContain('ship');+ const back = collapseInstance(ship, '@uuid:ship', entities, load);+ expect(back.removed).toEqual(['a/0']);+ });+});++// ─── validateOverrides: identity checks ────────────────────────────────────++describe('validateOverrides identity', () => {+ it('flags duplicate ids and ids containing the reserved separator', () => {+ const prefab: PrefabData = {+ version: PREFAB_FORMAT_VERSION, name: 'Dup', rootEntityId: 'root',+ entities: [+ { prefabEntityId: 'root', name: 'Root', parent: null, children: [], components: [], visible: true },+ { prefabEntityId: 'root', name: 'Dupe', parent: null, children: [], components: [], visible: true },+ { prefabEntityId: 'a/b', name: 'Bad', parent: null, children: [], components: [], visible: true },+ ],+ };+ const { duplicateIds, invalidIds } = validateOverrides(prefab);+ expect(duplicateIds).toEqual(['root']);+ expect(invalidIds).toEqual(['a/b']);+ });++ it('is clean for a well-formed prefab', () => {+ const { duplicateIds, invalidIds } = validateOverrides(uuidPrefab());+ expect(duplicateIds).toEqual([]);+ expect(invalidIds).toEqual([]);+ });+});+// ─── Self-smoke ──────────────────────────────────────────────// Guard against accidentally removing the vi import when trimming.vi.fn;diff --git a/sdk/tests/scene-prefab.test.ts b/sdk/tests/scene-prefab.test.tsindex 9aeba6414..a053772b2 100644--- a/sdk/tests/scene-prefab.test.ts+++ b/sdk/tests/scene-prefab.test.ts@@ -232,13 +232,16 @@ describe('Prefab scene loading (PF1)', () => {});// ── extractPrefab: live subtree → a new prefab asset (the authoring path). ──- it('extractPrefab builds a PrefabData from a subtree (root first, string ids, detached, deep-cloned)', () => {+ it('extractPrefab builds a PrefabData from a subtree (root first, minted ids, detached, deep-cloned)', () => {const subtree: ExtractEntity[] = [{ id: 10, name: 'Turret', parent: 5 /* external scene parent */, children: [11, 12], components: [{ type: 'Transform', data: { position: { x: 3, y: 4, z: 0 } } }], visible: true },{ id: 11, name: 'Barrel', parent: 10, children: [], components: [{ type: 'Sprite', data: {} }], visible: true },{ id: 12, name: 'Scope', parent: 10, children: [], components: [], visible: false },];- const prefab = extractPrefab(subtree, 10, 'Turret');+ // Inject a deterministic id generator so the test can pin identity; the+ // editor uses the default (crypto.randomUUID) for globally-unique ids.+ let n = 0;+ const prefab = extractPrefab(subtree, 10, 'Turret', () => String(n++));expect(prefab.name).toBe('Turret');expect(prefab.rootEntityId).toBe('0');@@ -256,6 +259,21 @@ describe('Prefab scene loading (PF1)', () => {expect((root.components[0].data.position as { x: number }).x).toBe(3);});+ it('extractPrefab mints a fresh UUID per entity by default (globally-unique identity)', () => {+ const subtree: ExtractEntity[] = [+ { id: 10, name: 'Turret', parent: null, children: [11], components: [], visible: true },+ { id: 11, name: 'Barrel', parent: 10, children: [], components: [], visible: true },+ ];+ const prefab = extractPrefab(subtree, 10, 'Turret');+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+ for (const e of prefab.entities) expect(e.prefabEntityId).toMatch(UUID);+ expect(prefab.rootEntityId).toBe(prefab.entities[0].prefabEntityId);+ // Two extractions never share an id (the old String(i) counter would).+ const other = extractPrefab(subtree, 10, 'Turret');+ const ids = new Set([...prefab.entities, ...other.entities].map((e) => e.prefabEntityId));+ expect(ids.size).toBe(4);+ });+it('extract → flatten round-trips: a created prefab instantiates back to the same entities', () => {const subtree: ExtractEntity[] = [{ id: 10, name: 'Turret', parent: null, children: [11], components: [{ type: 'Transform', data: { position: { x: 1, y: 2, z: 0 } } }], visible: true },