Skip to content

core family ​

Entities, keys, events and pipelines, attributes and state machines, effects, definitions and prefabs, conditions, actions and interactions, assets, 2D spatial types, gauges and weighted picks.

Every symbol on this page is exported from the package root: import { Name } from "gamekit";

80 symbols.

SymbolSummary
Actionclass. Executes validation, transactional mutations, rollback, and post-commit notifications in fixed order.
ActionContextclass. Per-execution request view and staging area shared by action validation and commit callbacks.
ActionMutationclass. Named reversible unit of commit work with explicit applied state.
ActionRequestclass. Immutable-by-convention invocation data for a named Action.
ActionResultclass. Terminal action status with output, diagnostics, and mutation history available for compensation.
ActionSequenceclass. Executes action/request pairs in order and can compensate earlier commits after a later failure.
ActionSequenceResultclass. Terminal status and per-step results from an ActionSequence execution.
ActionSequenceStepclass. Binds one Action to the request used when its sequence reaches that step.
ActionStatusenum. Defines the closed action status value set.
AssetCancellationTokenclass. Cooperative cancellation flag observed between entries of an AssetLoadPlan.
AssetFailureclass. Captures one failed or dependency-blocked asset-plan entry.
AssetHandleclass. Retains one loaded asset until its owner releases the handle.
AssetKeyclass. Identifies one typed asset independently of its diagnostic label.
AssetLoadPlanclass. Mutable dependency graph of asset keys with per-entry loader, weight, and retry policy.
AssetLoadProgressclass. Mutable progress snapshot passed to an AssetManager plan callback after each outcome.
AssetManagerclass. Selects loaders, coalesces in-flight work, caches values, and unloads them after the final handle releases.
AssetPlanEntryclass. One asset-plan node with dependency identities and load policy.
AssetPlanResultclass. Aggregate handles, failures, counts, and cancellation state from one plan run.
AssetScopeclass. Groups asset handles so a scene, screen, or other owner can release them together.
Attributeclass. Lazily computes a value from a base or dependency set, then applies ordered modifiers and a final clamp.
AttributeInspectionclass. Point-in-time diagnostic snapshot of an Attribute after refresh.
AttributeModifierclass. Named pure transformation applied to an Attribute at an explicit priority.
AttributeSubscriptionclass. Idempotent lifetime handle for one Attribute change observer.
cloneValuefunction. Deep-copies arrays, maps, and object properties while preserving primitive values.
ComponentKeyclass. Identifies one component capability or ECS store independently of its label.
Conditionclass. Normalizes boolean, string, or ConditionResult evaluators into composable diagnostic outcomes.
ConditionResultclass. Normalized condition outcome with a primary explanation and optional aggregate reasons.
ContextKeyclass. Identifies a typed hierarchical context value without relying on string lookup.
CyclicDefinitionclass. Reports an inheritance cycle discovered while resolving definitions.
CyclicDependencyclass. Reports a directed dependency cycle, such as an asset load-plan loop.
Definitionclass. Immutable source definition with copied data and ordered parent ids.
DefinitionErrorclass. Adds definition identity and provenance to a registry resolution failure.
DefinitionRegistryclass. Resolves named definitions through ordered multiple inheritance and validator callbacks.
DuplicateRegistrationclass. Reports a second registration for an identity that must be unique.
EffectApplicationclass. Incoming typed effect payload and policy options passed through the application pipeline.
EffectCollectionclass. Owns effect handles, applies admission and stacking policy, and mirrors owner lifecycle callbacks.
EffectHandleclass. Stable handle controlling one effect's lifecycle, timer, and source cleanup.
EffectKeyclass. Identifies an effect kind and its typed payload across an entity's collection.
EffectOptionsclass. Optional collision, source-lifetime, and timed-expiration policy for an effect.
EffectRemovalReasonenum. Defines the closed effect removal reason value set.
EffectStackingclass. Factory for common collision policies consumed by EffectCollection.
EffectStackingContextclass. Collision-policy view of the incoming application and matching handles in insertion order.
EffectStackingResolutionclass. Policy decision naming accept, reject, replace, or refresh plus an optional retained handle.
EffectStateenum. Defines the closed effect state value set.
Entityclass. Owns a game object's hierarchy, local facts, components, and effects.
EntityAllocatorclass. Issues compact generational entity ids and recycles released slots without reviving stale handles.
EntityIdclass. Names one lifetime of an allocator slot using an index-and-generation pair.
EntityStateenum. Defines the closed entity state value set.
EntityTeardownQueueclass. Deduplicates deferred Entity disposal until an explicit FIFO flush boundary.
EventKeyclass. Identifies an event channel and statically carries the emitted payload type.
EventScopeclass. Owns typed local event listeners and delivers snapshot notifications in subscription order.
EventSubscriptionclass. Idempotent handle controlling one listener's lifetime in an EventScope.
FakeAssetLoaderclass. Deterministic in-memory loader with configurable failures, delays, and call-order inspection.
GameKitErrorclass. Base error type for GameKit style guide and lifecycle violations.
Gaugeclass. Neutral rate-filled value for cooldowns, charge bars and any meter that fills with time.
InteractionContextclass. Typed actor, target, and environment tuple shared across interaction discovery.
InteractionDefinitionclass. Builds one executable offer from context, optional availability logic, and metadata.
InteractionOfferclass. Point-in-time executable interaction choice produced during discovery.
InteractionProviderclass. Named discovery callback that produces zero or more offers for one context.
InteractionRegistryclass. Aggregates providers in registration order without imposing ranking or deduplication.
InvalidArgumentclass. Reports a public API argument that violates an immediate precondition.
InvalidDefinitionclass. Reports definition data that cannot be validated or resolved.
ISpatialIndexinterface. Defines deterministic identity-based insertion and broad-phase 2D spatial queries.
KeyedRegistryclass. Associates heterogeneous values with exact typed-key identities in registration order.
LinearSpatialIndexclass. Simple insertion-ordered spatial index that linearly scans copied bounds.
mergeDatafunction. Recursively overlays plain objects and maps, while other values replace the base.
MissingRegistrationclass. Reports a required typed-key, component, or definition registration that is absent.
MutablePipelineclass. Runs mutable processing stages over one shared context snapshot in insertion order.
PipelineContextclass. Mutable per-run input, cancellation flag, and optional output shared by pipeline stages.
PipelineResultclass. Immutable-by-convention snapshot of a completed pipeline's cancellation and output state.
PipelineSubscriptionclass. Idempotent lifetime handle for one stage in a MutablePipeline.
Prefabclass. Reusable factory binding for one definition id in a specific registry.
ResolvedDefinitionclass. Fully merged definition data plus the ordered ids that contributed to it.
StaleHandleclass. Reports mutation through an entity or effect handle whose lifetime has ended.
StateMachineclass. Runs explicit named-state callbacks with guarded, FIFO transitions and optional clock scheduling.
StateMachineInspectionclass. Point-in-time diagnostic counters and lifecycle flags for a StateMachine.
StateMachineStateclass. Named state with optional owner callbacks for entry, exit, and fixed updates.
Transform2Dclass. Mutable 2D position, rotation, and scale value with no scene-graph ownership.
TypedKeyclass. Provides a process-unique, type-carrying identity for registries; labels are diagnostic only.
WeightedPickclass. Weighted choice over an injected Random, the only source of chance, so a seed gives a fixed sequence.

Action ​

ts
import { Action } from "gamekit";
class Action<TPayload, TData>

Executes validation, transactional mutations, rollback, and post-commit notifications in fixed order. Validation denial never mutates; commit failure rolls back applied mutations in reverse order.

Members

ts
id: string

Stable identifier for this Action.

ts
description: string

Human-readable explanation of this item.

ts
constructor(id: string, description: string = "")

Creates a named action with no conditions, validation stages, or commit callback.

ts
addCondition(condition: Condition<any>): Action<TPayload, TData>

Appends a precondition and returns this action for fluent configuration.

ts
precondition(condition: Condition<any>): Action<TPayload, TData>

Fluent alias for appending a condition.

ts
guard(condition: Condition<any>): Action<TPayload, TData>

Fluent alias for appending a condition.

ts
validate(stage: Function): Action<TPayload, TData>

Appends a validation callback that may deny through context or throw failure.

ts
onCommit(commitFn: Function): Action<TPayload, TData>

Replaces the callback that stages or applies commit work after validation.

ts
execute(request: ActionRequest<TPayload>, targetScope: EventScope | null = null): ActionResult<TData>

Runs conditions and validators, commits staged mutations, then emits notifications. Notification failures are isolated after a successful commit.

ActionContext ​

ts
import { ActionContext } from "gamekit";
class ActionContext<TPayload>

Per-execution request view and staging area shared by action validation and commit callbacks.

Members

ts
request: ActionRequest<TPayload>

Original request that owns this execution.

ts
actor: any

