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(sdk): unify WASM subsystem bridges behind WasmBridge (F2)
esengine921e20da50ac
diff --git a/sdk/src/CoreApiBridge.ts b/sdk/src/CoreApiBridge.tsnew file mode 100644index 000000000..33a409b0f--- /dev/null+++ b/sdk/src/CoreApiBridge.ts@@ -0,0 +1,25 @@+/**+ * @file CoreApiBridge.ts+ * @brief Bridge for the core engine module's API facets.+ *+ * @details The renderer / draw / material / geometry / postprocess / gl-debug+ * APIs are all facets of the SAME main engine module, each historically+ * holding its own `let module` singleton. They route through one shared+ * base ({@link WasmBridge}) via this class so every call inherits the+ * terminal-abort guard; the per-instance `label` keeps diagnostics+ * specific (e.g. `geometry.geometry_upload`). The main module is shared+ * with BuiltinBridge, so installing the abort guard is idempotent and+ * the dead flag is shared by module identity.+ */++import type { ESEngineModule } from './wasm';+import { WasmBridge } from './WasmBridge';++export class CoreApiBridge extends WasmBridge<ESEngineModule> {+ protected readonly label: string;++ constructor(label: string) {+ super();+ this.label = label;+ }+}diff --git a/sdk/src/WasmBridge.ts b/sdk/src/WasmBridge.tsnew file mode 100644index 000000000..086f6e990--- /dev/null+++ b/sdk/src/WasmBridge.ts@@ -0,0 +1,159 @@+/**+ * @file WasmBridge.ts+ * @brief Single base class for every SDK→WASM subsystem bridge.+ *+ * @details The SDK historically reached into the WASM module five different+ * ways (a class wrapper for ECS, six global-singleton init/shutdown+ * modules, and per-subsystem typed interfaces for physics/spine/+ * tilemap/timeline). Each reinvented its own loader, ready state,+ * missing-binding policy, and — critically — its own error handling,+ * so only the ECS bridge ({@link ./ecs/BuiltinBridge}) honoured the+ * terminal-abort guard. physics/spine/timeline called straight into a+ * possibly-dead module.+ *+ * `WasmBridge` is the single channel. A subsystem connects its module+ * here once; the base installs the abort guard (see moduleHealth.ts)+ * and hands back a guarded view of the module in which EVERY function+ * call short-circuits with {@link WasmModuleAborted} after an abort+ * instead of touching a corpse. Existing call sites are unchanged:+ * `bridge.module` has the same type as the raw module, so the guard is+ * transparent.+ *+ * The guarded view passes through, unguarded:+ * - non-function properties (HEAP* views, constants) — read live so+ * they stay valid across ALLOW_MEMORY_GROWTH heap replacement;+ * - `_malloc`/`_free` — allocator infrastructure that+ * {@link ./wasmScratch withScratch} must still be able to call in+ * its `finally` after an abort, so re-guarding them would mask the+ * original error.+ */++import {+ installAbortGuard,+ isModuleAborted,+ throwIfModuleAborted,+ WasmModuleAborted,+} from './moduleHealth';++/** Properties that must reach the raw module untouched (allocator infra). */+function isAllocatorProp(prop: PropertyKey): boolean {+ return prop === '_malloc' || prop === '_free';+}++/**+ * Base class for a subsystem's bridge to its WASM module.+ *+ * @typeParam M - the module's call-surface type (e.g. `PhysicsWasmModule`).+ *+ * Subclasses only declare a {@link label} for diagnostics:+ * ```ts+ * export class PhysicsBridge extends WasmBridge<PhysicsWasmModule> {+ * protected readonly label = 'physics';+ * }+ * ```+ */+export abstract class WasmBridge<M extends object> {+ /** Short subsystem name used in {@link WasmModuleAborted} diagnostics. */+ protected abstract readonly label: string;++ private raw_: M | null = null;+ private guarded_: M | null = null;+ /**+ * The module whose `onAbort`/dead-flag is authoritative. For a standalone+ * module (its own emscripten runtime, e.g. the shipped physics module) this+ * is the module itself. For a side module that shares the main module's+ * heap, pass the main module as `healthModule` — that is where emscripten+ * fires `onAbort` and where the dead flag must be read.+ */+ private health_: object | null = null;++ /**+ * Bind this bridge to a freshly-loaded module. Installs the terminal-abort+ * guard and builds the guarded view. Calling again rebinds to a new module.+ *+ * @param module the module call surface used by `bridge.module`.+ * @param healthModule the abort-authoritative module; defaults to `module`.+ */+ connect(module: M, healthModule: object = module): void {+ this.raw_ = module;+ this.health_ = healthModule;+ installAbortGuard(healthModule);+ this.guarded_ = this.makeGuarded_(module, healthModule);+ }++ /** Unbind. Subsequent `module` access throws until reconnected. */+ disconnect(): void {+ this.raw_ = null;+ this.guarded_ = null;+ this.health_ = null;+ }++ /** True once {@link connect} has run and before {@link disconnect}. */+ get connected(): boolean {+ return this.raw_ !== null;+ }++ /**+ * The guarded module. Every function call is gated through the abort guard;+ * HEAP views, constants, and `_malloc`/`_free` pass through to the live+ * module. Same static type as the raw module, so call sites are unchanged.+ *+ * @throws if the bridge is not connected.+ */+ get module(): M {+ if (!this.guarded_) {+ throw new Error(`${this.label} bridge is not connected to a WASM module`);+ }+ return this.guarded_;+ }++ /**+ * The unguarded module, or null if not connected. Prefer {@link module};+ * reach for `raw` only when the guard is provably unwanted (it almost never+ * is — `_malloc`/`_free` and HEAP views already pass through `module`).+ */+ get raw(): M | null {+ return this.raw_;+ }++ private makeGuarded_(module: M, health: object): M {+ const label = this.label;+ // One wrapper per accessed function, built lazily and reused, so the+ // steady-state cost is a proxy get + Map lookup rather than a fresh+ // closure per call.+ const wrappers = new Map<PropertyKey, (...args: unknown[]) => unknown>();++ return new Proxy(module, {+ get(target, prop): unknown {+ // Read with `target` as receiver so any getter (e.g. a side+ // module's HEAPF32 proxy getter) resolves against the module.+ const value = Reflect.get(target, prop, target);+ if (typeof value !== 'function' || isAllocatorProp(prop)) {+ return value;+ }+ let wrapped = wrappers.get(prop);+ if (!wrapped) {+ const fn = value as (...args: unknown[]) => unknown;+ const op = `${label}.${typeof prop === 'string' ? prop : String(prop)}`;+ wrapped = (...args: unknown[]): unknown => {+ // Pre-check: never enter a dead module.+ throwIfModuleAborted(health, op);+ try {+ return fn.apply(target, args);+ } catch (err) {+ // If THIS call aborted the module, surface it as the+ // terminal error rather than letting the corpse's+ // return value (undefined memory) propagate.+ if (isModuleAborted(health)) {+ throw new WasmModuleAborted(op, undefined, err);+ }+ throw err;+ }+ };+ wrappers.set(prop, wrapped);+ }+ return wrapped;+ },+ }) as M;+ }+}diff --git a/sdk/src/draw.ts b/sdk/src/draw.tsindex 857549bb5..278032f3e 100644--- a/sdk/src/draw.ts+++ b/sdk/src/draw.ts@@ -11,6 +11,7 @@ import type { GeometryHandle } from './geometry';import type { ShaderHandle, MaterialHandle } from './material';import { Material, isTextureRef, classifyUniformArity, type UniformValue, type TextureRef } from './material';import { BlendMode } from './blend';+import { CoreApiBridge } from './CoreApiBridge';import { handleWasmError } from './wasmError';import { log } from './logger';@@ -20,6 +21,7 @@ export { BlendMode } from './blend';// Internal State// =============================================================================+const bridge = new CoreApiBridge('draw');let module: ESEngineModule | null = null;let viewProjectionPtr: number = 0;let transformPtr: number = 0;@@ -33,7 +35,8 @@ const uniformBuffer = new Float32Array(UNIFORMS_BUFFER_SIZE);// =============================================================================export function initDrawAPI(wasmModule: ESEngineModule): void {- module = wasmModule;+ bridge.connect(wasmModule);+ module = bridge.module;viewProjectionPtr = module._malloc(16 * 4);transformPtr = module._malloc(16 * 4);uniformsPtr = module._malloc(UNIFORMS_BUFFER_SIZE * 4);@@ -54,6 +57,7 @@ export function shutdownDrawAPI(): void {uniformsPtr = 0;}}+ bridge.disconnect();module = null;}diff --git a/sdk/src/geometry.ts b/sdk/src/geometry.tsindex 5a4c386f6..e05247895 100644--- a/sdk/src/geometry.ts+++ b/sdk/src/geometry.ts@@ -6,6 +6,7 @@*/import type { ESEngineModule } from './wasm';+import { CoreApiBridge } from './CoreApiBridge';// =============================================================================// Types@@ -40,6 +41,7 @@ export interface GeometryOptions {// Internal State// =============================================================================+const bridge = new CoreApiBridge('geometry');let module: ESEngineModule | null = null;let vertexPtr: number = 0;let indexPtr: number = 0;@@ -54,7 +56,8 @@ const LAYOUT_BUFFER_SIZE = 64;// =============================================================================export function initGeometryAPI(wasmModule: ESEngineModule): void {- module = wasmModule;+ bridge.connect(wasmModule);+ module = bridge.module;vertexPtr = module._malloc(VERTEX_BUFFER_SIZE * 4);indexPtr = module._malloc(INDEX_BUFFER_SIZE * 4);layoutPtr = module._malloc(LAYOUT_BUFFER_SIZE * 4);@@ -69,6 +72,7 @@ export function shutdownGeometryAPI(): void {indexPtr = 0;layoutPtr = 0;}+ bridge.disconnect();module = null;}diff --git a/sdk/src/glDebug.ts b/sdk/src/glDebug.tsindex 01970371c..a98c19da8 100644--- a/sdk/src/glDebug.ts+++ b/sdk/src/glDebug.ts@@ -4,14 +4,18 @@*/import type { ESEngineModule } from './wasm';+import { CoreApiBridge } from './CoreApiBridge';+const bridge = new CoreApiBridge('glDebug');let module: ESEngineModule | null = null;export function initGLDebugAPI(wasmModule: ESEngineModule): void {- module = wasmModule;+ bridge.connect(wasmModule);+ module = bridge.module;}export function shutdownGLDebugAPI(): void {+ bridge.disconnect();module = null;}diff --git a/sdk/src/material.ts b/sdk/src/material.tsindex 9a980e82e..76a34958b 100644--- a/sdk/src/material.ts+++ b/sdk/src/material.ts@@ -5,6 +5,7 @@*/import type { ESEngineModule } from './wasm';+import { CoreApiBridge } from './CoreApiBridge';import { requireResourceManager } from './resourceManager';import type { Vec2, Vec3, Vec4 } from './types';import { BlendMode } from './blend';@@ -95,6 +96,7 @@ export interface MaterialData {// Internal State// =============================================================================+const bridge = new CoreApiBridge('material');let module: ESEngineModule | null = null;let nextMaterialId = 1;const materials = new Map<MaterialHandle, MaterialData>();@@ -104,7 +106,8 @@ const materials = new Map<MaterialHandle, MaterialData>();// =============================================================================export function initMaterialAPI(wasmModule: ESEngineModule): void {- module = wasmModule;+ bridge.connect(wasmModule);+ module = bridge.module;registerMaterialCallback();}@@ -118,6 +121,7 @@ export function shutdownMaterialAPI(): void {materialCallbackRegistered = false;encodedNameCache.clear();encoder = null;+ bridge.disconnect();module = null;}diff --git a/sdk/src/physics/PhysicsBridge.ts b/sdk/src/physics/PhysicsBridge.tsnew file mode 100644index 000000000..c0e60cb4c--- /dev/null+++ b/sdk/src/physics/PhysicsBridge.ts@@ -0,0 +1,17 @@+/**+ * @file PhysicsBridge.ts+ * @brief Physics subsystem's bridge to its WASM module.+ *+ * @details The physics module is loaded standalone (its own emscripten runtime+ * with its own `onAbort`), so the bridge's health module is the module+ * itself. All `_physics_*` calls made through `bridge.module` inherit+ * the terminal-abort guard for free — closing the gap where physics+ * previously called straight into a possibly-dead module.+ */++import { WasmBridge } from '../WasmBridge';+import type { PhysicsWasmModule } from './PhysicsModuleLoader';++export class PhysicsBridge extends WasmBridge<PhysicsWasmModule> {+ protected readonly label = 'physics';+}diff --git a/sdk/src/physics/PhysicsPlugin.ts b/sdk/src/physics/PhysicsPlugin.tsindex c7b7d9a75..5a223bfc5 100644--- a/sdk/src/physics/PhysicsPlugin.ts+++ b/sdk/src/physics/PhysicsPlugin.ts@@ -16,6 +16,7 @@ import {type PhysicsModuleFactory,} from './PhysicsModuleLoader';import { setupPhysicsDebugDraw } from './PhysicsDebugDraw';+import { PhysicsBridge } from './PhysicsBridge';import { PhysicsRuntime } from './PhysicsRuntime';import { Physics, PhysicsAPI } from './Physics';import { registerPhysicsSystem } from './PhysicsSystem';@@ -68,6 +69,7 @@ export class PhysicsPlugin implements Plugin {private config_: ResolvedPhysicsConfig;private wasmUrl_: string;private factory_?: PhysicsModuleFactory;+ private bridge_ = new PhysicsBridge();constructor(wasmUrl: string, config: PhysicsPluginConfig = {}, factory?: PhysicsModuleFactory) {this.wasmUrl_ = wasmUrl;@@ -85,7 +87,16 @@ export class PhysicsPlugin implements Plugin {app.insertResource(PhysicsRuntime, { module: null, initPromise: null });const initPromise = loadPhysicsModule(this.wasmUrl_, this.factory_).then(- (module: PhysicsWasmModule) => {+ (loaded: PhysicsWasmModule) => {+ // Route the module through the single WASM bridge: this installs+ // the terminal-abort guard and yields a guarded view in which+ // every `_physics_*` call short-circuits after an abort. The+ // guarded module has the same type, so every downstream call+ // site (PhysicsSystem closures, the Physics API wrapper) gains+ // abort safety without changing a single call.+ this.bridge_.connect(loaded);+ const module = this.bridge_.module;+module._physics_init(this.config_.gravity.x,this.config_.gravity.y,diff --git a/sdk/src/postprocess/PostProcessAPI.ts b/sdk/src/postprocess/PostProcessAPI.tsindex 5b86a2cd9..c12de6809 100644--- a/sdk/src/postprocess/PostProcessAPI.ts+++ b/sdk/src/postprocess/PostProcessAPI.ts@@ -3,13 +3,16 @@ import type { Entity } from '../types';import type { ShaderHandle } from '../material';import { Material } from '../material';import { handleWasmError } from '../wasmError';+import { CoreApiBridge } from '../CoreApiBridge';import { PostProcessStack, getCameraBindings, getStacks } from './PostProcessStack';import { POSTPROCESS_VERTEX } from './shaders';+const bridge = new CoreApiBridge('postprocess');let module: ESEngineModule | null = null;export function initPostProcessAPI(wasmModule: ESEngineModule): void {- module = wasmModule;+ bridge.connect(wasmModule);+ module = bridge.module;}export function shutdownPostProcessAPI(): void {@@ -21,6 +24,7 @@ export function shutdownPostProcessAPI(): void {if (module && PostProcess.isInitialized()) {PostProcess.shutdown();}+ bridge.disconnect();module = null;}diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.tsindex 89725f1d3..9a98e7563 100644--- a/sdk/src/renderer.ts+++ b/sdk/src/renderer.ts@@ -1,4 +1,5 @@import type { ESEngineModule, CppRegistry } from './wasm';+import { CoreApiBridge } from './CoreApiBridge';import { handleWasmError } from './wasmError';import { requireResourceManager } from './resourceManager';import { decodeFrameCapture, replayToDrawCall as replayToDrawCallImpl, getSnapshotImageData as getSnapshotImpl, type FrameCaptureData } from './frameCapture';@@ -28,11 +29,13 @@ export interface RenderStats {culled: number;}+const bridge = new CoreApiBridge('renderer');let module: ESEngineModule | null = null;let viewProjectionPtr: number = 0;export function initRendererAPI(wasmModule: ESEngineModule): void {- module = wasmModule;+ bridge.connect(wasmModule);+ module = bridge.module;viewProjectionPtr = module._malloc(16 * 4);}@@ -41,6 +44,7 @@ export function shutdownRendererAPI(): void {module._free(viewProjectionPtr);viewProjectionPtr = 0;}+ bridge.disconnect();module = null;}diff --git a/sdk/src/spine/SpineBridge.ts b/sdk/src/spine/SpineBridge.tsnew file mode 100644index 000000000..ce98386c6--- /dev/null+++ b/sdk/src/spine/SpineBridge.ts@@ -0,0 +1,33 @@+/**+ * @file SpineBridge.ts+ * @brief Spine's bridges to its two WASM surfaces.+ *+ * @details Spine spans two runtimes (see SpineManager): the built-in `spine_*`+ * exports on the MAIN engine module, and version-specific standalone+ * side modules (3.8 / 4.1) each with their own runtime. Both surfaces+ * route through {@link WasmBridge} so every call inherits the+ * terminal-abort guard.+ */++import type { ESEngineModule } from '../wasm';+import { WasmBridge } from '../WasmBridge';+import type { SpineWrappedAPI } from './SpineModuleLoader';++/**+ * Guards the built-in `spine_*` exports on the main engine module. The main+ * module is shared with {@link ../ecs/BuiltinBridge BuiltinBridge}; installing+ * the abort guard twice is idempotent and the dead flag is shared by module+ * identity, so an abort anywhere short-circuits everywhere.+ */+export class SpineCoreBridge extends WasmBridge<ESEngineModule> {+ protected readonly label = 'spine';+}++/**+ * Guards a version-specific spine side module's wrapped API. The call surface+ * (`SpineWrappedAPI`, all functions) is guarded; its abort-authoritative module+ * is the raw side module, which owns the heap, allocator, and `onAbort`.+ */+export class SpineModuleBridge extends WasmBridge<SpineWrappedAPI> {+ protected readonly label = 'spine';+}diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.tsindex 8c8dc64d2..d49f39d62 100644--- a/sdk/src/spine/SpineController.ts+++ b/sdk/src/spine/SpineController.ts@@ -5,6 +5,7 @@import type { Entity, Vec2 } from '../types';import type { SpineWasmModule, SpineWrappedAPI } from './SpineModuleLoader';+import { SpineModuleBridge } from './SpineBridge';import { log } from '../logger';import { withMalloc, withScratch } from '../wasmScratch';@@ -59,11 +60,17 @@ export interface SpineEvent {export class SpineModuleController {private raw_: SpineWasmModule;private api_: SpineWrappedAPI;+ private bridge_ = new SpineModuleBridge();private listeners_: Map<Entity, Map<SpineEventType, Set<SpineEventCallback>>>;constructor(raw: SpineWasmModule, api: SpineWrappedAPI) {this.raw_ = raw;- this.api_ = api;+ // Guard the API call surface; the raw side module is the abort authority+ // (it owns onAbort + the heap). Every `this.api_.*` call below is now+ // abort-safe with no per-call change; `this.raw_` stays raw for the heap+ // reads and withScratch allocations that must run even after an abort.+ this.bridge_.connect(api, raw);+ this.api_ = this.bridge_.module;this.listeners_ = new Map();}diff --git a/sdk/src/spine/SpineCppAPI.ts b/sdk/src/spine/SpineCppAPI.tsindex 9bd19b6b6..ef4a0a83b 100644--- a/sdk/src/spine/SpineCppAPI.ts+++ b/sdk/src/spine/SpineCppAPI.ts@@ -1,13 +1,22 @@import type { ESEngineModule, CppRegistry } from '../wasm';import type { Entity } from '../types';+import { SpineCoreBridge } from './SpineBridge';+const bridge = new SpineCoreBridge();let module: ESEngineModule | null = null;export function initSpineCppAPI(wasmModule: ESEngineModule): void {- module = wasmModule;+ // Route through the single WASM bridge: every `spine_*` call below then+ // short-circuits with WasmModuleAborted after an abort instead of touching+ // a dead module. The optional-chaining call sites are unchanged — a missing+ // binding still resolves to undefined (handled by `?? fallback`); only a+ // post-abort call throws.+ bridge.connect(wasmModule);+ module = bridge.module;}export function shutdownSpineCppAPI(): void {+ bridge.disconnect();module = null;}diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.tsindex d869a32e7..ded4073b3 100644--- a/sdk/src/tilemap/tilemapAPI.ts+++ b/sdk/src/tilemap/tilemapAPI.ts@@ -1,5 +1,6 @@import type { ESEngineModule } from '../wasm';import { withMalloc } from '../wasmScratch';+import { CoreApiBridge } from '../CoreApiBridge';interface TilemapModule {tilemap_initLayer(entity: number, width: number, height: number,@@ -99,13 +100,16 @@ interface TilemapModule {_free(ptr: number): void;}+const bridge = new CoreApiBridge('tilemap');let module_: TilemapModule | null = null;export function initTilemapAPI(m: ESEngineModule): void {- module_ = m as unknown as TilemapModule;+ bridge.connect(m);+ module_ = bridge.module as unknown as TilemapModule;}export function shutdownTilemapAPI(): void {+ bridge.disconnect();module_ = null;}diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.tsindex 451557358..e7ec664a9 100644--- a/sdk/src/timeline/TimelinePlugin.ts+++ b/sdk/src/timeline/TimelinePlugin.ts@@ -14,6 +14,7 @@ import {advanceAndProcess,} from './TimelineRuntime';import type { ESEngineModule } from '../wasm';+import { CoreApiBridge } from '../CoreApiBridge';import type { Entity } from '../types';export { setNestedProperty } from './TimelineRuntime';@@ -70,6 +71,7 @@ export class TimelinePlugin implements Plugin {private textureHandles_ = new Map<string, Map<string, number>>();private handles_ = new Map<number, UploadResult>();private animFramesStates_ = new Map<number, AnimFramesState>();+ private bridge_ = new CoreApiBridge('timeline');registerAsset(path: string, asset: TimelineAsset): void {this.loadedAssets_.set(path, asset);@@ -100,8 +102,15 @@ export class TimelinePlugin implements Plugin {app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time)],(time: TimeData) => {- const module = world.getWasmModule() as ESEngineModule;- if (!module) return;+ const rawModule = world.getWasmModule() as ESEngineModule;+ if (!rawModule) return;+ // Route the main module through the bridge once (re-connect only+ // if the underlying module changes). Every `_tl_*` call below —+ // and everything handed `module` (TimelineControl via+ // setTimelineModule, the uploader, the runtime) — then inherits+ // the terminal-abort guard.+ if (this.bridge_.raw !== rawModule) this.bridge_.connect(rawModule);+ const module = this.bridge_.module;setTimelineModule(module);const registry = world.getCppRegistry() as any;diff --git a/sdk/src/ui/uiHelpers.ts b/sdk/src/ui/uiHelpers.tsindex 5f5fdb962..9ee5c8801 100644--- a/sdk/src/ui/uiHelpers.ts+++ b/sdk/src/ui/uiHelpers.ts@@ -1,3 +1,4 @@+import { CoreApiBridge } from '../CoreApiBridge';import { Sprite, Parent, Transform } from '../component';import type { ParentData, SpriteData, TransformData, AnyComponentDef } from '../component';import { Image } from './core/image';@@ -80,11 +81,13 @@ export function computeUIRectLayout(};}+const bridge = new CoreApiBridge('uiHelpers');let module_: ESEngineModule | null = null;let nativeRegistry_: CppRegistry | null = null;export function initUIHelpers(module: ESEngineModule, registry: CppRegistry): void {- module_ = module;+ bridge.connect(module);+ module_ = bridge.module;nativeRegistry_ = registry;}diff --git a/sdk/tests/core-bridge.test.ts b/sdk/tests/core-bridge.test.tsnew file mode 100644index 000000000..487bbbeb7--- /dev/null+++ b/sdk/tests/core-bridge.test.ts@@ -0,0 +1,67 @@+/**+ * @file core-bridge.test.ts+ * @brief F2 core batch: the six core engine-module API facets (renderer /+ * draw / material / geometry / postprocess / gl-debug) route through+ * one shared CoreApiBridge, so each inherits the terminal-abort guard.+ * Verified directly on CoreApiBridge and end-to-end via GLDebug.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { WasmModuleAborted } from '../src/moduleHealth';+import { CoreApiBridge } from '../src/CoreApiBridge';+import { GLDebug, initGLDebugAPI, shutdownGLDebugAPI } from '../src/glDebug';+import type { ESEngineModule } from '../src/wasm';++describe('CoreApiBridge', () => {+ it('carries the per-instance label into abort diagnostics', () => {+ const bridge = new CoreApiBridge('geometry');+ const m = {+ geometry_upload: () => 0,+ onAbort: undefined as ((w: unknown) => void) | undefined,+ _malloc: () => 0,+ _free: () => {},+ } as unknown as ESEngineModule;+ bridge.connect(m);++ (m as unknown as { onAbort: (w: unknown) => void }).onAbort('oom');+ let caught: unknown;+ try { (bridge.module as unknown as { geometry_upload: () => void }).geometry_upload(); }+ catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('geometry.geometry_upload');+ });+});++describe('GLDebug (core facet end-to-end)', () => {+ afterEach(() => shutdownGLDebugAPI());++ function makeModule(): ESEngineModule {+ return {+ gl_checkErrors: (_ctx: string) => 7,+ gl_enableErrorCheck: vi.fn(),+ renderer_diagnose: vi.fn(),+ onAbort: undefined,+ } as unknown as ESEngineModule;+ }++ it('routes calls through the guard when healthy', () => {+ initGLDebugAPI(makeModule());+ expect(GLDebug.check('frame')).toBe(7);+ });++ it('refuses calls after the module aborts', () => {+ const m = makeModule();+ initGLDebugAPI(m);+ (m as unknown as { onAbort: (w: unknown) => void }).onAbort('unreachable');++ let caught: unknown;+ try { GLDebug.check('frame'); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('glDebug.gl_checkErrors');+ });++ it('falls back to 0 once disconnected', () => {+ initGLDebugAPI(makeModule());+ shutdownGLDebugAPI();+ expect(GLDebug.check('frame')).toBe(0);+ });+});diff --git a/sdk/tests/spine-bridge.test.ts b/sdk/tests/spine-bridge.test.tsnew file mode 100644index 000000000..6233781c3--- /dev/null+++ b/sdk/tests/spine-bridge.test.ts@@ -0,0 +1,120 @@+/**+ * @file spine-bridge.test.ts+ * @brief F2 spine migration: both spine WASM surfaces (the main-module+ * `spine_*` exports behind SpineCpp, and a side module's wrapped API+ * behind SpineModuleController) inherit the terminal-abort guard with+ * no change to their call sites.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { WasmModuleAborted } from '../src/moduleHealth';+import {+ SpineCpp, initSpineCppAPI, shutdownSpineCppAPI,+} from '../src/spine/SpineCppAPI';+import { SpineModuleController } from '../src/spine/SpineController';+import type { ESEngineModule } from '../src/wasm';+import type { SpineWasmModule, SpineWrappedAPI } from '../src/spine/SpineModuleLoader';++// ---------------------------------------------------------------------------+// Surface 1: SpineCpp over the main engine module's spine_* exports.+// ---------------------------------------------------------------------------+function makeMainModule(over: Record<string, unknown> = {}): ESEngineModule {+ return {+ spine_play: (_e: number, _a: string, _l: boolean, _t: number) => true,+ spine_setSkin: (_e: number, _s: string) => true,+ onAbort: undefined,+ ...over,+ } as unknown as ESEngineModule;+}++describe('SpineCpp (main-module surface)', () => {+ afterEach(() => shutdownSpineCppAPI());++ it('calls spine_* through the guard when healthy', () => {+ initSpineCppAPI(makeMainModule());+ expect(SpineCpp.play(0 as never, 'walk')).toBe(true);+ });++ it('refuses spine_* calls after the module aborts', () => {+ const m = makeMainModule();+ initSpineCppAPI(m);+ (m as unknown as { onAbort: (w: unknown) => void }).onAbort('unreachable');++ let caught: unknown;+ try { SpineCpp.play(0 as never, 'walk'); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('spine.spine_play');+ });++ it('keeps missing-binding tolerance (absent export → fallback, not throw)', () => {+ // Module without spine_setSkin: optional chaining still yields the+ // `?? false` fallback rather than throwing.+ initSpineCppAPI(makeMainModule({ spine_setSkin: undefined }));+ expect(SpineCpp.setSkin(0 as never, 'armor')).toBe(false);+ });++ it('returns fallbacks once disconnected', () => {+ initSpineCppAPI(makeMainModule());+ shutdownSpineCppAPI();+ expect(SpineCpp.play(0 as never, 'walk')).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// Surface 2: SpineModuleController over a side module (api surface + raw heap).+// ---------------------------------------------------------------------------+function makeRaw(): SpineWasmModule {+ return {+ HEAPF32: new Float32Array(64),+ HEAPU8: new Uint8Array(256),+ HEAPU32: new Uint32Array(64),+ _malloc: () => 16, // non-zero ptr so withScratch tracks/frees it+ _free: vi.fn(),+ onAbort: undefined,+ cwrap: () => () => 0,+ UTF8ToString: () => '',+ stringToNewUTF8: () => 0,+ } as unknown as SpineWasmModule;+}++function makeApi(): SpineWrappedAPI {+ return {+ playAnimation: vi.fn(() => 1),+ getBounds: vi.fn(),+ } as unknown as SpineWrappedAPI;+}++describe('SpineModuleController (side-module surface)', () => {+ it('routes api calls through the guard when healthy', () => {+ const api = makeApi();+ const c = new SpineModuleController(makeRaw(), api);+ expect(c.play(0, 'walk')).toBe(true);+ expect(api.playAnimation).toHaveBeenCalledOnce();+ });++ it('refuses api calls after the side module aborts', () => {+ const raw = makeRaw();+ const api = makeApi();+ const c = new SpineModuleController(raw, api);++ (raw as unknown as { onAbort: (w: unknown) => void }).onAbort('oom');++ let caught: unknown;+ try { c.play(0, 'walk'); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('spine.playAnimation');+ // the dead module was never actually called+ expect(api.playAnimation).not.toHaveBeenCalled();+ });++ it('frees scratch through the raw allocator even when a guarded call aborts', () => {+ const raw = makeRaw();+ const c = new SpineModuleController(raw, makeApi());+ (raw as unknown as { onAbort: (w: unknown) => void }).onAbort('oom');++ // getBounds allocates via raw._malloc then calls api.getBounds (guarded,+ // now throwing): the withMalloc finally must still free.+ expect(() => c.getBounds(0)).toThrow(WasmModuleAborted);+ expect((raw as unknown as { _free: ReturnType<typeof vi.fn> })._free)+ .toHaveBeenCalledWith(16);+ });+});diff --git a/sdk/tests/timeline-tilemap-ui-bridge.test.ts b/sdk/tests/timeline-tilemap-ui-bridge.test.tsnew file mode 100644index 000000000..77cebebf1--- /dev/null+++ b/sdk/tests/timeline-tilemap-ui-bridge.test.ts@@ -0,0 +1,121 @@+/**+ * @file timeline-tilemap-ui-bridge.test.ts+ * @brief F2 final batch: tilemap, timeline, and uiHelpers route their WASM+ * access through the shared CoreApiBridge, so every tilemap_* / _tl_* /+ * ui_* call inherits the terminal-abort guard. With these three, all+ * five historical bridge patterns are unified behind WasmBridge.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { WasmModuleAborted } from '../src/moduleHealth';+import { CoreApiBridge } from '../src/CoreApiBridge';+import { TilemapAPI, initTilemapAPI, shutdownTilemapAPI } from '../src/tilemap/tilemapAPI';+import { initUIHelpers, setUIRectSizeNative } from '../src/ui/uiHelpers';+import {+ TimelineControl, setTimelineModule, setTimelineHandle,+} from '../src/timeline/TimelineControl';+import type { ESEngineModule, CppRegistry } from '../src/wasm';+import type { Entity } from '../src/types';++function abort(m: object, reason = 'oom'): void {+ (m as { onAbort: (w: unknown) => void }).onAbort(reason);+}++// ---------------------------------------------------------------------------+// tilemap — init-seam routing (module_ becomes the guarded proxy)+// ---------------------------------------------------------------------------+describe('tilemap bridge', () => {+ afterEach(() => shutdownTilemapAPI());++ function makeModule(): ESEngineModule {+ return {+ tilemap_getTile: (_e: number, _x: number, _y: number) => 5,+ tilemap_setVisible: vi.fn(),+ onAbort: undefined,+ _malloc: () => 16,+ _free: vi.fn(),+ HEAPU8: new Uint8Array(64),+ } as unknown as ESEngineModule;+ }++ it('routes tilemap_* through the guard when healthy', () => {+ initTilemapAPI(makeModule());+ expect(TilemapAPI.getTile(0, 0, 0)).toBe(5);+ });++ it('refuses tilemap_* after an abort', () => {+ const m = makeModule();+ initTilemapAPI(m);+ abort(m);+ let caught: unknown;+ try { TilemapAPI.getTile(0, 0, 0); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('tilemap.tilemap_getTile');+ });++ it('falls back once disconnected', () => {+ initTilemapAPI(makeModule());+ shutdownTilemapAPI();+ expect(TilemapAPI.getTile(0, 0, 0)).toBe(0);+ });+});++// ---------------------------------------------------------------------------+// uiHelpers — init-seam routing (module_ guarded; registry untouched)+// ---------------------------------------------------------------------------+describe('uiHelpers bridge', () => {+ function makeModule(): ESEngineModule {+ return {+ setUIRectSize: vi.fn(),+ onAbort: undefined,+ } as unknown as ESEngineModule;+ }+ const registry = {} as unknown as CppRegistry;++ it('routes ui calls through the guard when healthy', () => {+ const m = makeModule();+ initUIHelpers(m, registry);+ setUIRectSizeNative(1 as unknown as Entity, 10, 20);+ expect((m as unknown as { setUIRectSize: ReturnType<typeof vi.fn> }).setUIRectSize)+ .toHaveBeenCalledWith(registry, 1, 10, 20);+ });++ it('refuses ui calls after an abort', () => {+ const m = makeModule();+ initUIHelpers(m, registry);+ abort(m);+ let caught: unknown;+ try { setUIRectSizeNative(1 as unknown as Entity, 10, 20); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('uiHelpers.setUIRectSize');+ });+});++// ---------------------------------------------------------------------------+// timeline — the plugin feeds TimelineControl a guarded module; verify the+// control path honours it (the plugin wiring that produces the guarded module+// is covered by typecheck).+// ---------------------------------------------------------------------------+describe('timeline bridge (control path)', () => {+ function makeModule(): ESEngineModule {+ return {+ _tl_play: vi.fn(),+ _tl_isPlaying: () => 1,+ onAbort: undefined,+ } as unknown as ESEngineModule;+ }++ it('honours the guarded module: short-circuits _tl_* after an abort', () => {+ const raw = makeModule();+ const bridge = new CoreApiBridge('timeline');+ bridge.connect(raw);+ setTimelineModule(bridge.module); // exactly what TimelinePlugin does+ setTimelineHandle(7 as unknown as Entity, 100);++ TimelineControl.play(7 as unknown as Entity);+ expect((raw as unknown as { _tl_play: ReturnType<typeof vi.fn> })._tl_play)+ .toHaveBeenCalledWith(100);++ abort(raw);+ expect(() => TimelineControl.play(7 as unknown as Entity)).toThrow(WasmModuleAborted);+ });+});diff --git a/sdk/tests/wasm-bridge.test.ts b/sdk/tests/wasm-bridge.test.tsnew file mode 100644index 000000000..413447b07--- /dev/null+++ b/sdk/tests/wasm-bridge.test.ts@@ -0,0 +1,182 @@+/**+ * @file wasm-bridge.test.ts+ * @brief The single SDK→WASM bridge base class: it installs the terminal-abort+ * guard once and hands back a guarded module view in which every+ * function call refuses to touch a dead module — while HEAP views and+ * the allocator pass straight through.+ */+import { describe, it, expect, vi } from 'vitest';+import { WasmBridge } from '../src/WasmBridge';+import { WasmModuleAborted, isModuleAborted } from '../src/moduleHealth';+import { withMalloc } from '../src/wasmScratch';+import { PhysicsBridge } from '../src/physics/PhysicsBridge';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';++// ---------------------------------------------------------------------------+// A tiny module that looks like an emscripten module: some callable exports,+// HEAP views, an allocator, and an emscripten-style onAbort hook.+// ---------------------------------------------------------------------------+interface TestModule {+ add(a: number, b: number): number;+ boom(): number;+ HEAPF32: Float32Array;+ freed: number[];+ onAbort?: (what: unknown) => void;+ _malloc(size: number): number;+ _free(ptr: number): void;+}++function makeModule(): TestModule {+ const heap = new Float32Array(16);+ const m: TestModule = {+ add: (a, b) => a + b,+ // Aborts mid-call (flips the dead flag via onAbort), then throws raw.+ boom() {+ this.onAbort?.('memory access out of bounds');+ throw new Error('raw failure');+ },+ HEAPF32: heap,+ freed: [],+ _malloc: (size: number) => size, // pretend ptr === size+ _free(ptr: number) { this.freed.push(ptr); },+ };+ return m;+}++class TestBridge extends WasmBridge<TestModule> {+ protected readonly label = 'test';+}++describe('WasmBridge base', () => {+ it('throws on module access before connect', () => {+ const b = new TestBridge();+ expect(b.connected).toBe(false);+ expect(() => b.module).toThrow(/not connected/);+ expect(b.raw).toBeNull();+ });++ it('passes healthy function calls straight through', () => {+ const b = new TestBridge();+ b.connect(makeModule());+ expect(b.connected).toBe(true);+ expect(b.module.add(2, 3)).toBe(5);+ });++ it('installs the abort guard on connect', () => {+ const b = new TestBridge();+ const m = makeModule();+ b.connect(m);+ expect(isModuleAborted(m)).toBe(false);+ m.onAbort!('OOM');+ expect(isModuleAborted(m)).toBe(true);+ });++ it('short-circuits guarded calls after an abort (pre-check)', () => {+ const b = new TestBridge();+ const m = makeModule();+ b.connect(m);+ m.onAbort!('OOM');++ let caught: unknown;+ try { b.module.add(1, 2); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('test.add');+ });++ it('surfaces an abort that happens DURING a call as WasmModuleAborted', () => {+ const b = new TestBridge();+ b.connect(makeModule());++ let caught: unknown;+ try { b.module.boom(); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ // original raw error is preserved as the cause+ expect((caught as { cause?: Error }).cause).toBeInstanceOf(Error);+ expect(((caught as { cause?: Error }).cause as Error).message).toBe('raw failure');+ });++ it('passes HEAP views through live (re-read each access)', () => {+ const b = new TestBridge();+ const m = makeModule();+ b.connect(m);+ b.module.HEAPF32[0] = 42;+ expect(m.HEAPF32[0]).toBe(42);++ // Emulate ALLOW_MEMORY_GROWTH replacing the heap: the guarded view must+ // see the new array, not a cached one.+ const grown = new Float32Array(32);+ grown[0] = 7;+ m.HEAPF32 = grown;+ expect(b.module.HEAPF32[0]).toBe(7);+ });++ it('leaves _malloc/_free unguarded so withScratch can free after an abort', () => {+ const b = new TestBridge();+ const m = makeModule();+ b.connect(m);++ // A scratch whose body aborts the module: the op throws, but the+ // finally still frees through the unguarded allocator.+ expect(() => withMalloc(b.module, 8, () => {+ b.module.boom();+ })).toThrow(WasmModuleAborted);+ expect(m.freed).toEqual([8]); // freed despite the abort+ });++ it('disconnect unbinds the module', () => {+ const b = new TestBridge();+ b.connect(makeModule());+ b.disconnect();+ expect(b.connected).toBe(false);+ expect(() => b.module).toThrow(/not connected/);+ });+});++// ---------------------------------------------------------------------------+// Physics sample: the first subsystem migrated onto the bridge. A minimal fake+// physics module verifies that `_physics_*` calls inherit the abort guard with+// zero changes to the ~60 existing call sites.+// ---------------------------------------------------------------------------+function makePhysicsModule(): PhysicsWasmModule {+ const heap = new Float32Array(16);+ const fake = {+ steps: 0,+ _physics_step(_dt: number) { (this as { steps: number }).steps++; },+ _physics_getGravity: () => 0,+ HEAPF32: heap,+ HEAPU8: new Uint8Array(64),+ HEAPU32: new Uint32Array(16),+ _malloc: (size: number) => size,+ _free: vi.fn(),+ onAbort: undefined as ((what: unknown) => void) | undefined,+ };+ return fake as unknown as PhysicsWasmModule;+}++describe('PhysicsBridge (F2 sample)', () => {+ it('routes _physics_* calls through the guard', () => {+ const bridge = new PhysicsBridge();+ const m = makePhysicsModule();+ bridge.connect(m);++ bridge.module._physics_step(1 / 60);+ bridge.module._physics_step(1 / 60);+ expect((m as unknown as { steps: number }).steps).toBe(2);+ });++ it('refuses _physics_* calls after the physics module aborts', () => {+ const bridge = new PhysicsBridge();+ const m = makePhysicsModule();+ bridge.connect(m);++ // Emscripten fires onAbort on the standalone physics module.+ (m as unknown as { onAbort: (w: unknown) => void }).onAbort('unreachable');++ let caught: unknown;+ try { bridge.module._physics_step(1 / 60); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect((caught as WasmModuleAborted).context).toBe('physics._physics_step');+ // the dead module was NOT stepped again+ expect((m as unknown as { steps: number }).steps).toBe(0);+ });+});