import type { Message, Msgid, Pci, Severity } from "./syslog/Pdu.js"; import Syslog from "./syslog/Syslog.js"; import type { IContainer, IScope } from "./types/IContainer.js"; export interface DynamicService { [key: string]: unknown; } /** * Registre des scopes ouverts : nom de scope → ensemble des instances * vivantes. Il ne sert qu'à les COMPTER ({@link Container.scopeCount}) et à * les refermer toutes au {@link Container.clean} : un `Set` tenu par l'objet * lui-même rend ce service sans fabriquer de clé. Un index par identifiant * chaîne — fabriqué et haché à chaque ouverture — coûte ~70 % du cycle * `enterScope` + `leaveScope`, payé à chaque requête. */ export type Scopes = Map>; /** Porteur du prototype partagé des services (cf {@link createProto}). */ export type ProtoService = { (): void; prototype: DynamicService; }; /** * Dependency Injection container — registers services by name and exposes * them to the rest of the framework. * * Services are stored on a prototype-backed object (`protoService`) so they * are inherited by child scopes (see {@link Scope}). Configuration does not * live here: each module reads its own `options`. * * Conventional usage: * ```ts * const c = new Container(); * c.set("logger", new LoggerService()); * const logger = c.get("logger"); * ``` * * See `docs/architecture/injection-portees.md` for the high-level rationale * and the scope model used by the HTTP/WS request pipeline. */ declare class Container implements IContainer { #private; protoService: ProtoService; protected services: DynamicService | null; private scopes; /** * Create a new container. When an existing container is passed in, the * new instance inherits its services (via prototype chaining) — used by * {@link Scope} to build short-lived containers that share base services * but isolate per-request state. * * @param input - parent container to inherit services from * @param adoptedProtoService - canal réservé à {@link Scope} : adopte le * proto-services du PARENT au lieu d'allouer une closure locale morte */ constructor(input?: Container, adoptedProtoService?: ProtoService); /** * Identifiant unique du conteneur dans le process (base 36). Fabriqué à la * première lecture, puis stable : ouvrir un scope par requête ne coûte ni * chaîne ni tour de compteur tant que personne ne le lit. */ get id(): string; /** * `true` après {@link clean} — pour un scope, après {@link leaveScope}. * Les services sont alors libérés : `get()` rend `null` (même pour * un service hérité) et `set()` lève. {@link reset} rend un conteneur racine * utilisable ; un scope, lui, ne se rouvre pas. * * Lu sur l'état existant plutôt que sur un drapeau : aucun champ de plus par * scope, donc ni octet ni écriture ajoutés à `enterScope`. */ get closed(): boolean; private setServices; /** * Emit a log entry through the registered `syslog` service. Falls back to * `console.warn` when no syslog is set (early boot, isolated test). * * @param pci - log payload (string or structured PDU body) * @param severity - syslog severity level * @param msgid - message id; defaults to `"SERVICES CONTAINER"` * @param msg - optional message detail */ log(pci: Pci, severity?: Severity, msgid?: Msgid, msg?: Message): ReturnType | void; /** * Register a service under `name`. The service is stored both directly on * the container and on its prototype, so child scopes can read it without * an extra hop. * * @param name - service identifier (any non-empty string) * @param object - the instance to register (no type constraint — services * are not required to extend any base class) * @throws Error if `name` is empty or the container has been cleaned */ set(name: string, object: unknown): void; /** * Resolve a service by name. Returns `null` if the service is unknown or * the container has been cleaned — callers should narrow the result * before use. * * @param name - service identifier * @returns the service instance typed as `T`, or `null` */ get(name: string): T | null; /** * Unregister a service. Open scopes stop inheriting it (they read through * the shared prototype), but a scope's OWN override of the same name is * left untouched — it belongs to that unit of work, not to this container. * * @param name - service identifier * @returns `true` when a service was actually removed, `false` otherwise */ remove(name: string): boolean; /** Whether a service is registered under `name`. */ has(name: string): boolean; /** All service names currently registered on this container. */ keys(): string[]; /** All `[name, service]` pairs currently registered on this container. */ entries(): [string, unknown][]; /** * Declare a scope. Scopes are short-lived containers (typically created * per HTTP/WS request) that inherit services from this container but * store their own per-request services. Must be called * once before {@link enterScope} can produce instances. * * @param name - scope identifier (e.g. `"request"`) * @returns the open instances of that scope, read-only (rarely used by * callers — {@link scopeCount} answers the usual question) */ addScope(name: string): ReadonlySet; /** * Open a new instance of the named scope. The returned {@link Scope} * inherits services from this container but tracks its own services in * isolation. * * @param name - scope name previously declared via {@link addScope} * @returns a fresh `Scope` instance with a unique `id` * @throws Error when the scope has not been declared */ enterScope(name: string): Scope; /** * Close a scope instance and release its services. Always * called when the unit of work that opened the scope finishes (request * end, WS close). * * @param scope - the scope instance returned by {@link enterScope} */ leaveScope(scope: IScope): void; /** * Nombre d'instances VIVANTES du scope nommé — introspection bon marché * (sondes de fuite, Studio, diagnostics) sans exposer la structure interne. * * @param name - scope identifier (e.g. `"request"`) * @returns le nombre de scopes ouverts, `0` si le scope est inconnu */ scopeCount(name: string): number; /** * Close every open instance of the named scope and forget it. After this * call, {@link enterScope}(`name`) will throw until {@link addScope} is * called again. * * @param name - scope identifier */ removeScope(name: string): void; private removeAllScopes; /** * Tear the container down: close every scope and drop services. After `clean()`, any `get`/`set`/`enterScope` call on this * instance throws or returns `null`. Called by the kernel during * graceful shutdown. */ clean(): void; /** * Clean the container and rebuild fresh prototype chains, leaving it * ready to register services again. Used by hot-reload paths in tests * and dev mode; production code rarely calls this directly. */ reset(): void; } /** * Short-lived child container tied to a parent {@link Container}. Used by * the HTTP/WS kernel to isolate per-request services (e.g. request-bound * sessions, scoped resolvers) without polluting the global container. * * Services defined on a `Scope` shadow the parent's — reads fall back to the * parent transparently when nothing is found locally. */ declare class Scope extends Container implements IScope { name: string; private owned; constructor(name: string, parent: Container, parentProtoService: ProtoService); /** * Refused on a scope: rebuilding fresh prototypes would silently detach it * from its parent (every inherited service would read as `null`). * * @throws Error always — close the scope with {@link Container.leaveScope} */ reset(): void; /** * Register a per-request service — own property ONLY (shadowing). Depuis * l'adoption des protos parents, l'écriture prototype de * {@link Container.set} toucherait le proto PARTAGÉ du parent : un service * per-request (controller, context) deviendrait visible de TOUTES les * requêtes concurrentes. (L'ancien chemin écrivait sur un proto local mort * — travail perdu à chaque set.) */ set(name: string, object: unknown): void; /** * Unregister a service registered ON THIS SCOPE (own property only). Les * services hérités du parent ne sont jamais touchés — même raison que * {@link Scope.set} : le proto est partagé depuis l'adoption. */ remove(name: string): boolean; /** * `true` si `name` est posé SUR ce scope (propriété propre) — jamais pour un * service hérité du parent. C'est la lecture qu'il faut pour savoir si la * requête possède déjà son exemplaire d'un service : `has()` suit la chaîne * de prototypes, et répondrait `true` pour un singleton homonyme. * * @param name - clé du service */ hasOwn(name: string): boolean; /** * Lie la durée de vie de `instance` à celle du scope : son `clean()`, s'il * en a un, sera appelé à la fermeture ({@link Container.leaveScope}), dans * l'ordre INVERSE des rattachements — un service créé après ceux dont il * dépend est nettoyé avant eux. * * @param instance - l'objet à nettoyer avec le scope * @throws Error si le scope est déjà fermé : l'objet ne serait jamais * nettoyé, puisque la fermeture a déjà eu lieu. */ own(instance: object): void; /** * Nettoie les objets rattachés ({@link own}), du dernier au premier, puis * libère le scope. Appelé par * {@link Container.leaveScope} quand l'unité de travail qui l'a ouvert se * termine. * * Les services du scope sont encore lisibles pendant les * `clean()` des objets rattachés : ils sont libérés APRÈS. Un `clean()` qui * lève est journalisé et n'interrompt pas les suivants — sans quoi un seul * service fautif laisserait tous ceux créés avant lui sans nettoyage. * * `clean()` n'est pas attendu : la fermeture reste synchrone. Un `async * clean()` part en arrière-plan, et son rejet est journalisé — jamais une * `unhandledRejection`. Hors de toute bulle de requête en HTTP : y lire le * scope par `this.container`, pas par `RequestContext`. */ clean(): void; /** Message d'un `clean()` rattaché qui a échoué (chemin froid). */ private static cleanFailure; } export default Container; export { Scope };