Actor reference copied from the request for callback convenience.

ts
target: any

Target reference copied from the request for callback convenience.

ts
payload: TPayload

Typed payload copied from the request.

ts
metadata: any

Auxiliary request metadata reference.

ts
constructor(request: ActionRequest<TPayload>)

Copies request fields and starts with no denial, output, mutations, or notifications.

ts
deny(reason: string): void

Marks validation denied and records the explanation returned to the caller.

ts
get isDenied(): boolean

Whether any validation callback has denied execution.

ts
get denialReason(): string

Latest explanation supplied to deny.

ts
produce(data: any): void

Replaces the successful result payload.

ts
get resultData(): any

Latest produced payload, or null when none was produced.

ts
stageMutation(id: string, apply: Function, rollback: Function | null = null): ActionMutation

Creates and appends an unapplied mutation for commit-order execution.

ts
addMutation(mutation: ActionMutation): void

Appends a prebuilt mutation to the commit sequence.

ts
get stagedMutations(): ActionMutation[]

Ordered mutation list consumed by Action after the commit callback.

ts
emitOnCommit(scope: EventScope, key: EventKey<any>, event: any): void

Queues an event fact for best-effort emission only after all mutations commit.

ts
get stagedNotifications(): ActionNotificationEntry[]

Ordered post-commit notification list consumed by Action.

ActionMutation ​

ts
import { ActionMutation } from "gamekit";
class ActionMutation

Named reversible unit of commit work with explicit applied state.

Members

ts
id: string

Stable identifier for this ActionMutation.

ts
apply: Function

Callback invoked once during forward commit.

ts
rollback: Function | null

Optional compensation callback invoked in reverse order.

ts
applied: boolean = false

Whether forward work remains eligible for rollback.

ts
constructor(id: string, apply: Function, rollback: Function | null = null)

Captures a non-empty diagnostic id and forward/optional compensation callbacks.

ActionRequest ​

ts
import { ActionRequest } from "gamekit";
class ActionRequest<TPayload>

Immutable-by-convention invocation data for a named Action.

Members

ts
actionId: string

Non-empty action identity expected by dispatching game code.

ts
actor: any

Game object initiating the action, or null.

ts
target: any

Game object receiving the action, or null.

ts
payload: TPayload

Typed action-specific input.

ts
metadata: any

Optional auxiliary data not interpreted by GameKit.

ts
constructor(actionId: string, actor: any = null, target: any = null, payload: TPayload = null, metadata: any = null)

Captures a non-empty action id and game-owned invocation values.

ActionResult ​

ts
import { ActionResult } from "gamekit";
class ActionResult<TData>

Terminal action status with output, diagnostics, and mutation history available for compensation.

Members

ts
status: ActionStatus

Committed, denied-before-commit, or failed-during-validation/commit.

ts
request: ActionRequest<any>

Original request associated with the execution.

ts
data: TData | null

Produced success payload, or null for denial/failure or no output.

ts
reason: string | null

Human-readable denial or failure explanation, when applicable.

ts
error: Error | null

Caught validation or commit exception, never notification errors.

ts
appliedMutations: ActionMutation[]

Forward mutations attempted before terminal completion.

ts
constructor( status: ActionStatus, request: ActionRequest<any>, data: TData | null = null, reason: string | null = null, error: Error | null = null, appliedMutations: ActionMutation[] = [] )

Captures terminal execution state without copying request or mutation references.

ts
get ok(): boolean

true only for a fully committed action.

ts
get isCommitted(): boolean

Whether validation and every mutation completed successfully.

ts
get isDenied(): boolean

Whether validation rejected execution before commit.

ts
get isFailed(): boolean

Whether a validator or commit callback threw.

ts
rollback(): void

Best-effort compensates still-applied mutations in reverse order; compensation errors are isolated.

ActionSequence ​

ts
import { ActionSequence } from "gamekit";
class ActionSequence

Executes action/request pairs in order and can compensate earlier commits after a later failure.

Members

ts
constructor(rollbackOnFailure: boolean = true)

Configures whether a denied or failed step rolls back earlier committed steps.

ts
add(action: Action<any, any>, request: ActionRequest<any>): ActionSequence

Appends an action and its request and returns this sequence for chaining.

ts
execute(targetScope: EventScope | null = null): ActionSequenceResult

Stops on the first non-commit and optionally rolls back prior results in reverse order.

ActionSequenceResult ​

ts
import { ActionSequenceResult } from "gamekit";
class ActionSequenceResult

Terminal status and per-step results from an ActionSequence execution.

Members

ts
status: ActionStatus

Overall status, inherited from the first unsuccessful step when present.

ts
executedCount: int

Number of steps attempted, including the unsuccessful step.

ts
results: ActionResult<any>[]

Ordered results for every attempted step.

ts
rolledBack: boolean

Whether compensation of prior committed steps was requested.

ts
failureReason: string | null

First denial or failure explanation, or null on complete commit.

ts
constructor( status: ActionStatus, executedCount: int, results: ActionResult<any>[], rolledBack: boolean, failureReason: string | null = null )

Captures sequence outcome and ordered step history.

ts
get ok(): boolean

true only when every step committed.

ActionSequenceStep ​

ts
import { ActionSequenceStep } from "gamekit";
class ActionSequenceStep

Binds one Action to the request used when its sequence reaches that step.

Members

ts
action: Action<any, any>

Executable action reference.

ts
request: ActionRequest<any>

Invocation passed to the action.

ts
constructor(action: Action<any, any>, request: ActionRequest<any>)

Captures the action/request pair without executing it.

ActionStatus ​

ts
import { ActionStatus } from "gamekit";
enum ActionStatus

Defines the closed action status value set. Store and compare these values directly rather than introducing string aliases;

MemberMeaning
COMMITTED = "committed"The requested mutations completed.
DENIED = "denied"Validation or a rule denied the request.
FAILED = "failed"Execution started but did not complete successfully.

AssetCancellationToken ​

ts
import { AssetCancellationToken } from "gamekit";
class AssetCancellationToken

Cooperative cancellation flag observed between entries of an AssetLoadPlan.

Members

ts
isCancelled: boolean = false

Whether cancellation has been requested.

ts
reason: string = ""

Latest game-supplied cancellation explanation.

ts
cancel(reason: string = "cancelled"): void

Permanently marks the token cancelled and records the reason.

AssetFailure ​

ts
import { AssetFailure } from "gamekit";
class AssetFailure

Captures one failed or dependency-blocked asset-plan entry.

Members

ts
key: AssetKey<any>

Asset whose load did not complete.

ts
message: string

Final human-readable failure explanation.

ts
error: any

Last thrown loader value, or null for dependency blocking.

ts
attempts: int

Loader invocations made; zero means a dependency blocked loading.

ts
trace: string[]

Per-attempt diagnostic lines in execution order.

ts
constructor(key: AssetKey<any>, message: string, error: any = null, attempts: int = 1, trace: string[] = [])

Captures the terminal failure details for plan inspection.

AssetHandle ​

ts
import { AssetHandle } from "gamekit";
class AssetHandle<T>

Retains one loaded asset until its owner releases the handle.

Members

ts
key: AssetKey<T>

Key of the asset retained by this handle.

ts
isReleased: boolean = false

Whether this handle has already dropped its manager reference.

ts
constructor(key: AssetKey<T>, manager: IAssetHandleManager<T>, scope: IAssetHandleScope | null = null)

Creates a handle managed by AssetManager; consumers normally receive one from load or acquire.

ts
get scope(): IAssetHandleScope | null

Scope that will release this handle, or null for an independently managed handle.

ts
get(): T

Reads the retained asset value while the handle remains live.

  • Throws: StaleHandle When this handle has been released.
ts
release(): void

Releases this handle's reference and detaches it from its scope. Repeated calls do nothing; the asset unloads when this is its final handle.

AssetKey ​

ts
import { AssetKey } from "gamekit";
class AssetKey<T> extends TypedKey<T>

Identifies one typed asset independently of its diagnostic label.

Members

ts
constructor(label: string)

Allocates a fresh asset identity with the label shown in diagnostics.

AssetLoadPlan ​

ts
import { AssetLoadPlan } from "gamekit";
class AssetLoadPlan

Mutable dependency graph of asset keys with per-entry loader, weight, and retry policy.

Members

ts
entries: Array<AssetPlanEntry> = []

Registration-ordered entries; adding an existing key replaces it in place.

ts
add<T>( key: AssetKey<T>, dependencies: Array<AssetKey<any>> = [], options: any = null ): AssetLoadPlan

Adds or replaces an entry, normalizing weight and retry values in AssetPlanEntry.

ts
has(key: AssetKey<any>): boolean

Tests membership by exact AssetKey identity.

ts
getEntry(key: AssetKey<any>): AssetPlanEntry | null

Returns the entry for exact key identity, or null when absent.

ts
validate(): void

