Skip to content

@web-engine-dev/serialization

Schema-based binary and JSON serialization for game engines. Supports versioning, upgrades, and circular reference handling.

Features

  • Schema-Based: Define schemas matching ECS component types
  • Binary Encoding: Efficient MessagePack-inspired format
  • JSON Encoding: Human-readable with extended type support
  • Versioning: Schema versions and automatic upgrades
  • Circular References: Automatic reference handling
  • TypedArray Support: Efficient numeric array encoding

Installation

bash
npm install @web-engine-dev/serialization
# or
pnpm add @web-engine-dev/serialization

Quick Start

typescript
import {
  defineSchema,
  objectOf,
  arrayOf,
  toBinary,
  fromBinary,
  toJson,
  fromJson,
} from '@web-engine-dev/serialization';

// Define a schema
const PlayerSchema = defineSchema(
  'Player',
  objectOf({
    name: 'string',
    position: objectOf({ x: 'f32', y: 'f32', z: 'f32' }),
    health: 'i32',
    inventory: arrayOf('string'),
  })
);

// Create data
const player = {
  name: 'Hero',
  position: { x: 0, y: 1, z: 0 },
  health: 100,
  inventory: ['sword', 'shield'],
};

// Serialize to binary
const binary = toBinary(player, PlayerSchema);

// Serialize to JSON
const json = toJson(player, PlayerSchema, true);

// Deserialize
const restored = fromBinary(binary, PlayerSchema);
const restored2 = fromJson(json, PlayerSchema);

API Reference

Schema Definition

FunctionDescription
defineSchemaDefine a named schema
objectOf()Object type with properties
arrayOf()Array of type
mapOf()Map with key/value types
optional()Optional property
refTo()Reference to another schema
enumOf()Enum type

Primitive Types

TypeDescription
i8Signed 8-bit integer
i16Signed 16-bit
i32Signed 32-bit
u8Unsigned 8-bit
u16Unsigned 16-bit
u32Unsigned 32-bit
f3232-bit float
f6464-bit float
stringUTF-8 string
boolBoolean

Serialization Functions

typescript
// Binary
const bytes = toBinary(data, schema);
const data = fromBinary(bytes, schema);

// JSON
const json = toJson(data, schema, pretty?);
const data = fromJson(json, schema);

Schema Registry

typescript
import { globalSchemaRegistry } from '@web-engine-dev/serialization';

globalSchemaRegistry.register(MySchema);
const schema = globalSchemaRegistry.get('MySchema');

Versioning

typescript
const SchemaV2 = defineSchema(
  'Player',
  objectOf({
    name: 'string',
    position: objectOf({ x: 'f32', y: 'f32', z: 'f32' }),
    health: 'i32',
    maxHealth: 'i32', // New field
  }),
  {
    version: 2,
    upgrades: {
      1: (data) => ({ ...data, maxHealth: 100 }),
    },
  }
);

Circular References

typescript
const NodeSchema = defineSchema(
  'Node',
  objectOf({
    name: 'string',
    parent: optional(refTo('Node')),
    children: arrayOf(refTo('Node')),
  })
);

// Circular references are automatically handled

Proprietary software. All rights reserved.