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(events): an event payload is a value, so its layout is a project shape

esengine44775a004824
diff --git a/compiler/src/abi.ts b/compiler/src/abi.ts
index 6042cdb98..16daae0b7 100644
--- a/compiler/src/abi.ts
+++ b/compiler/src/abi.ts
@@ -505,14 +505,19 @@ export function abiHandshake(
// component to a project must not invalidate a module that never reads it.
const named = new Set<string>();
for (const p of plans) {
- // A reader's slot queries the EVENT, which `defineEvent<T>` erases, so
- // the other half of this digest cannot recompute one — counted here, it
- // refuses every module with a reader. The payload layout owes its own.
+ // A reader's slot IS the event, and it is named below with the writers'
+ // — once, and as a payload rather than as a component the runtime would
+ // be asked to resolve.
const payloads = new Set((p.readers ?? []).map((r) => r.slot));
p.queries.forEach((q, k) => {
if (payloads.has(k)) return;
for (const a of q) named.add(a.comp);
});
+ // The payload's field ORDER is what compiled code baked in, so it is a
+ // project shape like any other: the runtime reads the same order off the
+ // value `defineEvent` carries.
+ for (const r of p.readers) named.add(r.event);
+ for (const w of p.writers) named.add(w.event);
}
// A project's own RESOURCE is a project shape; the ENGINE's is not, being
// covered by `engineAbi`. Counting one twice puts it in a digest the
diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.ts
index fcc4bc055..876850eda 100644
--- a/compiler/src/frontend.ts
+++ b/compiler/src/frontend.ts
@@ -222,6 +222,10 @@ class SystemLowerer {
/** Event payloads by declared name, and the const each is bound to. */
private readonly events: ReadonlyMap<string, CompShape> = new Map(),
private readonly eventBindings: ReadonlyMap<string, string> = new Map(),
+ /** Events with no payload VALUE beside their type. Compiled code reads a
+ * payload by position, and only the value tells the runtime which
+ * position is which. */
+ private readonly unpayloaded: ReadonlySet<string> = new Set(),
) {}
/** The event a binding names, or null when the program declares no such one. */
@@ -333,6 +337,11 @@ class SystemLowerer {
if (!name) {
throw new NotInSubset(el, `'${arg.text}' is not an event this program declares`);
}
+ if (this.unpayloaded.has(name)) {
+ throw new NotInSubset(el, `'${name}' is declared without a payload value, so nothing`
+ + ' at run time can say which field a compiled system read. Give defineEvent a'
+ + ` default: defineEvent<...>('${name}', { ... })`, 'permanent');
+ }
return kind === 'EventWriter'
? { k: 'channel', name, channel: 'event' } as EirType
: { k: 'events', name } as EirType;
@@ -860,6 +869,28 @@ function componentShape(call: ts.CallExpression, tag: boolean): CompShape | null
return { name: nameArg.text, storage: 'host', fields };
}
+/**
+ * The second argument's leaves, dotted, in declaration order — the same walk
+ * `eventFieldsOf` makes at run time. Null where it is absent or is not a literal
+ * of scalars, which is the only shape both sides can agree about.
+ */
+function declaredPayload(call: ts.CallExpression): string[] | null {
+ const literal = call.arguments[1];
+ if (!literal || !ts.isObjectLiteralExpression(literal)) return null;
+ const out: string[] = [];
+ const walk = (node: ts.ObjectLiteralExpression, prefix: string): boolean => {
+ for (const prop of node.properties) {
+ if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) return false;
+ const path = prefix ? `${prefix}.${prop.name.text}` : prop.name.text;
+ if (ts.isObjectLiteralExpression(prop.initializer)) {
+ if (!walk(prop.initializer, path)) return false;
+ } else out.push(path);
+ }
+ return true;
+ };
+ return walk(literal, '') ? out : null;
+}
+
/**
* `defineEvent<{ target: Entity; amount: number }>('DamageDealt')` -> a shape.
*
@@ -978,6 +1009,8 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str
/** Event payloads, by declared name — a second namespace from components. */
const events = new Map<string, CompShape>();
const eventBindings = new Map<string, string>();
+ /** Events declared with no payload value, which compiled code may not use. */
+ const unpayloaded = new Set<string>();
/** Resources the PROJECT declared, whose layout travels in the manifest. */
const userResources = new Set<string>();
const consts = new Map<string, ConstValue>();
@@ -1075,6 +1108,19 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str
});
return;
}
+ // The payload as a VALUE, held against it as a type: the layout
+ // comes from the type and the runtime can read only the value,
+ // so a disagreement is two halves over different fields.
+ const declared = declaredPayload(node);
+ if (declared === null) unpayloaded.add(shape.name);
+ else if (declared.join(',') !== [...shape.fields.keys()].join(',')) {
+ unpayloaded.add(shape.name);
+ diagnostics.push({
+ file: sf.fileName, line: lineOf(sf, node), kind: 'permanent', severity: 'note',
+ message: `'${shape.name}' declares the payload [${declared.join(', ')}] and its`
+ + ` type says [${[...shape.fields.keys()].join(', ')}] — one of the two moved`,
+ });
+ }
events.set(shape.name, shape);
// ONE shape table downstream: a payload's fields are read the
// same way a component's are, so every later pass finds them
@@ -1127,7 +1173,7 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str
}
if (!name || !params || !body || fns.has(name)) return;
try {
- fns.set(name, new SystemLowerer(comps, bindings, consts, fns, fnFailures, events, eventBindings)
+ fns.set(name, new SystemLowerer(comps, bindings, consts, fns, fnFailures, events, eventBindings, unpayloaded)
.lowerFn(name, params, body));
} catch (e) {
if (!(e instanceof NotInSubset)) throw e;
@@ -1152,7 +1198,8 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str
if (!params || !fn || !ts.isArrowFunction(fn)) {
throw new NotInSubset(node, 'defineSystem takes a parameter array and an arrow function');
}
- systems.push(new SystemLowerer(comps, bindings, consts, fns, fnFailures, events, eventBindings).lower(name, params, fn));
+ systems.push(new SystemLowerer(comps, bindings, consts, fns, fnFailures, events,
+ eventBindings, unpayloaded).lower(name, params, fn));
} catch (e) {
if (!(e instanceof NotInSubset)) throw e;
diagnostics.push({
diff --git a/compiler/tests/fixtures/event-no-payload.ts b/compiler/tests/fixtures/event-no-payload.ts
new file mode 100644
index 000000000..97609656f
--- /dev/null
+++ b/compiler/tests/fixtures/event-no-payload.ts
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file event-no-payload.ts
+ * @brief An event a compiled system reads, declared without a payload value.
+ *
+ * @details `defineEvent<T>` erases T, so the layout the compiled code bakes in
+ * is one nothing at run time can name. The subset asks for the value.
+ */
+import { defineComponent, defineEvent, defineSystem, EventReader, EventWriter, Query, Mut } from 'esengine';
+
+export const Mover = defineComponent('NoPayloadMover', { speed: 100 });
+
+/** No second argument: the payload exists only as a type. */
+export const Silent = defineEvent<{ amount: number }>('NoPayloadSilent');
+
+/** Declared with one, and so usable. */
+export const Loud = defineEvent<{ amount: number }>('NoPayloadLoud', { amount: 0 });
+
+/** The names agree and the ORDER does not, which is every field at another
+ * position — the value says one thing and the type says the other. */
+export const Crossed = defineEvent<{ first: number; second: number }>(
+ 'NoPayloadCrossed', { second: 0, first: 0 });
+
+/**
+ * @compiled
+ */
+export const readsSilent = defineSystem(
+ [EventReader(Silent), Query(Mut(Mover))],
+ (hits, query) => {
+ for (const h of hits) { for (const [, m] of query) { m.speed += h.amount; } }
+ },
+ { name: 'ReadsSilent' },
+);
+
+/**
+ * @compiled
+ */
+export const writesSilent = defineSystem(
+ [Query(Mut(Mover)), EventWriter(Silent)],
+ (query, out) => {
+ for (const [, m] of query) { out.send({ amount: m.speed }); }
+ },
+ { name: 'WritesSilent' },
+);
+
+/**
+ * @compiled
+ */
+export const readsLoud = defineSystem(
+ [EventReader(Loud), Query(Mut(Mover))],
+ (hits, query) => {
+ for (const h of hits) { for (const [, m] of query) { m.speed += h.amount; } }
+ },
+ { name: 'ReadsLoud' },
+);
+
+/**
+ * @compiled
+ */
+export const readsCrossed = defineSystem(
+ [EventReader(Crossed), Query(Mut(Mover))],
+ (hits, query) => {
+ for (const h of hits) { for (const [, m] of query) { m.speed += h.first + h.second; } }
+ },
+ { name: 'ReadsCrossed' },
+);
diff --git a/compiler/tests/fixtures/in-subset.ts b/compiler/tests/fixtures/in-subset.ts
index 0ccaadfdf..72d5b3bbe 100644
--- a/compiler/tests/fixtures/in-subset.ts
+++ b/compiler/tests/fixtures/in-subset.ts
@@ -163,7 +163,7 @@ export const gateSystem = defineSystem(
);
/** One payload, and the two halves that put it into memory and take it out. */
-export const Pinged = defineEvent<{ by: number }>('FixturePinged');
+export const Pinged = defineEvent<{ by: number }>('FixturePinged', { by: 0 });
export const pingSystem = defineSystem(
[Query(Mut(Drift)), EventWriter(Pinged)],
diff --git a/compiler/tests/stubs/esengine.ts b/compiler/tests/stubs/esengine.ts
index 156e193a3..ac95296dd 100644
--- a/compiler/tests/stubs/esengine.ts
+++ b/compiler/tests/stubs/esengine.ts
@@ -39,8 +39,9 @@ export function ResMut(resource: unknown): unknown {
}
export const Input = { _name: 'Input' };
export { exact } from '../../../sdk/src/math/exact';
-export function defineEvent<T>(name: string): { _name: string } {
+export function defineEvent<T>(name: string, payload?: T & object): { _name: string } {
void (undefined as T | undefined);
+ void payload;
return { _name: name };
}
export function EventWriter(event: unknown): unknown {
diff --git a/compiler/tests/subset.test.ts b/compiler/tests/subset.test.ts
index f676b1853..db12a825e 100644
--- a/compiler/tests/subset.test.ts
+++ b/compiler/tests/subset.test.ts
@@ -99,3 +99,47 @@ describe('a promise the author wrote down', () => {
expect(brokenPromises(result).map((d) => d.system)).toEqual(['FixturePromised']);
});
});
+
+/**
+ * `defineEvent<T>` erases T, so a payload declared only as a type leaves the
+ * layout compiled code baked in unnameable at run time — and the two halves of
+ * the project handshake then range over different fields. The subset asks for
+ * the value, the way a component and a resource already carry theirs.
+ */
+describe('an event a compiled system uses carries its payload as a value', () => {
+ const NO_PAYLOAD = resolve(HERE, 'fixtures/event-no-payload.ts');
+ const lowered = lowerProgram([NO_PAYLOAD], builtinShapes());
+ const broken = brokenPromises(lowered);
+ const about = (system: string) => broken.find((d) => d.system === system);
+
+ it('refuses a reader of one that does not, with a line and the fix', () => {
+ const found = about('ReadsSilent');
+ expect(found, 'ReadsSilent was not refused').toBeDefined();
+ expect(found!.line).toBeGreaterThan(0);
+ expect(found!.message).toMatch(/declared without a payload value/);
+ expect(found!.message).toMatch(/defineEvent<\.\.\.>\('NoPayloadSilent', \{ \.\.\. \}\)/);
+ });
+
+ it('refuses a writer of one too — the layout is the same contract', () => {
+ expect(about('WritesSilent'), 'WritesSilent was not refused').toBeDefined();
+ });
+
+ /** The value and the type are two statements of one layout, so the compiler
+ * holds them together — a payload declared in another order is every field
+ * at another position, and the runtime would read the value's. */
+ it('refuses one whose declared value and type disagree, naming both', () => {
+ const said = lowered.diagnostics.find((d) => /NoPayloadCrossed/.test(d.message));
+ expect(said, 'the disagreement was not reported').toBeDefined();
+ expect(said!.message).toMatch(/declares the payload \[second, first\]/);
+ expect(said!.message).toMatch(/type says \[first, second\]/);
+ expect(said!.line).toBeGreaterThan(0);
+ // And the system that reads it does not compile against a layout the
+ // two halves cannot agree on.
+ expect(about('ReadsCrossed'), 'ReadsCrossed was not refused').toBeDefined();
+ });
+
+ it('and compiles the one whose event carries its payload', () => {
+ expect(about('ReadsLoud')).toBeUndefined();
+ expect(lowered.module.systems.some((s) => s.name === 'ReadsLoud')).toBe(true);
+ });
+});
diff --git a/examples/celestial-heights/src/events.ts b/examples/celestial-heights/src/events.ts
index c9678948d..ad73e11f5 100644
--- a/examples/celestial-heights/src/events.ts
+++ b/examples/celestial-heights/src/events.ts
@@ -10,6 +10,7 @@ export const DamageDealt = defineEvent<{
/** Where the blow came from, for knockback and hit sparks. */
fromX: number;
fromY: number;
-}>('DamageDealt');
+}>('DamageDealt', { target: 0 as Entity, amount: 0, fromX: 0, fromY: 0 });
-export const Died = defineEvent<{ entity: Entity; isPlayer: boolean }>('Died');
+export const Died = defineEvent<{ entity: Entity; isPlayer: boolean }>(
+ 'Died', { entity: 0 as Entity, isPlayer: false });
diff --git a/examples/event-system/src/events.ts b/examples/event-system/src/events.ts
index 043034a19..e0668e1ad 100644
--- a/examples/event-system/src/events.ts
+++ b/examples/event-system/src/events.ts
@@ -10,8 +10,9 @@ export interface CollectEvent {
points: number;
}
-export const SpawnRequestEvent = defineEvent<SpawnRequest>('SpawnRequest');
-export const CollectEventDef = defineEvent<CollectEvent>('CollectEvent');
+export const SpawnRequestEvent = defineEvent<SpawnRequest>(
+ 'SpawnRequest', { x: 0, y: 0, color: { r: 0, g: 0, b: 0 } });
+export const CollectEventDef = defineEvent<CollectEvent>('CollectEvent', { points: 0 });
export interface ScoreData {
value: number;
diff --git a/pipeline/tests/build-compiled-systems.test.ts b/pipeline/tests/build-compiled-systems.test.ts
index a92a619b6..59f3740a7 100644
--- a/pipeline/tests/build-compiled-systems.test.ts
+++ b/pipeline/tests/build-compiled-systems.test.ts
@@ -453,7 +453,7 @@ export const moveSystem = defineSystem(
describe('a compiled system that reads an event', () => {
const READER = `import { defineComponent, defineEvent, defineSystem, Query, Mut, EventReader } from 'esengine';
export const Mover = defineComponent('Mover', { speed: 100 });
-export const Hit = defineEvent<{ amount: number }>('Hit');
+export const Hit = defineEvent<{ amount: number }>('Hit', { amount: 0 });
/** @compiled */
export const absorb = defineSystem(
[EventReader(Hit), Query(Mut(Mover))],
@@ -469,9 +469,11 @@ export const absorb = defineSystem(
expect(out.manifest!.systems[0]!.readers).toHaveLength(1);
// Exactly what a runtime holding this project computes: its components, and
- // nothing that answers to an event's name. Counting `Hit` here refused every
- // reader module ever built, blaming a component that had not moved.
- expect(out.manifest!.projectShapes)
- .toBe(projectShapeDigest([{ name: 'Mover', fields: ['speed'] }]));
+ // the payload read off the value `defineEvent` carries. Both halves range
+ // over the same set, which is what a reader module needs to load at all.
+ expect(out.manifest!.projectShapes).toBe(projectShapeDigest([
+ { name: 'Mover', fields: ['speed'] },
+ { name: 'Hit', fields: ['amount'] },
+ ]));
});
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 7fb314d8c..6bdb45d53 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -3118,6 +3118,7 @@ target: string | undefined
## EventDef — interface @public
```
+@internal _default: object | undefined
@internal _id: symbol
@internal _name: string
@internal _phantom: T | undefined
@@ -10319,7 +10320,7 @@ PluralSelector
## defineEvent — function @public
```
-<T>(name: string): EventDef<T>
+<T>(name: string, payload?: T & object): EventDef<T>
```
## defineInputMap — function @public
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index db6fca58f..a1ec379ca 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -3126,6 +3126,7 @@ target: string | undefined
## EventDef — interface @public
```
+@internal _default: object | undefined
@internal _id: symbol
@internal _name: string
@internal _phantom: T | undefined
@@ -10552,7 +10553,7 @@ PluralSelector
## defineEvent — function @public
```
-<T>(name: string): EventDef<T>
+<T>(name: string, payload?: T & object): EventDef<T>
```
## defineInputMap — function @public
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4df0d017c..038274c05 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -3113,6 +3113,7 @@ target: string | undefined
## EventDef — interface @public
```
+@internal _default: object | undefined
@internal _id: symbol
@internal _name: string
@internal _phantom: T | undefined
@@ -10314,7 +10315,7 @@ PluralSelector
## defineEvent — function @public
```
-<T>(name: string): EventDef<T>
+<T>(name: string, payload?: T & object): EventDef<T>
```
## defineInputMap — function @public
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 00fa50506..5295b18cc 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -3113,6 +3113,7 @@ target: string | undefined
## EventDef — interface @public
```
+@internal _default: object | undefined
@internal _id: symbol
@internal _name: string
@internal _phantom: T | undefined
@@ -10571,7 +10572,7 @@ PluralSelector
## defineEvent — function @public
```
-<T>(name: string): EventDef<T>
+<T>(name: string, payload?: T & object): EventDef<T>
```
## defineInputMap — function @public
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 925e3b806..ca8737a5f 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -3113,6 +3113,7 @@ target: string | undefined
## EventDef — interface @public
```
+@internal _default: object | undefined
@internal _id: symbol
@internal _name: string
@internal _phantom: T | undefined
@@ -10342,7 +10343,7 @@ PluralSelector
## defineEvent — function @public
```
-<T>(name: string): EventDef<T>
+<T>(name: string, payload?: T & object): EventDef<T>
```
## defineInputMap — function @public
diff --git a/sdk/src/ecs/aot/AotSystems.ts b/sdk/src/ecs/aot/AotSystems.ts
index 65441a133..588d09169 100644
--- a/sdk/src/ecs/aot/AotSystems.ts
+++ b/sdk/src/ecs/aot/AotSystems.ts
@@ -17,6 +17,7 @@
import type { AnyComponentDef } from '../component';
import { engineAbiDigest, projectShapeDigest, type ShapeDigestInput } from './abiDigest';
+import { eventFieldsOf } from '../event';
/** One system's declaration, as the build wrote it beside the module. */
export interface AotSystemDecl {
@@ -38,6 +39,31 @@ export interface AotSystemDecl {
readonly writers?: readonly { slot: number; event: string; fields: readonly string[] }[];
}
+/**
+ * What a road knows that the manifest cannot say for itself. Each answer comes
+ * from the RUNTIME, never from the manifest: a manifest compared against itself
+ * always agrees.
+ */
+export interface InstallOptions {
+ /** The fields this runtime's copy of a resource has, in ITS order, or
+ * undefined when there is no such resource. */
+ readonly resourceFields?: (name: string) => readonly string[] | undefined;
+ /** The fields this runtime's copy of an event payload has, in ITS order.
+ * Undefined is "cannot say" — an event declared without a payload value. */
+ readonly eventFields?: (name: string) => readonly string[] | undefined;
+ /** `sizeof(es_addr_t)` where this module will run: 4 in a wasm module
+ * addressing the engine's memory by offset, 8 in a library the host
+ * loaded into its own process. */
+ readonly addressBytes?: 4 | 8;
+ /** Which declarations become twins. The handshake is still checked over the
+ * WHOLE manifest, because that is what the module is. Default: all. */
+ readonly runs?: (name: string) => boolean;
+ /** What the ARTIFACT says it was built as, or null where this road cannot
+ * ask it. Two builds over one engine and one project agree on both digests
+ * while declaring different queries, mut flags and event payloads. */
+ readonly moduleContract?: string | null;
+}
+
export interface AotManifest {
/** The engine the module was built against (EHT offsets, resource shapes,
* struct sizes, address width). */
@@ -106,33 +132,15 @@ export class AotSystems {
manifest: AotManifest,
exports: Readonly<Record<string, unknown>>,
resolve: (name: string) => AnyComponentDef | undefined,
- /**
- * The fields this runtime's copy of a resource has, in ITS order, or
- * undefined when there is no such resource. Asked rather than taken
- * from the manifest: a manifest compared against itself always agrees.
- */
- resourceFields: (name: string) => readonly string[] | undefined = () => [],
- /**
- * `sizeof(es_addr_t)` where this module will run: 4 in a wasm module
- * addressing the engine's memory by offset, 8 in a library the host
- * loaded into its own process. The digest carries it, so asking for
- * the wrong one is the refusal it is supposed to be.
- */
- addressBytes: 4 | 8 = 4,
- /**
- * Which declarations become twins. The handshake is still checked over
- * the WHOLE manifest, because that is what the module is; a host that
- * could bind only some of it still loaded all of it. Default: all.
- */
- runs: (name: string) => boolean = () => true,
- /**
- * What the ARTIFACT says it was built as, or null where this road
- * cannot ask it. Two builds over one engine and one project agree on
- * both digests below while declaring different queries, mut flags and
- * event payloads — which is what the bookkeeping here reads.
- */
- moduleContract: string | null = null,
+ opts: InstallOptions = {},
): void {
+ const {
+ resourceFields = () => [],
+ eventFields = eventFieldsOf,
+ addressBytes = 4,
+ runs = () => true,
+ moduleContract = null,
+ } = opts;
// Two questions with two fixes, so two answers rather than one that can
// only say "something moved".
const engine = engineAbiDigest(addressBytes);
@@ -149,7 +157,7 @@ export class AotSystems {
+ 'different builds — the declarations this runtime reads are not the ones the '
+ 'module compiled. Rebuild both.');
}
- const shapes = projectShapeDigest(scriptShapes(manifest, resolve, resourceFields));
+ const shapes = projectShapeDigest(scriptShapes(manifest, resolve, resourceFields, eventFields));
if (manifest.projectShapes !== shapes) {
throw new Error(
`AOT module refused: built for components ${manifest.projectShapes}, this project `
@@ -198,6 +206,7 @@ function scriptShapes(
manifest: AotManifest,
resolve: (name: string) => AnyComponentDef | undefined,
resourceFields: (name: string) => readonly string[] | undefined,
+ eventFields: (name: string) => readonly string[] | undefined,
): ShapeDigestInput[] {
const seen = new Set<string>();
const out: ShapeDigestInput[] = [];
@@ -212,9 +221,16 @@ function scriptShapes(
// what says whether that order is still the one here.
out.push({ name: r.name, fields: [...(resourceFields(r.name) ?? [])] });
}
- // A reader's slot queries the EVENT it reads. Skipped on PURPOSE and
- // not by failing to resolve: both halves of a digest must range over
- // the same set. The payload layout still owes a mechanism of its own.
+ // A payload's field ORDER is what the compiled code baked in, and this
+ // side reads it off the value `defineEvent` carries — never off the
+ // manifest, which compared against itself always agrees.
+ for (const ch of [...(decl.readers ?? []), ...(decl.writers ?? [])]) {
+ if (seen.has(ch.event)) continue;
+ seen.add(ch.event);
+ out.push({ name: ch.event, fields: [...(eventFields(ch.event) ?? [])] });
+ }
+ // A reader's slot IS that event, counted just above rather than resolved
+ // here: both halves of a digest must range over the same set.
const payloads = new Set((decl.readers ?? []).map((r) => r.slot));
for (const [k, query] of decl.queries.entries()) {
if (payloads.has(k)) continue;
diff --git a/sdk/src/ecs/aot/installAot.ts b/sdk/src/ecs/aot/installAot.ts
index aaf3c0cc0..e0382bd02 100644
--- a/sdk/src/ecs/aot/installAot.ts
+++ b/sdk/src/ecs/aot/installAot.ts
@@ -106,11 +106,13 @@ export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'>): Promi
(exports['_initialize'] as (() => void) | undefined)?.();
const systems = new AotSystems();
- systems.install(opts.manifest, exports, componentNamed,
- opts.resourceFields ?? ((name) => {
+ systems.install(opts.manifest, exports, componentNamed, {
+ resourceFields: opts.resourceFields ?? ((name) => {
const value = opts.resources(name);
return value === undefined ? undefined : Object.keys(value);
- }), 4, () => true, moduleContractOf(exports));
+ }),
+ moduleContract: moduleContractOf(exports),
+ });
const runtime: AotRuntime = {
systems,
diff --git a/sdk/src/ecs/aot/installNativeAot.ts b/sdk/src/ecs/aot/installNativeAot.ts
index ab6f65df3..bd2053127 100644
--- a/sdk/src/ecs/aot/installNativeAot.ts
+++ b/sdk/src/ecs/aot/installNativeAot.ts
@@ -159,9 +159,11 @@ export function installNativeAot(opts: InstallNativeAotOptions): AotRuntime | nu
// The artifact is the host's to read here, so the pairing comes back from
// it rather than off an export this side can reach.
const paired = bindings.contract?.() ?? '';
- systems.install(opts.manifest, exports, (name) => getComponent(name),
- () => [], NATIVE_ADDRESS_BYTES, (name) => byName.has(name),
- paired === '' ? null : paired);
+ systems.install(opts.manifest, exports, (name) => getComponent(name), {
+ addressBytes: NATIVE_ADDRESS_BYTES,
+ runs: (name) => byName.has(name),
+ moduleContract: paired === '' ? null : paired,
+ });
// Every script component any twin names, so one epoch change re-reports all
// of them rather than whichever twin happened to run first.
diff --git a/sdk/src/ecs/event.ts b/sdk/src/ecs/event.ts
index 357038fcf..2c22141b6 100644
--- a/sdk/src/ecs/event.ts
+++ b/sdk/src/ecs/event.ts
@@ -20,6 +20,14 @@ export interface EventDef<T> {
readonly _id: symbol;
/** @internal */
readonly _name: string;
+ /**
+ * The payload's fields, as a value rather than as an erased type — the same
+ * thing `defineComponent` and `defineResource` carry, and for the same
+ * reason: a mechanism that has to know this shape can ask.
+ *
+ * @internal
+ */
+ readonly _default?: object;
/** @internal */
readonly _phantom?: T;
}
@@ -29,12 +37,19 @@ export interface EventDef<T> {
* readable for exactly the next one, so a reader that misses a frame misses the
* event — events are for this-frame signalling, not a queue.
*
+ * `payload` is a default of the shape `T`, the way a component declares its
+ * fields. Optional, and needed only where a `@compiled` system reads or writes
+ * the event: `T` is erased at run time, so without it nothing on this side can
+ * say what layout the compiled code baked in. The compiler asks for it by name
+ * and line when a promise depends on it.
+ *
* @public
*/
-export function defineEvent<T>(name: string): EventDef<T> {
+export function defineEvent<T>(name: string, payload?: T & object): EventDef<T> {
const def: EventDef<T> = {
_id: Symbol(`Event_${name}`),
_name: name,
+ ...(payload === undefined ? {} : { _default: payload as object }),
};
// By name as well, because a compiled module's manifest carries names. The
// FIRST wins: a second event of the same name is a different event, and
@@ -54,6 +69,28 @@ export function eventNamed(name: string): EventDef<unknown> | undefined {
return byName.get(name);
}
+/**
+ * The payload's fields as compiled code reads them: one entry per leaf, dotted,
+ * in declaration order. Undefined where the event was declared without a
+ * payload — which is "cannot say", never "no fields".
+ *
+ * @internal
+ */
+export function eventFieldsOf(name: string): readonly string[] | undefined {
+ const shape = byName.get(name)?._default;
+ if (shape === undefined) return undefined;
+ const out: string[] = [];
+ const walk = (value: object, prefix: string): void => {
+ for (const [key, at] of Object.entries(value)) {
+ const path = prefix ? `${prefix}.${key}` : key;
+ if (at !== null && typeof at === 'object') walk(at as object, path);
+ else out.push(path);
+ }
+ };
+ walk(shape, '');
+ return out;
+}
+
// =============================================================================
// Event Bus (double-buffered)
// =============================================================================
diff --git a/sdk/tests/aot-app.test.ts b/sdk/tests/aot-app.test.ts
index cd25274d3..4ab00800a 100644
--- a/sdk/tests/aot-app.test.ts
+++ b/sdk/tests/aot-app.test.ts
@@ -203,7 +203,7 @@ describe('an App told to run its compiled twins', () => {
const wasm = buildAotModule(EMCC!, EVENT_C, 'es_sys_Absorb');
const { app } = bootMockApp();
const Fade = defineComponent('Fade', { alpha: 1, step: 0.1 }) as AnyComponentDef;
- const Hit = defineEvent<{ amount: number }>('Hit');
+ const Hit = defineEvent<{ amount: number }>('Hit', { amount: 0 });
app.addSystemToSchedule(Schedule.Update, defineSystem(
[EventReader(Hit), Query(Mut(Fade))], () => { /* the twin is the point */ },
{ name: 'Absorb' }));
@@ -226,7 +226,7 @@ describe('an App told to run its compiled twins', () => {
const wasm = buildAotModule(EMCC!, EVENT_C, 'es_sys_Emit');
const { app } = bootMockApp();
const Fade = defineComponent('Fade', { alpha: 1, step: 0.1 }) as AnyComponentDef;
- const Hit = defineEvent<{ amount: number }>('Sent');
+ const Hit = defineEvent<{ amount: number }>('Sent', { amount: 0 });
const seen: number[] = [];
app.addSystemToSchedule(Schedule.Update, defineSystem(
[Query(Fade), EventWriter(Hit)], () => { /* the twin is the point */ },
diff --git a/sdk/tests/aot-dispatcher-seam.test.ts b/sdk/tests/aot-dispatcher-seam.test.ts
index 8fa1e0357..acf6ae67d 100644
--- a/sdk/tests/aot-dispatcher-seam.test.ts
+++ b/sdk/tests/aot-dispatcher-seam.test.ts
@@ -67,8 +67,7 @@ function hostRuntime(world: World, seen: { dispatcher?: HostPackedDispatcher }):
MANIFEST,
{ es_sys_Drift: () => { throw new Error('the host calls it, not the runner'); } },
(name) => (name === 'Drift' ? Drift : undefined),
- () => [],
- NATIVE_ADDR,
+ { addressBytes: NATIVE_ADDR },
);
return {
systems,
diff --git a/sdk/tests/aot-native-install.test.ts b/sdk/tests/aot-native-install.test.ts
index e593210dd..829962327 100644
--- a/sdk/tests/aot-native-install.test.ts
+++ b/sdk/tests/aot-native-install.test.ts
@@ -103,7 +103,10 @@ function fixture(boundNames: readonly string[]) {
*/
const EVENT_MANIFEST: AotManifest = {
engineAbi: engineAbiDigest(8),
- projectShapes: projectShapeDigest([{ name: 'Drift', fields: ['x'] }]),
+ projectShapes: projectShapeDigest([
+ { name: 'Drift', fields: ['x'] },
+ { name: 'Hit', fields: ['amount'] },
+ ]),
systems: [
{
name: 'SendSystem', symbol: 'es_sys_Send', resources: [],
@@ -124,7 +127,7 @@ const EVENT_MANIFEST: AotManifest = {
function eventFixture() {
const Drift = declareDrift();
- const Hit = defineEvent<{ amount: number }>('Hit');
+ const Hit = defineEvent<{ amount: number }>('Hit', { amount: 0 });
const events = new EventRegistry();
const world = new World();
const runner = new SystemRunner(world, new ResourceStorage(), events);
@@ -384,32 +387,66 @@ describe('a module and the sidecar written beside it', () => {
/**
- * Both halves of `projectShapes` must range over the same set. A reader's slot
- * queries the EVENT it reads, which `defineEvent<T>` erases — left in on either
- * side alone, every module with a reader is refused, blaming a component that
- * never moved.
+ * A payload's field ORDER is what compiled code baked in, and a manifest
+ * compared against itself always agrees. `defineEvent` carries the payload as a
+ * VALUE — what a component's defaults already are — so this side says what the
+ * order is without being told by the module.
*/
-describe('an event a reader names is not a component either half counts', () => {
- /** The event shares a real component's NAME, which is what makes this a test
- * and not a restatement: without the slot rule this side would resolve it
- * and count a shape the compiler did not. */
- function manifest(): AotManifest {
- return {
- engineAbi: engineAbiDigest(8),
- projectShapes: projectShapeDigest([{ name: 'Drift', fields: ['x'] }]),
- systems: [{
- name: 'AbsorbSystem', symbol: 'es_sys_Absorb', resources: [],
- queries: [[{ comp: 'Named', mut: false }], [{ comp: 'Drift', mut: true }]],
- readers: [{ slot: 0, event: 'Named', fields: ['amount'] }],
- }],
+describe('an event payload is a project shape', () => {
+ const manifestFor = (fields: readonly string[]): AotManifest => ({
+ engineAbi: engineAbiDigest(8),
+ projectShapes: projectShapeDigest([
+ { name: 'Drift', fields: ['x'] },
+ { name: 'Struck', fields: [...fields] },
+ ]),
+ systems: [{
+ name: 'AbsorbSystem', symbol: 'es_sys_Absorb', resources: [],
+ queries: [[{ comp: 'Struck', mut: false }], [{ comp: 'Drift', mut: true }]],
+ readers: [{ slot: 0, event: 'Struck', fields: [...fields] }],
+ }],
+ });
+
+ const install = (m: AotManifest) => () => new AotSystems().install(
+ m, { es_sys_Absorb: () => {} }, (name) => getComponent(name), { addressBytes: 8 });
+
+ it('installs where the payload this project declares is the one it was built for', () => {
+ declareDrift();
+ defineEvent<{ target: number; amount: number }>('Struck', { target: 0, amount: 0 });
+ expect(install(manifestFor(['target', 'amount']))).not.toThrow();
+ });
+
+ /** A rename: the module reads a field now called something else, and every
+ * value it delivers is undefined. */
+ it('refuses a module built against a payload this project no longer has', () => {
+ declareDrift();
+ defineEvent<{ target: number; power: number }>('Renamed', { target: 0, power: 0 });
+ const m = manifestFor(['target', 'amount']);
+ const renamed: AotManifest = {
+ ...m,
+ projectShapes: projectShapeDigest([
+ { name: 'Drift', fields: ['x'] },
+ { name: 'Renamed', fields: ['target', 'amount'] },
+ ]),
+ systems: [{ ...m.systems[0]!, queries: [[{ comp: 'Renamed', mut: false }], [{ comp: 'Drift', mut: true }]],
+ readers: [{ slot: 0, event: 'Renamed', fields: ['target', 'amount'] }] }],
};
- }
+ expect(install(renamed)).toThrow(/built for components/);
+ });
- it('is left out even where a component answers to its name', () => {
+ /** And the reorder, which changes every position without changing a name. */
+ it('refuses a module built against the same fields in another order', () => {
declareDrift();
- defineComponent('Named', { amount: 0 });
- const m = manifest();
- expect(() => new AotSystems().install(
- m, { es_sys_Absorb: () => {} }, (name) => getComponent(name), () => [], 8)).not.toThrow();
+ defineEvent<{ target: number; amount: number }>('Reordered', { amount: 0, target: 0 });
+ const m = manifestFor(['target', 'amount']);
+ const swapped: AotManifest = {
+ ...m,
+ projectShapes: projectShapeDigest([
+ { name: 'Drift', fields: ['x'] },
+ { name: 'Reordered', fields: ['target', 'amount'] },
+ ]),
+ systems: [{ ...m.systems[0]!, queries: [[{ comp: 'Reordered', mut: false }], [{ comp: 'Drift', mut: true }]],
+ readers: [{ slot: 0, event: 'Reordered', fields: ['target', 'amount'] }] }],
+ };
+ expect(install(swapped)).toThrow(/built for components/);
});
});
diff --git a/sdk/tests/helpers/aotFade.ts b/sdk/tests/helpers/aotFade.ts
index d6e420c8d..a317ddc27 100644
--- a/sdk/tests/helpers/aotFade.ts
+++ b/sdk/tests/helpers/aotFade.ts
@@ -223,10 +223,16 @@ export function userResManifest(fields: readonly string[]): AotManifest {
/** The manifest for whichever half is being run. */
export function eventManifest(which: 'Absorb' | 'Emit'): AotManifest {
- const shapes = projectShapeDigest([{ name: 'Fade', fields: FADE_FIELDS }]);
+ // The payload is a project shape too: the compiled code baked its field
+ // order in, and this side reads the same order off what `defineEvent` was
+ // given. The two events differ, so the digests do.
+ const shapesFor = (event: string) => projectShapeDigest([
+ { name: 'Fade', fields: FADE_FIELDS },
+ { name: event, fields: ['amount'] },
+ ]);
return which === 'Absorb'
? {
- engineAbi: engineAbiDigest(4), projectShapes: shapes,
+ engineAbi: engineAbiDigest(4), projectShapes: shapesFor('Hit'),
systems: [{
name: 'Absorb', symbol: 'es_sys_Absorb', resources: [],
queries: [[{ comp: 'Hit', mut: false }], [{ comp: 'Fade', mut: true }]],
@@ -234,7 +240,7 @@ export function eventManifest(which: 'Absorb' | 'Emit'): AotManifest {
}],
}
: {
- engineAbi: engineAbiDigest(4), projectShapes: shapes,
+ engineAbi: engineAbiDigest(4), projectShapes: shapesFor('Sent'),
systems: [{
name: 'Emit', symbol: 'es_sys_Emit', resources: [],
queries: [[{ comp: 'Fade', mut: false }]],
diff --git a/tools/lib/apiSnapshot.mjs b/tools/lib/apiSnapshot.mjs
index 08b2265ce..732a17574 100644
--- a/tools/lib/apiSnapshot.mjs
+++ b/tools/lib/apiSnapshot.mjs
@@ -61,6 +61,51 @@ export function isAdditiveMembers(before, after) {
return added.length > 0 && added.every((line) => /:\s.*\|\s*undefined$/.test(line));
}
+/**
+ * A function that kept every parameter it had and gained OPTIONAL ones at the
+ * end: every call written against the old signature still compiles and means
+ * the same thing, which is the whole of what @public promises. Prefix and
+ * optional both — a required, changed or inserted parameter stays a failure.
+ */
+export function isAddedOptionalParam(before, after) {
+ const parts = (s) => {
+ // `<T>(a: number, b?: string): R` — the parameter list, and the rest.
+ const open = s.indexOf('(');
+ const close = s.lastIndexOf(')');
+ if (open < 0 || close < open) return null;
+ const params = s.slice(open + 1, close).trim();
+ return {
+ head: s.slice(0, open),
+ tail: s.slice(close + 1),
+ // Split on commas outside brackets, so `Map<a, b>` stays one.
+ list: splitParams(params),
+ };
+ };
+ const a = parts(before.trim());
+ const b = parts(after.trim());
+ if (a === null || b === null) return false;
+ if (a.head !== b.head || a.tail !== b.tail) return false;
+ if (b.list.length <= a.list.length) return false;
+ if (a.list.some((p, i) => p !== b.list[i])) return false;
+ return b.list.slice(a.list.length).every((p) => /^[A-Za-z_$][\w$]*\?\s*:/.test(p));
+}
+
+/** Top-level commas only: a parameter's own type may hold them. */
+function splitParams(text) {
+ const out = [];
+ let depth = 0;
+ let at = 0;
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i];
+ if ('<([{'.includes(c)) depth++;
+ else if ('>)]}'.includes(c)) depth--;
+ else if (c === ',' && depth === 0) { out.push(text.slice(at, i).trim()); at = i + 1; }
+ }
+ const last = text.slice(at).trim();
+ if (last) out.push(last);
+ return out;
+}
+
/**
* A string-literal union that kept every member and gained more. The direction
* is the rule: every value that was legal still is, while a union that LOST one
@@ -105,6 +150,9 @@ export function baselineFindings(was, now) {
} else if (before.kind === 'type'
&& isWidenedUnion(promisedBody(before.body), promisedBody(after.body))) {
notes.push(`${name} — @public union gained a member`);
+ } else if (before.kind === 'function'
+ && isAddedOptionalParam(promisedBody(before.body), promisedBody(after.body))) {
+ notes.push(`${name} — @public function gained an optional parameter`);
} else {
failures.push(`${name} — @public signature changed`);
}
diff --git a/tools/tests/api-baseline.test.ts b/tools/tests/api-baseline.test.ts
index 3834bd6e5..01bdc9e80 100644
--- a/tools/tests/api-baseline.test.ts
+++ b/tools/tests/api-baseline.test.ts
@@ -139,3 +139,48 @@ describe('an interface that gains an optional member', () => {
expect(isAdditiveMembers('a: string | undefined', 'a: string | undefined')).toBe(false);
});
});
+
+/**
+ * A trailing OPTIONAL parameter breaks no call that was written, which is the
+ * whole of what @public promises. Every other edit to a signature does break
+ * one, so the rule has to be a prefix rule and not "the strings differ".
+ */
+describe('a @public function that gained an optional parameter', () => {
+ const was = sig('defineEvent — function @public', '<T>(name: string): EventDef<T>');
+ const changed = (body: string) =>
+ baselineFindings(snapshot(was), snapshot(sig('defineEvent — function @public', body)));
+
+ it('is a note, not a broken promise', () => {
+ const { failures, notes } = changed('<T>(name: string, payload?: T & object): EventDef<T>');
+ expect(failures).toEqual([]);
+ expect(notes.join(' ')).toMatch(/gained an optional parameter/);
+ });
+
+ it('is still broken when the new parameter is REQUIRED', () => {
+ expect(changed('<T>(name: string, payload: T & object): EventDef<T>').failures)
+ .toEqual(['defineEvent — @public signature changed']);
+ });
+
+ it('is still broken when an existing parameter changed', () => {
+ expect(changed('<T>(name: number, payload?: T): EventDef<T>').failures)
+ .toEqual(['defineEvent — @public signature changed']);
+ });
+
+ it('is still broken when the return type changed', () => {
+ expect(changed('<T>(name: string, payload?: T): EventDef<unknown>').failures)
+ .toEqual(['defineEvent — @public signature changed']);
+ });
+
+ it('is still broken when a parameter was inserted rather than appended', () => {
+ expect(changed('<T>(payload?: T, name: string): EventDef<T>').failures)
+ .toEqual(['defineEvent — @public signature changed']);
+ });
+
+ /** A type parameter list is not a parameter list; a comma inside one must
+ * not split a parameter either. */
+ it('reads a parameter whose own type carries a comma', () => {
+ const wide = sig('f — function @public', '(a: Map<string, number>): void');
+ const wider = sig('f — function @public', '(a: Map<string, number>, b?: number): void');
+ expect(baselineFindings(snapshot(wide), snapshot(wider)).failures).toEqual([]);
+ });
+});