Resolves dependency waves to detect cycles before any loader work begins.

ts
getTopologicalWaves(): Array<Array<AssetPlanEntry>>

Groups entries into dependency-ready waves while preserving registration order within each wave. Dependencies outside the plan are assumed already satisfied.

AssetLoadProgress ​

ts
import { AssetLoadProgress } from "gamekit";
class AssetLoadProgress

Mutable progress snapshot passed to an AssetManager plan callback after each outcome.

Members

ts
loadedCount: int = 0

Entries that acquired a handle successfully.

ts
totalCount: int = 0

Total entries declared by the plan.

ts
loadedWeight: int = 0

Sum of successful entry weights.

ts
totalWeight: int = 0

Sum of all normalized entry weights.

ts
ratio: float = 0.0

Successful weight divided by total weight, from zero through one.

ts
lastKey: AssetKey<any> | null = null

Most recently loaded key, or null before the first success.

ts
failedCount: int = 0

Entries failed or blocked by failed dependencies.

AssetManager ​

ts
import { AssetManager } from "gamekit";
class AssetManager implements IAssetHandleManager<any>, IAssetScopeManager

Selects loaders, coalesces in-flight work, caches values, and unloads them after the final handle releases. Create one manager for the asset domain that owns its loaders, then shut it down only after every scope has stopped requesting assets.

Members

ts
isShutdown: boolean = false

Whether this manager has stopped accepting new work.

ts
constructor(defaultLoader: any = null)

Starts an empty asset domain with an optional fallback loader.

ts
registerLoader<T>(key: AssetKey<T>, loader: any): void

Associates a loader with exact key identity, replacing any earlier association.

ts
setDefaultLoader(loader: any): void

Replaces the fallback selected when a key has no loader override.

ts
createScope(name: string = ""): AssetScope

Creates a scope that can release every handle it acquires together.

  • Throws: GameKitError When the manager has been shut down.
ts
unregisterScope(scope: IAssetHandleScope): void

Stops retaining a disposed scope; removing an unknown scope is harmless.

ts
isLoaded(key: AssetKey<any>): boolean

Tests whether a key has a completed cached record.

ts
getRefCount(key: AssetKey<any>): int

Returns live handles retaining the key, or zero when unloaded.

ts
getAssetValue<T>(key: AssetKey<T>): T

Returns a loaded asset without acquiring another handle.

  • Throws: MissingRegistration When the key has no loaded record.
ts
acquireHandle<T>(key: AssetKey<T>, scope: IAssetHandleScope | null = null): AssetHandle<T>

Acquires a retaining handle for an already loaded asset. The returned handle increments the reference count and is released directly or by its scope.

  • Throws: GameKitError When the manager is shut down.
  • Throws: MissingRegistration When the asset is not loaded.
ts
releaseHandle(key: AssetKey<any>, handle: any): void

Drops one known handle reference and unloads the record when its count reaches zero.

ts
replaceAsset<T>(key: AssetKey<T>, newAsset: T): void

Swaps a loaded value without invalidating handles, then best-effort unloads the old value.

ts
async acquireOrLoad<T>(key: AssetKey<T>, scope: IAssetHandleScope | null = null, customLoader: any = null): Promise<AssetHandle<T>>

Returns a retaining handle, loading the key when no cached record exists. Concurrent requests for the same key await one shared load and each receive its own handle.

  • Throws: GameKitError When the manager is shut down.
  • Throws: MissingRegistration When no loader can be selected.
ts
async load<T>(key: AssetKey<T>, options: any = null): Promise<AssetHandle<T>>

Acquires or loads one key using optional {scope, loader} overrides.

ts
async loadPlan(plan: AssetLoadPlan, options: any = null): Promise<AssetPlanResult>

Loads a validated dependency plan wave by wave and records all outcomes. A failed dependency blocks dependants; continueOnError controls later independent work.

ts
shutdown(): void

Stops new asset work, disposes active scopes, and unloads every cached record. In-flight promises are forgotten; do not use the manager after shutdown.

AssetPlanEntry ​

ts
import { AssetPlanEntry } from "gamekit";
class AssetPlanEntry

One asset-plan node with dependency identities and load policy.

Members

ts
key: AssetKey<any>

Asset identity loaded by this node.

ts
dependencies: Array<AssetKey<any>>

Keys that must succeed first when also present in the plan.

ts
loader: any

Optional loader override; null uses key-specific or manager default selection.

ts
weight: int

Relative contribution to aggregate progress.

ts
retries: int

Additional attempts after the initial load, clamped to zero or greater.

ts
constructor( key: AssetKey<any>, dependencies: Array<AssetKey<any>> = [], loader: any = null, weight: int = 1, retries: int = 0 )

Captures policy, coercing non-positive weight to one and negative retries to zero.

AssetPlanResult ​

ts
import { AssetPlanResult } from "gamekit";
class AssetPlanResult

Aggregate handles, failures, counts, and cancellation state from one plan run.

Members

ts
isOk: boolean = true

Remains true only when no entry failed and cancellation did not occur.

ts
isCancelled: boolean = false

Whether cooperative cancellation stopped traversal between entries.

ts
loadedCount: int = 0

Number of handles acquired successfully.

ts
failedCount: int = 0

Number of loader failures plus dependency-blocked entries.

ts
handles: Array<AssetHandle<any>> = []

Successful handles in plan execution order.

ts
failures: Array<AssetFailure> = []

Terminal failures in plan execution order.

ts
hasHandle(key: AssetKey<any>): boolean

Tests successful handle presence by exact key identity.

ts
getHandle<T>(key: AssetKey<T>): AssetHandle<T> | null

Returns the successful handle for a key, or null.

ts
getFailure(key: AssetKey<any>): AssetFailure | null

Returns the terminal failure for a key, or null.

ts
getFailureTrace(key: AssetKey<any>): string | null

Joins per-attempt trace lines, or returns null when the key did not fail.

AssetScope ​

ts
import { AssetScope } from "gamekit";
class AssetScope implements IAssetHandleScope

Groups asset handles so a scene, screen, or other owner can release them together.

Members

ts
name: string

Optional label used in diagnostics.

ts
isDisposed: boolean = false

Whether this resource has released its owned references.

ts
constructor(manager: IAssetScopeManager, name: string = "")

Creates a scope registered with an asset manager.

ts
async load<T>(key: AssetKey<T>): Promise<AssetHandle<T>>

Loads an asset and attaches the resulting handle to this scope. If disposal wins the asynchronous race, the returned handle is already released.

ts
acquire<T>(key: AssetKey<T>): AssetHandle<T>

Acquires an already loaded asset and records the handle in this scope.

  • Throws: GameKitError When the scope has been disposed.
ts
has(key: AssetKey<any>): boolean

Reports whether this live scope retains a handle for the key.

ts
get<T>(key: AssetKey<T>): T | null

Finds the retained value for a key without changing its reference count.

ts
getRequired<T>(key: AssetKey<T>): T

Finds a retained value and treats absence as a configuration error.

  • Throws: MissingRegistration When the scope has no live handle for the key.
ts
getHandle<T>(key: AssetKey<T>): AssetHandle<T> | null

Finds this scope's live handle for a key.

ts
release(key: AssetKey<any>): void

Disposes this scope and releases a snapshot of all of its handles. It unregisters itself after release; repeated calls are harmless.

ts
releaseAll(): void

Alias for releaseAll for owners that use disposable lifecycle terminology.

ts
dispose(): void

Disposable-lifecycle alias for releaseAll.

Attribute ​

ts
import { Attribute } from "gamekit";
class Attribute<T>

Lazily computes a value from a base or dependency set, then applies ordered modifiers and a final clamp. Changes notify a listener snapshot only after a successful recalculation.

Members

ts
constructor(baseValue: T, clamp: Function | null = null)

Starts dirty with a base value and optional final-value clamp.

ts
get value(): T

Recalculates when dirty and returns the cached effective value.

ts
get baseValue(): T

Unmodified source value; derived attributes retain it but do not read it.

ts
get dirty(): boolean

Whether the effective value requires recalculation.

ts
get recalculations(): int

Number of successful effective-value calculations.

ts
setBase(value: T): void

Replaces a non-derived base, recalculates immediately, and notifies on change.

ts
addModifier(modifier: AttributeModifier<T>): void

Adds a unique modifier, ordered by priority then insertion order, and recalculates.

ts
removeModifier(id: string): boolean

Removes a modifier by id and reports whether recalculation occurred.

ts
derive(dependencies: Attribute<any>[], calculate: Function): void

Replaces base calculation with a dependency snapshot callback and subscribes to dependency changes. Direct and transitive cycles are rejected before existing derivation state changes.

ts
clearDerived(): void

Drops dependency subscriptions and resumes calculation from the retained base value.

ts
subscribe(listener: Function): AttributeSubscription<T>

Appends a (next, previous) observer and returns its idempotent lifetime handle.

