save family
Codecs, save schemas and migrations, save documents, byte storage, save slots and the settings store.
Most symbols on this page come from the package root, import { Name } from "gamekit";. The rest come from gamekit/src/save, as each entry shows.
26 symbols.
| Symbol | Summary |
|---|---|
canonicalizeValue | function. Recursively rebuilds objects with lexicographically sorted keys while preserving array order and scalar values. |
Codec | class. Extensible bidirectional boundary between a runtime type and JSON-compatible save data. |
CodecContext | class. Per-operation codec services and policy, including reference resolution and preserved unknown fields. |
Codecs | class. Factory namespace for primitive and compositional save codecs. |
FaultInjectingByteStorage | class. Test decorator that injects deterministic storage failures, partial writes, and corruption before delegating. |
FsByteStorage | class. FsByteStorage implements byte-oriented persistence for save documents and slots. |
IByteStorage | interface. Asynchronous text-blob storage boundary used by atomic save and settings workflows. |
inspectSaveDocument | function. Parses only a save envelope's positive integer version and optional string schema ID. |
MemoryByteStorage | class. Deterministic process-local IByteStorage for tests and ephemeral saves. |
MigrationStep | class. One consecutive schema migration with optional validation on both sides of its version boundary. |
RecordField | class. Declares one named field in a record codec, including decode presence and default rules. |
ReferencePolicy | enum. Chooses whether an unresolved persisted reference fails decoding (STRICT) or decodes as null (ALLOW_NULL). |
ReferenceResolver | class. Resolves persisted (kind, id) pairs to live objects from a local registry with an optional fallback. |
SaveDocument | class. In-memory representation of a versioned save envelope and its encoded payload. |
SaveDocumentHeader | class. Lightweight version and schema identity read without decoding a save payload. |
SaveResult | class. Non-throwing outcome for expected persistence, compatibility, and data-quality failures. |
SaveResultKind | enum. Distinguishes success, environmental unavailability, invalid data, version incompatibility, and unreadable serialization. |
SaveSchema | class. Versioned codec pipeline that canonicalizes writes and validates every consecutive migration boundary on reads. |
SaveSlotInfo | class. Listing result for one primary slot, including recoverability and metadata health. |
SaveSlotManager | class. Coordinates named, game-defined save documents over caller-provided byte storage. |
SaveSlotManagerOptions | class. Naming and rotation configuration for SaveSlotManager storage keys. |
SaveSlotMetadata | class. User-facing and schema metadata embedded beside a slot's encoded game data. |
serializeCanonical | function. Serializes JSON-compatible data after recursively sorting object keys. |
SettingsStore | class. Atomic single-document settings storage, separate from named game-save slots. |
SlotCancellationToken | class. Cooperative preflight cancellation flag for queued slot saves and loads. |
UnknownFieldPolicy | enum. Chooses whether record decoding rejects undeclared fields or preserves them in CodecContext for round trips. |
canonicalizeValue
ts
import { canonicalizeValue } from "gamekit";
function canonicalizeValue(val: any): anyRecursively rebuilds objects with lexicographically sorted keys while preserving array order and scalar values.
val: JSON-compatible value to normalize.- Returns: Detached arrays/objects suitable for deterministic serialization.
Codec
ts
import { Codec } from "gamekit";
class Codec<T>Extensible bidirectional boundary between a runtime type and JSON-compatible save data. The base implementation is an identity codec; concrete codecs validate decode input and report expected failures through SaveResult.
Members
ts
encode(value: T, context?: CodecContext): anyEncodes a runtime value; subclasses may consult resolver and preservation policy from the context.
value: Runtime value to encode.context: Optional per-operation reference and unknown-field state.
ts
decode(data: any, context?: CodecContext): SaveResult<T>Decodes persisted data; the base class accepts it unchanged.
data: JSON-compatible representation to decode.context: Optional resolver and preservation state shared by nested codecs.- Returns: Successful typed value or a categorized validation failure.
CodecContext
ts
import { CodecContext } from "gamekit";
class CodecContextPer-operation codec services and policy, including reference resolution and preserved unknown fields. Reuse the same context across decode and encode when PRESERVE must round-trip forward-compatible fields.
Members
ts
resolver: ReferenceResolver | nullRegistry consulted by reference codecs, or null when references cannot resolve.
ts
unknownFieldPolicy: UnknownFieldPolicyWhether record codecs reject or retain undeclared properties.
ts
referencePolicy: ReferencePolicyWhether unresolved references fail or become null.
ts
constructor( resolver: ReferenceResolver | null = null, unknownFieldPolicy: UnknownFieldPolicy = UnknownFieldPolicy.REJECT, referencePolicy: ReferencePolicy = ReferencePolicy.STRICT )Configures services shared by nested codec calls.
resolver: Reference registry, if the schema contains object identities.unknownFieldPolicy: Record behavior for undeclared properties.referencePolicy: Decode behavior for missing reference targets.
ts
setPreservedUnknownFields(id: string, fields: any): voidAssociates detached unknown-field data with a record identity for later encoding.
id: Record identity chosen by the record codec.fields: Undeclared field object to retain.
ts
getPreservedUnknownFields(id: string): anyLooks up unknown fields previously captured for a record identity.
id: Record identity used during decoding.- Returns: Preserved object, or
undefinedwhen none was captured.
Codecs
ts
import { Codecs } from "gamekit";
class CodecsFactory namespace for primitive and compositional save codecs.
Members
ts
static int(): Codec<int>Creates a codec accepting only finite integral JSON numbers.
ts
static float(): Codec<float>Creates a codec accepting finite JSON numbers.
ts
static string(): Codec<string>Creates a codec accepting string values.
ts
static boolean(): Codec<boolean>Creates a codec accepting boolean values.
ts
static id(): Codec<string>Creates a codec for non-empty string identifiers.
ts
static optional<T>(codec: Codec<T>): Codec<T | null>Wraps a codec so null round-trips without invoking the inner codec.
codec: Inner codec for non-null values.
ts
static array<T>(elementCodec: Codec<T>): Codec<T[]>Applies one codec to each array element in order and stops at the first decode failure.
elementCodec: Codec for every element.
ts
static record<T>( fields: RecordField[], factory: (fields: any) => T, extractor: ((val: T, fieldName: string) => any) | null = null ): Codec<T>Builds a record codec from declared fields and bidirectional value adapters.
fields: Ordered field definitions written to the record.factory: Creates a typed value from successfully decoded named fields.extractor: Optional(value, fieldName)reader; direct property access is the default.
ts
static taggedVariant<T>( tagField: string, variants: Map<string, Codec<any>>, tagExtractor: (value: T) => string ): Codec<T>Builds a discriminated-union codec using a tag persisted in each record.
tagField: Persisted discriminator property name.variants: Codecs indexed by accepted discriminator values.tagExtractor: Reads the discriminator from a runtime value during encode.
ts
static reference<T>(kind: string, idExtractor: (value: T) => string): Codec<T>Builds a codec that persists object identity and resolves it on load.
kind: Namespace supplied to the context resolver.idExtractor: Reads the stable identifier written during encode.
FaultInjectingByteStorage
ts
import { FaultInjectingByteStorage } from "gamekit";
class FaultInjectingByteStorage implements IByteStorageTest decorator that injects deterministic storage failures, partial writes, and corruption before delegating. One-shot flags clear only when their operation and optional path pattern match.
Members
ts
inner: IByteStorageUnderlying storage used whenever no fault intercepts the call.
ts
failNextWrite: boolean = falseOne-shot injected failure flag for the next matching write.
ts
failNextRename: boolean = falseOne-shot injected failure flag for the next matching rename.
ts
failNextRead: boolean = falseOne-shot injected failure flag for the next matching read.
ts
failNextCopy: boolean = falseOne-shot injected failure flag for the next matching copy.
ts
failNextRemove: boolean = falseOne-shot injected failure flag for the next matching remove.
ts
failNextExists: boolean = falseOne-shot injected failure flag for the next matching exists.
ts
failNextList: boolean = falseOne-shot injected failure flag for the next matching list.
ts
failPattern: string = ""Optional substring limiting path-sensitive one-shot faults; empty matches every path.
ts
quotaExceeded: boolean = falsePersistent flag making every matching write report quota exhaustion.
ts
storageMissing: boolean = falsePersistent flag making all storage operations report a missing device.
ts
partialWriteBytes: int = -1Non-negative one-shot character count written instead of complete content; -1 disables it.
ts
corruptOnWrite: boolean = falseOne-shot flag prefixing matching write content with an invalid marker.
ts
constructor(inner: IByteStorage)Wraps an existing storage implementation without copying its contents.
inner: Backend receiving non-intercepted calls.
ts
async read(path: string): Promise<SaveResult<string>>Injects missing-device or matching one-shot read failure before delegating.
path: Key tested againstfailPattern.
ts
async write(path: string, content: string): Promise<SaveResult<boolean>>Applies missing-device, quota, one-shot failure, partial-write, then corruption behavior in that priority.
path: Destination key tested againstfailPattern.content: Original complete content.
ts
async remove(path: string): Promise<SaveResult<boolean>>Injects missing-device or matching one-shot removal failure before delegating.
path: Key tested againstfailPattern.
ts
async exists(path: string): Promise<SaveResult<boolean>>Injects missing-device or matching one-shot existence failure before delegating.
path: Key tested againstfailPattern.
ts
async rename(oldPath: string, newPath: string): Promise<SaveResult<boolean>>Injects rename failure when either source or destination matches, then delegates otherwise.
oldPath: Source key.newPath: Rename destination participating in pattern matching.
ts
async copy(srcPath: string, destPath: string): Promise<SaveResult<boolean>>Injects copy failure when either key matches, then delegates otherwise.
srcPath: Source key.destPath: Copy destination participating in pattern matching.
ts
async list(prefix: string = ""): Promise<SaveResult<string[]>>Injects missing-device or one-shot listing failure before delegation; failPattern does not filter list faults.
prefix: Prefix forwarded to the underlying storage.
FsByteStorage
ts
import { FsByteStorage } from "gamekit/src/save";
class FsByteStorage implements IByteStorageFsByteStorage implements byte-oriented persistence for save documents and slots.
Members
ts
baseDir: stringDirectory used to resolve relative storage paths.
ts
constructor(baseDir: string)Initializes a fs byte storage with explicit dependencies.
baseDir: Directory prepended to relative paths; absolute paths bypass it.
ts
async read(path: string): Promise<SaveResult<string>>FsByteStorage Reads bytes from the requested location.
path: Source file as an absolute path or relative tobaseDir.- Returns: File contents, or an unavailable result when the file is absent or unreadable.
ts
async write(path: string, content: string): Promise<SaveResult<boolean>>FsByteStorage Persists the supplied bytes at the requested location.
path: Destination file as an absolute path or relative tobaseDir.content: Text payload written after creating missing parent directories.- Returns: Success with true, or an unavailable result describing the filesystem error.
ts
async remove(path: string): Promise<SaveResult<boolean>>FsByteStorage Removes the current value if it is registered.
path: Entry to remove, resolved againstbaseDirwhen relative.- Returns: Success with true even when the path is already absent; filesystem failures are unavailable results.
ts
async exists(path: string): Promise<SaveResult<boolean>>FsByteStorage Reports whether the requested persisted entry exists.
path: Entry to query, resolved againstbaseDirwhen relative.- Returns: Success containing the existence flag, or an unavailable result if the check fails.
ts
async rename(oldPath: string, newPath: string): Promise<SaveResult<boolean>>Moves one entry, creating the destination's parent directories first.
oldPath: Existing absolute path or path relative tobaseDir.newPath: Destination absolute path or path relative tobaseDir.- Returns: Success with true, or an unavailable result describing the filesystem error.
ts
async copy(srcPath: string, destPath: string): Promise<SaveResult<boolean>>FsByteStorage Returns a detached copy safe to retain independently.
srcPath: Existing absolute path or path relative tobaseDir.destPath: Destination absolute path or path relative tobaseDir.- Returns: Success with true, or an unavailable result describing the filesystem error.
ts
async list(prefix: string = ""): Promise<SaveResult<string[]>>Lists direct entries in baseDir in lexical order.
prefix: Optional filename prefix; an empty string includes every entry.- Returns: Matching entry names, an empty list for a missing directory, or an unavailable result on failure.
IByteStorage
ts
import { IByteStorage } from "gamekit";
interface IByteStorageAsynchronous text-blob storage boundary used by atomic save and settings workflows. Environmental failures are returned as SaveResult rather than thrown. Paths are opaque keys to non-filesystem implementations.
Members
ts
read(path: string): Promise<SaveResult<string>>Reads the complete text blob at a path.
path: Storage-relative key.- Returns: Content or
UNAVAILABLEwhen it cannot be read.
ts
write(path: string, content: string): Promise<SaveResult<boolean>>Replaces or creates a complete text blob.
path: Destination storage key.content: Exact text to persist.
ts
remove(path: string): Promise<SaveResult<boolean>>Removes a blob; implementations may treat an absent path as success.
path: Storage key to remove.
ts
exists(path: string): Promise<SaveResult<boolean>>Checks path presence without reading content.
path: Storage key to test.
ts
rename(oldPath: string, newPath: string): Promise<SaveResult<boolean>>Moves one blob to a new key for final atomic replacement where the backend supports it.
oldPath: Source key that must exist.newPath: Destination key to replace.
ts
copy(srcPath: string, destPath: string): Promise<SaveResult<boolean>>Copies source content to a second key without removing the source.
srcPath: Source key to read without removal.destPath: Destination key to replace.
ts
list(prefix?: string): Promise<SaveResult<string[]>>Lists storage keys beginning with an optional prefix.
prefix: Key prefix, or empty/omitted for all entries.- Returns: Matching keys; deterministic implementations should sort them.
inspectSaveDocument
ts
import { inspectSaveDocument } from "gamekit";
function inspectSaveDocument(text: string): SaveResult<SaveDocumentHeader>Parses only a save envelope's positive integer version and optional string schema ID.
text: Candidate JSON document.- Returns: Header without touching payload data, or
CORRUPT/MALFORMEDfor invalid input.
MemoryByteStorage
ts
import { MemoryByteStorage } from "gamekit";
class MemoryByteStorage implements IByteStorageDeterministic process-local IByteStorage for tests and ephemeral saves. Paths map directly to strings; all operations resolve immediately and listings are sorted.
Members
ts
async read(path: string): Promise<SaveResult<string>>Reads the exact string associated with a key.
path: In-memory key.- Returns: Content or
UNAVAILABLEwhen absent.
ts
async write(path: string, content: string): Promise<SaveResult<boolean>>Creates or replaces one in-memory entry.
path: Key to create or replace.content: Exact string to retain.
ts
async remove(path: string): Promise<SaveResult<boolean>>Deletes a key and succeeds even when it was absent.
path: Key to delete.
ts
async exists(path: string): Promise<SaveResult<boolean>>Reports map membership without reading the value.
path: Key to test.
ts
async rename(oldPath: string, newPath: string): Promise<SaveResult<boolean>>Moves content and replaces any destination entry.
oldPath: Key whose entry is moved.newPath: Key receiving the moved entry.- Returns:
UNAVAILABLEif the source is absent.
ts
async copy(srcPath: string, destPath: string): Promise<SaveResult<boolean>>Duplicates content to a destination key, replacing its old value.
srcPath: Key whose string is duplicated.destPath: Key receiving the duplicate.- Returns:
UNAVAILABLEif the source is absent.
ts
async list(prefix: string = ""): Promise<SaveResult<string[]>>Returns matching keys in lexical order.
prefix: Optional prefix filter.
ts
clear(): voidDeletes every in-memory entry synchronously.
MigrationStep
ts
import { MigrationStep } from "gamekit";
class MigrationStepOne consecutive schema migration with optional validation on both sides of its version boundary.
Members
ts
sourceVersion: intVersion accepted before migration.
ts
targetVersion: intVersion produced after migration; always sourceVersion + 1.
ts
migrateFn: (data: any) => anySynchronous transform from source-shaped data to target-shaped data.
ts
validateSourceFn: ((data: any) => SaveResult<boolean>) | nullOptional validation run immediately before the transform.
ts
validateTargetFn: ((data: any) => SaveResult<boolean>) | nullOptional validation run immediately after the transform.
ts
constructor( sourceVersion: int, targetVersion: int, migrateFn: (data: any) => any, validateSourceFn: ((data: any) => SaveResult<boolean>) | null = null, validateTargetFn: ((data: any) => SaveResult<boolean>) | null = null )Defines a single n -> n+1 migration boundary.
sourceVersion: Input document version.targetVersion: Exactly the next integer version.migrateFn: Transform returning non-null target data.validateSourceFn: Optional source-shape validator.validateTargetFn: Optional target-shape validator.- Throws: Error unless target is exactly one greater than source.
RecordField
ts
import { RecordField } from "gamekit";
class RecordFieldDeclares one named field in a record codec, including decode presence and default rules.
Members
ts
name: stringPersisted property name.
ts
codec: Codec<any>Codec applied to this property's runtime and serialized values.
ts
required: booleanWhether a missing property is a malformed decode.
ts
defaultValue: anyRuntime value supplied when an optional property is absent.
ts
constructor(name: string, codec: Codec<any>, required: boolean = true, defaultValue: any = null)Defines record behavior for one property.
name: Persisted key.codec: Value codec for the key.required: Whether absence fails decoding.defaultValue: Value used when a non-required key is absent.
ReferencePolicy
ts
import { ReferencePolicy } from "gamekit";
enum ReferencePolicyChooses whether an unresolved persisted reference fails decoding (STRICT) or decodes as null (ALLOW_NULL).
| Member | Meaning |
|---|---|
STRICT = 0 | Fail decoding when a referenced value cannot be resolved. |
ALLOW_NULL = 1 | Represent an unresolved reference as null. |
ReferenceResolver
ts
import { ReferenceResolver } from "gamekit";
class ReferenceResolverResolves persisted (kind, id) pairs to live objects from a local registry with an optional fallback.
Members
ts
constructor(fallbackResolver: ((kind: string, id: string) => any) | null = null)Creates an empty local registry.
fallbackResolver: Optional(kind, id)lookup used only after a local miss.
ts
register(kind: string, id: string, target: any): voidRegisters or replaces the local target for one namespaced identity.
kind: Reference namespace.id: Stable identifier within that namespace.target: Live object returned by later resolution.
ts
resolve(kind: string, id: string): anyResolves locally first, then delegates to the fallback.
kind: Reference namespace to search.id: Stable identity within the namespace.- Returns: Registered/fallback target, or
nullwhen unresolved.
ts
has(kind: string, id: string): booleanTests only the local registry without invoking the fallback.
kind: Local reference namespace.id: Identity to test.
SaveDocument
ts
import { SaveDocument } from "gamekit";
class SaveDocumentIn-memory representation of a versioned save envelope and its encoded payload.
Members
ts
version: intPositive schema version describing data.
ts
schemaId: stringSchema identity, or an empty string for legacy/unidentified documents.
ts
data: anyCodec-produced JSON-compatible payload.
ts
constructor(version: int, data: any, schemaId: string = "")Wraps already encoded data; validation is performed by SaveSchema.load.
version: Schema version of the payload.data: Encoded payload.schemaId: Optional schema identity.
SaveDocumentHeader
ts
import { SaveDocumentHeader } from "gamekit";
class SaveDocumentHeaderLightweight version and schema identity read without decoding a save payload.
Members
ts
version: intPositive version declared by the envelope.
ts
schemaId: stringDeclared schema identity, or empty when absent/non-string.
ts
constructor(version: int, schemaId: string = "")Captures inspected envelope metadata.
version: Validated positive document version.schemaId: Optional schema identity.
SaveResult
ts
import { SaveResult } from "gamekit";
class SaveResult<T>Non-throwing outcome for expected persistence, compatibility, and data-quality failures. Successful results carry value; failures carry kind, message, and the version boundary where known.
Members
ts
isOk: booleantrue only when value contains the requested result.
ts
value: anySuccessful payload, or null for factory-created failures.
ts
kind: SaveResultKindMachine-readable outcome category.
ts
message: stringHuman-readable diagnostic for a failed operation.
ts
version: intDocument or migration version associated with the outcome; zero means unavailable.
ts
constructor(isOk: boolean, value: any, kind: SaveResultKind, message: string, version: int = 0)Creates an explicit outcome record; prefer the named factories at call sites.
isOk: Success flag governing whethervalueis meaningful.value: Decoded value or operation payload.kind: Stable outcome category.message: Human-readable diagnostic, normally empty on success.version: Relevant schema version, or zero when unknown.
ts
static ok<T>(value: any, version: int = 0): SaveResult<T>Creates a successful result with kind OK and no diagnostic message.
value: Successful payload.version: Schema version attached to the payload.
ts
static unavailable<T>(message: string, version: int = 0): SaveResult<T>Reports missing storage, missing slots, cancellation, or environmental I/O failure.
message: Diagnostic suitable for logs or UI translation.version: Known document version, if any.
ts
static malformed<T>(message: string, version: int = 0): SaveResult<T>Reports a structurally valid envelope whose fields, validation, or migration data are invalid.
message: Description of the rejected shape or boundary.version: Version at which validation failed.
ts
static incompatible<T>(message: string, version: int = 0): SaveResult<T>Reports a schema ID/version mismatch or missing migration path.
message: Compatibility explanation.version: Document or boundary version that cannot be consumed.
ts
static corrupt<T>(message: string, version: int = 0): SaveResult<T>Reports unreadable serialization or a non-object save envelope.
message: Parse or envelope diagnostic.version: Known version, normally zero when parsing failed.
SaveResultKind
ts
import { SaveResultKind } from "gamekit";
enum SaveResultKindDistinguishes success, environmental unavailability, invalid data, version incompatibility, and unreadable serialization.
| Member | Meaning |
|---|---|
OK = "ok" | The operation completed with a value. |
UNAVAILABLE = "unavailable" | Environment or storage access prevented the operation. |
MALFORMED = "malformed" | The data does not match its expected encoding. |
INCOMPATIBLE = "incompatible" | The data version cannot be read by this schema. |
CORRUPT = "corrupt" | Persisted bytes are damaged or incomplete. |
SaveSchema
ts
import { SaveSchema } from "gamekit";
class SaveSchema<T>Versioned codec pipeline that canonicalizes writes and validates every consecutive migration boundary on reads. Expected document failures return SaveResult; constructor/registration misuse throws.
Members
ts
schemaId: stringIdentity compared with non-empty document schema IDs.
ts
currentVersion: intPositive version written by dump and reached by all migration paths.
ts
codec: Codec<T>Codec applied after migration on load and before envelope creation on dump.
ts
constructor(schemaId: string, currentVersion: int, codec: Codec<T>)Creates a schema with no historical migration steps or validators.
schemaId: Expected envelope identity; empty accepts unidentified documents.currentVersion: Positive version for new writes.codec: Runtime payload codec.- Throws: Error if current version is not positive.
ts
addMigration(step: MigrationStep): voidRegisters one migration keyed by its source version.
step: Consecutive boundary used when loading that source version.- Throws: Error if a step for the source version already exists.
ts
addValidator(version: int, validator: (data: any) => SaveResult<boolean>): voidRegisters a validation callback for one historical schema version.
version: Document version whose encoded payload shape is checked.validator: Callback returning a success or diagnostic failure.
ts
inspect(text: string): SaveResult<SaveDocumentHeader>Reads version and schema ID without checking this schema's identity or decoding payload data.
text: Candidate JSON envelope.- Returns: Header metadata or categorized parse/shape failure.
ts
dump(value: T, context?: CodecContext, pretty: boolean = false): SaveResult<string>Encodes a runtime value into a canonical current-version envelope.
value: Runtime payload to persist.context: Optional reference and unknown-field state passed to the codec.pretty: Whether to emit two-space-indented canonical JSON.- Returns: Successful JSON text tagged with
currentVersion.
ts
load(text: string, context?: CodecContext): SaveResult<T>Parses an envelope, verifies identity/version, migrates consecutively with before-and-after validation, then decodes.
text: Candidate save JSON.context: Optional services shared through nested decode calls.- Returns: Current-version value, or
CORRUPT,MALFORMED, orINCOMPATIBLEwithout throwing expected data failures.
SaveSlotInfo
ts
import { SaveSlotInfo } from "gamekit";
class SaveSlotInfoListing result for one primary slot, including recoverability and metadata health.
Members
ts
slotId: stringLogical slot name without storage extensions.
ts
metadata: SaveSlotMetadata | nullParsed primary-or-backup metadata, or null when inspection failed.
ts
hasBackup: booleanWhether a backup blob exists for possible recovery.
ts
isCorrupt: booleanWhether metadata inspection failed for the listed slot.
ts
constructor( slotId: string, metadata: SaveSlotMetadata | null, hasBackup: boolean = false, isCorrupt: boolean = false )Captures one detached slot-list entry.
slotId: Name represented by this listing entry.metadata: Parsed metadata when available.hasBackup: Backup-presence flag.isCorrupt: Inspection-failure flag.
SaveSlotManager
ts
import { SaveSlotManager } from "gamekit";
class SaveSlotManager<T>Coordinates named, game-defined save documents over caller-provided byte storage. One manager owns its per-slot operation queues until shutdown; schemas and storage remain supplied by the game.
Members
ts
storage: IByteStorageByte storage receiving primary, temporary, and backup blobs.
ts
schema: SaveSchema<T>Current codec and migration pipeline for slot payloads.
ts
extension: stringPrimary key suffix.
ts
tempExtension: stringSibling temporary-write suffix.
ts
backupExtension: stringPrevious-primary backup suffix.
ts
maxAutosaves: intAutosave ring cardinality.
ts
autosavePrefix: stringPrefix for zero-based autosave names.
ts
constructor( storage: IByteStorage, schema: SaveSchema<T>, options?: any )Creates independent per-slot queues and an autosave cursor at index zero.
storage: Backend used for every blob operation.schema: Current payload schema.options: Optional suffix, autosave size, and prefix overrides.
ts
async shutdown(): Promise<void>Rejects new saves/loads/inspections and waits for all already queued slot operations to settle.
ts
async saveSlot( slotId: string, data: T, metadata?: any, cancelToken?: SlotCancellationToken ): Promise<SaveResult<SaveSlotMetadata>>Serializes behind prior work for the same slot, then writes temp, validates, backs up, and atomically renames.
slotId: Logical name used to derive storage keys.data: Runtime payload encoded by the schema codec.metadata: Metadata instance or partial metadata object; missing schema fields are filled.cancelToken: Optional token checked when queued work begins.- Returns: Final metadata on success, otherwise a categorized storage or validation failure.
ts
async loadSlot( slotId: string, cancelToken?: SlotCancellationToken ): Promise<SaveResult<T>>Loads through the schema after earlier work for this slot, falling back to backup and restoring primary when recovery succeeds.
slotId: Slot to load from primary or backup.cancelToken: Optional token checked before storage access.- Returns: Decoded current-version payload or the primary failure when recovery fails.
ts
async inspectSlot( slotId: string ): Promise<SaveResult<SaveSlotMetadata>>Reads metadata without decoding game data, trying backup after any primary inspection failure.
slotId: Logical slot name serialized behind work for the same slot.- Returns: Parsed primary or backup metadata.
ts
async listSlots(): Promise<SaveResult<SaveSlotInfo[]>>Lists primary slot keys, inspects their metadata, and returns entries sorted by slot ID.
- Returns: Slot information including backup presence and corruption flags.
ts
async deleteSlot(slotId: string): Promise<SaveResult<boolean>>Serially requests removal of a slot's primary, temporary, and backup blobs.
slotId: Slot whose three derived keys are removed.- Returns: Success after all removal attempts; individual removal results are intentionally ignored.
ts
async rotateAutosave(data: T, metadata?: any): Promise<SaveResult<SaveSlotMetadata>>Advances the in-memory round-robin cursor and saves to <prefix><index>.
data: Runtime payload for the chosen autosave slot.metadata: Optional display and timestamp metadata.- Returns: The delegated slot-save result.
ts
async latestAutosave(): Promise<SaveResult<SaveSlotMetadata>>Inspects the configured autosave ring and selects the greatest metadata timestamp.
- Returns: Latest readable metadata, or
UNAVAILABLEwhen none can be inspected.
SaveSlotManagerOptions
ts
import { SaveSlotManagerOptions } from "gamekit";
class SaveSlotManagerOptionsNaming and rotation configuration for SaveSlotManager storage keys.
Members
ts
extension: string = ".sav"Primary slot suffix, default .sav.
ts
tempExtension: string = ".tmp"Sibling temporary-write suffix, default .tmp.
ts
backupExtension: string = ".bak"Previous-primary backup suffix, default .bak.
ts
maxAutosaves: int = 3Number of names in the round-robin autosave ring.
ts
autosavePrefix: string = "autosave_"Prefix placed before the zero-based autosave ring index.
ts
constructor( extension: string = ".sav", tempExtension: string = ".tmp", backupExtension: string = ".bak", maxAutosaves: int = 3, autosavePrefix: string = "autosave_" )Supplies storage naming defaults and autosave ring size.
extension: Primary suffix.tempExtension: Temporary suffix.backupExtension: Backup suffix.maxAutosaves: Autosave ring cardinality.autosavePrefix: Autosave name prefix.
SaveSlotMetadata
ts
import { SaveSlotMetadata } from "gamekit";
class SaveSlotMetadataUser-facing and schema metadata embedded beside a slot's encoded game data.
Members
ts
slotId: stringLogical slot name without file suffixes.
ts
schemaId: stringSchema identity recorded at save time.
ts
version: intPayload schema version recorded at save time.
ts
timestamp: intGame-supplied integer timestamp used to choose the latest autosave.
ts
playTime: floatGame-supplied play duration, conventionally in seconds.
ts
title: stringDisplay label for save-selection UI.
ts
custom: anyGame-defined JSON-compatible metadata; null construction input becomes an empty object.
ts
constructor( slotId: string = "", schemaId: string = "", version: int = 1, timestamp: int = 0, playTime: float = 0.0, title: string = "", custom: any = null )Builds metadata without imposing clock or presentation conventions.
slotId: Name embedded in the slot envelope.schemaId: Save schema identity.version: Payload version.timestamp: Comparable game-selected timestamp.playTime: Game-selected duration.title: Human-readable slot label.custom: Additional JSON-compatible fields.
serializeCanonical
ts
import { serializeCanonical } from "gamekit";
function serializeCanonical(value: any, pretty: boolean = false): stringSerializes JSON-compatible data after recursively sorting object keys.
value: Data to canonicalize and encode.pretty: Whether to indent with two spaces; compact output is the default.- Returns: Deterministic JSON text for equivalent values.
SettingsStore
ts
import { SettingsStore } from "gamekit";
class SettingsStore<T>Atomic single-document settings storage, separate from named game-save slots. Writes use temp validation, backup, and rename; loads recover a valid backup and restore primary.
Members
ts
storage: IByteStorageBackend holding primary, temporary, and backup settings blobs.
ts
filename: stringPrimary settings storage key.
ts
schema: SaveSchema<T>Codec and migration pipeline for the settings payload.
ts
tempFilename: stringSibling temporary key derived as <filename>.tmp.
ts
backupFilename: stringPrevious-primary key derived as <filename>.bak.
ts
constructor( storage: IByteStorage, filename: string = "settings.json", schema: SaveSchema<T> )Derives sibling temp and backup names from the primary key.
storage: Backend for all settings blobs.filename: Primary key, defaulting tosettings.json.schema: Versioned settings schema.
ts
async save(settings: T): Promise<SaveResult<boolean>>Encodes settings, validates a sibling temporary blob, backs up an existing primary, then renames the temp.
settings: Runtime settings value.- Returns: Success at the schema's current version, or a categorized encode/storage/validation failure.
ts
async load(): Promise<SaveResult<T>>Loads and migrates primary settings, or recovers a valid backup and copies it back to primary.
- Returns: Decoded settings; if recovery fails, the original primary failure is retained.
ts
async hasSettings(): Promise<boolean>Returns true only when the primary key's existence check succeeds and reports presence.
ts
async clear(): Promise<SaveResult<boolean>>Requests removal of primary, temp, and backup settings blobs.
- Returns: Success after all attempts; individual removal failures are intentionally ignored.
SlotCancellationToken
ts
import { SlotCancellationToken } from "gamekit";
class SlotCancellationTokenCooperative preflight cancellation flag for queued slot saves and loads. Cancellation is checked when an operation reaches the front of its per-slot queue, not during storage I/O already underway.
Members
ts
cancel(): voidPermanently marks the token cancelled; repeated calls are inert.
ts
get isCancelled(): booleanIs true after cancellation has been requested.
UnknownFieldPolicy
ts
import { UnknownFieldPolicy } from "gamekit";
enum UnknownFieldPolicyChooses whether record decoding rejects undeclared fields or preserves them in CodecContext for round trips.
| Member | Meaning |
|---|---|
REJECT = 0 | Fail decoding when an undeclared field is present. |
PRESERVE = 1 | Retain undeclared fields for a later round trip. |