import { createCompositeLogger, type Logger, type RootLogger } from "@workleap/logging"; import memoize from "memoize"; import { EventBus } from "../messaging/EventBus.ts"; import type { DeferredRegistrationScopeCompletionFunction, DeferredRegistrationScopeOptions, Plugin } from "../plugins/Plugin.ts"; import { LocalModuleRegistry } from "../registration/LocalModuleRegistry.ts"; import { ModuleManager } from "../registration/ModuleManager.ts"; export type RuntimeMode = "development" | "production"; export type ModuleManagerFactory = (runtime: Runtime) => ModuleManager; export type PluginFactory = (runtime: TRuntime) => Plugin; export interface RuntimeOptions { mode?: RuntimeMode; moduleManager?: ModuleManagerFactory; loggers?: RootLogger[]; plugins?: PluginFactory[]; } export interface RuntimeMethodOptions { logger?: Logger; } export interface RegisterRouteOptions extends RuntimeMethodOptions { hoist?: true; parentPath?: string; parentId?: string; } export interface RegisterNavigationItemOptions extends RuntimeMethodOptions { menuId?: string; sectionId?: string; } export interface GetNavigationItemsOptions { menuId?: string; } export interface GetPluginOptions { throwOnNotFound?: boolean; } export interface StartDeferredRegistrationScopeOptions extends RuntimeMethodOptions { transactional?: boolean; } export interface CompleteDeferredRegistrationScopeOptions extends RuntimeMethodOptions {} export interface ValidateRegistrationsOptions extends RuntimeMethodOptions {} /** * The non plugin counterpart of {@link Plugin.onDeferredRegistrationScopeStarted}. Same options, same * return value, same guarantees — use it to clear and replay a registry that modules fill from their * deferred registration functions when that registry isn't owned by a plugin. * * Prefer the plugin hook when the registry lives in a plugin: it needs no subscription and no disposal. */ export type DeferredRegistrationScopeStartedListener = (options: DeferredRegistrationScopeOptions) => DeferredRegistrationScopeCompletionFunction | void; export const RootMenuId = "root"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export interface IRuntime = any> { get moduleManager(): ModuleManager; registerRoute: (route: TRoute, options?: RegisterRouteOptions) => void; registerPublicRoute: (route: Omit, options?: RegisterRouteOptions) => void; get routes(): TRoute[]; registerNavigationItem: (navigationItem: TNavigationItem, options?: RegisterNavigationItemOptions) => void; getNavigationItems: (options?: GetNavigationItemsOptions) => TNavigationItem[]; getNavigationItemsByMenu: () => Map; startDeferredRegistrationScope: (options?: StartDeferredRegistrationScopeOptions) => void; completeDeferredRegistrationScope: (options?: CompleteDeferredRegistrationScopeOptions) => void; registerDeferredRegistrationScopeStartedListener: (callback: DeferredRegistrationScopeStartedListener) => () => void; removeDeferredRegistrationScopeStartedListener: (callback: DeferredRegistrationScopeStartedListener) => void; _notifyDeferredRegistrationScopeStarted: (options: DeferredRegistrationScopeOptions) => DeferredRegistrationScopeCompletionFunction[]; get mode(): RuntimeMode; get plugins(): Plugin[]; getPlugin: (pluginName: string, options?: GetPluginOptions) => Plugin | undefined; get logger(): Logger; get eventBus(): EventBus; startScope: (logger: Logger) => TRuntime; _getLogger: (options?: RuntimeMethodOptions) => Logger; _validateRegistrations: (options?: ValidateRegistrationsOptions) => void; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export abstract class Runtime = any> implements IRuntime { protected readonly _mode: RuntimeMode; protected readonly _moduleManager: ModuleManager; protected readonly _logger: Logger; protected readonly _eventBus: EventBus; protected readonly _plugins: Plugin[]; readonly #deferredRegistrationScopeStartedListeners = new Set(); readonly #memoizeGetPlugin = memoize((pluginName: string) => this._plugins.find(x => x.name === pluginName)); constructor(options: RuntimeOptions = {}) { const { mode = "development", moduleManager = x => new ModuleManager(x, [new LocalModuleRegistry()]), loggers = [], plugins = [] } = options; this._mode = mode; this._moduleManager = moduleManager(this); this._logger = createCompositeLogger(mode === "development", loggers); this._eventBus = new EventBus(this._logger); this._plugins = plugins.map(x => x(this as unknown as TRuntime)); } get moduleManager(): ModuleManager { return this._moduleManager; } abstract registerRoute(route: TRoute, options?: RegisterRouteOptions): void; abstract registerPublicRoute(route: Omit, options?: RegisterRouteOptions): void; abstract get routes(): TRoute[]; abstract registerNavigationItem(navigationItem: TNavigationItem, options?: RegisterNavigationItemOptions): void; abstract getNavigationItems(options?: GetNavigationItemsOptions): TNavigationItem[]; abstract getNavigationItemsByMenu(): Map; abstract startDeferredRegistrationScope(options?: StartDeferredRegistrationScopeOptions): void; abstract completeDeferredRegistrationScope(options?: CompleteDeferredRegistrationScopeOptions): void; /** * Registers a listener executed when a deferred registration run starts, before any module's deferred * registration function. Implement it to clear and replay a registry that modules fill from their * deferred registration functions, otherwise its entries outlive the condition that registered them. * * The listener may return a function to be executed once the run has settled, while the runtime's scope * is still open. It's the place to commit a buffered registry, and it must not read the runtime's * navigation items: on an update run, the items of that run are not committed yet. * * Both the listener and the function it returns must be synchronous, nothing awaits them. An error * thrown by either is logged and swallowed, it never fails the run. * * When the registry lives in a plugin, implement {@link Plugin.onDeferredRegistrationScopeStarted} * instead — it's the same contract with nothing to subscribe or dispose. * * @returns A function removing the listener. */ registerDeferredRegistrationScopeStartedListener(callback: DeferredRegistrationScopeStartedListener) { this.#deferredRegistrationScopeStartedListeners.add(callback); return () => { this.removeDeferredRegistrationScopeStartedListener(callback); }; } /** * Removes a listener registered with {@link Runtime.registerDeferredRegistrationScopeStartedListener}. */ removeDeferredRegistrationScopeStartedListener(callback: DeferredRegistrationScopeStartedListener) { this.#deferredRegistrationScopeStartedListeners.delete(callback); } /** * Framework internal. Driven by "ModuleManager.#withDeferredRegistrationScope", alongside the plugin * hooks, so that both surfaces share one set of ordering and error guarantees. * * @returns The completion functions returned by the notified listeners, in registration order. */ _notifyDeferredRegistrationScopeStarted(options: DeferredRegistrationScopeOptions) { const completionFunctions: DeferredRegistrationScopeCompletionFunction[] = []; // The set is copied first so that a listener disposing of itself, or of another listener, doesn't // alter the notification that is currently in progress. for (const listener of new Set(this.#deferredRegistrationScopeStartedListeners)) { try { const completionFunction = listener({ ...options }); if (typeof completionFunction === "function") { completionFunctions.push(completionFunction); } } catch (error: unknown) { // A faulty listener is isolated rather than failing the run, for the same reasons a faulty // plugin is. See "ModuleManager.#withDeferredRegistrationScope". this._logger .withText("[squide] An error occured while starting a deferred registration scope listener.") .withError(error as Error) .error(); } } return completionFunctions; } get mode() { return this._mode; } get plugins() { return this._plugins; } getPlugin(pluginName: string, options: GetPluginOptions = {}) { const { throwOnNotFound = true } = options; const plugin = this.#memoizeGetPlugin(pluginName); if (!plugin && throwOnNotFound) { throw new Error(`[squide] Cannot find a plugin named "${pluginName}". Did you register an instance of the plugin with the application runtime instance?`); } return plugin; } get logger() { return this._logger; } get eventBus() { return this._eventBus; } abstract startScope(logger: Logger): TRuntime; _getLogger(options: RuntimeMethodOptions = {}) { const { logger } = options; return logger ? logger : this._logger; } abstract _validateRegistrations(options?: ValidateRegistrationsOptions): void; } export abstract class RuntimeScope = Runtime> implements IRuntime { protected readonly _runtime: TRuntime; protected readonly _logger: Logger; constructor(runtime: TRuntime, logger: Logger) { this._runtime = runtime; this._logger = logger; } get moduleManager(): ModuleManager { throw new Error("[squide] Cannot retrieve the module manager from a runtime scope instance."); } registerRoute(route: TRoute, options: RegisterRouteOptions = {}) { this._runtime.registerRoute(route, { ...options, logger: this._getLogger(options) }); } registerPublicRoute(route: Omit, options: RegisterRouteOptions = {}) { this._runtime.registerPublicRoute(route, { ...options, logger: this._getLogger(options) }); } get routes(): TRoute[] { return this._runtime.routes; } registerNavigationItem(navigationItem: TNavigationItem, options: RegisterNavigationItemOptions = {}) { this._runtime.registerNavigationItem(navigationItem, { ...options, logger: this._getLogger(options) }); } getNavigationItems(options?: GetNavigationItemsOptions) { return this._runtime.getNavigationItems(options); } getNavigationItemsByMenu() { return this._runtime.getNavigationItemsByMenu(); } startDeferredRegistrationScope() { throw new Error("[squide] Cannot start a deferred registration scope from a runtime scope instance."); } completeDeferredRegistrationScope() { throw new Error("[squide] Cannot complete a deferred registration scope from a runtime scope instance."); } // Starting and completing a scope is restricted because it drives the run, but merely observing the // boundary is not, in the same way that the event bus is fully reachable from a runtime scope instance. registerDeferredRegistrationScopeStartedListener(callback: DeferredRegistrationScopeStartedListener) { return this._runtime.registerDeferredRegistrationScopeStartedListener(callback); } removeDeferredRegistrationScopeStartedListener(callback: DeferredRegistrationScopeStartedListener) { this._runtime.removeDeferredRegistrationScopeStartedListener(callback); } _notifyDeferredRegistrationScopeStarted(): DeferredRegistrationScopeCompletionFunction[] { throw new Error("[squide] Cannot notify the deferred registration scope started listeners from a runtime scope instance."); } get mode(): RuntimeMode { return this._runtime.mode; } get plugins() { return this._runtime.plugins; } getPlugin(pluginName: string, options?: GetPluginOptions) { return this._runtime.getPlugin(pluginName, options); } get logger() { return this._runtime.logger; } get eventBus() { return this._runtime.eventBus; } startScope(): TRuntime { throw new Error("[squide] Cannot start a runtime scope from a runtime scope instance."); } _getLogger(options: RuntimeMethodOptions = {}) { const { logger } = options; return logger ? logger : this._logger; } _validateRegistrations() { throw new Error("[squide] Cannot validate registrations from a runtime scope instance."); } }