ts
inspect(): AttributeInspection<T>

Forces refresh and captures counts plus current base/effective values.

ts
removeSubscription(subscription: AttributeSubscription<T>): void

Deactivates an observer handle and removes it from future snapshots.

AttributeInspection ​

ts
import { AttributeInspection } from "gamekit";
class AttributeInspection<T>

Point-in-time diagnostic snapshot of an Attribute after refresh.

Members

ts
baseValue: T

Retained source value, even when derivation currently replaces it.

ts
value: T

Effective derived, modified, and clamped value.

ts
modifierCount: int

Number of transformations currently attached.

ts
dependencyCount: int

Number of attributes feeding a derived calculation.

ts
listenerCount: int

Number of active change observers.

ts
recalculations: int

Successful calculations since construction.

ts
dirty: boolean

Whether another read would need recalculation at capture time.

ts
constructor(baseValue: T, value: T, modifierCount: int, dependencyCount: int, listenerCount: int, recalculations: int, dirty: boolean)

Captures values and counters without retaining a reference to the Attribute.

AttributeModifier ​

ts
import { AttributeModifier } from "gamekit";
class AttributeModifier<T>

Named pure transformation applied to an Attribute at an explicit priority.

Members

ts
id: string

Stable identifier for this AttributeModifier.

ts
order: int

Ascending priority; equal priorities retain insertion order.

ts
apply: Function

Callback receiving the preceding effective value and returning the next value.

ts
constructor(id: string, order: int, apply: Function)

Captures a non-empty unique id, priority, and transformation callback.

AttributeSubscription ​

ts
import { AttributeSubscription } from "gamekit";
class AttributeSubscription<T>

Idempotent lifetime handle for one Attribute change observer.

Members

ts
active: boolean = true

Whether this AttributeSubscription still accepts work.

ts
constructor(owner: Attribute<T>, entry: AttributeListenerEntry<T>)

Binds the handle to its owner and private listener entry.

ts
dispose(): void

Removes the listener from future notifications; repeated calls do nothing.

ts
matches(entry: AttributeListenerEntry<T>): boolean

Tests private listener-entry identity during owner cleanup.

ts
deactivate(): void

Marks the handle inactive and drops its owner reference without re-entry.

cloneValue ​

ts
import { cloneValue } from "gamekit";
function cloneValue(val: any): any

Deep-copies arrays, maps, and object properties while preserving primitive values.

ComponentKey ​

ts
import { ComponentKey } from "gamekit";
class ComponentKey<T> extends TypedKey<T>

Identifies one component capability or ECS store independently of its label.

Members

ts
constructor(label: string)

Allocates a fresh component identity with the label shown in diagnostics.

Condition ​

ts
import { Condition } from "gamekit";
class Condition<TContext>

Normalizes boolean, string, or ConditionResult evaluators into composable diagnostic outcomes.

Members

ts
id: string

Stable identifier for this Condition.

ts
description: string

Human-readable explanation of this item.

ts
constructor(id: string, description: string, evaluator: Function)

Binds a non-empty diagnostic id and description to a context evaluator.

ts
evaluate(context: TContext): ConditionResult

Converts true or empty string to pass, false or non-empty string to failure, and preserves explicit results.

ts
and(other: Condition<TContext>, shortCircuit: boolean = true): Condition<TContext>

Builds a two-condition conjunction using a derived composite id.

ts
or(other: Condition<TContext>, shortCircuit: boolean = true): Condition<TContext>

Builds a two-condition disjunction using a derived composite id.

ts
not(failureReason: string = ""): Condition<TContext>

Builds an inverse condition with an optional reason for an unexpected pass.

ts
static all<T>(conditions: Condition<T>[], shortCircuit: boolean = true, id: string = "all"): Condition<T>

Builds a conjunction that either stops at the first failure or aggregates failure reasons.

ts
static any<T>(conditions: Condition<T>[], shortCircuit: boolean = true, id: string = "any"): Condition<T>

Builds a disjunction that can stop at the first pass and reports every failure when none pass.

ts
static not<T>(condition: Condition<T>, failureReason: string = "", id: string = "not"): Condition<T>

Builds a condition that passes only when the wrapped condition fails.

ConditionResult ​

ts
import { ConditionResult } from "gamekit";
class ConditionResult

Normalized condition outcome with a primary explanation and optional aggregate reasons.

Members

ts
passed: boolean

true when evaluation permits the guarded operation.

ts
conditionId: string

Identity of the decisive condition or composite.

ts
reason: string

Primary human-readable outcome explanation.

ts
reasons: string[]

Aggregate failure explanations; defaults to the primary reason when non-empty.

ts
constructor(passed: boolean, conditionId: string = "", reason: string = "", reasons: string[] = [])

Captures an outcome and normalizes its reason list.

ts
get ok(): boolean

Alias for passed used by result-oriented call sites.

ts
static pass(conditionId: string = "", reason: string = ""): ConditionResult

Creates a successful outcome with optional identity and explanation.

ts
static fail(conditionId: string, reason: string, reasons: string[] = []): ConditionResult

Creates a failed outcome, defaulting the aggregate list to the primary reason.

ContextKey ​

ts
import { ContextKey } from "gamekit";
class ContextKey<T> extends TypedKey<T>

Identifies a typed hierarchical context value without relying on string lookup.

Members

ts
constructor(label: string)

Allocates a fresh context identity with the label shown in diagnostics.

CyclicDefinition ​

ts
import { CyclicDefinition } from "gamekit";
class CyclicDefinition extends DefinitionError

Reports an inheritance cycle discovered while resolving definitions.

Members

ts
cycle: string[]

Ordered ids that form the detected cycle.

ts
constructor(message: string, cycle: string[] = [])

Uses the first cycle id as the inherited definition id when available.

CyclicDependency ​

ts
import { CyclicDependency } from "gamekit";
class CyclicDependency extends GameKitError

Reports a directed dependency cycle, such as an asset load-plan loop.

Members

ts
cycle: string[]

Ordered labels participating in the detected loop.

ts
constructor(message: string, cycle: string[] = [])

Retains the cycle alongside the human-readable message.

Definition ​

ts
import { Definition } from "gamekit";
class Definition

Immutable source definition with copied data and ordered parent ids.

Members

ts
readonly id: string

Stable identifier for this Definition.

ts
readonly inherits: string[]

Parent ids merged left to right before this definition's data.

ts
readonly data: any

Deep copy of the registered source data.

ts
constructor(id: string, data: any, inherits: string[] = [])

Validates non-empty ids and copies data plus the inheritance list.

DefinitionError ​

ts
import { DefinitionError } from "gamekit";
class DefinitionError extends GameKitError

Adds definition identity and provenance to a registry resolution failure.

Members

ts
definitionId: string

Definition id being resolved, or an empty string when no single id applies.

ts
provenance: string[]

Resolution path from the requested definition to the failure point.

ts
constructor(message: string, definitionId: string = "", provenance: string[] = [])

Captures a diagnostic message with optional definition and resolution path context.

DefinitionRegistry ​

ts
import { DefinitionRegistry } from "gamekit";
class DefinitionRegistry

Resolves named definitions through ordered multiple inheritance and validator callbacks. Every public resolution returns detached data and reports cycles or missing parents with provenance.

Members

ts
define(id: string, data: any, inherits: string[] = []): Definition

Constructs and registers a copied source definition.

ts
register(def: Definition): Definition

Registers one unique Definition by id and returns the same source object.

ts
has(id: string): boolean

Tests exact string-id registration without resolving parents.

ts
addValidator(validator: Function): void

Appends a validator run against each fully merged candidate.

ts
resolve(id: string): ResolvedDefinition

Resolves parents left to right, overlays child data, validates, and returns detached data.

ts
get(id: string): ResolvedDefinition | null

Returns a resolved snapshot, or null only when the requested root id is absent.

ts
getRequired(id: string): ResolvedDefinition

Returns a resolved snapshot and throws MissingRegistration when the root id is absent.

ts
instantiate(id: string, factory: Function, context: any = null): any

Resolves fresh data and invokes factory(resolvedDefinition, context).

ts
createPrefab(id: string, factory: Function): Prefab

Creates a reusable factory binding after verifying that the root id exists.

DuplicateRegistration ​

ts
import { DuplicateRegistration } from "gamekit";
class DuplicateRegistration extends GameKitError

Reports a second registration for an identity that must be unique.

Members

ts
definitionId: string

Conflicting definition or registration id, when one is available.

ts
provenance: string[]

Resolution or registration path that exposed the conflict.

ts
constructor(message: string, definitionId: string = "", provenance: string[] = [])

Captures optional identity and provenance context for diagnostics.

EffectApplication ​

ts
import { EffectApplication } from "gamekit";
class EffectApplication<T>

Incoming typed effect payload and policy options passed through the application pipeline.

Members

