import { ContextValues, CommonConfig, GlobalConfig, InheritableCfg } from './types.js'; import { Output } from './Output'; export class CommonCfg implements InheritableCfg { name: string; parent?: InheritableCfg; #config: CommonConfig; constructor(name: string, cfg?: CommonConfig, parent?: InheritableCfg) { this.name = name; this.parent = parent; this.#config = cfg || {}; } getConfig(mergeParents: boolean = true): GlobalConfig { const parentConfig: GlobalConfig | undefined = this.parent?.getConfig(); if (!mergeParents) { return { logLevels: parentConfig?.logLevels || [], enabled: true, ...this.#config, } } let parentContext: ContextValues = parentConfig?.context || {}; const result = { logLevels: [], enabled: true, ...parentConfig, ...this.#config, context: { ...parentContext, ...this.#config.context || {}, } } return result; } setConfig(newConfig: CommonConfig, replace: boolean = false) { if (replace === true) { this.#config = newConfig; } else { this.#config = { ...this.#config, ...newConfig, } } } getLogLevel(): string | undefined { return this.#config.logLevel; } setLogLevel(levelName: string | undefined) { this.#config.logLevel = levelName; } setContext(newContext: ContextValues) { this.#config.context = newContext; } addContext(newContext: ContextValues) { const thisConfig: CommonConfig = this.#config; if (thisConfig.context === undefined) { thisConfig.context = { ...newContext, }; } else { const newContextKeys = Object.keys(newContext); if (newContextKeys.length > 0) { for (const key of newContextKeys) { thisConfig.context[key] = newContext[key]; } } } this.#config = thisConfig; } getChild(name, cfg?: CommonConfig): CommonCfg { return new CommonCfg(name, cfg, this); } getDebugVar(): string | undefined { return this.#config.debugVar; } }