Skip to content

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.

feat(sdk): editor-grade prefab data model

esengine6a015bdb4ffe
diff --git a/examples/space-shooter/src/resources.ts b/examples/space-shooter/src/resources.ts
index 7940712ef..ffd9722f9 100644
--- a/examples/space-shooter/src/resources.ts
+++ b/examples/space-shooter/src/resources.ts
@@ -30,7 +30,7 @@ export const PREFAB_STAR = 'assets/prefabs/Star.esprefab';
export function positionOverride(x: number, y: number): PrefabOverride {
return {
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType: 'Transform',
propertyName: 'position',
@@ -40,7 +40,7 @@ export function positionOverride(x: number, y: number): PrefabOverride {
export function propOverride(componentType: string, propertyName: string, value: unknown): PrefabOverride {
return {
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType,
propertyName,
diff --git a/sdk/src/asset/loaders/PrefabAssetLoader.ts b/sdk/src/asset/loaders/PrefabAssetLoader.ts
index 5f200571d..41465a64f 100644
--- a/sdk/src/asset/loaders/PrefabAssetLoader.ts
+++ b/sdk/src/asset/loaders/PrefabAssetLoader.ts
@@ -1,5 +1,6 @@
import type { AssetLoader, LoadContext, PrefabResult } from '../AssetLoader';
-import type { PrefabData } from '../../prefab';
+import { migratePrefabData } from '../../prefab';
+import { log } from '../../logger';
export class PrefabAssetLoader implements AssetLoader<PrefabResult> {
readonly type = 'prefab';
@@ -8,7 +9,14 @@ export class PrefabAssetLoader implements AssetLoader<PrefabResult> {
async load(path: string, ctx: LoadContext): Promise<PrefabResult> {
const buildPath = ctx.catalog.getBuildPath(path);
const text = await ctx.loadText(buildPath);
- const data = JSON.parse(text) as PrefabData;
+ const raw = JSON.parse(text) as unknown;
+ const { data, migrated, fromVersion, toVersion } = migratePrefabData(raw);
+ if (migrated) {
+ log.info(
+ 'prefab',
+ `migrated "${path}" ${fromVersion} → ${toVersion} (legacy numeric ids → strings). Re-save to persist.`,
+ );
+ }
return { data };
}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 3903d5566..6c1997a68 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -122,15 +122,26 @@ export {
export {
flattenPrefab,
applyOverrides,
+ bucketOverridesByEntity,
remapComponentEntityRefs,
cloneComponents,
cloneComponentData,
+ cloneMetadata,
collectNestedPrefabPaths,
preloadNestedPrefabs,
+ migratePrefabData,
+ PREFAB_FORMAT_VERSION,
+ diffAgainstSource,
+ validateOverrides,
+ type PrefabEntityId,
type ProcessedEntity,
type FlattenContext,
type FlattenResult,
type ComponentData as PrefabComponentData,
+ type MigrationResult,
+ type DiffOptions,
+ type ValidateResult,
+ type StaleOverride,
} from './prefab/index';
export { Prefabs, PrefabServer, PrefabsPlugin, prefabsPlugin } from './prefabServer';
diff --git a/sdk/src/prefab.ts b/sdk/src/prefab.ts
index ba5b55fd1..b0807ce98 100644
--- a/sdk/src/prefab.ts
+++ b/sdk/src/prefab.ts
@@ -5,12 +5,33 @@ import { loadSceneWithAssets, type SceneData } from './scene';
import {
flattenPrefab,
preloadNestedPrefabs,
+ migratePrefabData,
type PrefabData,
type PrefabOverride,
type FlattenContext,
} from './prefab/index';
-export type { PrefabData, PrefabEntityData, PrefabOverride, NestedPrefabRef } from './prefab/index';
+export type {
+ PrefabData,
+ PrefabEntityData,
+ PrefabEntityId,
+ PrefabOverride,
+ NestedPrefabRef,
+ ProcessedEntity,
+ MigrationResult,
+ DiffOptions,
+ ValidateResult,
+ StaleOverride,
+} from './prefab/index';
+export {
+ migratePrefabData,
+ diffAgainstSource,
+ validateOverrides,
+ PREFAB_FORMAT_VERSION,
+ cloneComponentData,
+ cloneMetadata,
+ bucketOverridesByEntity,
+} from './prefab/index';
export interface InstantiatePrefabOptions {
assets?: Assets;
@@ -29,15 +50,22 @@ export async function instantiatePrefab(
prefab: PrefabData,
options?: InstantiatePrefabOptions,
): Promise<InstantiatePrefabResult> {
+ // Accept both current and legacy formats — callers that hand us raw JSON
+ // from disk no longer have to migrate it themselves.
+ const migratedTop = migratePrefabData(prefab);
+ const normalized = migratedTop.data;
+
const prefabCache = new Map<string, PrefabData>();
if (options?.assets) {
const assets = options.assets;
await preloadNestedPrefabs(
- prefab,
+ normalized,
async (path) => {
const result = await assets.loadPrefab(path);
- return result.data as PrefabData;
+ // Safety net: asset loader already migrates, but if a caller
+ // side-loaded a PrefabData manually, re-migration is idempotent.
+ return migratePrefabData(result.data as PrefabData).data;
},
prefabCache,
);
@@ -52,14 +80,14 @@ export async function instantiatePrefab(
};
const { entities: processed, rootId } = flattenPrefab(
- prefab,
+ normalized,
options?.overrides ?? [],
ctx,
);
const sceneData: SceneData = {
- version: prefab.version,
- name: prefab.name,
+ version: normalized.version,
+ name: normalized.name,
entities: processed.map(e => ({
id: e.id,
name: e.name,
diff --git a/sdk/src/prefab/clone.ts b/sdk/src/prefab/clone.ts
index 283e26d48..b21161085 100644
--- a/sdk/src/prefab/clone.ts
+++ b/sdk/src/prefab/clone.ts
@@ -10,3 +10,7 @@ export function cloneComponents(components: ComponentData[]): ComponentData[] {
export function cloneComponentData(data: Record<string, unknown>): Record<string, unknown> {
return JSON.parse(JSON.stringify(data));
}
+
+export function cloneMetadata(metadata: Record<string, unknown>): Record<string, unknown> {
+ return JSON.parse(JSON.stringify(metadata));
+}
diff --git a/sdk/src/prefab/diff.ts b/sdk/src/prefab/diff.ts
new file mode 100644
index 000000000..156bf21db
--- /dev/null
+++ b/sdk/src/prefab/diff.ts
@@ -0,0 +1,207 @@
+import type {
+ ComponentData,
+ PrefabData,
+ PrefabEntityData,
+ PrefabEntityId,
+ PrefabOverride,
+ ProcessedEntity,
+} from './types';
+
+export interface DiffOptions {
+ /**
+ * Metadata keys whose presence/value should not produce diffs. Editor
+ * selection markers, per-panel UI state, and prefab-tracking metadata
+ * that belongs on the *instance root* rather than the prefab itself
+ * typically live here (e.g. `prefab:source`, `prefab:overrides`).
+ */
+ ignoreMetadataKeys?: readonly string[];
+ /**
+ * Entity names whose children should be excluded from the diff entirely
+ * (useful for editor-only scaffolding entities).
+ */
+ ignoreEntityNames?: readonly string[];
+ /**
+ * Optional numeric tolerance for float equality checks. Defaults to 0
+ * (exact equality). Raise to tame small FP drift from Transform math.
+ */
+ floatEpsilon?: number;
+}
+
+/**
+ * Compute the minimal `PrefabOverride[]` that, applied to `source`, produces
+ * the `instance` state. The editor calls this on every change to an instance
+ * to keep `prefab:overrides` accurate.
+ *
+ * Contract:
+ * applyOverrides(flattenPrefab(source, [], ctx), diffAgainstSource(source, instance))
+ * reproduces `instance` modulo runtime id remapping.
+ *
+ * Current scope:
+ * - Handles property / component_added / component_replaced / component_removed
+ * / name / visibility / metadata_set / metadata_removed
+ * - Handles instance entities that are NEW relative to source (reports them
+ * via `untracked` — caller decides whether to surface as variant additions
+ * or error)
+ * - Does NOT yet emit "entity_removed" overrides (entity deletion from an
+ * instance has no override type today); missing entities are reported via
+ * `orphanedSourceIds`.
+ */
+export function diffAgainstSource(
+ source: PrefabData,
+ instance: readonly ProcessedEntity[],
+ options?: DiffOptions,
+): {
+ overrides: PrefabOverride[];
+ untracked: ProcessedEntity[];
+ orphanedSourceIds: PrefabEntityId[];
+} {
+ const sourceById = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const e of source.entities) sourceById.set(e.prefabEntityId, e);
+
+ const instanceByPrefabId = new Map<PrefabEntityId, ProcessedEntity>();
+ for (const e of instance) instanceByPrefabId.set(e.prefabEntityId, e);
+
+ const ignoredMeta = new Set(options?.ignoreMetadataKeys ?? []);
+ const ignoredNames = new Set(options?.ignoreEntityNames ?? []);
+ const eps = options?.floatEpsilon ?? 0;
+
+ const overrides: PrefabOverride[] = [];
+ const untracked: ProcessedEntity[] = [];
+ const orphanedSourceIds: PrefabEntityId[] = [];
+
+ for (const instEntity of instance) {
+ if (ignoredNames.has(instEntity.name)) continue;
+ const src = sourceById.get(instEntity.prefabEntityId);
+ if (!src) {
+ untracked.push(instEntity);
+ continue;
+ }
+
+ if (instEntity.name !== src.name) {
+ overrides.push({
+ prefabEntityId: instEntity.prefabEntityId,
+ type: 'name',
+ value: instEntity.name,
+ });
+ }
+ if (instEntity.visible !== src.visible) {
+ overrides.push({
+ prefabEntityId: instEntity.prefabEntityId,
+ type: 'visibility',
+ value: instEntity.visible,
+ });
+ }
+
+ diffMetadata(src.metadata, instEntity.metadata, ignoredMeta, instEntity.prefabEntityId, overrides);
+ diffComponents(src.components, instEntity.components, instEntity.prefabEntityId, eps, overrides);
+ }
+
+ for (const [id] of sourceById) {
+ if (!instanceByPrefabId.has(id)) orphanedSourceIds.push(id);
+ }
+
+ return { overrides, untracked, orphanedSourceIds };
+}
+
+function diffMetadata(
+ srcMeta: Record<string, unknown> | undefined,
+ instMeta: Record<string, unknown> | undefined,
+ ignored: Set<string>,
+ entityId: PrefabEntityId,
+ out: PrefabOverride[],
+): void {
+ const src = srcMeta ?? {};
+ const inst = instMeta ?? {};
+ const keys = new Set<string>([...Object.keys(src), ...Object.keys(inst)]);
+ for (const key of keys) {
+ if (ignored.has(key)) continue;
+ const inSrc = key in src;
+ const inInst = key in inst;
+ if (inInst && !inSrc) {
+ out.push({ prefabEntityId: entityId, type: 'metadata_set', metadataKey: key, value: inst[key] });
+ } else if (!inInst && inSrc) {
+ out.push({ prefabEntityId: entityId, type: 'metadata_removed', metadataKey: key });
+ } else if (inInst && inSrc && !deepEqual(src[key], inst[key])) {
+ out.push({ prefabEntityId: entityId, type: 'metadata_set', metadataKey: key, value: inst[key] });
+ }
+ }
+}
+
+function diffComponents(
+ srcComps: readonly ComponentData[],
+ instComps: readonly ComponentData[],
+ entityId: PrefabEntityId,
+ eps: number,
+ out: PrefabOverride[],
+): void {
+ const srcByType = new Map<string, ComponentData>();
+ for (const c of srcComps) srcByType.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) {
+ 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) {
+ out.push({
+ prefabEntityId: entityId,
+ type: 'component_added',
+ componentData: { type, data: deepClone(instComp.data) },
+ });
+ continue;
+ }
+
+ // Per-property diff keeps override list small and human-readable,
+ // and lets Inspector "revert this field" work without dragging the
+ // whole component along.
+ const keys = new Set<string>([
+ ...Object.keys(srcComp.data),
+ ...Object.keys(instComp.data),
+ ]);
+ for (const key of keys) {
+ const a = srcComp.data[key];
+ const b = instComp.data[key];
+ if (!deepEqual(a, b, eps)) {
+ out.push({
+ prefabEntityId: entityId,
+ type: 'property',
+ componentType: type,
+ propertyName: key,
+ value: deepClone(b),
+ });
+ }
+ }
+ }
+}
+
+function deepEqual(a: unknown, b: unknown, eps = 0): boolean {
+ if (a === b) return true;
+ if (typeof a === 'number' && typeof b === 'number') {
+ if (Number.isNaN(a) && Number.isNaN(b)) return true;
+ return eps > 0 ? Math.abs(a - b) <= eps : false;
+ }
+ if (a === null || b === null || a === undefined || b === undefined) return false;
+ if (typeof a !== 'object' || typeof b !== 'object') return false;
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
+ if (Array.isArray(a) && Array.isArray(b)) {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i], eps)) return false;
+ return true;
+ }
+ const ao = a as Record<string, unknown>;
+ const bo = b as Record<string, unknown>;
+ const ak = Object.keys(ao);
+ const bk = Object.keys(bo);
+ if (ak.length !== bk.length) return false;
+ for (const k of ak) if (!deepEqual(ao[k], bo[k], eps)) return false;
+ return true;
+}
+
+function deepClone<T>(v: T): T {
+ return JSON.parse(JSON.stringify(v)) as T;
+}
diff --git a/sdk/src/prefab/entityRef.ts b/sdk/src/prefab/entityRef.ts
index ead1f1863..47d6c2e32 100644
--- a/sdk/src/prefab/entityRef.ts
+++ b/sdk/src/prefab/entityRef.ts
@@ -1,21 +1,38 @@
-import type { ComponentData } from './types';
+import type { ComponentData, PrefabEntityId } from './types';
import { getComponent } from '../component';
import { INVALID_ENTITY } from '../types';
+/**
+ * Remap entity-typed component fields from prefab-local ids to runtime ids.
+ *
+ * The mapping is keyed by `PrefabEntityId` (string) → runtime entity (number),
+ * matching what flatten built. A component field whose value is a string —
+ * the authored prefab-local reference — gets resolved through the mapping;
+ * a numeric value is treated as already a runtime id (or zero/INVALID) and
+ * left alone, so partially-instantiated/mutated components round-trip.
+ */
export function remapComponentEntityRefs(
components: ComponentData[],
- idMapping: Map<number, number>,
+ idMapping: Map<PrefabEntityId, number>,
): void {
for (const comp of components) {
const def = getComponent(comp.type);
if (!def || def.entityFields.length === 0) continue;
for (const field of def.entityFields) {
const value = comp.data[field];
- if (typeof value === 'number' && value !== INVALID_ENTITY) {
+ if (typeof value === 'string') {
const mapped = idMapping.get(value);
if (mapped !== undefined) {
comp.data[field] = mapped;
}
+ } else if (typeof value === 'number' && value !== INVALID_ENTITY) {
+ // Already a numeric id; if a caller authored components with
+ // numeric refs, fall back to numeric→numeric mapping for
+ // legacy compatibility (no-op when the id isn't in the map).
+ const mapped = (idMapping as Map<unknown, number>).get(value);
+ if (mapped !== undefined) {
+ comp.data[field] = mapped;
+ }
}
}
}
diff --git a/sdk/src/prefab/flatten.ts b/sdk/src/prefab/flatten.ts
index 120f47b7c..974bf6b0c 100644
--- a/sdk/src/prefab/flatten.ts
+++ b/sdk/src/prefab/flatten.ts
@@ -1,13 +1,15 @@
import type {
PrefabData,
+ PrefabEntityData,
+ PrefabEntityId,
PrefabOverride,
ProcessedEntity,
FlattenContext,
FlattenResult,
} from './types';
-import { cloneComponents } from './clone';
+import { cloneComponents, cloneMetadata } from './clone';
import { remapComponentEntityRefs } from './entityRef';
-import { applyOverrides } from './override';
+import { applyOverrides, bucketOverridesByEntity } from './override';
const MAX_PREFAB_NESTING_DEPTH = 10;
@@ -28,8 +30,11 @@ export function flattenPrefab(
return flattenVariant(prefab, overrides, ctx, depth);
}
+ validateParentChildConsistency(prefab);
+
const visited = ctx.visited ?? new Set<string>();
- const idMapping = new Map<number, number>();
+ // Stable identity → runtime entity id allocated by ctx.
+ const idMapping = new Map<PrefabEntityId, number>();
for (const pe of prefab.entities) {
if (!pe.nestedPrefab) {
@@ -38,6 +43,7 @@ export function flattenPrefab(
}
const result: ProcessedEntity[] = [];
+ const overrideBuckets = bucketOverridesByEntity(overrides);
for (const pe of prefab.entities) {
if (pe.nestedPrefab) {
@@ -57,8 +63,11 @@ 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.
visited.add(nestedPath);
-
const nested = flattenPrefab(
nestedPrefab,
pe.nestedPrefab.overrides,
@@ -93,25 +102,36 @@ export function flattenPrefab(
.filter((c): c is number => c !== undefined),
components: cloneComponents(pe.components),
visible: pe.visible,
+ ...(pe.metadata ? { metadata: cloneMetadata(pe.metadata) } : {}),
};
// Apply overrides BEFORE remapping so newly added/replaced
// components — and property overrides that target an
// entityField — get their prefab-entity-id values remapped
// to the allocated entity ids in the same pass.
- applyOverrides(entity, overrides);
+ applyOverrides(entity, overrideBuckets.get(pe.prefabEntityId));
remapComponentEntityRefs(entity.components, idMapping);
result.push(entity);
}
const rootId = idMapping.get(prefab.rootEntityId);
if (rootId === undefined) {
- throw new Error('Failed to resolve prefab root entity');
+ throw new Error(
+ `Failed to resolve prefab root entity "${prefab.rootEntityId}" in "${prefab.name}"`,
+ );
}
return { entities: result, rootId };
}
+/**
+ * Variants merge their own `entities` list onto the base before applying
+ * overrides. An entry whose `prefabEntityId` matches an entry in the base
+ * **replaces** that entry's authored data; an entry whose id is new gets
+ * **appended** as an additional child of the base. The variant's root
+ * identity must equal the base's root — variants extend, they do not
+ * relocate the root.
+ */
function flattenVariant(
variant: PrefabData,
instanceOverrides: PrefabOverride[],
@@ -135,12 +155,211 @@ function flattenVariant(
visited.add(basePath);
+ // If the base is itself a variant, resolve its chain first so we merge
+ // against a flat prefab. This preserves the pre-UUID behaviour where
+ // the recursive flattenPrefab call transparently handled nested variants.
+ const resolvedBase = basePrefab.basePrefab
+ ? resolveVariantChain(basePrefab, ctx, depth + 1, visited)
+ : basePrefab;
+
+ const merged = mergeVariantEntities(resolvedBase, variant);
+
const variantOverrides = variant.overrides ?? [];
const combinedOverrides = [...variantOverrides, ...instanceOverrides];
return flattenPrefab(
- basePrefab,
+ merged,
combinedOverrides,
{ ...ctx, visited, depth: depth + 1 },
);
}
+
+function resolveVariantChain(
+ variant: PrefabData,
+ ctx: FlattenContext,
+ depth: number,
+ visited: Set<string>,
+): PrefabData {
+ if (depth > MAX_PREFAB_NESTING_DEPTH) {
+ throw new Error(
+ `Prefab variant chain exceeded depth ${MAX_PREFAB_NESTING_DEPTH}; ` +
+ `suspected circular inheritance ending at "${variant.name}"`,
+ );
+ }
+ const basePath = variant.basePrefab;
+ if (!basePath) return variant;
+ if (visited.has(basePath)) {
+ throw new Error(
+ `[Prefab] Circular variant reference detected: "${basePath}" ` +
+ `is already being instantiated in the current prefab chain`,
+ );
+ }
+ const base = ctx.loadPrefab(basePath);
+ if (!base) {
+ throw new Error(`Failed to load base prefab for variant: ${basePath}`);
+ }
+ visited.add(basePath);
+ const resolvedBase = base.basePrefab
+ ? resolveVariantChain(base, ctx, depth + 1, visited)
+ : base;
+ return mergeVariantEntities(resolvedBase, variant);
+}
+
+function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabData {
+ if (variant.rootEntityId !== base.rootEntityId) {
+ throw new Error(
+ `Variant "${variant.name}" rootEntityId "${variant.rootEntityId}" ` +
+ `must match base "${base.name}" rootEntityId "${base.rootEntityId}". ` +
+ `Variants extend the base; they do not relocate the root.`,
+ );
+ }
+
+ const baseById = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const e of base.entities) baseById.set(e.prefabEntityId, e);
+
+ const merged: PrefabEntityData[] = base.entities.map(e => ({ ...e }));
+ const mergedById = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const e of merged) mergedById.set(e.prefabEntityId, e);
+
+ const variantEntities = variant.entities ?? [];
+ for (const ve of variantEntities) {
+ const existing = mergedById.get(ve.prefabEntityId);
+ if (existing) {
+ // Variant entry replaces base authored data wholesale (matching
+ // Unity behaviour where editing inside the variant becomes the
+ // new authored state for that entity within this variant).
+ const replaced: PrefabEntityData = {
+ ...ve,
+ children: [...ve.children],
+ components: ve.components.map(c => ({
+ type: c.type,
+ data: { ...c.data },
+ })),
+ ...(ve.metadata ? { metadata: { ...ve.metadata } } : {}),
+ };
+ const idx = merged.indexOf(existing);
+ merged[idx] = replaced;
+ mergedById.set(ve.prefabEntityId, replaced);
+ continue;
+ }
+
+ // New entity. Validate its parent points somewhere reachable.
+ if (ve.parent === null) {
+ throw new Error(
+ `Variant "${variant.name}" entity "${ve.prefabEntityId}" has ` +
+ `parent=null but is not the root. Variant additions must attach ` +
+ `to an existing entity from the base or another variant addition.`,
+ );
+ }
+ const added: PrefabEntityData = {
+ ...ve,
+ children: [...ve.children],
+ components: ve.components.map(c => ({
+ type: c.type,
+ data: { ...c.data },
+ })),
+ ...(ve.metadata ? { metadata: { ...ve.metadata } } : {}),
+ };
+ merged.push(added);
+ mergedById.set(ve.prefabEntityId, added);
+ }
+
+ // Pass 2: link added entities into their parents' children lists,
+ // and validate referential integrity.
+ const baseIds = new Set(base.entities.map(e => e.prefabEntityId));
+ for (const ve of variantEntities) {
+ const isNew = !baseIds.has(ve.prefabEntityId);
+ if (!isNew) continue;
+ const parent = mergedById.get(ve.parent!);
+ if (!parent) {
+ throw new Error(
+ `Variant "${variant.name}" entity "${ve.prefabEntityId}" parent ` +
+ `"${ve.parent!}" not found in base or other variant additions.`,
+ );
+ }
+ if (!parent.children.includes(ve.prefabEntityId)) {
+ parent.children = [...parent.children, ve.prefabEntityId];
+ }
+ }
+
+ // Validate no cycles among the merged set before flatten downstream.
+ detectCycle(merged, variant.name);
+
+ return {
+ version: base.version,
+ name: variant.name,
+ rootEntityId: base.rootEntityId,
+ entities: merged,
+ // basePrefab intentionally dropped; the merged result is no longer a
+ // variant for downstream flatten purposes.
+ };
+}
+
+function validateParentChildConsistency(prefab: PrefabData): void {
+ const byId = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const e of prefab.entities) byId.set(e.prefabEntityId, e);
+
+ for (const e of prefab.entities) {
+ if (e.parent !== null) {
+ const parent = byId.get(e.parent);
+ if (!parent) {
+ throw new Error(
+ `Prefab "${prefab.name}" entity "${e.prefabEntityId}" parent ` +
+ `"${e.parent}" does not exist.`,
+ );
+ }
+ if (!parent.children.includes(e.prefabEntityId)) {
+ throw new Error(
+ `Prefab "${prefab.name}" inconsistent topology: entity ` +
+ `"${e.prefabEntityId}" claims parent "${e.parent}" but the ` +
+ `parent's children list does not contain it. children is ` +
+ `the source of truth — fix by adding the child id there.`,
+ );
+ }
+ }
+ for (const childId of e.children) {
+ const child = byId.get(childId);
+ if (!child) {
+ throw new Error(
+ `Prefab "${prefab.name}" entity "${e.prefabEntityId}" lists ` +
+ `child "${childId}" which does not exist.`,
+ );
+ }
+ if (child.parent !== e.prefabEntityId) {
+ throw new Error(
+ `Prefab "${prefab.name}" inconsistent topology: entity ` +
+ `"${e.prefabEntityId}" lists "${childId}" as a child but ` +
+ `the child's parent points elsewhere ("${child.parent ?? 'null'}").`,
+ );
+ }
+ }
+ }
+}
+
+function detectCycle(entities: PrefabEntityData[], prefabName: string): void {
+ const byId = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const e of entities) byId.set(e.prefabEntityId, e);
+ const WHITE = 0, GRAY = 1, BLACK = 2;
+ const color = new Map<PrefabEntityId, number>();
+ for (const e of entities) color.set(e.prefabEntityId, WHITE);
+
+ const visit = (id: PrefabEntityId, path: PrefabEntityId[]): void => {
+ const c = color.get(id);
+ if (c === BLACK) return;
+ if (c === GRAY) {
+ const cycleStart = path.indexOf(id);
+ const cycle = path.slice(cycleStart).concat(id);
+ throw new Error(
+ `Prefab "${prefabName}" parent cycle detected: ${cycle.join(' → ')}`,
+ );
+ }
+ color.set(id, GRAY);
+ const entity = byId.get(id);
+ if (entity?.parent !== null && entity?.parent !== undefined) {
+ visit(entity.parent, [...path, id]);
+ }
+ color.set(id, BLACK);
+ };
+
+ for (const e of entities) visit(e.prefabEntityId, []);
+}
diff --git a/sdk/src/prefab/index.ts b/sdk/src/prefab/index.ts
index dc3402adc..2e35ad5f2 100644
--- a/sdk/src/prefab/index.ts
+++ b/sdk/src/prefab/index.ts
@@ -2,6 +2,7 @@ export type {
ComponentData,
PrefabData,
PrefabEntityData,
+ PrefabEntityId,
PrefabOverride,
NestedPrefabRef,
ProcessedEntity,
@@ -10,7 +11,13 @@ export type {
} from './types';
export { flattenPrefab } from './flatten';
-export { applyOverrides } from './override';
+export { applyOverrides, bucketOverridesByEntity } from './override';
export { remapComponentEntityRefs } from './entityRef';
-export { cloneComponents, cloneComponentData } from './clone';
+export { cloneComponents, cloneComponentData, cloneMetadata } from './clone';
export { collectNestedPrefabPaths, preloadNestedPrefabs } from './collect';
+export { migratePrefabData, PREFAB_FORMAT_VERSION } from './migrate';
+export type { MigrationResult } from './migrate';
+export { diffAgainstSource } from './diff';
+export type { DiffOptions } from './diff';
+export { validateOverrides } from './validate';
+export type { ValidateResult, StaleOverride } from './validate';
diff --git a/sdk/src/prefab/migrate.ts b/sdk/src/prefab/migrate.ts
new file mode 100644
index 000000000..8a147c8d9
--- /dev/null
+++ b/sdk/src/prefab/migrate.ts
@@ -0,0 +1,148 @@
+import type { PrefabData, PrefabEntityData, PrefabOverride } from './types';
+
+/**
+ * Result of a migration pass over a prefab JSON blob. `migrated` is true
+ * when at least one field was upgraded; callers can choose to log/warn so
+ * users know to re-save in the new format.
+ */
+export interface MigrationResult {
+ data: PrefabData;
+ migrated: boolean;
+ fromVersion: string;
+ toVersion: string;
+}
+
+export const PREFAB_FORMAT_VERSION = '2';
+
+/**
+ * Upgrade a parsed `.esprefab` JSON value to the current format.
+ *
+ * The historical format used numeric entity ids; current format uses
+ * opaque strings (UUIDs for editor-authored prefabs). Numeric ids are
+ * stringified with `String(n)` so cross-references — `parent`, `children`,
+ * `rootEntityId`, `PrefabOverride.prefabEntityId`, `nestedPrefab.overrides`
+ * — remain consistent.
+ *
+ * The function is total: it accepts already-migrated data and returns it
+ * with `migrated: false`. Throws on shapes that can't be reconciled.
+ */
+export function migratePrefabData(raw: unknown): MigrationResult {
+ if (typeof raw !== 'object' || raw === null) {
+ throw new Error('Prefab data must be an object');
+ }
+ const obj = raw as Record<string, unknown>;
+ if (!Array.isArray(obj['entities'])) {
+ throw new Error('Prefab data must have an "entities" array');
+ }
+ if (typeof obj['rootEntityId'] !== 'string' && typeof obj['rootEntityId'] !== 'number') {
+ throw new Error('Prefab data must have a "rootEntityId" string or number');
+ }
+
+ const fromVersion = typeof obj['version'] === 'string' ? obj['version'] : '1.0';
+ const isLegacy = needsMigration(obj);
+
+ if (!isLegacy) {
+ return {
+ data: obj as unknown as PrefabData,
+ migrated: false,
+ fromVersion,
+ toVersion: fromVersion,
+ };
+ }
+
+ const upgraded = upgradeNumericIds(obj);
+ upgraded.version = PREFAB_FORMAT_VERSION;
+ return {
+ data: upgraded,
+ migrated: true,
+ fromVersion,
+ toVersion: PREFAB_FORMAT_VERSION,
+ };
+}
+
+function needsMigration(obj: Record<string, unknown>): boolean {
+ if (typeof obj['rootEntityId'] === 'number') return true;
+ const entities = obj['entities'] as unknown[];
+ for (const e of entities) {
+ if (typeof e !== 'object' || e === null) continue;
+ const er = e as Record<string, unknown>;
+ if (typeof er['prefabEntityId'] === 'number') return true;
+ if (typeof er['parent'] === 'number') return true;
+ const children = er['children'];
+ if (Array.isArray(children) && children.some(c => typeof c === 'number')) return true;
+ }
+ const overrides = obj['overrides'];
+ if (Array.isArray(overrides)) {
+ for (const o of overrides) {
+ if (typeof o !== 'object' || o === null) continue;
+ const or = o as Record<string, unknown>;
+ if (typeof or['prefabEntityId'] === 'number') return true;
+ }
+ }
+ return false;
+}
+
+function upgradeNumericIds(obj: Record<string, unknown>): PrefabData {
+ const stringify = (v: unknown): string => {
+ if (typeof v === 'string') return v;
+ if (typeof v === 'number') return String(v);
+ throw new Error(`Cannot stringify prefab id of type ${typeof v}`);
+ };
+
+ const entities = (obj['entities'] as unknown[]).map((e): PrefabEntityData => {
+ const er = e as Record<string, unknown>;
+ const out: PrefabEntityData = {
+ prefabEntityId: stringify(er['prefabEntityId']),
+ name: typeof er['name'] === 'string' ? er['name'] : '',
+ parent: er['parent'] === null || er['parent'] === undefined
+ ? null
+ : stringify(er['parent']),
+ children: Array.isArray(er['children'])
+ ? (er['children'] as unknown[]).map(stringify)
+ : [],
+ components: Array.isArray(er['components'])
+ ? (er['components'] as PrefabEntityData['components'])
+ : [],
+ visible: er['visible'] !== false,
+ };
+ if (er['metadata'] && typeof er['metadata'] === 'object') {
+ out.metadata = er['metadata'] as Record<string, unknown>;
+ }
+ if (er['nestedPrefab'] && typeof er['nestedPrefab'] === 'object') {
+ const np = er['nestedPrefab'] as Record<string, unknown>;
+ out.nestedPrefab = {
+ prefabPath: typeof np['prefabPath'] === 'string' ? np['prefabPath'] : '',
+ overrides: Array.isArray(np['overrides'])
+ ? upgradeOverrides(np['overrides'])
+ : [],
+ };
+ }
+ return out;
+ });
+
+ const result: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: typeof obj['name'] === 'string' ? obj['name'] : '',
+ rootEntityId: stringify(obj['rootEntityId']),
+ entities,
+ };
+ if (typeof obj['basePrefab'] === 'string') {
+ result.basePrefab = obj['basePrefab'];
+ }
+ if (Array.isArray(obj['overrides'])) {
+ result.overrides = upgradeOverrides(obj['overrides']);
+ }
+ return result;
+}
+
+function upgradeOverrides(raw: unknown[]): PrefabOverride[] {
+ return raw.map((o): PrefabOverride => {
+ const or = o as Record<string, unknown>;
+ const id = or['prefabEntityId'];
+ const upgraded: PrefabOverride = {
+ ...(or as unknown as PrefabOverride),
+ prefabEntityId: typeof id === 'number' ? String(id) : (id as string),
+ };
+ return upgraded;
+ });
+}
diff --git a/sdk/src/prefab/override.ts b/sdk/src/prefab/override.ts
index 7703ad885..8a68e3dfb 100644
--- a/sdk/src/prefab/override.ts
+++ b/sdk/src/prefab/override.ts
@@ -1,8 +1,34 @@
-import type { ProcessedEntity, PrefabOverride } from './types';
+import type {
+ PrefabEntityId,
+ PrefabOverride,
+ ProcessedEntity,
+} from './types';
import { cloneComponentData } from './clone';
-export function applyOverrides(entity: ProcessedEntity, overrides: PrefabOverride[]): void {
+/**
+ * Group overrides by their target entity once so flatten can apply each
+ * entity's overrides in O(K) instead of O(N×M) per scene tree.
+ */
+export function bucketOverridesByEntity(
+ overrides: readonly PrefabOverride[],
+): Map<PrefabEntityId, PrefabOverride[]> {
+ const buckets = new Map<PrefabEntityId, PrefabOverride[]>();
+ for (const o of overrides) {
+ const list = buckets.get(o.prefabEntityId);
+ if (list) list.push(o);
+ else buckets.set(o.prefabEntityId, [o]);
+ }
+ return buckets;
+}
+
+export function applyOverrides(
+ entity: ProcessedEntity,
+ overrides: readonly PrefabOverride[] | undefined,
+): void {
+ if (!overrides || overrides.length === 0) return;
for (const override of overrides) {
+ // Bucket pre-filters by entity, but allow callers to pass the raw
+ // list too — we still gate here so this function stays standalone.
if (override.prefabEntityId !== entity.prefabEntityId) continue;
switch (override.type) {
@@ -58,6 +84,20 @@ export function applyOverrides(entity: ProcessedEntity, overrides: PrefabOverrid
);
}
break;
+ case 'metadata_set':
+ if (typeof override.metadataKey === 'string') {
+ if (!entity.metadata) entity.metadata = {};
+ entity.metadata[override.metadataKey] = override.value;
+ }
+ break;
+ case 'metadata_removed':
+ if (typeof override.metadataKey === 'string' && entity.metadata) {
+ Reflect.deleteProperty(entity.metadata, override.metadataKey);
+ if (Object.keys(entity.metadata).length === 0) {
+ delete entity.metadata;
+ }
+ }
+ break;
}
}
}
diff --git a/sdk/src/prefab/types.ts b/sdk/src/prefab/types.ts
index 987cd10ad..7709eb27f 100644
--- a/sdk/src/prefab/types.ts
+++ b/sdk/src/prefab/types.ts
@@ -3,22 +3,46 @@ export interface ComponentData {
data: Record<string, unknown>;
}
+/**
+ * Per-entity identity inside a prefab file.
+ *
+ * The string is opaque — UUIDs for editor-authored prefabs, stringified
+ * integers for migrated legacy files. Stability matters more than format:
+ * once an entity has been assigned a `PrefabEntityId`, the editor must
+ * never reassign or reuse it for the lifetime of the prefab, otherwise
+ * existing instance overrides will silently apply to the wrong target.
+ */
+export type PrefabEntityId = string;
+
export interface PrefabData {
version: string;
name: string;
- rootEntityId: number;
+ rootEntityId: PrefabEntityId;
entities: PrefabEntityData[];
+ /**
+ * If set, this prefab inherits from another prefab. The variant's own
+ * `entities` list may **override** existing base entries (matched by
+ * `prefabEntityId`) and **add** new entities; `overrides` is applied
+ * on top of the merged result.
+ */
basePrefab?: string;
overrides?: PrefabOverride[];
}
export interface PrefabEntityData {
- prefabEntityId: number;
+ prefabEntityId: PrefabEntityId;
name: string;
- parent: number | null;
- children: number[];
+ parent: PrefabEntityId | null;
+ children: PrefabEntityId[];
components: ComponentData[];
visible: boolean;
+ /**
+ * Editor/tooling state that survives prefab round-trip. Not consumed by
+ * the runtime engine — the runtime instantiation path drops this. The
+ * editor uses it to round-trip per-entity metadata such as asset refs
+ * (`asset:Comp.field` → uuid) and selection markers.
+ */
+ metadata?: Record<string, unknown>;
nestedPrefab?: NestedPrefabRef;
}
@@ -44,30 +68,41 @@ export interface NestedPrefabRef {
* explicitly want to override the base's copy.
* - `component_removed` — delete the component if present.
* Requires: componentType.
+ * - `metadata_set` — set or replace one metadata key. Requires:
+ * metadataKey, value (any JSON-serialisable).
+ * Idempotent — applying twice is a no-op.
+ * - `metadata_removed` — delete one metadata key if present. Requires:
+ * metadataKey.
*/
export interface PrefabOverride {
- prefabEntityId: number;
+ prefabEntityId: PrefabEntityId;
type:
| 'property'
| 'component_added'
| 'component_replaced'
| 'component_removed'
| 'name'
- | 'visibility';
+ | 'visibility'
+ | 'metadata_set'
+ | 'metadata_removed';
componentType?: string;
propertyName?: string;
+ metadataKey?: string;
value?: unknown;
componentData?: ComponentData;
}
export interface ProcessedEntity {
+ /** Runtime entity id assigned by the flatten allocator. */
id: number;
- prefabEntityId: number;
+ /** Stable identity from the source prefab; preserved for diff/override matching. */
+ prefabEntityId: PrefabEntityId;
name: string;
parent: number | null;
children: number[];
components: ComponentData[];
visible: boolean;
+ metadata?: Record<string, unknown>;
}
export interface FlattenContext {
diff --git a/sdk/src/prefab/validate.ts b/sdk/src/prefab/validate.ts
new file mode 100644
index 000000000..232385d1c
--- /dev/null
+++ b/sdk/src/prefab/validate.ts
@@ -0,0 +1,136 @@
+import type {
+ PrefabData,
+ PrefabEntityData,
+ PrefabEntityId,
+ PrefabOverride,
+} from './types';
+
+export interface StaleOverride {
+ override: PrefabOverride;
+ reason: string;
+ /** Where in the prefab the override lives. */
+ site: 'variant' | 'nested' | 'instance';
+ /** For nested sites, the nested prefab's entity id whose overrides list it came from. */
+ nestedAt?: PrefabEntityId;
+}
+
+export interface ValidateResult {
+ stale: StaleOverride[];
+ /**
+ * Entity ids mentioned in the prefab's own `children` lists that have
+ * no corresponding entity entry. Surfaces corruption from third-party
+ * editing tools; flatten also fails hard on this, so this is a softer
+ * diagnostic the editor can surface before flatten.
+ */
+ orphanedChildren: PrefabEntityId[];
+}
+
+/**
+ * Find overrides pointing at entities or components that no longer exist.
+ *
+ * The check is structural (no flatten). For nested-prefab site validation
+ * pass a loader via `options.loadPrefab`; without it, nested overrides are
+ * skipped (treated as "cannot verify").
+ *
+ * Used by the editor on scene open + on Apply-to-Source to warn the user
+ * before stale overrides silently disappear.
+ */
+export function validateOverrides(
+ prefab: PrefabData,
+ options?: {
+ /** Overrides applied at instance site, e.g. `prefab:overrides` metadata. */
+ instanceOverrides?: readonly PrefabOverride[];
+ loadPrefab?: (path: string) => PrefabData | null;
+ },
+): ValidateResult {
+ const stale: StaleOverride[] = [];
+ const orphanedChildren: PrefabEntityId[] = [];
+
+ const byId = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const e of prefab.entities) byId.set(e.prefabEntityId, e);
+
+ for (const e of prefab.entities) {
+ for (const childId of e.children) {
+ if (!byId.has(childId)) orphanedChildren.push(childId);
+ }
+ }
+
+ const checkAgainst = (
+ overrides: readonly PrefabOverride[],
+ target: PrefabData,
+ site: StaleOverride['site'],
+ nestedAt?: PrefabEntityId,
+ ): void => {
+ const map = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const e of target.entities) map.set(e.prefabEntityId, e);
+ for (const o of overrides) {
+ const entity = map.get(o.prefabEntityId);
+ if (!entity) {
+ stale.push({
+ override: o,
+ reason: `entity "${o.prefabEntityId}" not found in "${target.name}"`,
+ site,
+ ...(nestedAt !== undefined ? { nestedAt } : {}),
+ });
+ continue;
+ }
+ const reason = reasonForOverride(o, entity);
+ if (reason) {
+ stale.push({
+ override: o,
+ reason,
+ site,
+ ...(nestedAt !== undefined ? { nestedAt } : {}),
+ });
+ }
+ }
+ };
+
+ if (prefab.overrides) {
+ checkAgainst(prefab.overrides, prefab, 'variant');
+ }
+ if (options?.instanceOverrides) {
+ checkAgainst(options.instanceOverrides, prefab, 'instance');
+ }
+
+ if (options?.loadPrefab) {
+ const loader = options.loadPrefab;
+ for (const e of prefab.entities) {
+ if (!e.nestedPrefab) continue;
+ const nested = loader(e.nestedPrefab.prefabPath);
+ if (!nested) continue;
+ checkAgainst(e.nestedPrefab.overrides, nested, 'nested', e.prefabEntityId);
+ }
+ }
+
+ return { stale, orphanedChildren };
+}
+
+function reasonForOverride(
+ override: PrefabOverride,
+ entity: PrefabEntityData,
+): string | null {
+ switch (override.type) {
+ case 'property':
+ case 'component_removed': {
+ const type = override.componentType;
+ if (!type) return 'missing componentType';
+ const exists = entity.components.some(c => c.type === type);
+ return exists ? null : `component "${type}" not present on "${entity.prefabEntityId}"`;
+ }
+ case 'component_replaced':
+ case 'component_added':
+ // Both are upserts; they can't be stale by definition.
+ return null;
+ case 'metadata_removed': {
+ const key = override.metadataKey;
+ if (!key) return 'missing metadataKey';
+ const present = entity.metadata && Object.prototype.hasOwnProperty.call(entity.metadata, key);
+ return present ? null : `metadata key "${key}" not present on "${entity.prefabEntityId}"`;
+ }
+ case 'metadata_set':
+ case 'name':
+ case 'visibility':
+ return null;
+ }
+}
diff --git a/sdk/tests/prefab-rigor.test.ts b/sdk/tests/prefab-rigor.test.ts
new file mode 100644
index 000000000..8090387f0
--- /dev/null
+++ b/sdk/tests/prefab-rigor.test.ts
@@ -0,0 +1,649 @@
+/**
+ * Rigor suite for the prefab data model:
+ * - UUID identity + legacy migration round-trip
+ * - Per-entity metadata through flatten + overrides
+ * - Variant additions (new entities contributed by variant)
+ * - diffAgainstSource inverse of applyOverrides
+ * - validateOverrides catches stale refs
+ * - parent/children consistency invariant
+ * - O(N+M) override application (correctness under bucketed path)
+ *
+ * Covers the gaps flagged during the editor-readiness audit. Numeric-id
+ * existing tests stay in `prefab.test.ts`; this file targets the new
+ * surface introduced for editor authoring.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+import type { PrefabData, PrefabOverride, ProcessedEntity } from '../src/prefab';
+import {
+ migratePrefabData,
+ diffAgainstSource,
+ validateOverrides,
+ PREFAB_FORMAT_VERSION,
+} from '../src/prefab';
+import {
+ flattenPrefab,
+ bucketOverridesByEntity,
+} from '../src/prefab/index';
+import type { FlattenContext } from '../src/prefab/index';
+
+function uuidPrefab(): PrefabData {
+ return {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Hero',
+ rootEntityId: 'root',
+ entities: [
+ {
+ prefabEntityId: 'root',
+ name: 'Hero',
+ parent: null,
+ children: ['weapon'],
+ components: [
+ { type: 'Transform', data: { x: 0, y: 0 } },
+ { type: 'Sprite', data: { texture: 'hero.png', color: 'white' } },
+ ],
+ visible: true,
+ metadata: { 'asset:Sprite.texture': 'uuid-hero-png' },
+ },
+ {
+ prefabEntityId: 'weapon',
+ name: 'Weapon',
+ parent: 'root',
+ children: [],
+ components: [
+ { type: 'Sprite', data: { texture: 'sword.png' } },
+ ],
+ visible: true,
+ },
+ ],
+ };
+}
+
+function freshCtx(): FlattenContext {
+ let n = 0;
+ return {
+ allocateId: () => n++,
+ loadPrefab: () => null,
+ visited: new Set(),
+ };
+}
+
+// ─── Migration + round-trip ────────────────────────────────────
+
+describe('migratePrefabData', () => {
+ it('upgrades numeric ids to strings and preserves cross-references', () => {
+ const legacy = {
+ version: '1.0',
+ name: 'Legacy',
+ rootEntityId: 0,
+ entities: [
+ {
+ prefabEntityId: 0,
+ name: 'Root',
+ parent: null,
+ children: [1],
+ components: [],
+ visible: true,
+ },
+ {
+ prefabEntityId: 1,
+ name: 'Child',
+ parent: 0,
+ children: [],
+ components: [],
+ visible: true,
+ },
+ ],
+ overrides: [
+ { prefabEntityId: 1, type: 'name', value: 'Renamed' },
+ ],
+ };
+
+ const { data, migrated, fromVersion, toVersion } = migratePrefabData(legacy);
+ expect(migrated).toBe(true);
+ expect(fromVersion).toBe('1.0');
+ expect(toVersion).toBe(PREFAB_FORMAT_VERSION);
+ expect(data.rootEntityId).toBe('0');
+ expect(data.entities[0].prefabEntityId).toBe('0');
+ expect(data.entities[0].children).toEqual(['1']);
+ expect(data.entities[1].parent).toBe('0');
+ expect(data.overrides![0].prefabEntityId).toBe('1');
+ });
+
+ it('is idempotent on already-migrated data', () => {
+ const current = uuidPrefab();
+ const { data, migrated } = migratePrefabData(current);
+ expect(migrated).toBe(false);
+ expect(data).toBe(current);
+ });
+
+ it('round-trips through JSON without drift', () => {
+ const original = uuidPrefab();
+ const serialized = JSON.stringify(original);
+ const parsed = JSON.parse(serialized);
+ const { data } = migratePrefabData(parsed);
+ const reSerialized = JSON.stringify(data);
+ // parsed path → migrate-no-op → re-stringify must equal original
+ expect(JSON.parse(reSerialized)).toEqual(original);
+ });
+
+ it('throws on shapes that are not prefab data', () => {
+ expect(() => migratePrefabData(null)).toThrow(/must be an object/);
+ expect(() => migratePrefabData({})).toThrow(/entities/);
+ expect(() => migratePrefabData({ entities: [], rootEntityId: null })).toThrow(
+ /rootEntityId/,
+ );
+ });
+});
+
+// ─── Metadata carries through flatten ─────────────────────────
+
+describe('prefab metadata', () => {
+ it('flatten preserves per-entity metadata on ProcessedEntity', () => {
+ const { entities } = flattenPrefab(uuidPrefab(), [], freshCtx());
+ const root = entities.find(e => e.prefabEntityId === 'root');
+ expect(root?.metadata).toEqual({ 'asset:Sprite.texture': 'uuid-hero-png' });
+ });
+
+ it('metadata_set override adds a new key to an entity without existing metadata', () => {
+ const prefab = uuidPrefab();
+ const overrides: PrefabOverride[] = [
+ { prefabEntityId: 'weapon', type: 'metadata_set', metadataKey: 'debug:autoSpin', value: true },
+ ];
+ const { entities } = flattenPrefab(prefab, overrides, freshCtx());
+ const weapon = entities.find(e => e.prefabEntityId === 'weapon');
+ expect(weapon?.metadata).toEqual({ 'debug:autoSpin': true });
+ });
+
+ it('metadata_set override replaces an existing key', () => {
+ const prefab = uuidPrefab();
+ const overrides: PrefabOverride[] = [
+ {
+ prefabEntityId: 'root',
+ type: 'metadata_set',
+ metadataKey: 'asset:Sprite.texture',
+ value: 'uuid-different',
+ },
+ ];
+ const { entities } = flattenPrefab(prefab, overrides, freshCtx());
+ const root = entities.find(e => e.prefabEntityId === 'root');
+ expect(root?.metadata?.['asset:Sprite.texture']).toBe('uuid-different');
+ });
+
+ it('metadata_removed drops the key and clears the object when empty', () => {
+ const prefab = uuidPrefab();
+ const overrides: PrefabOverride[] = [
+ { prefabEntityId: 'root', type: 'metadata_removed', metadataKey: 'asset:Sprite.texture' },
+ ];
+ const { entities } = flattenPrefab(prefab, overrides, freshCtx());
+ const root = entities.find(e => e.prefabEntityId === 'root');
+ expect(root?.metadata).toBeUndefined();
+ });
+
+ it('cloneMetadata is deep (mutating the source does not leak into flatten result)', () => {
+ const prefab = uuidPrefab();
+ const original = prefab.entities[0].metadata!['asset:Sprite.texture'];
+ const { entities } = flattenPrefab(prefab, [], freshCtx());
+ prefab.entities[0].metadata!['asset:Sprite.texture'] = 'MUTATED';
+ const root = entities.find(e => e.prefabEntityId === 'root');
+ expect(root?.metadata?.['asset:Sprite.texture']).toBe(original);
+ });
+});
+
+// ─── Variant additions ────────────────────────────────────────
+
+describe('variant additions', () => {
+ it('variant entities with new ids get added to base with parent wiring', () => {
+ const base = uuidPrefab();
+ const variant: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'HeroWithShield',
+ rootEntityId: 'root',
+ basePrefab: 'base.esprefab',
+ entities: [
+ {
+ prefabEntityId: 'shield',
+ name: 'Shield',
+ parent: 'root',
+ children: [],
+ components: [{ type: 'Sprite', data: { texture: 'shield.png' } }],
+ visible: true,
+ },
+ ],
+ };
+ const ctx: FlattenContext = {
+ allocateId: (() => { let n = 0; return () => n++; })(),
+ loadPrefab: (path) => path === 'base.esprefab' ? base : null,
+ visited: new Set(),
+ };
+ const { entities } = flattenPrefab(variant, [], ctx);
+ expect(entities.some(e => e.prefabEntityId === 'shield')).toBe(true);
+ expect(entities.some(e => e.prefabEntityId === 'weapon')).toBe(true);
+ expect(entities.some(e => e.prefabEntityId === 'root')).toBe(true);
+
+ // Shield must be a child of root in the runtime tree.
+ const root = entities.find(e => e.prefabEntityId === 'root')!;
+ const shield = entities.find(e => e.prefabEntityId === 'shield')!;
+ expect(root.children).toContain(shield.id);
+ });
+
+ it('rejects variant additions with unknown parent', () => {
+ const base = uuidPrefab();
+ const variant: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Broken',
+ rootEntityId: 'root',
+ basePrefab: 'base.esprefab',
+ entities: [
+ {
+ prefabEntityId: 'floater',
+ name: 'Floater',
+ parent: 'ghost',
+ children: [],
+ components: [],
+ visible: true,
+ },
+ ],
+ };
+ const ctx: FlattenContext = {
+ allocateId: (() => { let n = 0; return () => n++; })(),
+ loadPrefab: (path) => path === 'base.esprefab' ? base : null,
+ visited: new Set(),
+ };
+ expect(() => flattenPrefab(variant, [], ctx)).toThrow(/parent "ghost" not found/);
+ });
+
+ it('variant entry with a known id replaces the base authored data', () => {
+ const base = uuidPrefab();
+ const variant: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'HeroReskin',
+ rootEntityId: 'root',
+ basePrefab: 'base.esprefab',
+ entities: [
+ {
+ prefabEntityId: 'weapon',
+ name: 'BigWeapon',
+ parent: 'root',
+ children: [],
+ components: [{ type: 'Sprite', data: { texture: 'greatsword.png' } }],
+ visible: true,
+ },
+ ],
+ };
+ const ctx: FlattenContext = {
+ allocateId: (() => { let n = 0; return () => n++; })(),
+ loadPrefab: (path) => path === 'base.esprefab' ? base : null,
+ visited: new Set(),
+ };
+ const { entities } = flattenPrefab(variant, [], ctx);
+ const weapon = entities.find(e => e.prefabEntityId === 'weapon')!;
+ expect(weapon.name).toBe('BigWeapon');
+ expect(weapon.components[0].data['texture']).toBe('greatsword.png');
+ });
+
+ it('rejects variants whose rootEntityId disagrees with base', () => {
+ const base = uuidPrefab();
+ const variant: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'BadVariant',
+ rootEntityId: 'different-root',
+ basePrefab: 'base.esprefab',
+ entities: [],
+ };
+ const ctx: FlattenContext = {
+ allocateId: (() => { let n = 0; return () => n++; })(),
+ loadPrefab: (path) => path === 'base.esprefab' ? base : null,
+ visited: new Set(),
+ };
+ expect(() => flattenPrefab(variant, [], ctx)).toThrow(/rootEntityId/);
+ });
+});
+
+// ─── Parent/children invariant ────────────────────────────────
+
+describe('parent/children consistency', () => {
+ it('throws when a child points at a missing entity', () => {
+ const broken: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Broken',
+ rootEntityId: 'root',
+ entities: [
+ {
+ prefabEntityId: 'root',
+ name: 'Root',
+ parent: null,
+ children: ['phantom'],
+ components: [],
+ visible: true,
+ },
+ ],
+ };
+ expect(() => flattenPrefab(broken, [], freshCtx())).toThrow(/child "phantom" which does not exist/);
+ });
+
+ it('throws when a parent pointer disagrees with children lists', () => {
+ const broken: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Broken',
+ rootEntityId: 'root',
+ entities: [
+ {
+ prefabEntityId: 'root',
+ name: 'Root',
+ parent: null,
+ children: [],
+ components: [],
+ visible: true,
+ },
+ {
+ prefabEntityId: 'orphan',
+ name: 'Orphan',
+ parent: 'root',
+ children: [],
+ components: [],
+ visible: true,
+ },
+ ],
+ };
+ expect(() => flattenPrefab(broken, [], freshCtx())).toThrow(
+ /parent's children list does not contain it/,
+ );
+ });
+});
+
+// ─── diffAgainstSource ─────────────────────────────────────────
+
+describe('diffAgainstSource', () => {
+ function cloneForInstance(prefab: PrefabData): ProcessedEntity[] {
+ let n = 0;
+ return prefab.entities.map(e => {
+ const out: ProcessedEntity = {
+ id: n++,
+ prefabEntityId: e.prefabEntityId,
+ name: e.name,
+ parent: null,
+ children: [],
+ components: e.components.map(c => ({
+ type: c.type,
+ data: { ...c.data },
+ })),
+ visible: e.visible,
+ };
+ if (e.metadata) out.metadata = { ...e.metadata };
+ return out;
+ });
+ }
+
+ it('returns an empty override list when instance equals source', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ const result = diffAgainstSource(prefab, instance);
+ expect(result.overrides).toEqual([]);
+ expect(result.untracked).toEqual([]);
+ expect(result.orphanedSourceIds).toEqual([]);
+ });
+
+ it('emits property override for changed field', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ instance[0].components[0].data = { x: 50, y: 0 };
+ const { overrides } = diffAgainstSource(prefab, instance);
+ expect(overrides).toContainEqual({
+ prefabEntityId: 'root',
+ type: 'property',
+ componentType: 'Transform',
+ propertyName: 'x',
+ value: 50,
+ });
+ });
+
+ it('emits component_added for new component and component_removed for missing one', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ instance[0].components.push({ type: 'Velocity', data: { linear: { x: 1, y: 0, z: 0 } } });
+ instance[0].components = instance[0].components.filter(c => c.type !== 'Sprite');
+ const { overrides } = diffAgainstSource(prefab, instance);
+ expect(overrides).toContainEqual(
+ expect.objectContaining({ type: 'component_added', componentData: expect.objectContaining({ type: 'Velocity' }) }),
+ );
+ expect(overrides).toContainEqual({
+ prefabEntityId: 'root',
+ type: 'component_removed',
+ componentType: 'Sprite',
+ });
+ });
+
+ it('emits name + visibility overrides', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ instance[0].name = 'Hero#42';
+ instance[1].visible = false;
+ const { overrides } = diffAgainstSource(prefab, instance);
+ expect(overrides).toContainEqual({ prefabEntityId: 'root', type: 'name', value: 'Hero#42' });
+ expect(overrides).toContainEqual({ prefabEntityId: 'weapon', type: 'visibility', value: false });
+ });
+
+ it('emits metadata_set for new/changed and metadata_removed for dropped keys', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ // Change existing key
+ instance[0].metadata!['asset:Sprite.texture'] = 'uuid-different';
+ // Add new key
+ instance[0].metadata!['debug:autoSpin'] = true;
+ // Drop on weapon (wasn't there) — no diff expected
+ const { overrides } = diffAgainstSource(prefab, instance);
+ expect(overrides).toContainEqual({
+ prefabEntityId: 'root',
+ type: 'metadata_set',
+ metadataKey: 'asset:Sprite.texture',
+ value: 'uuid-different',
+ });
+ expect(overrides).toContainEqual({
+ prefabEntityId: 'root',
+ type: 'metadata_set',
+ metadataKey: 'debug:autoSpin',
+ value: true,
+ });
+ });
+
+ it('honours ignoreMetadataKeys', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ instance[0].metadata!['prefab:source'] = '@uuid:abc';
+ const { overrides } = diffAgainstSource(prefab, instance, {
+ ignoreMetadataKeys: ['prefab:source'],
+ });
+ expect(overrides).toEqual([]);
+ });
+
+ it('reports untracked entities and orphaned source ids', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ instance.push({
+ id: 99,
+ prefabEntityId: 'new-entity',
+ name: 'Adhoc',
+ parent: null,
+ children: [],
+ components: [],
+ visible: true,
+ });
+ instance.shift(); // drop the root so it's orphaned from source POV
+ const { untracked, orphanedSourceIds } = diffAgainstSource(prefab, instance);
+ expect(untracked.map(e => e.prefabEntityId)).toEqual(['new-entity']);
+ expect(orphanedSourceIds).toContain('root');
+ });
+
+ it('round-trip: applyOverrides(flatten(source), diffAgainstSource(source, instance)) reproduces instance', () => {
+ const prefab = uuidPrefab();
+ const instance = cloneForInstance(prefab);
+ instance[0].name = 'Modified';
+ instance[0].components[0].data = { x: 99, y: 0 };
+ instance[1].visible = false;
+ if (!instance[1].metadata) instance[1].metadata = {};
+ instance[1].metadata['custom'] = 42;
+
+ const { overrides } = diffAgainstSource(prefab, instance);
+
+ const { entities: reflattened } = flattenPrefab(prefab, overrides, freshCtx());
+ const reRoot = reflattened.find(e => e.prefabEntityId === 'root')!;
+ const reWeapon = reflattened.find(e => e.prefabEntityId === 'weapon')!;
+ expect(reRoot.name).toBe('Modified');
+ expect(reRoot.components.find(c => c.type === 'Transform')?.data).toEqual({ x: 99, y: 0 });
+ expect(reWeapon.visible).toBe(false);
+ expect(reWeapon.metadata?.['custom']).toBe(42);
+ });
+});
+
+// ─── validateOverrides ────────────────────────────────────────
+
+describe('validateOverrides', () => {
+ it('returns empty when all overrides resolve', () => {
+ const prefab = uuidPrefab();
+ const { stale, orphanedChildren } = validateOverrides(prefab, {
+ instanceOverrides: [
+ { prefabEntityId: 'root', type: 'name', value: 'X' },
+ { prefabEntityId: 'weapon', type: 'visibility', value: false },
+ ],
+ });
+ expect(stale).toEqual([]);
+ expect(orphanedChildren).toEqual([]);
+ });
+
+ it('flags override pointing at missing entity', () => {
+ const prefab = uuidPrefab();
+ const { stale } = validateOverrides(prefab, {
+ instanceOverrides: [
+ { prefabEntityId: 'ghost', type: 'name', value: 'X' },
+ ],
+ });
+ expect(stale).toHaveLength(1);
+ expect(stale[0].reason).toMatch(/entity "ghost" not found/);
+ });
+
+ it('flags property override for component not present on entity', () => {
+ const prefab = uuidPrefab();
+ const { stale } = validateOverrides(prefab, {
+ instanceOverrides: [
+ {
+ prefabEntityId: 'weapon',
+ type: 'property',
+ componentType: 'Physics',
+ propertyName: 'mass',
+ value: 1,
+ },
+ ],
+ });
+ expect(stale[0].reason).toMatch(/component "Physics" not present/);
+ });
+
+ it('flags metadata_removed when key is not present', () => {
+ const prefab = uuidPrefab();
+ const { stale } = validateOverrides(prefab, {
+ instanceOverrides: [
+ { prefabEntityId: 'weapon', type: 'metadata_removed', metadataKey: 'does-not-exist' },
+ ],
+ });
+ expect(stale[0].reason).toMatch(/metadata key "does-not-exist" not present/);
+ });
+
+ it('walks nested prefab overrides when a loader is supplied', () => {
+ const nested: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Nested',
+ rootEntityId: 'n-root',
+ entities: [
+ {
+ prefabEntityId: 'n-root',
+ name: 'NRoot',
+ parent: null,
+ children: [],
+ components: [],
+ visible: true,
+ },
+ ],
+ };
+ const outer: PrefabData = {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Outer',
+ rootEntityId: 'root',
+ entities: [
+ {
+ prefabEntityId: 'root',
+ name: 'Root',
+ parent: null,
+ children: [],
+ components: [],
+ visible: true,
+ nestedPrefab: {
+ prefabPath: 'nested.esprefab',
+ overrides: [
+ { prefabEntityId: 'ghost-in-nested', type: 'name', value: 'X' },
+ ],
+ },
+ },
+ ],
+ };
+ const { stale } = validateOverrides(outer, {
+ loadPrefab: (path) => path === 'nested.esprefab' ? nested : null,
+ });
+ expect(stale).toHaveLength(1);
+ expect(stale[0].site).toBe('nested');
+ expect(stale[0].nestedAt).toBe('root');
+ });
+});
+
+// ─── Bucketing (perf-correctness) ─────────────────────────────
+
+describe('bucketOverridesByEntity', () => {
+ it('groups overrides by prefabEntityId preserving order within each bucket', () => {
+ const overrides: PrefabOverride[] = [
+ { prefabEntityId: 'a', type: 'name', value: 'A1' },
+ { prefabEntityId: 'b', type: 'name', value: 'B1' },
+ { prefabEntityId: 'a', type: 'visibility', value: true },
+ { prefabEntityId: 'c', type: 'name', value: 'C1' },
+ { prefabEntityId: 'a', type: 'name', value: 'A2' },
+ ];
+ const buckets = bucketOverridesByEntity(overrides);
+ expect(buckets.get('a')!.map(o => o.value)).toEqual(['A1', true, 'A2']);
+ expect(buckets.get('b')!.map(o => o.value)).toEqual(['B1']);
+ expect(buckets.get('c')!.map(o => o.value)).toEqual(['C1']);
+ });
+
+ it('applied via flatten yields same result as pre-bucketed list', () => {
+ const prefab = uuidPrefab();
+ const overrides: PrefabOverride[] = [
+ { prefabEntityId: 'root', type: 'name', value: 'One' },
+ { prefabEntityId: 'weapon', type: 'visibility', value: false },
+ { prefabEntityId: 'root', type: 'visibility', value: false },
+ ];
+ const { entities } = flattenPrefab(prefab, overrides, freshCtx());
+ const root = entities.find(e => e.prefabEntityId === 'root')!;
+ const weapon = entities.find(e => e.prefabEntityId === 'weapon')!;
+ expect(root.name).toBe('One');
+ expect(root.visible).toBe(false);
+ expect(weapon.visible).toBe(false);
+ });
+});
+
+// ─── Loader migration log side effect ────────────────────────
+// (lightweight — heavier asset-loader integration covered elsewhere)
+
+describe('migration visible to callers', () => {
+ it('exposes fromVersion/toVersion so callers can inform the user', () => {
+ const { migrated, fromVersion, toVersion } = migratePrefabData({
+ version: '1.0',
+ name: 'x',
+ rootEntityId: 0,
+ entities: [{ prefabEntityId: 0, name: 'r', parent: null, children: [], components: [], visible: true }],
+ });
+ expect(migrated).toBe(true);
+ expect(fromVersion).toBe('1.0');
+ expect(toVersion).toBe(PREFAB_FORMAT_VERSION);
+ });
+});
+
+// ─── Self-smoke ──────────────────────────────────────────────
+// Guard against accidentally removing the vi import when trimming.
+vi.fn;
diff --git a/sdk/tests/prefab.test.ts b/sdk/tests/prefab.test.ts
index 5c20323ba..f936a6449 100644
--- a/sdk/tests/prefab.test.ts
+++ b/sdk/tests/prefab.test.ts
@@ -34,22 +34,22 @@ function simplePrefab(overrides?: Partial<PrefabData>): PrefabData {
return {
version: '1.0',
name: 'TestPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
- children: [1],
+ children: [ '1'],
components: [
{ type: 'Transform', data: { x: 0, y: 0 } },
],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'Child',
- parent: 0,
+ parent: '0',
children: [],
components: [
{ type: 'Sprite', data: { texture: 'test.png', color: 'red' } },
@@ -136,13 +136,14 @@ describe('Prefab', () => {
expect(result.entities.size).toBe(2);
});
- it('should filter children to only mapped entities', async () => {
+ it('should reject prefab whose children array references a missing entity', async () => {
const prefab = simplePrefab();
- prefab.entities[0].children = [1, 999];
- await instantiatePrefab(world, prefab);
-
- const root = capturedSceneData!.entities.find(e => e.name === 'Root')!;
- expect(root.children).toHaveLength(1);
+ (prefab.entities[0] as { children: string[] }).children = ['1', '999'];
+ // Strict: authoring a phantom child id is a structural corruption
+ // we surface early instead of silently filtering.
+ await expect(instantiatePrefab(world, prefab)).rejects.toThrow(
+ /lists child "999" which does not exist/,
+ );
});
it('should pass assets and assetBaseUrl to loadSceneWithAssets', async () => {
@@ -184,7 +185,7 @@ describe('Prefab', () => {
it('should apply property override to matching component', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'property',
componentType: 'Sprite',
propertyName: 'color',
@@ -201,7 +202,7 @@ describe('Prefab', () => {
it('should not modify non-matching entity', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType: 'Transform',
propertyName: 'x',
@@ -218,7 +219,7 @@ describe('Prefab', () => {
it('should ignore property override for non-existing component', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'property',
componentType: 'NonExistent',
propertyName: 'x',
@@ -237,7 +238,7 @@ describe('Prefab', () => {
it('should apply name override', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'name',
value: 'RenamedChild',
}];
@@ -251,7 +252,7 @@ describe('Prefab', () => {
it('should ignore name override with non-string value', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'name',
value: 42,
}];
@@ -267,7 +268,7 @@ describe('Prefab', () => {
it('should apply visibility override', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'visibility',
value: false,
}];
@@ -281,7 +282,7 @@ describe('Prefab', () => {
it('should ignore visibility override with non-boolean value', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'visibility',
value: 'false',
}];
@@ -297,7 +298,7 @@ describe('Prefab', () => {
it('should add a new component via override', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_added',
componentData: { type: 'Health', data: { value: 50 } },
}];
@@ -313,7 +314,7 @@ describe('Prefab', () => {
it('should not add duplicate component', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_added',
componentData: { type: 'Sprite', data: { texture: 'new.png' } },
}];
@@ -329,7 +330,7 @@ describe('Prefab', () => {
it('should deep clone component_added data', async () => {
const componentData = { type: 'Health', data: { value: 50 } };
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_added',
componentData,
}];
@@ -345,7 +346,7 @@ describe('Prefab', () => {
it('should ignore component_added without componentData', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_added',
}];
@@ -360,7 +361,7 @@ describe('Prefab', () => {
it('should remove a component via override', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_removed',
componentType: 'Sprite',
}];
@@ -374,7 +375,7 @@ describe('Prefab', () => {
it('should ignore removal of non-existing component', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_removed',
componentType: 'NonExistent',
}];
@@ -390,7 +391,7 @@ describe('Prefab', () => {
it('replaces the component data when the component exists', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_replaced',
componentData: { type: 'Sprite', data: { texture: 'replaced.png', color: 'blue' } },
}];
@@ -407,7 +408,7 @@ describe('Prefab', () => {
it('inserts the component when it does not already exist (upsert)', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_replaced',
componentData: { type: 'Health', data: { value: 75 } },
}];
@@ -423,7 +424,7 @@ describe('Prefab', () => {
it('deep clones the replacement data', async () => {
const componentData = { type: 'Sprite', data: { texture: 'other.png', color: 'green' } };
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_replaced',
componentData,
}];
@@ -439,7 +440,7 @@ describe('Prefab', () => {
it('ignores component_replaced without componentData', async () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_replaced',
}];
@@ -456,7 +457,7 @@ describe('Prefab', () => {
// Added — idempotent; existing Sprite stays as 'test.png'.
await instantiatePrefab(world, prefab, {
overrides: [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_added',
componentData: { type: 'Sprite', data: { texture: 'A.png' } },
}],
@@ -469,7 +470,7 @@ describe('Prefab', () => {
// Replaced — upserts; Sprite is now 'B.png'.
await instantiatePrefab(world, prefab, {
overrides: [{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_replaced',
componentData: { type: 'Sprite', data: { texture: 'B.png' } },
}],
@@ -492,30 +493,30 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'SliderPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'SliderRoot',
parent: null,
- children: [1, 2],
+ children: [ '1', '2'],
components: [
{ type: 'Slider', data: { fillEntity: 1, handleEntity: 2, value: 0.5 } },
],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'Fill',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
},
{
- prefabEntityId: 2,
+ prefabEntityId: '2',
name: 'Handle',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -538,10 +539,10 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'SliderPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'SliderRoot',
parent: null,
children: [],
@@ -565,9 +566,9 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'Test',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
children: [],
@@ -590,17 +591,17 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'SliderPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
- { prefabEntityId: 0, name: 'Root', parent: null, children: [1, 2], components: [], visible: true },
- { prefabEntityId: 1, name: 'Fill', parent: 0, children: [], components: [], visible: true },
- { prefabEntityId: 2, name: 'Handle', parent: 0, children: [], components: [], visible: true },
+ { prefabEntityId: '0', name: 'Root', parent: null, children: [ '1', '2'], components: [], visible: true },
+ { prefabEntityId: '1', name: 'Fill', parent: '0', children: [], components: [], visible: true },
+ { prefabEntityId: '2', name: 'Handle', parent: '0', children: [], components: [], visible: true },
],
};
await instantiatePrefab(world, prefab, {
overrides: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'component_added',
componentData: {
type: 'Slider',
@@ -622,24 +623,24 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'SliderPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
- children: [1, 2],
+ children: [ '1', '2'],
components: [{ type: 'Slider', data: { fillEntity: 0, handleEntity: 0, value: 0 } }],
visible: true,
},
- { prefabEntityId: 1, name: 'Fill', parent: 0, children: [], components: [], visible: true },
- { prefabEntityId: 2, name: 'Handle', parent: 0, children: [], components: [], visible: true },
+ { prefabEntityId: '1', name: 'Fill', parent: '0', children: [], components: [], visible: true },
+ { prefabEntityId: '2', name: 'Handle', parent: '0', children: [], components: [], visible: true },
],
};
await instantiatePrefab(world, prefab, {
overrides: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'component_replaced',
componentData: {
type: 'Slider',
@@ -660,23 +661,23 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'SliderPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
- children: [1],
+ children: [ '1'],
components: [{ type: 'Slider', data: { fillEntity: 0, handleEntity: 0, value: 0 } }],
visible: true,
},
- { prefabEntityId: 1, name: 'Fill', parent: 0, children: [], components: [], visible: true },
+ { prefabEntityId: '1', name: 'Fill', parent: '0', children: [], components: [], visible: true },
],
};
await instantiatePrefab(world, prefab, {
overrides: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType: 'Slider',
propertyName: 'fillEntity',
@@ -696,9 +697,9 @@ describe('Prefab', () => {
const childPrefab: PrefabData = {
version: '1.0',
name: 'ChildPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'NestedRoot',
parent: null,
children: [],
@@ -710,20 +711,20 @@ describe('Prefab', () => {
const parentPrefab: PrefabData = {
version: '1.0',
name: 'ParentPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'ParentRoot',
parent: null,
- children: [1],
+ children: [ '1'],
components: [{ type: 'Transform', data: { x: 0 } }],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'NestedSlot',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -751,20 +752,20 @@ describe('Prefab', () => {
const childPrefab: PrefabData = {
version: '1.0',
name: 'ChildPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'NestedRoot',
parent: null,
- children: [1],
+ children: [ '1'],
components: [],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'NestedChild',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -775,20 +776,20 @@ describe('Prefab', () => {
const parentPrefab: PrefabData = {
version: '1.0',
name: 'ParentPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'ParentRoot',
parent: null,
- children: [1],
+ children: [ '1'],
components: [],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'NestedSlot',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -815,9 +816,9 @@ describe('Prefab', () => {
const childPrefab: PrefabData = {
version: '1.0',
name: 'ChildPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'NestedRoot',
parent: null,
children: [],
@@ -829,20 +830,20 @@ describe('Prefab', () => {
const parentPrefab: PrefabData = {
version: '1.0',
name: 'ParentPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'ParentRoot',
parent: null,
- children: [1],
+ children: [ '1'],
components: [],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'NestedSlot',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -869,9 +870,9 @@ describe('Prefab', () => {
const childPrefab: PrefabData = {
version: '1.0',
name: 'ChildPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'NestedRoot',
parent: null,
children: [],
@@ -883,27 +884,27 @@ describe('Prefab', () => {
const parentPrefab: PrefabData = {
version: '1.0',
name: 'ParentPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'ParentRoot',
parent: null,
- children: [1],
+ children: [ '1'],
components: [],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'NestedSlot',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
nestedPrefab: {
prefabPath: 'child.prefab',
overrides: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType: 'Sprite',
propertyName: 'color',
@@ -929,20 +930,20 @@ describe('Prefab', () => {
const selfRefPrefab: PrefabData = {
version: '1.0',
name: 'SelfRef',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
- children: [1],
+ children: [ '1'],
components: [],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'Nested',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -967,20 +968,20 @@ describe('Prefab', () => {
const deepPrefab: PrefabData = {
version: '1.0',
name: 'Deep',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
- children: [1],
+ children: [ '1'],
components: [],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'Nested',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -1018,20 +1019,20 @@ describe('Prefab', () => {
const parentPrefab: PrefabData = {
version: '1.0',
name: 'Parent',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
- children: [1],
+ children: [ '1'],
components: [],
visible: true,
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
name: 'Nested',
- parent: 0,
+ parent: '0',
children: [],
components: [],
visible: true,
@@ -1054,19 +1055,19 @@ describe('Prefab', () => {
const prefab = simplePrefab();
const overrides: PrefabOverride[] = [
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'name',
value: 'RenamedChild',
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'property',
componentType: 'Sprite',
propertyName: 'color',
value: 'blue',
},
{
- prefabEntityId: 1,
+ prefabEntityId: '1',
type: 'component_added',
componentData: { type: 'Health', data: { value: 100 } },
},
@@ -1086,9 +1087,9 @@ describe('Prefab', () => {
const childPrefab: PrefabData = {
version: '1.0',
name: 'ChildPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'NestedRoot',
parent: null,
children: [],
@@ -1100,9 +1101,9 @@ describe('Prefab', () => {
const parentPrefab: PrefabData = {
version: '1.0',
name: 'ParentPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Slot',
parent: null,
children: [],
@@ -1129,9 +1130,9 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'BadPrefab',
- rootEntityId: 99,
+ rootEntityId: '99',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
children: [],
@@ -1151,9 +1152,9 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'SingleEntity',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'OnlyEntity',
parent: null,
children: [],
@@ -1173,20 +1174,20 @@ describe('Prefab', () => {
const prefab: PrefabData = {
version: '1.0',
name: 'NonSequential',
- rootEntityId: 5,
+ rootEntityId: '5',
entities: [
{
- prefabEntityId: 5,
+ prefabEntityId: '5',
name: 'Root',
parent: null,
- children: [10],
+ children: [ '10'],
components: [],
visible: true,
},
{
- prefabEntityId: 10,
+ prefabEntityId: '10',
name: 'Child',
- parent: 5,
+ parent: '5',
children: [],
components: [],
visible: true,
@@ -1219,10 +1220,10 @@ describe('Prefab', () => {
const basePrefab: PrefabData = {
version: '1.0',
name: 'BasePrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
children: [],
@@ -1235,12 +1236,12 @@ describe('Prefab', () => {
const variant: PrefabData = {
version: '1.0',
name: 'VariantPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [],
basePrefab: 'base.prefab',
overrides: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType: 'Transform',
propertyName: 'x',
@@ -1266,10 +1267,10 @@ describe('Prefab', () => {
const basePrefab: PrefabData = {
version: '1.0',
name: 'BasePrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'Root',
parent: null,
children: [],
@@ -1282,12 +1283,12 @@ describe('Prefab', () => {
const variant: PrefabData = {
version: '1.0',
name: 'VariantPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [],
basePrefab: 'base.prefab',
overrides: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType: 'Sprite',
propertyName: 'color',
@@ -1302,7 +1303,7 @@ describe('Prefab', () => {
const instanceOverrides: PrefabOverride[] = [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'property',
componentType: 'Sprite',
propertyName: 'size',
@@ -1325,7 +1326,7 @@ describe('Prefab', () => {
const variant: PrefabData = {
version: '1.0',
name: 'CircularVariant',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [],
basePrefab: 'self.prefab',
};
@@ -1343,10 +1344,10 @@ describe('Prefab', () => {
const basePrefab: PrefabData = {
version: '1.0',
name: 'BasePrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
name: 'OriginalName',
parent: null,
children: [],
@@ -1359,12 +1360,12 @@ describe('Prefab', () => {
const variant: PrefabData = {
version: '1.0',
name: 'VariantPrefab',
- rootEntityId: 0,
+ rootEntityId: '0',
entities: [],
basePrefab: 'base.prefab',
overrides: [
{
- prefabEntityId: 0,
+ prefabEntityId: '0',
type: 'name',
value: 'RenamedInVariant',
},