@navios/core 2.0.0-alpha.0 → 2.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +33 -3
  2. package/README.md +8 -6
  3. package/lib/{async-context-6pdlnNLA.d.mts → async-context-BAdt7bno.d.mts} +11 -9
  4. package/lib/async-context-BAdt7bno.d.mts.map +1 -0
  5. package/lib/{async-context-Dqk7pE-D.d.cts → async-context-RsWmy2Hi.d.cts} +11 -9
  6. package/lib/async-context-RsWmy2Hi.d.cts.map +1 -0
  7. package/lib/{attribute-factory-B3VuYnp7.d.cts → attribute-factory-BW1kgBqf.d.mts} +2 -2
  8. package/lib/{attribute-factory-B3VuYnp7.d.cts.map → attribute-factory-BW1kgBqf.d.mts.map} +1 -1
  9. package/lib/{attribute-factory-mKOXoVnV.d.mts → attribute-factory-DqN4x5XM.d.cts} +2 -2
  10. package/lib/{attribute-factory-mKOXoVnV.d.mts.map → attribute-factory-DqN4x5XM.d.cts.map} +1 -1
  11. package/lib/attribute-value-BNiJjxl1.mjs +225 -0
  12. package/lib/attribute-value-BNiJjxl1.mjs.map +1 -0
  13. package/lib/attribute-value-Cux5HhOL.cjs +314 -0
  14. package/lib/attribute-value-Cux5HhOL.cjs.map +1 -0
  15. package/lib/{basic-execution-context-DSk5MNtc.cjs → basic-execution-context-5uq2DvEA.cjs} +66 -29
  16. package/lib/basic-execution-context-5uq2DvEA.cjs.map +1 -0
  17. package/lib/{basic-execution-context-CeGuhMOz.mjs → basic-execution-context-u1VktGoM.mjs} +61 -30
  18. package/lib/basic-execution-context-u1VktGoM.mjs.map +1 -0
  19. package/lib/{execution-context-BPD3FeFb.d.mts → execution-context-BVSmLkYp.d.cts} +2 -2
  20. package/lib/{execution-context-BPD3FeFb.d.mts.map → execution-context-BVSmLkYp.d.cts.map} +1 -1
  21. package/lib/{execution-context-BTJdHhbf.d.cts → execution-context-C5F9rojO.d.mts} +2 -2
  22. package/lib/{execution-context-BTJdHhbf.d.cts.map → execution-context-C5F9rojO.d.mts.map} +1 -1
  23. package/lib/{module-graph-DCP9MHG0.cjs → execution-context-token--cKS4cJv.cjs} +135 -12
  24. package/lib/execution-context-token--cKS4cJv.cjs.map +1 -0
  25. package/lib/{module-graph-xvVEykFM.mjs → execution-context-token-Cb3M3Ao0.mjs} +93 -12
  26. package/lib/execution-context-token-Cb3M3Ao0.mjs.map +1 -0
  27. package/lib/index.cjs +84 -101
  28. package/lib/index.cjs.map +1 -1
  29. package/lib/index.d.cts +14 -10
  30. package/lib/index.d.cts.map +1 -1
  31. package/lib/index.d.mts +14 -10
  32. package/lib/index.d.mts.map +1 -1
  33. package/lib/index.mjs +76 -92
  34. package/lib/index.mjs.map +1 -1
  35. package/lib/legacy-compat/index.cjs +2 -2
  36. package/lib/legacy-compat/index.d.cts +3 -3
  37. package/lib/legacy-compat/index.d.mts +2 -2
  38. package/lib/legacy-compat/index.mjs +2 -2
  39. package/lib/{module-DZewk_2r.cjs → module-Bz83ZnJ5.cjs} +43 -34
  40. package/lib/module-Bz83ZnJ5.cjs.map +1 -0
  41. package/lib/{module-options-Dmse0gii.d.mts → module-options-CSqQUSTm.d.mts} +2 -2
  42. package/lib/{module-options-Dmse0gii.d.mts.map → module-options-CSqQUSTm.d.mts.map} +1 -1
  43. package/lib/{module-options-IuDO-p8u.d.cts → module-options-DSRBri4J.d.cts} +2 -2
  44. package/lib/{module-options-IuDO-p8u.d.cts.map → module-options-DSRBri4J.d.cts.map} +1 -1
  45. package/lib/{module-Bha7GER_.mjs → module-zPXwR2qp.mjs} +38 -35
  46. package/lib/module-zPXwR2qp.mjs.map +1 -0
  47. package/lib/settled-within-B6gpu2XW.cjs +32 -0
  48. package/lib/settled-within-B6gpu2XW.cjs.map +1 -0
  49. package/lib/settled-within-Bc2pj8WB.mjs +21 -0
  50. package/lib/settled-within-Bc2pj8WB.mjs.map +1 -0
  51. package/lib/testing/index.cjs +12 -34
  52. package/lib/testing/index.cjs.map +1 -1
  53. package/lib/testing/index.d.cts +2 -2
  54. package/lib/testing/index.d.cts.map +1 -1
  55. package/lib/testing/index.d.mts +1 -1
  56. package/lib/testing/index.d.mts.map +1 -1
  57. package/lib/testing/index.mjs +12 -34
  58. package/lib/testing/index.mjs.map +1 -1
  59. package/lib/transport.cjs +19 -8
  60. package/lib/transport.d.cts +102 -38
  61. package/lib/transport.d.cts.map +1 -1
  62. package/lib/transport.d.mts +102 -38
  63. package/lib/transport.d.mts.map +1 -1
  64. package/lib/transport.mjs +6 -7
  65. package/package.json +2 -2
  66. package/lib/async-context-6pdlnNLA.d.mts.map +0 -1
  67. package/lib/async-context-Dqk7pE-D.d.cts.map +0 -1
  68. package/lib/attribute-value-CjX9ZkLq.cjs +0 -172
  69. package/lib/attribute-value-CjX9ZkLq.cjs.map +0 -1
  70. package/lib/attribute-value-DMEA255r.mjs +0 -119
  71. package/lib/attribute-value-DMEA255r.mjs.map +0 -1
  72. package/lib/basic-execution-context-CeGuhMOz.mjs.map +0 -1
  73. package/lib/basic-execution-context-DSk5MNtc.cjs.map +0 -1
  74. package/lib/execution-context-token-BXUKB2hf.cjs +0 -112
  75. package/lib/execution-context-token-BXUKB2hf.cjs.map +0 -1
  76. package/lib/execution-context-token-CrXmTvk2.mjs +0 -77
  77. package/lib/execution-context-token-CrXmTvk2.mjs.map +0 -1
  78. package/lib/module-Bha7GER_.mjs.map +0 -1
  79. package/lib/module-DZewk_2r.cjs.map +0 -1
  80. package/lib/module-graph-DCP9MHG0.cjs.map +0 -1
  81. package/lib/module-graph-xvVEykFM.mjs.map +0 -1
  82. package/lib/module-metadata-C8S92seK.cjs +0 -95
  83. package/lib/module-metadata-C8S92seK.cjs.map +0 -1
  84. package/lib/module-metadata-k3RTt20x.mjs +0 -66
  85. package/lib/module-metadata-k3RTt20x.mjs.map +0 -1
