A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(bridge): verify all builtin bindings up-front in strict mode
esengine11065048220d
diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex d78881794..0fabe131c 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -8,6 +8,7 @@ import { Schedule, SystemDef, SystemRunner } from './system';import { ResourceStorage, Time, TimeData, type ResourceDef } from './resource';import { EventRegistry, type EventDef } from './event';import type { ESEngineModule, CppRegistry } from './wasm';+import type { BridgeConnectOptions } from './ecs/BuiltinBridge';import { UICameraInfo } from './ui/UICameraInfo';import { inputPlugin } from './input';import { assetPlugin } from './asset';@@ -222,8 +223,12 @@ export class App {// C++ Integration// =========================================================================- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this {- this.world_.connectCpp(cppRegistry, module);+ connectCpp(+ cppRegistry: CppRegistry,+ module?: ESEngineModule,+ options?: BridgeConnectOptions,+ ): this {+ this.world_.connectCpp(cppRegistry, module, options);if (module) {this.module_ = module;@@ -779,7 +784,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aconst app = App.new();const cppRegistry = new module.Registry() as unknown as CppRegistry;- app.connectCpp(cppRegistry, module);+ app.connectCpp(cppRegistry, module, { strict: true });if (options?.glContextHandle) {module.initRendererWithContext(options.glContextHandle);diff --git a/sdk/src/ecs/BuiltinBridge.ts b/sdk/src/ecs/BuiltinBridge.tsindex 00a2096ec..9e45f0917 100644--- a/sdk/src/ecs/BuiltinBridge.ts+++ b/sdk/src/ecs/BuiltinBridge.ts@@ -8,6 +8,7 @@ import type { BuiltinComponentDef } from '../component';import type { CppRegistry, ESEngineModule } from '../wasm';import { validateComponentData, formatValidationErrors } from '../validation';import { handleWasmError } from '../wasmError';+import { COMPONENT_META } from '../component.generated';import { PTR_LAYOUTS } from '../ptrLayouts.generated';import { PTR_ACCESSORS } from './ptrAccessors.generated';@@ -169,6 +170,38 @@ export interface BuiltinMethods {remove: (e: Entity) => void;}+/** Result of verifying a connected C++ Registry against the generated metadata. */+export interface BridgeVerification {+ /** True when every component in COMPONENT_META has all four methods. */+ readonly ok: boolean;+ /** List of components with missing bindings (empty when ok). */+ readonly missing: readonly { readonly name: string; readonly methods: readonly string[] }[];+}++/** Options for {@link BuiltinBridge.connect}. */+export interface BridgeConnectOptions {+ /**+ * When true (recommended for production), verify every component in+ * COMPONENT_META against the registry at connect time and throw a single+ * aggregated diagnostic if any bindings are missing. When false (default,+ * legacy-compatible), pre-populate the method cache for whatever bindings+ * exist and let per-component lookups throw on demand — this keeps+ * partial mock registries used in unit tests working unchanged.+ */+ readonly strict?: boolean;+}++const METHOD_PREFIXES = ['add', 'get', 'has', 'remove'] as const;++function formatMissingBindings(missing: readonly { name: string; methods: readonly string[] }[]): string {+ const detail = missing.map(m => ` - ${m.name}: missing ${m.methods.join(', ')}`).join('\n');+ return (+ `C++ Registry is missing ${String(missing.length)} builtin component binding(s):\n${detail}\n\n` ++ `Likely cause: WebBindings.generated.cpp is out of sync with component.generated.ts. ` ++ `Rerun the EHT generator and rebuild the WASM target.`+ );+}+// =============================================================================// BuiltinBridge// =============================================================================@@ -179,16 +212,43 @@ export class BuiltinBridge {private builtinMethodCache_ = new Map<string, BuiltinMethods>();private builtinEntitySets_ = new Map<string, Set<Entity>>();- connect(cppRegistry: CppRegistry, module?: ESEngineModule): void {+ /**+ * Bind to a C++ Registry.+ *+ * Production call sites should pass `{ strict: true }` so the bridge+ * verifies that every component declared in COMPONENT_META has its four+ * bindings (add/get/has/remove) and throws a single aggregated diagnostic+ * if any are missing. This surfaces drift between the WASM build and the+ * generated metadata at startup rather than on first component use.+ *+ * In non-strict mode (default, used by unit tests with partial mock+ * registries) the cache is pre-populated for whatever bindings exist and+ * individual `getBuiltinMethods()` calls throw lazily on missing ones.+ */+ connect(+ cppRegistry: CppRegistry,+ module?: ESEngineModule,+ options: BridgeConnectOptions = {},+ ): void {this.cppRegistry_ = cppRegistry;this.module_ = module ?? null;this.builtinMethodCache_.clear();+ this.builtinEntitySets_.clear();++ const verification = this.verifyAgainst_(cppRegistry);+ if (options.strict && !verification.ok) {+ this.cppRegistry_ = null;+ this.module_ = null;+ this.builtinMethodCache_.clear();+ throw new Error(formatMissingBindings(verification.missing));+ }}disconnect(): void {this.cppRegistry_ = null;this.module_ = null;this.builtinMethodCache_.clear();+ this.builtinEntitySets_.clear();}get hasCpp(): boolean {@@ -203,29 +263,61 @@ export class BuiltinBridge {return this.module_;}+ /**+ * Describe the current binding state without throwing. Useful for+ * diagnostics and tests that want to inspect coverage.+ */+ verify(): BridgeVerification {+ if (!this.cppRegistry_) return { ok: false, missing: [{ name: '<registry>', methods: ['connect() not called'] }] };+ return this.verifyAgainst_(this.cppRegistry_);+ }++ private verifyAgainst_(reg: CppRegistry): BridgeVerification {+ const missing: { name: string; methods: string[] }[] = [];+ for (const cppName of Object.keys(COMPONENT_META)) {+ const missingMethods: string[] = [];+ for (const prefix of METHOD_PREFIXES) {+ const fn = reg[`${prefix}${cppName}`];+ if (typeof fn !== 'function') missingMethods.push(`${prefix}${cppName}`);+ }+ if (missingMethods.length > 0) {+ missing.push({ name: cppName, methods: missingMethods });+ continue;+ }+ this.resolveAndCache_(reg, cppName);+ }+ return { ok: missing.length === 0, missing };+ }+getBuiltinMethods(cppName: string): BuiltinMethods {- let methods = this.builtinMethodCache_.get(cppName);- if (methods) return methods;+ const cached = this.builtinMethodCache_.get(cppName);+ if (cached) return cached;+ if (!this.cppRegistry_) {+ throw new Error(`BuiltinBridge.getBuiltinMethods("${cppName}") called before connect().`);+ }+ // Fallback for components not declared in COMPONENT_META — user-defined+ // builtins and test-only synthetic components. Production components are+ // resolved eagerly in verifyAgainst_ and never hit this path.+ return this.resolveAndCache_(this.cppRegistry_, cppName);+ }- const reg = this.cppRegistry_!;+ private resolveAndCache_(reg: CppRegistry, cppName: string): BuiltinMethods {const addFn = reg[`add${cppName}`];const getFn = reg[`get${cppName}`];const hasFn = reg[`has${cppName}`];const removeFn = reg[`remove${cppName}`];-if (typeof addFn !== 'function' || typeof getFn !== 'function' ||typeof hasFn !== 'function' || typeof removeFn !== 'function') {throw new Error(`C++ Registry missing methods for component "${cppName}". ` +- `Expected: add${cppName}, get${cppName}, has${cppName}, remove${cppName}`+ `Expected: add${cppName}, get${cppName}, has${cppName}, remove${cppName}`,);}-- methods = {- add: addFn.bind(reg),- get: getFn.bind(reg),- has: hasFn.bind(reg),- remove: removeFn.bind(reg),+ const methods: BuiltinMethods = {+ add: (addFn as (e: Entity, d: unknown) => void).bind(reg),+ get: (getFn as (e: Entity) => unknown).bind(reg),+ has: (hasFn as (e: Entity) => boolean).bind(reg),+ remove: (removeFn as (e: Entity) => void).bind(reg),};this.builtinMethodCache_.set(cppName, methods);return methods;diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex b1a65c1f8..ff5920b0f 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -7,7 +7,7 @@ import { Entity } from './types';import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getComponentRegistry, Name } from './component';import type { CppRegistry, ESEngineModule } from './wasm';import { handleWasmError } from './wasmError';-import { BuiltinBridge, convertFromWasm, convertForWasm, type BuiltinMethods } from './ecs/BuiltinBridge';+import { BuiltinBridge, convertFromWasm, convertForWasm, type BridgeConnectOptions, type BuiltinMethods } from './ecs/BuiltinBridge';import { ScriptStorage } from './ecs/ScriptStorage';import { NameIndex } from './ecs/NameIndex';import { ChangeTracker } from './ecs/ChangeTracker';@@ -81,8 +81,12 @@ export class World {return this.builtin_;}- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): void {- this.builtin_.connect(cppRegistry, module);+ connectCpp(+ cppRegistry: CppRegistry,+ module?: ESEngineModule,+ options?: BridgeConnectOptions,+ ): void {+ this.builtin_.connect(cppRegistry, module, options);}disconnectCpp(): void {diff --git a/sdk/tests/builtin-bridge.test.ts b/sdk/tests/builtin-bridge.test.tsnew file mode 100644index 000000000..ed2f90093--- /dev/null+++ b/sdk/tests/builtin-bridge.test.ts@@ -0,0 +1,117 @@+/**+ * @file builtin-bridge.test.ts+ * @brief Ensure BuiltinBridge eagerly verifies all component bindings at+ * connect time and surfaces drift between the C++ Registry and the+ * generated component metadata in one diagnostic.+ */+import { describe, expect, it } from 'vitest';+import { BuiltinBridge } from '../src/ecs/BuiltinBridge';+import { COMPONENT_META } from '../src/component.generated';+import type { CppRegistry } from '../src/wasm';++function stubMethod() { return undefined; }++/** Build a fake CppRegistry that satisfies COMPONENT_META. */+function makeCompleteRegistry(): Record<string, (...args: unknown[]) => unknown> {+ const reg: Record<string, (...args: unknown[]) => unknown> = {};+ for (const name of Object.keys(COMPONENT_META)) {+ for (const prefix of ['add', 'get', 'has', 'remove']) {+ reg[`${prefix}${name}`] = stubMethod;+ }+ }+ return reg;+}++describe('BuiltinBridge', () => {+ it('connects successfully in strict mode when every component has all four methods', () => {+ const bridge = new BuiltinBridge();+ const reg = makeCompleteRegistry() as unknown as CppRegistry;++ expect(() => { bridge.connect(reg, undefined, { strict: true }); }).not.toThrow();+ expect(bridge.hasCpp).toBe(true);+ expect(bridge.verify().ok).toBe(true);+ });++ it('throws an aggregated error in strict mode listing every missing method', () => {+ const bridge = new BuiltinBridge();+ const reg = makeCompleteRegistry();+ const firstName = Object.keys(COMPONENT_META)[0];+ const secondName = Object.keys(COMPONENT_META)[1];+ if (!firstName || !secondName) {+ throw new Error('COMPONENT_META fixture is empty — test cannot run');+ }++ delete reg[`add${firstName}`];+ delete reg[`remove${firstName}`];+ delete reg[`get${secondName}`];++ let caught: Error | null = null;+ try {+ bridge.connect(reg as unknown as CppRegistry, undefined, { strict: true });+ } catch (e) {+ caught = e as Error;+ }++ expect(caught).not.toBeNull();+ expect(caught!.message).toContain(firstName);+ expect(caught!.message).toContain(`add${firstName}`);+ expect(caught!.message).toContain(`remove${firstName}`);+ expect(caught!.message).toContain(secondName);+ expect(caught!.message).toContain(`get${secondName}`);+ expect(caught!.message).not.toContain(`has${firstName}`);+ });++ it('does not throw on missing bindings in non-strict mode (default)', () => {+ const bridge = new BuiltinBridge();+ const reg = makeCompleteRegistry();+ const firstName = Object.keys(COMPONENT_META)[0];+ if (!firstName) throw new Error('COMPONENT_META fixture is empty');+ delete reg[`add${firstName}`];++ expect(() => { bridge.connect(reg as unknown as CppRegistry); }).not.toThrow();+ expect(bridge.hasCpp).toBe(true);+ expect(bridge.verify().ok).toBe(false);+ });++ it('leaves the bridge disconnected after a failed strict connect', () => {+ const bridge = new BuiltinBridge();+ const reg = makeCompleteRegistry();+ const firstName = Object.keys(COMPONENT_META)[0];+ if (!firstName) throw new Error('COMPONENT_META fixture is empty');+ delete reg[`add${firstName}`];++ expect(() => { bridge.connect(reg as unknown as CppRegistry, undefined, { strict: true }); }).toThrow();+ expect(bridge.hasCpp).toBe(false);+ expect(bridge.getCppRegistry()).toBeNull();+ });++ it('resets cached state on disconnect', () => {+ const bridge = new BuiltinBridge();+ const reg = makeCompleteRegistry() as unknown as CppRegistry;+ bridge.connect(reg, undefined, { strict: true });++ bridge.disconnect();++ expect(bridge.hasCpp).toBe(false);+ expect(bridge.getCppRegistry()).toBeNull();+ expect(bridge.verify().ok).toBe(false);+ });++ it('caches bound methods so getBuiltinMethods returns the same handle', () => {+ const bridge = new BuiltinBridge();+ const reg = makeCompleteRegistry() as unknown as CppRegistry;+ bridge.connect(reg, undefined, { strict: true });++ const firstName = Object.keys(COMPONENT_META)[0];+ if (!firstName) throw new Error('COMPONENT_META fixture is empty');++ const m1 = bridge.getBuiltinMethods(firstName);+ const m2 = bridge.getBuiltinMethods(firstName);+ expect(m1).toBe(m2);+ });++ it('throws a descriptive error when getBuiltinMethods is called before connect', () => {+ const bridge = new BuiltinBridge();+ expect(() => bridge.getBuiltinMethods('Transform')).toThrow(/before connect/);+ });+});