logixia 1.8.2 → 1.8.3

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 (54) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{index-CthBT3t8.d.mts → index-BFUPvkkQ.d.mts} +12 -1
  3. package/dist/index-BFUPvkkQ.d.mts.map +1 -0
  4. package/dist/{index-ClPZrfIU.d.ts → index-DknhKCCg.d.ts} +12 -1
  5. package/dist/index-DknhKCCg.d.ts.map +1 -0
  6. package/dist/index.d.mts +54 -15
  7. package/dist/index.d.mts.map +1 -1
  8. package/dist/index.d.ts +54 -15
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +54 -24
  11. package/dist/index.js.map +1 -1
  12. package/dist/index.mjs +54 -23
  13. package/dist/index.mjs.map +1 -1
  14. package/dist/{logitron-logger.module-Fof9Er2E.js → logitron-logger.module-B-sUxEiz.js} +159 -33
  15. package/dist/logitron-logger.module-B-sUxEiz.js.map +1 -0
  16. package/dist/{logitron-logger.module-DucvDnxZ.mjs → logitron-logger.module-B0A-mnc7.mjs} +154 -34
  17. package/dist/logitron-logger.module-B0A-mnc7.mjs.map +1 -0
  18. package/dist/{logitron-logger.module-Dx2mUz-g.d.ts → logitron-logger.module-BcxoyFoO.d.ts} +99 -7
  19. package/dist/logitron-logger.module-BcxoyFoO.d.ts.map +1 -0
  20. package/dist/{logitron-logger.module-KU_L04y1.d.mts → logitron-logger.module-HaMh8Nh7.d.mts} +99 -7
  21. package/dist/logitron-logger.module-HaMh8Nh7.d.mts.map +1 -0
  22. package/dist/middleware.d.mts +1 -1
  23. package/dist/middleware.d.ts +1 -1
  24. package/dist/nest.d.mts +4 -44
  25. package/dist/nest.d.mts.map +1 -1
  26. package/dist/nest.d.ts +4 -44
  27. package/dist/nest.d.ts.map +1 -1
  28. package/dist/nest.js +3 -93
  29. package/dist/nest.mjs +3 -92
  30. package/dist/{promise-BrZcjavs.mjs → promise-B4HzEg1I.mjs} +413 -261
  31. package/dist/promise-B4HzEg1I.mjs.map +1 -0
  32. package/dist/{promise-BI-3eI4n.js → promise-FtXoEiT6.js} +413 -261
  33. package/dist/promise-FtXoEiT6.js.map +1 -0
  34. package/dist/testing.d.mts +1 -1
  35. package/dist/testing.d.ts +1 -1
  36. package/dist/{transport.manager-DU1W0wV3.js → transport.manager-CqPyddCV.js} +2 -2
  37. package/dist/{transport.manager-DU1W0wV3.js.map → transport.manager-CqPyddCV.js.map} +1 -1
  38. package/dist/{transport.manager-BCnLEmOy.mjs → transport.manager-DMdotLoQ.mjs} +2 -2
  39. package/dist/{transport.manager-BCnLEmOy.mjs.map → transport.manager-DMdotLoQ.mjs.map} +1 -1
  40. package/dist/transports.d.mts +1 -1
  41. package/dist/transports.d.ts +1 -1
  42. package/dist/transports.js +1 -1
  43. package/dist/transports.mjs +1 -1
  44. package/package.json +2 -1
  45. package/dist/index-ClPZrfIU.d.ts.map +0 -1
  46. package/dist/index-CthBT3t8.d.mts.map +0 -1
  47. package/dist/logitron-logger.module-DucvDnxZ.mjs.map +0 -1
  48. package/dist/logitron-logger.module-Dx2mUz-g.d.ts.map +0 -1
  49. package/dist/logitron-logger.module-Fof9Er2E.js.map +0 -1
  50. package/dist/logitron-logger.module-KU_L04y1.d.mts.map +0 -1
  51. package/dist/nest.js.map +0 -1
  52. package/dist/nest.mjs.map +0 -1
  53. package/dist/promise-BI-3eI4n.js.map +0 -1
  54. package/dist/promise-BrZcjavs.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,7 +1,6 @@
1
- import { A as disableOtelBridge, B as PluginRegistry, C as traceStorage, D as resetShutdownHandlers, E as registerForShutdown, F as normalizeError, G as createFastifyContextHook, H as usePlugin, I as serializeError, L as DEFAULT_LOG_COLORS, M as getOtelMetaFields, N as initOtelBridge, O as applyRedaction, P as isError, R as DEFAULT_LOG_LEVELS, S as setTraceId, T as flushOnExit, U as LogixiaContext, V as globalPluginRegistry, W as createExpressContextMiddleware, _ as createTraceMiddleware, b as getTraceContextKey, c as LogixiaLoggerService, d as LogixiaLogger, f as createLogger$1, g as _setActiveContextKey, h as TraceContext, i as WebSocketTraceInterceptor, j as getActiveOtelContext, k as redactObject, l as __decorate, m as TRACE_CONTEXT_KEY, n as LOGIXIA_LOGGER_PREFIX, o as __decorateParam, p as DEFAULT_TRACE_HEADERS, r as LogixiaLoggerModule, s as KafkaTraceInterceptor, t as LOGIXIA_LOGGER_CONFIG, u as __decorateMetadata, v as extractTraceId, w as deregisterFromShutdown, x as runWithTraceId, y as getCurrentTraceId, z as LogLevel } from "./logitron-logger.module-DucvDnxZ.mjs";
2
- import { f as internalWarn } from "./transport.manager-BCnLEmOy.mjs";
1
+ import { A as redactObject, B as LogLevel, C as setTraceId, D as registerForShutdown, E as flushOnExit, F as isError, G as createExpressContextMiddleware, H as globalPluginRegistry, I as normalizeError, K as createFastifyContextHook, L as serializeError, M as getActiveOtelContext, N as getOtelMetaFields, O as resetShutdownHandlers, P as initOtelBridge, R as DEFAULT_LOG_COLORS, S as runWithTraceId, T as deregisterFromShutdown, U as usePlugin, V as PluginRegistry, W as LogixiaContext, _ as _setActiveContextKey, b as getCurrentTraceId, c as KafkaTraceInterceptor, d as __decorateMetadata, f as LogixiaLogger, g as TraceContext, h as TRACE_CONTEXT_KEY, i as WebSocketTraceInterceptor, j as disableOtelBridge, k as applyRedaction, l as LogixiaLoggerService, m as DEFAULT_TRACE_HEADERS, n as LOGIXIA_LOGGER_PREFIX, o as resolveResponseHeader, p as createLogger$1, r as LogixiaLoggerModule, s as __decorateParam, t as LOGIXIA_LOGGER_CONFIG, u as __decorate, v as createTraceMiddleware, w as traceStorage, x as getTraceContextKey, y as extractTraceId, z as DEFAULT_LOG_LEVELS } from "./logitron-logger.module-B0A-mnc7.mjs";
2
+ import { f as internalWarn } from "./transport.manager-DMdotLoQ.mjs";
3
3
  import "./search-1txemGPh.mjs";
4
- import { randomUUID } from "node:crypto";
5
4
  import { Catch, Inject, Optional } from "@nestjs/common";
6
5
 
7
6
  //#region src/exceptions/exception.ts
