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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file cpp-contract.test.ts
* @brief Handshake guard for the hand-written TS constants/enums that MUST
* stay byte-identical with a C++ definition across the WASM boundary.
*
* These cross-language contracts (tween wire enums, the particle color-LUT size,
* the packed-Entity bit split, the tilemap cell encoding, the UI base layer) live
* outside EHT's parsed component directory, so EHT does not generate them — they
* are hand-copied with a "MUST match C++" comment and, until now, NO guard. A
* silent drift here corrupts data at the boundary (mis-decoded entity handles,
* wrong LUT stride, mis-rendered tiles) with no compile error.
*
* This test IS the guard: it parses the real C++ headers and asserts the shipping
* TS values match. Add a value on one side and forget the other -> RED here, with
* a message pointing at the drift. It is the test-time equivalent of the ABI-hash
* handshake EHT already enforces for components.
*/
import { describe, it, expect } from 'vitest';
import { readFileSync, existsSync, readdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { EasingType } from '../src/animation/Easing';
import { TweenState, LoopMode } from '../src/animation/TweenTypes';
import { TweenTarget } from '../src/animation/Tween';
import { GRADIENT_LUT_SIZE } from '../src/particle/gradient';
import { ENTITY_INDEX_BITS, ENTITY_GEN_BITS } from '../src/types';
import { TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D } from '../src/tilemap/tileBits';
import { CHUNK_SIZE } from '../src/tilemap/chunkCodec';
import { UI_BASE_LAYER } from '../src/wasm/constants.generated';
// EHT-generated twins (the authoritative C++ ES_ENUM values) + the module-local
// names the UI/physics modules publish them under.
import * as gen from '../src/wasm/wasm.generated';
import { BodyType } from '../src/physics/PhysicsComponents';
import { UIPositionType, AlignSelf } from '../src/ui/core/ui-node';
import { UIVisualType, FillMethod, FillOrigin } from '../src/ui/core/ui-visual';
import { MaskMode } from '../src/ui/core/ui-mask';
import { SpriteMaskInteraction, SpriteDrawMode } from '../src/ecs/component';
import { ScrollMovement } from '../src/ui/core/ui-scroll';
import { TilemapOrientation } from '../src/tilemap/tileGeometry';
import { TextAlign } from '../src/ui/core/text';
import {
FlexDirection, FlexWrap, JustifyContent, AlignItems, AlignContent,
} from '../src/ui/layout/flex';
import { ParticleEasing } from '../src/ecs/component';
// Repo root is two levels up from sdk/tests/ (mirrors the spine integration tests).
const CPP = resolve(__dirname, '../../src/esengine');
const readCpp = (rel: string): string => {
const p = resolve(CPP, rel);
// Fail loud (not skip) if the source moved — a silently-disabled guard is
// worse than no guard.
if (!existsSync(p)) throw new Error(`C++ contract source missing: ${p}`);
return readFileSync(p, 'utf8');
};
/** Strip C/C++ comments so they can't be mistaken for enum entries or values. */
function stripComments(src: string): string {
return src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
}
/**
* Parse a `enum class Name : type { ... }` body into ordered {name, value},
* resolving implicit increments and explicit `= N` (decimal or 0x hex).
*/
function parseEnum(src: string, name: string): Array<{ name: string; value: number }> {
const re = new RegExp(`enum\\s+class\\s+${name}\\s*(?::\\s*\\w+\\s*)?\\{([^}]*)\\}`);
const m = re.exec(stripComments(src));
if (!m) throw new Error(`C++ enum '${name}' not found`);
const out: Array<{ name: string; value: number }> = [];
let next = 0;
for (const raw of m[1].split(',')) {
const part = raw.trim();
if (!part) continue;
const em = /^(\w+)\s*(?:=\s*(.+))?$/.exec(part);
if (!em) throw new Error(`C++ enum '${name}': cannot parse entry '${part}'`);
const value = em[2] != null ? Number(em[2].trim()) : next;
if (Number.isNaN(value)) throw new Error(`C++ enum '${name}': non-numeric value for '${em[1]}'`);
out.push({ name: em[1], value });
next = value + 1;
}
return out;
}
/** Parse a `[static|inline] constexpr <type> NAME = <value>;` integer constant. */
function parseConst(src: string, name: string): number {
const m = new RegExp(`constexpr\\s+\\w+\\s+${name}\\s*=\\s*([^;]+);`).exec(stripComments(src));
if (!m) throw new Error(`C++ constant '${name}' not found`);
const v = Number(m[1].trim());
if (Number.isNaN(v)) throw new Error(`C++ constant '${name}': non-numeric value '${m[1].trim()}'`);
return v;
}
/** Drop a trailing sentinel (e.g. COUNT) and index the rest by name. */
function byName(entries: Array<{ name: string; value: number }>, sentinel = 'COUNT'): Map<string, number> {
const map = new Map<string, number>();
for (const e of entries) if (e.name !== sentinel) map.set(e.name, e.value);
return map;
}
const sortedEntries = (m: Map<string, number>): Array<[string, number]> =>
[...m.entries()].sort((a, b) => a[0].localeCompare(b[0]));
/** Forward (name -> number) entries of a numeric TS enum, dropping its reverse map. */
function enumForward(e: Record<string, string | number>): Map<string, number> {
const map = new Map<string, number>();
for (const [k, v] of Object.entries(e)) if (typeof v === 'number') map.set(k, v);
return map;
}
describe('C++ contract: animation tween enums (animation/TweenData.hpp)', () => {
// Generated from that header now, so the pin is IDENTITY: same-values-
// different-object is the drift a re-export eliminates, and only `toBe`
// sees it. The values are in the ABI layout hash.
const cases: Array<[string, unknown, unknown]> = [
['EasingType', EasingType, gen.EasingType],
['TweenState', TweenState, gen.TweenState],
['LoopMode', LoopMode, gen.LoopMode],
['TweenTarget', TweenTarget, gen.TweenTarget],
];
for (const [label, published, generated] of cases) {
it(`${label} is a re-export of the generated enum`, () => {
expect(published).toBe(generated);
});
}
});
describe('C++ contract: particle color LUT (particle/ParticleSystem.hpp)', () => {
it('GRADIENT_LUT_SIZE === kColorLutSize', () => {
// GENERATED from this header now, so this is a second parser of it:
// what it catches is a stale projection or an extraction bug.
const cpp = parseConst(readCpp('particle/ParticleSystem.hpp'), 'kColorLutSize');
expect(GRADIENT_LUT_SIZE).toBe(cpp);
});
});
describe('C++ contract: packed Entity bit split (core/Types.hpp)', () => {
it('ENTITY_INDEX_BITS / ENTITY_GEN_BITS === PackedId<index, gen>', () => {
// The split is GENERATED from this header now, so what this catches is a
// checked-in projection gone stale — read with a SECOND parser, so an
// extraction bug is a disagreement rather than a plausible number.
const m = /PackedId<\s*(\d+)\s*,\s*(\d+)\s*>/.exec(stripComments(readCpp('core/Types.hpp')));
if (!m) throw new Error('C++ Entity::Layout PackedId<index, gen> not found');
expect([ENTITY_INDEX_BITS, ENTITY_GEN_BITS]).toEqual([Number(m[1]), Number(m[2])]);
});
});
describe('C++ contract: tilemap cell encoding (tilemap/TilemapSystem.hpp)', () => {
const src = readCpp('tilemap/TilemapSystem.hpp');
it('tile id mask + flip bits match', () => {
expect({
TILE_ID_MASK,
TILE_FLIP_H,
TILE_FLIP_V,
TILE_FLIP_D,
}).toEqual({
TILE_ID_MASK: parseConst(src, 'TILE_ID_MASK'),
TILE_FLIP_H: parseConst(src, 'TILE_FLIP_H'),
TILE_FLIP_V: parseConst(src, 'TILE_FLIP_V'),
TILE_FLIP_D: parseConst(src, 'TILE_FLIP_D'),
});
});
it('CHUNK_SIZE matches (chunk codec stride)', () => {
expect(CHUNK_SIZE).toBe(parseConst(src, 'CHUNK_SIZE'));
});
});
describe('C++ contract: UI base layer (renderer/plugins/UIElementPlugin.hpp)', () => {
it('UI_BASE_LAYER is generated from the header, not restated beside it', () => {
// It was declared twice — `const UI_BASE_LAYER = 1000` in the TS text
// renderer, with a comment saying it must match. Generated now, so this
// pin is a SECOND reader of the header rather than a guard on a copy.
expect(UI_BASE_LAYER).toBe(parseConst(readCpp('renderer/plugins/UIElementPlugin.hpp'), 'UI_BASE_LAYER'));
});
});
describe('C++ contract: module-published enums ARE their EHT-generated twin', () => {
// These used to be hand-restated `as const` copies in the UI/physics modules;
// they are now re-exports of the generated enums. Pin the object IDENTITY so a
// future edit can't silently reintroduce a copy — same-values-different-object
// is exactly the drift vector the re-export eliminated.
const cases: Array<[string, unknown, unknown]> = [
['BodyType', BodyType, gen.BodyType],
['UIPositionType', UIPositionType, gen.UIPositionType],
['AlignSelf', AlignSelf, gen.AlignSelf],
['UIVisualType', UIVisualType, gen.UIVisualType],
['FillMethod', FillMethod, gen.UIFillMethod],
['FillOrigin', FillOrigin, gen.UIFillOrigin],
['ParticleEasing', ParticleEasing, gen.ParticleEasing],
['MaskMode', MaskMode, gen.MaskMode],
['SpriteMaskInteraction', SpriteMaskInteraction, gen.SpriteMaskInteraction],
['SpriteDrawMode', SpriteDrawMode, gen.SpriteDrawMode],
['ScrollMovement', ScrollMovement, gen.ScrollMovement],
['TilemapOrientation', TilemapOrientation, gen.TilemapOrientation],
['FlexDirection', FlexDirection, gen.FlexDirection],
['FlexWrap', FlexWrap, gen.FlexWrap],
['JustifyContent', JustifyContent, gen.JustifyContent],
['AlignItems', AlignItems, gen.AlignItems],
['AlignContent', AlignContent, gen.AlignContent],
];
for (const [label, published, generated] of cases) {
it(`${label} is a re-export of the generated enum`, () => {
expect(published).toBe(generated);
});
}
});
describe('C++ contract: enums that must stay their own declaration', () => {
// TextAlign cannot be a re-export: it is @public, and the generated enums
// carry no tier, so re-exporting would quietly demote a frozen promise. It
// keeps its own doc and tag, and pays for that with a VALUE pin.
it('TextAlign has the values the generated enum does', () => {
expect({ ...TextAlign }).toEqual({
Left: gen.TextAlign.Left, Center: gen.TextAlign.Center, Right: gen.TextAlign.Right,
});
});
});
describe('C++ contract: a component field that IS an enum is typed as one', () => {
// The generator knows which enum a field is — its C++ type is one, or
// ES_PROPERTY names one. Answering `number` leaves the field unable to
// reject a value the engine has no meaning for.
it('no ES_PROPERTY(enum=) field is generated as a bare number', () => {
const data = readFileSync(
resolve(__dirname, '../src/ecs/component.generated.ts'), 'utf8');
const loose: string[] = [];
for (const dir of ['ecs/components', 'renderer/components']) {
const at = resolve(CPP, dir);
if (!existsSync(at)) continue;
for (const name of readdirSync(at).filter((f) => f.endsWith('.hpp'))) {
const lines = readFileSync(resolve(at, name), 'utf8').split('\n');
lines.forEach((line, i) => {
const enumName = /enum=([A-Za-z_]\w*)/.exec(line)?.[1];
if (!enumName) return;
const decl = lines.slice(i, i + 5)
.map((l) => /^\s*(?:u8|u16|u32|i8|i16|i32)\s+(\w+)\s*[{=]/.exec(l)?.[1])
.find(Boolean);
if (!decl) return;
// `?` because a field added to a frozen component is optional — the
// mark is additive, the TYPE is what this holds.
if (!new RegExp(`^\\s*${decl}\\??: ${enumName};$`, 'm').test(data)) {
loose.push(`${name}: ${decl} should be generated as ${enumName}`);
}
});
}
}
expect(loose).toEqual([]);
});
});