package/lib/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["InjectionToken","registerInjectable","InjectionToken","inject","Container","registerInjectable","InjectableScope","Container","provide","InjectionToken","registerProvider"],"sources":["../src/logger/cli-colors.mts","../src/logger/log-levels.mts","../src/logger/logger-output.mts","../src/logger/type-guards.mts","../src/logger/console-logger.mts","../src/internal/schema-from-guard.mts","../src/logger/pending-output.mts","../src/logger/logger.mts","../src/plugins/order-plugins.mts","../src/application/lifecycle-hooks.mts","../src/application/lifecycle-step.mts","../src/application/module-providers.mts","../src/application/settled-within.mts","../src/application/shutdown-signals.mts","../src/application/application.mts","../src/config/config-service.mts","../src/config/env.mts","../src/config/describe-issue.mts","../src/config/provide-config.mts","../src/config/env-config-provider.mts","../src/execution/context-key.mts","../src/plugins/plugin.mts"],"sourcesContent":["type ColorTextFn = (text: string) => string\n\nconst isColorAllowed = () => !process.env.NO_COLOR\nconst colorIfAllowed = (colorFn: ColorTextFn) => (text: string) =>\n isColorAllowed() ? colorFn(text) : text\n\nexport const clc = {\n bold: colorIfAllowed((text: string) => `\\x1B[1m${text}\\x1B[0m`),\n green: colorIfAllowed((text: string) => `\\x1B[32m${text}\\x1B[39m`),\n yellow: colorIfAllowed((text: string) => `\\x1B[33m${text}\\x1B[39m`),\n red: colorIfAllowed((text: string) => `\\x1B[31m${text}\\x1B[39m`),\n magentaBright: colorIfAllowed((text: string) => `\\x1B[95m${text}\\x1B[39m`),\n cyanBright: colorIfAllowed((text: string) => `\\x1B[96m${text}\\x1B[39m`),\n}\nexport const yellow = colorIfAllowed((text: string) => `\\x1B[38;5;3m${text}\\x1B[39m`)\n","/**\n * Available log levels in order of severity (lowest to highest).\n */\nexport const LOG_LEVELS = [\n 'verbose',\n 'debug',\n 'log',\n 'warn',\n 'error',\n 'fatal',\n] as const satisfies string[]\n\n/**\n * Log level type.\n *\n * Represents the severity level of a log message.\n * Levels are: 'verbose', 'debug', 'log', 'warn', 'error', 'fatal'\n *\n * @publicApi\n */\nexport type LogLevel = (typeof LOG_LEVELS)[number]\n\n/**\n * @publicApi\n */\nexport function isLogLevel(maybeLogLevel: any): maybeLogLevel is LogLevel {\n return LOG_LEVELS.includes(maybeLogLevel)\n}\n\nconst LOG_LEVEL_VALUES: Record<LogLevel, number> = {\n verbose: 0,\n debug: 1,\n log: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n}\n\n/**\n * Checks if target level is enabled.\n * @param targetLevel target level\n * @param logLevels array of enabled log levels\n */\nexport function isLogLevelEnabled(\n targetLevel: LogLevel,\n logLevels: LogLevel[] | undefined,\n): boolean {\n if (!logLevels || (Array.isArray(logLevels) && logLevels?.length === 0)) {\n return false\n }\n if (logLevels.includes(targetLevel)) {\n return true\n }\n const highestLogLevelValue = logLevels\n .map((level) => LOG_LEVEL_VALUES[level])\n .sort((a, b) => b - a)?.[0]\n\n const targetLevelValue = LOG_LEVEL_VALUES[targetLevel]\n return targetLevelValue >= highestLogLevelValue\n}\n\nfunction requireLogLevel(level: string): LogLevel {\n if (!isLogLevel(level)) {\n throw new Error(`parse error (unknown log level): ${level}`)\n }\n return level\n}\n\n/**\n * Reads log levels out of a setting: `'error'`, `'warn,error'`, `'>=warn'` or\n * `'>warn'`. An empty string stands for every level.\n * @publicApi\n */\nexport function filterLogLevels(parseableString = ''): LogLevel[] {\n const sanitizedString = parseableString.replaceAll(' ', '').toLowerCase()\n\n if (sanitizedString === '') {\n return [...LOG_LEVELS]\n }\n if (sanitizedString[0] === '>') {\n const orEqual = sanitizedString[1] === '='\n const logLevelIndex = LOG_LEVELS.indexOf(\n requireLogLevel(sanitizedString.substring(orEqual ? 2 : 1)),\n )\n return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1)\n }\n return sanitizedString.split(',').map(requireLogLevel)\n}\n","import { InjectionToken } from '@navios/di'\n\nimport type { LogLevel } from './log-levels.mjs'\n\n/**\n * @publicApi\n */\nexport interface LoggerService {\n /**\n * Write a 'log' level log.\n */\n log(message: any, ...optionalParams: any[]): any\n\n /**\n * Write an 'error' level log.\n */\n error(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'warn' level log.\n */\n warn(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'debug' level log.\n */\n debug?(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'verbose' level log.\n */\n verbose?(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'fatal' level log.\n */\n fatal?(message: any, ...optionalParams: any[]): any\n\n /**\n * Set log levels.\n * @param levels log levels\n */\n setLogLevels?(levels: LogLevel[]): any\n}\n\n/**\n * Injection token for the logger output service.\n *\n * This token is used to provide a custom logger implementation.\n * By default, it's bound to ConsoleLogger.\n */\nexport const LoggerOutput = InjectionToken.create<LoggerService>('LoggerOutput')\n","export const isUndefined = (obj: any): obj is undefined => typeof obj === 'undefined'\n\nexport const isObject = (fn: any): fn is object => !isNil(fn) && typeof fn === 'object'\n\nexport const isPlainObject = (fn: any): fn is object => {\n if (!isObject(fn)) {\n return false\n }\n const proto = Object.getPrototypeOf(fn)\n if (proto === null) {\n return true\n }\n const ctor = Object.prototype.hasOwnProperty.call(proto, 'constructor') && proto.constructor\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object)\n )\n}\n\nexport const isFunction = (val: any): val is Function => typeof val === 'function'\nexport const isString = (val: any): val is string => typeof val === 'string'\nexport const isNil = (val: any): val is null | undefined => isUndefined(val) || val === null\n","// Ported from NestJS (https://github.com/nestjs/nest, MIT licence). Big thanks\n// to the NestJS team for their work.\nimport type { InspectOptions } from 'util'\nimport { inspect } from 'util'\n\nimport { registerInjectable } from '@navios/di'\n\nimport { currentContext } from '../execution/async-context.mjs'\n\nimport { clc, yellow } from './cli-colors.mjs'\nimport { isLogLevelEnabled, LOG_LEVELS } from './log-levels.mjs'\nimport { LoggerOutput } from './logger-output.mjs'\nimport { isFunction, isPlainObject, isString, isUndefined } from './type-guards.mjs'\n\nimport type { ConsoleLoggerOptions } from './console-logger-options.mjs'\nimport type { LogLevel } from './log-levels.mjs'\nimport type { LoggerService } from './logger-output.mjs'\n\nconst DEFAULT_DEPTH = 5\n\n/** Every level, and `log` and above in production. */\nfunction defaultLogLevels(): LogLevel[] {\n return process.env.NODE_ENV === 'production'\n ? LOG_LEVELS.slice(LOG_LEVELS.indexOf('log'))\n : [...LOG_LEVELS]\n}\n\ninterface JsonError {\n name: string\n message: string\n stack?: string\n cause?: unknown\n /** What the error itself carries: `code`, `status`, `detail`. */\n [field: string]: unknown\n}\n\n/** Has a place of its own, or stands on the prototype in most errors. */\nconst commonFields = new Set(['name', 'message', 'stack', 'cause'])\n\n/**\n * An error as JSON shows it. `encode` gives the value to show for one that is\n * not an error.\n */\nfunction toJsonError(\n error: Error,\n encode: (value: unknown) => unknown,\n path: unknown[] = [],\n): JsonError {\n const inside = [...path, error]\n const showOne = (value: unknown): unknown => {\n if (inside.includes(value)) {\n return '[Circular]'\n }\n return value instanceof Error ? toJsonError(value, encode, inside) : encode(value)\n }\n const show = (value: unknown) => (Array.isArray(value) ? value.map(showOne) : showOne(value))\n const { name, message, stack, cause } = error\n const described: JsonError = { name, message, stack }\n if (cause !== undefined) {\n described.cause = show(cause)\n }\n if (error instanceof AggregateError) {\n described.errors = show(error.errors)\n }\n for (const field of Object.keys(error)) {\n if (!commonFields.has(field)) {\n try {\n described[field] = show((error as unknown as Record<string, unknown>)[field])\n } catch (reason) {\n described[field] = `[cannot be read: ${reason instanceof Error ? reason.message : reason}]`\n }\n }\n }\n return described\n}\n\nconst dateTimeFormatter = new Intl.DateTimeFormat(undefined, {\n year: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n day: '2-digit',\n month: '2-digit',\n})\n\nfunction withoutUndefined(options: ConsoleLoggerOptions = {}): ConsoleLoggerOptions {\n return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined))\n}\n\n/**\n * Prints to the console. Without options it prints every level, `log` and\n * above when `NODE_ENV` is `production`, in colour when stdout is a terminal.\n * @publicApi\n */\nexport class ConsoleLogger implements LoggerService {\n /**\n * Creates a new ConsoleLogger instance with the given options.\n * This is a convenience method that instantiates and sets up the logger in one call.\n */\n static create(): ConsoleLogger\n static create(context: string): ConsoleLogger\n static create(options: ConsoleLoggerOptions): ConsoleLogger\n static create(context: string, options: ConsoleLoggerOptions): ConsoleLogger\n static create(\n contextOrOptions?: string | ConsoleLoggerOptions,\n options?: ConsoleLoggerOptions,\n ): ConsoleLogger {\n return new this(contextOrOptions as string, options as ConsoleLoggerOptions)\n }\n\n /**\n * The options in effect: those given so far, and the defaults.\n */\n protected options: ConsoleLoggerOptions = {}\n /**\n * The context of the logger (can be set manually or automatically inferred).\n */\n protected context?: string\n /**\n * The original context of the logger (set by the constructor or `setup`).\n */\n protected originalContext?: string\n /**\n * The options used for the \"inspect\" method.\n */\n protected inspectOptions: InspectOptions = {}\n /**\n * The last timestamp at which the log message was printed.\n */\n protected lastTimestampAt?: number\n /**\n * The options that were given.\n */\n private given: ConsoleLoggerOptions = {}\n\n constructor()\n constructor(context: string)\n constructor(options: ConsoleLoggerOptions)\n constructor(context: string, options: ConsoleLoggerOptions)\n constructor(contextOrOptions?: string | ConsoleLoggerOptions, options?: ConsoleLoggerOptions) {\n this.setup(contextOrOptions as string, options as ConsoleLoggerOptions)\n }\n\n /**\n * Changes the options that are given and leaves the others as they are.\n */\n setup(): void\n setup(context: string): void\n setup(options: ConsoleLoggerOptions): void\n setup(context: string, options: ConsoleLoggerOptions): void\n setup(contextOrOptions?: string | ConsoleLoggerOptions, options?: ConsoleLoggerOptions) {\n const [context, opts] = isString(contextOrOptions)\n ? [contextOrOptions, options]\n : options\n ? [undefined, options]\n : [contextOrOptions?.context, contextOrOptions]\n\n this.applyOptions({ ...this.given, ...withoutUndefined(opts) })\n\n if (context) {\n this.context = context\n this.originalContext = context\n }\n }\n\n /**\n * Like `setup`, for the options that were not given.\n * @internal\n */\n setDefaults(options: ConsoleLoggerOptions): void {\n this.applyOptions({ ...options, ...this.given })\n }\n\n private applyOptions(given: ConsoleLoggerOptions): void {\n this.given = given\n this.options = {\n ...given,\n logLevels: given.logLevels ?? defaultLogLevels(),\n colors: given.colors ?? (!given.json && process.stdout.isTTY === true),\n prefix: given.prefix ?? 'Navios',\n }\n this.inspectOptions = this.getInspectOptions()\n }\n\n /**\n * Write a 'log' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n log(message: any, context?: string): void\n log(message: any, ...optionalParams: [...any, string?]): void\n log(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('log')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'log')\n }\n\n /**\n * Write an 'error' level log, if the configured level allows for it.\n * Prints to `stderr` with newline.\n */\n error(message: any, stackOrContext?: string): void\n error(message: any, stack?: string, context?: string): void\n error(message: any, ...optionalParams: [...any, string?, string?]): void\n error(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('error')) {\n return\n }\n const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([\n message,\n ...optionalParams,\n ])\n\n this.printMessages(messages, context, 'error', undefined, 'stderr', stack)\n this.printStackTrace(stack as string)\n }\n\n /**\n * Write a 'warn' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n warn(message: any, context?: string): void\n warn(message: any, ...optionalParams: [...any, string?]): void\n warn(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('warn')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'warn')\n }\n\n /**\n * Write a 'debug' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n debug(message: any, context?: string): void\n debug(message: any, ...optionalParams: [...any, string?]): void\n debug(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('debug')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'debug')\n }\n\n /**\n * Write a 'verbose' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n verbose(message: any, context?: string): void\n verbose(message: any, ...optionalParams: [...any, string?]): void\n verbose(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('verbose')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'verbose')\n }\n\n /**\n * Write a 'fatal' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n fatal(message: any, context?: string): void\n fatal(message: any, ...optionalParams: [...any, string?]): void\n fatal(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('fatal')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'fatal')\n }\n\n /**\n * Set log levels\n * @param levels log levels\n */\n setLogLevels(levels: LogLevel[]) {\n this.setup({ logLevels: levels })\n }\n\n /**\n * Set logger context\n * @param context context\n */\n setContext(context: string) {\n this.context = context\n }\n\n /**\n * Resets the logger context to the value that was passed to the constructor or `setup`.\n */\n resetContext() {\n this.context = this.originalContext\n }\n\n isLevelEnabled(level: LogLevel): boolean {\n const logLevels = this.options?.logLevels\n return isLogLevelEnabled(level, logLevels)\n }\n\n /**\n * Gets the current request ID from the AsyncLocalStorage store.\n * Only returns a value if the requestId option is enabled.\n */\n protected getCurrentRequestId(): string | undefined {\n if (!this.options.requestId) {\n return undefined\n }\n return currentContext()?.id\n }\n\n protected getTimestamp(): string {\n return dateTimeFormatter.format(Date.now())\n }\n\n protected printMessages(\n messages: unknown[],\n context = '',\n logLevel: LogLevel = 'log',\n requestId?: string,\n writeStreamType?: 'stdout' | 'stderr',\n errorStack?: unknown,\n ) {\n const resolvedRequestId = requestId ?? this.getCurrentRequestId()\n if (this.options.json) {\n for (const line of this.toJsonLines(messages)) {\n this.guarded(() =>\n this.printAsJson(line.message, {\n context,\n logLevel,\n writeStreamType,\n errorStack,\n requestId: resolvedRequestId,\n error: line.error,\n }),\n )\n }\n return\n }\n for (const message of messages) {\n this.guarded(() => {\n const pidMessage = this.formatPid(process.pid)\n const contextMessage = this.formatContext(context)\n const timestampDiff = this.updateAndGetTimestampDiff()\n const formattedLogLevel = logLevel.toUpperCase().padStart(7, ' ')\n const formattedMessage = this.formatMessage(\n logLevel,\n message,\n pidMessage,\n formattedLogLevel,\n contextMessage,\n timestampDiff,\n resolvedRequestId,\n )\n\n process[writeStreamType ?? 'stdout'].write(formattedMessage)\n })\n }\n }\n\n /** A message and the error logged with it share a line. */\n private toJsonLines(messages: unknown[]): Array<{ message: unknown; error?: Error }> {\n const lines: Array<{ message: unknown; error?: Error }> = []\n for (const message of messages) {\n const last = lines.at(-1)\n if (!(message instanceof Error)) {\n lines.push({ message })\n } else if (last && !last.error) {\n last.error = message\n } else {\n lines.push({ message: message.message, error: message })\n }\n }\n return lines\n }\n\n /** Logging must not fail the code that logs. */\n private guarded(print: () => void): void {\n try {\n print()\n } catch (error) {\n try {\n const reason = error instanceof Error ? error.message : String(error)\n process.stderr.write(`[Navios] A log message could not be printed: ${reason}\\n`)\n } catch {\n // There is nothing left to tell.\n }\n }\n }\n\n protected printAsJson(\n message: unknown,\n options: {\n context: string\n logLevel: LogLevel\n writeStreamType?: 'stdout' | 'stderr'\n errorStack?: unknown\n requestId?: string\n error?: Error\n },\n ) {\n type JsonLogObject = {\n level: LogLevel\n pid: number\n timestamp: number\n message: unknown\n context?: string\n stack?: unknown\n requestId?: string\n error?: JsonError\n }\n\n const logObject: JsonLogObject = {\n level: options.logLevel,\n pid: process.pid,\n timestamp: Date.now(),\n message,\n }\n\n if (options.context) {\n logObject.context = options.context\n }\n\n if (options.errorStack) {\n logObject.stack = options.errorStack\n }\n if (this.options.requestId && options.requestId) {\n logObject.requestId = options.requestId\n }\n if (options.error) {\n logObject.error = toJsonError(options.error, (value) => this.encodable(value))\n }\n\n const formattedMessage =\n !this.options.colors && this.inspectOptions.compact === true\n ? this.stringify(logObject)\n : inspect(logObject, this.inspectOptions)\n process[options.writeStreamType ?? 'stdout'].write(`${formattedMessage}\\n`)\n }\n\n private stringify(logObject: { message: unknown; error?: JsonError }): string {\n const replacer = (key: string, value: unknown) => this.stringifyReplacer(key, value)\n try {\n return JSON.stringify(logObject, replacer)\n } catch {\n // Circular, or with a `toJSON` or a getter that throws.\n const { message, error } = logObject\n return JSON.stringify({\n ...logObject,\n message: typeof message === 'string' ? message : inspect(message, this.inspectOptions),\n error: error && inspect(error, this.inspectOptions),\n })\n }\n }\n\n /** A field that JSON cannot hold must not cost the rest of an error. */\n private encodable(value: unknown): unknown {\n if (typeof value !== 'object' || value === null) {\n return value\n }\n try {\n JSON.stringify(value, (key, inner) => this.stringifyReplacer(key, inner))\n return value\n } catch {\n return inspect(value, { ...this.inspectOptions, depth: 1 })\n }\n }\n\n protected formatPid(pid: number) {\n const showPrefix = this.options.showPrefix ?? true\n const showPid = this.options.showPid ?? true\n\n if (!showPrefix && !showPid) {\n return ''\n }\n\n const prefix = showPrefix ? `[${this.options.prefix}]` : ''\n const pidPart = showPid ? `${pid}` : ''\n const separator = showPrefix && showPid ? ' ' : ''\n const suffix = showPrefix || showPid ? ' - ' : ''\n\n return `${prefix}${separator}${pidPart}${suffix}`\n }\n\n protected formatContext(context: string): string {\n const showContext = this.options.showContext ?? true\n if (!context || !showContext) {\n return ''\n }\n\n context = `[${context}] `\n return this.options.colors ? yellow(context) : context\n }\n\n protected formatMessage(\n logLevel: LogLevel,\n message: unknown,\n pidMessage: string,\n formattedLogLevel: string,\n contextMessage: string,\n timestampDiff: string,\n requestId?: string,\n ) {\n const output = this.stringifyMessage(message, logLevel)\n const showLogLevel = this.options.showLogLevel ?? true\n const showTimestamp = this.options.showTimestamp ?? true\n\n pidMessage = this.colorize(pidMessage, logLevel)\n formattedLogLevel = showLogLevel ? this.colorize(formattedLogLevel, logLevel) : ''\n\n const timestamp = showTimestamp ? this.getTimestamp() : ''\n const requestIdPart = this.getRequestId(requestId)\n\n // Build the message parts, filtering out empty ones\n const parts: string[] = []\n\n if (pidMessage) parts.push(pidMessage.trimEnd())\n if (requestIdPart) parts.push(requestIdPart.trimEnd())\n if (timestamp) parts.push(timestamp)\n if (formattedLogLevel) parts.push(formattedLogLevel)\n if (contextMessage) parts.push(contextMessage.trimEnd())\n\n const prefix = parts.length > 0 ? parts.join(' ') + ' ' : ''\n\n return `${prefix}${output}${timestampDiff}\\n`\n }\n\n protected getRequestId(requestId?: string) {\n if (this.options.requestId && requestId) {\n return `(${this.colorize(requestId, 'log')}) `\n }\n return ''\n }\n\n protected stringifyMessage(message: unknown, logLevel: LogLevel): string {\n if (isFunction(message)) {\n const messageAsStr = Function.prototype.toString.call(message)\n const isClass = messageAsStr.startsWith('class ')\n if (isClass) {\n // If the message is a class, we will display the class name.\n return this.stringifyMessage(message.name, logLevel)\n }\n // If the message is a non-class function, call it and re-resolve its value.\n return this.stringifyMessage(message(), logLevel)\n }\n\n if (typeof message === 'string') {\n return this.colorize(message, logLevel)\n }\n\n const outputText = inspect(message, this.inspectOptions)\n if (isPlainObject(message)) {\n return `Object(${Object.keys(message).length}) ${outputText}`\n }\n if (Array.isArray(message)) {\n return `Array(${message.length}) ${outputText}`\n }\n return outputText\n }\n\n protected colorize(message: string, logLevel: LogLevel) {\n if (!this.options.colors || this.options.json) {\n return message\n }\n const color = this.getColorByLogLevel(logLevel)\n return color(message)\n }\n\n protected printStackTrace(stack: string) {\n if (!stack || this.options.json) {\n return\n }\n this.guarded(() => process.stderr.write(`${stack}\\n`))\n }\n\n protected updateAndGetTimestampDiff(): string {\n const showTimeDiff = this.options?.showTimeDiff ?? false\n const includeTimestamp = this.lastTimestampAt && showTimeDiff\n const result = includeTimestamp\n ? this.formatTimestampDiff(Date.now() - this.lastTimestampAt!)\n : ''\n this.lastTimestampAt = Date.now()\n return result\n }\n\n protected formatTimestampDiff(timestampDiff: number) {\n const formattedDiff = ` +${timestampDiff}ms`\n return this.options.colors ? yellow(formattedDiff) : formattedDiff\n }\n\n protected getInspectOptions() {\n let breakLength = this.options.breakLength\n if (typeof breakLength === 'undefined') {\n breakLength = this.options.colors\n ? this.options.compact\n ? Infinity\n : undefined\n : this.options.compact === false\n ? undefined\n : Infinity // default breakLength to Infinity if inline is not set and colors is false\n }\n\n const inspectOptions: InspectOptions = {\n depth: this.options.depth ?? DEFAULT_DEPTH,\n sorted: this.options.sorted,\n showHidden: this.options.showHidden,\n compact: this.options.compact ?? (this.options.json ? true : false),\n colors: this.options.colors,\n breakLength,\n }\n\n if (this.options.maxArrayLength) {\n inspectOptions.maxArrayLength = this.options.maxArrayLength\n }\n if (this.options.maxStringLength) {\n inspectOptions.maxStringLength = this.options.maxStringLength\n }\n\n return inspectOptions\n }\n\n protected stringifyReplacer(key: string, value: unknown) {\n // Mimic util.inspect behavior for JSON logger with compact on and colors off\n if (typeof value === 'bigint') {\n return value.toString()\n }\n if (typeof value === 'symbol') {\n return value.toString()\n }\n\n if (value instanceof Map || value instanceof Set || value instanceof Error) {\n return `${inspect(value, this.inspectOptions)}`\n }\n return value\n }\n\n private getContextAndMessagesToPrint(args: unknown[]) {\n if (args?.length <= 1) {\n return { messages: args, context: this.context }\n }\n const lastElement = args[args.length - 1]\n const isContext = isString(lastElement)\n if (!isContext) {\n return { messages: args, context: this.context }\n }\n return {\n context: lastElement,\n messages: args.slice(0, args.length - 1),\n }\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]) {\n if (args.length === 2) {\n const [message, second] = args\n if (isUndefined(second)) {\n return { messages: [message], context: this.context }\n }\n if (!isString(second)) {\n return { messages: args, context: this.context }\n }\n return this.isStackFormat(second)\n ? { messages: [message], stack: second, context: this.context }\n : { messages: [message], context: second }\n }\n\n const { messages, context } = this.getContextAndMessagesToPrint(args)\n if (messages?.length <= 1) {\n return { messages, context }\n }\n const lastElement = messages[messages.length - 1]\n const isStack = isString(lastElement)\n // https://github.com/nestjs/nest/issues/11074#issuecomment-1421680060\n if (!isStack && !isUndefined(lastElement)) {\n return { messages, context }\n }\n return {\n stack: lastElement,\n messages: messages.slice(0, messages.length - 1),\n context,\n }\n }\n\n private isStackFormat(stack: string) {\n return /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(stack)\n }\n\n private getColorByLogLevel(level: LogLevel) {\n switch (level) {\n case 'debug':\n return clc.magentaBright\n case 'warn':\n return clc.yellow\n case 'error':\n return clc.red\n case 'verbose':\n return clc.cyanBright\n case 'fatal':\n return clc.bold\n default:\n return clc.green\n }\n }\n}\n\nregisterInjectable(ConsoleLogger, { token: LoggerOutput })\n","import type { StandardSchemaV1 } from '@navios/di'\n\n/**\n * A minimal Standard Schema built from a type guard. Used for the framework's\n * own option objects so that core needs no schema library at runtime.\n * @internal\n */\nexport function schemaFromGuard<T>(\n guard: (value: unknown) => value is T,\n message: string,\n): StandardSchemaV1<T, T> {\n return {\n '~standard': {\n version: 1,\n vendor: 'navios',\n validate: (value) => (guard(value) ? { value } : { issues: [{ message }] }),\n },\n }\n}\n","import type { Container } from '@navios/di'\n\nimport type { LoggerService } from './logger-output.mjs'\n\ntype Level = 'log' | 'error' | 'warn' | 'debug' | 'verbose' | 'fatal'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Stands in for the logger output of a container until everything that may\n * provide it, plugins included, has had its turn, and holds back what is\n * logged until then: resolving the output any earlier would settle it.\n */\nexport class PendingOutput implements LoggerService {\n private output: LoggerService | null = null\n private held: Array<[Level, unknown[]]> = []\n\n /** `settleNow` settles for the output that can be had at once. */\n constructor(readonly settleNow: () => void) {\n if (unsettled.size === 0) {\n process.on('exit', settleAll)\n }\n unsettled.add(this)\n }\n\n log(...args: any[]) {\n this.write('log', args)\n }\n\n error(...args: any[]) {\n this.write('error', args)\n }\n\n warn(...args: any[]) {\n this.write('warn', args)\n }\n\n debug(...args: any[]) {\n this.write('debug', args)\n }\n\n verbose(...args: any[]) {\n this.write('verbose', args)\n }\n\n fatal(...args: any[]) {\n this.write('fatal', args)\n }\n\n get isSettled(): boolean {\n return this.output !== null\n }\n\n /** Writes what is held, and everything from here on, to `output`. */\n settle(output: LoggerService): void {\n this.output = output\n if (unsettled.delete(this) && unsettled.size === 0) {\n process.off('exit', settleAll)\n }\n for (const [level, args] of this.held.splice(0)) {\n try {\n this.write(level, args)\n } catch {\n // Whoever logged it has gone on.\n console.error(...args)\n }\n }\n }\n\n private write(level: Level, args: unknown[]): void {\n if (this.output === null) {\n this.held.push([level, args])\n return\n }\n const [message, ...rest] = args\n this.output[level]?.(message, ...rest)\n }\n}\n\n/** Those whose messages would be lost if the process ended now. */\nconst unsettled = new Set<PendingOutput>()\n\nfunction settleAll(): void {\n for (const output of unsettled) {\n output.settleNow()\n }\n}\n\nconst pending = new WeakMap<Container, PendingOutput>()\n\n/** Makes loggers that are built in `container` from now on wait for its output. */\nexport function deferOutput(container: Container, settleNow: () => void): PendingOutput {\n const output = new PendingOutput(settleNow)\n pending.set(container, output)\n return output\n}\n\n/** Ends what `deferOutput` did, for loggers that are built from now on. */\nexport function endDeferral(container: Container): void {\n pending.delete(container)\n}\n\nexport function pendingOutput(container: Container): PendingOutput | undefined {\n return pending.get(container)\n}\n","import { Container, inject, InjectableScope, InjectionToken, registerInjectable } from '@navios/di'\n\nimport { schemaFromGuard } from '../internal/schema-from-guard.mjs'\n\nimport { LoggerOutput } from './logger-output.mjs'\nimport { pendingOutput } from './pending-output.mjs'\n\nimport type { LoggerService } from './logger-output.mjs'\n\n/**\n * Schema for logger options.\n */\nexport type LoggerOptions = { context?: string } | undefined\n\nexport const loggerOptionsSchema = schemaFromGuard<LoggerOptions>(\n (value): value is LoggerOptions =>\n value === undefined ||\n (typeof value === 'object' &&\n value !== null &&\n ((value as { context?: unknown }).context === undefined ||\n typeof (value as { context?: unknown }).context === 'string')),\n 'Logger options must be an object with an optional string `context`',\n)\n\n/**\n * Injection token for the Logger service.\n *\n * Use this token to inject a contextualized logger instance.\n *\n * @example\n * ```typescript\n * const logger = inject(Logger, { context: 'MyService' })\n * logger.log('Hello world') // Logs with context: [MyService]\n * ```\n */\nexport const Logger = InjectionToken.create<LoggerInstance, typeof loggerOptionsSchema>(\n 'Logger',\n loggerOptionsSchema,\n)\n\n/**\n * Logger service instance that can be injected into services and controllers.\n *\n * Provides contextualized logging with automatic context injection.\n * The context is set when the logger is injected using the `inject` function.\n *\n * @example\n * ```typescript\n * @Injectable()\n * export class UserService {\n * private logger = inject(Logger, { context: UserService.name })\n *\n * async findUser(id: string) {\n * this.logger.log(`Finding user ${id}`)\n * // Logs with context: [UserService]\n * }\n * }\n * ```\n */\nexport class LoggerInstance implements LoggerService {\n protected localInstance: LoggerService = pendingOutput(inject(Container)) ?? inject(LoggerOutput)\n\n protected context?: string\n\n constructor(config: LoggerOptions = {}) {\n this.context = config?.context\n }\n\n /**\n * Write an 'error' level log.\n */\n error(message: any, stack?: string, context?: string): void\n error(message: any, ...optionalParams: [...any, string?, string?]): void\n error(message: any, ...optionalParams: any[]) {\n optionalParams = this.context\n ? (optionalParams.length ? optionalParams : [undefined]).concat(this.context)\n : optionalParams\n\n this.localInstance?.error(message, ...optionalParams)\n }\n\n /**\n * Write a 'log' level log.\n */\n log(message: any, context?: string): void\n log(message: any, ...optionalParams: [...any, string?]): void\n log(message: any, ...optionalParams: any[]) {\n optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams\n this.localInstance?.log(message, ...optionalParams)\n }\n\n /**\n * Write a 'warn' level log.\n */\n warn(message: any, context?: string): void\n warn(message: any, ...optionalParams: [...any, string?]): void\n warn(message: any, ...optionalParams: any[]) {\n optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams\n this.localInstance?.warn(message, ...optionalParams)\n }\n\n /**\n * Write a 'debug' level log.\n */\n debug(message: any, context?: string): void\n debug(message: any, ...optionalParams: [...any, string?]): void\n debug(message: any, ...optionalParams: any[]) {\n optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams\n this.localInstance?.debug?.(message, ...optionalParams)\n }\n\n /**\n * Write a 'verbose' level log.\n */\n verbose(message: any, context?: string): void\n verbose(message: any, ...optionalParams: [...any, string?]): void\n verbose(message: any, ...optionalParams: any[]) {\n optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams\n this.localInstance?.verbose?.(message, ...optionalParams)\n }\n\n /**\n * Write a 'fatal' level log.\n */\n fatal(message: any, context?: string): void\n fatal(message: any, ...optionalParams: [...any, string?]): void\n fatal(message: any, ...optionalParams: any[]) {\n optionalParams = this.context ? optionalParams.concat(this.context) : optionalParams\n this.localInstance?.fatal?.(message, ...optionalParams)\n }\n}\n\n// Transient: the context is free text, so a stored instance per context would\n// be one for every id that is logged with.\nregisterInjectable(LoggerInstance, { token: Logger, scope: InjectableScope.Transient })\n","import { isDeepStrictEqual } from 'node:util'\n\nimport type { PluginInstance } from './plugin.mjs'\n\n/**\n * Orders plugins so that each comes after the plugins it depends on. A plugin\n * registered twice is applied once; registering it again with other options\n * is an error, since only one of the two could take effect, and so are two\n * plugins of one name.\n */\nexport function orderPlugins(plugins: readonly PluginInstance[]): PluginInstance[] {\n const byName = new Map<string, PluginInstance>()\n for (const plugin of plugins) {\n const { name } = plugin.definition\n const existing = byName.get(name)\n if (existing === undefined) {\n byName.set(name, plugin)\n } else if (existing.definition !== plugin.definition) {\n throw new Error(`[Navios] Two plugins are named \"${name}\".`)\n } else if (!isDeepStrictEqual(existing.options, plugin.options)) {\n throw new Error(\n `[Navios] Plugin \"${name}\" is registered twice with different options. Register it once.`,\n )\n }\n }\n const ordered: PluginInstance[] = []\n const state = new Map<string, 'visiting' | 'done'>()\n const visit = (name: string, requiredBy: string | null): void => {\n const plugin = byName.get(name)\n if (!plugin) {\n throw new Error(\n `[Navios] Plugin \"${requiredBy}\" depends on \"${name}\", which is not registered.`,\n )\n }\n const current = state.get(name)\n if (current === 'done') {\n return\n }\n if (current === 'visiting') {\n throw new Error(`[Navios] Plugins depend on each other in a cycle through \"${name}\".`)\n }\n state.set(name, 'visiting')\n for (const dependency of plugin.definition.dependsOn ?? []) {\n visit(dependency, name)\n }\n state.set(name, 'done')\n ordered.push(plugin)\n }\n for (const name of byName.keys()) {\n visit(name, null)\n }\n return ordered\n}\n","export interface OnModuleInit {\n onModuleInit(): void | Promise<void>\n}\n\nexport interface OnApplicationBootstrap {\n onApplicationBootstrap(): void | Promise<void>\n}\n\nexport interface OnApplicationShutdown {\n onApplicationShutdown(signal?: string): void | Promise<void>\n}\n\n/**\n * Whether an object or its class declares a hook. The property is looked up and\n * not read: a proxy may answer for every name, or throw for one it does not know.\n */\nexport function declaresHook(instance: unknown, name: string): boolean {\n if ((typeof instance !== 'object' && typeof instance !== 'function') || instance === null) {\n return false\n }\n try {\n for (let at: object | null = instance; at !== null; at = Reflect.getPrototypeOf(at)) {\n const declared = Reflect.getOwnPropertyDescriptor(at, name)\n if (declared !== undefined) {\n return declared.get !== undefined || typeof declared.value === 'function'\n }\n }\n } catch {\n // A proxy that does not even let itself be looked at.\n }\n return false\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nexport type LifecyclePhase = 'init' | 'start' | 'shutdown'\n\n/**\n * One piece of code that an application calls and waits for: a hook, the\n * set-up of a plugin, the stop of a transport. When it calls back into a\n * lifecycle method that waits for the step itself, neither would ever finish.\n */\ninterface Step {\n readonly owner: object\n readonly phase: LifecyclePhase\n readonly outer: Step | undefined\n running: boolean\n}\n\nconst storage = new AsyncLocalStorage<Step>()\nlet running = 0\n\n/** Runs `fn` as a step of `owner`. */\nexport function runStep<T>(\n owner: object,\n phase: LifecyclePhase,\n fn: () => T | Promise<T>,\n): Promise<T> {\n const step: Step = { owner, phase, outer: storage.getStore(), running: true }\n running++\n return storage.run(step, async () => {\n try {\n return await fn()\n } finally {\n // Timers and servers that the step created stay in its async context,\n // but nobody waits for the step any more.\n step.running = false\n if (--running === 0) {\n // On runtimes that implement the storage with async hooks, it would\n // go on costing something for every promise of the process.\n storage.disable()\n }\n }\n })\n}\n\n/** The phase of the innermost step of `owner` that the caller is part of. */\nexport function currentPhase(owner: object): LifecyclePhase | null {\n for (let step = storage.getStore(); step !== undefined; step = step.outer) {\n if (step.owner === owner && step.running) {\n return step.phase\n }\n }\n return null\n}\n\n/** Runs `fn` as part of no step. */\nexport function outsideSteps<T>(fn: () => T): T {\n return storage.exit(fn)\n}\n","import type { ClassType, InjectionToken, Provider } from '@navios/di'\n\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ModuleProvider {\n readonly module: ClassType\n readonly provider: Provider\n /**\n * Another module that provides something else for the token, when nothing\n * says which of the two is meant.\n */\n readonly rival?: ClassType\n}\n\ntype Candidate = { node: ModuleNode; provider: Provider }\n\n/** What a provider consists of. Its type does not show it. */\nfunction parts(provider: Provider): unknown[] {\n const { record } = provider as unknown as { record: Record<string, unknown> }\n return [record.kind, record.scope, record.target, record.fn, record.value]\n}\n\n/** Whether two providers of one token come to the same. */\nfunction isSame(left: Provider, right: Provider): boolean {\n const other = parts(right)\n return parts(left).every((part, index) => Object.is(part, other[index]))\n}\n\nfunction importsIndirectly(importer: ModuleNode, imported: ModuleNode): boolean {\n const seen = new Set<ModuleNode>()\n const pending = [imported]\n for (let node = pending.pop(); node !== undefined; node = pending.pop()) {\n if (node === importer) {\n return true\n }\n if (!seen.has(node)) {\n seen.add(node)\n pending.push(...node.importers)\n }\n }\n return false\n}\n\nfunction choose(candidates: readonly Candidate[]): ModuleProvider {\n const [first] = candidates\n const others = candidates.filter(({ provider }) => !isSame(provider, first.provider))\n if (others.length === 0) {\n return { module: first.node.module, provider: first.provider }\n }\n const [top, ...rest] = candidates.filter(\n ({ node }) =>\n !candidates.some((other) => other.node !== node && importsIndirectly(other.node, node)),\n )\n const rival = rest.find(({ provider }) => !isSame(provider, top.provider))\n return { module: top.node.module, provider: top.provider, rival: rival?.node.module }\n}\n\n/**\n * The provider that modules supply for each token. A module overrides what it\n * imports, directly or not, and of several in one list the last one counts.\n * Modules of the application override those that plugins add. Between modules\n * that do not import each other nothing says which one is meant, unless they\n * provide the same.\n */\nexport function moduleProviders(\n graph: readonly ModuleNode[],\n isOfApplication: (module: ClassType) => boolean,\n): Map<InjectionToken<any, any>, ModuleProvider> {\n const candidates = new Map<InjectionToken<any, any>, Candidate[]>()\n // Importers first, so that a module that overrides another comes before it.\n for (const node of [...graph].reverse()) {\n const own = new Map(node.providers.map((provider) => [provider.token, provider]))\n for (const [token, provider] of own) {\n const list = candidates.get(token)\n if (list) {\n list.push({ node, provider })\n } else {\n candidates.set(token, [{ node, provider }])\n }\n }\n }\n const chosen = new Map<InjectionToken<any, any>, ModuleProvider>()\n for (const [token, all] of candidates) {\n const ofApplication = all.filter(({ node }) => isOfApplication(node.module))\n chosen.set(token, choose(ofApplication.length > 0 ? ofApplication : all))\n }\n return chosen\n}\n","/** The longest delay a timer takes. */\nexport const MAX_DELAY_MS = 2 ** 31 - 1\n\n/**\n * Whether `work` settles within `ms`. Rejects when it rejects in time; a later\n * rejection is dropped.\n */\nexport async function settledWithin(work: Promise<unknown>, ms: number): Promise<boolean> {\n if (ms > MAX_DELAY_MS) {\n await work\n return true\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<false>((resolve) => {\n timer = setTimeout(resolve, ms, false)\n })\n try {\n return await Promise.race([work.then(() => true), timeout])\n } finally {\n clearTimeout(timer)\n }\n}\n","import { constants } from 'node:os'\n\nimport { outsideSteps } from './lifecycle-step.mjs'\n\ninterface Closable {\n close(signal?: string): Promise<void>\n}\n\nexport interface ShutdownHooksOptions {\n /**\n * Whether the signal ends the process once every application has closed,\n * as it would have without a listener. It does not when something else in\n * the process listens to the signal.\n * @default true\n */\n exit?: boolean\n}\n\ninterface Registration {\n exit: boolean\n onError(signal: string, error: unknown): void\n}\n\n/** Every application that one signal closes, until it is closed. */\ninterface SignalRegistry {\n readonly applications: Map<Closable, Registration>\n readonly listener: () => void\n}\n\nconst registries = new Map<NodeJS.Signals, SignalRegistry>()\n\n/** Closes `application` when the process receives one of the signals. */\nexport function closeOnSignals(\n application: Closable,\n signals: readonly NodeJS.Signals[],\n registration: Registration,\n): void {\n for (const signal of signals) {\n let registry = registries.get(signal)\n if (registry === undefined) {\n const created: SignalRegistry = {\n applications: new Map(),\n listener: () => void receive(signal, created),\n }\n registry = created\n registries.set(signal, registry)\n process.on(signal, registry.listener)\n }\n registry.applications.set(application, registration)\n }\n}\n\n/**\n * Ends what `closeOnSignals` did for an application once it has closed. Until\n * then a signal must not end the process.\n */\nexport function stopListening(application: Closable, closing: Promise<unknown>): void {\n for (const { applications } of registries.values()) {\n if (applications.has(application)) {\n const forgetIt = () => forget(application)\n closing.then(forgetIt, forgetIt)\n return\n }\n }\n}\n\nfunction forget(application: Closable): void {\n for (const [signal, registry] of registries) {\n if (registry.applications.delete(application) && registry.applications.size === 0) {\n remove(signal, registry)\n }\n }\n}\n\nfunction remove(signal: NodeJS.Signals, registry: SignalRegistry): void {\n registries.delete(signal)\n process.off(signal, registry.listener)\n}\n\nasync function receive(signal: NodeJS.Signals, registry: SignalRegistry): Promise<void> {\n // From here on signals do what they do by default: a second one ends the\n // process at once.\n remove(signal, registry)\n const applications = [...registry.applications]\n await Promise.all(\n applications.map(async ([application, { onError }]) => {\n forget(application)\n try {\n // A listener runs in the async context it was installed in, which may\n // be a hook that the shutdown has to wait for.\n await outsideSteps(() => application.close(signal))\n } catch (error) {\n onError(signal, error)\n }\n }),\n )\n const exit = applications.every(([, registration]) => registration.exit)\n if (exit && process.listenerCount(signal) === 0) {\n endProcess(signal)\n }\n}\n\nfunction endProcess(signal: NodeJS.Signals): void {\n if (process.pid === 1) {\n // The first process of a container gets no signal that it does not handle.\n process.exit(128 + constants.signals[signal])\n } else {\n process.kill(process.pid, signal)\n }\n}\n","import { Container, provide } from '@navios/di'\nimport {\n constructedInstances,\n hasOwnProvider,\n setErrorReporter,\n setProvider,\n} from '@navios/di/internal'\n\nimport type { ClassType, InjectionToken, Provider } from '@navios/di'\n\nimport { enableAsyncContext } from '../execution/async-context.mjs'\nimport { createContextHost } from '../execution/context-host.mjs'\nimport { ConsoleLogger } from '../logger/console-logger.mjs'\nimport { LoggerOutput } from '../logger/logger-output.mjs'\nimport { Logger } from '../logger/logger.mjs'\nimport { deferOutput, endDeferral } from '../logger/pending-output.mjs'\nimport { buildModuleGraph } from '../modules/module-graph.mjs'\nimport { assertProviders } from '../modules/module-metadata.mjs'\nimport { orderPlugins } from '../plugins/order-plugins.mjs'\n\nimport type { InterceptorClass } from '../interceptors/interceptor.mjs'\nimport type { LoggerService } from '../logger/logger-output.mjs'\nimport type { LoggerInstance } from '../logger/logger.mjs'\nimport type { PendingOutput } from '../logger/pending-output.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\nimport type { PluginApi, PluginInstance } from '../plugins/plugin.mjs'\nimport type {\n Transport,\n TransportFactory,\n TransportHost,\n TransportInstance,\n} from '../transports/transport.mjs'\n\nimport { declaresHook } from './lifecycle-hooks.mjs'\nimport { currentPhase, outsideSteps, runStep } from './lifecycle-step.mjs'\nimport { moduleProviders } from './module-providers.mjs'\nimport { MAX_DELAY_MS, settledWithin } from './settled-within.mjs'\nimport { closeOnSignals, stopListening } from './shutdown-signals.mjs'\n\nimport type { ApplicationOptions } from './application-options.mjs'\nimport type {\n OnApplicationBootstrap,\n OnApplicationShutdown,\n OnModuleInit,\n} from './lifecycle-hooks.mjs'\nimport type { ShutdownHooksOptions } from './shutdown-signals.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nconst noopLogger: LoggerService = {\n log() {},\n error() {},\n warn() {},\n debug() {},\n verbose() {},\n fatal() {},\n}\n\n/**\n * How much longer than the time it was given a transport may take to stop. It\n * has things to release once the work in flight is done, or was cut off.\n */\nconst STOP_GRACE_MS = 3000\n\n/** The containers that back an application which has not been closed. */\nconst backing = new WeakSet<Container>()\n\nfunction ignore(): void {}\n\nfunction closedError(): Error {\n return new Error('[Navios] The application is closed.')\n}\n\n/** What a call returns that its caller must not wait for, and need not handle. */\nfunction refused(message: string): Promise<never> {\n const rejected = Promise.reject(new Error(`[Navios] ${message}`))\n rejected.catch(ignore)\n return rejected\n}\n\nfunction className(instance: unknown): string {\n try {\n return String(Object.getPrototypeOf(instance)?.constructor?.name)\n } catch {\n return 'an object'\n }\n}\n\ninterface TransportSlot {\n readonly instance: TransportInstance\n transport: Transport | null\n started: boolean\n stopped: boolean\n}\n\n/**\n * An application: a module tree, one container, and the transports through\n * which work reaches it.\n *\n * ```ts\n * const app = createApplication(AppModule, {\n * transports: [queueTransport({ url })],\n * })\n * await app.start()\n * ```\n */\nexport class Application {\n readonly container: Container\n protected logger!: LoggerInstance\n private readonly plugins: PluginInstance[]\n private readonly slots: TransportSlot[]\n private readonly extraModules: ClassType[] = []\n private readonly globalInterceptors: InterceptorClass[] = []\n private readonly bootstrapHooks: Array<() => void | Promise<void>> = []\n private readonly shutdownHooks: Array<{\n plugin: string\n run: (signal?: string) => void | Promise<void>\n }> = []\n /** What modules and plugins provide. Everything else is the caller's. */\n private readonly supplied = new Map<InjectionToken<any, any>, Provider | 'plugin'>()\n /** For the log, once there is one. */\n private readonly notes: string[] = []\n /** What loggers write to until it is settled where the log goes. */\n private pendingOutput: PendingOutput | null = null\n private transportsCreated = false\n private settingUpPlugins = false\n private initialised = false\n private initialisation: Promise<void> | null = null\n private startup: Promise<void> | null = null\n private closed = false\n private closing: Promise<void> | null = null\n private tearingDown: Promise<void> | null = null\n private signal: string | undefined\n\n constructor(\n private readonly appModule: ClassType,\n private readonly applicationOptions: ApplicationOptions = {},\n ) {\n const options = applicationOptions\n if (options.container && backing.has(options.container)) {\n throw new Error(\n '[Navios] This container already backs an open application. Close that one first, or ' +\n 'give each application a container of its own.',\n )\n }\n this.container = options.container ?? new Container()\n // The last one of several for one token counts.\n const given = new Map<InjectionToken<any, any>, [option: string, Provider]>()\n assertProviders('The application', options.providers ?? [])\n for (const provider of options.providers ?? []) {\n given.set(provider.token, ['providers', provider])\n }\n const { logger } = options\n if (logger !== undefined && !Array.isArray(logger)) {\n const value = logger === false ? noopLogger : logger\n given.set(LoggerOutput, ['logger', provide(LoggerOutput, { value })])\n }\n for (const [option, provider] of given.values()) {\n this.provideOption(option, provider)\n }\n this.plugins = [...(options.plugins ?? [])]\n this.slots = []\n for (const instance of options.transports ?? []) {\n if (this.slots.some((slot) => slot.instance.instanceName === instance.instanceName)) {\n throw new Error(`[Navios] Two transports are named \"${instance.instanceName}\".`)\n }\n this.slots.push({ instance, transport: null, started: false, stopped: false })\n }\n backing.add(this.container)\n setErrorReporter(this.container, (error, description) => this.report(description, error))\n }\n\n /** Supplies what an option provides, unless the given container does. */\n private provideOption(option: string, provider: Provider): void {\n const { token } = provider\n if (this.isProvidedByCaller(token)) {\n this.notes.push(\n `The container provides ${token}, so the one of the \\`${option}\\` option is not used.`,\n )\n } else if (!setProvider(this.container, provider)) {\n throw new Error(\n `[Navios] \\`${option}\\` has ${token}, which has already been resolved in \\`container\\`.`,\n )\n }\n }\n\n /** Tells what nobody else receives. Never throws. */\n private report(message: string, error?: unknown): void {\n try {\n if (this.logger) {\n this.logger.error(message, error)\n return\n }\n if (this.applicationOptions.logger === false) {\n return\n }\n } catch {\n // The logger fails as well.\n }\n console.error(`[Navios] ${message}`, ...(error === undefined ? [] : [error]))\n }\n\n // --------------------------------------------------------------------------\n // Configuration, before init()\n // --------------------------------------------------------------------------\n\n private assertConfigurable(what: string): void {\n if (this.initialisation !== null) {\n throw new Error(`[Navios] ${what} must be called before init()`)\n }\n }\n\n usePlugin(plugin: PluginInstance): this {\n this.assertConfigurable('usePlugin()')\n this.plugins.push(plugin)\n return this\n }\n\n /** Adds an interceptor around every handler, on every transport. */\n intercept(interceptor: InterceptorClass): this {\n this.assertConfigurable('intercept()')\n this.globalInterceptors.push(interceptor)\n return this\n }\n\n // --------------------------------------------------------------------------\n // Access\n // --------------------------------------------------------------------------\n\n get: Container['get'] = ((token: any, args?: unknown) =>\n (this.container.get as any)(token, args)) as Container['get']\n\n /**\n * One of the application's transports. Transports are created by `init()`.\n * Throws when the application has no such transport; `findTransport`\n * returns `undefined` instead.\n */\n transport<T extends Transport>(factory: TransportFactory<any, T>, instanceName?: string): T {\n const name = instanceName ?? factory.definition.name\n if (!this.transportsCreated) {\n throw new Error(`[Navios] The \"${name}\" transport is created by init(); call init() first.`)\n }\n const transport = this.findTransport(factory, instanceName)\n if (transport === undefined) {\n throw new Error(`[Navios] The application has no \"${name}\" transport.`)\n }\n return transport\n }\n\n /** Like `transport`, but `undefined` when there is none, or not yet. */\n findTransport<T extends Transport>(\n factory: TransportFactory<any, T>,\n instanceName?: string,\n ): T | undefined {\n const name = instanceName ?? factory.definition.name\n for (const slot of this.slots) {\n if (slot.instance.definition === factory.definition && slot.instance.instanceName === name) {\n return (slot.transport ?? undefined) as T | undefined\n }\n }\n return undefined\n }\n\n // --------------------------------------------------------------------------\n // Initialisation\n // --------------------------------------------------------------------------\n\n /**\n * Builds the application: transports, plugins, modules and each\n * transport's handlers. Runs once, however often and from wherever it is\n * called; every caller gets the outcome of that run. Only a hook that the\n * run itself waits for cannot call it.\n *\n * An application that fails to initialise is closed before this rejects, and\n * stays failed, because it is only partly built.\n */\n init(): Promise<this> {\n if (currentPhase(this) === 'init') {\n return refused('init() was called from inside init(), which waits for the caller.')\n }\n const waitsForCaller = currentPhase(this) === 'shutdown' && !this.initialised\n if (this.closed && (this.initialisation === null || waitsForCaller)) {\n return Promise.reject(closedError())\n }\n this.initialisation ??= this.initialise()\n return this.initialisation.then(() => this)\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw closedError()\n }\n }\n\n /**\n * Rejects when the application has been closed, after that shutdown has\n * finished: the process may end when the caller fails.\n */\n protected async assertStillOpen(): Promise<void> {\n await this.closing?.catch(ignore)\n this.assertOpen()\n }\n\n /** Calls code that the application waits for. */\n private step<T>(phase: 'init' | 'start', fn: () => T | Promise<T>): Promise<T> {\n this.assertNotTornDown()\n return runStep(this, phase, fn)\n }\n\n /** A shutdown does not wait for a start-up that hangs; that one ends here. */\n private assertNotTornDown(): void {\n if (this.tearingDown !== null) {\n throw closedError()\n }\n }\n\n private async initialise(): Promise<void> {\n this.pendingOutput = deferOutput(this.container, () => this.settleLoggerNow())\n try {\n await this.build()\n } catch (error) {\n await this.tearDownFailed()\n throw error\n } finally {\n endDeferral(this.container)\n }\n }\n\n /**\n * Nothing may be left half-open when the start-up fails: what was created\n * holds what it acquired, and background work would go on.\n */\n private async tearDownFailed(): Promise<void> {\n try {\n await this.teardown(0)\n } catch (error) {\n this.report('Error disposing the container', error)\n }\n }\n\n private async build(): Promise<void> {\n const { applicationOptions: options, container } = this\n\n // The providers of the modules come first: whatever is resolved from here\n // on must already see them.\n let graph = buildModuleGraph([this.appModule])\n const own = new Set(graph.map((node) => node.module))\n this.applyModuleProviders(graph, own, 'before plugins')\n\n this.logger = await this.step('init', () => container.get(Logger, { context: 'Navios' }))\n for (const note of this.notes.splice(0)) {\n this.logger.debug(note)\n }\n\n if (options.asyncContext) {\n await enableAsyncContext()\n }\n\n const host: TransportHost = {\n container,\n logger: this.logger,\n contextHost: createContextHost(\n container,\n options.requestScopedServices ?? (process.env.NODE_ENV === 'production' ? 'allow' : 'warn'),\n this.logger,\n ),\n asyncContext: options.asyncContext ?? false,\n interceptors: this.globalInterceptors,\n }\n this.transportsCreated = true\n for (const slot of this.slots) {\n const { definition, options: transportOptions } = slot.instance\n slot.transport = await this.step('init', () => definition.create(host, transportOptions))\n if (this.tearingDown !== null) {\n // Created too late for the shutdown to see it.\n await this.stopTransport(slot, 0)\n }\n }\n\n await this.setupPlugins()\n if (this.extraModules.length > 0) {\n // Modules that plugins added are only known now.\n graph = buildModuleGraph([this.appModule, ...this.extraModules])\n }\n this.applyModuleProviders(graph, own, 'after plugins')\n\n // Everything that may provide the logger has had its turn.\n await this.step('init', () => this.settleLogger())\n\n for (const node of graph) {\n await this.step('init', async () => {\n const instance = await container.get(node.module)\n if (declaresHook(instance, 'onModuleInit')) {\n await (instance as OnModuleInit).onModuleInit()\n }\n })\n }\n\n for (const slot of this.slots) {\n await this.step('init', () => slot.transport!.setup(graph))\n }\n\n for (const hook of this.bootstrapHooks) {\n await this.step('init', hook)\n }\n for (const instance of constructedInstances(container)) {\n if (declaresHook(instance, 'onApplicationBootstrap')) {\n await this.step('init', () => (instance as OnApplicationBootstrap).onApplicationBootstrap())\n }\n }\n this.assertNotTornDown()\n this.initialised = true\n }\n\n /**\n * Whether the caller provides a token: with the options of the application\n * or in its container, where an instance may also have been put.\n */\n private isProvidedByCaller(token: InjectionToken<any, any>): boolean {\n if (this.supplied.has(token)) {\n return false\n }\n if (hasOwnProvider(this.container, token)) {\n return true\n }\n const instance = this.container.peek(token)\n return instance !== null && !constructedInstances(this.container).includes(instance)\n }\n\n /**\n * Supplies what the modules provide, unless the application or a plugin\n * provides it. Modules that disagree about a token are an error where one of\n * them would have to be used, which is settled after the plugins.\n */\n private applyModuleProviders(\n graph: readonly ModuleNode[],\n own: ReadonlySet<ClassType>,\n when: 'before plugins' | 'after plugins',\n ): void {\n const provided = moduleProviders(graph, (module) => own.has(module))\n for (const [token, { provider, module, rival }] of provided) {\n const supplied = this.supplied.get(token)\n if (supplied === provider || supplied === 'plugin' || this.isProvidedByCaller(token)) {\n continue\n }\n let used = provider\n if (rival !== undefined) {\n const conflict = new Error(\n `[Navios] Modules ${rival.name} and ${module.name} both provide ${token}, and neither ` +\n `imports the other. Provide it in a module that imports both, or with the ` +\n `\\`providers\\` option of the application.`,\n )\n if (when === 'after plugins') {\n throw conflict\n }\n // Whoever needs the token before a plugin may have decided gets to know.\n used = provide(token, {\n factory: () => {\n throw conflict\n },\n })\n }\n if (!setProvider(this.container, used)) {\n throw new Error(\n `[Navios] ${module.name} provides ${token}, which has already been resolved. Resolve ` +\n `it later, or provide it with the \\`providers\\` option of the application.`,\n )\n }\n this.supplied.set(token, used)\n }\n }\n\n private async settleLogger(): Promise<void> {\n const output = await this.container.get(LoggerOutput)\n this.configureOutput(output)\n this.pendingOutput!.settle(output)\n endDeferral(this.container)\n }\n\n /** What was logged so far is not lost, whatever becomes of the start-up. */\n private settleLoggerNow(): void {\n if (this.pendingOutput === null || this.pendingOutput.isSettled) {\n return\n }\n let output: LoggerService\n try {\n output = this.container.getSync(LoggerOutput)\n this.configureOutput(output)\n } catch {\n // It is built asynchronously, or cannot be built.\n output = new ConsoleLogger()\n this.configureOutput(output)\n }\n this.pendingOutput.settle(output)\n }\n\n private configureOutput(output: LoggerService): void {\n const { logger, asyncContext } = this.applicationOptions\n if (Array.isArray(logger)) {\n output.setLogLevels?.(logger)\n }\n if (asyncContext && output instanceof ConsoleLogger) {\n output.setDefaults({ requestId: true })\n }\n }\n\n private async setupPlugins(): Promise<void> {\n this.settingUpPlugins = true\n try {\n for (const { definition, options } of orderPlugins(this.plugins)) {\n this.logger.debug(`Setting up plugin ${definition.name}`)\n const api = this.pluginApi(definition.name)\n await this.step('init', () => definition.setup(api, options))\n }\n } finally {\n this.settingUpPlugins = false\n }\n }\n\n private pluginApi(plugin: string): PluginApi {\n const { container } = this\n const assertSetup = (call: string) => {\n if (!this.settingUpPlugins) {\n throw new Error(`[Navios] api.${call}() must be called during setup`)\n }\n }\n return {\n container,\n provide: ((target: any, impl: any) => {\n assertSetup('provide')\n const { token } = provide(target, impl)\n if (this.isProvidedByCaller(token)) {\n this.logger.debug(\n `Plugin ${plugin} provides ${token}, but the application provides its own.`,\n )\n return\n }\n container.provide(target, impl)\n this.supplied.set(token, 'plugin')\n }) as Container['provide'],\n decorate: ((target: any, decorator: any) => {\n assertSetup('decorate')\n container.decorate(target, decorator)\n }) as Container['decorate'],\n intercept: (interceptor) => {\n assertSetup('intercept')\n this.globalInterceptors.push(interceptor)\n },\n addModule: (module) => {\n assertSetup('addModule')\n this.extraModules.push(module)\n },\n transport: (factory, instanceName) => this.findTransport(factory, instanceName),\n onBootstrap: (hook) => {\n assertSetup('onBootstrap')\n this.bootstrapHooks.push(hook)\n },\n onShutdown: (hook) => {\n assertSetup('onShutdown')\n this.shutdownHooks.push({ plugin, run: hook })\n },\n }\n }\n\n // --------------------------------------------------------------------------\n // Running\n // --------------------------------------------------------------------------\n\n /**\n * Initialises the application if needed, then starts every transport, in\n * the order they were listed. A transport is started at most once, however\n * often this is called. An application whose transports do not all start is\n * closed before this rejects.\n *\n * Called from something `init()` waits for, it starts the application\n * afterwards and returns a promise that rejects.\n */\n start(): Promise<this> {\n const phase = currentPhase(this)\n if (phase !== 'init' && phase !== 'start') {\n return this.startOnce()\n }\n if (phase === 'init') {\n outsideSteps(() => this.startOnce()).catch((error: unknown) => {\n // Whoever called init() learns why that failed.\n if (this.startup !== null) {\n this.report('Error starting the application', error)\n }\n })\n }\n return refused(\n `start() was called from inside ${phase}(), which waits for the caller.` +\n (phase === 'init' ? ' Call it without waiting for it.' : ''),\n )\n }\n\n private async startOnce(): Promise<this> {\n await this.init()\n if (this.startup === null) {\n // The application may have been closed while it was initialising.\n await this.assertStillOpen()\n this.startup ??= this.startTransports()\n }\n await this.startup\n return this\n }\n\n private async startTransports(): Promise<void> {\n try {\n for (const slot of this.slots) {\n if (!slot.started) {\n slot.started = true\n await this.startTransport(slot)\n }\n }\n this.assertNotTornDown()\n } catch (error) {\n await this.tearDownFailed()\n throw error\n }\n }\n\n private async startTransport(slot: TransportSlot): Promise<void> {\n try {\n await this.step('start', () => slot.transport!.start?.())\n } finally {\n if (slot.stopped) {\n // The shutdown did not wait any longer, and stopped what had not started.\n slot.stopped = false\n await this.stopTransport(slot, 0)\n }\n }\n }\n\n /**\n * Closes the application when the process receives one of the signals. Call\n * it before `start()`, so that a signal during the start-up is seen.\n *\n * A signal that has a listener no longer ends the process. When everything\n * the signal closes is closed, the process is therefore sent the signal\n * again, or exits with its code when it is process 1, unless `exit` is\n * `false` or something else listens to it. A second signal does not wait for\n * the shutdown, unlike one during a `close()` that the application called.\n */\n enableShutdownHooks(\n signals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'],\n options: ShutdownHooksOptions = {},\n ): this {\n this.assertOpen()\n closeOnSignals(this, signals, {\n exit: options.exit ?? true,\n onError: (signal, error) => this.report(`Error closing the application on ${signal}`, error),\n })\n return this\n }\n\n /**\n * Shuts down: every transport stops accepting work and waits for what is\n * in flight, shutdown hooks run in reverse order, then the container is\n * disposed, which runs `onServiceDestroy` hooks. Each step gets\n * `shutdownTimeout`; one that takes longer is reported and left behind.\n *\n * Runs once, however often and from wherever it is called, and every caller\n * gets the outcome of that run, with two exceptions, since they would wait\n * for themselves. Called from something the shutdown waits for, it resolves\n * at once. Called from something `init()` or `start()` waits for, it closes\n * the application afterwards and returns a promise that rejects.\n */\n close(signal?: string): Promise<void> {\n const phase = currentPhase(this)\n if (phase === 'shutdown') {\n return Promise.resolve()\n }\n if (this.closing === null) {\n this.signal ??= signal\n this.closing = this.shutdown()\n stopListening(this, this.closing)\n }\n if (phase !== null) {\n this.closing.catch((error: unknown) => this.report('Error closing the application', error))\n return refused(\n `close() was called from inside ${phase}(), which waits for the caller. Throw an error ` +\n `instead, or call close() without waiting for it.`,\n )\n }\n return this.closing\n }\n\n /** Transports are given it, and may add to it, for a timer of theirs. */\n private get shutdownTimeout(): number {\n const { shutdownTimeout = 10_000 } = this.applicationOptions\n return Math.min(shutdownTimeout, MAX_DELAY_MS - 60_000)\n }\n\n private async shutdown(): Promise<void> {\n this.closed = true\n // Whatever is still being built or started is let finish first, so that\n // nothing is created or started after it was stopped. Their failures\n // belong to whoever called init() or start().\n for (const [call, pending] of [\n ['init()', this.initialisation],\n ['start()', this.startup],\n ] as const) {\n if (pending !== null) {\n await this.shutdownStep(call, this.shutdownTimeout, () => pending.catch(ignore))\n }\n }\n await this.teardown(this.shutdownTimeout)\n }\n\n /** Takes down whatever was built so far, once. */\n private teardown(transportTimeout: number): Promise<void> {\n if (this.tearingDown === null) {\n this.closed = true\n this.tearingDown = this.takeDown(transportTimeout)\n stopListening(this, this.tearingDown)\n }\n return this.tearingDown\n }\n\n private async takeDown(transportTimeout: number): Promise<void> {\n const { container, shutdownTimeout } = this\n this.settleLoggerNow()\n try {\n await Promise.all(this.slots.map((slot) => this.stopTransport(slot, transportTimeout)))\n\n for (const instance of constructedInstances(container).reverse()) {\n if (declaresHook(instance, 'onApplicationShutdown')) {\n const label = `onApplicationShutdown of ${className(instance)}`\n await this.shutdownStep(label, shutdownTimeout, () =>\n (instance as OnApplicationShutdown).onApplicationShutdown(this.signal),\n )\n }\n }\n for (const { plugin, run } of this.shutdownHooks.reverse()) {\n await this.shutdownStep(`onShutdown of plugin ${plugin}`, shutdownTimeout, () =>\n run(this.signal),\n )\n }\n const disposal = runStep(this, 'shutdown', () => container.dispose())\n if (!(await settledWithin(disposal, shutdownTimeout))) {\n this.reportTimeout('disposal of the container', shutdownTimeout)\n }\n } finally {\n backing.delete(container)\n }\n }\n\n /**\n * Stops a transport that was created, once, however often and from\n * wherever this is asked for.\n */\n private async stopTransport(slot: TransportSlot, timeoutMs: number): Promise<void> {\n const { transport } = slot\n if (transport !== null && !slot.stopped) {\n slot.stopped = true\n const label = `stop of transport ${slot.instance.instanceName}`\n await this.shutdownStep(label, timeoutMs + STOP_GRACE_MS, () => transport.stop(timeoutMs))\n }\n }\n\n /** Runs one part of the shutdown. Whatever becomes of it, the rest follows. */\n private async shutdownStep(\n label: string,\n timeoutMs: number,\n fn: () => void | Promise<void>,\n ): Promise<void> {\n try {\n if (!(await settledWithin(runStep(this, 'shutdown', fn), timeoutMs))) {\n this.reportTimeout(label, timeoutMs)\n }\n } catch (error) {\n this.report(`Error in shutdown step \"${label}\"`, error)\n }\n }\n\n private reportTimeout(label: string, timeoutMs: number): void {\n this.report(`Shutdown step \"${label}\" did not finish within ${timeoutMs} ms`)\n }\n\n /** Alias of `close()`. */\n dispose(): Promise<void> {\n return this.close()\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.close()\n }\n}\n\n/**\n * Creates an application from its root module. Call `init()` to build it, or\n * `start()` to build it and start its transports.\n */\nexport function createApplication(appModule: ClassType, options?: ApplicationOptions): Application {\n return new Application(appModule, options)\n}\n","import type { Path, PathValue } from './config-path.mjs'\n\n/**\n * Interface for configuration service implementations.\n *\n * Provides type-safe access to configuration values with support for nested paths.\n *\n * @typeParam Config - The configuration object type\n */\nexport interface ConfigServiceInterface<Config extends object = Record<string, unknown>> {\n /**\n * Gets the entire configuration object.\n */\n getConfig: () => Config\n /**\n * Gets a configuration value by key path. Returns `null` if not found.\n *\n * @param key - Dot-separated path to the configuration value (e.g., 'database.host')\n * @returns The configuration value or `null` if not found\n */\n get: <Key extends Path<Config>>(key: Key) => NonNullable<PathValue<Config, Key>> | null\n\n /**\n * Gets a configuration value by key path, or returns a default value if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param defaultValue - Default value to return if the key is not found\n * @returns The configuration value or the default value\n */\n getOrDefault: <Key extends Path<Config>>(\n key: Key,\n defaultValue: NonNullable<PathValue<Config, Key>>,\n ) => NonNullable<PathValue<Config, Key>>\n\n /**\n * Gets a configuration value by key path, or throws an error if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param errorMessage - Optional custom error message\n * @returns The configuration value\n * @throws Error if the key is not found\n */\n getOrThrow: <Key extends Path<Config>>(\n key: Key,\n errorMessage?: string,\n ) => NonNullable<PathValue<Config, Key>>\n}\n\n/**\n * Service for managing application configuration with type-safe access.\n *\n * Provides methods to access configuration values using dot-notation paths\n * with full TypeScript type inference. `provideConfig()` gives the token of\n * one; `new ConfigService({ ... })` is what a test provides for it.\n *\n * @typeParam Config - The configuration object type\n *\n * @example\n * ```typescript\n * interface AppConfig {\n * database: {\n * host: string\n * port: number\n * }\n * api: {\n * timeout: number\n * }\n * }\n *\n * export const AppConfig = provideConfig<AppConfig>({ load: () => readConfig() })\n *\n * @Injectable()\n * export class DatabaseService {\n * private config = inject(AppConfig)\n *\n * connect() {\n * const host = this.config.getOrThrow('database.host')\n * const port = this.config.getOrDefault('database.port', 5432)\n * // host is typed as string, port is typed as number\n * }\n * }\n * ```\n */\nexport class ConfigService<\n Config extends object = Record<string, unknown>,\n> implements ConfigServiceInterface<Config> {\n /**\n * Creates a new ConfigService instance.\n *\n * @param config - The configuration object\n */\n constructor(private readonly config: Config = {} as Config) {}\n\n /**\n * Gets the entire configuration object.\n *\n * @returns The complete configuration object\n */\n getConfig(): Config {\n return this.config\n }\n\n /**\n * Gets a configuration value by key path.\n *\n * Returns `null` if the key is not found or if any part of the path is invalid.\n *\n * @param key - Dot-separated path to the configuration value (e.g., 'database.host')\n * @returns The configuration value or `null` if not found\n *\n * @example\n * ```typescript\n * const host = config.get('database.host') // string | null\n * const port = config.get('database.port') // number | null\n * ```\n */\n get<Key extends Path<Config>>(key: Key): NonNullable<PathValue<Config, Key>> | null {\n let value: any = this.config\n for (const part of String(key).split('.')) {\n if (value === null || value === undefined || typeof value !== 'object') {\n return null\n }\n value = value[part]\n }\n return (value as NonNullable<PathValue<Config, Key>>) ?? null\n }\n\n /**\n * Gets a configuration value by key path, or returns a default value if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param defaultValue - Default value to return if the key is not found\n * @returns The configuration value or the default value\n *\n * @example\n * ```typescript\n * const port = config.getOrDefault('database.port', 5432) // number\n * ```\n */\n getOrDefault<Key extends Path<Config>>(\n key: Key,\n defaultValue: NonNullable<PathValue<Config, Key>>,\n ): NonNullable<PathValue<Config, Key>> {\n return this.get(key) ?? defaultValue\n }\n\n /**\n * Gets a configuration value by key path, or throws an error if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param errorMessage - Optional custom error message\n * @returns The configuration value\n * @throws Error if the key is not found\n *\n * @example\n * ```typescript\n * const host = config.getOrThrow('database.host') // string (throws if not found)\n * const apiKey = config.getOrThrow('api.key', 'API key is required') // string\n * ```\n */\n getOrThrow<Key extends Path<Config>>(\n key: Key,\n errorMessage?: string,\n ): NonNullable<PathValue<Config, Key>> {\n const value = this.get(key)\n if (value === null) {\n throw new Error(errorMessage || `Configuration value for key \"${String(key)}\" is not defined`)\n }\n return value\n }\n}\n","import { env } from 'node:process'\n\n/**\n * Reads an integer. A variable that is missing or empty gives the default; one\n * that is not an integer throws, because it is a mistake the default would hide.\n */\nexport function envInt(key: keyof NodeJS.ProcessEnv, defaultValue: number): number {\n const raw = env[key]?.trim()\n if (!raw) {\n return defaultValue\n }\n const value = Number(raw)\n if (!/^[+-]?\\d+$/.test(raw) || !Number.isSafeInteger(value)) {\n throw new Error(`[Navios] The environment variable ${key} is not an integer.`)\n }\n return value\n}\n\n/** Reads a string. A variable that is missing or empty gives the default. */\nexport function envString(key: keyof NodeJS.ProcessEnv): string | undefined\nexport function envString(key: keyof NodeJS.ProcessEnv, defaultValue: string): string\nexport function envString(\n key: keyof NodeJS.ProcessEnv,\n defaultValue: string | undefined,\n): string | undefined\nexport function envString(key: keyof NodeJS.ProcessEnv, defaultValue?: string): string | undefined {\n return env[key] || defaultValue || undefined\n}\n","import type { StandardSchemaIssue } from '@navios/di'\n\n/** As many characters of a value in a row tell something about it. */\nconst TELLING = 4\n/** The same for a value that is one of many. */\nconst TELLING_OF_MANY = 8\n\ntype Path = NonNullable<StandardSchemaIssue['path']>\n\nfunction keyOf(part: Path[number]): PropertyKey {\n return typeof part === 'object' ? part.key : part\n}\n\n/** Whether `message` has `length` characters of `value` in a row, or all it has. */\nfunction tells(message: string, value: string, length: number): boolean {\n const text = value.toLowerCase()\n const size = Math.min(length, text.length)\n for (let start = 0; size > 0 && start + size <= text.length; start++) {\n if (message.includes(text.slice(start, start + size))) {\n return true\n }\n }\n return false\n}\n\n/** The texts in which something may appear in a message. */\nfunction* texts(value: unknown, seen = new Set<unknown>()): Generator<string> {\n if (typeof value !== 'object' || value === null) {\n if (value !== undefined && value !== null && typeof value !== 'boolean') {\n yield String(value)\n }\n return\n }\n if (seen.has(value)) {\n return\n }\n seen.add(value)\n const { toJSON, toString } = value as { toJSON?: unknown; toString?: unknown }\n if (typeof toJSON === 'function') {\n yield String(toJSON.call(value))\n }\n if (typeof toString === 'function' && toString !== Object.prototype.toString) {\n yield String(value)\n }\n const inner = value instanceof Map || value instanceof Set ? value.values() : Object.values(value)\n for (const each of inner) {\n yield* texts(each, seen)\n }\n}\n\nfunction valueAt(loaded: unknown, path: Path): unknown {\n let value = loaded\n for (const part of path) {\n if (typeof value !== 'object' || value === null) {\n return undefined\n }\n value = (value as Record<PropertyKey, unknown>)[keyOf(part)]\n }\n return value\n}\n\nfunction mayContainValue(message: string, loaded: unknown, path: Path): boolean {\n const text = message.toLowerCase()\n const value = valueAt(loaded, path)\n if (typeof value === 'object' && value !== null) {\n return [...texts(value)].some(\n (part) => part.length >= TELLING && tells(text, part, TELLING_OF_MANY),\n )\n }\n if (value !== undefined) {\n return [...texts(value)].some((whole) => tells(text, whole, TELLING))\n }\n // Nothing is there, unless the schema moved what it validates. A word such as\n // `production` may well be in a message by itself.\n return [...texts(loaded)].some(\n (part) =>\n part.length >= TELLING && !/^[a-z]+$/i.test(part) && tells(text, part, TELLING_OF_MANY),\n )\n}\n\n/**\n * Says what is wrong with a configuration, without a value of it. Some schema\n * libraries put the value that they refuse into the message.\n */\nexport function describeIssue(\n { path = [], message }: StandardSchemaIssue,\n loaded: unknown,\n): string {\n const at = path.map((part) => String(keyOf(part))).join('.')\n let isTold = false\n try {\n isTold = !mayContainValue(message, loaded, path)\n } catch {\n // What cannot be looked at cannot be told from the message either.\n }\n if (!isTold) {\n const subject = at === '' ? 'The configuration' : at\n return `${subject} is invalid. What the schema says about it may contain the value.`\n }\n return at === '' ? message : `${at}: ${message}`\n}\n","import { InjectionToken, registerProvider } from '@navios/di'\n\nimport type { InferOutput, StandardSchemaV1 } from '@navios/di'\n\nimport { ConfigService } from './config-service.mjs'\nimport { describeIssue } from './describe-issue.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ConfigProviderOptions<ConfigMap extends object> {\n /** Names the token, for errors. @default 'Config' */\n name?: string\n /** Loads the raw configuration. */\n load: () => ConfigMap | Promise<ConfigMap>\n}\n\nexport interface ValidatedConfigProviderOptions<Schema extends StandardSchemaV1> {\n /** Names the token, for errors. @default 'Config' */\n name?: string\n /** Loads the raw configuration. */\n load: () => unknown\n /**\n * Validates what `load` returned and types the service. Must validate\n * synchronously.\n */\n schema: Schema\n}\n\n/**\n * The configuration to use, out of what was loaded. Its errors say what is\n * wrong and carry no value: they end up in logs, and a configuration holds\n * secrets.\n */\nfunction checked(name: string, schema: StandardSchemaV1 | undefined, loaded: unknown): object {\n let config = loaded\n if (schema) {\n const result = schema['~standard'].validate(loaded)\n if (result instanceof Promise) {\n result.catch(() => {})\n throw new Error(\n `[Navios] The schema of the configuration ${name} must validate synchronously.`,\n )\n }\n if (result.issues) {\n throw new Error(\n `[Navios] Invalid configuration ${name}: ` +\n result.issues.map((issue) => describeIssue(issue, loaded)).join('; '),\n )\n }\n config = result.value\n }\n if (typeof config !== 'object' || config === null || Array.isArray(config)) {\n throw new Error(`[Navios] The configuration ${name} must be an object.`)\n }\n return config\n}\n\n/**\n * Creates the token of a `ConfigService` whose content comes from `load`,\n * called once per container. With a `schema`, the loaded value is validated\n * and the service is typed from the schema's output.\n */\nexport function provideConfig<Schema extends StandardSchemaV1<any, object>>(\n options: ValidatedConfigProviderOptions<Schema>,\n): InjectionToken<ConfigService<InferOutput<Schema>>, undefined>\nexport function provideConfig<ConfigMap extends object>(\n options: ConfigProviderOptions<ConfigMap>,\n): InjectionToken<ConfigService<ConfigMap>, undefined>\nexport function provideConfig(options: {\n name?: string\n load: () => unknown\n schema?: StandardSchemaV1\n}): InjectionToken<ConfigService<any>, undefined> {\n const name = options.name ?? 'Config'\n const serve = (loaded: unknown) => new ConfigService(checked(name, options.schema, loaded))\n const token = InjectionToken.create<ConfigService<any>>(name)\n registerProvider(token, {\n factory: () => {\n // A configuration that is there at once can be used synchronously.\n const loaded = options.load() as PromiseLike<unknown> | null | undefined\n return typeof loaded?.then === 'function'\n ? Promise.resolve(loaded).then(serve)\n : serve(loaded)\n },\n })\n return token\n}\n","import { env } from 'node:process'\n\nimport type { InjectionToken } from '@navios/di'\n\nimport { provideConfig } from './provide-config.mjs'\n\nimport type { ConfigService } from './config-service.mjs'\n\n/**\n * A `ConfigService` holding a snapshot of `process.env`, taken when a\n * container first resolves it.\n */\nexport const EnvConfigProvider: InjectionToken<\n ConfigService<Record<string, string | undefined>>,\n undefined\n> = provideConfig<Record<string, string | undefined>>({\n name: 'EnvConfig',\n load: () => ({ ...env }),\n})\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * A typed slot in an execution context. Something sets it (usually a guard),\n * and reading it before that throws.\n *\n * ```ts\n * export const CurrentUser = createContextKey<User>('CurrentUser')\n * ```\n */\nexport class PlainContextKey<T> {\n declare readonly __type: T\n\n constructor(public readonly name: string) {}\n\n toString(): string {\n return this.name\n }\n}\n\nexport function createContextKey<T>(name: string): PlainContextKey<T> {\n return new PlainContextKey<T>(name)\n}\n\n/** A key every transport's context accepts. */\nexport type ContextKey<T = any> = PlainContextKey<T>\n\n/**\n * The type `ctx.get(key)` returns: a plain key's type, or, for a key that is\n * a class whose instances compute the value with `resolve`, what `resolve`\n * returns (a promise when it returns a thenable). A transport decides whether\n * it accepts such classes as keys.\n */\nexport type ContextValue<K> =\n K extends PlainContextKey<infer T>\n ? T\n : K extends new () => { resolve(ctx: any): infer R }\n ? ResolvedValue<R>\n : never\n\ntype ResolvedValue<R> = R extends Promise<any> ? R : R extends PromiseLike<infer T> ? Promise<T> : R\n","import type { ClassType, Container } from '@navios/di'\n\nimport type { InterceptorClass } from '../interceptors/interceptor.mjs'\nimport type { OptionsArgument } from '../internal/options-argument.mjs'\nimport type { Transport, TransportFactory } from '../transports/transport.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * What a plugin can do. Everything but `transport()` and `container` belongs\n * into `setup`: afterwards it throws, because it could not take effect.\n * `provide` and `decorate` apply at once, the rest at its point of `init()`.\n */\nexport interface PluginApi {\n readonly container: Container\n /**\n * Supplies a provider. It wins over the providers of modules and over the\n * default of the token. What the application itself provides, with its\n * `providers` option or in its container, stays.\n */\n readonly provide: Container['provide']\n /** Wraps every instance of a service after it is built. */\n readonly decorate: Container['decorate']\n /** Adds an interceptor around every handler, on every transport. */\n intercept(interceptor: InterceptorClass): void\n /**\n * Adds a module, and so its handlers, to the application. What it provides\n * is a default: the modules of the application override it.\n */\n addModule(module: ClassType): void\n /**\n * One of the application's transports, already created, or `undefined`\n * when the application has none of this kind. What only one transport\n * offers is reached through it.\n */\n transport<T extends Transport>(\n factory: TransportFactory<any, T>,\n instanceName?: string,\n ): T | undefined\n /** Runs after every transport is set up and before any starts. */\n onBootstrap(hook: () => void | Promise<void>): void\n /** Runs when the application closes, in reverse registration order. */\n onShutdown(hook: (signal?: string) => void | Promise<void>): void\n}\n\nexport interface PluginDefinition<Options = void> {\n /**\n * Unique name. One plugin registered twice with equal options is applied\n * once; anything else under one name is an error.\n */\n name: string\n /** Names of plugins that must be set up before this one. */\n dependsOn?: string[]\n setup(api: PluginApi, options: Options): void | Promise<void>\n}\n\nexport interface PluginInstance {\n readonly definition: PluginDefinition<any>\n /** `{}` when the plugin was given none. */\n readonly options: unknown\n}\n\n/**\n * Defines a plugin.\n *\n * ```ts\n * export const tracing = definePlugin({\n * name: 'tracing',\n * setup(api, options: { serviceName: string }) {\n * api.intercept(TracingInterceptor)\n * api.onShutdown(() => flush())\n * },\n * })\n *\n * app.usePlugin(tracing({ serviceName: 'api' }))\n * ```\n */\nexport function definePlugin<Options = void>(\n definition: PluginDefinition<Options>,\n): (...options: OptionsArgument<Options>) => PluginInstance {\n return (options?: Options) => ({ definition, options: options ?? {} })\n}\n"],"mappings":";;;;;;;;;;;;;AAEA,MAAM,uBAAuB,CAAC,QAAQ,IAAI;AAC1C,MAAM,kBAAkB,aAA0B,SAChD,eAAe,IAAI,QAAQ,IAAI,IAAI;AAErC,MAAa,MAAM;CACjB,MAAM,gBAAgB,SAAiB,UAAU,KAAK,QAAQ;CAC9D,OAAO,gBAAgB,SAAiB,WAAW,KAAK,SAAS;CACjE,QAAQ,gBAAgB,SAAiB,WAAW,KAAK,SAAS;CAClE,KAAK,gBAAgB,SAAiB,WAAW,KAAK,SAAS;CAC/D,eAAe,gBAAgB,SAAiB,WAAW,KAAK,SAAS;CACzE,YAAY,gBAAgB,SAAiB,WAAW,KAAK,S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AM;CAClB,EACF,CAAC;CACD,OAAO;AACT;;;;;;AC1EA,MAAa,oBAGT,cAAkD;CACpD,MAAM;CACN,aAAa,EAAE,GAAG,IAAI;AACxB,CAAC;;;;;;;;;;ACRD,IAAa,kBAAb,MAAgC;CAGF;CAA5B,YAA4B,MAAc;EAAd,KAAA,OAAA;CAAe;CAE3C,WAAmB;EACjB,OAAO,KAAK;CACd;AACF;AAEA,SAAgB,iBAAoB,MAAkC;CACpE,OAAO,IAAI,gBAAmB,IAAI;AACpC;;;;;;;;;;;;;;;;;ACuDA,SAAgB,aACd,YAC0D;CAC1D,QAAQ,aAAuB;EAAE;EAAY,SAAS,WAAW,CAAC;CAAE;AACtE"}
1
+ {"version":3,"file":"index.mjs","names":["InjectionToken","registerInjectable","InjectionToken","inject","Container","registerInjectable","InjectableScope","Container","provide","InjectionToken","registerProvider"],"sources":["../src/logger/cli-colors.mts","../src/logger/log-levels.mts","../src/logger/logger-output.mts","../src/logger/type-guards.mts","../src/logger/console-logger.mts","../src/internal/schema-from-guard.mts","../src/logger/pending-output.mts","../src/logger/logger.mts","../src/plugins/order-plugins.mts","../src/application/lifecycle-hooks.mts","../src/application/lifecycle-step.mts","../src/application/module-providers.mts","../src/application/shutdown-signals.mts","../src/application/application.mts","../src/config/config-service.mts","../src/config/env.mts","../src/config/describe-issue.mts","../src/config/provide-config.mts","../src/config/env-config-provider.mts","../src/execution/context-key.mts","../src/plugins/plugin.mts"],"sourcesContent":["type ColorTextFn = (text: string) => string\n\nconst isColorAllowed = () => !process.env.NO_COLOR\nconst colorIfAllowed = (colorFn: ColorTextFn) => (text: string) =>\n isColorAllowed() ? colorFn(text) : text\n\nexport const clc = {\n bold: colorIfAllowed((text: string) => `\\x1B[1m${text}\\x1B[0m`),\n green: colorIfAllowed((text: string) => `\\x1B[32m${text}\\x1B[39m`),\n yellow: colorIfAllowed((text: string) => `\\x1B[33m${text}\\x1B[39m`),\n red: colorIfAllowed((text: string) => `\\x1B[31m${text}\\x1B[39m`),\n magentaBright: colorIfAllowed((text: string) => `\\x1B[95m${text}\\x1B[39m`),\n cyanBright: colorIfAllowed((text: string) => `\\x1B[96m${text}\\x1B[39m`),\n}\nexport const yellow = colorIfAllowed((text: string) => `\\x1B[38;5;3m${text}\\x1B[39m`)\n","/**\n * Available log levels in order of severity (lowest to highest).\n */\nexport const LOG_LEVELS = [\n 'verbose',\n 'debug',\n 'log',\n 'warn',\n 'error',\n 'fatal',\n] as const satisfies string[]\n\n/**\n * Log level type.\n *\n * Represents the severity level of a log message.\n * Levels are: 'verbose', 'debug', 'log', 'warn', 'error', 'fatal'\n *\n * @publicApi\n */\nexport type LogLevel = (typeof LOG_LEVELS)[number]\n\nfunction isLogLevel(maybeLogLevel: any): maybeLogLevel is LogLevel {\n return LOG_LEVELS.includes(maybeLogLevel)\n}\n\nconst LOG_LEVEL_VALUES: Record<LogLevel, number> = {\n verbose: 0,\n debug: 1,\n log: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n}\n\n/**\n * Checks if target level is enabled.\n * @param targetLevel target level\n * @param logLevels array of enabled log levels\n */\nexport function isLogLevelEnabled(\n targetLevel: LogLevel,\n logLevels: LogLevel[] | undefined,\n): boolean {\n if (!logLevels || (Array.isArray(logLevels) && logLevels?.length === 0)) {\n return false\n }\n if (logLevels.includes(targetLevel)) {\n return true\n }\n const highestLogLevelValue = logLevels\n .map((level) => LOG_LEVEL_VALUES[level])\n .sort((a, b) => b - a)?.[0]\n\n const targetLevelValue = LOG_LEVEL_VALUES[targetLevel]\n return targetLevelValue >= highestLogLevelValue\n}\n\nfunction requireLogLevel(level: string): LogLevel {\n if (!isLogLevel(level)) {\n throw new Error(`parse error (unknown log level): ${level}`)\n }\n return level\n}\n\n/**\n * Reads log levels out of a setting: `'error'`, `'warn,error'`, `'>=warn'` or\n * `'>warn'`. An empty string stands for every level.\n * @publicApi\n */\nexport function filterLogLevels(parseableString = ''): LogLevel[] {\n const sanitizedString = parseableString.replaceAll(' ', '').toLowerCase()\n\n if (sanitizedString === '') {\n return [...LOG_LEVELS]\n }\n if (sanitizedString[0] === '>') {\n const orEqual = sanitizedString[1] === '='\n const logLevelIndex = LOG_LEVELS.indexOf(\n requireLogLevel(sanitizedString.substring(orEqual ? 2 : 1)),\n )\n return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1)\n }\n return sanitizedString.split(',').map(requireLogLevel)\n}\n","import { InjectionToken } from '@navios/di'\n\nimport type { LogLevel } from './log-levels.mjs'\n\n/**\n * @publicApi\n */\nexport interface LoggerService {\n /**\n * Write a 'log' level log.\n */\n log(message: any, ...optionalParams: any[]): any\n\n /**\n * Write an 'error' level log.\n */\n error(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'warn' level log.\n */\n warn(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'debug' level log.\n */\n debug?(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'verbose' level log.\n */\n verbose?(message: any, ...optionalParams: any[]): any\n\n /**\n * Write a 'fatal' level log.\n */\n fatal?(message: any, ...optionalParams: any[]): any\n\n /**\n * Set log levels.\n * @param levels log levels\n */\n setLogLevels?(levels: LogLevel[]): any\n}\n\n/**\n * Injection token for the logger output service.\n *\n * This token is used to provide a custom logger implementation.\n * By default, it's bound to ConsoleLogger.\n */\nexport const LoggerOutput = InjectionToken.create<LoggerService>('LoggerOutput')\n","export const isUndefined = (obj: any): obj is undefined => typeof obj === 'undefined'\n\nexport const isObject = (fn: any): fn is object => !isNil(fn) && typeof fn === 'object'\n\nexport const isPlainObject = (fn: any): fn is object => {\n if (!isObject(fn)) {\n return false\n }\n const proto = Object.getPrototypeOf(fn)\n if (proto === null) {\n return true\n }\n const ctor = Object.prototype.hasOwnProperty.call(proto, 'constructor') && proto.constructor\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object)\n )\n}\n\nexport const isFunction = (val: any): val is Function => typeof val === 'function'\nexport const isString = (val: any): val is string => typeof val === 'string'\nconst isNil = (val: any): val is null | undefined => isUndefined(val) || val === null\n","// Ported from NestJS (https://github.com/nestjs/nest, MIT licence). Big thanks\n// to the NestJS team for their work.\nimport type { InspectOptions } from 'node:util'\nimport { inspect } from 'node:util'\n\nimport { registerInjectable } from '@navios/di'\n\nimport { currentContext } from '../execution/async-context.mjs'\n\nimport { clc, yellow } from './cli-colors.mjs'\nimport { isLogLevelEnabled, LOG_LEVELS } from './log-levels.mjs'\nimport { LoggerOutput } from './logger-output.mjs'\nimport { isFunction, isPlainObject, isString, isUndefined } from './type-guards.mjs'\n\nimport type { ConsoleLoggerOptions } from './console-logger-options.mjs'\nimport type { LogLevel } from './log-levels.mjs'\nimport type { LoggerService } from './logger-output.mjs'\n\nconst DEFAULT_DEPTH = 5\n\n/** Every level, and `log` and above in production. */\nfunction defaultLogLevels(): LogLevel[] {\n return process.env.NODE_ENV === 'production'\n ? LOG_LEVELS.slice(LOG_LEVELS.indexOf('log'))\n : [...LOG_LEVELS]\n}\n\ninterface JsonError {\n name: string\n message: string\n stack?: string\n cause?: unknown\n /** What the error itself carries: `code`, `status`, `detail`. */\n [field: string]: unknown\n}\n\n/** Has a place of its own, or stands on the prototype in most errors. */\nconst commonFields = new Set(['name', 'message', 'stack', 'cause'])\n\n/**\n * An error as JSON shows it. `encode` gives the value to show for one that is\n * not an error.\n */\nfunction toJsonError(\n error: Error,\n encode: (value: unknown) => unknown,\n path: unknown[] = [],\n): JsonError {\n const inside = [...path, error]\n const showOne = (value: unknown): unknown => {\n if (inside.includes(value)) {\n return '[Circular]'\n }\n return value instanceof Error ? toJsonError(value, encode, inside) : encode(value)\n }\n const show = (value: unknown) => (Array.isArray(value) ? value.map(showOne) : showOne(value))\n const { name, message, stack, cause } = error\n const described: JsonError = { name, message, stack }\n if (cause !== undefined) {\n described.cause = show(cause)\n }\n if (error instanceof AggregateError) {\n described.errors = show(error.errors)\n }\n for (const field of Object.keys(error)) {\n if (!commonFields.has(field)) {\n try {\n described[field] = show((error as unknown as Record<string, unknown>)[field])\n } catch (reason) {\n described[field] = `[cannot be read: ${reason instanceof Error ? reason.message : reason}]`\n }\n }\n }\n return described\n}\n\nconst dateTimeFormatter = new Intl.DateTimeFormat(undefined, {\n year: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n day: '2-digit',\n month: '2-digit',\n})\n\nfunction withoutUndefined(options: ConsoleLoggerOptions = {}): ConsoleLoggerOptions {\n return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined))\n}\n\n/**\n * Prints to the console. Without options it prints every level, `log` and\n * above when `NODE_ENV` is `production`, in colour when stdout is a terminal.\n * @publicApi\n */\nexport class ConsoleLogger implements LoggerService {\n /**\n * Creates a new ConsoleLogger instance with the given options.\n * This is a convenience method that instantiates and sets up the logger in one call.\n */\n static create(): ConsoleLogger\n static create(context: string): ConsoleLogger\n static create(options: ConsoleLoggerOptions): ConsoleLogger\n static create(context: string, options: ConsoleLoggerOptions): ConsoleLogger\n static create(\n contextOrOptions?: string | ConsoleLoggerOptions,\n options?: ConsoleLoggerOptions,\n ): ConsoleLogger {\n return new this(contextOrOptions as string, options as ConsoleLoggerOptions)\n }\n\n /**\n * The options in effect: those given so far, and the defaults.\n */\n protected options: ConsoleLoggerOptions = {}\n /**\n * The context of the logger (can be set manually or automatically inferred).\n */\n protected context?: string\n /**\n * The original context of the logger (set by the constructor or `setup`).\n */\n protected originalContext?: string\n /**\n * The options used for the \"inspect\" method.\n */\n protected inspectOptions: InspectOptions = {}\n /**\n * The last timestamp at which the log message was printed.\n */\n protected lastTimestampAt?: number\n /**\n * The options that were given.\n */\n private given: ConsoleLoggerOptions = {}\n\n constructor()\n constructor(context: string)\n constructor(options: ConsoleLoggerOptions)\n constructor(context: string, options: ConsoleLoggerOptions)\n constructor(contextOrOptions?: string | ConsoleLoggerOptions, options?: ConsoleLoggerOptions) {\n this.setup(contextOrOptions as string, options as ConsoleLoggerOptions)\n }\n\n /**\n * Changes the options that are given and leaves the others as they are.\n */\n setup(): void\n setup(context: string): void\n setup(options: ConsoleLoggerOptions): void\n setup(context: string, options: ConsoleLoggerOptions): void\n setup(contextOrOptions?: string | ConsoleLoggerOptions, options?: ConsoleLoggerOptions) {\n const [context, opts] = isString(contextOrOptions)\n ? [contextOrOptions, options]\n : options\n ? [undefined, options]\n : [contextOrOptions?.context, contextOrOptions]\n\n this.applyOptions({ ...this.given, ...withoutUndefined(opts) })\n\n if (context) {\n this.context = context\n this.originalContext = context\n }\n }\n\n /**\n * Like `setup`, for the options that were not given.\n * @internal\n */\n setDefaults(options: ConsoleLoggerOptions): void {\n this.applyOptions({ ...options, ...this.given })\n }\n\n private applyOptions(given: ConsoleLoggerOptions): void {\n this.given = given\n this.options = {\n ...given,\n logLevels: given.logLevels ?? defaultLogLevels(),\n colors: given.colors ?? (!given.json && process.stdout.isTTY === true),\n prefix: given.prefix ?? 'Navios',\n }\n this.inspectOptions = this.getInspectOptions()\n }\n\n /**\n * Write a 'log' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n log(message: any, context?: string): void\n log(message: any, ...optionalParams: [...any, string?]): void\n log(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('log')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'log')\n }\n\n /**\n * Write an 'error' level log, if the configured level allows for it.\n * Prints to `stderr` with newline.\n */\n error(message: any, stackOrContext?: string): void\n error(message: any, stack?: string, context?: string): void\n error(message: any, ...optionalParams: [...any, string?, string?]): void\n error(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('error')) {\n return\n }\n const { messages, context, stack } = this.getContextAndStackAndMessagesToPrint([\n message,\n ...optionalParams,\n ])\n\n this.printMessages(messages, context, 'error', 'stderr', stack)\n this.printStackTrace(stack as string)\n }\n\n /**\n * Write a 'warn' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n warn(message: any, context?: string): void\n warn(message: any, ...optionalParams: [...any, string?]): void\n warn(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('warn')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'warn')\n }\n\n /**\n * Write a 'debug' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n debug(message: any, context?: string): void\n debug(message: any, ...optionalParams: [...any, string?]): void\n debug(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('debug')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'debug')\n }\n\n /**\n * Write a 'verbose' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n verbose(message: any, context?: string): void\n verbose(message: any, ...optionalParams: [...any, string?]): void\n verbose(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('verbose')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'verbose')\n }\n\n /**\n * Write a 'fatal' level log, if the configured level allows for it.\n * Prints to `stdout` with newline.\n */\n fatal(message: any, context?: string): void\n fatal(message: any, ...optionalParams: [...any, string?]): void\n fatal(message: any, ...optionalParams: any[]) {\n if (!this.isLevelEnabled('fatal')) {\n return\n }\n const { messages, context } = this.getContextAndMessagesToPrint([message, ...optionalParams])\n this.printMessages(messages, context, 'fatal')\n }\n\n /**\n * Set log levels\n * @param levels log levels\n */\n setLogLevels(levels: LogLevel[]) {\n this.setup({ logLevels: levels })\n }\n\n /**\n * Set logger context\n * @param context context\n */\n setContext(context: string) {\n this.context = context\n }\n\n /**\n * Resets the logger context to the value that was passed to the constructor or `setup`.\n */\n resetContext() {\n this.context = this.originalContext\n }\n\n isLevelEnabled(level: LogLevel): boolean {\n const logLevels = this.options?.logLevels\n return isLogLevelEnabled(level, logLevels)\n }\n\n /**\n * Gets the current request ID from the AsyncLocalStorage store.\n * Only returns a value if the requestId option is enabled.\n */\n protected getCurrentRequestId(): string | undefined {\n if (!this.options.requestId) {\n return undefined\n }\n return currentContext()?.id\n }\n\n protected getTimestamp(): string {\n return dateTimeFormatter.format(Date.now())\n }\n\n protected printMessages(\n messages: unknown[],\n context = '',\n logLevel: LogLevel = 'log',\n writeStreamType?: 'stdout' | 'stderr',\n errorStack?: unknown,\n ) {\n const requestId = this.getCurrentRequestId()\n if (this.options.json) {\n for (const line of this.toJsonLines(messages)) {\n this.guarded(() =>\n this.printAsJson(line.message, {\n context,\n logLevel,\n writeStreamType,\n errorStack,\n requestId,\n error: line.error,\n }),\n )\n }\n return\n }\n for (const message of messages) {\n this.guarded(() => {\n const pidMessage = this.formatPid(process.pid)\n const contextMessage = this.formatContext(context)\n const timestampDiff = this.updateAndGetTimestampDiff()\n const formattedLogLevel = logLevel.toUpperCase().padStart(7, ' ')\n const formattedMessage = this.formatMessage(\n logLevel,\n message,\n pidMessage,\n formattedLogLevel,\n contextMessage,\n timestampDiff,\n requestId,\n )\n\n process[writeStreamType ?? 'stdout'].write(formattedMessage)\n })\n }\n }\n\n /** A message and the error logged with it share a line. */\n private toJsonLines(messages: unknown[]): Array<{ message: unknown; error?: Error }> {\n const lines: Array<{ message: unknown; error?: Error }> = []\n for (const message of messages) {\n const last = lines.at(-1)\n if (!(message instanceof Error)) {\n lines.push({ message })\n } else if (last && !last.error) {\n last.error = message\n } else {\n lines.push({ message: message.message, error: message })\n }\n }\n return lines\n }\n\n /** Logging must not fail the code that logs. */\n private guarded(print: () => void): void {\n try {\n print()\n } catch (error) {\n try {\n const reason = error instanceof Error ? error.message : String(error)\n process.stderr.write(`[Navios] A log message could not be printed: ${reason}\\n`)\n } catch {\n // There is nothing left to tell.\n }\n }\n }\n\n protected printAsJson(\n message: unknown,\n options: {\n context: string\n logLevel: LogLevel\n writeStreamType?: 'stdout' | 'stderr'\n errorStack?: unknown\n requestId?: string\n error?: Error\n },\n ) {\n type JsonLogObject = {\n level: LogLevel\n pid: number\n timestamp: number\n message: unknown\n context?: string\n stack?: unknown\n requestId?: string\n error?: JsonError\n }\n\n const logObject: JsonLogObject = {\n level: options.logLevel,\n pid: process.pid,\n timestamp: Date.now(),\n message,\n }\n\n if (options.context) {\n logObject.context = options.context\n }\n\n if (options.errorStack) {\n logObject.stack = options.errorStack\n }\n if (options.requestId) {\n logObject.requestId = options.requestId\n }\n if (options.error) {\n logObject.error = toJsonError(options.error, (value) => this.encodable(value))\n }\n\n const formattedMessage =\n !this.options.colors && this.inspectOptions.compact === true\n ? this.stringify(logObject)\n : inspect(logObject, this.inspectOptions)\n process[options.writeStreamType ?? 'stdout'].write(`${formattedMessage}\\n`)\n }\n\n private stringify(logObject: { message: unknown; error?: JsonError }): string {\n const replacer = (key: string, value: unknown) => this.stringifyReplacer(key, value)\n try {\n return JSON.stringify(logObject, replacer)\n } catch {\n // Circular, or with a `toJSON` or a getter that throws.\n const { message, error } = logObject\n return JSON.stringify({\n ...logObject,\n message: typeof message === 'string' ? message : inspect(message, this.inspectOptions),\n error: error && inspect(error, this.inspectOptions),\n })\n }\n }\n\n /** A field that JSON cannot hold must not cost the rest of an error. */\n private encodable(value: unknown): unknown {\n if (typeof value !== 'object' || value === null) {\n return value\n }\n try {\n JSON.stringify(value, (key, inner) => this.stringifyReplacer(key, inner))\n return value\n } catch {\n return inspect(value, { ...this.inspectOptions, depth: 1 })\n }\n }\n\n protected formatPid(pid: number) {\n const showPrefix = this.options.showPrefix ?? true\n const showPid = this.options.showPid ?? true\n\n if (!showPrefix && !showPid) {\n return ''\n }\n\n const prefix = showPrefix ? `[${this.options.prefix}]` : ''\n const pidPart = showPid ? `${pid}` : ''\n const separator = showPrefix && showPid ? ' ' : ''\n const suffix = showPrefix || showPid ? ' - ' : ''\n\n return `${prefix}${separator}${pidPart}${suffix}`\n }\n\n protected formatContext(context: string): string {\n const showContext = this.options.showContext ?? true\n if (!context || !showContext) {\n return ''\n }\n\n context = `[${context}] `\n return this.options.colors ? yellow(context) : context\n }\n\n protected formatMessage(\n logLevel: LogLevel,\n message: unknown,\n pidMessage: string,\n formattedLogLevel: string,\n contextMessage: string,\n timestampDiff: string,\n requestId?: string,\n ) {\n const output = this.stringifyMessage(message, logLevel)\n const showLogLevel = this.options.showLogLevel ?? true\n const showTimestamp = this.options.showTimestamp ?? true\n\n pidMessage = this.colorize(pidMessage, logLevel)\n formattedLogLevel = showLogLevel ? this.colorize(formattedLogLevel, logLevel) : ''\n\n const timestamp = showTimestamp ? this.getTimestamp() : ''\n const requestIdPart = this.getRequestId(requestId)\n\n // Build the message parts, filtering out empty ones\n const parts: string[] = []\n\n if (pidMessage) parts.push(pidMessage.trimEnd())\n if (requestIdPart) parts.push(requestIdPart.trimEnd())\n if (timestamp) parts.push(timestamp)\n if (formattedLogLevel) parts.push(formattedLogLevel)\n if (contextMessage) parts.push(contextMessage.trimEnd())\n\n const prefix = parts.length > 0 ? parts.join(' ') + ' ' : ''\n\n return `${prefix}${output}${timestampDiff}\\n`\n }\n\n protected getRequestId(requestId?: string) {\n if (requestId) {\n return `(${this.colorize(requestId, 'log')}) `\n }\n return ''\n }\n\n protected stringifyMessage(message: unknown, logLevel: LogLevel): string {\n if (isFunction(message)) {\n const messageAsStr = Function.prototype.toString.call(message)\n const isClass = messageAsStr.startsWith('class ')\n if (isClass) {\n // If the message is a class, we will display the class name.\n return this.stringifyMessage(message.name, logLevel)\n }\n // If the message is a non-class function, call it and re-resolve its value.\n return this.stringifyMessage(message(), logLevel)\n }\n\n if (typeof message === 'string') {\n return this.colorize(message, logLevel)\n }\n\n const outputText = inspect(message, this.inspectOptions)\n if (isPlainObject(message)) {\n return `Object(${Object.keys(message).length}) ${outputText}`\n }\n if (Array.isArray(message)) {\n return `Array(${message.length}) ${outputText}`\n }\n return outputText\n }\n\n protected colorize(message: string, logLevel: LogLevel) {\n if (!this.options.colors || this.options.json) {\n return message\n }\n const color = this.getColorByLogLevel(logLevel)\n return color(message)\n }\n\n protected printStackTrace(stack: string) {\n if (!stack || this.options.json) {\n return\n }\n this.guarded(() => process.stderr.write(`${stack}\\n`))\n }\n\n protected updateAndGetTimestampDiff(): string {\n const showTimeDiff = this.options?.showTimeDiff ?? false\n const includeTimestamp = this.lastTimestampAt && showTimeDiff\n const result = includeTimestamp\n ? this.formatTimestampDiff(Date.now() - this.lastTimestampAt!)\n : ''\n this.lastTimestampAt = Date.now()\n return result\n }\n\n protected formatTimestampDiff(timestampDiff: number) {\n const formattedDiff = ` +${timestampDiff}ms`\n return this.options.colors ? yellow(formattedDiff) : formattedDiff\n }\n\n protected getInspectOptions() {\n let breakLength = this.options.breakLength\n if (typeof breakLength === 'undefined') {\n breakLength = this.options.colors\n ? this.options.compact\n ? Infinity\n : undefined\n : this.options.compact === false\n ? undefined\n : Infinity // default breakLength to Infinity if inline is not set and colors is false\n }\n\n const inspectOptions: InspectOptions = {\n depth: this.options.depth ?? DEFAULT_DEPTH,\n sorted: this.options.sorted,\n showHidden: this.options.showHidden,\n compact: this.options.compact ?? (this.options.json ? true : false),\n colors: this.options.colors,\n breakLength,\n }\n\n if (this.options.maxArrayLength) {\n inspectOptions.maxArrayLength = this.options.maxArrayLength\n }\n if (this.options.maxStringLength) {\n inspectOptions.maxStringLength = this.options.maxStringLength\n }\n\n return inspectOptions\n }\n\n protected stringifyReplacer(key: string, value: unknown) {\n // Mimic util.inspect behavior for JSON logger with compact on and colors off\n if (typeof value === 'bigint') {\n return value.toString()\n }\n if (typeof value === 'symbol') {\n return value.toString()\n }\n\n if (value instanceof Map || value instanceof Set || value instanceof Error) {\n return `${inspect(value, this.inspectOptions)}`\n }\n return value\n }\n\n private getContextAndMessagesToPrint(args: unknown[]) {\n if (args?.length <= 1) {\n return { messages: args, context: this.context }\n }\n const lastElement = args[args.length - 1]\n const isContext = isString(lastElement)\n if (!isContext) {\n return { messages: args, context: this.context }\n }\n return {\n context: lastElement,\n messages: args.slice(0, args.length - 1),\n }\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]) {\n if (args.length === 2) {\n const [message, second] = args\n if (isUndefined(second)) {\n return { messages: [message], context: this.context }\n }\n if (!isString(second)) {\n return { messages: args, context: this.context }\n }\n return this.isStackFormat(second)\n ? { messages: [message], stack: second, context: this.context }\n : { messages: [message], context: second }\n }\n\n const { messages, context } = this.getContextAndMessagesToPrint(args)\n if (messages?.length <= 1) {\n return { messages, context }\n }\n const lastElement = messages[messages.length - 1]\n const isStack = isString(lastElement)\n // https://github.com/nestjs/nest/issues/11074#issuecomment-1421680060\n if (!isStack && !isUndefined(lastElement)) {\n return { messages, context }\n }\n return {\n stack: lastElement,\n messages: messages.slice(0, messages.length - 1),\n context,\n }\n }\n\n private isStackFormat(stack: string) {\n return /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(stack)\n }\n\n private getColorByLogLevel(level: LogLevel) {\n switch (level) {\n case 'debug':\n return clc.magentaBright\n case 'warn':\n return clc.yellow\n case 'error':\n return clc.red\n case 'verbose':\n return clc.cyanBright\n case 'fatal':\n return clc.bold\n default:\n return clc.green\n }\n }\n}\n\nregisterInjectable(ConsoleLogger, { token: LoggerOutput })\n","import type { StandardSchemaV1 } from '@navios/di'\n\n/**\n * A minimal Standard Schema built from a type guard. Used for the framework's\n * own option objects so that core needs no schema library at runtime.\n * @internal\n */\nexport function schemaFromGuard<T>(\n guard: (value: unknown) => value is T,\n message: string,\n): StandardSchemaV1<T, T> {\n return {\n '~standard': {\n version: 1,\n vendor: 'navios',\n validate: (value) => (guard(value) ? { value } : { issues: [{ message }] }),\n },\n }\n}\n","import type { Container } from '@navios/di'\n\nimport type { LoggerService } from './logger-output.mjs'\n\ntype Level = 'log' | 'error' | 'warn' | 'debug' | 'verbose' | 'fatal'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Stands in for the logger output of a container until everything that may\n * provide it, plugins included, has had its turn, and holds back what is\n * logged until then: resolving the output any earlier would settle it.\n */\nexport class PendingOutput implements LoggerService {\n private output: LoggerService | null = null\n private held: Array<[Level, unknown[]]> = []\n\n /** `settleNow` settles for the output that can be had at once. */\n constructor(readonly settleNow: () => void) {\n if (unsettled.size === 0 && hasExitEvent) {\n process.on('exit', settleAll)\n }\n unsettled.add(this)\n }\n\n log(...args: any[]) {\n this.write('log', args)\n }\n\n error(...args: any[]) {\n this.write('error', args)\n }\n\n warn(...args: any[]) {\n this.write('warn', args)\n }\n\n debug(...args: any[]) {\n this.write('debug', args)\n }\n\n verbose(...args: any[]) {\n this.write('verbose', args)\n }\n\n fatal(...args: any[]) {\n this.write('fatal', args)\n }\n\n get isSettled(): boolean {\n return this.output !== null\n }\n\n /** Writes what is held, and everything from here on, to `output`. */\n settle(output: LoggerService): void {\n this.output = output\n if (unsettled.delete(this) && unsettled.size === 0 && hasExitEvent) {\n process.off('exit', settleAll)\n }\n for (const [level, args] of this.held.splice(0)) {\n try {\n this.write(level, args)\n } catch {\n // Whoever logged it has gone on.\n console.error(...args)\n }\n }\n }\n\n private write(level: Level, args: unknown[]): void {\n if (this.output === null) {\n this.held.push([level, args])\n return\n }\n const [message, ...rest] = args\n this.output[level]?.(message, ...rest)\n }\n}\n\n/**\n * Whether the runtime tells when the process ends. A Worker with a\n * compatibility date before 2025-09-15 has a `process` without `on()`, and no\n * exit to wait for.\n */\nconst hasExitEvent = typeof process.on === 'function'\n\n/** Those whose messages would be lost if the process ended now. */\nconst unsettled = new Set<PendingOutput>()\n\nfunction settleAll(): void {\n for (const output of unsettled) {\n output.settleNow()\n }\n}\n\nconst pending = new WeakMap<Container, PendingOutput>()\n\n/** Makes loggers that are built in `container` from now on wait for its output. */\nexport function deferOutput(container: Container, settleNow: () => void): PendingOutput {\n const output = new PendingOutput(settleNow)\n pending.set(container, output)\n return output\n}\n\n/** Ends what `deferOutput` did, for loggers that are built from now on. */\nexport function endDeferral(container: Container): void {\n pending.delete(container)\n}\n\nexport function pendingOutput(container: Container): PendingOutput | undefined {\n return pending.get(container)\n}\n","import { Container, inject, InjectableScope, InjectionToken, registerInjectable } from '@navios/di'\n\nimport { schemaFromGuard } from '../internal/schema-from-guard.mjs'\n\nimport { LoggerOutput } from './logger-output.mjs'\nimport { pendingOutput } from './pending-output.mjs'\n\nimport type { LogLevel } from './log-levels.mjs'\nimport type { LoggerService } from './logger-output.mjs'\n\n/**\n * Schema for logger options.\n */\nexport type LoggerOptions = { context?: string } | undefined\n\nconst loggerOptionsSchema = schemaFromGuard<LoggerOptions>(\n (value): value is LoggerOptions =>\n value === undefined ||\n (typeof value === 'object' &&\n value !== null &&\n ((value as { context?: unknown }).context === undefined ||\n typeof (value as { context?: unknown }).context === 'string')),\n 'Logger options must be an object with an optional string `context`',\n)\n\n/**\n * Injection token for the Logger service.\n *\n * Use this token to inject a contextualized logger instance.\n *\n * @example\n * ```typescript\n * const logger = inject(Logger, { context: 'MyService' })\n * logger.log('Hello world') // Logs with context: [MyService]\n * ```\n */\nexport const Logger = InjectionToken.create<LoggerInstance, typeof loggerOptionsSchema>(\n 'Logger',\n loggerOptionsSchema,\n)\n\n/**\n * Logger service instance that can be injected into services and controllers.\n *\n * Provides contextualized logging with automatic context injection.\n * The context is set when the logger is injected using the `inject` function.\n *\n * @example\n * ```typescript\n * @Injectable()\n * export class UserService {\n * private logger = inject(Logger, { context: UserService.name })\n *\n * async findUser(id: string) {\n * this.logger.log(`Finding user ${id}`)\n * // Logs with context: [UserService]\n * }\n * }\n * ```\n */\nexport class LoggerInstance implements LoggerService {\n protected localInstance: LoggerService = pendingOutput(inject(Container)) ?? inject(LoggerOutput)\n\n protected context?: string\n\n constructor(config: LoggerOptions = {}) {\n this.context = config?.context\n }\n\n /**\n * Write an 'error' level log.\n */\n error(message: any, stack?: string, context?: string): void\n error(message: any, ...optionalParams: [...any, string?, string?]): void\n error(message: any, ...optionalParams: any[]) {\n if (this.context && optionalParams.length === 0) {\n // The context of an error comes after its stack.\n optionalParams.push(undefined)\n }\n this.forward('error', message, optionalParams)\n }\n\n /**\n * Write a 'log' level log.\n */\n log(message: any, context?: string): void\n log(message: any, ...optionalParams: [...any, string?]): void\n log(message: any, ...optionalParams: any[]) {\n this.forward('log', message, optionalParams)\n }\n\n /**\n * Write a 'warn' level log.\n */\n warn(message: any, context?: string): void\n warn(message: any, ...optionalParams: [...any, string?]): void\n warn(message: any, ...optionalParams: any[]) {\n this.forward('warn', message, optionalParams)\n }\n\n /**\n * Write a 'debug' level log.\n */\n debug(message: any, context?: string): void\n debug(message: any, ...optionalParams: [...any, string?]): void\n debug(message: any, ...optionalParams: any[]) {\n this.forward('debug', message, optionalParams)\n }\n\n /**\n * Write a 'verbose' level log.\n */\n verbose(message: any, context?: string): void\n verbose(message: any, ...optionalParams: [...any, string?]): void\n verbose(message: any, ...optionalParams: any[]) {\n this.forward('verbose', message, optionalParams)\n }\n\n /**\n * Write a 'fatal' level log.\n */\n fatal(message: any, context?: string): void\n fatal(message: any, ...optionalParams: [...any, string?]): void\n fatal(message: any, ...optionalParams: any[]) {\n this.forward('fatal', message, optionalParams)\n }\n\n /** Writes to the output, the context last. `params` is the caller's own array. */\n private forward(level: LogLevel, message: any, params: any[]): void {\n if (this.context) {\n params.push(this.context)\n }\n this.localInstance[level]?.(message, ...params)\n }\n}\n\n// Transient: the context is free text, so a stored instance per context would\n// be one for every id that is logged with.\nregisterInjectable(LoggerInstance, { token: Logger, scope: InjectableScope.Transient })\n","import { isDeepStrictEqual } from 'node:util'\n\nimport type { PluginInstance } from './plugin.mjs'\n\n/**\n * Orders plugins so that each comes after the plugins it depends on. A plugin\n * registered twice is applied once; registering it again with other options\n * is an error, since only one of the two could take effect, and so are two\n * plugins of one name.\n */\nexport function orderPlugins(plugins: readonly PluginInstance[]): PluginInstance[] {\n const byName = new Map<string, PluginInstance>()\n for (const plugin of plugins) {\n const { name } = plugin.definition\n const existing = byName.get(name)\n if (existing === undefined) {\n byName.set(name, plugin)\n } else if (existing.definition !== plugin.definition) {\n throw new Error(`[Navios] Two plugins are named \"${name}\".`)\n } else if (!isDeepStrictEqual(existing.options, plugin.options)) {\n throw new Error(\n `[Navios] Plugin \"${name}\" is registered twice with different options. Register it once.`,\n )\n }\n }\n const ordered: PluginInstance[] = []\n const state = new Map<string, 'visiting' | 'done'>()\n const visit = (name: string, requiredBy: string | null): void => {\n const plugin = byName.get(name)\n if (!plugin) {\n throw new Error(\n `[Navios] Plugin \"${requiredBy}\" depends on \"${name}\", which is not registered.`,\n )\n }\n const current = state.get(name)\n if (current === 'done') {\n return\n }\n if (current === 'visiting') {\n throw new Error(`[Navios] Plugins depend on each other in a cycle through \"${name}\".`)\n }\n state.set(name, 'visiting')\n for (const dependency of plugin.definition.dependsOn ?? []) {\n visit(dependency, name)\n }\n state.set(name, 'done')\n ordered.push(plugin)\n }\n for (const name of byName.keys()) {\n visit(name, null)\n }\n return ordered\n}\n","export interface OnModuleInit {\n onModuleInit(): void | Promise<void>\n}\n\nexport interface OnApplicationBootstrap {\n onApplicationBootstrap(): void | Promise<void>\n}\n\nexport interface OnApplicationShutdown {\n onApplicationShutdown(signal?: string): void | Promise<void>\n}\n\n/**\n * Whether an object or its class declares a hook. The property is looked up and\n * not read: a proxy may answer for every name, or throw for one it does not know.\n */\nexport function declaresHook(instance: unknown, name: string): boolean {\n if ((typeof instance !== 'object' && typeof instance !== 'function') || instance === null) {\n return false\n }\n try {\n for (let at: object | null = instance; at !== null; at = Reflect.getPrototypeOf(at)) {\n const declared = Reflect.getOwnPropertyDescriptor(at, name)\n if (declared !== undefined) {\n return declared.get !== undefined || typeof declared.value === 'function'\n }\n }\n } catch {\n // A proxy that does not even let itself be looked at.\n }\n return false\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\ntype LifecyclePhase = 'init' | 'start' | 'shutdown'\n\n/**\n * One piece of code that an application calls and waits for: a hook, the\n * set-up of a plugin, the stop of a transport. When it calls back into a\n * lifecycle method that waits for the step itself, neither would ever finish.\n */\ninterface Step {\n readonly owner: object\n readonly phase: LifecyclePhase\n readonly outer: Step | undefined\n running: boolean\n}\n\nconst storage = new AsyncLocalStorage<Step>()\nlet running = 0\n\n/** Runs `fn` as a step of `owner`. */\nexport function runStep<T>(\n owner: object,\n phase: LifecyclePhase,\n fn: () => T | Promise<T>,\n): Promise<T> {\n const step: Step = { owner, phase, outer: storage.getStore(), running: true }\n running++\n return storage.run(step, async () => {\n try {\n return await fn()\n } finally {\n // Timers and servers that the step created stay in its async context,\n // but nobody waits for the step any more.\n step.running = false\n if (--running === 0) {\n // On runtimes that implement the storage with async hooks, it would\n // go on costing something for every promise of the process.\n try {\n storage.disable()\n } catch {\n // workerd has the method, which throws: its storage costs nothing.\n }\n }\n }\n })\n}\n\n/** The phase of the innermost step of `owner` that the caller is part of. */\nexport function currentPhase(owner: object): LifecyclePhase | null {\n for (let step = storage.getStore(); step !== undefined; step = step.outer) {\n if (step.owner === owner && step.running) {\n return step.phase\n }\n }\n return null\n}\n\n/** Runs `fn` as part of no step. */\nexport function outsideSteps<T>(fn: () => T): T {\n return storage.exit(fn)\n}\n","import { isSameProvider } from '@navios/di/internal'\n\nimport type { ClassType, InjectionToken, Provider } from '@navios/di'\n\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ninterface ModuleProvider {\n readonly module: ClassType\n readonly provider: Provider\n /**\n * Another module that provides something else for the token, when nothing\n * says which of the two is meant.\n */\n readonly rival?: ClassType\n}\n\ntype Candidate = { node: ModuleNode; provider: Provider }\n\nfunction importsIndirectly(importer: ModuleNode, imported: ModuleNode): boolean {\n const seen = new Set<ModuleNode>()\n const pending = [imported]\n for (let node = pending.pop(); node !== undefined; node = pending.pop()) {\n if (node === importer) {\n return true\n }\n if (!seen.has(node)) {\n seen.add(node)\n pending.push(...node.importers)\n }\n }\n return false\n}\n\nfunction choose(candidates: readonly Candidate[]): ModuleProvider {\n const [first] = candidates\n const others = candidates.filter(({ provider }) => !isSameProvider(provider, first.provider))\n if (others.length === 0) {\n return { module: first.node.module, provider: first.provider }\n }\n const [top, ...rest] = candidates.filter(\n ({ node }) =>\n !candidates.some((other) => other.node !== node && importsIndirectly(other.node, node)),\n )\n const rival = rest.find(({ provider }) => !isSameProvider(provider, top.provider))\n return { module: top.node.module, provider: top.provider, rival: rival?.node.module }\n}\n\n/**\n * The provider that modules supply for each token. A module overrides what it\n * imports, directly or not, and of several in one list the last one counts.\n * Modules of the application override those that plugins add. Between modules\n * that do not import each other nothing says which one is meant, unless they\n * provide the same.\n */\nexport function moduleProviders(\n graph: readonly ModuleNode[],\n isOfApplication: (module: ClassType) => boolean,\n): Map<InjectionToken<any, any>, ModuleProvider> {\n const candidates = new Map<InjectionToken<any, any>, Candidate[]>()\n // Importers first, so that a module that overrides another comes before it.\n for (const node of [...graph].reverse()) {\n const own = new Map(node.providers.map((provider) => [provider.token, provider]))\n for (const [token, provider] of own) {\n const list = candidates.get(token)\n if (list) {\n list.push({ node, provider })\n } else {\n candidates.set(token, [{ node, provider }])\n }\n }\n }\n const chosen = new Map<InjectionToken<any, any>, ModuleProvider>()\n for (const [token, all] of candidates) {\n const ofApplication = all.filter(({ node }) => isOfApplication(node.module))\n chosen.set(token, choose(ofApplication.length > 0 ? ofApplication : all))\n }\n return chosen\n}\n","import { outsideSteps } from './lifecycle-step.mjs'\n\ninterface Closable {\n close(signal?: string): Promise<void>\n}\n\nexport interface ShutdownHooksOptions {\n /**\n * Whether the signal ends the process once every application has closed,\n * as it would have without a listener. It does not when something else in\n * the process listens to the signal.\n * @default true\n */\n exit?: boolean\n}\n\ninterface Registration {\n exit: boolean\n onError(signal: string, error: unknown): void\n}\n\n/** Every application that one signal closes, until it is closed. */\ninterface SignalRegistry {\n readonly applications: Map<Closable, Registration>\n readonly listener: () => void\n}\n\nconst registries = new Map<NodeJS.Signals, SignalRegistry>()\n\n/** Closes `application` when the process receives one of the signals. */\nexport function closeOnSignals(\n application: Closable,\n signals: readonly NodeJS.Signals[],\n registration: Registration,\n): void {\n for (const signal of signals) {\n let registry = registries.get(signal)\n if (registry === undefined) {\n const created: SignalRegistry = {\n applications: new Map(),\n listener: () => void receive(signal, created),\n }\n registry = created\n registries.set(signal, registry)\n process.on(signal, registry.listener)\n }\n registry.applications.set(application, registration)\n }\n}\n\n/**\n * Ends what `closeOnSignals` did for an application once it has closed. Until\n * then a signal must not end the process.\n */\nexport function stopListening(application: Closable, closing: Promise<unknown>): void {\n for (const { applications } of registries.values()) {\n if (applications.has(application)) {\n const forgetIt = () => forget(application)\n closing.then(forgetIt, forgetIt)\n return\n }\n }\n}\n\nfunction forget(application: Closable): void {\n for (const [signal, registry] of registries) {\n if (registry.applications.delete(application) && registry.applications.size === 0) {\n remove(signal, registry)\n }\n }\n}\n\nfunction remove(signal: NodeJS.Signals, registry: SignalRegistry): void {\n registries.delete(signal)\n process.off(signal, registry.listener)\n}\n\nasync function receive(signal: NodeJS.Signals, registry: SignalRegistry): Promise<void> {\n // From here on signals do what they do by default: a second one ends the\n // process at once.\n remove(signal, registry)\n const applications = [...registry.applications]\n await Promise.all(\n applications.map(async ([application, { onError }]) => {\n forget(application)\n try {\n // A listener runs in the async context it was installed in, which may\n // be a hook that the shutdown has to wait for.\n await outsideSteps(() => application.close(signal))\n } catch (error) {\n onError(signal, error)\n }\n }),\n )\n const exit = applications.every(([, registration]) => registration.exit)\n if (exit && process.listenerCount(signal) === 0) {\n endProcess(signal)\n }\n}\n\n/**\n * The numbers that are the same on every platform, for a runtime that has no\n * `node:os` to ask.\n */\nconst SIGNAL_NUMBERS: Partial<Record<NodeJS.Signals, number>> = {\n SIGHUP: 1,\n SIGINT: 2,\n SIGQUIT: 3,\n SIGABRT: 6,\n SIGKILL: 9,\n SIGALRM: 14,\n SIGTERM: 15,\n}\n\n/**\n * The number of a signal. `node:os` is asked for when a signal has arrived\n * and not imported: workerd has no such module before the compatibility date\n * 2025-09-15, and a Worker that never gets a signal must still load.\n */\nfunction signalNumber(signal: NodeJS.Signals): number | undefined {\n let numbers: Partial<Record<string, number>> | undefined\n try {\n numbers = process.getBuiltinModule?.('node:os')?.constants.signals\n } catch {\n // The runtime does not have it.\n }\n return numbers?.[signal] ?? SIGNAL_NUMBERS[signal]\n}\n\nfunction endProcess(signal: NodeJS.Signals): void {\n if (process.pid === 1) {\n // The first process of a container gets no signal that it does not handle.\n const number = signalNumber(signal)\n process.exit(number === undefined ? 1 : 128 + number)\n } else {\n process.kill(process.pid, signal)\n }\n}\n","import { Container, provide } from '@navios/di'\nimport {\n constructedInstances,\n hasOwnProvider,\n setErrorReporter,\n setProvider,\n} from '@navios/di/internal'\n\nimport type { ClassType, InjectionToken, Provider } from '@navios/di'\n\nimport { enableAsyncContext } from '../execution/async-context.mjs'\nimport { createContextHost } from '../execution/context-host.mjs'\nimport { ConsoleLogger } from '../logger/console-logger.mjs'\nimport { LoggerOutput } from '../logger/logger-output.mjs'\nimport { Logger } from '../logger/logger.mjs'\nimport { deferOutput, endDeferral } from '../logger/pending-output.mjs'\nimport { buildModuleGraph } from '../modules/module-graph.mjs'\nimport { assertProviders } from '../modules/module-metadata.mjs'\nimport { orderPlugins } from '../plugins/order-plugins.mjs'\nimport { MAX_DELAY_MS, settledWithin } from '../transports/settled-within.mjs'\n\nimport type { InterceptorClass } from '../interceptors/interceptor.mjs'\nimport type { LoggerService } from '../logger/logger-output.mjs'\nimport type { LoggerInstance } from '../logger/logger.mjs'\nimport type { PendingOutput } from '../logger/pending-output.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\nimport type { PluginApi, PluginInstance } from '../plugins/plugin.mjs'\nimport type {\n Transport,\n TransportFactory,\n TransportHost,\n TransportInstance,\n} from '../transports/transport.mjs'\n\nimport { declaresHook } from './lifecycle-hooks.mjs'\nimport { currentPhase, outsideSteps, runStep } from './lifecycle-step.mjs'\nimport { moduleProviders } from './module-providers.mjs'\nimport { closeOnSignals, stopListening } from './shutdown-signals.mjs'\n\nimport type { ApplicationOptions } from './application-options.mjs'\nimport type {\n OnApplicationBootstrap,\n OnApplicationShutdown,\n OnModuleInit,\n} from './lifecycle-hooks.mjs'\nimport type { ShutdownHooksOptions } from './shutdown-signals.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nconst noopLogger: LoggerService = {\n log() {},\n error() {},\n warn() {},\n debug() {},\n verbose() {},\n fatal() {},\n}\n\n/**\n * How much longer than the time it was given a transport may take to stop. It\n * has things to release once the work in flight is done, or was cut off.\n */\nconst STOP_GRACE_MS = 3000\n\n/** The containers that back an application which has not been closed. */\nconst backing = new WeakSet<Container>()\n\nfunction ignore(): void {}\n\nfunction closedError(): Error {\n return new Error('[Navios] The application is closed.')\n}\n\n/** What a call returns that its caller must not wait for, and need not handle. */\nfunction refused(message: string): Promise<never> {\n const rejected = Promise.reject(new Error(`[Navios] ${message}`))\n rejected.catch(ignore)\n return rejected\n}\n\nfunction className(instance: unknown): string {\n try {\n return String(Object.getPrototypeOf(instance)?.constructor?.name)\n } catch {\n return 'an object'\n }\n}\n\ninterface TransportSlot {\n readonly instance: TransportInstance\n transport: Transport | null\n stopped: boolean\n}\n\n/**\n * An application: a module tree, one container, and the transports through\n * which work reaches it.\n *\n * ```ts\n * const app = createApplication(AppModule, {\n * transports: [queueTransport({ url })],\n * })\n * await app.start()\n * ```\n */\nexport class Application {\n readonly container: Container\n protected logger!: LoggerInstance\n private readonly plugins: PluginInstance[]\n private readonly slots: TransportSlot[]\n private readonly extraModules: ClassType[] = []\n private readonly globalInterceptors: InterceptorClass[] = []\n private readonly bootstrapHooks: Array<() => void | Promise<void>> = []\n private readonly shutdownHooks: Array<{\n plugin: string\n run: (signal?: string) => void | Promise<void>\n }> = []\n /** What modules and plugins provide. Everything else is the caller's. */\n private readonly supplied = new Map<InjectionToken<any, any>, Provider | 'plugin'>()\n /** For the log, once there is one. */\n private readonly notes: string[] = []\n /** What loggers write to until it is settled where the log goes. */\n private pendingOutput: PendingOutput | null = null\n private transportsCreated = false\n private settingUpPlugins = false\n private initialised = false\n private initialisation: Promise<void> | null = null\n private startup: Promise<void> | null = null\n private closing: Promise<void> | null = null\n private tearingDown: Promise<void> | null = null\n private signal: string | undefined\n\n constructor(\n private readonly appModule: ClassType,\n private readonly applicationOptions: ApplicationOptions = {},\n ) {\n const options = applicationOptions\n if (options.container && backing.has(options.container)) {\n throw new Error(\n '[Navios] This container already backs an open application. Close that one first, or ' +\n 'give each application a container of its own.',\n )\n }\n this.container = options.container ?? new Container()\n // The last one of several for one token counts.\n const given = new Map<InjectionToken<any, any>, [option: string, Provider]>()\n assertProviders('The application', options.providers ?? [])\n for (const provider of options.providers ?? []) {\n given.set(provider.token, ['providers', provider])\n }\n const { logger } = options\n if (logger !== undefined && !Array.isArray(logger)) {\n const value = logger === false ? noopLogger : logger\n given.set(LoggerOutput, ['logger', provide(LoggerOutput, { value })])\n }\n for (const [option, provider] of given.values()) {\n this.provideOption(option, provider)\n }\n this.plugins = [...(options.plugins ?? [])]\n this.slots = []\n for (const instance of options.transports ?? []) {\n if (this.slots.some((slot) => slot.instance.instanceName === instance.instanceName)) {\n throw new Error(`[Navios] Two transports are named \"${instance.instanceName}\".`)\n }\n this.slots.push({ instance, transport: null, stopped: false })\n }\n backing.add(this.container)\n setErrorReporter(this.container, (error, description) => this.report(description, error))\n }\n\n /** Supplies what an option provides, unless the given container does. */\n private provideOption(option: string, provider: Provider): void {\n const { token } = provider\n if (this.isProvidedByCaller(token)) {\n this.notes.push(\n `The container provides ${token}, so the one of the \\`${option}\\` option is not used.`,\n )\n } else if (!setProvider(this.container, provider)) {\n throw new Error(\n `[Navios] \\`${option}\\` has ${token}, which has already been resolved in \\`container\\`.`,\n )\n }\n }\n\n /** Tells what nobody else receives. Never throws. */\n private report(message: string, error?: unknown): void {\n try {\n if (this.logger) {\n this.logger.error(message, error)\n return\n }\n if (this.applicationOptions.logger === false) {\n return\n }\n } catch {\n // The logger fails as well.\n }\n console.error(`[Navios] ${message}`, ...(error === undefined ? [] : [error]))\n }\n\n // --------------------------------------------------------------------------\n // Configuration, before init()\n // --------------------------------------------------------------------------\n\n private assertConfigurable(what: string): void {\n if (this.initialisation !== null) {\n throw new Error(`[Navios] ${what} must be called before init()`)\n }\n }\n\n usePlugin(plugin: PluginInstance): this {\n this.assertConfigurable('usePlugin()')\n this.plugins.push(plugin)\n return this\n }\n\n /** Adds an interceptor around every handler, on every transport. */\n intercept(interceptor: InterceptorClass): this {\n this.assertConfigurable('intercept()')\n this.globalInterceptors.push(interceptor)\n return this\n }\n\n // --------------------------------------------------------------------------\n // Access\n // --------------------------------------------------------------------------\n\n get: Container['get'] = ((token: any, args?: unknown) =>\n (this.container.get as any)(token, args)) as Container['get']\n\n /**\n * One of the application's transports. Transports are created by `init()`.\n * Throws when the application has no such transport; `findTransport`\n * returns `undefined` instead.\n */\n transport<T extends Transport>(factory: TransportFactory<any, T>, instanceName?: string): T {\n const name = instanceName ?? factory.definition.name\n if (!this.transportsCreated) {\n throw new Error(`[Navios] The \"${name}\" transport is created by init(); call init() first.`)\n }\n const transport = this.findTransport(factory, instanceName)\n if (transport === undefined) {\n throw new Error(`[Navios] The application has no \"${name}\" transport.`)\n }\n return transport\n }\n\n /** Like `transport`, but `undefined` when there is none, or not yet. */\n findTransport<T extends Transport>(\n factory: TransportFactory<any, T>,\n instanceName?: string,\n ): T | undefined {\n const name = instanceName ?? factory.definition.name\n for (const slot of this.slots) {\n if (slot.instance.definition === factory.definition && slot.instance.instanceName === name) {\n return (slot.transport ?? undefined) as T | undefined\n }\n }\n return undefined\n }\n\n // --------------------------------------------------------------------------\n // Initialisation\n // --------------------------------------------------------------------------\n\n /**\n * Builds the application: transports, plugins, modules and each\n * transport's handlers. Runs once, however often and from wherever it is\n * called; every caller gets the outcome of that run. Only a hook that the\n * run itself waits for cannot call it.\n *\n * An application that fails to initialise is closed before this rejects, and\n * stays failed, because it is only partly built.\n */\n init(): Promise<this> {\n if (currentPhase(this) === 'init') {\n return refused('init() was called from inside init(), which waits for the caller.')\n }\n const waitsForCaller = currentPhase(this) === 'shutdown' && !this.initialised\n if (this.closed && (this.initialisation === null || waitsForCaller)) {\n return Promise.reject(closedError())\n }\n this.initialisation ??= this.initialise()\n return this.initialisation.then(() => this)\n }\n\n /** Whether `close()` was called, or a failed start-up took the application down. */\n private get closed(): boolean {\n return this.closing !== null || this.tearingDown !== null\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw closedError()\n }\n }\n\n /**\n * Rejects when the application has been closed, after that shutdown has\n * finished: the process may end when the caller fails.\n */\n protected async assertStillOpen(): Promise<void> {\n await this.closing?.catch(ignore)\n this.assertOpen()\n }\n\n /** Calls code that the application waits for. */\n private step<T>(phase: 'init' | 'start', fn: () => T | Promise<T>): Promise<T> {\n this.assertNotTornDown()\n return runStep(this, phase, fn)\n }\n\n /** A shutdown does not wait for a start-up that hangs; that one ends here. */\n private assertNotTornDown(): void {\n if (this.tearingDown !== null) {\n throw closedError()\n }\n }\n\n private async initialise(): Promise<void> {\n this.pendingOutput = deferOutput(this.container, () => this.settleLoggerNow())\n try {\n await this.build()\n } catch (error) {\n await this.tearDownFailed()\n throw error\n } finally {\n endDeferral(this.container)\n }\n }\n\n /**\n * Nothing may be left half-open when the start-up fails: what was created\n * holds what it acquired, and background work would go on.\n */\n private async tearDownFailed(): Promise<void> {\n try {\n await this.teardown(0)\n } catch (error) {\n this.report('Error disposing the container', error)\n }\n }\n\n private async build(): Promise<void> {\n const { applicationOptions: options, container } = this\n\n // The providers of the modules come first: whatever is resolved from here\n // on must already see them.\n let graph = buildModuleGraph([this.appModule])\n const own = new Set(graph.map((node) => node.module))\n this.applyModuleProviders(graph, own, 'before plugins')\n\n this.logger = await this.step('init', () => container.get(Logger, { context: 'Navios' }))\n for (const note of this.notes.splice(0)) {\n this.logger.debug(note)\n }\n\n if (options.asyncContext) {\n await enableAsyncContext()\n }\n\n const host: TransportHost = {\n container,\n logger: this.logger,\n contextHost: createContextHost(\n container,\n options.requestScopedServices ?? (process.env.NODE_ENV === 'production' ? 'allow' : 'warn'),\n this.logger,\n ),\n asyncContext: options.asyncContext ?? false,\n interceptors: this.globalInterceptors,\n }\n this.transportsCreated = true\n for (const slot of this.slots) {\n const { definition, options: transportOptions } = slot.instance\n slot.transport = await this.step('init', () => definition.create(host, transportOptions))\n if (this.tearingDown !== null) {\n // Created too late for the shutdown to see it.\n await this.stopTransport(slot, 0)\n }\n }\n\n await this.setupPlugins()\n if (this.extraModules.length > 0) {\n // Modules that plugins added are only known now.\n graph = buildModuleGraph([this.appModule, ...this.extraModules])\n }\n this.applyModuleProviders(graph, own, 'after plugins')\n\n // Everything that may provide the logger has had its turn.\n await this.step('init', () => this.settleLogger())\n\n for (const node of graph) {\n await this.step('init', async () => {\n const instance = await container.get(node.module)\n if (declaresHook(instance, 'onModuleInit')) {\n await (instance as OnModuleInit).onModuleInit()\n }\n })\n }\n\n for (const slot of this.slots) {\n await this.step('init', () => slot.transport!.setup(graph))\n }\n\n for (const hook of this.bootstrapHooks) {\n await this.step('init', hook)\n }\n for (const instance of constructedInstances(container)) {\n if (declaresHook(instance, 'onApplicationBootstrap')) {\n await this.step('init', () => (instance as OnApplicationBootstrap).onApplicationBootstrap())\n }\n }\n this.assertNotTornDown()\n this.initialised = true\n }\n\n /**\n * Whether the caller provides a token: with the options of the application\n * or in its container, where an instance may also have been put.\n */\n private isProvidedByCaller(token: InjectionToken<any, any>): boolean {\n if (this.supplied.has(token)) {\n return false\n }\n if (hasOwnProvider(this.container, token)) {\n return true\n }\n const instance = this.container.peek(token)\n return instance !== null && !constructedInstances(this.container).includes(instance)\n }\n\n /**\n * Supplies what the modules provide, unless the application or a plugin\n * provides it. Modules that disagree about a token are an error where one of\n * them would have to be used, which is settled after the plugins.\n */\n private applyModuleProviders(\n graph: readonly ModuleNode[],\n own: ReadonlySet<ClassType>,\n when: 'before plugins' | 'after plugins',\n ): void {\n const provided = moduleProviders(graph, (module) => own.has(module))\n for (const [token, { provider, module, rival }] of provided) {\n const supplied = this.supplied.get(token)\n if (supplied === provider || supplied === 'plugin' || this.isProvidedByCaller(token)) {\n continue\n }\n let used = provider\n if (rival !== undefined) {\n const conflict = new Error(\n `[Navios] Modules ${rival.name} and ${module.name} both provide ${token}, and neither ` +\n `imports the other. Provide it in a module that imports both, or with the ` +\n `\\`providers\\` option of the application.`,\n )\n if (when === 'after plugins') {\n throw conflict\n }\n // Whoever needs the token before a plugin may have decided gets to know.\n used = provide(token, {\n factory: () => {\n throw conflict\n },\n })\n }\n if (!setProvider(this.container, used)) {\n throw new Error(\n `[Navios] ${module.name} provides ${token}, which has already been resolved. Resolve ` +\n `it later, or provide it with the \\`providers\\` option of the application.`,\n )\n }\n this.supplied.set(token, used)\n }\n }\n\n private async settleLogger(): Promise<void> {\n const output = await this.container.get(LoggerOutput)\n this.configureOutput(output)\n this.pendingOutput!.settle(output)\n endDeferral(this.container)\n }\n\n /** What was logged so far is not lost, whatever becomes of the start-up. */\n private settleLoggerNow(): void {\n if (this.pendingOutput === null || this.pendingOutput.isSettled) {\n return\n }\n let output: LoggerService\n try {\n output = this.container.getSync(LoggerOutput)\n this.configureOutput(output)\n } catch {\n // It is built asynchronously, or cannot be built.\n output = new ConsoleLogger()\n this.configureOutput(output)\n }\n this.pendingOutput.settle(output)\n }\n\n private configureOutput(output: LoggerService): void {\n const { logger, asyncContext } = this.applicationOptions\n if (Array.isArray(logger)) {\n output.setLogLevels?.(logger)\n }\n if (asyncContext && output instanceof ConsoleLogger) {\n output.setDefaults({ requestId: true })\n }\n }\n\n private async setupPlugins(): Promise<void> {\n this.settingUpPlugins = true\n try {\n for (const { definition, options } of orderPlugins(this.plugins)) {\n this.logger.debug(`Setting up plugin ${definition.name}`)\n const api = this.pluginApi(definition.name)\n await this.step('init', () => definition.setup(api, options))\n }\n } finally {\n this.settingUpPlugins = false\n }\n }\n\n private pluginApi(plugin: string): PluginApi {\n const { container } = this\n const assertSetup = (call: string) => {\n if (!this.settingUpPlugins) {\n throw new Error(`[Navios] api.${call}() must be called during setup`)\n }\n }\n return {\n container,\n provide: ((target: any, impl: any) => {\n assertSetup('provide')\n const { token } = provide(target, impl)\n if (this.isProvidedByCaller(token)) {\n this.logger.debug(\n `Plugin ${plugin} provides ${token}, but the application provides its own.`,\n )\n return\n }\n container.provide(target, impl)\n this.supplied.set(token, 'plugin')\n }) as Container['provide'],\n decorate: ((target: any, decorator: any) => {\n assertSetup('decorate')\n container.decorate(target, decorator)\n }) as Container['decorate'],\n intercept: (interceptor) => {\n assertSetup('intercept')\n this.globalInterceptors.push(interceptor)\n },\n addModule: (module) => {\n assertSetup('addModule')\n this.extraModules.push(module)\n },\n transport: (factory, instanceName) => this.findTransport(factory, instanceName),\n onBootstrap: (hook) => {\n assertSetup('onBootstrap')\n this.bootstrapHooks.push(hook)\n },\n onShutdown: (hook) => {\n assertSetup('onShutdown')\n this.shutdownHooks.push({ plugin, run: hook })\n },\n }\n }\n\n // --------------------------------------------------------------------------\n // Running\n // --------------------------------------------------------------------------\n\n /**\n * Initialises the application if needed, then starts every transport, in\n * the order they were listed. A transport is started at most once, however\n * often this is called. An application whose transports do not all start is\n * closed before this rejects.\n *\n * Called from something `init()` waits for, it starts the application\n * afterwards and returns a promise that rejects.\n */\n start(): Promise<this> {\n const phase = currentPhase(this)\n if (phase !== 'init' && phase !== 'start') {\n return this.startOnce()\n }\n if (phase === 'init') {\n outsideSteps(() => this.startOnce()).catch((error: unknown) => {\n // Whoever called init() learns why that failed.\n if (this.startup !== null) {\n this.report('Error starting the application', error)\n }\n })\n }\n return refused(\n `start() was called from inside ${phase}(), which waits for the caller.` +\n (phase === 'init' ? ' Call it without waiting for it.' : ''),\n )\n }\n\n private async startOnce(): Promise<this> {\n await this.init()\n if (this.startup === null) {\n // The application may have been closed while it was initialising.\n await this.assertStillOpen()\n this.startup ??= this.startTransports()\n }\n await this.startup\n return this\n }\n\n private async startTransports(): Promise<void> {\n try {\n // Runs once: `startup` is never retried.\n for (const slot of this.slots) {\n await this.startTransport(slot)\n }\n this.assertNotTornDown()\n } catch (error) {\n await this.tearDownFailed()\n throw error\n }\n }\n\n private async startTransport(slot: TransportSlot): Promise<void> {\n try {\n await this.step('start', () => slot.transport!.start?.())\n } finally {\n if (slot.stopped) {\n // The shutdown did not wait any longer, and stopped what had not started.\n slot.stopped = false\n await this.stopTransport(slot, 0)\n }\n }\n }\n\n /**\n * Closes the application when the process receives one of the signals. Call\n * it before `start()`, so that a signal during the start-up is seen.\n *\n * A signal that has a listener no longer ends the process. When everything\n * the signal closes is closed, the process is therefore sent the signal\n * again, or exits with its code when it is process 1, unless `exit` is\n * `false` or something else listens to it. A second signal does not wait for\n * the shutdown, unlike one during a `close()` that the application called.\n */\n enableShutdownHooks(\n signals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'],\n options: ShutdownHooksOptions = {},\n ): this {\n this.assertOpen()\n closeOnSignals(this, signals, {\n exit: options.exit ?? true,\n onError: (signal, error) => this.report(`Error closing the application on ${signal}`, error),\n })\n return this\n }\n\n /**\n * Shuts down: every transport stops accepting work and waits for what is\n * in flight, shutdown hooks run in reverse order, then the container is\n * disposed, which runs `onServiceDestroy` hooks. Each step gets\n * `shutdownTimeout`; one that takes longer is reported and left behind.\n *\n * Runs once, however often and from wherever it is called, and every caller\n * gets the outcome of that run, with two exceptions, since they would wait\n * for themselves. Called from something the shutdown waits for, it resolves\n * at once. Called from something `init()` or `start()` waits for, it closes\n * the application afterwards and returns a promise that rejects.\n */\n close(signal?: string): Promise<void> {\n const phase = currentPhase(this)\n if (phase === 'shutdown') {\n return Promise.resolve()\n }\n if (this.closing === null) {\n this.signal ??= signal\n // Signals are no longer listened to once it reaches the teardown, which it always does.\n this.closing = this.shutdown()\n }\n if (phase !== null) {\n this.closing.catch((error: unknown) => this.report('Error closing the application', error))\n return refused(\n `close() was called from inside ${phase}(), which waits for the caller. Throw an error ` +\n `instead, or call close() without waiting for it.`,\n )\n }\n return this.closing\n }\n\n /** Transports are given it, and may add to it, for a timer of theirs. */\n private get shutdownTimeout(): number {\n const { shutdownTimeout = 10_000 } = this.applicationOptions\n return Math.min(shutdownTimeout, MAX_DELAY_MS - 60_000)\n }\n\n private async shutdown(): Promise<void> {\n // Whatever is still being built or started is let finish first, so that\n // nothing is created or started after it was stopped. Their failures\n // belong to whoever called init() or start().\n for (const [call, pending] of [\n ['init()', this.initialisation],\n ['start()', this.startup],\n ] as const) {\n if (pending !== null) {\n await this.shutdownStep(call, this.shutdownTimeout, () => pending.catch(ignore))\n }\n }\n await this.teardown(this.shutdownTimeout)\n }\n\n /** Takes down whatever was built so far, once. */\n private teardown(transportTimeout: number): Promise<void> {\n if (this.tearingDown === null) {\n this.tearingDown = this.takeDown(transportTimeout)\n stopListening(this, this.tearingDown)\n }\n return this.tearingDown\n }\n\n private async takeDown(transportTimeout: number): Promise<void> {\n const { container, shutdownTimeout } = this\n this.settleLoggerNow()\n try {\n await Promise.all(this.slots.map((slot) => this.stopTransport(slot, transportTimeout)))\n\n for (const instance of constructedInstances(container).reverse()) {\n if (declaresHook(instance, 'onApplicationShutdown')) {\n const label = `onApplicationShutdown of ${className(instance)}`\n await this.shutdownStep(label, shutdownTimeout, () =>\n (instance as OnApplicationShutdown).onApplicationShutdown(this.signal),\n )\n }\n }\n for (const { plugin, run } of this.shutdownHooks.reverse()) {\n await this.shutdownStep(`onShutdown of plugin ${plugin}`, shutdownTimeout, () =>\n run(this.signal),\n )\n }\n const disposal = runStep(this, 'shutdown', () => container.dispose())\n if (!(await settledWithin(disposal, shutdownTimeout))) {\n this.reportTimeout('disposal of the container', shutdownTimeout)\n }\n } finally {\n backing.delete(container)\n }\n }\n\n /**\n * Stops a transport that was created, once, however often and from\n * wherever this is asked for.\n */\n private async stopTransport(slot: TransportSlot, timeoutMs: number): Promise<void> {\n const { transport } = slot\n if (transport !== null && !slot.stopped) {\n slot.stopped = true\n const label = `stop of transport ${slot.instance.instanceName}`\n await this.shutdownStep(label, timeoutMs + STOP_GRACE_MS, () => transport.stop(timeoutMs))\n }\n }\n\n /** Runs one part of the shutdown. Whatever becomes of it, the rest follows. */\n private async shutdownStep(\n label: string,\n timeoutMs: number,\n fn: () => void | Promise<void>,\n ): Promise<void> {\n try {\n if (!(await settledWithin(runStep(this, 'shutdown', fn), timeoutMs))) {\n this.reportTimeout(label, timeoutMs)\n }\n } catch (error) {\n this.report(`Error in shutdown step \"${label}\"`, error)\n }\n }\n\n private reportTimeout(label: string, timeoutMs: number): void {\n this.report(`Shutdown step \"${label}\" did not finish within ${timeoutMs} ms`)\n }\n\n /** Alias of `close()`. */\n dispose(): Promise<void> {\n return this.close()\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.close()\n }\n}\n\n/**\n * Creates an application from its root module. Call `init()` to build it, or\n * `start()` to build it and start its transports.\n */\nexport function createApplication(appModule: ClassType, options?: ApplicationOptions): Application {\n return new Application(appModule, options)\n}\n","import type { Path, PathValue } from './config-path.mjs'\n\n/**\n * Interface for configuration service implementations.\n *\n * Provides type-safe access to configuration values with support for nested paths.\n *\n * @typeParam Config - The configuration object type\n */\nexport interface ConfigServiceInterface<Config extends object = Record<string, unknown>> {\n /**\n * Gets the entire configuration object.\n */\n getConfig: () => Config\n /**\n * Gets a configuration value by key path. Returns `null` if not found.\n *\n * @param key - Dot-separated path to the configuration value (e.g., 'database.host')\n * @returns The configuration value or `null` if not found\n */\n get: <Key extends Path<Config>>(key: Key) => NonNullable<PathValue<Config, Key>> | null\n\n /**\n * Gets a configuration value by key path, or returns a default value if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param defaultValue - Default value to return if the key is not found\n * @returns The configuration value or the default value\n */\n getOrDefault: <Key extends Path<Config>>(\n key: Key,\n defaultValue: NonNullable<PathValue<Config, Key>>,\n ) => NonNullable<PathValue<Config, Key>>\n\n /**\n * Gets a configuration value by key path, or throws an error if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param errorMessage - Optional custom error message\n * @returns The configuration value\n * @throws Error if the key is not found\n */\n getOrThrow: <Key extends Path<Config>>(\n key: Key,\n errorMessage?: string,\n ) => NonNullable<PathValue<Config, Key>>\n}\n\n/**\n * Service for managing application configuration with type-safe access.\n *\n * Provides methods to access configuration values using dot-notation paths\n * with full TypeScript type inference. `provideConfig()` gives the token of\n * one; `new ConfigService({ ... })` is what a test provides for it.\n *\n * @typeParam Config - The configuration object type\n *\n * @example\n * ```typescript\n * interface AppConfig {\n * database: {\n * host: string\n * port: number\n * }\n * api: {\n * timeout: number\n * }\n * }\n *\n * export const AppConfig = provideConfig<AppConfig>({ load: () => readConfig() })\n *\n * @Injectable()\n * export class DatabaseService {\n * private config = inject(AppConfig)\n *\n * connect() {\n * const host = this.config.getOrThrow('database.host')\n * const port = this.config.getOrDefault('database.port', 5432)\n * // host is typed as string, port is typed as number\n * }\n * }\n * ```\n */\nexport class ConfigService<\n Config extends object = Record<string, unknown>,\n> implements ConfigServiceInterface<Config> {\n /**\n * Creates a new ConfigService instance.\n *\n * @param config - The configuration object\n */\n constructor(private readonly config: Config = {} as Config) {}\n\n /**\n * Gets the entire configuration object.\n *\n * @returns The complete configuration object\n */\n getConfig(): Config {\n return this.config\n }\n\n /**\n * Gets a configuration value by key path.\n *\n * Returns `null` if the key is not found or if any part of the path is invalid.\n *\n * @param key - Dot-separated path to the configuration value (e.g., 'database.host')\n * @returns The configuration value or `null` if not found\n *\n * @example\n * ```typescript\n * const host = config.get('database.host') // string | null\n * const port = config.get('database.port') // number | null\n * ```\n */\n get<Key extends Path<Config>>(key: Key): NonNullable<PathValue<Config, Key>> | null {\n let value: any = this.config\n for (const part of String(key).split('.')) {\n if (value === null || value === undefined || typeof value !== 'object') {\n return null\n }\n value = value[part]\n }\n return (value as NonNullable<PathValue<Config, Key>>) ?? null\n }\n\n /**\n * Gets a configuration value by key path, or returns a default value if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param defaultValue - Default value to return if the key is not found\n * @returns The configuration value or the default value\n *\n * @example\n * ```typescript\n * const port = config.getOrDefault('database.port', 5432) // number\n * ```\n */\n getOrDefault<Key extends Path<Config>>(\n key: Key,\n defaultValue: NonNullable<PathValue<Config, Key>>,\n ): NonNullable<PathValue<Config, Key>> {\n return this.get(key) ?? defaultValue\n }\n\n /**\n * Gets a configuration value by key path, or throws an error if not found.\n *\n * @param key - Dot-separated path to the configuration value\n * @param errorMessage - Optional custom error message\n * @returns The configuration value\n * @throws Error if the key is not found\n *\n * @example\n * ```typescript\n * const host = config.getOrThrow('database.host') // string (throws if not found)\n * const apiKey = config.getOrThrow('api.key', 'API key is required') // string\n * ```\n */\n getOrThrow<Key extends Path<Config>>(\n key: Key,\n errorMessage?: string,\n ): NonNullable<PathValue<Config, Key>> {\n const value = this.get(key)\n if (value === null) {\n throw new Error(errorMessage || `Configuration value for key \"${String(key)}\" is not defined`)\n }\n return value\n }\n}\n","import { env } from 'node:process'\n\n/**\n * Reads an integer. A variable that is missing or empty gives the default; one\n * that is not an integer throws, because it is a mistake the default would hide.\n */\nexport function envInt(key: keyof NodeJS.ProcessEnv, defaultValue: number): number {\n const raw = env[key]?.trim()\n if (!raw) {\n return defaultValue\n }\n const value = Number(raw)\n if (!/^[+-]?\\d+$/.test(raw) || !Number.isSafeInteger(value)) {\n throw new Error(`[Navios] The environment variable ${key} is not an integer.`)\n }\n return value\n}\n\n/** Reads a string. A variable that is missing or empty gives the default. */\nexport function envString(key: keyof NodeJS.ProcessEnv): string | undefined\nexport function envString(key: keyof NodeJS.ProcessEnv, defaultValue: string): string\nexport function envString(\n key: keyof NodeJS.ProcessEnv,\n defaultValue: string | undefined,\n): string | undefined\nexport function envString(key: keyof NodeJS.ProcessEnv, defaultValue?: string): string | undefined {\n return env[key] || defaultValue || undefined\n}\n","import type { StandardSchemaIssue } from '@navios/di'\n\n/** As many characters of a value in a row tell something about it. */\nconst TELLING = 4\n/** The same for a value that is one of many. */\nconst TELLING_OF_MANY = 8\n\ntype Path = NonNullable<StandardSchemaIssue['path']>\n\nfunction keyOf(part: Path[number]): PropertyKey {\n return typeof part === 'object' ? part.key : part\n}\n\n/** Whether `message` has `length` characters of `value` in a row, or all it has. */\nfunction tells(message: string, value: string, length: number): boolean {\n const text = value.toLowerCase()\n const size = Math.min(length, text.length)\n for (let start = 0; size > 0 && start + size <= text.length; start++) {\n if (message.includes(text.slice(start, start + size))) {\n return true\n }\n }\n return false\n}\n\n/** The texts in which something may appear in a message. */\nfunction* texts(value: unknown, seen = new Set<unknown>()): Generator<string> {\n if (typeof value !== 'object' || value === null) {\n if (value !== undefined && value !== null && typeof value !== 'boolean') {\n yield String(value)\n }\n return\n }\n if (seen.has(value)) {\n return\n }\n seen.add(value)\n const { toJSON, toString } = value as { toJSON?: unknown; toString?: unknown }\n if (typeof toJSON === 'function') {\n yield String(toJSON.call(value))\n }\n if (typeof toString === 'function' && toString !== Object.prototype.toString) {\n yield String(value)\n }\n const inner = value instanceof Map || value instanceof Set ? value.values() : Object.values(value)\n for (const each of inner) {\n yield* texts(each, seen)\n }\n}\n\nfunction valueAt(loaded: unknown, path: Path): unknown {\n let value = loaded\n for (const part of path) {\n if (typeof value !== 'object' || value === null) {\n return undefined\n }\n value = (value as Record<PropertyKey, unknown>)[keyOf(part)]\n }\n return value\n}\n\nfunction mayContainValue(message: string, loaded: unknown, path: Path): boolean {\n const text = message.toLowerCase()\n const value = valueAt(loaded, path)\n if (typeof value === 'object' && value !== null) {\n return [...texts(value)].some(\n (part) => part.length >= TELLING && tells(text, part, TELLING_OF_MANY),\n )\n }\n if (value !== undefined) {\n return [...texts(value)].some((whole) => tells(text, whole, TELLING))\n }\n // Nothing is there, unless the schema moved what it validates. A word such as\n // `production` may well be in a message by itself.\n return [...texts(loaded)].some(\n (part) =>\n part.length >= TELLING && !/^[a-z]+$/i.test(part) && tells(text, part, TELLING_OF_MANY),\n )\n}\n\n/**\n * Says what is wrong with a configuration, without a value of it. Some schema\n * libraries put the value that they refuse into the message.\n */\nexport function describeIssue(\n { path = [], message }: StandardSchemaIssue,\n loaded: unknown,\n): string {\n const at = path.map((part) => String(keyOf(part))).join('.')\n let isTold = false\n try {\n isTold = !mayContainValue(message, loaded, path)\n } catch {\n // What cannot be looked at cannot be told from the message either.\n }\n if (!isTold) {\n const subject = at === '' ? 'The configuration' : at\n return `${subject} is invalid. What the schema says about it may contain the value.`\n }\n return at === '' ? message : `${at}: ${message}`\n}\n","import { InjectionToken, registerProvider } from '@navios/di'\n\nimport type { InferOutput, StandardSchemaV1 } from '@navios/di'\n\nimport { validateNow } from '../internal/validate-now.mjs'\n\nimport { ConfigService } from './config-service.mjs'\nimport { describeIssue } from './describe-issue.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ConfigProviderOptions<ConfigMap extends object> {\n /** Names the token, for errors. @default 'Config' */\n name?: string\n /** Loads the raw configuration. */\n load: () => ConfigMap | Promise<ConfigMap>\n}\n\nexport interface ValidatedConfigProviderOptions<Schema extends StandardSchemaV1> {\n /** Names the token, for errors. @default 'Config' */\n name?: string\n /** Loads the raw configuration. */\n load: () => unknown\n /**\n * Validates what `load` returned and types the service. Must validate\n * synchronously.\n */\n schema: Schema\n}\n\n/**\n * The configuration to use, out of what was loaded. Its errors say what is\n * wrong and carry no value: they end up in logs, and a configuration holds\n * secrets.\n */\nfunction checked(name: string, schema: StandardSchemaV1 | undefined, loaded: unknown): object {\n let config = loaded\n if (schema) {\n const result = validateNow(\n schema,\n loaded,\n `[Navios] The schema of the configuration ${name} must validate synchronously.`,\n )\n if (result.issues) {\n throw new Error(\n `[Navios] Invalid configuration ${name}: ` +\n result.issues.map((issue) => describeIssue(issue, loaded)).join('; '),\n )\n }\n config = result.value\n }\n if (typeof config !== 'object' || config === null || Array.isArray(config)) {\n throw new Error(`[Navios] The configuration ${name} must be an object.`)\n }\n return config\n}\n\n/**\n * Creates the token of a `ConfigService` whose content comes from `load`,\n * called once per container. With a `schema`, the loaded value is validated\n * and the service is typed from the schema's output.\n */\nexport function provideConfig<Schema extends StandardSchemaV1<any, object>>(\n options: ValidatedConfigProviderOptions<Schema>,\n): InjectionToken<ConfigService<InferOutput<Schema>>, undefined>\nexport function provideConfig<ConfigMap extends object>(\n options: ConfigProviderOptions<ConfigMap>,\n): InjectionToken<ConfigService<ConfigMap>, undefined>\nexport function provideConfig(options: {\n name?: string\n load: () => unknown\n schema?: StandardSchemaV1\n}): InjectionToken<ConfigService<any>, undefined> {\n const name = options.name ?? 'Config'\n const serve = (loaded: unknown) => new ConfigService(checked(name, options.schema, loaded))\n const token = InjectionToken.create<ConfigService<any>>(name)\n registerProvider(token, {\n factory: () => {\n // A configuration that is there at once can be used synchronously.\n const loaded = options.load() as PromiseLike<unknown> | null | undefined\n return typeof loaded?.then === 'function'\n ? Promise.resolve(loaded).then(serve)\n : serve(loaded)\n },\n })\n return token\n}\n","import { env } from 'node:process'\n\nimport type { InjectionToken } from '@navios/di'\n\nimport { provideConfig } from './provide-config.mjs'\n\nimport type { ConfigService } from './config-service.mjs'\n\n/**\n * A `ConfigService` holding a snapshot of `process.env`, taken when a\n * container first resolves it.\n */\nexport const EnvConfigProvider: InjectionToken<\n ConfigService<Record<string, string | undefined>>,\n undefined\n> = provideConfig<Record<string, string | undefined>>({\n name: 'EnvConfig',\n load: () => ({ ...env }),\n})\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * A typed slot in an execution context. Something sets it (usually a guard),\n * and reading it before that throws.\n *\n * ```ts\n * export const CurrentUser = createContextKey<User>('CurrentUser')\n * ```\n */\nexport class PlainContextKey<T> {\n declare readonly __type: T\n\n constructor(public readonly name: string) {}\n\n toString(): string {\n return this.name\n }\n}\n\nexport function createContextKey<T>(name: string): PlainContextKey<T> {\n return new PlainContextKey<T>(name)\n}\n\n/** A key every transport's context accepts. */\nexport type ContextKey<T = any> = PlainContextKey<T>\n\n/**\n * The type `ctx.get(key)` returns: a plain key's type, or, for a key that is\n * a class whose instances compute the value with `resolve`, what `resolve`\n * returns (a promise when it returns a thenable). A transport decides whether\n * it accepts such classes as keys.\n */\nexport type ContextValue<K> =\n K extends PlainContextKey<infer T>\n ? T\n : K extends new () => { resolve(ctx: any): infer R }\n ? ResolvedValue<R>\n : never\n\ntype ResolvedValue<R> = R extends Promise<any> ? R : R extends PromiseLike<infer T> ? Promise<T> : R\n","import type { ClassType, Container } from '@navios/di'\n\nimport type { InterceptorClass } from '../interceptors/interceptor.mjs'\nimport type { OptionsArgument } from '../internal/options-argument.mjs'\nimport type { Transport, TransportFactory } from '../transports/transport.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * What a plugin can do. Everything but `transport()` and `container` belongs\n * into `setup`: afterwards it throws, because it could not take effect.\n * `provide` and `decorate` apply at once, the rest at its point of `init()`.\n */\nexport interface PluginApi {\n readonly container: Container\n /**\n * Supplies a provider. It wins over the providers of modules and over the\n * default of the token. What the application itself provides, with its\n * `providers` option or in its container, stays.\n */\n readonly provide: Container['provide']\n /** Wraps every instance of a service after it is built. */\n readonly decorate: Container['decorate']\n /** Adds an interceptor around every handler, on every transport. */\n intercept(interceptor: InterceptorClass): void\n /**\n * Adds a module, and so its handlers, to the application. What it provides\n * is a default: the modules of the application override it.\n */\n addModule(module: ClassType): void\n /**\n * One of the application's transports, already created, or `undefined`\n * when the application has none of this kind. What only one transport\n * offers is reached through it.\n */\n transport<T extends Transport>(\n factory: TransportFactory<any, T>,\n instanceName?: string,\n ): T | undefined\n /** Runs after every transport is set up and before any starts. */\n onBootstrap(hook: () => void | Promise<void>): void\n /** Runs when the application closes, in reverse registration order. */\n onShutdown(hook: (signal?: string) => void | Promise<void>): void\n}\n\nexport interface PluginDefinition<Options = void> {\n /**\n * Unique name. One plugin registered twice with equal options is applied\n * once; anything else under one name is an error.\n */\n name: string\n /** Names of plugins that must be set up before this one. */\n dependsOn?: string[]\n setup(api: PluginApi, options: Options): void | Promise<void>\n}\n\nexport interface PluginInstance {\n readonly definition: PluginDefinition<any>\n /** `{}` when the plugin was given none. */\n readonly options: unknown\n}\n\n/**\n * Defines a plugin.\n *\n * ```ts\n * export const tracing = definePlugin({\n * name: 'tracing',\n * setup(api, options: { serviceName: string }) {\n * api.intercept(TracingInterceptor)\n * api.onShutdown(() => flush())\n * },\n * })\n *\n * app.usePlugin(tracing({ serviceName: 'api' }))\n * ```\n */\nexport function definePlugin<Options = void>(\n definition: PluginDefinition<Options>,\n): (...options: OptionsArgument<Options>) => P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