ts
key: EffectKey<T>

Effect identity used for collision and lookup.

ts
payload: T

Game-owned behavior or data being attached.

ts
options: EffectOptions<T>

Source, duration, scheduler, and stacking policy for this attempt.

ts
constructor(key: EffectKey<T>, payload: T, options: EffectOptions<T>)

Captures one pre-attachment request for pipeline inspection.

EffectCollection ​

ts
import { EffectCollection } from "gamekit";
class EffectCollection

Owns effect handles, applies admission and stacking policy, and mirrors owner lifecycle callbacks. Handles remain insertion ordered and terminal removal cleans timers plus source observation exactly once.

Members

ts
owner: IEffectOwner

Entity or game object passed to effect lifecycle callbacks.

ts
pipeline: MutablePipeline<EffectApplication<any>, any> = ...

Pre-admission pipeline that may cancel an application before collision policy.

ts
constructor(owner: IEffectOwner)

Starts an empty collection bound to one lifecycle owner.

ts
add<T>(key: EffectKey<T>, value: T, options: EffectOptions<T> | null = null): EffectHandle<T> | null

Runs admission, resolves same-key collisions, and enters the accepted effect into current owner lifecycle. Returns null for pipeline cancellation or policy rejection.

ts
get<T>(key: EffectKey<T>): EffectHandle<T>[]

Returns a new insertion-ordered array of live handles matching exact key identity.

ts
lifecycleEntries(): EffectHandle<any>[]

Returns a detached snapshot used to interleave effects with other owner capabilities.

ts
contains(effect: EffectHandle<any>): boolean

Tests exact handle identity, not key equivalence.

ts
activate(effect: EffectHandle<any>): void

Activates a currently retained handle; foreign or terminal handles are ignored.

ts
suspend(effect: EffectHandle<any>): void

Suspends a currently retained active handle; foreign handles are ignored.

ts
remove(effect: EffectHandle<any>, reason: EffectRemovalReason = EffectRemovalReason.REMOVED): void

Terminally removes a retained handle and emits lifecycle callbacks for the stated reason.

ts
expire(effect: EffectHandle<any>): void

Applies the special expiration boundary without a preceding suspend callback.

ts
refresh(effect: EffectHandle<any>, duration: float | null): void

Replaces a retained effect's non-negative duration and restarts its scheduler timer.

ts
removeAll(reason: EffectRemovalReason): void

Removes a reverse-order snapshot so teardown mirrors capability unwinding.

EffectHandle ​

ts
import { EffectHandle } from "gamekit";
class EffectHandle<T>

Stable handle controlling one effect's lifecycle, timer, and source cleanup.

Members

ts
id: int

Stable identifier for this EffectHandle.

ts
key: EffectKey<T>

Typed effect identity shared by colliding applications.

ts
value: T

Attached game-owned effect behavior or data.

ts
source: any | null

Optional lifetime owner whose disposal removes this effect.

ts
duration: float | null

Current expiration delay, or null for no timer.

ts
state: EffectState = EffectState.SUSPENDED

Suspended, active, removed, or expired lifecycle state.

ts
order: int

Monotonic capability order shared with the owning Entity.

ts
attached: boolean = false

Whether onAttach has run at least once.

ts
constructor(collection: any, id: int, order: int, key: EffectKey<T>, value: T, options: EffectOptions<T>)

Captures collection ownership and options; attachment occurs separately.

ts
get active(): boolean

Whether the effect currently participates in active owner behavior.

ts
get removed(): boolean

Whether the effect reached either terminal removed or expired state.

ts
suspend(): void

Requests idempotent suspension through the owning collection.

ts
activate(): void

Requests attachment if needed, then idempotent activation through the collection.

ts
remove(): void

Requests terminal manual removal through the owning collection.

ts
refresh(duration: float | null = this.duration): void

Restarts timed expiration, defaulting to the current duration.

EffectKey ​

ts
import { EffectKey } from "gamekit";
class EffectKey<T> extends TypedKey<T>

Identifies an effect kind and its typed payload across an entity's collection.

Members

ts
constructor(label: string)

Allocates a fresh effect identity with the label shown in diagnostics.

EffectOptions ​

ts
import { EffectOptions } from "gamekit";
class EffectOptions<T>

Optional collision, source-lifetime, and timed-expiration policy for an effect.

Members

ts
policy: Function | null

Stacking callback required when the key already has live effects.

ts
source: any | null

Optional object whose disposal removes this effect.

ts
duration: float | null

Non-negative lifetime in seconds of the scheduler's time, or null for no timer.

ts
scheduler: any | null

Explicit core Ticker (App.ticker, node.ticker) required whenever duration is present; headless tests may pass a ClockScheduler.

ts
constructor(policy: Function | null = null, source: any | null = null, duration: float | null = null, scheduler: any | null = null)

Validates that timed effects have a non-negative duration and scheduler.

EffectRemovalReason ​

ts
import { EffectRemovalReason } from "gamekit";
enum EffectRemovalReason

Defines the closed effect removal reason value set. Store and compare these values directly rather than introducing string aliases;

MemberMeaning
REMOVED = "removed"The owner explicitly removed the effect.
REPLACED = "replaced"A replacement displaced the effect.
REJECTED = "rejected"Stacking rules rejected the effect.
EXPIRED = "expired"The effect reached its expiration condition.
SOURCE_DISPOSED = "source-disposed"The effect's source owner was disposed.
TARGET_DISPOSED = "target-disposed"The effect's target owner was disposed.

EffectStacking ​

ts
import { EffectStacking } from "gamekit";
class EffectStacking

Factory for common collision policies consumed by EffectCollection.

Members

ts
static accumulate(): Function

Accepts every incoming effect alongside existing matches.

ts
static replace(): Function

Removes all existing matches before accepting the incoming effect.

ts
static strongest(compare: Function): Function

Rejects incoming payloads not strictly stronger than every existing value; otherwise replaces them.

ts
static refreshDuration(): Function

Keeps the most recently added match and restarts its timer using incoming duration.

EffectStackingContext ​

ts
import { EffectStackingContext } from "gamekit";
class EffectStackingContext<T>

Collision-policy view of the incoming application and matching handles in insertion order.

Members

ts
incoming: EffectApplication<T>

Application currently seeking admission.

ts
existing: EffectHandle<T>[]

Live handles with the same key, oldest first.

ts
constructor(incoming: EffectApplication<T>, existing: EffectHandle<T>[])

Captures the collision inputs for one synchronous policy decision.

ts
accept(): EffectStackingResolution<T>

Chooses to retain matches and add the incoming effect.

ts
reject(): EffectStackingResolution<T>

Chooses to reject incoming payload with a removal callback.

ts
replace(): EffectStackingResolution<T>

Chooses to remove every match and add the incoming effect.

ts
refresh(effect: EffectHandle<T>): EffectStackingResolution<T>

Chooses one existing handle to retain and retime instead of adding.

EffectStackingResolution ​

ts
import { EffectStackingResolution } from "gamekit";
class EffectStackingResolution<T>

Policy decision naming accept, reject, replace, or refresh plus an optional retained handle.

Members

ts
action: string

Decision string interpreted and validated by EffectCollection.

ts
retained: EffectHandle<T> | null

Existing handle required only for refresh.

ts
constructor(action: string, retained: EffectHandle<T> | null = null)

Captures a policy decision; collection application validates action semantics.

EffectState ​

ts
import { EffectState } from "gamekit";
enum EffectState

Defines the closed effect state value set. Store and compare these values directly rather than introducing string aliases;

MemberMeaning
ACTIVE = "active"The effect currently applies.
SUSPENDED = "suspended"The effect is retained but not currently applied.
EXPIRED = "expired"The effect ended because its duration elapsed.
REMOVED = "removed"The effect is no longer retained by its collection.

Entity ​

ts
import { Entity } from "gamekit";
class Entity implements IEffectOwner

Owns a game object's hierarchy, local facts, components, and effects. An Entity is detached until attached to an active root; its identity and owned state survive reparenting but not dispose.

Members

ts
parent: Entity | null = null

Current hierarchy owner, or null for a root or detached entity.

ts
state: EntityState = EntityState.DETACHED

Detached, attached, active, or terminal disposed lifecycle state.

ts
events: EventScope

Local non-bubbling event scope closed before disposal callbacks.

ts
effects: EffectCollection

Effect collection whose lifecycle follows this entity.

ts
constructor(eventErrorSink: Function | null = null)

Creates a detached entity with local events and effects; the optional sink observes listener errors.

ts
onAttach(): void

Override hook called parent-before-child when entering a hierarchy.

ts
onActivate(): void

Override hook called parent-before-child when entering active state.

ts
onDeactivate(): void

Override hook called child-before-parent when leaving active state.

ts
onDetach(): void

Override hook called child-before-parent before hierarchy unlinking.

ts
onDispose(): void

