UNPKG

entangle.ts

Version:

A declarative, event-driven framework for orchestrating business logic in TypeScript & Node.js applications.

78 lines (77 loc) 3.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HiggsField = void 0; /** * The Higgs Field gives "mass" (substance) to particle classes, * turning them into real, usable instances. It acts as a hierarchical * dependency injection container that manages object lifecycles and scopes. */ class HiggsField { constructor(parent) { this.parent = parent; // eslint-disable-next-line @typescript-eslint/no-explicit-any this.particles = new Map(); // eslint-disable-next-line @typescript-eslint/no-explicit-any this.factories = new Map(); } /** * Registers a factory function that defines how to create a particle. * @template T The type of the particle instance. * @param particleClass The class constructor for the particle. * @param factory The function that returns a new instance of the particle. * @param options Lifecycle options for the particle (e.g., scope). */ register(particleClass, factory, options = { lifecycle: 'singleton', destroyOnInteraction: true, }) { this.factories.set(particleClass, { factory, options }); } /** * Retrieves an instance of a particle, respecting its scope and the scope hierarchy. * @template T The expected type of the particle instance. * @param particleClass The class used to register the particle. * @returns An instance of the particle. * @throws {Error} If the particle is not registered in this scope or any parent scope. */ get(particleClass) { var _a; const registration = this.factories.has(particleClass) ? this.factories.get(particleClass) : (_a = this.parent) === null || _a === void 0 ? void 0 : _a.factories.get(particleClass); if (!registration) { throw new Error(`Particle ${particleClass.name} is not registered.`); } if (registration.options.lifecycle === 'transient') { return registration.factory(); } if (!this.particles.has(particleClass)) { const newInstance = registration.factory(); this.particles.set(particleClass, newInstance); } return this.particles.get(particleClass); } /** * Destroy a particle */ destroy(particleClass) { this.particles.delete(particleClass); this.factories.delete(particleClass); } /** * Helper method used to get a particle object of options defined upon creation */ getParticleOptions(particleClass) { var _a; return (_a = this.factories.get(particleClass)) === null || _a === void 0 ? void 0 : _a.options; } /** * Creates a new child scope (a "bubble universe") of this Higgs Field. * This new scope is isolated but can resolve dependencies from its parent. * @returns A new, scoped `HiggsField` instance. */ createScope() { return new HiggsField(this); } } exports.HiggsField = HiggsField;