@@ -39,13 +38,16 @@ function isLogixiaException(value) {
39
38
  //#endregion
40
39
  //#region src/exceptions/builder.ts
41
40
  /**
42
- * Generates a trace ID using Node's built-in `crypto.randomUUID`.
43
- * No extra dependencies required.
41
+ * Generates a trace ID via the shared {@link TraceContext} generator.
42
+ *
43
+ * Delegates to `TraceContext.instance.generate()` so any custom generator
44
+ * configured on `TraceIdConfig.generator` is respected — avoids the silent
45
+ * "builder has its own UUID source" divergence this module had previously.
44
46
  *
45
47
  * @example `'550e8400-e29b-41d4-a716-446655440000'`
46
48
  */
47
49
  function generateTraceId() {
48
- return randomUUID();
50
+ return TraceContext.instance.generate();
49
51
  }
50
52
  /** @deprecated Use `generateTraceId` instead. */
51
53
  const generateRequestId = generateTraceId;
@@ -99,24 +101,34 @@ var ErrorResponseBuilder = class {
99
101
  * @param params - See `BuildParams`.
100
102
  * @returns The unified error response and the HTTP status code to send.
101
103
  *
104
+ * @remarks
105
+ * `traceId` does not need to be supplied by the caller in most cases — the
106
+ * builder reads `TraceContext.instance.getCurrentTraceId()` internally and
107
+ * falls back to the explicit `traceId` argument only when AsyncLocalStorage
108
+ * is empty. If neither source yields a value, `meta.trace_id` is omitted.
109
+ *
102
110
  * @example In a NestJS exception filter
103
111
  * ```ts
104
112
  * const { response, httpStatus } = ErrorResponseBuilder.build<AppCode, AppType>({
105
113
  * exception,
106
- * traceId: request.headers['x-trace-id'] as string | undefined,
114
+ * // Omit traceId it will be picked up from ALS automatically.
107
115
  * path: request.url,
108
116
  * service: process.env.SERVICE_NAME,
109
117
  * startTime: request.startTime,
110
118
  * });
111
119
  *
112
120
  * if (process.env.NODE_ENV === 'production') delete response.debug;
113
- * response.setHeader('X-Trace-ID', response.meta.trace_id);
121
+ * // Echo the resolved traceId back on whatever header your TraceIdConfig says —
122
+ * // do NOT hardcode 'X-Trace-Id', use `resolveResponseHeader(config)` instead.
123
+ * if (response.meta.trace_id) {
124
+ * response.setHeader(resolveResponseHeader(config) ?? 'X-Trace-Id', response.meta.trace_id);
125
+ * }
114
126
  * response.status(httpStatus).json(response);
115
127
  * ```
116
128
  */
117
129
  static build(params) {
118
130
  const { exception, path, service, startTime, traceId: rawTraceId } = params;
119
- const traceId = rawTraceId ?? generateTraceId();
131
+ const traceId = TraceContext.instance.getCurrentTraceId() ?? rawTraceId;
120
132
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
121
133
  const durationMs = startTime !== void 0 ? Date.now() - startTime : void 0;
122
134
  if (isLogixiaException(exception)) {
@@ -134,7 +146,7 @@ var ErrorResponseBuilder = class {
134
146
  success: false,
135
147
  error: errorBlock,
136
148
  meta: {
137
- trace_id: traceId,
149
+ ...traceId !== void 0 ? { trace_id: traceId } : {},
138
150
  timestamp,
139
151
  path,
140
152
  status: exception.httpStatus
@@ -165,7 +177,7 @@ var ErrorResponseBuilder = class {
165
177
  message
166
178
  },
167
179
  meta: {
168
- trace_id: traceId,
180
+ ...traceId !== void 0 ? { trace_id: traceId } : {},
169
181
  timestamp,
170
182
  path,
171
183
  status
@@ -185,7 +197,7 @@ var ErrorResponseBuilder = class {
185
197
  message: "An unexpected error occurred."
186
198
  },
187
199
  meta: {
188
- trace_id: traceId,
200
+ ...traceId !== void 0 ? { trace_id: traceId } : {},
189
201
  timestamp,
190
202
  path,
191
203
  status: 500
@@ -199,6 +211,7 @@ var ErrorResponseBuilder = class {
199
211
 
200
212
  //#endregion
201
213
  //#region src/core/nestjs-extras.ts
214
+ var _ref;
202
215
  /**
203
216
  * Inject the Logixia logger registered in the current NestJS DI container.
204
217
  *
@@ -242,9 +255,12 @@ function LogMethod(options = {}) {
242
255
  const start = Date.now();
243
256
  const entry = { method: label };
244
257
  if (logArgs && args.length > 0) entry["args"] = args;
258
+ const reportLogFailure = (phase, err) => {
259
+ process.stderr.write(`[logixia] @LogMethod(${label}) ${phase} log failed: ${String(err)}\n`);
260
+ };
245
261
  if (logger$1) {
246
262
  const logFnRaw = logger$1[level];
247
- await (typeof logFnRaw === "function" ? logFnRaw : logger$1.debug).bind(logger$1)(`→ ${label}`, entry).catch(() => void 0);
263
+ await (typeof logFnRaw === "function" ? logFnRaw : logger$1.debug).bind(logger$1)(`→ ${label}`, entry).catch((e) => reportLogFailure("entry", e));
248
264
  }
249
265
  try {
250
266
  const result = await originalMethod.apply(this, args);
@@ -255,13 +271,17 @@ function LogMethod(options = {}) {
255
271
  if (logResult) exit["result"] = result;
256
272
  if (logger$1) {
257
273
  const logFnRaw = logger$1[level];
258
- await (typeof logFnRaw === "function" ? logFnRaw : logger$1.debug).bind(logger$1)(`← ${label}`, exit).catch(() => void 0);
274
+ await (typeof logFnRaw === "function" ? logFnRaw : logger$1.debug).bind(logger$1)(`← ${label}`, exit).catch((e) => reportLogFailure("exit", e));
259
275
  }
260
276
  return result;
261
277
  } catch (error) {
262
278
  if (logger$1 && logErrors) {
263
279
  const err = error instanceof Error ? error : new Error(String(error));
264
- logger$1.error(err, `${label} durationMs=${Date.now() - start}`);
280
+ const errLog = logger$1.error(err, {
281
+ method: label,
282
+ durationMs: Date.now() - start
283
+ });
284
+ if (errLog !== void 0 && errLog !== null && typeof errLog.catch === "function") errLog.catch((e) => reportLogFailure("error", e));
265
285
  }
266
286
  throw error;
267
287
  }
@@ -270,15 +290,16 @@ function LogMethod(options = {}) {
270
290
  };
271
291
  }
272
292
  let LogixiaExceptionFilter = class LogixiaExceptionFilter$1 {
273
- constructor(logger$1) {
293
+ constructor(logger$1, loggerConfig) {
274
294
  this._logger = logger$1 ?? LogixiaLoggerModule._globalLogger ?? void 0;
295
+ this._traceConfig = typeof (loggerConfig === null || loggerConfig === void 0 ? void 0 : loggerConfig.traceId) === "object" ? loggerConfig.traceId : void 0;
275
296
  }
276
297
  catch(exception, host) {
277
298
  var _request$headers;
278
299
  const ctx = host.switchToHttp();
279
300
  const request = ctx.getRequest();
280
301
  const response = ctx.getResponse();
281
- const traceId = ((_request$headers = request.headers) === null || _request$headers === void 0 ? void 0 : _request$headers["x-trace-id"]) ?? request.id ?? void 0;
302
+ const traceId = TraceContext.instance.getCurrentTraceId() ?? ((_request$headers = request.headers) === null || _request$headers === void 0 ? void 0 : _request$headers["x-trace-id"]) ?? request.id ?? void 0;
282
303
  const { response: errorResponse, httpStatus } = ErrorResponseBuilder.build({
283
304
  exception,
284
305
  traceId,
@@ -290,16 +311,24 @@ let LogixiaExceptionFilter = class LogixiaExceptionFilter$1 {
290
311
  method: request.method ?? "",
291
312
  url: request.url ?? "",
292
313
  status: httpStatus,
293
- trace_id: errorResponse.meta.trace_id
314
+ ...errorResponse.meta.trace_id !== void 0 ? { trace_id: errorResponse.meta.trace_id } : {}
315
+ };
316
+ const onLogFailure = (err) => {
317
+ process.stderr.write(`[logixia] ExceptionFilter failed to write log entry: ${String(err)}\n`);
294
318
  };
319
+ let logPromise;
295
320
  if (httpStatus >= 500) {
296
321
  const err = exception instanceof Error ? exception : new Error(String(exception));
297
- this._logger.error(err, requestMeta);
298
- } else if (isLogixiaException(exception)) this._logger.warn(`[${errorResponse.error.code}] ${errorResponse.error.message}`, requestMeta);
299
- else this._logger.warn(`[${httpStatus}] ${errorResponse.error.message}`, requestMeta);
322
+ logPromise = this._logger.error(err, requestMeta);
323
+ } else if (isLogixiaException(exception)) logPromise = this._logger.warn(`[${errorResponse.error.code}] ${errorResponse.error.message}`, requestMeta);
324
+ else logPromise = this._logger.warn(`[${httpStatus}] ${errorResponse.error.message}`, requestMeta);
325
+ if (logPromise && typeof logPromise.catch === "function") logPromise.catch(onLogFailure);
300
326
  }
301
327
  if (process.env["NODE_ENV"] === "production") delete errorResponse.debug;
302
- response.setHeader("X-Trace-ID", errorResponse.meta.trace_id);
328
+ if (errorResponse.meta.trace_id) {
329
+ const traceHeader = resolveResponseHeader(this._traceConfig);
330
+ if (traceHeader) response.setHeader(traceHeader, errorResponse.meta.trace_id);
331
+ }
303
332
  if (httpStatus === 429) response.setHeader("Retry-After", "60");
304
333
  response.status(httpStatus).json(errorResponse);
305
334
  }
@@ -308,7 +337,9 @@ LogixiaExceptionFilter = __decorate([
308
337
  Catch(),
309
338
  __decorateParam(0, Optional()),
310
339
  __decorateParam(0, Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`)),
311
- __decorateMetadata("design:paramtypes", [Object])
340
+ __decorateParam(1, Optional()),
341
+ __decorateParam(1, Inject(LOGIXIA_LOGGER_CONFIG)),
342
+ __decorateMetadata("design:paramtypes", [Object, typeof (_ref = typeof Partial !== "undefined" && Partial) === "function" ? _ref : Object])
312
343
  ], LogixiaExceptionFilter);
313
344
 
314
345
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["cause: string | undefined","debug","errorBlock: LogixiaErrorResponse<TCode, TType>['error']","message: string","logger: LogixiaLoggerService | undefined","logger","entry: Record<string, unknown>","exit: Record<string, unknown>","LogixiaExceptionFilter","logger?: LogixiaLoggerService","requestMeta: Record<string, unknown>","formatted: Record<string, unknown>","serialized: Record<string, unknown>","parts: string[]","warnings: string[]","logger","DEFAULT_BUCKETS: readonly number[]","pairs: Record<string, string>","lines: string[]","createLoggerFromCore"],"sources":["../src/exceptions/exception.ts","../src/exceptions/builder.ts","../src/core/nestjs-extras.ts","../src/formatters/json.formatter.ts","../src/formatters/text.formatter.ts","../src/utils/typed-logger.ts","../src/metrics.ts","../src/index.ts"],"sourcesContent":["/**\n * LogixiaException — a strictly typed, framework-agnostic exception class.\n *\n * You bring your own error codes and types; logixia enforces the shape.\n * The `ErrorResponseBuilder` knows how to turn a `LogixiaException` into the\n * standard `LogixiaErrorResponse` wire format.\n *\n * @template TCode - Your error code union. e.g. `'PE-AUTH-001' | 'PE-USR-001'`\n * @template TType - Your error type union. e.g. `'authentication_error' | 'validation_error'`\n *\n * @example Basic throw\n * ```ts\n * throw new LogixiaException({\n * code: 'PE-AUTH-001',\n * type: 'authentication_error',\n * httpStatus: 401,\n * message: 'Invalid email or password.',\n * });\n * ```\n *\n * @example Fully typed with your own code/type unions\n * ```ts\n * type AppCode = 'PE-AUTH-001' | 'PE-VAL-001';\n * type AppType = 'authentication_error' | 'validation_error';\n *\n * throw new LogixiaException<AppCode, AppType>({\n * code: 'PE-VAL-001',\n * type: 'validation_error',\n * httpStatus: 400,\n * message: 'Validation failed.',\n * details: [\n * { field: 'email', message: 'must be a valid email', code: 'invalid_format' },\n * ],\n * });\n * ```\n *\n * @example With field pointer (Stripe param pattern)\n * ```ts\n * throw new LogixiaException({\n * code: 'PE-USR-002',\n * type: 'conflict_error',\n * httpStatus: 409,\n * message: 'This email is already in use.',\n * param: 'email',\n * });\n * ```\n *\n * @example With cause chain (ES 2022)\n * ```ts\n * try {\n * await db.save(user);\n * } catch (err) {\n * throw new LogixiaException({\n * code: 'PE-DB-001',\n * type: 'server_error',\n * httpStatus: 409,\n * message: 'Duplicate record.',\n * cause: err instanceof Error ? err : undefined,\n * });\n * }\n * ```\n */\n\nimport type { ErrorDetail } from './types.js';\n\n// ── Options ───────────────────────────────────────────────────────────────────\n\n/**\n * Constructor options for `LogixiaException`.\n *\n * All user-supplied fields — logixia only owns the wire format.\n */\nexport interface LogixiaExceptionOptions<\n TCode extends string = string,\n TType extends string = string,\n> {\n /**\n * Machine-readable, stable error code.\n * e.g. `'PE-AUTH-001'`\n */\n code: TCode;\n\n /**\n * Broad error type category.\n * e.g. `'authentication_error'` | `'validation_error'` | `'rate_limit_error'`\n */\n type: TType;\n\n /**\n * HTTP status code to send on the wire.\n * e.g. `401` | `400` | `429` | `500`\n */\n httpStatus: number;\n\n /**\n * Human-readable message for the end-user.\n * This IS sent in the response body — keep it safe (no internal paths, etc.).\n */\n message: string;\n\n /**\n * The specific request field that caused this error (Stripe pattern).\n * e.g. `'email'` | `'metadata.name'`\n */\n param?: string;\n\n /**\n * Array of per-field validation errors (GitHub pattern).\n * Typically used for `400` / `422` validation failures.\n */\n details?: ErrorDetail[];\n\n /**\n * Documentation URL for this error (Twilio pattern).\n * e.g. `'https://docs.example.com/errors/PE-AUTH-001'`\n */\n docUrl?: string;\n\n /**\n * Original error for ES 2022 cause chaining.\n * Serialised into `debug.cause` by the `ErrorResponseBuilder`.\n * Never sent to the client in production.\n */\n cause?: Error;\n\n /**\n * Arbitrary metadata for logging purposes only.\n * This is **never** included in the HTTP response — it is passed to your\n * logger / monitoring integrations through the exception object.\n *\n * @example\n * ```ts\n * metadata: { userId: 'u_abc', attemptCount: 3 }\n * ```\n */\n metadata?: Record<string, unknown>;\n}\n\n// ── Exception class ───────────────────────────────────────────────────────────\n\nexport class LogixiaException<\n TCode extends string = string,\n TType extends string = string,\n> extends Error {\n /** @readonly The machine-readable error code supplied by the caller. */\n public readonly errorCode: TCode;\n /** @readonly The error type category supplied by the caller. */\n public readonly errorType: TType;\n /** @readonly HTTP status code to respond with. */\n public readonly httpStatus: number;\n /** @readonly Field pointer that caused this error (Stripe pattern). */\n public readonly param: string | undefined;\n /** @readonly Field-level validation errors (GitHub pattern). */\n public readonly details: ErrorDetail[] | undefined;\n /** @readonly Documentation URL for this error (Twilio pattern). */\n public readonly docUrl: string | undefined;\n /**\n * @readonly Extra context for your logger — never serialised into the HTTP response.\n */\n public readonly metadata: Record<string, unknown> | undefined;\n\n constructor(options: LogixiaExceptionOptions<TCode, TType>) {\n // Pass `cause` through the standard ES 2022 Error options so native\n // tooling (Node.js, Sentry, etc.) can walk the full error chain.\n super(options.message, { cause: options.cause });\n\n this.name = 'LogixiaException';\n this.errorCode = options.code;\n this.errorType = options.type;\n this.httpStatus = options.httpStatus;\n this.param = options.param;\n this.details = options.details;\n this.docUrl = options.docUrl;\n this.metadata = options.metadata;\n\n // Restore the correct prototype chain when compiling to ES5.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n// ── Type guard ────────────────────────────────────────────────────────────────\n\n/**\n * Returns `true` when `value` is a `LogixiaException` instance.\n *\n * Useful in exception filters or middleware that need to distinguish a\n * `LogixiaException` from a plain `Error` or a framework `HttpException`.\n *\n * @example\n * ```ts\n * if (isLogixiaException(err)) {\n * console.log(err.errorCode, err.httpStatus);\n * }\n * ```\n */\nexport function isLogixiaException<TCode extends string = string, TType extends string = string>(\n value?: unknown\n): value is LogixiaException<TCode, TType> {\n return value instanceof LogixiaException;\n}\n","/**\n * ErrorResponseBuilder — turns any exception into a `LogixiaErrorResponse`.\n *\n * Priority order:\n * 1. `LogixiaException` — typed fields used directly\n * 2. NestJS `HttpException` — duck-typed; status + message extracted\n * 3. Plain `Error` / unknown — falls back to 500 `server_error`\n *\n * The builder **always** populates `debug` when possible.\n * Your exception filter is responsible for stripping it in production:\n * ```ts\n * if (process.env.NODE_ENV === 'production') delete response.debug;\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\n\nimport { isLogixiaException } from './exception.js';\nimport type { LogixiaErrorResponse } from './types.js';\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\n/** Input parameters for `ErrorResponseBuilder.build`. */\nexport interface BuildParams {\n /** The caught exception — any type. */\n exception: unknown;\n /**\n * Trace ID to embed in `meta.trace_id`.\n * If omitted a UUID-based ID is auto-generated.\n */\n traceId?: string | undefined;\n /** Request path. e.g. `'/api/v1/auth/login'` */\n path: string;\n /**\n * Originating service name for `debug.service`.\n * e.g. `process.env.SERVICE_NAME` → `'gatekeeper'`\n */\n service?: string | undefined;\n /**\n * `Date.now()` captured at the start of the request.\n * When present, `debug.duration_ms` is computed automatically.\n */\n startTime?: number | undefined;\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Generates a trace ID using Node's built-in `crypto.randomUUID`.\n * No extra dependencies required.\n *\n * @example `'550e8400-e29b-41d4-a716-446655440000'`\n */\nexport function generateTraceId(): string {\n return randomUUID();\n}\n\n/** @deprecated Use `generateTraceId` instead. */\nexport const generateRequestId = generateTraceId;\n\n/**\n * Maps an HTTP status code to a human-friendly error type string.\n * Used as a fallback when the exception is a generic `HttpException`.\n */\nfunction httpStatusToType(status: number): string {\n if (status === 400) return 'api_error';\n if (status === 401) return 'authentication_error';\n if (status === 402) return 'payment_error';\n if (status === 403) return 'authorization_error';\n if (status === 404) return 'not_found_error';\n if (status === 408) return 'timeout_error';\n if (status === 409) return 'conflict_error';\n if (status === 422) return 'validation_error';\n if (status === 429) return 'rate_limit_error';\n if (status >= 500) return 'server_error';\n if (status >= 400) return 'api_error';\n return 'server_error';\n}\n\n/**\n * Duck-type check for NestJS `HttpException`.\n * Avoids a hard import on `@nestjs/common` so the builder is usable outside NestJS.\n */\nfunction isHttpException(\n value: unknown\n): value is { getStatus(): number; getResponse(): unknown; message: string } {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Record<string, unknown>)['getStatus'] === 'function' &&\n typeof (value as Record<string, unknown>)['getResponse'] === 'function'\n );\n}\n\n/**\n * Builds the optional `debug` block from an error.\n * Returns `undefined` when there is nothing useful to include.\n */\nfunction buildDebug(\n error: unknown,\n service: string | undefined,\n durationMs: number | undefined\n): LogixiaErrorResponse['debug'] {\n const stack = error instanceof Error ? error.stack : undefined;\n\n const causeRaw =\n error instanceof Error ? (error as Error & { cause?: unknown }).cause : undefined;\n let cause: string | undefined;\n if (causeRaw instanceof Error) {\n cause = causeRaw.message;\n } else if (causeRaw !== undefined && causeRaw !== null) {\n cause = String(causeRaw);\n }\n\n if (!stack && !cause && !service && durationMs === undefined) return undefined;\n\n return {\n ...(stack !== undefined ? { stack } : {}),\n ...(cause !== undefined ? { cause } : {}),\n ...(service !== undefined ? { service } : {}),\n ...(durationMs !== undefined ? { duration_ms: durationMs } : {}),\n };\n}\n\n// ── Builder ───────────────────────────────────────────────────────────────────\n\nexport class ErrorResponseBuilder {\n /**\n * Build a `LogixiaErrorResponse` from any thrown value.\n *\n * @param params - See `BuildParams`.\n * @returns The unified error response and the HTTP status code to send.\n *\n * @example In a NestJS exception filter\n * ```ts\n * const { response, httpStatus } = ErrorResponseBuilder.build<AppCode, AppType>({\n * exception,\n * traceId: request.headers['x-trace-id'] as string | undefined,\n * path: request.url,\n * service: process.env.SERVICE_NAME,\n * startTime: request.startTime,\n * });\n *\n * if (process.env.NODE_ENV === 'production') delete response.debug;\n * response.setHeader('X-Trace-ID', response.meta.trace_id);\n * response.status(httpStatus).json(response);\n * ```\n */\n static build<TCode extends string = string, TType extends string = string>(\n params: BuildParams\n ): { response: LogixiaErrorResponse<TCode, TType>; httpStatus: number } {\n const { exception, path, service, startTime, traceId: rawTraceId } = params;\n const traceId = rawTraceId ?? generateTraceId();\n const timestamp = new Date().toISOString();\n const durationMs = startTime !== undefined ? Date.now() - startTime : undefined;\n\n // ── 1. LogixiaException ────────────────────────────────────────────────\n if (isLogixiaException<TCode, TType>(exception)) {\n const debug = buildDebug(exception, service, durationMs);\n\n const errorBlock: LogixiaErrorResponse<TCode, TType>['error'] = {\n type: exception.errorType,\n code: exception.errorCode,\n message: exception.message,\n };\n if (exception.param !== undefined) errorBlock.param = exception.param;\n if (exception.details !== undefined && exception.details.length > 0) {\n errorBlock.details = exception.details;\n }\n if (exception.docUrl !== undefined) errorBlock.doc_url = exception.docUrl;\n\n const response: LogixiaErrorResponse<TCode, TType> = {\n success: false,\n error: errorBlock,\n meta: {\n trace_id: traceId,\n timestamp,\n path,\n status: exception.httpStatus,\n },\n ...(debug !== undefined ? { debug } : {}),\n };\n\n return { response, httpStatus: exception.httpStatus };\n }\n\n // ── 2. NestJS HttpException (duck-typed) ──────────────────────────────\n if (isHttpException(exception)) {\n const status = exception.getStatus();\n const exResponse = exception.getResponse();\n\n // NestJS nests the message: { statusCode, message, error } or a plain string\n let message: string;\n if (typeof exResponse === 'string') {\n message = exResponse;\n } else if (typeof exResponse === 'object' && exResponse !== null && 'message' in exResponse) {\n const raw = (exResponse as { message: unknown }).message;\n message = Array.isArray(raw) ? raw.join(', ') : String(raw);\n } else {\n message = exception.message;\n }\n\n const type = httpStatusToType(status) as TType;\n const code = `HTTP_${status}` as TCode;\n const debug = buildDebug(exception, service, durationMs);\n\n const response: LogixiaErrorResponse<TCode, TType> = {\n success: false,\n error: { type, code, message },\n meta: { trace_id: traceId, timestamp, path, status },\n ...(debug !== undefined ? { debug } : {}),\n };\n\n return { response, httpStatus: status };\n }\n\n // ── 3. Unknown / plain Error ──────────────────────────────────────────\n const err = exception instanceof Error ? exception : new Error(String(exception));\n const debug = buildDebug(err, service, durationMs);\n\n const response: LogixiaErrorResponse<TCode, TType> = {\n success: false,\n error: {\n type: 'server_error' as TType,\n code: 'INTERNAL_SERVER_ERROR' as TCode,\n message: 'An unexpected error occurred.',\n },\n meta: { trace_id: traceId, timestamp, path, status: 500 },\n ...(debug !== undefined ? { debug } : {}),\n };\n\n return { response, httpStatus: 500 };\n }\n}\n","/**\n * logixia — NestJS extras: @InjectLogger, @LogMethod, LogixiaExceptionFilter\n *\n * Completes the NestJS deep integration story:\n * - @InjectLogger() — inject the logger via NestJS DI without typing LOGIXIA_TOKEN manually\n * - @LogMethod() — auto-log method entry / exit with args and return value\n * - LogixiaExceptionFilter — catch-all exception filter that logs unhandled errors\n * with full request context before re-throwing\n *\n * @example Full setup\n * ```ts\n * // app.module.ts\n * import { LogixiaModule } from 'logixia';\n * @Module({ imports: [LogixiaModule.forRoot({ appName: 'api' })] })\n * export class AppModule {}\n *\n * // order.service.ts\n * import { Injectable } from '@nestjs/common';\n * import { InjectLogger, LogMethod, LogixiaLoggerService } from 'logixia';\n *\n * @Injectable()\n * export class OrderService {\n * constructor(@InjectLogger() private readonly logger: LogixiaLoggerService) {}\n *\n * @LogMethod()\n * async createOrder(dto: CreateOrderDto) { … }\n * }\n *\n * // main.ts\n * import { LogixiaExceptionFilter } from 'logixia';\n * app.useGlobalFilters(new LogixiaExceptionFilter(logger));\n * ```\n */\n\nimport type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';\nimport { Catch, Inject, Optional } from '@nestjs/common';\n\nimport { ErrorResponseBuilder } from '../exceptions/builder';\nimport { isLogixiaException } from '../exceptions/exception';\nimport type { LogLevelString } from '../types';\nimport { LOGIXIA_LOGGER_PREFIX, LogixiaLoggerModule } from './logitron-logger.module';\nimport type { LogixiaLoggerService } from './logitron-nestjs.service';\n\n// ── @InjectLogger() ──────────────────────────────────────────────────────────\n\n/**\n * Inject the Logixia logger registered in the current NestJS DI container.\n *\n * Equivalent to `@Inject(LOGIXIA_LOGGER_TOKEN)` but without needing to import\n * the internal token constant yourself.\n *\n * @example\n * ```ts\n * constructor(@InjectLogger() private readonly logger: LogixiaLoggerService) {}\n * ```\n */\nexport const InjectLogger = (): ParameterDecorator => Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`);\n\n// ── @LogMethod() ─────────────────────────────────────────────────────────────\n\nexport interface LogMethodOptions {\n /**\n * Log level to use for entry / exit messages.\n * @default 'debug'\n */\n level?: LogLevelString;\n /**\n * Whether to log the arguments passed to the method.\n * Disable for high-throughput hot paths.\n * @default true\n */\n logArgs?: boolean;\n /**\n * Whether to log the return value of the method.\n * @default false\n */\n logResult?: boolean;\n /**\n * Whether to log error stack traces for thrown errors.\n * @default true\n */\n logErrors?: boolean;\n /**\n * Custom label used in log messages instead of the auto-detected class.method name.\n */\n label?: string;\n}\n\n/**\n * Method decorator that auto-logs entry, exit, duration, and errors.\n *\n * Works on both async and sync methods. Attaches to the logger found on the\n * class instance via a `logger` property (the conventional NestJS name).\n *\n * @example\n * ```ts\n * @LogMethod({ level: 'info', logArgs: true })\n * async processPayment(orderId: string): Promise<void> { … }\n * ```\n */\nexport function LogMethod(options: LogMethodOptions = {}): MethodDecorator {\n const { level = 'debug', logArgs = true, logResult = false, logErrors = true } = options;\n\n // Use PropertyDescriptor (not generic TypedPropertyDescriptor<T>) to avoid\n // strict generic inference issues with exactOptionalPropertyTypes.\n return function (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor\n ): PropertyDescriptor {\n const originalMethod = descriptor.value as ((...args: unknown[]) => unknown) | undefined;\n if (typeof originalMethod !== 'function') return descriptor;\n\n const methodName = String(propertyKey);\n const className =\n (target as { constructor?: { name?: string } }).constructor?.name ?? 'Unknown';\n const label = options.label ?? `${className}.${methodName}`;\n\n let _warnedNoLogger = false;\n\n descriptor.value = async function (\n this: { logger?: LogixiaLoggerService },\n ...args: unknown[]\n ) {\n // Prefer the instance's own logger; fall back to the global module logger.\n const logger: LogixiaLoggerService | undefined =\n this.logger ?? LogixiaLoggerModule._globalLogger ?? undefined;\n\n if (!logger && !_warnedNoLogger) {\n _warnedNoLogger = true;\n // eslint-disable-next-line no-console\n console.warn(\n `[logixia] @LogMethod on ${label}: no logger available. ` +\n `Either inject LogixiaLoggerService as this.logger or ensure LogixiaLoggerModule is initialised.`\n );\n }\n\n const start = Date.now();\n\n const entry: Record<string, unknown> = { method: label };\n if (logArgs && args.length > 0) {\n entry['args'] = args;\n }\n\n if (logger) {\n // Use logLevel (extended method) rather than the NestJS interface debug/info\n // which only accepts (message: unknown, context?: string)\n const logFnRaw = (\n logger as unknown as Record<\n string,\n (msg: string, data?: Record<string, unknown>) => Promise<void>\n >\n )[level];\n const logFn = (typeof logFnRaw === 'function' ? logFnRaw : logger.debug).bind(logger);\n await (logFn as (msg: string, data?: Record<string, unknown>) => Promise<void>)(\n `→ ${label}`,\n entry\n ).catch(() => void 0);\n }\n\n try {\n const result = await (originalMethod.apply(this, args) as Promise<unknown>);\n\n const exit: Record<string, unknown> = {\n method: label,\n durationMs: Date.now() - start,\n };\n if (logResult) exit['result'] = result;\n\n if (logger) {\n const logFnRaw = (\n logger as unknown as Record<\n string,\n (msg: string, data?: Record<string, unknown>) => Promise<void>\n >\n )[level];\n const logFn = (typeof logFnRaw === 'function' ? logFnRaw : logger.debug).bind(logger);\n await (logFn as (msg: string, data?: Record<string, unknown>) => Promise<void>)(\n `← ${label}`,\n exit\n ).catch(() => void 0);\n }\n\n return result;\n } catch (error) {\n if (logger && logErrors) {\n const err = error instanceof Error ? error : new Error(String(error));\n logger.error(err, `${label} durationMs=${Date.now() - start}`);\n }\n throw error;\n }\n };\n\n return descriptor;\n };\n}\n\n// ── LogixiaExceptionFilter ───────────────────────────────────────────────────\n\n/**\n * Global NestJS exception filter that converts any exception into the standard\n * `LogixiaErrorResponse` wire format and logs it with full request context.\n *\n * Handles three exception types in priority order:\n * 1. `LogixiaException` — typed fields used directly\n * 2. NestJS `HttpException` — status + message extracted\n * 3. Unknown / plain Error — falls back to 500 `server_error`\n *\n * **Debug stripping in production:**\n * The `debug` block is automatically stripped when `NODE_ENV === 'production'`.\n *\n * **Trace ID headers:**\n * `X-Trace-ID` and `X-Request-ID` are echoed back on every error response so\n * clients can correlate with server logs.\n *\n * **Retry-After header:**\n * Automatically added for `429` responses (`Retry-After: 60`).\n *\n * Register in `main.ts`:\n * ```ts\n * const logger = app.get(LogixiaLoggerService);\n * app.useGlobalFilters(new LogixiaExceptionFilter(logger));\n * ```\n */\n@Catch()\nexport class LogixiaExceptionFilter implements ExceptionFilter {\n private readonly _logger: LogixiaLoggerService | undefined;\n\n constructor(\n @Optional()\n @Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`)\n logger?: LogixiaLoggerService\n ) {\n // Prefer the injected logger; fall back to the global module logger so\n // `new LogixiaExceptionFilter()` (registered in main.ts before DI resolves)\n // still logs without needing an explicit logger argument.\n this._logger = logger ?? LogixiaLoggerModule._globalLogger ?? undefined;\n }\n\n catch(exception: unknown, host: ArgumentsHost): void {\n const ctx = host.switchToHttp();\n\n const request = ctx.getRequest<{\n method?: string;\n url?: string;\n id?: string;\n startTime?: number;\n headers?: Record<string, string | string[] | undefined>;\n }>();\n\n interface MinimalResponse {\n status(code: number): MinimalResponse;\n json(body: unknown): void;\n setHeader(name: string, value: string): void;\n }\n const response = ctx.getResponse<MinimalResponse>();\n\n // Prefer x-trace-id (set by TraceMiddleware) → request.id → auto-generate\n const traceId =\n (request.headers?.['x-trace-id'] as string | undefined) ?? request.id ?? undefined;\n\n const { response: errorResponse, httpStatus } = ErrorResponseBuilder.build({\n exception,\n traceId,\n path: request.url ?? '/',\n startTime: request.startTime,\n });\n\n // ── Logging ──────────────────────────────────────────────────────────────\n if (this._logger) {\n const requestMeta: Record<string, unknown> = {\n method: request.method ?? '',\n url: request.url ?? '',\n status: httpStatus,\n trace_id: errorResponse.meta.trace_id,\n };\n\n if (httpStatus >= 500) {\n const err = exception instanceof Error ? exception : new Error(String(exception));\n // fire-and-forget — cannot await inside a synchronous ExceptionFilter.catch\n this._logger.error(err, requestMeta);\n } else if (isLogixiaException(exception)) {\n this._logger.warn(\n `[${errorResponse.error.code}] ${errorResponse.error.message}`,\n requestMeta\n );\n } else {\n this._logger.warn(`[${httpStatus}] ${errorResponse.error.message}`, requestMeta);\n }\n }\n\n // ── Strip debug in production ─────────────────────────────────────────\n if (process.env['NODE_ENV'] === 'production') {\n delete errorResponse.debug;\n }\n\n // ── Response headers ──────────────────────────────────────────────────\n response.setHeader('X-Trace-ID', errorResponse.meta.trace_id);\n if (httpStatus === 429) {\n response.setHeader('Retry-After', '60');\n }\n\n response.status(httpStatus).json(errorResponse);\n }\n}\n","/**\n * JSON formatter for Logixia\n */\n\nimport type { ILogFormatter, LogEntry } from '../types';\nimport { serializeError } from '../utils/error.utils';\n\nexport class JsonFormatter implements ILogFormatter {\n private includeTimestamp: boolean;\n private includeLevel: boolean;\n private includeAppName: boolean;\n private includeTraceId: boolean;\n private includeContext: boolean;\n private prettyPrint: boolean;\n\n constructor(\n options: {\n includeTimestamp?: boolean;\n includeLevel?: boolean;\n includeAppName?: boolean;\n includeTraceId?: boolean;\n includeContext?: boolean;\n prettyPrint?: boolean;\n } = {}\n ) {\n this.includeTimestamp = options.includeTimestamp ?? true;\n this.includeLevel = options.includeLevel ?? true;\n this.includeAppName = options.includeAppName ?? true;\n this.includeTraceId = options.includeTraceId ?? true;\n this.includeContext = options.includeContext ?? true;\n this.prettyPrint = options.prettyPrint ?? false;\n }\n\n format(entry: LogEntry): string {\n const formatted: Record<string, unknown> = {};\n\n // Add timestamp\n if (this.includeTimestamp) {\n formatted.timestamp = entry.timestamp;\n }\n\n // Add log level\n if (this.includeLevel) {\n formatted.level = entry.level.toLowerCase();\n formatted.levelValue = entry.level;\n }\n\n // Add app name\n if (this.includeAppName) {\n formatted.appName = entry.appName;\n }\n\n // Add trace ID\n if (this.includeTraceId && entry.traceId) {\n formatted.traceId = entry.traceId;\n }\n\n // Add context\n if (this.includeContext && entry.context) {\n formatted.context = entry.context;\n }\n\n // Add message\n formatted.message = entry.message;\n\n // Add payload\n if (entry.payload && Object.keys(entry.payload).length > 0) {\n formatted.payload = this.serializePayload(entry.payload);\n }\n\n // Add error if present\n if (entry.error) {\n formatted.error = serializeError(entry.error);\n }\n\n // Add metadata\n formatted.meta = {\n pid: process.pid,\n hostname: process.env.HOSTNAME || 'unknown',\n version: process.version,\n };\n\n return this.prettyPrint ? JSON.stringify(formatted, null, 2) : JSON.stringify(formatted);\n }\n\n private serializePayload(payload: Record<string, unknown>): Record<string, unknown> {\n const serialized: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(payload)) {\n try {\n if (value instanceof Error) {\n serialized[key] = serializeError(value);\n } else if (value instanceof Date) {\n serialized[key] = value.toISOString();\n } else if (typeof value === 'function') {\n serialized[key] = '[Function]';\n } else if (typeof value === 'symbol') {\n serialized[key] = value.toString();\n } else if (value === undefined) {\n serialized[key] = null;\n } else {\n serialized[key] = value;\n }\n } catch {\n serialized[key] = '[Unserializable]';\n }\n }\n\n return serialized;\n }\n}\n","/**\n * Text formatter for Logixia\n */\n\nimport type { ILogFormatter, LogEntry } from '../types';\nimport { LogLevel } from '../types';\n\nexport class TextFormatter implements ILogFormatter {\n private colorize: boolean;\n private includeTimestamp: boolean;\n private includeAppName: boolean;\n private includeTraceId: boolean;\n private includeContext: boolean;\n private timestampFormat: 'iso' | 'locale' | 'short';\n private colors: Record<string, string>;\n\n constructor(\n options: {\n colorize?: boolean;\n includeTimestamp?: boolean;\n includeAppName?: boolean;\n includeTraceId?: boolean;\n includeContext?: boolean;\n timestampFormat?: 'iso' | 'locale' | 'short';\n colors?: Record<string, string>;\n } = {}\n ) {\n this.colorize = options.colorize ?? true;\n this.includeTimestamp = options.includeTimestamp ?? true;\n this.includeAppName = options.includeAppName ?? true;\n this.includeTraceId = options.includeTraceId ?? true;\n this.includeContext = options.includeContext ?? true;\n this.timestampFormat = options.timestampFormat ?? 'locale';\n this.colors = {\n error: '\\x1b[31m', // Red\n warn: '\\x1b[33m', // Yellow\n info: '\\x1b[32m', // Green\n debug: '\\x1b[34m', // Blue\n trace: '\\x1b[35m', // Magenta\n verbose: '\\x1b[36m', // Cyan\n reset: '\\x1b[0m', // Reset\n bold: '\\x1b[1m', // Bold\n dim: '\\x1b[2m', // Dim\n ...options.colors,\n };\n }\n\n format(entry: LogEntry): string {\n const parts: string[] = [];\n\n // Add timestamp\n if (this.includeTimestamp) {\n const timestamp = this.formatTimestamp(entry.timestamp);\n parts.push(this.colorize ? `${this.colors.dim}${timestamp}${this.colors.reset}` : timestamp);\n }\n\n // Add log level\n const levelName = entry.level.toLowerCase();\n const levelColor = this.colors[levelName] || this.colors.reset;\n const formattedLevel = this.colorize\n ? `${levelColor}${this.colors.bold}${levelName.toUpperCase().padEnd(5)}${this.colors.reset}`\n : levelName.toUpperCase().padEnd(5);\n parts.push(`[${formattedLevel}]`);\n\n // Add app name\n if (this.includeAppName) {\n const appName = this.colorize\n ? `${this.colors.bold}${entry.appName}${this.colors.reset}`\n : entry.appName;\n parts.push(`[${appName}]`);\n }\n\n // Add trace ID\n if (this.includeTraceId && entry.traceId) {\n const traceId = this.colorize\n ? `${this.colors.dim}${entry.traceId}${this.colors.reset}`\n : entry.traceId;\n parts.push(`[${traceId}]`);\n }\n\n // Add context\n if (this.includeContext && entry.context) {\n const context = this.colorize\n ? `${this.colors.cyan}${entry.context}${this.colors.reset}`\n : entry.context;\n parts.push(`[${context}]`);\n }\n\n // Add message\n const message =\n this.colorize && entry.level === LogLevel.ERROR\n ? `${this.colors.error}${entry.message}${this.colors.reset}`\n : entry.message;\n parts.push(message);\n\n // Add payload\n if (entry.payload && Object.keys(entry.payload).length > 0) {\n const payload = this.formatPayload(entry.payload);\n if (payload) {\n parts.push(this.colorize ? `${this.colors.dim}${payload}${this.colors.reset}` : payload);\n }\n }\n\n return parts.join(' ');\n }\n\n private formatTimestamp(timestamp: string): string {\n const date = new Date(timestamp);\n\n switch (this.timestampFormat) {\n case 'iso':\n return date.toISOString();\n case 'short':\n return date.toLocaleTimeString();\n case 'locale':\n default:\n return date.toLocaleString();\n }\n }\n\n private formatPayload(payload: Record<string, unknown>): string {\n try {\n // Handle simple objects\n if (Object.keys(payload).length === 1) {\n const entry = Object.entries(payload)[0];\n if (entry) {\n const [key, value] = entry;\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return `${key}=${value}`;\n }\n }\n }\n\n // Handle multiple properties or complex objects\n const formatted = Object.entries(payload)\n .map(([key, value]) => {\n if (value === null || value === undefined) {\n return `${key}=${value}`;\n }\n if (typeof value === 'string') {\n return `${key}=\"${value}\"`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return `${key}=${value}`;\n }\n if (value instanceof Date) {\n return `${key}=${value.toISOString()}`;\n }\n if (typeof value === 'object') {\n return `${key}=${JSON.stringify(value)}`;\n }\n return `${key}=${String(value)}`;\n })\n .join(' ');\n\n return formatted;\n } catch {\n return JSON.stringify(payload);\n }\n }\n\n /**\n * Create a formatter with preset configurations\n */\n static createSimple(): TextFormatter {\n return new TextFormatter({\n colorize: true,\n includeTimestamp: true,\n includeAppName: false,\n includeTraceId: false,\n includeContext: true,\n timestampFormat: 'short',\n });\n }\n\n static createDetailed(): TextFormatter {\n return new TextFormatter({\n colorize: true,\n includeTimestamp: true,\n includeAppName: true,\n includeTraceId: true,\n includeContext: true,\n timestampFormat: 'locale',\n });\n }\n\n static createMinimal(): TextFormatter {\n return new TextFormatter({\n colorize: false,\n includeTimestamp: false,\n includeAppName: false,\n includeTraceId: false,\n includeContext: false,\n });\n }\n}\n","/**\n * logixia — TypeScript typed log fields\n *\n * Solves the type-safety gap: standard `Record<string, unknown>` metadata gives\n * zero IDE autocomplete and lets typos slip silently into production logs.\n *\n * Two complementary utilities:\n *\n * 1. `createTypedLogger<TFields>()` — wraps any IBaseLogger so that the second\n * argument of every log method is constrained to `TFields` (a typed object).\n * Compile-time safety, zero runtime overhead.\n *\n * 2. `defineLogSchema<TFields>(schema)` — declares expected fields with optional\n * validators. In development (NODE_ENV !== 'production') every log call is\n * validated against the schema and a warning is emitted for missing required\n * fields or type mismatches.\n *\n * @example\n * ```ts\n * import { createTypedLogger, defineLogSchema } from 'logixia';\n *\n * interface OrderFields {\n * orderId: string;\n * userId: string;\n * amount?: number;\n * currency?: string;\n * }\n *\n * const schema = defineLogSchema<OrderFields>({\n * orderId: { type: 'string', required: true },\n * userId: { type: 'string', required: true },\n * amount: { type: 'number' },\n * currency: { type: 'string' },\n * });\n *\n * const orderLogger = createTypedLogger<OrderFields>(baseLogger, schema);\n * await orderLogger.info('Order created', { orderId: 'ord_123', userId: 'usr_456', amount: 99.99 });\n * // ^^^^ fully typed autocomplete ^^^^\n * ```\n */\n\nimport { internalWarn } from './internal-log';\n\n// ── Schema types ─────────────────────────────────────────────────────────────\n\nexport type LogFieldType = 'string' | 'number' | 'boolean' | 'object' | 'array';\n\nexport interface LogFieldDef {\n type: LogFieldType;\n /** Emit a warning when this field is missing from the log call. Default: false */\n required?: boolean;\n /** Custom validator — return a string to emit it as a warning message. */\n validate?: (value: unknown) => string | undefined;\n}\n\nexport type LogSchema<TFields extends Record<string, unknown>> = {\n [K in keyof TFields]: LogFieldDef;\n};\n\nexport interface CompiledSchema<TFields extends Record<string, unknown>> {\n readonly fields: LogSchema<TFields>;\n /**\n * Validate a payload against the schema.\n * Returns an array of warning strings (empty = pass).\n * Only runs in non-production environments.\n */\n validate(payload: Partial<TFields>): string[];\n}\n\n// ── defineLogSchema ──────────────────────────────────────────────────────────\n\n/**\n * Define a typed schema for a category of log entries.\n *\n * Call this once at module initialisation and pass it to `createTypedLogger`.\n * In development, every log call is validated against the schema.\n */\nexport function defineLogSchema<TFields extends Record<string, unknown>>(\n fields: LogSchema<TFields>\n): CompiledSchema<TFields> {\n return {\n fields,\n validate(payload: Partial<TFields>): string[] {\n if (process.env['NODE_ENV'] === 'production') return [];\n\n const warnings: string[] = [];\n\n for (const [key, def] of Object.entries(fields) as [keyof TFields & string, LogFieldDef][]) {\n const value = payload[key];\n\n if (def.required && (value === undefined || value === null)) {\n warnings.push(`Required field \"${key}\" is missing`);\n continue;\n }\n\n if (value !== undefined && value !== null) {\n const actualType = Array.isArray(value) ? 'array' : typeof value;\n if (actualType !== def.type) {\n warnings.push(`Field \"${key}\" expected type \"${def.type}\" but got \"${actualType}\"`);\n }\n\n if (def.validate) {\n const msg = def.validate(value);\n if (msg) warnings.push(`Field \"${key}\": ${msg}`);\n }\n }\n }\n\n return warnings;\n },\n };\n}\n\n// ── TypedLogger ──────────────────────────────────────────────────────────────\n\n/** IBaseLogger-compatible subset used by TypedLogger */\nexport interface LoggerLike {\n error(message: string | Error, data?: Record<string, unknown>): Promise<void>;\n warn(message: string, data?: Record<string, unknown>): Promise<void>;\n info(message: string, data?: Record<string, unknown>): Promise<void>;\n debug(message: string, data?: Record<string, unknown>): Promise<void>;\n verbose?(message: string, data?: Record<string, unknown>): Promise<void>;\n trace?(message: string, data?: Record<string, unknown>): Promise<void>;\n}\n\n/**\n * A logger whose metadata is typed to `TFields`.\n *\n * The `error` overload still accepts a plain `Error` object as the first arg\n * (with optional `TFields` data) so the typed logger remains a drop-in replacement.\n */\nexport interface TypedLogger<TFields extends Record<string, unknown>> {\n error(error: Error, data?: Partial<TFields>): Promise<void>;\n error(message: string, data?: Partial<TFields>): Promise<void>;\n warn(message: string, data?: Partial<TFields>): Promise<void>;\n info(message: string, data?: Partial<TFields>): Promise<void>;\n debug(message: string, data?: Partial<TFields>): Promise<void>;\n verbose(message: string, data?: Partial<TFields>): Promise<void>;\n trace(message: string, data?: Partial<TFields>): Promise<void>;\n /** Access the underlying untyped logger if needed. */\n readonly raw: LoggerLike;\n}\n\n/**\n * Wrap any logixia logger with a type-safe field interface.\n *\n * @param logger Any object that implements `IBaseLogger` (e.g. the result of `createLogger()`)\n * @param schema Optional schema for dev-time validation. Created with `defineLogSchema()`.\n */\nexport function createTypedLogger<TFields extends Record<string, unknown>>(\n logger: LoggerLike,\n schema?: CompiledSchema<TFields>\n): TypedLogger<TFields> {\n function withValidation(\n level: string,\n fn: (msg: string, data?: Record<string, unknown>) => Promise<void>,\n message: string,\n data?: Partial<TFields>\n ): Promise<void> {\n if (schema && data) {\n const warnings = schema.validate(data);\n for (const w of warnings) {\n internalWarn(`[logixia/schema] ${w} — level=${level} message=\"${message}\"`);\n }\n }\n return fn(message, data as Record<string, unknown> | undefined);\n }\n\n return {\n raw: logger,\n error(messageOrError: string | Error, data?: Partial<TFields>): Promise<void> {\n return logger.error(messageOrError as string, data as Record<string, unknown> | undefined);\n },\n warn: (m, d) => withValidation('warn', logger.warn.bind(logger), m, d),\n info: (m, d) => withValidation('info', logger.info.bind(logger), m, d),\n debug: (m, d) => withValidation('debug', logger.debug.bind(logger), m, d),\n verbose: (m, d) =>\n withValidation('verbose', (logger.verbose ?? logger.debug).bind(logger), m, d),\n trace: (m, d) => withValidation('trace', (logger.trace ?? logger.debug).bind(logger), m, d),\n };\n}\n","/**\n * logixia — Metrics extraction → Prometheus\n *\n * Automatically extracts metrics from structured log fields and exposes them\n * in the Prometheus text exposition format (version 0.0.4).\n * No external dependency — the format is fully self-contained.\n *\n * Supported metric types:\n * - `counter` — incremented on each matching log entry\n * - `histogram` — observes a numeric payload field per entry\n * - `gauge` — tracks the most recent numeric value of a payload field\n *\n * Usage:\n * ```ts\n * import { createMetricsPlugin } from 'logixia';\n *\n * const metrics = createMetricsPlugin({\n * http_request_duration: {\n * type: 'histogram',\n * field: 'duration',\n * labels: ['method', 'statusCode'],\n * help: 'HTTP request duration in milliseconds',\n * },\n * error_count: {\n * type: 'counter',\n * levelFilter: 'error',\n * labels: ['context'],\n * help: 'Total error log entries',\n * },\n * active_connections: {\n * type: 'gauge',\n * field: 'connections',\n * help: 'Current active connection count',\n * },\n * });\n *\n * logger.use(metrics); // start collecting\n * app.get('/metrics', metrics.expressHandler()); // expose for Prometheus scrape\n * ```\n *\n * All metric names are automatically prefixed with `logixia_`.\n * Output follows https://prometheus.io/docs/instrumenting/exposition_formats/\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport type { LogixiaPlugin } from './plugin';\nimport type { LogEntry } from './types/index';\n\n// ── Metric config types ───────────────────────────────────────────────────────\n\n/**\n * Increment a counter on each matching log entry.\n *\n * @example Count every error entry, labelled by context:\n * ```ts\n * error_count: { type: 'counter', levelFilter: 'error', labels: ['context'] }\n * ```\n *\n * @example Count entries where payload.event === 'checkout':\n * ```ts\n * checkout_events: { type: 'counter', field: 'event', value: 'checkout' }\n * ```\n */\nexport interface CounterConfig {\n type: 'counter';\n /** Only increment when `entry.level` equals this value. Omit to count all entries. */\n levelFilter?: string;\n /**\n * Only increment when `entry.payload[field] === value`.\n * If omitted, every entry (matching `levelFilter`) is counted.\n */\n field?: string;\n value?: unknown;\n /** `entry.payload` fields used as Prometheus label dimensions. `'level'` is also valid. */\n labels?: string[];\n help?: string;\n}\n\n/**\n * Observe a numeric payload field and bucket it into a Prometheus histogram.\n *\n * @example Duration histogram labelled by HTTP method and status code:\n * ```ts\n * http_request_duration: {\n * type: 'histogram',\n * field: 'duration',\n * labels: ['method', 'statusCode'],\n * buckets: [10, 25, 50, 100, 250, 500, 1000],\n * }\n * ```\n */\nexport interface HistogramConfig {\n type: 'histogram';\n /** The `entry.payload` field containing the numeric value to observe. */\n field: string;\n /** `entry.payload` fields used as Prometheus label dimensions. */\n labels?: string[];\n help?: string;\n /**\n * Bucket upper bounds (inclusive). Sorted automatically.\n * Default: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000]\n */\n buckets?: number[];\n}\n\n/**\n * Track the most recent numeric value of a payload field as a gauge.\n *\n * @example Track live connection count:\n * ```ts\n * active_connections: { type: 'gauge', field: 'connections' }\n * ```\n */\nexport interface GaugeConfig {\n type: 'gauge';\n /** The `entry.payload` field containing the numeric value. */\n field: string;\n /** `entry.payload` fields used as Prometheus label dimensions. */\n labels?: string[];\n help?: string;\n}\n\nexport type MetricConfig = CounterConfig | HistogramConfig | GaugeConfig;\nexport type MetricsMap = Record<string, MetricConfig>;\n\n// ── Internal metric state ─────────────────────────────────────────────────────\n\ninterface CounterState {\n type: 'counter';\n values: Map<string, number>;\n}\n\ninterface HistogramState {\n type: 'histogram';\n buckets: number[];\n /** Parallel arrays; index = bucket index; last entry = +Inf cumulative count */\n counts: Map<string, number[]>;\n sums: Map<string, number>;\n observations: Map<string, number>;\n}\n\ninterface GaugeState {\n type: 'gauge';\n values: Map<string, number>;\n}\n\ntype MetricState = CounterState | HistogramState | GaugeState;\n\n// ── Defaults ──────────────────────────────────────────────────────────────────\n\nconst DEFAULT_BUCKETS: readonly number[] = [\n 1, 5, 10, 25, 50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000,\n];\n\n// ── Label helpers ─────────────────────────────────────────────────────────────\n\nfunction buildLabelKey(config: MetricConfig, entry: LogEntry): string {\n const labelNames = config.labels ?? [];\n if (labelNames.length === 0) return '{}';\n const pairs: Record<string, string> = {};\n const payload = entry.payload ?? {};\n for (const name of labelNames) {\n const raw = name === 'level' ? entry.level : payload[name];\n pairs[name] = raw !== undefined && raw !== null ? String(raw) : '';\n }\n return JSON.stringify(pairs);\n}\n\nfunction renderLabels(labelKey: string): string {\n if (labelKey === '{}') return '';\n const obj = JSON.parse(labelKey) as Record<string, string>;\n const parts = Object.entries(obj).map(([k, v]) => `${k}=\"${escapeLabel(v)}\"`);\n return `{${parts.join(',')}}`;\n}\n\nfunction escapeLabel(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n');\n}\n\n// ── MetricsPlugin ─────────────────────────────────────────────────────────────\n\n/**\n * A logixia plugin that extracts Prometheus-compatible metrics from log entries.\n *\n * Implements `LogixiaPlugin` — pass directly to `logger.use()`:\n * ```ts\n * const metrics = new MetricsPlugin({ ... });\n * logger.use(metrics);\n * ```\n *\n * Or use the `createMetricsPlugin()` factory (preferred):\n * ```ts\n * const metrics = createMetricsPlugin({ ... });\n * logger.use(metrics);\n * ```\n */\nexport class MetricsPlugin implements LogixiaPlugin {\n public readonly name = 'logixia-metrics';\n\n private readonly map: MetricsMap;\n private readonly metricState = new Map<string, MetricState>();\n\n constructor(map: MetricsMap) {\n this.map = map;\n this.initAllState();\n }\n\n // ── LogixiaPlugin lifecycle ────────────────────────────────────────────────\n\n onInit(): void {\n // State is initialised in the constructor; nothing extra needed here.\n }\n\n onLog(entry: LogEntry): LogEntry {\n const payload = entry.payload ?? {};\n\n for (const [rawName, config] of Object.entries(this.map)) {\n const state = this.metricState.get(rawName);\n if (!state) continue;\n\n const labelKey = buildLabelKey(config, entry);\n\n if (config.type === 'counter' && state.type === 'counter') {\n // Level filter\n if (config.levelFilter && entry.level !== config.levelFilter) continue;\n // Field/value filter\n if (config.field !== undefined && payload[config.field] !== config.value) continue;\n state.values.set(labelKey, (state.values.get(labelKey) ?? 0) + 1);\n } else if (config.type === 'histogram' && state.type === 'histogram') {\n const raw = payload[config.field];\n if (raw === undefined || raw === null) continue;\n const val = Number(raw);\n if (Number.isNaN(val)) continue;\n\n // Initialise per-label arrays on first observation\n if (!state.counts.has(labelKey)) {\n state.counts.set(\n labelKey,\n Array.from<number>({ length: state.buckets.length + 1 }).fill(0)\n );\n state.sums.set(labelKey, 0);\n state.observations.set(labelKey, 0);\n }\n\n const bucketArr = state.counts.get(labelKey)!;\n for (let i = 0; i < state.buckets.length; i++) {\n if (val <= state.buckets[i]!) bucketArr[i]!++;\n }\n // The +Inf bucket (last slot) always increments\n bucketArr[state.buckets.length]!++;\n state.sums.set(labelKey, (state.sums.get(labelKey) ?? 0) + val);\n state.observations.set(labelKey, (state.observations.get(labelKey) ?? 0) + 1);\n } else if (config.type === 'gauge' && state.type === 'gauge') {\n const raw = payload[config.field];\n if (raw === undefined || raw === null) continue;\n const val = Number(raw);\n if (Number.isNaN(val)) continue;\n state.values.set(labelKey, val);\n }\n }\n\n // Always pass the entry through unchanged\n return entry;\n }\n\n // ── Output ─────────────────────────────────────────────────────────────────\n\n /**\n * Render all registered metrics in the Prometheus text exposition format\n * (version 0.0.4).\n *\n * All metric names are prefixed with `logixia_`.\n *\n * @example\n * ```\n * # HELP logixia_error_count Total error log entries\n * # TYPE logixia_error_count counter\n * logixia_error_count{context=\"OrderService\"} 7\n * ```\n */\n render(): string {\n const lines: string[] = [];\n\n for (const [rawName, config] of Object.entries(this.map)) {\n const metricName = `logixia_${rawName}`;\n const state = this.metricState.get(rawName);\n if (!state) continue;\n\n const helpText = config.help ?? rawName.replace(/_/g, ' ');\n lines.push(`# HELP ${metricName} ${helpText}`);\n lines.push(`# TYPE ${metricName} ${config.type}`);\n\n if (state.type === 'counter') {\n if (state.values.size === 0) {\n lines.push(`${metricName} 0`);\n } else {\n for (const [labelKey, count] of state.values) {\n lines.push(`${metricName}${renderLabels(labelKey)} ${count}`);\n }\n }\n } else if (state.type === 'histogram') {\n for (const [labelKey, bucketCounts] of state.counts) {\n const labelSuffix = renderLabels(labelKey);\n const baseObj = labelKey === '{}' ? {} : (JSON.parse(labelKey) as Record<string, string>);\n\n // One line per finite bucket\n for (let i = 0; i < state.buckets.length; i++) {\n const leKey = JSON.stringify({ ...baseObj, le: String(state.buckets[i]) });\n lines.push(`${metricName}_bucket${renderLabels(leKey)} ${bucketCounts[i] ?? 0}`);\n }\n // +Inf bucket\n const infKey = JSON.stringify({ ...baseObj, le: '+Inf' });\n lines.push(\n `${metricName}_bucket${renderLabels(infKey)} ${bucketCounts[state.buckets.length] ?? 0}`\n );\n lines.push(`${metricName}_sum${labelSuffix} ${state.sums.get(labelKey) ?? 0}`);\n lines.push(`${metricName}_count${labelSuffix} ${state.observations.get(labelKey) ?? 0}`);\n }\n } else if (state.type === 'gauge') {\n if (state.values.size === 0) {\n lines.push(`${metricName} 0`);\n } else {\n for (const [labelKey, val] of state.values) {\n lines.push(`${metricName}${renderLabels(labelKey)} ${val}`);\n }\n }\n }\n }\n\n return `${lines.join('\\n')}\\n`;\n }\n\n /**\n * Reset all metric counters and observations back to zero.\n * Useful between test runs or on a scheduled reset interval.\n */\n reset(): void {\n this.metricState.clear();\n this.initAllState();\n }\n\n /**\n * Express route handler — call `app.get('/metrics', metrics.expressHandler())`.\n *\n * @example\n * ```ts\n * import express from 'express';\n * const app = express();\n * app.get('/metrics', metrics.expressHandler());\n * ```\n */\n expressHandler(): (\n req: unknown,\n res: { set(k: string, v: string): unknown; end(body: string): void }\n ) => void {\n return (_req, res) => {\n res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');\n res.end(this.render());\n };\n }\n\n /**\n * Raw Node.js `http` server handler.\n * Responds to `GET /metrics` with the Prometheus text payload.\n *\n * @example Start a dedicated metrics server on the standard port:\n * ```ts\n * import http from 'node:http';\n * const server = http.createServer(metrics.httpHandler());\n * server.listen(9464); // Prometheus default port for custom exporters\n * ```\n */\n httpHandler(): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n const isMetricsPath = req.url === '/metrics' || req.url === '/metrics/';\n if (!isMetricsPath) {\n res.writeHead(404).end('Not found');\n return;\n }\n const body = this.render();\n res.writeHead(200, {\n 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n });\n res.end(body);\n };\n }\n\n // ── Private helpers ────────────────────────────────────────────────────────\n\n private initAllState(): void {\n for (const [rawName, config] of Object.entries(this.map)) {\n this.initSingleState(rawName, config);\n }\n }\n\n private initSingleState(rawName: string, config: MetricConfig): void {\n if (config.type === 'counter') {\n this.metricState.set(rawName, { type: 'counter', values: new Map() });\n } else if (config.type === 'histogram') {\n const buckets = [...(config.buckets ?? DEFAULT_BUCKETS)].sort((a, b) => a - b);\n this.metricState.set(rawName, {\n type: 'histogram',\n buckets,\n counts: new Map(),\n sums: new Map(),\n observations: new Map(),\n });\n } else {\n this.metricState.set(rawName, { type: 'gauge', values: new Map() });\n }\n }\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\n/**\n * Create a `MetricsPlugin` from a metrics map and return it ready for\n * `logger.use()`.\n *\n * @example\n * ```ts\n * import { createMetricsPlugin } from 'logixia';\n *\n * const metrics = createMetricsPlugin({\n * http_request_duration: {\n * type: 'histogram',\n * field: 'duration',\n * labels: ['method', 'statusCode'],\n * help: 'HTTP request duration in milliseconds',\n * },\n * error_count: {\n * type: 'counter',\n * levelFilter: 'error',\n * labels: ['context'],\n * help: 'Total error log entries',\n * },\n * });\n *\n * logger.use(metrics);\n * app.get('/metrics', metrics.expressHandler());\n * ```\n */\nexport function createMetricsPlugin(map: MetricsMap): MetricsPlugin {\n return new MetricsPlugin(map);\n}\n","/**\n * Logixia - Advanced TypeScript Logger\n *\n * A comprehensive logging library with support for:\n * - Multiple output formats (console, file, JSON)\n * - Trace ID tracking\n * - Performance monitoring\n * - NestJS integration\n * - Customizable log levels and colors\n * - Intelligent log search and aggregation\n * - Natural language query processing\n * - Pattern recognition and anomaly detection\n */\n\nimport { createLogger as createLoggerFromCore, LogixiaLogger } from './core/logitron-logger';\nimport { LogixiaLoggerService } from './core/logitron-nestjs.service';\nimport type { Environment, LogColor, LoggerConfig } from './types';\nimport { LogLevel } from './types';\n\n// Type exports\nexport * from './core/logitron-logger.module';\nexport * from './core/logitron-nestjs.service';\nexport type { LogMethodOptions } from './core/nestjs-extras';\nexport { InjectLogger, LogixiaExceptionFilter, LogMethod } from './core/nestjs-extras';\nexport * from './formatters';\nexport * from './types';\nexport * from './utils/error.utils';\nexport type { OtelBridgeOptions, OtelSpanContext } from './utils/otel';\nexport {\n disableOtelBridge,\n getActiveOtelContext,\n getOtelMetaFields,\n initOtelBridge,\n} from './utils/otel';\nexport { applyRedaction, redactObject } from './utils/redact.utils';\nexport * from './utils/shutdown.utils';\nexport * from './utils/trace.utils';\nexport type {\n CompiledSchema,\n LogFieldDef,\n LogFieldType,\n LoggerLike,\n LogSchema,\n TypedLogger,\n} from './utils/typed-logger';\nexport { createTypedLogger, defineLogSchema } from './utils/typed-logger';\n\n// Search module exports\nexport * from './search';\n\n// Context propagation (AsyncLocalStorage)\nexport type { LogContext } from './context/async-context';\nexport {\n createExpressContextMiddleware,\n createFastifyContextHook,\n LogixiaContext,\n} from './context/async-context';\n\n// Sampling stats (SamplingConfig is already exported via ./types)\nexport type { SamplingStats } from './utils/sampling.utils';\n\n// Plugin API (Feature 20)\nexport type { LogixiaPlugin } from './plugin';\nexport { globalPluginRegistry, PluginRegistry, usePlugin } from './plugin';\n\n// Exception system — typed LogixiaException + unified error response format\nexport type {\n BuildParams,\n ErrorDetail,\n LogixiaErrorResponse,\n LogixiaExceptionOptions,\n} from './exceptions';\nexport {\n ErrorResponseBuilder,\n generateRequestId,\n generateTraceId,\n isLogixiaException,\n LogixiaException,\n} from './exceptions';\n\n// Metrics extraction → Prometheus (Feature 21)\nexport type {\n CounterConfig,\n GaugeConfig,\n HistogramConfig,\n MetricConfig,\n MetricsMap,\n} from './metrics';\nexport { createMetricsPlugin, MetricsPlugin } from './metrics';\n\n// Core exports\nexport { DEFAULT_CONFIG, LogixiaLogger, LogixiaLoggerService };\n\n/**\n * Default configuration for Logixia logger\n */\nconst DEFAULT_CONFIG = {\n appName: 'App',\n environment: 'development' as Environment,\n traceId: true,\n format: {\n timestamp: true,\n colorize: true,\n json: false,\n },\n silent: false,\n levelOptions: {\n level: LogLevel.INFO,\n levels: {\n [LogLevel.ERROR]: 0,\n [LogLevel.WARN]: 1,\n [LogLevel.INFO]: 2,\n [LogLevel.DEBUG]: 3,\n [LogLevel.TRACE]: 4,\n [LogLevel.VERBOSE]: 5,\n },\n colors: {\n [LogLevel.ERROR]: 'red',\n [LogLevel.WARN]: 'yellow',\n [LogLevel.INFO]: 'blue',\n [LogLevel.DEBUG]: 'green',\n [LogLevel.TRACE]: 'gray',\n [LogLevel.VERBOSE]: 'cyan',\n } as Record<string, LogColor>,\n },\n fields: {\n timestamp: true,\n level: true,\n appName: true,\n traceId: true,\n message: true,\n payload: true,\n timeTaken: true,\n },\n outputs: ['console'],\n};\n\n/**\n * Create a new Logixia logger instance with TypeScript support for custom levels\n * @param config - Logger configuration\n * @returns Typed logger instance\n */\nexport const createLogger = createLoggerFromCore;\n\n/**\n * Create a new Logixia logger service for NestJS\n * @param config - Logger configuration\n * @returns LogixiaLoggerService instance\n */\nexport function createLoggerService(config?: Partial<LoggerConfig>): LogixiaLoggerService {\n return new LogixiaLoggerService({ ...DEFAULT_CONFIG, ...config });\n}\n\n/**\n * Default logger instance\n */\nexport const logger = new LogixiaLogger(DEFAULT_CONFIG);\n\n/**\n * Export default configuration for reference\n */\n"],"mappings":";;;;;;;AA4IA,IAAa,mBAAb,cAGU,MAAM;CAkBd,YAAY,SAAgD;AAG1D,QAAM,QAAQ,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;AAEhD,OAAK,OAAO;AACZ,OAAK,YAAY,QAAQ;AACzB,OAAK,YAAY,QAAQ;AACzB,OAAK,aAAa,QAAQ;AAC1B,OAAK,QAAQ,QAAQ;AACrB,OAAK,UAAU,QAAQ;AACvB,OAAK,SAAS,QAAQ;AACtB,OAAK,WAAW,QAAQ;AAGxB,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;;;;;;;;;;;;AAmBrD,SAAgB,mBACd,OACyC;AACzC,QAAO,iBAAiB;;;;;;;;;;;ACjJ1B,SAAgB,kBAA0B;AACxC,QAAO,YAAY;;;AAIrB,MAAa,oBAAoB;;;;;AAMjC,SAAS,iBAAiB,QAAwB;AAChD,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW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AAoB,KAAgC;AAClE,QAAO,IAAI,cAAc,IAAI;;;;;;;;AC7V/B,MAAM,iBAAiB;CACrB,SAAS;CACT,aAAa;CACb,SAAS;CACT,QAAQ;EACN,WAAW;EACX,UAAU;EACV,MAAM;EACP;CACD,QAAQ;CACR,cAAc;EACZ,OAAO,SAAS;EAChB,QAAQ;IACL,SAAS,QAAQ;IACjB,SAAS,OAAO;IAChB,SAAS,OAAO;IAChB,SAAS,QAAQ;IACjB,SAAS,QAAQ;IACjB,SAAS,UAAU;GACrB;EACD,QAAQ;IACL,SAAS,QAAQ;IACjB,SAAS,OAAO;IAChB,SAAS,OAAO;IAChB,SAAS,QAAQ;IACjB,SAAS,QAAQ;IACjB,SAAS,UAAU;GACrB;EACF;CACD,QAAQ;EACN,WAAW;EACX,OAAO;EACP,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,WAAW;EACZ;CACD,SAAS,CAAC,UAAU;CACrB;;;;;;AAOD,MAAa,eAAeC;;;;;;AAO5B,SAAgB,oBAAoB,QAAsD;AACxF,QAAO,IAAI,qBAAqB;EAAE,GAAG;EAAgB,GAAG;EAAQ,CAAC;;;;;AAMnE,MAAa,SAAS,IAAI,cAAc,eAAe"}
1
+ {"version":3,"file":"index.mjs","names":["cause: string | undefined","debug","errorBlock: LogixiaErrorResponse<TCode, TType>['error']","message: string","logger: LogixiaLoggerService | undefined","logger","entry: Record<string, unknown>","exit: Record<string, unknown>","errLog: unknown","LogixiaExceptionFilter","logger?: LogixiaLoggerService","loggerConfig?: Partial<LoggerConfig>","requestMeta: Record<string, unknown>","logPromise: Promise<void> | void","formatted: Record<string, unknown>","serialized: Record<string, unknown>","parts: string[]","warnings: string[]","logger","DEFAULT_BUCKETS: readonly number[]","pairs: Record<string, string>","lines: string[]","createLoggerFromCore"],"sources":["../src/exceptions/exception.ts","../src/exceptions/builder.ts","../src/core/nestjs-extras.ts","../src/formatters/json.formatter.ts","../src/formatters/text.formatter.ts","../src/utils/typed-logger.ts","../src/metrics.ts","../src/index.ts"],"sourcesContent":["/**\n * LogixiaException — a strictly typed, framework-agnostic exception class.\n *\n * You bring your own error codes and types; logixia enforces the shape.\n * The `ErrorResponseBuilder` knows how to turn a `LogixiaException` into the\n * standard `LogixiaErrorResponse` wire format.\n *\n * @template TCode - Your error code union. e.g. `'PE-AUTH-001' | 'PE-USR-001'`\n * @template TType - Your error type union. e.g. `'authentication_error' | 'validation_error'`\n *\n * @example Basic throw\n * ```ts\n * throw new LogixiaException({\n * code: 'PE-AUTH-001',\n * type: 'authentication_error',\n * httpStatus: 401,\n * message: 'Invalid email or password.',\n * });\n * ```\n *\n * @example Fully typed with your own code/type unions\n * ```ts\n * type AppCode = 'PE-AUTH-001' | 'PE-VAL-001';\n * type AppType = 'authentication_error' | 'validation_error';\n *\n * throw new LogixiaException<AppCode, AppType>({\n * code: 'PE-VAL-001',\n * type: 'validation_error',\n * httpStatus: 400,\n * message: 'Validation failed.',\n * details: [\n * { field: 'email', message: 'must be a valid email', code: 'invalid_format' },\n * ],\n * });\n * ```\n *\n * @example With field pointer (Stripe param pattern)\n * ```ts\n * throw new LogixiaException({\n * code: 'PE-USR-002',\n * type: 'conflict_error',\n * httpStatus: 409,\n * message: 'This email is already in use.',\n * param: 'email',\n * });\n * ```\n *\n * @example With cause chain (ES 2022)\n * ```ts\n * try {\n * await db.save(user);\n * } catch (err) {\n * throw new LogixiaException({\n * code: 'PE-DB-001',\n * type: 'server_error',\n * httpStatus: 409,\n * message: 'Duplicate record.',\n * cause: err instanceof Error ? err : undefined,\n * });\n * }\n * ```\n */\n\nimport type { ErrorDetail } from './types.js';\n\n// ── Options ───────────────────────────────────────────────────────────────────\n\n/**\n * Constructor options for `LogixiaException`.\n *\n * All user-supplied fields — logixia only owns the wire format.\n */\nexport interface LogixiaExceptionOptions<\n TCode extends string = string,\n TType extends string = string,\n> {\n /**\n * Machine-readable, stable error code.\n * e.g. `'PE-AUTH-001'`\n */\n code: TCode;\n\n /**\n * Broad error type category.\n * e.g. `'authentication_error'` | `'validation_error'` | `'rate_limit_error'`\n */\n type: TType;\n\n /**\n * HTTP status code to send on the wire.\n * e.g. `401` | `400` | `429` | `500`\n */\n httpStatus: number;\n\n /**\n * Human-readable message for the end-user.\n * This IS sent in the response body — keep it safe (no internal paths, etc.).\n */\n message: string;\n\n /**\n * The specific request field that caused this error (Stripe pattern).\n * e.g. `'email'` | `'metadata.name'`\n */\n param?: string;\n\n /**\n * Array of per-field validation errors (GitHub pattern).\n * Typically used for `400` / `422` validation failures.\n */\n details?: ErrorDetail[];\n\n /**\n * Documentation URL for this error (Twilio pattern).\n * e.g. `'https://docs.example.com/errors/PE-AUTH-001'`\n */\n docUrl?: string;\n\n /**\n * Original error for ES 2022 cause chaining.\n * Serialised into `debug.cause` by the `ErrorResponseBuilder`.\n * Never sent to the client in production.\n */\n cause?: Error;\n\n /**\n * Arbitrary metadata for logging purposes only.\n * This is **never** included in the HTTP response — it is passed to your\n * logger / monitoring integrations through the exception object.\n *\n * @example\n * ```ts\n * metadata: { userId: 'u_abc', attemptCount: 3 }\n * ```\n */\n metadata?: Record<string, unknown>;\n}\n\n// ── Exception class ───────────────────────────────────────────────────────────\n\nexport class LogixiaException<\n TCode extends string = string,\n TType extends string = string,\n> extends Error {\n /** @readonly The machine-readable error code supplied by the caller. */\n public readonly errorCode: TCode;\n /** @readonly The error type category supplied by the caller. */\n public readonly errorType: TType;\n /** @readonly HTTP status code to respond with. */\n public readonly httpStatus: number;\n /** @readonly Field pointer that caused this error (Stripe pattern). */\n public readonly param: string | undefined;\n /** @readonly Field-level validation errors (GitHub pattern). */\n public readonly details: ErrorDetail[] | undefined;\n /** @readonly Documentation URL for this error (Twilio pattern). */\n public readonly docUrl: string | undefined;\n /**\n * @readonly Extra context for your logger — never serialised into the HTTP response.\n */\n public readonly metadata: Record<string, unknown> | undefined;\n\n constructor(options: LogixiaExceptionOptions<TCode, TType>) {\n // Pass `cause` through the standard ES 2022 Error options so native\n // tooling (Node.js, Sentry, etc.) can walk the full error chain.\n super(options.message, { cause: options.cause });\n\n this.name = 'LogixiaException';\n this.errorCode = options.code;\n this.errorType = options.type;\n this.httpStatus = options.httpStatus;\n this.param = options.param;\n this.details = options.details;\n this.docUrl = options.docUrl;\n this.metadata = options.metadata;\n\n // Restore the correct prototype chain when compiling to ES5.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n// ── Type guard ────────────────────────────────────────────────────────────────\n\n/**\n * Returns `true` when `value` is a `LogixiaException` instance.\n *\n * Useful in exception filters or middleware that need to distinguish a\n * `LogixiaException` from a plain `Error` or a framework `HttpException`.\n *\n * @example\n * ```ts\n * if (isLogixiaException(err)) {\n * console.log(err.errorCode, err.httpStatus);\n * }\n * ```\n */\nexport function isLogixiaException<TCode extends string = string, TType extends string = string>(\n value?: unknown\n): value is LogixiaException<TCode, TType> {\n return value instanceof LogixiaException;\n}\n","/**\n * ErrorResponseBuilder — turns any exception into a `LogixiaErrorResponse`.\n *\n * Priority order:\n * 1. `LogixiaException` — typed fields used directly\n * 2. NestJS `HttpException` — duck-typed; status + message extracted\n * 3. Plain `Error` / unknown — falls back to 500 `server_error`\n *\n * The builder **always** populates `debug` when possible.\n * Your exception filter is responsible for stripping it in production:\n * ```ts\n * if (process.env.NODE_ENV === 'production') delete response.debug;\n * ```\n */\n\nimport { TraceContext } from '../utils/trace.utils.js';\nimport { isLogixiaException } from './exception.js';\nimport type { LogixiaErrorResponse } from './types.js';\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\n/** Input parameters for `ErrorResponseBuilder.build`. */\nexport interface BuildParams {\n /** The caught exception — any type. */\n exception: unknown;\n /**\n * Trace ID to embed in `meta.trace_id`.\n * If omitted a UUID-based ID is auto-generated.\n */\n traceId?: string | undefined;\n /** Request path. e.g. `'/api/v1/auth/login'` */\n path: string;\n /**\n * Originating service name for `debug.service`.\n * e.g. `process.env.SERVICE_NAME` → `'gatekeeper'`\n */\n service?: string | undefined;\n /**\n * `Date.now()` captured at the start of the request.\n * When present, `debug.duration_ms` is computed automatically.\n */\n startTime?: number | undefined;\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Generates a trace ID via the shared {@link TraceContext} generator.\n *\n * Delegates to `TraceContext.instance.generate()` so any custom generator\n * configured on `TraceIdConfig.generator` is respected — avoids the silent\n * \"builder has its own UUID source\" divergence this module had previously.\n *\n * @example `'550e8400-e29b-41d4-a716-446655440000'`\n */\nexport function generateTraceId(): string {\n return TraceContext.instance.generate();\n}\n\n/** @deprecated Use `generateTraceId` instead. */\nexport const generateRequestId = generateTraceId;\n\n/**\n * Maps an HTTP status code to a human-friendly error type string.\n * Used as a fallback when the exception is a generic `HttpException`.\n */\nfunction httpStatusToType(status: number): string {\n if (status === 400) return 'api_error';\n if (status === 401) return 'authentication_error';\n if (status === 402) return 'payment_error';\n if (status === 403) return 'authorization_error';\n if (status === 404) return 'not_found_error';\n if (status === 408) return 'timeout_error';\n if (status === 409) return 'conflict_error';\n if (status === 422) return 'validation_error';\n if (status === 429) return 'rate_limit_error';\n if (status >= 500) return 'server_error';\n if (status >= 400) return 'api_error';\n return 'server_error';\n}\n\n/**\n * Duck-type check for NestJS `HttpException`.\n * Avoids a hard import on `@nestjs/common` so the builder is usable outside NestJS.\n */\nfunction isHttpException(\n value: unknown\n): value is { getStatus(): number; getResponse(): unknown; message: string } {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Record<string, unknown>)['getStatus'] === 'function' &&\n typeof (value as Record<string, unknown>)['getResponse'] === 'function'\n );\n}\n\n/**\n * Builds the optional `debug` block from an error.\n * Returns `undefined` when there is nothing useful to include.\n */\nfunction buildDebug(\n error: unknown,\n service: string | undefined,\n durationMs: number | undefined\n): LogixiaErrorResponse['debug'] {\n const stack = error instanceof Error ? error.stack : undefined;\n\n const causeRaw =\n error instanceof Error ? (error as Error & { cause?: unknown }).cause : undefined;\n let cause: string | undefined;\n if (causeRaw instanceof Error) {\n cause = causeRaw.message;\n } else if (causeRaw !== undefined && causeRaw !== null) {\n cause = String(causeRaw);\n }\n\n if (!stack && !cause && !service && durationMs === undefined) return undefined;\n\n return {\n ...(stack !== undefined ? { stack } : {}),\n ...(cause !== undefined ? { cause } : {}),\n ...(service !== undefined ? { service } : {}),\n ...(durationMs !== undefined ? { duration_ms: durationMs } : {}),\n };\n}\n\n// ── Builder ───────────────────────────────────────────────────────────────────\n\nexport class ErrorResponseBuilder {\n /**\n * Build a `LogixiaErrorResponse` from any thrown value.\n *\n * @param params - See `BuildParams`.\n * @returns The unified error response and the HTTP status code to send.\n *\n * @remarks\n * `traceId` does not need to be supplied by the caller in most cases — the\n * builder reads `TraceContext.instance.getCurrentTraceId()` internally and\n * falls back to the explicit `traceId` argument only when AsyncLocalStorage\n * is empty. If neither source yields a value, `meta.trace_id` is omitted.\n *\n * @example In a NestJS exception filter\n * ```ts\n * const { response, httpStatus } = ErrorResponseBuilder.build<AppCode, AppType>({\n * exception,\n * // Omit traceId — it will be picked up from ALS automatically.\n * path: request.url,\n * service: process.env.SERVICE_NAME,\n * startTime: request.startTime,\n * });\n *\n * if (process.env.NODE_ENV === 'production') delete response.debug;\n * // Echo the resolved traceId back on whatever header your TraceIdConfig says —\n * // do NOT hardcode 'X-Trace-Id', use `resolveResponseHeader(config)` instead.\n * if (response.meta.trace_id) {\n * response.setHeader(resolveResponseHeader(config) ?? 'X-Trace-Id', response.meta.trace_id);\n * }\n * response.status(httpStatus).json(response);\n * ```\n */\n static build<TCode extends string = string, TType extends string = string>(\n params: BuildParams\n ): { response: LogixiaErrorResponse<TCode, TType>; httpStatus: number } {\n const { exception, path, service, startTime, traceId: rawTraceId } = params;\n // ALS is authoritative → caller-supplied → undefined (field omitted from response).\n const traceId = TraceContext.instance.getCurrentTraceId() ?? rawTraceId;\n const timestamp = new Date().toISOString();\n const durationMs = startTime !== undefined ? Date.now() - startTime : undefined;\n\n // ── 1. LogixiaException ────────────────────────────────────────────────\n if (isLogixiaException<TCode, TType>(exception)) {\n const debug = buildDebug(exception, service, durationMs);\n\n const errorBlock: LogixiaErrorResponse<TCode, TType>['error'] = {\n type: exception.errorType,\n code: exception.errorCode,\n message: exception.message,\n };\n if (exception.param !== undefined) errorBlock.param = exception.param;\n if (exception.details !== undefined && exception.details.length > 0) {\n errorBlock.details = exception.details;\n }\n if (exception.docUrl !== undefined) errorBlock.doc_url = exception.docUrl;\n\n const response: LogixiaErrorResponse<TCode, TType> = {\n success: false,\n error: errorBlock,\n meta: {\n ...(traceId !== undefined ? { trace_id: traceId } : {}),\n timestamp,\n path,\n status: exception.httpStatus,\n },\n ...(debug !== undefined ? { debug } : {}),\n };\n\n return { response, httpStatus: exception.httpStatus };\n }\n\n // ── 2. NestJS HttpException (duck-typed) ──────────────────────────────\n if (isHttpException(exception)) {\n const status = exception.getStatus();\n const exResponse = exception.getResponse();\n\n // NestJS nests the message: { statusCode, message, error } or a plain string\n let message: string;\n if (typeof exResponse === 'string') {\n message = exResponse;\n } else if (typeof exResponse === 'object' && exResponse !== null && 'message' in exResponse) {\n const raw = (exResponse as { message: unknown }).message;\n message = Array.isArray(raw) ? raw.join(', ') : String(raw);\n } else {\n message = exception.message;\n }\n\n const type = httpStatusToType(status) as TType;\n const code = `HTTP_${status}` as TCode;\n const debug = buildDebug(exception, service, durationMs);\n\n const response: LogixiaErrorResponse<TCode, TType> = {\n success: false,\n error: { type, code, message },\n meta: { ...(traceId !== undefined ? { trace_id: traceId } : {}), timestamp, path, status },\n ...(debug !== undefined ? { debug } : {}),\n };\n\n return { response, httpStatus: status };\n }\n\n // ── 3. Unknown / plain Error ──────────────────────────────────────────\n const err = exception instanceof Error ? exception : new Error(String(exception));\n const debug = buildDebug(err, service, durationMs);\n\n const response: LogixiaErrorResponse<TCode, TType> = {\n success: false,\n error: {\n type: 'server_error' as TType,\n code: 'INTERNAL_SERVER_ERROR' as TCode,\n message: 'An unexpected error occurred.',\n },\n meta: {\n ...(traceId !== undefined ? { trace_id: traceId } : {}),\n timestamp,\n path,\n status: 500,\n },\n ...(debug !== undefined ? { debug } : {}),\n };\n\n return { response, httpStatus: 500 };\n }\n}\n","/**\n * logixia — NestJS extras: @InjectLogger, @LogMethod, LogixiaExceptionFilter\n *\n * Completes the NestJS deep integration story:\n * - @InjectLogger() — inject the logger via NestJS DI without typing LOGIXIA_TOKEN manually\n * - @LogMethod() — auto-log method entry / exit with args and return value\n * - LogixiaExceptionFilter — catch-all exception filter that logs unhandled errors\n * with full request context before re-throwing\n *\n * @example Full setup\n * ```ts\n * // app.module.ts\n * import { LogixiaModule } from 'logixia';\n * @Module({ imports: [LogixiaModule.forRoot({ appName: 'api' })] })\n * export class AppModule {}\n *\n * // order.service.ts\n * import { Injectable } from '@nestjs/common';\n * import { InjectLogger, LogMethod, LogixiaLoggerService } from 'logixia';\n *\n * @Injectable()\n * export class OrderService {\n * constructor(@InjectLogger() private readonly logger: LogixiaLoggerService) {}\n *\n * @LogMethod()\n * async createOrder(dto: CreateOrderDto) { … }\n * }\n *\n * // main.ts\n * import { LogixiaExceptionFilter } from 'logixia';\n * app.useGlobalFilters(new LogixiaExceptionFilter(logger));\n * ```\n */\n\nimport type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';\nimport { Catch, Inject, Optional } from '@nestjs/common';\n\nimport { ErrorResponseBuilder } from '../exceptions/builder';\nimport { isLogixiaException } from '../exceptions/exception';\nimport type { LoggerConfig, LogLevelString, TraceIdConfig } from '../types';\nimport { TraceContext } from '../utils/trace.utils';\nimport {\n LOGIXIA_LOGGER_CONFIG,\n LOGIXIA_LOGGER_PREFIX,\n LogixiaLoggerModule,\n} from './logitron-logger.module';\nimport type { LogixiaLoggerService } from './logitron-nestjs.service';\nimport { resolveResponseHeader } from './trace.middleware';\n\n// ── @InjectLogger() ──────────────────────────────────────────────────────────\n\n/**\n * Inject the Logixia logger registered in the current NestJS DI container.\n *\n * Equivalent to `@Inject(LOGIXIA_LOGGER_TOKEN)` but without needing to import\n * the internal token constant yourself.\n *\n * @example\n * ```ts\n * constructor(@InjectLogger() private readonly logger: LogixiaLoggerService) {}\n * ```\n */\nexport const InjectLogger = (): ParameterDecorator => Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`);\n\n// ── @LogMethod() ─────────────────────────────────────────────────────────────\n\nexport interface LogMethodOptions {\n /**\n * Log level to use for entry / exit messages.\n * @default 'debug'\n */\n level?: LogLevelString;\n /**\n * Whether to log the arguments passed to the method.\n * Disable for high-throughput hot paths.\n * @default true\n */\n logArgs?: boolean;\n /**\n * Whether to log the return value of the method.\n * @default false\n */\n logResult?: boolean;\n /**\n * Whether to log error stack traces for thrown errors.\n * @default true\n */\n logErrors?: boolean;\n /**\n * Custom label used in log messages instead of the auto-detected class.method name.\n */\n label?: string;\n}\n\n/**\n * Method decorator that auto-logs entry, exit, duration, and errors.\n *\n * Works on both async and sync methods. Attaches to the logger found on the\n * class instance via a `logger` property (the conventional NestJS name).\n *\n * @example\n * ```ts\n * @LogMethod({ level: 'info', logArgs: true })\n * async processPayment(orderId: string): Promise<void> { … }\n * ```\n */\nexport function LogMethod(options: LogMethodOptions = {}): MethodDecorator {\n const { level = 'debug', logArgs = true, logResult = false, logErrors = true } = options;\n\n // Use PropertyDescriptor (not generic TypedPropertyDescriptor<T>) to avoid\n // strict generic inference issues with exactOptionalPropertyTypes.\n return function (\n target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor\n ): PropertyDescriptor {\n const originalMethod = descriptor.value as ((...args: unknown[]) => unknown) | undefined;\n if (typeof originalMethod !== 'function') return descriptor;\n\n const methodName = String(propertyKey);\n const className =\n (target as { constructor?: { name?: string } }).constructor?.name ?? 'Unknown';\n const label = options.label ?? `${className}.${methodName}`;\n\n let _warnedNoLogger = false;\n\n descriptor.value = async function (\n this: { logger?: LogixiaLoggerService },\n ...args: unknown[]\n ) {\n // Prefer the instance's own logger; fall back to the global module logger.\n const logger: LogixiaLoggerService | undefined =\n this.logger ?? LogixiaLoggerModule._globalLogger ?? undefined;\n\n if (!logger && !_warnedNoLogger) {\n _warnedNoLogger = true;\n // eslint-disable-next-line no-console\n console.warn(\n `[logixia] @LogMethod on ${label}: no logger available. ` +\n `Either inject LogixiaLoggerService as this.logger or ensure LogixiaLoggerModule is initialised.`\n );\n }\n\n const start = Date.now();\n\n const entry: Record<string, unknown> = { method: label };\n if (logArgs && args.length > 0) {\n entry['args'] = args;\n }\n\n // Surface logger failures on stderr instead of silently swallowing them —\n // a broken transport is an operator problem that must be observable.\n // Uses a flat 2-arg helper (avoids curried `(phase) => (err) =>` nesting\n // which trips the sonarjs no-nested-functions depth rule).\n const reportLogFailure = (phase: string, err: unknown): void => {\n process.stderr.write(\n `[logixia] @LogMethod(${label}) ${phase} log failed: ${String(err)}\\n`\n );\n };\n\n if (logger) {\n // Use logLevel (extended method) rather than the NestJS interface debug/info\n // which only accepts (message: unknown, context?: string)\n const logFnRaw = (\n logger as unknown as Record<\n string,\n (msg: string, data?: Record<string, unknown>) => Promise<void>\n >\n )[level];\n const logFn = (typeof logFnRaw === 'function' ? logFnRaw : logger.debug).bind(logger);\n const entryPromise = (\n logFn as (msg: string, data?: Record<string, unknown>) => Promise<void>\n )(`→ ${label}`, entry);\n await entryPromise.catch((e: unknown) => reportLogFailure('entry', e));\n }\n\n try {\n const result = await (originalMethod.apply(this, args) as Promise<unknown>);\n\n const exit: Record<string, unknown> = {\n method: label,\n durationMs: Date.now() - start,\n };\n if (logResult) exit['result'] = result;\n\n if (logger) {\n const logFnRaw = (\n logger as unknown as Record<\n string,\n (msg: string, data?: Record<string, unknown>) => Promise<void>\n >\n )[level];\n const logFn = (typeof logFnRaw === 'function' ? logFnRaw : logger.debug).bind(logger);\n const exitPromise = (\n logFn as (msg: string, data?: Record<string, unknown>) => Promise<void>\n )(`← ${label}`, exit);\n await exitPromise.catch((e: unknown) => reportLogFailure('exit', e));\n }\n\n return result;\n } catch (error) {\n if (logger && logErrors) {\n const err = error instanceof Error ? error : new Error(String(error));\n // Use the structured overload (Record<string, unknown>) so we get\n // Promise<void> back and can attach a stderr fallback for transport\n // failures — otherwise they'd become unhandled rejections.\n const errLog: unknown = logger.error(err, {\n method: label,\n durationMs: Date.now() - start,\n });\n if (\n errLog !== undefined &&\n errLog !== null &&\n typeof (errLog as Promise<void>).catch === 'function'\n ) {\n (errLog as Promise<void>).catch((e: unknown) => reportLogFailure('error', e));\n }\n }\n throw error;\n }\n };\n\n return descriptor;\n };\n}\n\n// ── LogixiaExceptionFilter ───────────────────────────────────────────────────\n\n/**\n * Global NestJS exception filter that converts any exception into the standard\n * `LogixiaErrorResponse` wire format and logs it with full request context.\n *\n * Handles three exception types in priority order:\n * 1. `LogixiaException` — typed fields used directly\n * 2. NestJS `HttpException` — status + message extracted\n * 3. Unknown / plain Error — falls back to 500 `server_error`\n *\n * **Debug stripping in production:**\n * The `debug` block is automatically stripped when `NODE_ENV === 'production'`.\n *\n * **Trace ID headers:**\n * `X-Trace-ID` and `X-Request-ID` are echoed back on every error response so\n * clients can correlate with server logs.\n *\n * **Retry-After header:**\n * Automatically added for `429` responses (`Retry-After: 60`).\n *\n * Register in `main.ts`:\n * ```ts\n * const logger = app.get(LogixiaLoggerService);\n * app.useGlobalFilters(new LogixiaExceptionFilter(logger));\n * ```\n */\n@Catch()\nexport class LogixiaExceptionFilter implements ExceptionFilter {\n private readonly _logger: LogixiaLoggerService | undefined;\n private readonly _traceConfig: TraceIdConfig | undefined;\n\n constructor(\n @Optional()\n @Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`)\n logger?: LogixiaLoggerService,\n @Optional()\n @Inject(LOGIXIA_LOGGER_CONFIG)\n loggerConfig?: Partial<LoggerConfig>\n ) {\n // Prefer the injected logger; fall back to the global module logger so\n // `new LogixiaExceptionFilter()` (registered in main.ts before DI resolves)\n // still logs without needing an explicit logger argument.\n this._logger = logger ?? LogixiaLoggerModule._globalLogger ?? undefined;\n // Pick up the user-configured trace settings (response header name, etc.)\n // so the filter echoes the same header the middleware writes.\n this._traceConfig =\n typeof loggerConfig?.traceId === 'object' ? loggerConfig.traceId : undefined;\n }\n\n catch(exception: unknown, host: ArgumentsHost): void {\n const ctx = host.switchToHttp();\n\n const request = ctx.getRequest<{\n method?: string;\n url?: string;\n id?: string;\n startTime?: number;\n headers?: Record<string, string | string[] | undefined>;\n }>();\n\n interface MinimalResponse {\n status(code: number): MinimalResponse;\n json(body: unknown): void;\n setHeader(name: string, value: string): void;\n }\n const response = ctx.getResponse<MinimalResponse>();\n\n // ALS is the single source of truth (set by TraceMiddleware).\n // Fall back to header/request.id only if ALS has nothing (e.g. traceId disabled).\n const traceId =\n TraceContext.instance.getCurrentTraceId() ??\n (request.headers?.['x-trace-id'] as string | undefined) ??\n request.id ??\n undefined;\n\n const { response: errorResponse, httpStatus } = ErrorResponseBuilder.build({\n exception,\n traceId,\n path: request.url ?? '/',\n startTime: request.startTime,\n });\n\n // ── Logging ──────────────────────────────────────────────────────────────\n if (this._logger) {\n const requestMeta: Record<string, unknown> = {\n method: request.method ?? '',\n url: request.url ?? '',\n status: httpStatus,\n // Only include trace_id when it exists — keeps log records honest when\n // tracing is disabled (instead of writing `trace_id: undefined`).\n ...(errorResponse.meta.trace_id !== undefined\n ? { trace_id: errorResponse.meta.trace_id }\n : {}),\n };\n\n // `error()` / `warn()` return Promise<void> for the structured overload.\n // We cannot await inside a synchronous ExceptionFilter.catch(), so attach\n // a `.catch()` to prevent unhandledRejection if a transport fails — and\n // fall back to stderr so the error is never silently swallowed.\n const onLogFailure = (err: unknown): void => {\n process.stderr.write(\n `[logixia] ExceptionFilter failed to write log entry: ${String(err)}\\n`\n );\n };\n\n let logPromise: Promise<void> | void;\n if (httpStatus >= 500) {\n const err = exception instanceof Error ? exception : new Error(String(exception));\n logPromise = this._logger.error(err, requestMeta);\n } else if (isLogixiaException(exception)) {\n logPromise = this._logger.warn(\n `[${errorResponse.error.code}] ${errorResponse.error.message}`,\n requestMeta\n );\n } else {\n logPromise = this._logger.warn(\n `[${httpStatus}] ${errorResponse.error.message}`,\n requestMeta\n );\n }\n\n if (logPromise && typeof (logPromise as Promise<void>).catch === 'function') {\n (logPromise as Promise<void>).catch(onLogFailure);\n }\n }\n\n // ── Strip debug in production ─────────────────────────────────────────\n if (process.env['NODE_ENV'] === 'production') {\n delete errorResponse.debug;\n }\n\n // ── Response headers ──────────────────────────────────────────────────\n if (errorResponse.meta.trace_id) {\n const traceHeader = resolveResponseHeader(this._traceConfig);\n if (traceHeader) {\n response.setHeader(traceHeader, errorResponse.meta.trace_id);\n }\n }\n if (httpStatus === 429) {\n response.setHeader('Retry-After', '60');\n }\n\n response.status(httpStatus).json(errorResponse);\n }\n}\n","/**\n * JSON formatter for Logixia\n */\n\nimport type { ILogFormatter, LogEntry } from '../types';\nimport { serializeError } from '../utils/error.utils';\n\nexport class JsonFormatter implements ILogFormatter {\n private includeTimestamp: boolean;\n private includeLevel: boolean;\n private includeAppName: boolean;\n private includeTraceId: boolean;\n private includeContext: boolean;\n private prettyPrint: boolean;\n\n constructor(\n options: {\n includeTimestamp?: boolean;\n includeLevel?: boolean;\n includeAppName?: boolean;\n includeTraceId?: boolean;\n includeContext?: boolean;\n prettyPrint?: boolean;\n } = {}\n ) {\n this.includeTimestamp = options.includeTimestamp ?? true;\n this.includeLevel = options.includeLevel ?? true;\n this.includeAppName = options.includeAppName ?? true;\n this.includeTraceId = options.includeTraceId ?? true;\n this.includeContext = options.includeContext ?? true;\n this.prettyPrint = options.prettyPrint ?? false;\n }\n\n format(entry: LogEntry): string {\n const formatted: Record<string, unknown> = {};\n\n // Add timestamp\n if (this.includeTimestamp) {\n formatted.timestamp = entry.timestamp;\n }\n\n // Add log level\n if (this.includeLevel) {\n formatted.level = entry.level.toLowerCase();\n formatted.levelValue = entry.level;\n }\n\n // Add app name\n if (this.includeAppName) {\n formatted.appName = entry.appName;\n }\n\n // Add trace ID\n if (this.includeTraceId && entry.traceId) {\n formatted.traceId = entry.traceId;\n }\n\n // Add context\n if (this.includeContext && entry.context) {\n formatted.context = entry.context;\n }\n\n // Add message\n formatted.message = entry.message;\n\n // Add payload\n if (entry.payload && Object.keys(entry.payload).length > 0) {\n formatted.payload = this.serializePayload(entry.payload);\n }\n\n // Add error if present\n if (entry.error) {\n formatted.error = serializeError(entry.error);\n }\n\n // Add metadata\n formatted.meta = {\n pid: process.pid,\n hostname: process.env.HOSTNAME || 'unknown',\n version: process.version,\n };\n\n return this.prettyPrint ? JSON.stringify(formatted, null, 2) : JSON.stringify(formatted);\n }\n\n private serializePayload(payload: Record<string, unknown>): Record<string, unknown> {\n const serialized: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(payload)) {\n try {\n if (value instanceof Error) {\n serialized[key] = serializeError(value);\n } else if (value instanceof Date) {\n serialized[key] = value.toISOString();\n } else if (typeof value === 'function') {\n serialized[key] = '[Function]';\n } else if (typeof value === 'symbol') {\n serialized[key] = value.toString();\n } else if (value === undefined) {\n serialized[key] = null;\n } else {\n serialized[key] = value;\n }\n } catch {\n serialized[key] = '[Unserializable]';\n }\n }\n\n return serialized;\n }\n}\n","/**\n * Text formatter for Logixia\n */\n\nimport type { ILogFormatter, LogEntry } from '../types';\nimport { LogLevel } from '../types';\n\nexport class TextFormatter implements ILogFormatter {\n private colorize: boolean;\n private includeTimestamp: boolean;\n private includeAppName: boolean;\n private includeTraceId: boolean;\n private includeContext: boolean;\n private timestampFormat: 'iso' | 'locale' | 'short';\n private colors: Record<string, string>;\n\n constructor(\n options: {\n colorize?: boolean;\n includeTimestamp?: boolean;\n includeAppName?: boolean;\n includeTraceId?: boolean;\n includeContext?: boolean;\n timestampFormat?: 'iso' | 'locale' | 'short';\n colors?: Record<string, string>;\n } = {}\n ) {\n this.colorize = options.colorize ?? true;\n this.includeTimestamp = options.includeTimestamp ?? true;\n this.includeAppName = options.includeAppName ?? true;\n this.includeTraceId = options.includeTraceId ?? true;\n this.includeContext = options.includeContext ?? true;\n this.timestampFormat = options.timestampFormat ?? 'locale';\n this.colors = {\n error: '\\x1b[31m', // Red\n warn: '\\x1b[33m', // Yellow\n info: '\\x1b[32m', // Green\n debug: '\\x1b[34m', // Blue\n trace: '\\x1b[35m', // Magenta\n verbose: '\\x1b[36m', // Cyan\n reset: '\\x1b[0m', // Reset\n bold: '\\x1b[1m', // Bold\n dim: '\\x1b[2m', // Dim\n ...options.colors,\n };\n }\n\n format(entry: LogEntry): string {\n const parts: string[] = [];\n\n // Add timestamp\n if (this.includeTimestamp) {\n const timestamp = this.formatTimestamp(entry.timestamp);\n parts.push(this.colorize ? `${this.colors.dim}${timestamp}${this.colors.reset}` : timestamp);\n }\n\n // Add log level\n const levelName = entry.level.toLowerCase();\n const levelColor = this.colors[levelName] || this.colors.reset;\n const formattedLevel = this.colorize\n ? `${levelColor}${this.colors.bold}${levelName.toUpperCase().padEnd(5)}${this.colors.reset}`\n : levelName.toUpperCase().padEnd(5);\n parts.push(`[${formattedLevel}]`);\n\n // Add app name\n if (this.includeAppName) {\n const appName = this.colorize\n ? `${this.colors.bold}${entry.appName}${this.colors.reset}`\n : entry.appName;\n parts.push(`[${appName}]`);\n }\n\n // Add trace ID\n if (this.includeTraceId && entry.traceId) {\n const traceId = this.colorize\n ? `${this.colors.dim}${entry.traceId}${this.colors.reset}`\n : entry.traceId;\n parts.push(`[${traceId}]`);\n }\n\n // Add context\n if (this.includeContext && entry.context) {\n const context = this.colorize\n ? `${this.colors.cyan}${entry.context}${this.colors.reset}`\n : entry.context;\n parts.push(`[${context}]`);\n }\n\n // Add message\n const message =\n this.colorize && entry.level === LogLevel.ERROR\n ? `${this.colors.error}${entry.message}${this.colors.reset}`\n : entry.message;\n parts.push(message);\n\n // Add payload\n if (entry.payload && Object.keys(entry.payload).length > 0) {\n const payload = this.formatPayload(entry.payload);\n if (payload) {\n parts.push(this.colorize ? `${this.colors.dim}${payload}${this.colors.reset}` : payload);\n }\n }\n\n return parts.join(' ');\n }\n\n private formatTimestamp(timestamp: string): string {\n const date = new Date(timestamp);\n\n switch (this.timestampFormat) {\n case 'iso':\n return date.toISOString();\n case 'short':\n return date.toLocaleTimeString();\n case 'locale':\n default:\n return date.toLocaleString();\n }\n }\n\n private formatPayload(payload: Record<string, unknown>): string {\n try {\n // Handle simple objects\n if (Object.keys(payload).length === 1) {\n const entry = Object.entries(payload)[0];\n if (entry) {\n const [key, value] = entry;\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return `${key}=${value}`;\n }\n }\n }\n\n // Handle multiple properties or complex objects\n const formatted = Object.entries(payload)\n .map(([key, value]) => {\n if (value === null || value === undefined) {\n return `${key}=${value}`;\n }\n if (typeof value === 'string') {\n return `${key}=\"${value}\"`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return `${key}=${value}`;\n }\n if (value instanceof Date) {\n return `${key}=${value.toISOString()}`;\n }\n if (typeof value === 'object') {\n return `${key}=${JSON.stringify(value)}`;\n }\n return `${key}=${String(value)}`;\n })\n .join(' ');\n\n return formatted;\n } catch {\n return JSON.stringify(payload);\n }\n }\n\n /**\n * Create a formatter with preset configurations\n */\n static createSimple(): TextFormatter {\n return new TextFormatter({\n colorize: true,\n includeTimestamp: true,\n includeAppName: false,\n includeTraceId: false,\n includeContext: true,\n timestampFormat: 'short',\n });\n }\n\n static createDetailed(): TextFormatter {\n return new TextFormatter({\n colorize: true,\n includeTimestamp: true,\n includeAppName: true,\n includeTraceId: true,\n includeContext: true,\n timestampFormat: 'locale',\n });\n }\n\n static createMinimal(): TextFormatter {\n return new TextFormatter({\n colorize: false,\n includeTimestamp: false,\n includeAppName: false,\n includeTraceId: false,\n includeContext: false,\n });\n }\n}\n","/**\n * logixia — TypeScript typed log fields\n *\n * Solves the type-safety gap: standard `Record<string, unknown>` metadata gives\n * zero IDE autocomplete and lets typos slip silently into production logs.\n *\n * Two complementary utilities:\n *\n * 1. `createTypedLogger<TFields>()` — wraps any IBaseLogger so that the second\n * argument of every log method is constrained to `TFields` (a typed object).\n * Compile-time safety, zero runtime overhead.\n *\n * 2. `defineLogSchema<TFields>(schema)` — declares expected fields with optional\n * validators. In development (NODE_ENV !== 'production') every log call is\n * validated against the schema and a warning is emitted for missing required\n * fields or type mismatches.\n *\n * @example\n * ```ts\n * import { createTypedLogger, defineLogSchema } from 'logixia';\n *\n * interface OrderFields {\n * orderId: string;\n * userId: string;\n * amount?: number;\n * currency?: string;\n * }\n *\n * const schema = defineLogSchema<OrderFields>({\n * orderId: { type: 'string', required: true },\n * userId: { type: 'string', required: true },\n * amount: { type: 'number' },\n * currency: { type: 'string' },\n * });\n *\n * const orderLogger = createTypedLogger<OrderFields>(baseLogger, schema);\n * await orderLogger.info('Order created', { orderId: 'ord_123', userId: 'usr_456', amount: 99.99 });\n * // ^^^^ fully typed autocomplete ^^^^\n * ```\n */\n\nimport { internalWarn } from './internal-log';\n\n// ── Schema types ─────────────────────────────────────────────────────────────\n\nexport type LogFieldType = 'string' | 'number' | 'boolean' | 'object' | 'array';\n\nexport interface LogFieldDef {\n type: LogFieldType;\n /** Emit a warning when this field is missing from the log call. Default: false */\n required?: boolean;\n /** Custom validator — return a string to emit it as a warning message. */\n validate?: (value: unknown) => string | undefined;\n}\n\nexport type LogSchema<TFields extends Record<string, unknown>> = {\n [K in keyof TFields]: LogFieldDef;\n};\n\nexport interface CompiledSchema<TFields extends Record<string, unknown>> {\n readonly fields: LogSchema<TFields>;\n /**\n * Validate a payload against the schema.\n * Returns an array of warning strings (empty = pass).\n * Only runs in non-production environments.\n */\n validate(payload: Partial<TFields>): string[];\n}\n\n// ── defineLogSchema ──────────────────────────────────────────────────────────\n\n/**\n * Define a typed schema for a category of log entries.\n *\n * Call this once at module initialisation and pass it to `createTypedLogger`.\n * In development, every log call is validated against the schema.\n */\nexport function defineLogSchema<TFields extends Record<string, unknown>>(\n fields: LogSchema<TFields>\n): CompiledSchema<TFields> {\n return {\n fields,\n validate(payload: Partial<TFields>): string[] {\n if (process.env['NODE_ENV'] === 'production') return [];\n\n const warnings: string[] = [];\n\n for (const [key, def] of Object.entries(fields) as [keyof TFields & string, LogFieldDef][]) {\n const value = payload[key];\n\n if (def.required && (value === undefined || value === null)) {\n warnings.push(`Required field \"${key}\" is missing`);\n continue;\n }\n\n if (value !== undefined && value !== null) {\n const actualType = Array.isArray(value) ? 'array' : typeof value;\n if (actualType !== def.type) {\n warnings.push(`Field \"${key}\" expected type \"${def.type}\" but got \"${actualType}\"`);\n }\n\n if (def.validate) {\n const msg = def.validate(value);\n if (msg) warnings.push(`Field \"${key}\": ${msg}`);\n }\n }\n }\n\n return warnings;\n },\n };\n}\n\n// ── TypedLogger ──────────────────────────────────────────────────────────────\n\n/** IBaseLogger-compatible subset used by TypedLogger */\nexport interface LoggerLike {\n error(message: string | Error, data?: Record<string, unknown>): Promise<void>;\n warn(message: string, data?: Record<string, unknown>): Promise<void>;\n info(message: string, data?: Record<string, unknown>): Promise<void>;\n debug(message: string, data?: Record<string, unknown>): Promise<void>;\n verbose?(message: string, data?: Record<string, unknown>): Promise<void>;\n trace?(message: string, data?: Record<string, unknown>): Promise<void>;\n}\n\n/**\n * A logger whose metadata is typed to `TFields`.\n *\n * The `error` overload still accepts a plain `Error` object as the first arg\n * (with optional `TFields` data) so the typed logger remains a drop-in replacement.\n */\nexport interface TypedLogger<TFields extends Record<string, unknown>> {\n error(error: Error, data?: Partial<TFields>): Promise<void>;\n error(message: string, data?: Partial<TFields>): Promise<void>;\n warn(message: string, data?: Partial<TFields>): Promise<void>;\n info(message: string, data?: Partial<TFields>): Promise<void>;\n debug(message: string, data?: Partial<TFields>): Promise<void>;\n verbose(message: string, data?: Partial<TFields>): Promise<void>;\n trace(message: string, data?: Partial<TFields>): Promise<void>;\n /** Access the underlying untyped logger if needed. */\n readonly raw: LoggerLike;\n}\n\n/**\n * Wrap any logixia logger with a type-safe field interface.\n *\n * @param logger Any object that implements `IBaseLogger` (e.g. the result of `createLogger()`)\n * @param schema Optional schema for dev-time validation. Created with `defineLogSchema()`.\n */\nexport function createTypedLogger<TFields extends Record<string, unknown>>(\n logger: LoggerLike,\n schema?: CompiledSchema<TFields>\n): TypedLogger<TFields> {\n function withValidation(\n level: string,\n fn: (msg: string, data?: Record<string, unknown>) => Promise<void>,\n message: string,\n data?: Partial<TFields>\n ): Promise<void> {\n if (schema && data) {\n const warnings = schema.validate(data);\n for (const w of warnings) {\n internalWarn(`[logixia/schema] ${w} — level=${level} message=\"${message}\"`);\n }\n }\n return fn(message, data as Record<string, unknown> | undefined);\n }\n\n return {\n raw: logger,\n error(messageOrError: string | Error, data?: Partial<TFields>): Promise<void> {\n return logger.error(messageOrError as string, data as Record<string, unknown> | undefined);\n },\n warn: (m, d) => withValidation('warn', logger.warn.bind(logger), m, d),\n info: (m, d) => withValidation('info', logger.info.bind(logger), m, d),\n debug: (m, d) => withValidation('debug', logger.debug.bind(logger), m, d),\n verbose: (m, d) =>\n withValidation('verbose', (logger.verbose ?? logger.debug).bind(logger), m, d),\n trace: (m, d) => withValidation('trace', (logger.trace ?? logger.debug).bind(logger), m, d),\n };\n}\n","/**\n * logixia — Metrics extraction → Prometheus\n *\n * Automatically extracts metrics from structured log fields and exposes them\n * in the Prometheus text exposition format (version 0.0.4).\n * No external dependency — the format is fully self-contained.\n *\n * Supported metric types:\n * - `counter` — incremented on each matching log entry\n * - `histogram` — observes a numeric payload field per entry\n * - `gauge` — tracks the most recent numeric value of a payload field\n *\n * Usage:\n * ```ts\n * import { createMetricsPlugin } from 'logixia';\n *\n * const metrics = createMetricsPlugin({\n * http_request_duration: {\n * type: 'histogram',\n * field: 'duration',\n * labels: ['method', 'statusCode'],\n * help: 'HTTP request duration in milliseconds',\n * },\n * error_count: {\n * type: 'counter',\n * levelFilter: 'error',\n * labels: ['context'],\n * help: 'Total error log entries',\n * },\n * active_connections: {\n * type: 'gauge',\n * field: 'connections',\n * help: 'Current active connection count',\n * },\n * });\n *\n * logger.use(metrics); // start collecting\n * app.get('/metrics', metrics.expressHandler()); // expose for Prometheus scrape\n * ```\n *\n * All metric names are automatically prefixed with `logixia_`.\n * Output follows https://prometheus.io/docs/instrumenting/exposition_formats/\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport type { LogixiaPlugin } from './plugin';\nimport type { LogEntry } from './types/index';\n\n// ── Metric config types ───────────────────────────────────────────────────────\n\n/**\n * Increment a counter on each matching log entry.\n *\n * @example Count every error entry, labelled by context:\n * ```ts\n * error_count: { type: 'counter', levelFilter: 'error', labels: ['context'] }\n * ```\n *\n * @example Count entries where payload.event === 'checkout':\n * ```ts\n * checkout_events: { type: 'counter', field: 'event', value: 'checkout' }\n * ```\n */\nexport interface CounterConfig {\n type: 'counter';\n /** Only increment when `entry.level` equals this value. Omit to count all entries. */\n levelFilter?: string;\n /**\n * Only increment when `entry.payload[field] === value`.\n * If omitted, every entry (matching `levelFilter`) is counted.\n */\n field?: string;\n value?: unknown;\n /** `entry.payload` fields used as Prometheus label dimensions. `'level'` is also valid. */\n labels?: string[];\n help?: string;\n}\n\n/**\n * Observe a numeric payload field and bucket it into a Prometheus histogram.\n *\n * @example Duration histogram labelled by HTTP method and status code:\n * ```ts\n * http_request_duration: {\n * type: 'histogram',\n * field: 'duration',\n * labels: ['method', 'statusCode'],\n * buckets: [10, 25, 50, 100, 250, 500, 1000],\n * }\n * ```\n */\nexport interface HistogramConfig {\n type: 'histogram';\n /** The `entry.payload` field containing the numeric value to observe. */\n field: string;\n /** `entry.payload` fields used as Prometheus label dimensions. */\n labels?: string[];\n help?: string;\n /**\n * Bucket upper bounds (inclusive). Sorted automatically.\n * Default: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000]\n */\n buckets?: number[];\n}\n\n/**\n * Track the most recent numeric value of a payload field as a gauge.\n *\n * @example Track live connection count:\n * ```ts\n * active_connections: { type: 'gauge', field: 'connections' }\n * ```\n */\nexport interface GaugeConfig {\n type: 'gauge';\n /** The `entry.payload` field containing the numeric value. */\n field: string;\n /** `entry.payload` fields used as Prometheus label dimensions. */\n labels?: string[];\n help?: string;\n}\n\nexport type MetricConfig = CounterConfig | HistogramConfig | GaugeConfig;\nexport type MetricsMap = Record<string, MetricConfig>;\n\n// ── Internal metric state ─────────────────────────────────────────────────────\n\ninterface CounterState {\n type: 'counter';\n values: Map<string, number>;\n}\n\ninterface HistogramState {\n type: 'histogram';\n buckets: number[];\n /** Parallel arrays; index = bucket index; last entry = +Inf cumulative count */\n counts: Map<string, number[]>;\n sums: Map<string, number>;\n observations: Map<string, number>;\n}\n\ninterface GaugeState {\n type: 'gauge';\n values: Map<string, number>;\n}\n\ntype MetricState = CounterState | HistogramState | GaugeState;\n\n// ── Defaults ──────────────────────────────────────────────────────────────────\n\nconst DEFAULT_BUCKETS: readonly number[] = [\n 1, 5, 10, 25, 50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000,\n];\n\n// ── Label helpers ─────────────────────────────────────────────────────────────\n\nfunction buildLabelKey(config: MetricConfig, entry: LogEntry): string {\n const labelNames = config.labels ?? [];\n if (labelNames.length === 0) return '{}';\n const pairs: Record<string, string> = {};\n const payload = entry.payload ?? {};\n for (const name of labelNames) {\n const raw = name === 'level' ? entry.level : payload[name];\n pairs[name] = raw !== undefined && raw !== null ? String(raw) : '';\n }\n return JSON.stringify(pairs);\n}\n\nfunction renderLabels(labelKey: string): string {\n if (labelKey === '{}') return '';\n const obj = JSON.parse(labelKey) as Record<string, string>;\n const parts = Object.entries(obj).map(([k, v]) => `${k}=\"${escapeLabel(v)}\"`);\n return `{${parts.join(',')}}`;\n}\n\nfunction escapeLabel(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n');\n}\n\n// ── MetricsPlugin ─────────────────────────────────────────────────────────────\n\n/**\n * A logixia plugin that extracts Prometheus-compatible metrics from log entries.\n *\n * Implements `LogixiaPlugin` — pass directly to `logger.use()`:\n * ```ts\n * const metrics = new MetricsPlugin({ ... });\n * logger.use(metrics);\n * ```\n *\n * Or use the `createMetricsPlugin()` factory (preferred):\n * ```ts\n * const metrics = createMetricsPlugin({ ... });\n * logger.use(metrics);\n * ```\n */\nexport class MetricsPlugin implements LogixiaPlugin {\n public readonly name = 'logixia-metrics';\n\n private readonly map: MetricsMap;\n private readonly metricState = new Map<string, MetricState>();\n\n constructor(map: MetricsMap) {\n this.map = map;\n this.initAllState();\n }\n\n // ── LogixiaPlugin lifecycle ────────────────────────────────────────────────\n\n onInit(): void {\n // State is initialised in the constructor; nothing extra needed here.\n }\n\n onLog(entry: LogEntry): LogEntry {\n const payload = entry.payload ?? {};\n\n for (const [rawName, config] of Object.entries(this.map)) {\n const state = this.metricState.get(rawName);\n if (!state) continue;\n\n const labelKey = buildLabelKey(config, entry);\n\n if (config.type === 'counter' && state.type === 'counter') {\n // Level filter\n if (config.levelFilter && entry.level !== config.levelFilter) continue;\n // Field/value filter\n if (config.field !== undefined && payload[config.field] !== config.value) continue;\n state.values.set(labelKey, (state.values.get(labelKey) ?? 0) + 1);\n } else if (config.type === 'histogram' && state.type === 'histogram') {\n const raw = payload[config.field];\n if (raw === undefined || raw === null) continue;\n const val = Number(raw);\n if (Number.isNaN(val)) continue;\n\n // Initialise per-label arrays on first observation\n if (!state.counts.has(labelKey)) {\n state.counts.set(\n labelKey,\n Array.from<number>({ length: state.buckets.length + 1 }).fill(0)\n );\n state.sums.set(labelKey, 0);\n state.observations.set(labelKey, 0);\n }\n\n const bucketArr = state.counts.get(labelKey)!;\n for (let i = 0; i < state.buckets.length; i++) {\n if (val <= state.buckets[i]!) bucketArr[i]!++;\n }\n // The +Inf bucket (last slot) always increments\n bucketArr[state.buckets.length]!++;\n state.sums.set(labelKey, (state.sums.get(labelKey) ?? 0) + val);\n state.observations.set(labelKey, (state.observations.get(labelKey) ?? 0) + 1);\n } else if (config.type === 'gauge' && state.type === 'gauge') {\n const raw = payload[config.field];\n if (raw === undefined || raw === null) continue;\n const val = Number(raw);\n if (Number.isNaN(val)) continue;\n state.values.set(labelKey, val);\n }\n }\n\n // Always pass the entry through unchanged\n return entry;\n }\n\n // ── Output ─────────────────────────────────────────────────────────────────\n\n /**\n * Render all registered metrics in the Prometheus text exposition format\n * (version 0.0.4).\n *\n * All metric names are prefixed with `logixia_`.\n *\n * @example\n * ```\n * # HELP logixia_error_count Total error log entries\n * # TYPE logixia_error_count counter\n * logixia_error_count{context=\"OrderService\"} 7\n * ```\n */\n render(): string {\n const lines: string[] = [];\n\n for (const [rawName, config] of Object.entries(this.map)) {\n const metricName = `logixia_${rawName}`;\n const state = this.metricState.get(rawName);\n if (!state) continue;\n\n const helpText = config.help ?? rawName.replace(/_/g, ' ');\n lines.push(`# HELP ${metricName} ${helpText}`);\n lines.push(`# TYPE ${metricName} ${config.type}`);\n\n if (state.type === 'counter') {\n if (state.values.size === 0) {\n lines.push(`${metricName} 0`);\n } else {\n for (const [labelKey, count] of state.values) {\n lines.push(`${metricName}${renderLabels(labelKey)} ${count}`);\n }\n }\n } else if (state.type === 'histogram') {\n for (const [labelKey, bucketCounts] of state.counts) {\n const labelSuffix = renderLabels(labelKey);\n const baseObj = labelKey === '{}' ? {} : (JSON.parse(labelKey) as Record<string, string>);\n\n // One line per finite bucket\n for (let i = 0; i < state.buckets.length; i++) {\n const leKey = JSON.stringify({ ...baseObj, le: String(state.buckets[i]) });\n lines.push(`${metricName}_bucket${renderLabels(leKey)} ${bucketCounts[i] ?? 0}`);\n }\n // +Inf bucket\n const infKey = JSON.stringify({ ...baseObj, le: '+Inf' });\n lines.push(\n `${metricName}_bucket${renderLabels(infKey)} ${bucketCounts[state.buckets.length] ?? 0}`\n );\n lines.push(`${metricName}_sum${labelSuffix} ${state.sums.get(labelKey) ?? 0}`);\n lines.push(`${metricName}_count${labelSuffix} ${state.observations.get(labelKey) ?? 0}`);\n }\n } else if (state.type === 'gauge') {\n if (state.values.size === 0) {\n lines.push(`${metricName} 0`);\n } else {\n for (const [labelKey, val] of state.values) {\n lines.push(`${metricName}${renderLabels(labelKey)} ${val}`);\n }\n }\n }\n }\n\n return `${lines.join('\\n')}\\n`;\n }\n\n /**\n * Reset all metric counters and observations back to zero.\n * Useful between test runs or on a scheduled reset interval.\n */\n reset(): void {\n this.metricState.clear();\n this.initAllState();\n }\n\n /**\n * Express route handler — call `app.get('/metrics', metrics.expressHandler())`.\n *\n * @example\n * ```ts\n * import express from 'express';\n * const app = express();\n * app.get('/metrics', metrics.expressHandler());\n * ```\n */\n expressHandler(): (\n req: unknown,\n res: { set(k: string, v: string): unknown; end(body: string): void }\n ) => void {\n return (_req, res) => {\n res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');\n res.end(this.render());\n };\n }\n\n /**\n * Raw Node.js `http` server handler.\n * Responds to `GET /metrics` with the Prometheus text payload.\n *\n * @example Start a dedicated metrics server on the standard port:\n * ```ts\n * import http from 'node:http';\n * const server = http.createServer(metrics.httpHandler());\n * server.listen(9464); // Prometheus default port for custom exporters\n * ```\n */\n httpHandler(): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n const isMetricsPath = req.url === '/metrics' || req.url === '/metrics/';\n if (!isMetricsPath) {\n res.writeHead(404).end('Not found');\n return;\n }\n const body = this.render();\n res.writeHead(200, {\n 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n });\n res.end(body);\n };\n }\n\n // ── Private helpers ────────────────────────────────────────────────────────\n\n private initAllState(): void {\n for (const [rawName, config] of Object.entries(this.map)) {\n this.initSingleState(rawName, config);\n }\n }\n\n private initSingleState(rawName: string, config: MetricConfig): void {\n if (config.type === 'counter') {\n this.metricState.set(rawName, { type: 'counter', values: new Map() });\n } else if (config.type === 'histogram') {\n const buckets = [...(config.buckets ?? DEFAULT_BUCKETS)].sort((a, b) => a - b);\n this.metricState.set(rawName, {\n type: 'histogram',\n buckets,\n counts: new Map(),\n sums: new Map(),\n observations: new Map(),\n });\n } else {\n this.metricState.set(rawName, { type: 'gauge', values: new Map() });\n }\n }\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\n/**\n * Create a `MetricsPlugin` from a metrics map and return it ready for\n * `logger.use()`.\n *\n * @example\n * ```ts\n * import { createMetricsPlugin } from 'logixia';\n *\n * const metrics = createMetricsPlugin({\n * http_request_duration: {\n * type: 'histogram',\n * field: 'duration',\n * labels: ['method', 'statusCode'],\n * help: 'HTTP request duration in milliseconds',\n * },\n * error_count: {\n * type: 'counter',\n * levelFilter: 'error',\n * labels: ['context'],\n * help: 'Total error log entries',\n * },\n * });\n *\n * logger.use(metrics);\n * app.get('/metrics', metrics.expressHandler());\n * ```\n */\nexport function createMetricsPlugin(map: MetricsMap): MetricsPlugin {\n return new MetricsPlugin(map);\n}\n","/**\n * Logixia - Advanced TypeScript Logger\n *\n * A comprehensive logging library with support for:\n * - Multiple output formats (console, file, JSON)\n * - Trace ID tracking\n * - Performance monitoring\n * - NestJS integration\n * - Customizable log levels and colors\n * - Intelligent log search and aggregation\n * - Natural language query processing\n * - Pattern recognition and anomaly detection\n */\n\nimport { createLogger as createLoggerFromCore, LogixiaLogger } from './core/logitron-logger';\nimport { LogixiaLoggerService } from './core/logitron-nestjs.service';\nimport type { Environment, LogColor, LoggerConfig } from './types';\nimport { LogLevel } from './types';\n\n// Type exports\nexport * from './core/logitron-logger.module';\nexport * from './core/logitron-nestjs.service';\nexport type { LogMethodOptions } from './core/nestjs-extras';\nexport { InjectLogger, LogixiaExceptionFilter, LogMethod } from './core/nestjs-extras';\nexport * from './formatters';\nexport * from './types';\nexport * from './utils/error.utils';\nexport type { OtelBridgeOptions, OtelSpanContext } from './utils/otel';\nexport {\n disableOtelBridge,\n getActiveOtelContext,\n getOtelMetaFields,\n initOtelBridge,\n} from './utils/otel';\nexport { applyRedaction, redactObject } from './utils/redact.utils';\nexport * from './utils/shutdown.utils';\nexport * from './utils/trace.utils';\nexport type {\n CompiledSchema,\n LogFieldDef,\n LogFieldType,\n LoggerLike,\n LogSchema,\n TypedLogger,\n} from './utils/typed-logger';\nexport { createTypedLogger, defineLogSchema } from './utils/typed-logger';\n\n// Search module exports\nexport * from './search';\n\n// Context propagation (AsyncLocalStorage)\nexport type { LogContext } from './context/async-context';\nexport {\n createExpressContextMiddleware,\n createFastifyContextHook,\n LogixiaContext,\n} from './context/async-context';\n\n// Sampling stats (SamplingConfig is already exported via ./types)\nexport type { SamplingStats } from './utils/sampling.utils';\n\n// Plugin API (Feature 20)\nexport type { LogixiaPlugin } from './plugin';\nexport { globalPluginRegistry, PluginRegistry, usePlugin } from './plugin';\n\n// Exception system — typed LogixiaException + unified error response format\nexport type {\n BuildParams,\n ErrorDetail,\n LogixiaErrorResponse,\n LogixiaExceptionOptions,\n} from './exceptions';\nexport {\n ErrorResponseBuilder,\n generateRequestId,\n generateTraceId,\n isLogixiaException,\n LogixiaException,\n} from './exceptions';\n\n// Metrics extraction → Prometheus (Feature 21)\nexport type {\n CounterConfig,\n GaugeConfig,\n HistogramConfig,\n MetricConfig,\n MetricsMap,\n} from './metrics';\nexport { createMetricsPlugin, MetricsPlugin } from './metrics';\n\n// Core exports\nexport { DEFAULT_CONFIG, LogixiaLogger, LogixiaLoggerService };\n\n/**\n * Default configuration for Logixia logger\n */\nconst DEFAULT_CONFIG = {\n appName: 'App',\n environment: 'development' as Environment,\n traceId: true,\n format: {\n timestamp: true,\n colorize: true,\n json: false,\n },\n silent: false,\n levelOptions: {\n level: LogLevel.INFO,\n levels: {\n [LogLevel.ERROR]: 0,\n [LogLevel.WARN]: 1,\n [LogLevel.INFO]: 2,\n [LogLevel.DEBUG]: 3,\n [LogLevel.TRACE]: 4,\n [LogLevel.VERBOSE]: 5,\n },\n colors: {\n [LogLevel.ERROR]: 'red',\n [LogLevel.WARN]: 'yellow',\n [LogLevel.INFO]: 'blue',\n [LogLevel.DEBUG]: 'green',\n [LogLevel.TRACE]: 'gray',\n [LogLevel.VERBOSE]: 'cyan',\n } as Record<string, LogColor>,\n },\n fields: {\n timestamp: true,\n level: true,\n appName: true,\n traceId: true,\n message: true,\n payload: true,\n timeTaken: true,\n },\n outputs: ['console'],\n};\n\n/**\n * Create a new Logixia logger instance with TypeScript support for custom levels\n * @param config - Logger configuration\n * @returns Typed logger instance\n */\nexport const createLogger = createLoggerFromCore;\n\n/**\n * Create a new Logixia logger service for NestJS\n * @param config - Logger configuration\n * @returns LogixiaLoggerService instance\n */\nexport function createLoggerService(config?: Partial<LoggerConfig>): LogixiaLoggerService {\n return new LogixiaLoggerService({ ...DEFAULT_CONFIG, ...config });\n}\n\n/**\n * Default logger instance\n */\nexport const logger = new LogixiaLogger(DEFAULT_CONFIG);\n\n/**\n * Export default configuration for reference\n */\n"],"mappings":";;;;;;AA4IA,IAAa,mBAAb,cAGU,MAAM;CAkBd,YAAY,SAAgD;AAG1D,QAAM,QAAQ,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;AAEhD,OAAK,OAAO;AACZ,OAAK,YAAY,QAAQ;AACzB,OAAK,YAAY,QAAQ;AACzB,OAAK,aAAa,QAAQ;AAC1B,OAAK,QAAQ,QAAQ;AACrB,OAAK,UAAU,QAAQ;AACvB,OAAK,SAAS,QAAQ;AACtB,OAAK,WAAW,QAAQ;AAGxB,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;;;;;;;;;;;;AAmBrD,SAAgB,mBACd,OACyC;AACzC,QAAO,iBAAiB;;;;;;;;;;;;;;AC/I1B,SAAgB,kBAA0B;AACxC,QAAO,aAAa,SAAS,UAAU;;;AAIzC,MAAa,oBAAoB;;;;;AAMjC,SAAS,iBAAiB,QAAwB;AAChD,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,WAAW,IAAK,QAAO;AAC3B,KAAI,UAAU,IAAK,QAAO;AAC1B,KAAI,UAAU,IAAK,QAAO;AAC1B,QAAO;;;;;;AAOT,SAAS,gBACP,OAC2E;AAC3E,Q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