Terminal override hook called child-before-parent during recursive disposal.

ts
onContextChanged(key: ContextKey<any>): void

Override invalidation hook delivered parent-before-child for a changed context key.

ts
children(): Entity[]

Returns a detached snapshot of non-disposed direct children in attachment order.

ts
ancestors(): Entity[]

Returns live ancestors nearest-first up to the hierarchy root.

ts
descendants(): Entity[]

Returns live descendants in parent-before-child preorder.

ts
addComponent<T>(key: ComponentKey<T>, value: T): void

Attaches one game-defined capability under its explicit identity key. The component becomes visible immediately and receives the Entity's current lifecycle; mutation from a component callback throws.

  • Throws: Error when the key is already present or lifecycle mutation is re-entrant.
ts
replaceComponent<T>(key: ComponentKey<T>, value: T): T | null

Removes the prior keyed component through lifecycle callbacks, then attaches its replacement. Returns the former value, or null when the key was absent.

ts
removeComponent<T>(key: ComponentKey<T>): T | null

Deactivates and detaches a keyed component before returning its value, or null when absent.

ts
getComponent<T>(key: ComponentKey<T>): T | null

Looks up a component without turning absence into a programming error. This reads only this Entity's explicit component table and returns null after disposal.

ts
getAncestorComponent<T>(key: ComponentKey<T>): T | null

Finds the nearest ancestor value for a key, deliberately excluding local membership.

ts
getDescendantComponents<T>(key: ComponentKey<T>): T[]

Collects matching descendant values in hierarchy preorder, excluding this entity.

ts
inspectComponents(): any[]

Captures key labels, attachment order, and game-owned value references for tooling.

ts
addEffect<T>(key: EffectKey<T>, value: T, options: EffectOptions<T> | null = null): EffectHandle<T> | null

Applies an effect through admission/stacking and current entity lifecycle.

ts
getEffects<T>(key: EffectKey<T>): EffectHandle<T>[]

Returns a detached insertion-ordered array of live handles matching exact key identity.

ts
attach(parent: Entity): void

Links a detached subtree under a live parent and activates it when that parent is active.

ts
activate(): void

Activates a root or child of an active parent in parent-before-child order.

ts
deactivate(): void

Deactivates an active root subtree in child-before-parent order.

ts
detach(): void

Deactivates and detaches the subtree child-before-parent while preserving all owned state.

ts
reparent(newParent: Entity): void

Transfers synchronously through detach and attach, then activates under an active new parent.

ts
dispose(): void

Idempotently closes events and disposes descendants, capabilities, and this entity child-first.

ts
disposeDeferred(queue: any): void

Enqueues terminal disposal while leaving the entity live until queue flush.

ts
setContext<T>(key: ContextKey<T>, value: T): void

Adds or replaces a local context value, then invalidates this subtree parent-first.

ts
removeContext<T>(key: ContextKey<T>): boolean

Removes a local context value and invalidates descendants only when membership changed.

ts
getContext<T>(key: ContextKey<T>): T | null

Resolves the nearest local-or-ancestor context value, or null at an absent boundary.

EntityAllocator ​

ts
import { EntityAllocator } from "gamekit";
class EntityAllocator

Issues compact generational entity ids and recycles released slots without reviving stale handles.

Members

ts
create(): EntityId

Allocates a live id, preferring the most recently released reusable slot.

ts
seedGeneration(index: int, generation: int): void

Sets a slot generation for boundary tests and persisted-id hardening; inactive seeded slots become reusable.

ts
isAlive(id: EntityId): boolean

Returns true only when the index exists, is live, and has the exact generation.

ts
resolve(id: EntityId): EntityId | null

Returns the supplied id when live, or null for unknown and stale identities.

ts
requireAlive(id: EntityId): void

Enforces liveness at mutation boundaries.

ts
destroy(id: EntityId): boolean

Invalidates a live id and increments its generation before recycling the slot. A slot at EntityId.MAX_GENERATION is retired permanently.

EntityId ​

ts
import { EntityId } from "gamekit";
class EntityId

Names one lifetime of an allocator slot using an index-and-generation pair.

Members

ts
static const MAX_GENERATION: int = 2147483647

Highest generation value before allocator slots retire instead of wrapping.

ts
index: int

Reusable allocator slot index; it is not unique without generation.

ts
generation: int

Slot generation that prevents a stale id from resolving after reuse.

ts
constructor(index: int, generation: int)

Captures an allocator-issued slot and generation without validating liveness.

ts
equals(other: EntityId): boolean

Requires both slot and generation to match.

ts
toString(): string

Formats the identity as entity index:generation for diagnostics.

EntityState ​

ts
import { EntityState } from "gamekit";
enum EntityState

Defines the closed entity state value set. Store and compare these values directly rather than introducing string aliases;

MemberMeaning
DETACHED = "Detached"The entity has no parent owner.
ATTACHED = "Attached"The entity belongs to a parent but is inactive.
ACTIVE = "Active"The entity is attached and receiving active lifecycle work.
DISPOSED = "Disposed"The entity has completed teardown.

EntityTeardownQueue ​

ts
import { EntityTeardownQueue } from "gamekit";
class EntityTeardownQueue

Deduplicates deferred Entity disposal until an explicit FIFO flush boundary.

Members

ts
defer(entity: Entity): void

Enqueues a live entity once by object identity; disposed entities are ignored.

ts
flush(): void

Disposes the current snapshot in issue order; callback additions wait for the next flush.

EventKey ​

ts
import { EventKey } from "gamekit";
class EventKey<T> extends TypedKey<T>

Identifies an event channel and statically carries the emitted payload type.

Members

ts
constructor(label: string)

Allocates a fresh event identity with the label shown in diagnostics.

EventScope ​

ts
import { EventScope } from "gamekit";
class EventScope

Owns typed local event listeners and delivers snapshot notifications in subscription order. Listener failures are isolated and optionally reported without aborting later listeners.

Members

ts
constructor(errorSink: Function | null = null)

Starts an open local scope with an optional (error, eventKey) reporting sink.

ts
get subscriptionCount(): int

Number of active listener handles owned by this scope.

ts
subscribe<T>(key: EventKey<T>, listener: Function): EventSubscription

Appends a listener for exact key identity and returns its idempotent cancellation handle. Subscribing after close returns an already inactive handle.

ts
emit<T>(key: EventKey<T>, event: T): void

Delivers a listener snapshot in subscription order; changes affect only later emissions. Closing during delivery stops remaining callbacks, while listener errors go to the sink.

ts
forward<T>(target: EventScope, key: EventKey<T>, event: T): void

Explicitly emits on another scope without introducing hierarchy or bubbling.

ts
close(): void

Idempotently prevents future delivery and deactivates every owned subscription.

ts
get isClosed(): boolean

Whether the scope has permanently stopped accepting listeners and events.

ts
removeSubscription(subscription: EventSubscription): void

Deactivates and removes an owned handle; repeated or foreign removal is harmless.

EventSubscription ​

ts
import { EventSubscription } from "gamekit";
class EventSubscription

Idempotent handle controlling one listener's lifetime in an EventScope.

Members

ts
active: boolean = true

Whether this EventSubscription still accepts work.

ts
constructor(scope: EventScope, entry: ListenerEntry)

Binds the handle to its owning scope and private listener entry.

ts
dispose(): void

Stops future delivery and detaches from the scope; repeated calls do nothing.

ts
matches(entry: ListenerEntry): boolean

Tests the private listener-entry identity during owner cleanup.

ts
deactivate(): void

Marks the handle inactive and drops its owner reference without re-entering the owner.

FakeAssetLoader ​

ts
import { FakeAssetLoader } from "gamekit";
class FakeAssetLoader

Deterministic in-memory loader with configurable failures, delays, and call-order inspection.

Members

ts
loadOrder: Array<AssetKey<any>> = []

Asset keys requested in chronological order, including failed attempts.

ts
loadOrderLabels: Array<string> = []

Labels captured at each request for concise assertions.

ts
unloadOrder: Array<AssetKey<any>> = []

Keys unloaded in chronological order.

ts
set<T>(key: AssetKey<T>, value: T): void

Associates a value with exact key identity for future successful loads.

ts
setFailures(key: AssetKey<any>, errors: string[]): void

Replaces the queue of error messages thrown by successive loads.

ts
setFailure(key: AssetKey<any>, error: string): void

Configures one failing attempt for a key.

ts
setDelay(key: AssetKey<any>, delayMs: int): void

Sets an asynchronous delay in milliseconds before outcome selection.

ts
getLoadCount(key: AssetKey<any>): int

Returns attempted loads for exact key identity.

ts
getUnloadCount(key: AssetKey<any>): int

Returns unload calls for exact key identity.

ts
async load(key: AssetKey<any>): Promise<any>

Records the attempt, waits its delay, consumes one queued failure, then returns configured or default mock data.

