feat: add world serialization support

Introduce `toJSON` and `fromJSON` methods to the `World` class to
allow saving and restoring world states. This requires components and
relationships to have human-readable names for stable serialization.
This commit is contained in:
2026-05-31 16:10:19 +08:00
parent d0bb119911
commit 1c55485f9f
8 changed files with 311 additions and 19 deletions
+9 -5
View File
@@ -5,13 +5,15 @@
*
* @example
* ```ts
* const Position = defineComponent({ x: 0, y: 0 });
* const Position = defineComponent('position', { x: 0, y: 0 });
* type Position = typeof Position.type;
* ```
*/
export interface ComponentDef<T extends Record<string, any>> {
/** Unique symbol used as the storage key. */
readonly _key: symbol;
/** Human-readable name, used for serialization. */
readonly name: string;
/** Default values applied when a component is first added. */
readonly defaults: T;
/** Phantom type for inference. */
@@ -19,15 +21,17 @@ export interface ComponentDef<T extends Record<string, any>> {
}
/**
* Define a component type. The argument provides both default values and the
* TypeScript shape.
* Define a component type. The name is used for serialization.
* The defaults object provides both the TypeScript shape and initial values.
*/
export function defineComponent<T extends Record<string, any>>(
defaults: T
name: string,
defaults: T,
): ComponentDef<T> {
return {
_key: Symbol(),
name,
defaults: { ...defaults },
type: undefined as unknown as T, // phantom; never read at runtime
type: undefined as unknown as T,
};
}