Skip to content

@web-engine-dev/resources

Global singleton/resource management for web-engine-dev. Provides a type-safe container for global resources and singletons that can be accessed by systems throughout the application.

Features

  • Type-Safe Access: Generic resource descriptors
  • Lazy Initialization: On-demand resource creation
  • Change Tracking: Optional mutation detection
  • Resource Queries: Unified access patterns

Installation

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

Quick Start

typescript
import { createResources, defineResource } from '@web-engine-dev/resources';

// Define resource types
const GameConfig = defineResource<{ difficulty: number }>('GameConfig');
const InputState = defineResource<{ keys: Set<string> }>('InputState');

// Create container
const resources = createResources();

// Insert resources
resources.insert(GameConfig, { difficulty: 1 });
resources.insert(InputState, { keys: new Set() });

// Get resources
const config = resources.get(GameConfig);
console.log(config.difficulty);

// Mutable access
const input = resources.getMut(InputState);
input.keys.add('Space');

API Reference

Resource Descriptor

typescript
const MyResource = defineResource<MyType>('MyResource');

Resources Container

MethodDescription
insert(desc, value)Insert a resource
insertLazy(desc, init)Insert with lazy initialization
get(desc)Get resource (read-only)
getMut(desc)Get resource (mutable)
tryGet(desc)Get or undefined
tryGetMut(desc)Get mutable or undefined
getOrInsert(desc, def)Get or insert default
has(desc)Check if resource exists
remove(desc)Remove a resource
clear()Remove all resources
size()Number of resources

Lazy Initialization

typescript
resources.insertLazy(ExpensiveResource, () => {
  // Only called on first access
  return loadExpensiveData();
});

// First access triggers initialization
const data = resources.get(ExpensiveResource);

Resource Queries

typescript
const query = resources.query(GameConfig);

if (query.exists()) {
  const value = query.get(); // Read-only
  const mut = query.getMut(); // Mutable
}

Use Cases

Game State

typescript
const GameState = defineResource<{
  score: number;
  level: number;
  paused: boolean;
}>('GameState');

resources.insert(GameState, { score: 0, level: 1, paused: false });

Configuration

typescript
const Settings = defineResource<{
  volume: number;
  fullscreen: boolean;
}>('Settings');

resources.insertLazy(Settings, () => loadSettingsFromStorage());

Shared Services

typescript
const AudioPlayer = defineResource<AudioPlayer>('AudioPlayer');
const NetworkClient = defineResource<NetworkClient>('NetworkClient');

Proprietary software. All rights reserved.