ts
unload(key: AssetKey<any>, asset: any): void

Records unload and invokes dispose on the asset.

ts
reset(): void

Clears configured data, failures, delays, counters, and order traces.

GameKitError ​

ts
import { GameKitError } from "gamekit";
class GameKitError extends Error

Base error type for GameKit style guide and lifecycle violations.

Members

ts
constructor(message: string)

Preserves a consumer-facing explanation through the standard Error surface.

Gauge ​

ts
import { Gauge } from "gamekit";
class Gauge

Neutral rate-filled value for cooldowns, charge bars and any meter that fills with time. Time arrives through advance, never read from a clock, so a crossing lands on the same tick every run.

Members

ts
value: float

Current fill, always within 0 and capacity.

ts
capacity: float

Fill at which the gauge is full.

ts
rate: float

Fill added per unit of time given to advance.

ts
paused: boolean = false

While true, advance leaves the value unchanged.

ts
constructor(capacity: float, rate: float, start: float = 0.0)

Starts at start (clamped into range, default empty).

  • Throws: InvalidArgument when capacity is not above zero or rate is negative.
ts
advance(dt: float): boolean

Adds rate * dt, clamped to capacity. Does nothing while paused.

  • dt: Time passed, not negative.
  • Returns: true only on the call that takes the gauge from below capacity to full.
  • Throws: InvalidArgument when dt is negative.
ts
consume(amount: float): void

Removes amount, flooring at zero.

  • Throws: InvalidArgument when amount is negative.
ts
fill(): void

Sets the value to capacity without reporting a crossing.

InteractionContext ​

ts
import { InteractionContext } from "gamekit";
class InteractionContext<TActor, TTarget, TEnv>

Typed actor, target, and environment tuple shared across interaction discovery.

Members

ts
actor: TActor

Game object attempting the interaction.

ts
target: TTarget

Game object being inspected or acted upon.

ts
environment: TEnv

Optional world or presentation context interpreted by providers.

ts
constructor(actor: TActor, target: TTarget, environment: TEnv = null)

Captures game-owned references without copying them.

InteractionDefinition ​

ts
import { InteractionDefinition } from "gamekit";
class InteractionDefinition<TMetadata>

Builds one executable offer from context, optional availability logic, and metadata.

Members

ts
id: string

Stable identifier for this InteractionDefinition.

ts
action: Action<any, any>

Action executed if the resulting offer is enabled.

ts
requestFactory: Function

Callback converting discovery context into an ActionRequest.

ts
condition: Condition<any> | null

Optional availability test evaluated during offer creation.

ts
metadataFactory: Function | null

Optional (context, enabled, conditionResult) presentation-data callback.

ts
constructor( id: string, action: Action<any, any>, requestFactory: Function, condition: Condition<any> | null = null, metadataFactory: Function | null = null )

Captures a non-empty offer id and its request, action, condition, and metadata factories.

ts
createOffer(context: InteractionContext<any, any, any>): InteractionOffer<TMetadata>

Evaluates availability once and captures the request plus metadata in a new offer.

InteractionOffer ​

ts
import { InteractionOffer } from "gamekit";
class InteractionOffer<TMetadata>

Point-in-time executable interaction choice produced during discovery.

Members

ts
id: string

Stable identifier for this InteractionOffer.

ts
action: Action<any, any>

Action invoked when this offer executes while enabled.

ts
request: ActionRequest<any>

Prebuilt invocation captured during discovery.

ts
enabled: boolean

Whether this behavior is currently enabled.

ts
conditionResult: ConditionResult | null

Availability explanation, or null when no condition was configured.

ts
metadata: TMetadata

Game-defined display or ranking data captured during discovery.

ts
constructor( id: string, action: Action<any, any>, request: ActionRequest<any>, enabled: boolean = true, conditionResult: ConditionResult | null = null, metadata: TMetadata = null )

Captures a non-empty id and the discovery-time execution state.

ts
execute(targetScope: EventScope | null = null): ActionResult<any>

Returns denial without invoking the action when disabled; otherwise executes the captured request.

InteractionProvider ​

ts
import { InteractionProvider } from "gamekit";
class InteractionProvider<TActor, TTarget, TEnv>

Named discovery callback that produces zero or more offers for one context.

Members

ts
id: string

Stable identifier for this InteractionProvider.

ts
constructor(id: string, discoverFn: Function)

Binds a non-empty provider id to a discovery callback.

ts
discover(context: InteractionContext<TActor, TTarget, TEnv>): InteractionOffer<any>[]

Normalizes a null callback result to an empty offer list.

ts
static fromDefinition(definition: InteractionDefinition<any>): InteractionProvider<any, any, any>

Wraps a single definition as a provider that always returns one captured offer.

InteractionRegistry ​

ts
import { InteractionRegistry } from "gamekit";
class InteractionRegistry

Aggregates providers in registration order without imposing ranking or deduplication.

Members

ts
register(provider: InteractionProvider<any, any, any>): void

Appends a provider; duplicate ids remain independently discoverable.

ts
unregister(id: string): boolean

Removes the first provider with the id and reports whether one existed.

ts
discover(actor: any, target: any, environment: any = null): InteractionOffer<any>[]

Builds one shared context and concatenates provider offers in stable order.

InvalidArgument ​

ts
import { InvalidArgument } from "gamekit";
class InvalidArgument extends GameKitError

Reports a public API argument that violates an immediate precondition.

Members

ts
constructor(message: string)

Captures the failed precondition in the inherited error message.

InvalidDefinition ​

ts
import { InvalidDefinition } from "gamekit";
class InvalidDefinition extends DefinitionError

Reports definition data that cannot be validated or resolved.

Members

ts
reason: string

Machine-comparable validation reason, separate from the display message.

ts
constructor(message: string, definitionId: string = "", provenance: string[] = [], reason: string = "")

Captures definition identity, provenance, and a concise validation reason.

ISpatialIndex ​

ts
import { ISpatialIndex } from "gamekit";
interface ISpatialIndex<T>

Defines deterministic identity-based insertion and broad-phase 2D spatial queries.

Members

ts
upsert(value: T, bounds: Rect): void

Inserts a value or replaces its copied bounds when the same object identity exists.

ts
remove(value: T): boolean

Removes exact object identity and reports whether membership changed.

ts
point(point: Vec2): T[]

Returns values whose half-open bounds contain a point (left/top inclusive, right/bottom exclusive).

ts
area(bounds: Rect): T[]

Returns values whose bounds overlap an area (touching edges do not overlap).

ts
nearest(point: Vec2, maxDistance?: float): T | null

Finds the first nearest bounds, optionally limited by a world-unit radius.

ts
swept(bounds: Rect, delta: Vec2): T[]

Broad-phases against the union of starting and translated bounds.

ts
readonly size: int

Number of distinct value identities currently indexed.

KeyedRegistry ​

ts
import { KeyedRegistry } from "gamekit";
class KeyedRegistry

Associates heterogeneous values with exact typed-key identities in registration order.

Members

ts
register<T>(key: TypedKey<T>, value: T): void

Retains a value under a key that must not already be present.

ts
get<T>(key: TypedKey<T>): T | null

Reads by key identity, returning null when no registration exists.

ts
getRequired<T>(key: TypedKey<T>): T

Reads by key identity and treats absence as a programming error.

LinearSpatialIndex ​

ts
import { LinearSpatialIndex } from "gamekit";
class LinearSpatialIndex<T> implements ISpatialIndex<T>

Simple insertion-ordered spatial index that linearly scans copied bounds.

Members

ts
upsert(value: T, bounds: Rect): void

Inserts by object identity or replaces that value's copied bounds in place.

ts
remove(value: T): boolean

Removes exact object identity and returns whether an entry existed.

ts
point(point: Vec2): T[]

Collects containing entries in insertion order. Uses half-open bounds semantics: left/top edges are inclusive, right/bottom edges are exclusive.

ts
area(bounds: Rect): T[]

Collects overlapping entries in insertion order. Touching edges do not overlap.

ts
nearest(point: Vec2, maxDistance: float = -1.0): T | null

Finds the first entry at minimum squared distance from a point to its bounds. A radius of -1 means unlimited; other negative values throw.

ts
swept(bounds: Rect, delta: Vec2): T[]

Broad-phases the union of starting and translated bounds, not the exact swept shape.

ts
get size(): int

Number of distinct value identities currently indexed.

mergeData ​

ts
import { mergeData } from "gamekit";
function mergeData(base: any, override: any): any

Recursively overlays plain objects and maps, while other values replace the base. The returned structure does not share nested containers with either input.

MissingRegistration ​

ts
import { MissingRegistration } from "gamekit";
class MissingRegistration extends GameKitError

Reports a required typed-key, component, or definition registration that is absent.

Members

ts
missingId: string

Missing definition or registration identity, when known.

ts
provenance: string[]

Lookup path that led to the absent registration.

