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(prefab): unified strict validator + CI gate (P1)

yhh586b1a2a9c8b
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 3e660c3e0..b2224310b 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -129,6 +129,9 @@ jobs:
- name: Type-check Examples
run: node build-tools/cli.js check-examples
+ - name: Validate prefab assets
+ run: node build-tools/cli.js validate-prefabs
+
- name: Run SDK tests
run: pnpm --filter ./sdk exec vitest run
diff --git a/build-tools/cli.js b/build-tools/cli.js
index 30b0b462e..a2756b284 100644
--- a/build-tools/cli.js
+++ b/build-tools/cli.js
@@ -17,6 +17,7 @@ import { startWatch } from './tasks/watch.js';
import { BuildManifest } from './manifest.js';
import { handleBuildError } from './utils/errorHelp.js';
import { checkExamples } from './tasks/check-examples.js';
+import { validatePrefabs } from './tasks/validate-prefabs.js';
program
.name('esengine-build')
@@ -212,6 +213,16 @@ program
logger.printTime(startTime);
});
+program
+ .command('validate-prefabs')
+ .description('Run the unified prefab validator over every shipped .esprefab')
+ .action(async () => {
+ logger.header('Validate Prefabs');
+ const startTime = Date.now();
+ await validatePrefabs(config.paths.root);
+ logger.printTime(startTime);
+ });
+
program
.command('toolchain')
.description('Package local emsdk + cmake into Tauri resources for bundling')
diff --git a/build-tools/tasks/validate-prefabs.js b/build-tools/tasks/validate-prefabs.js
new file mode 100644
index 000000000..02c845871
--- /dev/null
+++ b/build-tools/tasks/validate-prefabs.js
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file validate-prefabs.js
+ * @brief Run the SDK's unified prefab validator over every shipped .esprefab
+ *
+ * Loads each prefab (migrating legacy v1 → current format first), resolves
+ * nested/variant refs across the repo by uuid, and runs `validatePrefab`. Any
+ * ERROR fails CI; warnings (stale overrides, dangling refs) are printed only.
+ * The validator itself lives in the SDK so editor / runtime / cook / CI all
+ * share ONE implementation.
+ */
+
+import { readFileSync, readdirSync, statSync, existsSync } from 'fs';
+import path from 'path';
+import { pathToFileURL } from 'url';
+import * as logger from '../utils/logger.js';
+
+// Every directory tree that ships .esprefab assets to users.
+const PREFAB_ROOTS = ['examples', 'sdk/src/ui/widgets/prefabs', 'desktop/templates'];
+const SKIP_DIRS = new Set(['node_modules', '.esengine', 'dist', '.git']);
+
+function walkPrefabs(dir, out) {
+ if (!existsSync(dir)) return;
+ for (const entry of readdirSync(dir)) {
+ const full = path.join(dir, entry);
+ let st;
+ try { st = statSync(full); } catch { continue; }
+ if (st.isDirectory()) {
+ if (SKIP_DIRS.has(entry)) continue;
+ walkPrefabs(full, out);
+ } else if (entry.endsWith('.esprefab')) {
+ out.push(full);
+ }
+ }
+}
+
+export async function validatePrefabs(rootDir) {
+ logger.step('Validating prefab assets...');
+
+ const sdkNode = path.join(rootDir, 'sdk', 'dist', 'index.node.js');
+ if (!existsSync(sdkNode)) {
+ logger.error('SDK dist not found. Build SDK first: pnpm --filter ./sdk build');
+ process.exit(1);
+ }
+ const { validatePrefab, migratePrefabData } = await import(pathToFileURL(sdkNode).href);
+
+ const files = [];
+ for (const rel of PREFAB_ROOTS) walkPrefabs(path.join(rootDir, rel), files);
+ if (files.length === 0) {
+ logger.warn('No .esprefab files found');
+ return { files: 0, errors: 0, warnings: 0 };
+ }
+
+ // Parse + migrate every prefab up-front, and index by asset uuid (from the
+ // sibling .meta) so nested/variant `@uuid:` refs resolve for the loader.
+ const parsed = new Map(); // absolute file → migrated PrefabData
+ const byUuid = new Map(); // asset uuid → migrated PrefabData
+ let errors = 0;
+ for (const file of files) {
+ try {
+ const data = migratePrefabData(JSON.parse(readFileSync(file, 'utf8'))).data;
+ parsed.set(file, data);
+ const metaPath = `${file}.meta`;
+ if (existsSync(metaPath)) {
+ const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
+ if (meta.uuid) byUuid.set(meta.uuid, data);
+ }
+ } catch (err) {
+ logger.error(` ${path.relative(rootDir, file)} [parse] ${err.message}`);
+ errors++;
+ }
+ }
+
+ const resolveRef = (ref, fromFile) => {
+ if (typeof ref !== 'string') return null;
+ if (ref.startsWith('@uuid:')) return byUuid.get(ref.slice('@uuid:'.length)) ?? null;
+ const abs = path.isAbsolute(ref) ? ref : path.join(path.dirname(fromFile), ref);
+ return parsed.get(abs) ?? null;
+ };
+
+ let warnings = 0;
+ for (const file of files) {
+ const data = parsed.get(file);
+ if (!data) continue; // already counted as a parse error
+ const rel = path.relative(rootDir, file);
+ const diags = validatePrefab(data, { loadPrefab: (ref) => resolveRef(ref, file) });
+ if (diags.length === 0) {
+ logger.success(rel);
+ continue;
+ }
+ for (const d of diags) {
+ const at = d.entityId ? ` @${d.entityId}${d.field ? `.${d.field}` : ''}` : '';
+ const line = ` ${rel} [${d.code}]${at} ${d.message}`;
+ if (d.severity === 'error') { logger.error(line); errors++; }
+ else { logger.warn(line); warnings++; }
+ }
+ }
+
+ logger.step(`Prefab validation: ${files.length} files, ${errors} error(s), ${warnings} warning(s)`);
+ if (errors > 0) process.exitCode = 1;
+ return { files: files.length, errors, warnings };
+}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 66615fe5c..15652fdc1 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1283 stable · 17 beta · 0 deprecated
+Symbols: 1287 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4684,6 +4684,20 @@ rootEntityId: string
version: string
```
+## PrefabDiagnostic — interface
+```
+code: string
+entityId: string | undefined
+field: string | undefined
+message: string
+severity: PrefabDiagnosticSeverity
+```
+
+## PrefabDiagnosticSeverity — type
+```
+'error' | 'warning'
+```
+
## PrefabEntityData — interface
```
children: string[]
@@ -7412,6 +7426,12 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
() => void
```
+## ValidatePrefabOptions — interface
+```
+instanceOverrides: readonly PrefabOverride[] | undefined
+loadPrefab: ((path: string) => PrefabData | null) | undefined
+```
+
## ValidateResult — interface
```
duplicateIds: string[]
@@ -9880,6 +9900,11 @@ UIRenderOrderPlugin
(prefab: PrefabData, options?: { instanceOverrides?: readonly PrefabOverride[]; loadPrefab?: (path: string) => PrefabData | null; }): ValidateResult
```
+## validatePrefab — function
+```
+(prefab: PrefabData, options?: ValidatePrefabOptions): PrefabDiagnostic[]
+```
+
## vec2 — const
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ad97552bf..8174f679d 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1282 stable · 19 beta · 0 deprecated
+Symbols: 1286 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -4679,6 +4679,20 @@ rootEntityId: string
version: string
```
+## PrefabDiagnostic — interface
+```
+code: string
+entityId: string | undefined
+field: string | undefined
+message: string
+severity: PrefabDiagnosticSeverity
+```
+
+## PrefabDiagnosticSeverity — type
+```
+'error' | 'warning'
+```
+
## PrefabEntityData — interface
```
children: string[]
@@ -7407,6 +7421,12 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
() => void
```
+## ValidatePrefabOptions — interface
+```
+instanceOverrides: readonly PrefabOverride[] | undefined
+loadPrefab: ((path: string) => PrefabData | null) | undefined
+```
+
## ValidateResult — interface
```
duplicateIds: string[]
@@ -9885,6 +9905,11 @@ UIRenderOrderPlugin
(prefab: PrefabData, options?: { instanceOverrides?: readonly PrefabOverride[]; loadPrefab?: (path: string) => PrefabData | null; }): ValidateResult
```
+## validatePrefab — function
+```
+(prefab: PrefabData, options?: ValidatePrefabOptions): PrefabDiagnostic[]
+```
+
## vec2 — const
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 0a8f76967..587070ae1 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1293 stable · 17 beta · 0 deprecated
+Symbols: 1297 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -4686,6 +4686,20 @@ rootEntityId: string
version: string
```
+## PrefabDiagnostic — interface
+```
+code: string
+entityId: string | undefined
+field: string | undefined
+message: string
+severity: PrefabDiagnosticSeverity
+```
+
+## PrefabDiagnosticSeverity — type
+```
+'error' | 'warning'
+```
+
## PrefabEntityData — interface
```
children: string[]
@@ -7414,6 +7428,12 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
() => void
```
+## ValidatePrefabOptions — interface
+```
+instanceOverrides: readonly PrefabOverride[] | undefined
+loadPrefab: ((path: string) => PrefabData | null) | undefined
+```
+
## ValidateResult — interface
```
duplicateIds: string[]
@@ -9904,6 +9924,11 @@ UIRenderOrderPlugin
(prefab: PrefabData, options?: { instanceOverrides?: readonly PrefabOverride[]; loadPrefab?: (path: string) => PrefabData | null; }): ValidateResult
```
+## validatePrefab — function
+```
+(prefab: PrefabData, options?: ValidatePrefabOptions): PrefabDiagnostic[]
+```
+
## vec2 — const
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 765b54e84..a9ecbafd8 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -175,6 +175,7 @@ export {
diffAgainstSource,
applyOverridesToSource,
validateOverrides,
+ validatePrefab,
expandInstance,
collapseInstance,
expandEntry,
@@ -190,6 +191,9 @@ export {
type DiffOptions,
type ValidateResult,
type StaleOverride,
+ type PrefabDiagnostic,
+ type PrefabDiagnosticSeverity,
+ type ValidatePrefabOptions,
type AddedEntity,
type PrefabInstanceDelta,
type PrefabInstanceEntry,
diff --git a/sdk/src/prefab/index.ts b/sdk/src/prefab/index.ts
index d6e65e2ae..704ab2150 100644
--- a/sdk/src/prefab/index.ts
+++ b/sdk/src/prefab/index.ts
@@ -22,8 +22,14 @@ 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';
+export { validateOverrides, validatePrefab } from './validate';
+export type {
+ ValidateResult,
+ StaleOverride,
+ PrefabDiagnostic,
+ PrefabDiagnosticSeverity,
+ ValidatePrefabOptions,
+} from './validate';
export {
expandInstance,
diff --git a/sdk/src/prefab/validate.ts b/sdk/src/prefab/validate.ts
index 9bce3932f..56823b242 100644
--- a/sdk/src/prefab/validate.ts
+++ b/sdk/src/prefab/validate.ts
@@ -7,6 +7,7 @@ import type {
PrefabOverride,
} from './types';
import { PREFAB_ADDRESS_SEP } from './types';
+import { getComponent } from '../component';
export interface StaleOverride {
override: PrefabOverride;
@@ -157,3 +158,272 @@ function reasonForOverride(
return null;
}
}
+
+// ── Unified strict validator ────────────────────────────────────────────────
+// `validateOverrides` above is the editor's focused stale-override check.
+// `validatePrefab` is the ONE comprehensive asset validator meant to run at
+// every gate (editor open/save, runtime load, cook, CI). It never throws — it
+// returns structured diagnostics so each caller decides how to surface them.
+
+export type PrefabDiagnosticSeverity = 'error' | 'warning';
+
+/** One structured problem found in a prefab asset. */
+export interface PrefabDiagnostic {
+ /** Stable machine code (kebab-case), e.g. `duplicate-id`, `parent-cycle`. */
+ code: string;
+ severity: PrefabDiagnosticSeverity;
+ /** One-line human-readable explanation. */
+ message: string;
+ /** The entity the problem is on, when applicable. */
+ entityId?: PrefabEntityId;
+ /** The component type / `Comp.field` / metadata key involved, when applicable. */
+ field?: string;
+}
+
+export interface ValidatePrefabOptions {
+ /** Resolver for nested / variant dependency + nested-override checks. */
+ loadPrefab?: (path: string) => PrefabData | null;
+ /** Instance-site overrides (a scene instance's delta) to validate too. */
+ instanceOverrides?: readonly PrefabOverride[];
+}
+
+/**
+ * Validate a prefab asset end-to-end and return every problem found. Errors mean
+ * the prefab is structurally broken (flatten would misbehave or throw); warnings
+ * are suspicious but loadable (stale overrides, dangling refs). Pure + total.
+ */
+export function validatePrefab(
+ prefab: PrefabData,
+ options?: ValidatePrefabOptions,
+): PrefabDiagnostic[] {
+ const diags: PrefabDiagnostic[] = [];
+ const push = (
+ code: string,
+ severity: PrefabDiagnosticSeverity,
+ message: string,
+ entityId?: PrefabEntityId,
+ field?: string,
+ ): void => {
+ diags.push({
+ code,
+ severity,
+ message,
+ ...(entityId !== undefined ? { entityId } : {}),
+ ...(field !== undefined ? { field } : {}),
+ });
+ };
+
+ // Pass 1: id integrity + per-entity component-type uniqueness.
+ const byId = new Map<PrefabEntityId, PrefabEntityData>();
+ const seen = new Set<PrefabEntityId>();
+ for (const e of prefab.entities) {
+ if (e.prefabEntityId.includes(PREFAB_ADDRESS_SEP)) {
+ push('invalid-id', 'error', `entity id "${e.prefabEntityId}" contains the reserved separator "${PREFAB_ADDRESS_SEP}"`, e.prefabEntityId);
+ }
+ if (seen.has(e.prefabEntityId)) {
+ push('duplicate-id', 'error', `entity id "${e.prefabEntityId}" appears more than once`, e.prefabEntityId);
+ } else {
+ seen.add(e.prefabEntityId);
+ }
+ byId.set(e.prefabEntityId, e);
+
+ const compTypes = new Set<string>();
+ for (const c of e.components) {
+ if (compTypes.has(c.type)) {
+ push('duplicate-component', 'error', `entity "${e.prefabEntityId}" has more than one "${c.type}" component`, e.prefabEntityId, c.type);
+ } else {
+ compTypes.add(c.type);
+ }
+ }
+ }
+
+ // Pass 2: root existence (exactly one, referenced by rootEntityId).
+ if (!byId.has(prefab.rootEntityId)) {
+ push('root-missing', 'error', `rootEntityId "${prefab.rootEntityId}" is not an entity in the prefab`, prefab.rootEntityId);
+ }
+
+ // Pass 3: topology — parent/children two-way consistency + detached roots.
+ for (const e of prefab.entities) {
+ if (e.parent === null) {
+ if (e.prefabEntityId !== prefab.rootEntityId) {
+ push('detached-entity', 'error', `entity "${e.prefabEntityId}" has parent=null but is not the root`, e.prefabEntityId);
+ }
+ } else {
+ const parent = byId.get(e.parent);
+ if (!parent) {
+ push('missing-parent', 'error', `entity "${e.prefabEntityId}" parent "${e.parent}" does not exist`, e.prefabEntityId);
+ } else if (!parent.children.includes(e.prefabEntityId)) {
+ push('inconsistent-topology', 'error', `entity "${e.prefabEntityId}" claims parent "${e.parent}" but that parent's children omit it`, e.prefabEntityId);
+ }
+ }
+ for (const childId of e.children) {
+ const child = byId.get(childId);
+ if (!child) {
+ push('missing-child', 'error', `entity "${e.prefabEntityId}" lists child "${childId}" which does not exist`, e.prefabEntityId, childId);
+ } else if (child.parent !== e.prefabEntityId) {
+ push('inconsistent-topology', 'error', `entity "${e.prefabEntityId}" lists "${childId}" as a child but its parent points elsewhere`, e.prefabEntityId, childId);
+ }
+ }
+ }
+
+ // Pass 4: no parent cycle (report at most one — a cycle spams otherwise).
+ detectParentCycle(prefab, byId, push);
+
+ // Pass 5: every entity reachable from the root (via children edges).
+ if (byId.has(prefab.rootEntityId)) {
+ const reachable = new Set<PrefabEntityId>();
+ const queue: PrefabEntityId[] = [prefab.rootEntityId];
+ while (queue.length > 0) {
+ const cur = queue.shift()!;
+ if (reachable.has(cur)) continue;
+ reachable.add(cur);
+ for (const c of byId.get(cur)?.children ?? []) if (byId.has(c)) queue.push(c);
+ }
+ for (const e of prefab.entities) {
+ if (!reachable.has(e.prefabEntityId)) {
+ push('unreachable', 'error', `entity "${e.prefabEntityId}" is not reachable from the root "${prefab.rootEntityId}"`, e.prefabEntityId);
+ }
+ }
+ }
+
+ // Pass 6: entity-ref component fields must resolve within the prefab.
+ for (const e of prefab.entities) {
+ for (const c of e.components) {
+ const def = getComponent(c.type);
+ if (!def || def.entityFields.length === 0) continue;
+ for (const field of def.entityFields) {
+ const v = c.data[field];
+ if (typeof v === 'string' && !byId.has(v)) {
+ push('dangling-entity-ref', 'warning', `entity "${e.prefabEntityId}" field "${c.type}.${field}" references "${v}", which is not in the prefab`, e.prefabEntityId, `${c.type}.${field}`);
+ }
+ }
+ }
+ }
+
+ // Pass 7: override shape + staleness (variant / instance / nested sites).
+ const checkOverrides = (
+ overrides: readonly PrefabOverride[],
+ target: PrefabData,
+ site: string,
+ ): void => {
+ const map = new Map<PrefabEntityId, PrefabEntityData>();
+ for (const x of target.entities) map.set(x.prefabEntityId, x);
+ for (const o of overrides) {
+ const shape = overrideShapeError(o);
+ if (shape) {
+ push('invalid-override', 'error', `${site} override on "${o.prefabEntityId}": ${shape}`, o.prefabEntityId);
+ continue;
+ }
+ const entity = map.get(o.prefabEntityId);
+ if (!entity) {
+ push('stale-override', 'warning', `${site} override targets "${o.prefabEntityId}", not found in "${target.name}"`, o.prefabEntityId);
+ continue;
+ }
+ const reason = reasonForOverride(o, entity);
+ if (reason) push('stale-override', 'warning', `${site} override on "${o.prefabEntityId}": ${reason}`, o.prefabEntityId);
+ }
+ };
+ if (prefab.overrides) checkOverrides(prefab.overrides, prefab, 'variant');
+ if (options?.instanceOverrides) checkOverrides(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) checkOverrides(e.nestedPrefab.overrides, nested, `nested@${e.prefabEntityId}`);
+ }
+ // Pass 8: nested / variant dependency graph must be acyclic.
+ detectDependencyCycle(prefab, loader, push);
+ }
+
+ return diags;
+}
+
+/** Missing-required-field / wrong-value-type check for a single override. */
+function overrideShapeError(o: PrefabOverride): string | null {
+ switch (o.type) {
+ case 'property':
+ if (!o.componentType) return 'missing componentType';
+ if (o.propertyName === undefined) return 'missing propertyName';
+ return null;
+ case 'component_added':
+ case 'component_replaced':
+ if (!o.componentData || typeof o.componentData.type !== 'string') return 'missing componentData.type';
+ if (typeof o.componentData.data !== 'object' || o.componentData.data === null) return 'missing componentData.data';
+ return null;
+ case 'component_removed':
+ return o.componentType ? null : 'missing componentType';
+ case 'name':
+ return typeof o.value === 'string' ? null : 'name value must be a string';
+ case 'visibility':
+ return typeof o.value === 'boolean' ? null : 'visibility value must be a boolean';
+ case 'metadata_set':
+ case 'metadata_removed':
+ return typeof o.metadataKey === 'string' ? null : 'missing metadataKey';
+ default:
+ return `unknown override type "${(o as { type: string }).type}"`;
+ }
+}
+
+function detectParentCycle(
+ prefab: PrefabData,
+ byId: Map<PrefabEntityId, PrefabEntityData>,
+ push: (code: string, severity: PrefabDiagnosticSeverity, message: string, entityId?: PrefabEntityId) => void,
+): void {
+ const WHITE = 0, GRAY = 1, BLACK = 2;
+ const color = new Map<PrefabEntityId, number>();
+ for (const e of prefab.entities) color.set(e.prefabEntityId, WHITE);
+ let reported = false;
+
+ const visit = (id: PrefabEntityId, path: PrefabEntityId[]): void => {
+ if (reported) return;
+ const c = color.get(id);
+ if (c === BLACK) return;
+ if (c === GRAY) {
+ const start = path.indexOf(id);
+ const cycle = path.slice(start).concat(id).join(' → ');
+ push('parent-cycle', 'error', `parent cycle detected: ${cycle}`, id);
+ reported = true;
+ return;
+ }
+ color.set(id, GRAY);
+ const e = byId.get(id);
+ if (e && e.parent !== null && byId.has(e.parent)) visit(e.parent, [...path, id]);
+ color.set(id, BLACK);
+ };
+ for (const e of prefab.entities) visit(e.prefabEntityId, []);
+}
+
+function detectDependencyCycle(
+ prefab: PrefabData,
+ loadPrefab: (path: string) => PrefabData | null,
+ push: (code: string, severity: PrefabDiagnosticSeverity, message: string, entityId?: PrefabEntityId) => void,
+): void {
+ const stack = new Set<string>();
+ let reported = false;
+
+ const depsOf = (p: PrefabData): string[] => {
+ const deps: string[] = [];
+ if (p.basePrefab) deps.push(p.basePrefab);
+ for (const e of p.entities) if (e.nestedPrefab) deps.push(e.nestedPrefab.prefabPath);
+ return deps;
+ };
+
+ const walk = (p: PrefabData): void => {
+ if (reported) return;
+ for (const dep of depsOf(p)) {
+ if (stack.has(dep)) {
+ push('dependency-cycle', 'error', `prefab dependency cycle involving "${dep}"`);
+ reported = true;
+ return;
+ }
+ const child = loadPrefab(dep);
+ if (!child) continue;
+ stack.add(dep);
+ walk(child);
+ stack.delete(dep);
+ if (reported) return;
+ }
+ };
+ walk(prefab);
+}
diff --git a/sdk/tests/prefab-validate.test.ts b/sdk/tests/prefab-validate.test.ts
new file mode 100644
index 000000000..3844eb083
--- /dev/null
+++ b/sdk/tests/prefab-validate.test.ts
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The unified strict prefab validator (`validatePrefab`) — one structured-
+ * diagnostic pass shared by editor open/save, runtime load, cook and CI.
+ * Each test pins one diagnostic code so the CI gate + editor surfacing can
+ * rely on stable codes.
+ */
+import { describe, it, expect } from 'vitest';
+import type { PrefabData, PrefabDiagnostic } from '../src/prefab/index';
+import { validatePrefab, PREFAB_FORMAT_VERSION } from '../src/prefab/index';
+import { defineComponent } from '../src/component';
+
+function clean(): PrefabData {
+ return {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Hero',
+ rootEntityId: 'root',
+ entities: [
+ { prefabEntityId: 'root', name: 'Hero', parent: null, children: ['weapon'], components: [{ type: 'Transform', data: {} }], visible: true },
+ { prefabEntityId: 'weapon', name: 'Weapon', parent: 'root', children: [], components: [], visible: true },
+ ],
+ };
+}
+
+const codes = (d: PrefabDiagnostic[]): string[] => d.map((x) => x.code);
+const errors = (d: PrefabDiagnostic[]): PrefabDiagnostic[] => d.filter((x) => x.severity === 'error');
+
+describe('validatePrefab', () => {
+ it('returns no diagnostics for a well-formed prefab', () => {
+ expect(validatePrefab(clean())).toEqual([]);
+ });
+
+ it('flags a missing root', () => {
+ const p = clean();
+ p.rootEntityId = 'ghost';
+ expect(codes(validatePrefab(p))).toContain('root-missing');
+ });
+
+ it('flags a duplicate id', () => {
+ const p = clean();
+ p.entities[1].prefabEntityId = 'root';
+ p.entities[0].children = [];
+ const d = validatePrefab(p);
+ expect(codes(d)).toContain('duplicate-id');
+ });
+
+ it('flags an id containing the reserved separator', () => {
+ const p = clean();
+ p.entities[1].prefabEntityId = 'a/b';
+ p.entities[0].children = ['a/b'];
+ expect(codes(validatePrefab(p))).toContain('invalid-id');
+ });
+
+ it('flags a detached (parentless, non-root) entity', () => {
+ const p = clean();
+ p.entities[1].parent = null;
+ p.entities[0].children = [];
+ expect(codes(validatePrefab(p))).toContain('detached-entity');
+ });
+
+ it('flags a missing parent reference', () => {
+ const p = clean();
+ p.entities[1].parent = 'ghost';
+ p.entities[0].children = [];
+ expect(codes(validatePrefab(p))).toContain('missing-parent');
+ });
+
+ it('flags a missing child reference', () => {
+ const p = clean();
+ p.entities[0].children = ['weapon', 'ghost'];
+ expect(codes(validatePrefab(p))).toContain('missing-child');
+ });
+
+ it('flags parent/children disagreement', () => {
+ const p = clean();
+ p.entities[0].children = []; // root no longer lists weapon, but weapon.parent='root'
+ expect(codes(validatePrefab(p))).toContain('inconsistent-topology');
+ });
+
+ it('flags an entity unreachable from the root', () => {
+ const p = clean();
+ // A well-formed but disconnected pair reachable from neither root nor each-other-via-root.
+ p.entities.push(
+ { prefabEntityId: 'floatA', name: 'A', parent: 'floatB', children: [], components: [], visible: true },
+ { prefabEntityId: 'floatB', name: 'B', parent: null, children: ['floatA'], components: [], visible: true },
+ );
+ const d = validatePrefab(p);
+ expect(codes(d)).toContain('unreachable');
+ expect(codes(d)).toContain('detached-entity'); // floatB is a second parentless root
+ });
+
+ it('flags a parent cycle', () => {
+ const p: PrefabData = {
+ version: PREFAB_FORMAT_VERSION, name: 'Cyc', rootEntityId: 'a',
+ entities: [
+ { prefabEntityId: 'a', name: 'A', parent: 'b', children: ['b'], components: [], visible: true },
+ { prefabEntityId: 'b', name: 'B', parent: 'a', children: ['a'], components: [], visible: true },
+ ],
+ };
+ expect(codes(validatePrefab(p))).toContain('parent-cycle');
+ });
+
+ it('flags a duplicate component type on one entity', () => {
+ const p = clean();
+ p.entities[0].components = [{ type: 'Transform', data: {} }, { type: 'Transform', data: { x: 1 } }];
+ const d = validatePrefab(p);
+ expect(codes(d)).toContain('duplicate-component');
+ expect(d.find((x) => x.code === 'duplicate-component')?.field).toBe('Transform');
+ });
+
+ it('warns on a dangling entity-ref field', () => {
+ defineComponent('FollowTargetV', { target: 0 }, { entityFields: ['target'] });
+ const p = clean();
+ p.entities[1].components = [{ type: 'FollowTargetV', data: { target: 'ghost' } }];
+ const d = validatePrefab(p);
+ const ref = d.find((x) => x.code === 'dangling-entity-ref');
+ expect(ref?.severity).toBe('warning');
+ expect(ref?.field).toBe('FollowTargetV.target');
+ });
+
+ it('accepts an entity-ref that resolves within the prefab', () => {
+ defineComponent('FollowTargetV', { target: 0 }, { entityFields: ['target'] });
+ const p = clean();
+ p.entities[1].components = [{ type: 'FollowTargetV', data: { target: 'root' } }];
+ expect(codes(validatePrefab(p))).not.toContain('dangling-entity-ref');
+ });
+
+ it('flags a malformed override (missing componentType)', () => {
+ const p = clean();
+ p.overrides = [{ prefabEntityId: 'root', type: 'property', propertyName: 'x', value: 1 }];
+ expect(codes(validatePrefab(p))).toContain('invalid-override');
+ });
+
+ it('warns on a stale override targeting a missing entity', () => {
+ const p = clean();
+ const d = validatePrefab(p, { instanceOverrides: [{ prefabEntityId: 'ghost', type: 'name', value: 'X' }] });
+ const stale = d.find((x) => x.code === 'stale-override');
+ expect(stale?.severity).toBe('warning');
+ });
+
+ it('flags a nested/variant dependency cycle via the loader', () => {
+ 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: [] } },
+ ],
+ };
+ const d = validatePrefab(self, { loadPrefab: (p) => (p === 'self' ? self : null) });
+ expect(codes(d)).toContain('dependency-cycle');
+ });
+
+ it('separates errors from warnings', () => {
+ const p = clean();
+ p.rootEntityId = 'ghost'; // error
+ p.overrides = [{ prefabEntityId: 'nope', type: 'name', value: 'X' }]; // warning (stale)
+ const d = validatePrefab(p);
+ expect(errors(d).map((x) => x.code)).toContain('root-missing');
+ expect(d.some((x) => x.code === 'stale-override' && x.severity === 'warning')).toBe(true);
+ });
+});