UNPKG

@dawans/promptshield

Version:

Secure your LLM stack with enterprise-grade RulePacks for AI safety scanning

113 lines (112 loc) 3.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ServiceLocator = exports.Container = void 0; /** * Simple dependency injection container */ class Container { constructor() { this.services = new Map(); this.factories = new Map(); this.singletons = new Map(); } /** * Registers a service instance */ register(name, instance) { this.services.set(name, instance); } /** * Registers a factory function */ registerFactory(name, factory, singleton = false) { this.factories.set(name, factory); if (singleton) { // Mark as singleton but don't instantiate yet this.singletons.set(name, null); } } /** * Resolves a service by name */ resolve(name) { // Check if it's a direct instance if (this.services.has(name)) { return this.services.get(name); } // Check if it's a singleton that's already created if (this.singletons.has(name) && this.singletons.get(name) !== null) { return this.singletons.get(name); } // Check if it's a factory if (this.factories.has(name)) { const factory = this.factories.get(name); if (!factory) throw new Error(`Factory for '${name}' not found`); const instance = factory(); // If it's a singleton, cache it if (this.singletons.has(name)) { this.singletons.set(name, instance); } return instance; } throw new Error(`Service '${name}' not found in container`); } /** * Checks if a service is registered */ has(name) { return this.services.has(name) || this.factories.has(name); } /** * Gets all registered service names */ getServiceNames() { return [...this.services.keys(), ...this.factories.keys()]; } /** * Clears all registrations */ clear() { this.services.clear(); this.factories.clear(); this.singletons.clear(); } /** * Creates a child container */ createChild() { const child = new Container(); // Copy parent registrations this.services.forEach((value, key) => { child.services.set(key, value); }); this.factories.forEach((value, key) => { child.factories.set(key, value); }); // Don't copy singleton instances, only their registration this.singletons.forEach((_, key) => { child.singletons.set(key, null); }); return child; } } exports.Container = Container; /** * Service locator pattern for global access */ class ServiceLocator { static setContainer(container) { this.container = container; } static getContainer() { if (!this.container) { throw new Error('Container not initialized'); } return this.container; } static resolve(name) { return this.getContainer().resolve(name); } } exports.ServiceLocator = ServiceLocator;