ts
constructor(message: string, missingId: string = "", provenance: string[] = [])

Captures optional missing-id and lookup-path context for diagnostics.

MutablePipeline ​

ts
import { MutablePipeline } from "gamekit";
class MutablePipeline<I, O>

Runs mutable processing stages over one shared context snapshot in insertion order.

Members

ts
add(stage: Function): PipelineSubscription<I, O>

Appends a stage and returns an idempotent handle that can remove it.

ts
run(input: I): PipelineResult<O>

Runs the entry snapshot until exhausted or cancelled, then captures the optional output.

ts
dispose(): void

Removes all stages and deactivates their handles; repeated calls are harmless.

ts
removeSubscription(subscription: PipelineSubscription<I, O>): void

Deactivates and removes one stage; an in-progress run keeps its entry snapshot.

PipelineContext ​

ts
import { PipelineContext } from "gamekit";
class PipelineContext<I, O>

Mutable per-run input, cancellation flag, and optional output shared by pipeline stages.

Members

ts
input: I

Original input reference supplied to MutablePipeline.run.

ts
cancelled: boolean = false

Set once a stage requests that later stages be skipped.

ts
constructor(input: I)

Starts an uncancelled run with no produced output.

ts
cancel(): void

Prevents later stages in the current snapshot from running.

ts
produce(result: O): void

Replaces the output; the last stage to produce wins.

ts
get result(): O | null

Latest produced output, or null when no stage produced one.

PipelineResult ​

ts
import { PipelineResult } from "gamekit";
class PipelineResult<O>

Immutable-by-convention snapshot of a completed pipeline's cancellation and output state.

Members

ts
cancelled: boolean

Whether a stage stopped traversal before the snapshot ended.

ts
result: O | null

Last produced output, or null when no stage produced one.

ts
constructor(cancelled: boolean, result: O | null)

Captures terminal context values after pipeline traversal.

PipelineSubscription ​

ts
import { PipelineSubscription } from "gamekit";
class PipelineSubscription<I, O>

Idempotent lifetime handle for one stage in a MutablePipeline.

Members

ts
active: boolean = true

Whether this PipelineSubscription still accepts work.

ts
constructor(pipeline: MutablePipeline<I, O>, entry: PipelineStageEntry)

Binds the handle to its owner and private stage entry.

ts
dispose(): void

Removes the stage from future runs; repeated calls do nothing.

ts
matches(entry: PipelineStageEntry): boolean

Tests private stage-entry identity during owner cleanup.

ts
deactivate(): void

Marks the handle inactive and drops its owner reference without re-entry.

Prefab ​

ts
import { Prefab } from "gamekit";
class Prefab

Reusable factory binding for one definition id in a specific registry.

Members

ts
readonly definitionId: string

Registered definition resolved for every instantiation.

ts
constructor(registry: any, definitionId: string, factory: Function)

Binds a non-null registry and factory to a non-empty definition id.

ts
instantiate(context: any = null): any

Resolves fresh data and calls the factory as (resolvedDefinition, context).

ResolvedDefinition ​

ts
import { ResolvedDefinition } from "gamekit";
class ResolvedDefinition

Fully merged definition data plus the ordered ids that contributed to it.

Members

ts
readonly id: string

Stable identifier for this ResolvedDefinition.

ts
readonly data: any

Merged data snapshot returned independently to each resolver caller.

ts
readonly provenance: string[]

Unique parent-first contribution order ending with id.

ts
constructor(id: string, data: any, provenance: string[])

Captures a completed resolution result.

StaleHandle ​

ts
import { StaleHandle } from "gamekit";
class StaleHandle extends GameKitError

Reports mutation through an entity or effect handle whose lifetime has ended.

Members

ts
constructor(message: string)

Captures which retired identity was used in the inherited message.

StateMachine ​

ts
import { StateMachine } from "gamekit";
class StateMachine<TOwner>

Runs explicit named-state callbacks with guarded, FIFO transitions and optional clock scheduling. Transitions requested from callbacks queue behind the current callback and obey a per-drain work cap.

Members

ts
constructor(owner: TOwner, clock: any | null = null, transitionWorkCap: int = 64)

Binds an owner, optional scheduler, and positive transition-chain safety cap.

ts
get stateName(): string | null

Current state name, or null before start and after disposal.

ts
get processing(): boolean

Whether an enter, exit, update, or transition drain is active.

ts
get disposed(): boolean

Whether teardown has permanently disabled the machine.

ts
addState(state: StateMachineState<TOwner>): void

Registers a uniquely named state before the machine starts.

ts
permit(source: string, target: string, guard: Function | null = null): void

Declares one directed transition with an optional (owner, context) guard.

ts
start(name: string, context: any = null): void

Enters the initial state, then drains transitions queued by its callback.

ts
transition(target: string, context: any = null): boolean

Evaluates the declared guard and queues a permitted transition. Returns false only when the guard rejects it; callback requests return before the queue drains.

ts
update(delta: float): void

Invokes the current state's (owner, deltaSeconds) callback and drains queued transitions.

ts
transitionAfter(delay: float, target: string, context: any = null): any

Schedules a transition on the injected clock and returns its cancellable work handle.

ts
dispose(context: any = null): void

Idempotently cancels scheduled work, clears queued transitions, and exits the current state.

ts
inspect(): StateMachineInspection

Captures current state, queue, transition, processing, disposal, and timer counts.

StateMachineInspection ​

ts
import { StateMachineInspection } from "gamekit";
class StateMachineInspection

Point-in-time diagnostic counters and lifecycle flags for a StateMachine.

Members

ts
stateName: string | null

Current state name, or null when not started or disposed.

ts
queuedTransitions: int

FIFO requests waiting behind current callback work.

ts
transitionCount: int

Successful initial entry and state changes completed so far.

ts
processing: boolean

Whether callback or transition work was active at capture time.

ts
disposed: boolean

Whether the machine had permanently completed teardown.

ts
scheduledTransitions: int

Timer handles retained for cancellation on dispose.

ts
constructor(stateName: string | null, queuedTransitions: int, transitionCount: int, processing: boolean, disposed: boolean, scheduledTransitions: int)

Captures scalar state without retaining the inspected machine.

StateMachineState ​

ts
import { StateMachineState } from "gamekit";
class StateMachineState<TOwner>

Named state with optional owner callbacks for entry, exit, and fixed updates.

Members

ts
name: string

Optional label used in diagnostics.

ts
enter: Function | null

Optional (owner, context) callback invoked after becoming current.

ts
exit: Function | null

Optional (owner, context) callback invoked before leaving current state.

ts
update: Function | null

Optional (owner, deltaSeconds) callback invoked by machine updates.

ts
constructor(name: string, callbacks: any = {})

Captures a non-empty name and the recognized callbacks from an options object.

Transform2D ​

ts
import { Transform2D } from "gamekit";
class Transform2D

Mutable 2D position, rotation, and scale value with no scene-graph ownership.

Members

ts
position: Vec2

Translation in world units.

ts
rotation: float

Clockwise rotation in radians.

ts
scale: Vec2

Independent x/y scale multipliers.

ts
constructor(position: Vec2 = Vec2{}, rotation: float = 0.0, scale: Vec2 = Vec2{ x: 1.0, y: 1.0 })

Retains the supplied mutable vectors and rotation value.

ts
copy(): Transform2D

Deep-copies position and scale so later vector edits are independent.

TypedKey ​

ts
import { TypedKey } from "gamekit";
class TypedKey<T>

Provides a process-unique, type-carrying identity for registries; labels are diagnostic only.

Members

ts
label: string

Human-readable name shown in errors and inspection output.

ts
constructor(kind: string, label: string)

Allocates a fresh identity token for a non-empty diagnostic label.

ts
equals(other: TypedKey<any>): boolean

Compares identity tokens, so separately constructed keys never alias by label.

ts
getToken(): int

Exposes the process-local token used for equality and deterministic diagnostics.

ts
describe(): string

Formats the key kind, label, and unique token for error messages.

WeightedPick ​

ts
import { WeightedPick } from "gamekit";
class WeightedPick<T>

Weighted choice over an injected Random, the only source of chance, so a seed gives a fixed sequence. Entries with weight 0 are never chosen. fork(name) derives an independent stream from the original seed, so several tables stay reproducible whatever order they are created in.

Members

ts
constructor(random: Random)

Uses random for every draw; the table starts empty.

ts
get count(): int

Number of entries, including zero-weight ones.

ts
add(item: T, weight: float): void

Appends an entry. Higher weight is proportionally more likely; 0 is never chosen.

  • Throws: InvalidArgument when weight is negative or not a number.
ts
pick(): T

Draws one entry.

  • Throws: InvalidArgument when the table has no entry with a weight above zero.
ts
fork(name: string): WeightedPick<T>

Copies the entries onto a table that draws from random.fork(name); later add calls on either table do not affect the other.