logixia 1.13.3 → 2.0.4

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 (229) hide show
  1. package/README.md +117 -44
  2. package/dist/async-context-B05ArHgM.mjs +134 -0
  3. package/dist/async-context-B05ArHgM.mjs.map +1 -0
  4. package/dist/async-context-DTQgi8f7.js +150 -0
  5. package/dist/async-context-DTQgi8f7.js.map +1 -0
  6. package/dist/{azure-monitor.transport-CHnjVRF-.mjs → azure-monitor.transport-BPbgjATu.mjs} +27 -15
  7. package/dist/azure-monitor.transport-BPbgjATu.mjs.map +1 -0
  8. package/dist/{azure-monitor.transport-BDFO4F-i.d.ts → azure-monitor.transport-C7kYyZUW.d.mts} +3 -6
  9. package/dist/azure-monitor.transport-C7kYyZUW.d.mts.map +1 -0
  10. package/dist/{azure-monitor.transport-CrvfHd9C.js → azure-monitor.transport-CwbOLZHB.js} +32 -20
  11. package/dist/azure-monitor.transport-CwbOLZHB.js.map +1 -0
  12. package/dist/{azure-monitor.transport-D5wQEH04.d.mts → azure-monitor.transport-DV03Z5P4.d.ts} +3 -6
  13. package/dist/azure-monitor.transport-DV03Z5P4.d.ts.map +1 -0
  14. package/dist/azure.d.mts +1 -2
  15. package/dist/azure.d.ts +1 -2
  16. package/dist/azure.js +3 -6
  17. package/dist/azure.mjs +1 -6
  18. package/dist/{batch-buffer-PGvSgbmd.mjs → batch-buffer-0fgLmIPn.mjs} +21 -7
  19. package/dist/batch-buffer-0fgLmIPn.mjs.map +1 -0
  20. package/dist/{batch-buffer-BY-mRWIK.js → batch-buffer-DT4gdXmf.js} +53 -40
  21. package/dist/batch-buffer-DT4gdXmf.js.map +1 -0
  22. package/dist/browser.d.mts +52 -23
  23. package/dist/browser.d.mts.map +1 -1
  24. package/dist/browser.d.ts +52 -23
  25. package/dist/browser.d.ts.map +1 -1
  26. package/dist/browser.js +460 -62
  27. package/dist/browser.js.map +1 -1
  28. package/dist/browser.mjs +461 -65
  29. package/dist/browser.mjs.map +1 -1
  30. package/dist/{nestjs-extras-ImbuDhs1.mjs → builder-D70z6kjj.mjs} +279 -965
  31. package/dist/builder-D70z6kjj.mjs.map +1 -0
  32. package/dist/{nestjs-extras-DnJ6vrIC.js → builder-M7NoaugM.js} +421 -1177
  33. package/dist/builder-M7NoaugM.js.map +1 -0
  34. package/dist/cli/index.js +86 -67
  35. package/dist/cloudwatch.d.mts +1 -2
  36. package/dist/cloudwatch.d.ts +1 -2
  37. package/dist/cloudwatch.js +3 -7
  38. package/dist/cloudwatch.mjs +1 -7
  39. package/dist/{cloudwatch.transport-BO1ahxw-.js → cloudwatch.transport-B2wKQFF7.js} +61 -36
  40. package/dist/cloudwatch.transport-B2wKQFF7.js.map +1 -0
  41. package/dist/{cloudwatch.transport-DZ6ies7g.mjs → cloudwatch.transport-BTvYfLs9.mjs} +54 -28
  42. package/dist/cloudwatch.transport-BTvYfLs9.mjs.map +1 -0
  43. package/dist/{cloudwatch.transport-B00st6Xv.d.ts → cloudwatch.transport-Bf7L4I59.d.ts} +2 -6
  44. package/dist/cloudwatch.transport-Bf7L4I59.d.ts.map +1 -0
  45. package/dist/{cloudwatch.transport-Blc7Gtxt.d.mts → cloudwatch.transport-Rj4yTpRn.d.mts} +2 -6
  46. package/dist/cloudwatch.transport-Rj4yTpRn.d.mts.map +1 -0
  47. package/dist/{coerce.utils-Cu6IUTgX.mjs → coerce.utils-B_rEudCn.mjs} +3 -4
  48. package/dist/{coerce.utils-Cu6IUTgX.mjs.map → coerce.utils-B_rEudCn.mjs.map} +1 -1
  49. package/dist/{coerce.utils-B-LilukN.js → coerce.utils-C1C5sIX0.js} +8 -10
  50. package/dist/{coerce.utils-B-LilukN.js.map → coerce.utils-C1C5sIX0.js.map} +1 -1
  51. package/dist/correlation.d.mts +13 -16
  52. package/dist/correlation.d.mts.map +1 -1
  53. package/dist/correlation.d.ts +13 -16
  54. package/dist/correlation.d.ts.map +1 -1
  55. package/dist/correlation.js +58 -9
  56. package/dist/correlation.js.map +1 -1
  57. package/dist/correlation.mjs +56 -6
  58. package/dist/correlation.mjs.map +1 -1
  59. package/dist/{entry-fields-BJkuPnIg.mjs → entry-fields-CGuvT2R0.mjs} +5 -6
  60. package/dist/entry-fields-CGuvT2R0.mjs.map +1 -0
  61. package/dist/{entry-fields-BvOLFlJ4.js → entry-fields-RLd1jCoR.js} +10 -12
  62. package/dist/entry-fields-RLd1jCoR.js.map +1 -0
  63. package/dist/gcp.d.mts +1 -2
  64. package/dist/gcp.d.ts +1 -2
  65. package/dist/gcp.js +3 -7
  66. package/dist/gcp.mjs +1 -7
  67. package/dist/{gcp.transport-m4fVw0b1.d.ts → gcp.transport-C5D72b1g.d.mts} +3 -6
  68. package/dist/gcp.transport-C5D72b1g.d.mts.map +1 -0
  69. package/dist/{gcp.transport-zzNyIoih.d.mts → gcp.transport-CFQfdAOK.d.ts} +3 -6
  70. package/dist/gcp.transport-CFQfdAOK.d.ts.map +1 -0
  71. package/dist/{gcp.transport-DBX5TPIy.mjs → gcp.transport-CGKopAhQ.mjs} +55 -16
  72. package/dist/gcp.transport-CGKopAhQ.mjs.map +1 -0
  73. package/dist/{gcp.transport-CHV8MGgz.js → gcp.transport-KZe9hCAR.js} +60 -22
  74. package/dist/gcp.transport-KZe9hCAR.js.map +1 -0
  75. package/dist/{index-nZEeCr3X.d.ts → index-DwozbmB4.d.ts} +3 -8
  76. package/dist/index-DwozbmB4.d.ts.map +1 -0
  77. package/dist/{index-BPwEisy4.d.mts → index-xqaJtAZn.d.mts} +3 -8
  78. package/dist/index-xqaJtAZn.d.mts.map +1 -0
  79. package/dist/index.d.mts +141 -203
  80. package/dist/index.d.mts.map +1 -1
  81. package/dist/index.d.ts +140 -202
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +196 -381
  84. package/dist/index.js.map +1 -1
  85. package/dist/index.mjs +145 -294
  86. package/dist/index.mjs.map +1 -1
  87. package/dist/internal-log-b0Vp4qrB.js +183 -0
  88. package/dist/internal-log-b0Vp4qrB.js.map +1 -0
  89. package/dist/internal-log-uCSd1PMc.mjs +142 -0
  90. package/dist/internal-log-uCSd1PMc.mjs.map +1 -0
  91. package/dist/logitron-logger-D2B75Oc7.d.ts +365 -0
  92. package/dist/logitron-logger-D2B75Oc7.d.ts.map +1 -0
  93. package/dist/logitron-logger-oEd6wNhf.d.mts +365 -0
  94. package/dist/logitron-logger-oEd6wNhf.d.mts.map +1 -0
  95. package/dist/middleware.d.mts +10 -12
  96. package/dist/middleware.d.mts.map +1 -1
  97. package/dist/middleware.d.ts +10 -12
  98. package/dist/middleware.d.ts.map +1 -1
  99. package/dist/middleware.js +16 -47
  100. package/dist/middleware.js.map +1 -1
  101. package/dist/middleware.mjs +13 -45
  102. package/dist/middleware.mjs.map +1 -1
  103. package/dist/nest.d.mts +467 -10
  104. package/dist/nest.d.mts.map +1 -1
  105. package/dist/nest.d.ts +467 -10
  106. package/dist/nest.d.ts.map +1 -1
  107. package/dist/nest.js +889 -43
  108. package/dist/nest.js.map +1 -0
  109. package/dist/nest.mjs +850 -9
  110. package/dist/nest.mjs.map +1 -0
  111. package/dist/{trace.utils-CvXgaiQT.mjs → request-trace-C_fvIDv4.mjs} +44 -9
  112. package/dist/request-trace-C_fvIDv4.mjs.map +1 -0
  113. package/dist/{trace.utils-DpBOLDtq.js → request-trace-wTJdKp6-.js} +121 -77
  114. package/dist/request-trace-wTJdKp6-.js.map +1 -0
  115. package/dist/rolldown-runtime-D3PmRqjj.mjs +4 -0
  116. package/dist/{safe-stringify-DJ66tW5I.mjs → safe-stringify-BMRl3EX3.mjs} +3 -4
  117. package/dist/safe-stringify-BMRl3EX3.mjs.map +1 -0
  118. package/dist/{safe-stringify-DWo3aZp_.js → safe-stringify-DLz1Kz3o.js} +23 -25
  119. package/dist/safe-stringify-DLz1Kz3o.js.map +1 -0
  120. package/dist/{search-CHUZPl0h.d.ts → search-BH33XhuU.d.mts} +2 -22
  121. package/dist/search-BH33XhuU.d.mts.map +1 -0
  122. package/dist/{search-DjXSn6v5.mjs → search-CWMVYC-R.mjs} +34 -41
  123. package/dist/search-CWMVYC-R.mjs.map +1 -0
  124. package/dist/{search-BfBzDIT9.d.mts → search-CazwyX5Z.d.ts} +2 -22
  125. package/dist/search-CazwyX5Z.d.ts.map +1 -0
  126. package/dist/{search-B0MH1SJJ.js → search-DUfWuzFP.js} +64 -71
  127. package/dist/search-DUfWuzFP.js.map +1 -0
  128. package/dist/search.d.mts +2 -4
  129. package/dist/search.d.ts +2 -4
  130. package/dist/search.js +3 -4
  131. package/dist/search.mjs +1 -4
  132. package/dist/secret-config-BegMLkYl.mjs +209 -0
  133. package/dist/secret-config-BegMLkYl.mjs.map +1 -0
  134. package/dist/secret-config-CBZBs0p1.js +271 -0
  135. package/dist/secret-config-CBZBs0p1.js.map +1 -0
  136. package/dist/slack.transport-Ce96JBDk.mjs +824 -0
  137. package/dist/slack.transport-Ce96JBDk.mjs.map +1 -0
  138. package/dist/slack.transport-Dlx3xvb7.js +847 -0
  139. package/dist/slack.transport-Dlx3xvb7.js.map +1 -0
  140. package/dist/slack.transport-DrirgDNy.d.ts +159 -0
  141. package/dist/slack.transport-DrirgDNy.d.ts.map +1 -0
  142. package/dist/slack.transport-DxHOXlLu.d.mts +159 -0
  143. package/dist/slack.transport-DxHOXlLu.d.mts.map +1 -0
  144. package/dist/testing.d.mts +3 -8
  145. package/dist/testing.d.mts.map +1 -1
  146. package/dist/testing.d.ts +3 -8
  147. package/dist/testing.d.ts.map +1 -1
  148. package/dist/testing.js +3 -4
  149. package/dist/testing.js.map +1 -1
  150. package/dist/testing.mjs +2 -3
  151. package/dist/testing.mjs.map +1 -1
  152. package/dist/{transport.manager-Crau3Rle.js → transport.manager-DkcEOlqV.js} +331 -234
  153. package/dist/transport.manager-DkcEOlqV.js.map +1 -0
  154. package/dist/{transport.manager-CpdVHEGP.mjs → transport.manager-eZ_EeC00.mjs} +274 -178
  155. package/dist/transport.manager-eZ_EeC00.mjs.map +1 -0
  156. package/dist/{transport.types-CtNr3D7S.d.mts → transport.types-BJVL1QQl.d.mts} +5 -4
  157. package/dist/transport.types-BJVL1QQl.d.mts.map +1 -0
  158. package/dist/{transport.types-DqVLZTyf.d.ts → transport.types-BJVL1QQl.d.ts} +5 -4
  159. package/dist/transport.types-BJVL1QQl.d.ts.map +1 -0
  160. package/dist/transports.d.mts +32 -41
  161. package/dist/transports.d.mts.map +1 -1
  162. package/dist/transports.d.ts +32 -41
  163. package/dist/transports.d.ts.map +1 -1
  164. package/dist/transports.js +12 -12
  165. package/dist/transports.mjs +7 -12
  166. package/dist/worker-entry.js +337 -87
  167. package/dist/worker.d.mts +1 -2
  168. package/dist/worker.d.ts +1 -2
  169. package/dist/worker.js +3 -4
  170. package/dist/worker.mjs +1 -4
  171. package/dist/{worker.transport-Bj-i0P9V.d.ts → worker.transport-BuPwBi3d.d.ts} +2 -6
  172. package/dist/worker.transport-BuPwBi3d.d.ts.map +1 -0
  173. package/dist/{worker.transport-JP8YHBuU.js → worker.transport-C6GNl_r2.js} +44 -14
  174. package/dist/worker.transport-C6GNl_r2.js.map +1 -0
  175. package/dist/{worker.transport-otwhJ_Et.mjs → worker.transport-DLVA4y2e.mjs} +39 -9
  176. package/dist/worker.transport-DLVA4y2e.mjs.map +1 -0
  177. package/dist/{worker.transport-Bgv9heDI.d.mts → worker.transport-hJay1wxA.d.mts} +2 -6
  178. package/dist/worker.transport-hJay1wxA.d.mts.map +1 -0
  179. package/package.json +36 -19
  180. package/dist/async-context-BzJrbfQs.mjs +0 -72
  181. package/dist/async-context-BzJrbfQs.mjs.map +0 -1
  182. package/dist/async-context-DyQQYq3I.js +0 -92
  183. package/dist/async-context-DyQQYq3I.js.map +0 -1
  184. package/dist/azure-monitor.transport-BDFO4F-i.d.ts.map +0 -1
  185. package/dist/azure-monitor.transport-CHnjVRF-.mjs.map +0 -1
  186. package/dist/azure-monitor.transport-CrvfHd9C.js.map +0 -1
  187. package/dist/azure-monitor.transport-D5wQEH04.d.mts.map +0 -1
  188. package/dist/batch-buffer-BY-mRWIK.js.map +0 -1
  189. package/dist/batch-buffer-PGvSgbmd.mjs.map +0 -1
  190. package/dist/chunk-DLSkYcPk.mjs +0 -7
  191. package/dist/chunk-nOFOJqeH.js +0 -30
  192. package/dist/cloudwatch.transport-B00st6Xv.d.ts.map +0 -1
  193. package/dist/cloudwatch.transport-BO1ahxw-.js.map +0 -1
  194. package/dist/cloudwatch.transport-Blc7Gtxt.d.mts.map +0 -1
  195. package/dist/cloudwatch.transport-DZ6ies7g.mjs.map +0 -1
  196. package/dist/entry-fields-BJkuPnIg.mjs.map +0 -1
  197. package/dist/entry-fields-BvOLFlJ4.js.map +0 -1
  198. package/dist/gcp.transport-CHV8MGgz.js.map +0 -1
  199. package/dist/gcp.transport-DBX5TPIy.mjs.map +0 -1
  200. package/dist/gcp.transport-m4fVw0b1.d.ts.map +0 -1
  201. package/dist/gcp.transport-zzNyIoih.d.mts.map +0 -1
  202. package/dist/index-BPwEisy4.d.mts.map +0 -1
  203. package/dist/index-nZEeCr3X.d.ts.map +0 -1
  204. package/dist/internal-log-BUJYMZbE.js +0 -70
  205. package/dist/internal-log-BUJYMZbE.js.map +0 -1
  206. package/dist/internal-log-Cm8SOWSV.mjs +0 -52
  207. package/dist/internal-log-Cm8SOWSV.mjs.map +0 -1
  208. package/dist/nestjs-extras-DnJ6vrIC.js.map +0 -1
  209. package/dist/nestjs-extras-ImbuDhs1.mjs.map +0 -1
  210. package/dist/nestjs-extras-OkC796py.d.mts +0 -725
  211. package/dist/nestjs-extras-OkC796py.d.mts.map +0 -1
  212. package/dist/nestjs-extras-mKrHE9S6.d.ts +0 -725
  213. package/dist/nestjs-extras-mKrHE9S6.d.ts.map +0 -1
  214. package/dist/safe-stringify-DJ66tW5I.mjs.map +0 -1
  215. package/dist/safe-stringify-DWo3aZp_.js.map +0 -1
  216. package/dist/search-B0MH1SJJ.js.map +0 -1
  217. package/dist/search-BfBzDIT9.d.mts.map +0 -1
  218. package/dist/search-CHUZPl0h.d.ts.map +0 -1
  219. package/dist/search-DjXSn6v5.mjs.map +0 -1
  220. package/dist/trace.utils-CvXgaiQT.mjs.map +0 -1
  221. package/dist/trace.utils-DpBOLDtq.js.map +0 -1
  222. package/dist/transport.manager-CpdVHEGP.mjs.map +0 -1
  223. package/dist/transport.manager-Crau3Rle.js.map +0 -1
  224. package/dist/transport.types-CtNr3D7S.d.mts.map +0 -1
  225. package/dist/transport.types-DqVLZTyf.d.ts.map +0 -1
  226. package/dist/worker.transport-Bgv9heDI.d.mts.map +0 -1
  227. package/dist/worker.transport-Bj-i0P9V.d.ts.map +0 -1
  228. package/dist/worker.transport-JP8YHBuU.js.map +0 -1
  229. package/dist/worker.transport-otwhJ_Et.mjs.map +0 -1
@@ -1,16 +1,83 @@
1
- import { t as __require } from "./chunk-DLSkYcPk.mjs";
2
- import { n as internalLog, r as internalWarn, t as internalError } from "./internal-log-Cm8SOWSV.mjs";
3
- import { i as stringifyForLog } from "./safe-stringify-DJ66tW5I.mjs";
4
- import { d as sanitizeIncomingId, i as TraceContext, l as getTraceContextKey, s as extractTraceId, t as DEFAULT_TRACE_HEADERS } from "./trace.utils-CvXgaiQT.mjs";
5
- import { t as LogixiaContext } from "./async-context-BzJrbfQs.mjs";
6
- import { t as safeToString } from "./coerce.utils-Cu6IUTgX.mjs";
7
- import { t as TransportManager, u as stripControlChars } from "./transport.manager-CpdVHEGP.mjs";
8
- import { constants } from "node:os";
1
+ import { t as __require } from "./rolldown-runtime-D3PmRqjj.mjs";
2
+ import { o as TraceContext } from "./request-trace-C_fvIDv4.mjs";
3
+ import { t as LogixiaContext } from "./async-context-B05ArHgM.mjs";
4
+ import { n as internalLog, o as SENSITIVE_KEY_NAMES, r as internalWarn, t as internalError } from "./internal-log-uCSd1PMc.mjs";
5
+ import { n as protectSecrets } from "./secret-config-BegMLkYl.mjs";
6
+ import { t as safeToString } from "./coerce.utils-B_rEudCn.mjs";
7
+ import { i as stringifyForLog } from "./safe-stringify-BMRl3EX3.mjs";
8
+ import { d as stripControlChars, t as TransportManager } from "./transport.manager-eZ_EeC00.mjs";
9
9
  import buildFastStringify from "fast-json-stringify";
10
- import { Catch, Inject, Injectable, Module, Optional, RequestMethod, Scope } from "@nestjs/common";
11
- import { EMPTY, Observable } from "rxjs";
12
-
13
- //#region src/plugin.ts
10
+ import { constants } from "node:os";
11
+ // src/types/index.ts
12
+ const LogLevel = {
13
+ ERROR: "error",
14
+ WARN: "warn",
15
+ INFO: "info",
16
+ DEBUG: "debug",
17
+ TRACE: "trace",
18
+ VERBOSE: "verbose"
19
+ };
20
+ const DEFAULT_LOG_LEVELS = {
21
+ error: 0,
22
+ warn: 1,
23
+ info: 2,
24
+ debug: 3,
25
+ trace: 4,
26
+ verbose: 5
27
+ };
28
+ const DEFAULT_LOG_COLORS = {
29
+ error: "red",
30
+ warn: "yellow",
31
+ info: "green",
32
+ debug: "blue",
33
+ trace: "magenta",
34
+ verbose: "cyan"
35
+ };
36
+ // src/core/default-config.ts
37
+ /**
38
+ * Default configuration for Logixia logger
39
+ */
40
+ const DEFAULT_CONFIG = {
41
+ appName: "App",
42
+ environment: "development",
43
+ traceId: true,
44
+ format: {
45
+ timestamp: true,
46
+ colorize: true,
47
+ json: false
48
+ },
49
+ silent: false,
50
+ levelOptions: {
51
+ level: LogLevel.INFO,
52
+ levels: {
53
+ [LogLevel.ERROR]: 0,
54
+ [LogLevel.WARN]: 1,
55
+ [LogLevel.INFO]: 2,
56
+ [LogLevel.DEBUG]: 3,
57
+ [LogLevel.TRACE]: 4,
58
+ [LogLevel.VERBOSE]: 5
59
+ },
60
+ colors: {
61
+ [LogLevel.ERROR]: "red",
62
+ [LogLevel.WARN]: "yellow",
63
+ [LogLevel.INFO]: "blue",
64
+ [LogLevel.DEBUG]: "green",
65
+ [LogLevel.TRACE]: "gray",
66
+ [LogLevel.VERBOSE]: "cyan"
67
+ }
68
+ },
69
+ fields: {
70
+ timestamp: true,
71
+ level: true,
72
+ appName: true,
73
+ traceId: true,
74
+ message: true,
75
+ payload: true,
76
+ timeTaken: true
77
+ },
78
+ outputs: ["console"]
79
+ };
80
+ // src/plugin.ts
14
81
  /**
15
82
  * Holds an ordered list of `LogixiaPlugin` instances and dispatches lifecycle
16
83
  * events to them. One registry is created per logger instance; a global
@@ -115,36 +182,7 @@ const globalPluginRegistry = new PluginRegistry();
115
182
  function usePlugin(plugin) {
116
183
  globalPluginRegistry.register(plugin);
117
184
  }
118
-
119
- //#endregion
120
- //#region src/types/index.ts
121
- const LogLevel = {
122
- ERROR: "error",
123
- WARN: "warn",
124
- INFO: "info",
125
- DEBUG: "debug",
126
- TRACE: "trace",
127
- VERBOSE: "verbose"
128
- };
129
- const DEFAULT_LOG_LEVELS = {
130
- error: 0,
131
- warn: 1,
132
- info: 2,
133
- debug: 3,
134
- trace: 4,
135
- verbose: 5
136
- };
137
- const DEFAULT_LOG_COLORS = {
138
- error: "red",
139
- warn: "yellow",
140
- info: "green",
141
- debug: "blue",
142
- trace: "magenta",
143
- verbose: "cyan"
144
- };
145
-
146
- //#endregion
147
- //#region src/utils/error.utils.ts
185
+ // src/utils/error.utils.ts
148
186
  const EXTRA_FIELDS = [
149
187
  "code",
150
188
  "statusCode",
@@ -186,13 +224,15 @@ function _serializeError(error, includeStack, maxDepth, excludeFields, depth, se
186
224
  };
187
225
  if (includeStack && error.stack) serialized.stack = error.stack;
188
226
  const errorWithCause = error;
189
- if (errorWithCause.cause !== void 0) if (errorWithCause.cause instanceof Error) serialized.cause = _serializeError(errorWithCause.cause, includeStack, maxDepth, excludeFields, depth + 1, seen);
190
- else serialized.cause = serializeValue(errorWithCause.cause, maxDepth - depth - 1, seen);
227
+ if (errorWithCause.cause !== void 0) {
228
+ if (errorWithCause.cause instanceof Error) serialized.cause = _serializeError(errorWithCause.cause, includeStack, maxDepth, excludeFields, depth + 1, seen);
229
+ else serialized.cause = serializeValue(errorWithCause.cause, maxDepth - depth - 1, seen);
230
+ }
191
231
  const aggregateError = error;
192
232
  if (Array.isArray(aggregateError.errors)) serialized.errors = aggregateError.errors.map((e) => e instanceof Error ? _serializeError(e, includeStack, maxDepth, excludeFields, depth + 1, seen) : serializeValue(e, maxDepth - depth - 1, seen));
193
233
  const errorRecord = error;
194
234
  for (const field of EXTRA_FIELDS) if (!excludeFields.includes(field) && field in error && errorRecord[field] !== void 0) serialized[field] = errorRecord[field];
195
- const skip = new Set([
235
+ const skip = /* @__PURE__ */ new Set([
196
236
  "name",
197
237
  "message",
198
238
  "stack",
@@ -274,9 +314,7 @@ function normalizeError(error) {
274
314
  }
275
315
  return new Error(String(error));
276
316
  }
277
-
278
- //#endregion
279
- //#region src/utils/otel.ts
317
+ // src/utils/otel.ts
280
318
  let _otelApi;
281
319
  function tryLoadOtelApi() {
282
320
  if (_otelApi !== void 0) return _otelApi;
@@ -381,9 +419,7 @@ function _getOtelPayloadIfEnabled() {
381
419
  function disableOtelBridge() {
382
420
  _bridgeOptions = null;
383
421
  }
384
-
385
- //#endregion
386
- //#region src/utils/redact.utils.ts
422
+ // src/utils/redact.utils.ts
387
423
  const DEFAULT_CENSOR = "[REDACTED]";
388
424
  /** Maximum nesting depth walked; deeper values are replaced with a marker. */
389
425
  const MAX_DEPTH = 32;
@@ -412,34 +448,7 @@ const PII_CONSERVATIVE_PATTERNS = [
412
448
  /**
413
449
  * Conservative field-name paths auto-redacted by name regardless of value.
414
450
  */
415
- const PII_CONSERVATIVE_PATHS = [
416
- "**.password",
417
- "**.passwd",
418
- "**.secret",
419
- "**.token",
420
- "**.apiKey",
421
- "**.api_key",
422
- "**.accessToken",
423
- "**.access_token",
424
- "**.refreshToken",
425
- "**.refresh_token",
426
- "**.authorization",
427
- "**.credentials",
428
- "**.privateKey",
429
- "**.private_key",
430
- "**.clientSecret",
431
- "**.client_secret",
432
- "**.cookie",
433
- "**.set-cookie",
434
- "**.x-api-key",
435
- "**.session",
436
- "**.proxy-authorization",
437
- "**.x-auth-token",
438
- "**.x-access-token",
439
- "**.aws_secret_access_key",
440
- "**.awsSecretAccessKey",
441
- "**.secretAccessKey"
442
- ];
451
+ const PII_CONSERVATIVE_PATHS = SENSITIVE_KEY_NAMES.map((name) => `**.${name}`);
443
452
  /**
444
453
  * Aggressive patterns: also catch personal data that could identify a person.
445
454
  * Applied when `autoDetect: 'aggressive'`.
@@ -651,7 +660,7 @@ function walkToJSON(obj, state, fullPath, bare, depth) {
651
660
  function redactObject(obj, config, _currentPath = "") {
652
661
  const result = walkRecord(obj, {
653
662
  config,
654
- ancestors: new Set([obj]),
663
+ ancestors: /* @__PURE__ */ new Set([obj]),
655
664
  nodes: 0
656
665
  }, _currentPath, _currentPath, 0);
657
666
  return result === obj ? { ...obj } : result;
@@ -700,10 +709,8 @@ function isPlainObject(value) {
700
709
  if (ArrayBuffer.isView(value)) return false;
701
710
  return !OPAQUE_BUILTINS.some((ctor) => value instanceof ctor);
702
711
  }
703
-
704
- //#endregion
705
- //#region src/utils/sampling.utils.ts
706
- const ALWAYS_EMIT_LEVELS = new Set([
712
+ // src/utils/sampling.utils.ts
713
+ const ALWAYS_EMIT_LEVELS = /* @__PURE__ */ new Set([
707
714
  "error",
708
715
  "warn",
709
716
  "fatal"
@@ -721,8 +728,8 @@ var Sampler = class {
721
728
  constructor(config, onStats) {
722
729
  this.traceDecisions = /* @__PURE__ */ new Map();
723
730
  this.maxTrackedTraces = 1e5;
724
- this.traceTtlMs = 5 * 6e4;
725
- this.traceMaxLifetimeMs = 60 * 6e4;
731
+ this.traceTtlMs = 3e5;
732
+ this.traceMaxLifetimeMs = 36e5;
726
733
  this._tokenBucket = 0;
727
734
  this._lastRefillMs = Date.now();
728
735
  this._adaptiveWindow = [];
@@ -901,9 +908,14 @@ var Sampler = class {
901
908
  this._stats.dropped++;
902
909
  }
903
910
  };
904
-
905
- //#endregion
906
- //#region src/utils/shutdown.utils.ts
911
+ // src/utils/shutdown.utils.ts
912
+ /**
913
+ * Graceful shutdown utilities for Logixia
914
+ *
915
+ * Ensures all in-flight logs are flushed to every transport before the process
916
+ * exits on SIGTERM / SIGINT — solving the "last N seconds of logs are lost on
917
+ * deployment" problem reported in Pino issue #2002 and LogDNA issue #15.
918
+ */
907
919
  const MAX_BEFORE_EXIT_FLUSHES = 5;
908
920
  /** Module-level registry of all logger instances that have opted into graceful shutdown */
909
921
  const registry = /* @__PURE__ */ new Set();
@@ -1023,9 +1035,17 @@ function resetShutdownHandlers() {
1023
1035
  shutdownHandlerRegistered = false;
1024
1036
  shutdownInProgress = false;
1025
1037
  }
1026
-
1027
- //#endregion
1028
- //#region src/core/logitron-logger.ts
1038
+ // src/core/logitron-logger.ts
1039
+ /**
1040
+ * Core Logixia Logger implementation
1041
+ *
1042
+ * v1.1 additions:
1043
+ * - Feature 1: Graceful shutdown / flushOnExit (auto-registered via config)
1044
+ * - Feature 2: Built-in log redaction (path-based + regex)
1045
+ * - Feature 3: Per-namespace log levels + LOGIXIA_LEVEL* ENV overrides
1046
+ * - Feature 4: Cause-chain error serialization (handled in error.utils)
1047
+ * - Feature 5: Adaptive log level based on NODE_ENV / CI detection
1048
+ */
1029
1049
  const _fastStringifyEntry = buildFastStringify({
1030
1050
  type: "object",
1031
1051
  properties: {
@@ -1055,7 +1075,7 @@ function nowIso() {
1055
1075
  }
1056
1076
  function namespacePatternToRegex(pattern) {
1057
1077
  const escaped = pattern.split(".").map((s) => s === "*" ? "[^.]+" : s.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")).join("\\.");
1058
- return /* @__PURE__ */ new RegExp(`^${escaped}$`);
1078
+ return new RegExp(`^${escaped}$`);
1059
1079
  }
1060
1080
  /** Max compiled patterns to keep in memory. Oldest entry is evicted when full. */
1061
1081
  const _NS_CACHE_MAX = 1e3;
@@ -1097,7 +1117,7 @@ function canonicalLevel(level, known) {
1097
1117
  function resolveInitialLevel(config) {
1098
1118
  var _config$levelOptions, _config$levelOptions2;
1099
1119
  const envLevel = process.env["LOGIXIA_LEVEL"];
1100
- const knownLevels = new Set([...Object.values(LogLevel), ...Object.keys(((_config$levelOptions = config.levelOptions) === null || _config$levelOptions === void 0 ? void 0 : _config$levelOptions.levels) ?? {})]);
1120
+ const knownLevels = /* @__PURE__ */ new Set([...Object.values(LogLevel), ...Object.keys(((_config$levelOptions = config.levelOptions) === null || _config$levelOptions === void 0 ? void 0 : _config$levelOptions.levels) ?? {})]);
1101
1121
  if (envLevel && canonicalLevel(envLevel, knownLevels)) return envLevel;
1102
1122
  if ((_config$levelOptions2 = config.levelOptions) === null || _config$levelOptions2 === void 0 ? void 0 : _config$levelOptions2.level) return config.levelOptions.level;
1103
1123
  const nodeEnv = process.env["NODE_ENV"];
@@ -1107,6 +1127,19 @@ function resolveInitialLevel(config) {
1107
1127
  if (process.env["CI"]) return LogLevel.INFO;
1108
1128
  return LogLevel.INFO;
1109
1129
  }
1130
+ /**
1131
+ * The logixia logger. Create instances with {@link createLogger} so that custom
1132
+ * levels from `levelOptions.levels` also become methods.
1133
+ *
1134
+ * @example
1135
+ * ```ts
1136
+ * const logger = createLogger({ appName: 'api', environment: 'production' });
1137
+ * await logger.info('Server started', { port: 3000 });
1138
+ * const req = logger.child('RequestHandler', { requestId: 'r-1' });
1139
+ * await req.error(new Error('boom'));
1140
+ * await logger.close(); // flush buffered transports before exit
1141
+ * ```
1142
+ */
1110
1143
  var LogixiaLogger = class LogixiaLogger {
1111
1144
  constructor(config, context, parent) {
1112
1145
  this.timers = /* @__PURE__ */ new Map();
@@ -1124,7 +1157,7 @@ var LogixiaLogger = class LogixiaLogger {
1124
1157
  this._hasRedact = false;
1125
1158
  this._parent = parent;
1126
1159
  this._pluginRegistry = parent ? parent._pluginRegistry : new PluginRegistry();
1127
- this.config = {
1160
+ const defaultConfig = {
1128
1161
  appName: "App",
1129
1162
  environment: "development",
1130
1163
  traceId: true,
@@ -1152,7 +1185,10 @@ var LogixiaLogger = class LogixiaLogger {
1152
1185
  [LogLevel.TRACE]: "gray",
1153
1186
  [LogLevel.VERBOSE]: "cyan"
1154
1187
  }
1155
- },
1188
+ }
1189
+ };
1190
+ this.config = {
1191
+ ...defaultConfig,
1156
1192
  ...config
1157
1193
  };
1158
1194
  const resolvedLevel = resolveInitialLevel(this.config);
@@ -1170,6 +1206,7 @@ var LogixiaLogger = class LogixiaLogger {
1170
1206
  timeTaken: "[time_taken_MS]"
1171
1207
  };
1172
1208
  this.context = context ?? "";
1209
+ protectSecrets(this, ["config"]);
1173
1210
  if (parent) {
1174
1211
  this.transportManager = parent.transportManager;
1175
1212
  this._sampler = parent._sampler;
@@ -1235,7 +1272,7 @@ var LogixiaLogger = class LogixiaLogger {
1235
1272
  this.config.levelOptions.level = this._validLevel(this.config.levelOptions.level, "levelOptions.level") ?? LogLevel.INFO;
1236
1273
  const effectiveLevel = this.resolveEffectiveLevel();
1237
1274
  this._minLevelValue = this._levelValues.get(effectiveLevel) ?? 2;
1238
- this._colorMap = new Map([
1275
+ this._colorMap = /* @__PURE__ */ new Map([
1239
1276
  ["black", "\x1B[30m"],
1240
1277
  ["red", "\x1B[31m"],
1241
1278
  ["green", "\x1B[32m"],
@@ -1278,7 +1315,7 @@ var LogixiaLogger = class LogixiaLogger {
1278
1315
  "green",
1279
1316
  "blue"
1280
1317
  ];
1281
- const _BUILTIN_LEVELS = new Set([
1318
+ const _BUILTIN_LEVELS = /* @__PURE__ */ new Set([
1282
1319
  "error",
1283
1320
  "warn",
1284
1321
  "info",
@@ -1292,10 +1329,12 @@ var LogixiaLogger = class LogixiaLogger {
1292
1329
  if (colorize && this._fieldCache.get("level") !== false) {
1293
1330
  var _this$config$levelOpt4;
1294
1331
  let colorName = (_this$config$levelOpt4 = this.config.levelOptions) === null || _this$config$levelOpt4 === void 0 || (_this$config$levelOpt4 = _this$config$levelOpt4.colors) === null || _this$config$levelOpt4 === void 0 ? void 0 : _this$config$levelOpt4[lvl];
1295
- if (!colorName) if (_BUILTIN_LEVELS.has(lvl)) colorName = "white";
1296
- else {
1297
- colorName = _AUTO_PALETTE[_paletteIdx % _AUTO_PALETTE.length];
1298
- _paletteIdx++;
1332
+ if (!colorName) {
1333
+ if (_BUILTIN_LEVELS.has(lvl)) colorName = "white";
1334
+ else {
1335
+ colorName = _AUTO_PALETTE[_paletteIdx % _AUTO_PALETTE.length];
1336
+ _paletteIdx++;
1337
+ }
1299
1338
  }
1300
1339
  const code = this._colorMap.get(colorName.toLowerCase()) ?? this._colorMap.get("white");
1301
1340
  const reset = this._colorMap.get("reset");
@@ -1307,6 +1346,11 @@ var LogixiaLogger = class LogixiaLogger {
1307
1346
  else this._formattedAppName = colorize ? `${this._colorMap.get("gray")}${appNameRaw}${this._colorMap.get("reset")} ` : `${appNameRaw} `;
1308
1347
  this._hasRedact = !!(this.config.redact && ((((_this$config$redact$p = this.config.redact.paths) === null || _this$config$redact$p === void 0 ? void 0 : _this$config$redact$p.length) ?? 0) > 0 || (((_this$config$redact$p2 = this.config.redact.patterns) === null || _this$config$redact$p2 === void 0 ? void 0 : _this$config$redact$p2.length) ?? 0) > 0 || !!this.config.redact.autoDetect));
1309
1348
  }
1349
+ /**
1350
+ * Log at `error` level. An `Error` is logged with its message and serialized
1351
+ * (name, message, stack) under `data.error`; a string is logged as-is.
1352
+ * `data` is merged into the entry payload.
1353
+ */
1310
1354
  async error(messageOrError, data) {
1311
1355
  if (isError(messageOrError)) await this.log("error", messageOrError.message, {
1312
1356
  ...data,
@@ -1314,30 +1358,53 @@ var LogixiaLogger = class LogixiaLogger {
1314
1358
  });
1315
1359
  else await this.log("error", messageOrError, data);
1316
1360
  }
1361
+ /** Log `message` at `warn` level; `data` is merged into the entry payload. */
1317
1362
  async warn(message, data) {
1318
1363
  await this.log("warn", message, data);
1319
1364
  }
1365
+ /** Log `message` at `info` level; `data` is merged into the entry payload. */
1320
1366
  async info(message, data) {
1321
1367
  await this.log("info", message, data);
1322
1368
  }
1369
+ /** Log `message` at `debug` level; `data` is merged into the entry payload. */
1323
1370
  async debug(message, data) {
1324
1371
  await this.log("debug", message, data);
1325
1372
  }
1373
+ /** Log `message` at `trace` level; `data` is merged into the entry payload. */
1326
1374
  async trace(message, data) {
1327
1375
  await this.log("trace", message, data);
1328
1376
  }
1377
+ /** Log `message` at `verbose` level; `data` is merged into the entry payload. */
1329
1378
  async verbose(message, data) {
1330
1379
  await this.log("verbose", message, data);
1331
1380
  }
1381
+ /**
1382
+ * Log at an arbitrary level name, including custom levels. Levels below the
1383
+ * active threshold are dropped, as are level names that are not registered
1384
+ * in `levelOptions.levels` (and are not built-in).
1385
+ */
1332
1386
  async logLevel(level, message, data) {
1333
1387
  await this.log(level, message, data);
1334
1388
  }
1389
+ /** Start a named timer; finish it with {@link timeEnd}. Reusing a label restarts it. */
1335
1390
  time(label) {
1336
1391
  this.timers.set(label, {
1337
1392
  label,
1338
1393
  startTime: Date.now()
1339
1394
  });
1340
1395
  }
1396
+ /**
1397
+ * Stop the timer `label`, log its duration at `info` level, and return the
1398
+ * elapsed milliseconds. Logs a `warn` and returns `undefined` if the timer
1399
+ * does not exist.
1400
+ *
1401
+ * @example
1402
+ * ```ts
1403
+ * logger.time('db');
1404
+ * await query();
1405
+ * const ms = await logger.timeEnd('db');
1406
+ * ```
1407
+ */
1341
1408
  async timeEnd(label) {
1342
1409
  const timer = this.timers.get(label);
1343
1410
  if (!timer) {
@@ -1367,6 +1434,17 @@ var LogixiaLogger = class LogixiaLogger {
1367
1434
  throw error;
1368
1435
  }
1369
1436
  }
1437
+ /**
1438
+ * Change the minimum log level at runtime. The override outranks
1439
+ * `LOGIXIA_LEVEL`, `LOGIXIA_LEVEL_<NS>` and `namespaceLevels`, and survives
1440
+ * later changes to fields or namespace levels. Unknown level names are
1441
+ * ignored with a warning and the current level is kept.
1442
+ *
1443
+ * @example
1444
+ * ```ts
1445
+ * logger.setLevel('debug');
1446
+ * ```
1447
+ */
1370
1448
  setLevel(level) {
1371
1449
  const canonical = canonicalLevel(level, this._levelValues);
1372
1450
  if (canonical === void 0) {
@@ -1375,9 +1453,14 @@ var LogixiaLogger = class LogixiaLogger {
1375
1453
  }
1376
1454
  this.config.levelOptions = this.config.levelOptions ?? {};
1377
1455
  this.config.levelOptions.level = canonical;
1378
- this._minLevelValue = this._levelValues.get(canonical) ?? this._minLevelValue;
1456
+ this._runtimeLevel = canonical;
1379
1457
  this._buildPerfCaches();
1380
1458
  }
1459
+ /**
1460
+ * Return the configured minimum log level, not the per-namespace effective
1461
+ * one. Without `setLevel()` it is `LOGIXIA_LEVEL`, else `levelOptions.level`,
1462
+ * else a `NODE_ENV` default (`debug` in development, `warn` in test), else `info`.
1463
+ */
1381
1464
  getLevel() {
1382
1465
  var _this$config$levelOpt5;
1383
1466
  return ((_this$config$levelOpt5 = this.config.levelOptions) === null || _this$config$levelOpt5 === void 0 ? void 0 : _this$config$levelOpt5.level) ?? LogLevel.INFO;
@@ -1431,30 +1514,36 @@ var LogixiaLogger = class LogixiaLogger {
1431
1514
  getNamespaceLevels() {
1432
1515
  return { ...this.config.namespaceLevels };
1433
1516
  }
1517
+ /** Set the context label (e.g. a class or module name) attached to every subsequent entry. */
1434
1518
  setContext(context) {
1435
1519
  this.context = typeof context === "string" ? context : safeToString(context);
1436
1520
  }
1521
+ /** Return the current context label, or `undefined` if none is set. */
1437
1522
  getContext() {
1438
1523
  return this.context;
1439
1524
  }
1525
+ /** Show `fieldName` in log output, overriding the config for this logger instance. */
1440
1526
  enableField(fieldName) {
1441
1527
  this.fieldState.set(fieldName, true);
1442
1528
  this._fieldCache.set(fieldName, true);
1443
1529
  if (fieldName === "level" || fieldName === "appName") this._buildPerfCaches();
1444
1530
  internalLog(`Field '${fieldName}' enabled`);
1445
1531
  }
1532
+ /** Hide `fieldName` from log output, overriding the config for this logger instance. */
1446
1533
  disableField(fieldName) {
1447
1534
  this.fieldState.set(fieldName, false);
1448
1535
  this._fieldCache.set(fieldName, false);
1449
1536
  if (fieldName === "level" || fieldName === "appName") this._buildPerfCaches();
1450
1537
  internalLog(`Field '${fieldName}' disabled`);
1451
1538
  }
1539
+ /** Whether `fieldName` is currently shown: runtime override first, then config, default `true`. */
1452
1540
  isFieldEnabled(fieldName) {
1453
1541
  var _this$config$fields2;
1454
1542
  if (this.fieldState.has(fieldName)) return this.fieldState.get(fieldName);
1455
1543
  if (((_this$config$fields2 = this.config.fields) === null || _this$config$fields2 === void 0 ? void 0 : _this$config$fields2[fieldName]) !== void 0) return this.config.fields[fieldName] !== false;
1456
1544
  return true;
1457
1545
  }
1546
+ /** Return the visibility (`true` = shown) of every standard log field. */
1458
1547
  getFieldState() {
1459
1548
  return Object.fromEntries([
1460
1549
  "timestamp",
@@ -1471,6 +1560,7 @@ var LogixiaLogger = class LogixiaLogger {
1471
1560
  "environment"
1472
1561
  ].map((f) => [f, this.isFieldEnabled(f)]));
1473
1562
  }
1563
+ /** Drop all runtime enable/disable overrides so field visibility follows the config again. */
1474
1564
  resetFieldState() {
1475
1565
  this.fieldState.clear();
1476
1566
  internalLog("Field state reset to configuration defaults");
@@ -1485,10 +1575,12 @@ var LogixiaLogger = class LogixiaLogger {
1485
1575
  if (this.transportManager) this.transportManager.disableLevelPrompting();
1486
1576
  else internalWarn("Transport manager not initialized");
1487
1577
  }
1578
+ /** Restrict `transportId` to only the given `levels`. Warns if no transports are configured. */
1488
1579
  setTransportLevels(transportId, levels) {
1489
1580
  if (this.transportManager) this.transportManager.setTransportLevels(transportId, levels);
1490
1581
  else internalWarn("Transport manager not initialized");
1491
1582
  }
1583
+ /** Return the levels `transportId` is restricted to, or `undefined` if it has none. */
1492
1584
  getTransportLevels(transportId) {
1493
1585
  if (this.transportManager) return this.transportManager.getTransportLevels(transportId);
1494
1586
  internalWarn("Transport manager not initialized");
@@ -1497,10 +1589,23 @@ var LogixiaLogger = class LogixiaLogger {
1497
1589
  if (this.transportManager) this.transportManager.clearTransportLevelPreferences();
1498
1590
  else internalWarn("Transport manager not initialized");
1499
1591
  }
1592
+ /** Return the identifiers of the configured transports (empty if none). */
1500
1593
  getAvailableTransports() {
1501
1594
  var _this$transportManage;
1502
1595
  return ((_this$transportManage = this.transportManager) === null || _this$transportManage === void 0 ? void 0 : _this$transportManage.getTransports()) ?? [];
1503
1596
  }
1597
+ /**
1598
+ * Create a child logger with its own `context` that shares this logger's
1599
+ * configuration and transports. `data` is merged into the bound fields
1600
+ * inherited from this logger and added to every entry the child writes.
1601
+ * Closing a child does not close the shared transports.
1602
+ *
1603
+ * @example
1604
+ * ```ts
1605
+ * const req = logger.child('Checkout', { requestId: 'r-42' });
1606
+ * await req.info('started'); // entry includes requestId
1607
+ * ```
1608
+ */
1504
1609
  child(context, data) {
1505
1610
  const childLogger = new LogixiaLogger(this.config, context, this);
1506
1611
  const mergedContextData = {
@@ -1536,9 +1641,11 @@ var LogixiaLogger = class LogixiaLogger {
1536
1641
  this._pluginRegistry.unregister(pluginName);
1537
1642
  return this;
1538
1643
  }
1644
+ /** Flush buffered entries in all transports without closing them. */
1539
1645
  async flush() {
1540
1646
  if (this.transportManager) await this.transportManager.flush();
1541
1647
  }
1648
+ /** Report whether the transports are healthy; `healthy: false` if no transport manager exists. */
1542
1649
  async healthCheck() {
1543
1650
  if (!this.transportManager) return {
1544
1651
  healthy: false,
@@ -1546,6 +1653,20 @@ var LogixiaLogger = class LogixiaLogger {
1546
1653
  };
1547
1654
  return this.transportManager.healthCheck();
1548
1655
  }
1656
+ /**
1657
+ * Warn about timers that were never ended, then flush and close all transports,
1658
+ * stop the sampler and run plugin shutdown hooks. On a child logger only the
1659
+ * timer warnings run; the shared transports stay open.
1660
+ *
1661
+ * To flush on SIGTERM/SIGINT, set the `gracefulShutdown` config option rather
1662
+ * than writing your own signal handler; do not combine it with a manual
1663
+ * handler that calls `process.exit`, which can cut the flush short.
1664
+ *
1665
+ * @example
1666
+ * ```ts
1667
+ * await logger.close(); // e.g. at the end of a script or a test
1668
+ * ```
1669
+ */
1549
1670
  async close() {
1550
1671
  var _this$_sampler;
1551
1672
  for (const [label, timer] of this.timers) await this.warn(`Timer '${label}' was not ended properly`, {
@@ -1562,11 +1683,13 @@ var LogixiaLogger = class LogixiaLogger {
1562
1683
  async log(level, message, data) {
1563
1684
  if (this.config.silent) return;
1564
1685
  if (!this.shouldLog(level)) return;
1565
- if (this._sampler) {
1566
- const traceId$1 = this.config.traceId ? TraceContext.instance.getCurrentTraceId() : void 0;
1567
- if (!this._sampler.shouldEmit(level, traceId$1)) return;
1568
- }
1569
1686
  const alsContext = LogixiaContext.get();
1687
+ let activeTraceId;
1688
+ if (this.config.traceId) {
1689
+ const ctxTraceId = alsContext === null || alsContext === void 0 ? void 0 : alsContext.traceId;
1690
+ activeTraceId = TraceContext.instance.getCurrentTraceId() ?? (typeof ctxTraceId === "string" ? ctxTraceId : void 0);
1691
+ }
1692
+ if (this._sampler && !this._sampler.shouldEmit(level, activeTraceId)) return;
1570
1693
  const hasAls = alsContext !== void 0 && Object.keys(alsContext).length > 0;
1571
1694
  const otelFields = _isOtelBridgeEnabled() ? _getOtelPayloadIfEnabled() : void 0;
1572
1695
  const hasOtel = otelFields !== void 0 && Object.keys(otelFields).length > 0;
@@ -1586,14 +1709,16 @@ var LogixiaLogger = class LogixiaLogger {
1586
1709
  ...mergedData
1587
1710
  } : mergedData;
1588
1711
  let payload;
1589
- if (rawPayload !== void 0 && rawPayload !== null) if (this._hasRedact) try {
1590
- payload = applyRedaction(rawPayload, this.config.redact) ?? rawPayload;
1591
- } catch (error) {
1592
- internalError("Redaction failed", error);
1593
- payload = { redaction: REDACTION_FAILED };
1712
+ if (rawPayload !== void 0 && rawPayload !== null) {
1713
+ if (this._hasRedact) try {
1714
+ payload = applyRedaction(rawPayload, this.config.redact) ?? rawPayload;
1715
+ } catch (error) {
1716
+ internalError("Redaction failed", error);
1717
+ payload = { redaction: REDACTION_FAILED };
1718
+ }
1719
+ else payload = rawPayload;
1594
1720
  }
1595
- else payload = rawPayload;
1596
- const traceId = this.config.traceId ? TraceContext.instance.getCurrentTraceId() ?? this.fallbackTraceId : void 0;
1721
+ const traceId = this.config.traceId ? activeTraceId ?? this.fallbackTraceId : void 0;
1597
1722
  let safeMessage = message;
1598
1723
  if (this._hasRedact) try {
1599
1724
  safeMessage = applyRedactionToString(message, this.config.redact);
@@ -1631,12 +1756,14 @@ var LogixiaLogger = class LogixiaLogger {
1631
1756
  * Feature 3: Resolve the effective log level for this logger instance.
1632
1757
  *
1633
1758
  * Priority:
1759
+ * 0. A level set at runtime with `setLevel()` (explicit programmatic call, wins over all below)
1634
1760
  * 1. ENV `LOGIXIA_LEVEL_<NS_UPPER>` (e.g. LOGIXIA_LEVEL_DB for ns "db" or "db.queries")
1635
1761
  * 2. Matching `namespaceLevels` config entry (longer pattern = more specific, wins)
1636
1762
  * 3. Global `LOGIXIA_LEVEL` ENV override
1637
1763
  * 4. `levelOptions.level` (resolved via Feature 5 in constructor)
1638
1764
  */
1639
1765
  resolveEffectiveLevel() {
1766
+ if (this._runtimeLevel) return this._runtimeLevel;
1640
1767
  const ns = this.context;
1641
1768
  if (ns) {
1642
1769
  const nsKey = ns.split(".")[0].toUpperCase();
@@ -1710,6 +1837,22 @@ var LogixiaLogger = class LogixiaLogger {
1710
1837
  (level === LogLevel.ERROR ? process.stderr : process.stdout).write(this.formatLog(entry) + "\n");
1711
1838
  }
1712
1839
  };
1840
+ /**
1841
+ * Create a logger from `config`, with an optional default `context` label.
1842
+ *
1843
+ * Every key of `levelOptions.levels` that is not already a method becomes an
1844
+ * async method on the returned logger, typed through the config, and routes to
1845
+ * {@link LogixiaLogger.logLevel}.
1846
+ *
1847
+ * @example
1848
+ * ```ts
1849
+ * const logger = createLogger({
1850
+ * appName: 'api',
1851
+ * levelOptions: { level: 'info', levels: { error: 0, warn: 1, info: 2, audit: 2 } },
1852
+ * });
1853
+ * await logger.audit('user exported data', { userId: 'u1' });
1854
+ * ```
1855
+ */
1713
1856
  function createLogger(config, context) {
1714
1857
  var _config$levelOptions3;
1715
1858
  const logger = new LogixiaLogger(config, context);
@@ -1721,686 +1864,7 @@ function createLogger(config, context) {
1721
1864
  }
1722
1865
  return logger;
1723
1866
  }
1724
-
1725
- //#endregion
1726
- //#region \0@oxc-project+runtime@0.95.0/helpers/decorateMetadata.js
1727
- function __decorateMetadata(k, v) {
1728
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1729
- }
1730
-
1731
- //#endregion
1732
- //#region \0@oxc-project+runtime@0.95.0/helpers/decorate.js
1733
- function __decorate(decorators, target, key, desc) {
1734
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1735
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1736
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1737
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1738
- }
1739
-
1740
- //#endregion
1741
- //#region src/core/logitron-nestjs.service.ts
1742
- var _LogixiaLoggerService;
1743
- let LogixiaLoggerService = _LogixiaLoggerService = class LogixiaLoggerService$1 {
1744
- constructor(config) {
1745
- this._mergedConfig = {
1746
- appName: "NestJS-App",
1747
- environment: "development",
1748
- traceId: true,
1749
- format: {
1750
- timestamp: true,
1751
- colorize: true,
1752
- json: false
1753
- },
1754
- silent: false,
1755
- levelOptions: {
1756
- level: LogLevel.INFO,
1757
- levels: {
1758
- error: 0,
1759
- warn: 1,
1760
- log: 2,
1761
- debug: 3,
1762
- verbose: 4
1763
- },
1764
- colors: {
1765
- error: "red",
1766
- warn: "yellow",
1767
- log: "green",
1768
- debug: "blue",
1769
- verbose: "cyan"
1770
- }
1771
- },
1772
- fields: {
1773
- timestamp: "[yyyy-mm-dd HH:MM:ss.MS]",
1774
- level: "[log_level]",
1775
- appName: "[app_name]",
1776
- traceId: "[trace_id]",
1777
- message: "[message]",
1778
- payload: "[payload]",
1779
- timeTaken: "[time_taken_MS]"
1780
- },
1781
- ...config
1782
- };
1783
- this.logger = new LogixiaLogger(this._mergedConfig);
1784
- this._createCustomLevelMethods();
1785
- }
1786
- _createCustomLevelMethods() {
1787
- var _this$_mergedConfig$l;
1788
- const levels = (_this$_mergedConfig$l = this._mergedConfig.levelOptions) === null || _this$_mergedConfig$l === void 0 ? void 0 : _this$_mergedConfig$l.levels;
1789
- if (!levels) return;
1790
- for (const levelName of Object.keys(levels)) {
1791
- const lower = levelName.toLowerCase();
1792
- if (typeof this[lower] !== "undefined") continue;
1793
- this[lower] = async (message, data) => {
1794
- return this.logger.logLevel(lower, message, data);
1795
- };
1796
- }
1797
- }
1798
- /**
1799
- * NestJS `LoggerService.log` — void, string context.
1800
- * Maps internally to `info`.
1801
- *
1802
- * @example `logger.log('User signed up', 'AuthService')`
1803
- */
1804
- log(message, context) {
1805
- this.setContextIfProvided(context);
1806
- this.logger.info(this.formatMessage(message)).catch((err) => internalError("LogixiaLoggerService.log failed", err));
1807
- }
1808
- /**
1809
- * Native async `info` — structured data, returns `Promise<void>`.
1810
- *
1811
- * @example `await logger.info('User signed up', { userId: 'u_abc' })`
1812
- */
1813
- async info(message, data) {
1814
- return this.logger.info(message, data);
1815
- }
1816
- error(message, dataOrTrace, context) {
1817
- if (typeof dataOrTrace === "object" && dataOrTrace !== null) return message instanceof Error ? this.logger.error(message, dataOrTrace) : this.logger.error(this.formatMessage(message), dataOrTrace);
1818
- this.setContextIfProvided(context);
1819
- const errorData = {};
1820
- if (typeof dataOrTrace === "string" && dataOrTrace) errorData.stack = dataOrTrace;
1821
- (message instanceof Error ? this.logger.error(message, errorData) : this.logger.error(this.formatMessage(message), errorData)).catch((err) => internalError("LogixiaLoggerService.error failed", err));
1822
- }
1823
- warn(message, dataOrContext) {
1824
- if (typeof dataOrContext === "object" && dataOrContext !== null) return this.logger.warn(this.formatMessage(message), dataOrContext);
1825
- this.setContextIfProvided(typeof dataOrContext === "string" ? dataOrContext : void 0);
1826
- this.logger.warn(this.formatMessage(message)).catch((err) => internalError("LogixiaLoggerService.warn failed", err));
1827
- }
1828
- debug(message, dataOrContext) {
1829
- if (typeof dataOrContext === "object" && dataOrContext !== null) return this.logger.debug(this.formatMessage(message), dataOrContext);
1830
- this.setContextIfProvided(typeof dataOrContext === "string" ? dataOrContext : void 0);
1831
- this.logger.debug(this.formatMessage(message)).catch((err) => internalError("LogixiaLoggerService.debug failed", err));
1832
- }
1833
- verbose(message, dataOrContext) {
1834
- if (typeof dataOrContext === "object" && dataOrContext !== null) return this.logger.trace(this.formatMessage(message), dataOrContext);
1835
- this.setContextIfProvided(typeof dataOrContext === "string" ? dataOrContext : void 0);
1836
- this.logger.trace(this.formatMessage(message)).catch((err) => internalError("LogixiaLoggerService.verbose failed", err));
1837
- }
1838
- /**
1839
- * Native async `trace` — lowest verbosity level, structured data.
1840
- */
1841
- async trace(message, data) {
1842
- return this.logger.trace(message, data);
1843
- }
1844
- /**
1845
- * Log at any named level with structured data.
1846
- */
1847
- logLevel(level, message, data) {
1848
- return this.logger.logLevel(level, message, data);
1849
- }
1850
- time(label) {
1851
- this.logger.time(label);
1852
- }
1853
- async timeEnd(label) {
1854
- return this.logger.timeEnd(label);
1855
- }
1856
- async timeAsync(label, fn) {
1857
- return this.logger.timeAsync(label, fn);
1858
- }
1859
- setContext(context) {
1860
- const coerced = typeof context === "string" ? context : safeToString(context);
1861
- this.context = coerced;
1862
- this.logger.setContext(coerced);
1863
- }
1864
- getContext() {
1865
- return this.context;
1866
- }
1867
- setLevel(level) {
1868
- this.logger.setLevel(level);
1869
- }
1870
- getLevel() {
1871
- return this.logger.getLevel();
1872
- }
1873
- child(context, data) {
1874
- const childService = new _LogixiaLoggerService(this._mergedConfig);
1875
- childService.logger = this.logger.child(context, data);
1876
- childService.context = context;
1877
- return childService;
1878
- }
1879
- getCurrentTraceId() {
1880
- return TraceContext.instance.getCurrentTraceId();
1881
- }
1882
- /** Returns the AsyncLocalStorage key currently used to store the trace ID. */
1883
- get traceContextKey() {
1884
- return getTraceContextKey();
1885
- }
1886
- async close() {
1887
- return this.logger.close();
1888
- }
1889
- static create(config) {
1890
- return new _LogixiaLoggerService(config);
1891
- }
1892
- getLogger() {
1893
- return this.logger;
1894
- }
1895
- setContextIfProvided(context) {
1896
- if (typeof context !== "string" || context.length === 0) return;
1897
- if (context !== this.context) this.setContext(context);
1898
- }
1899
- formatMessage(message) {
1900
- if (typeof message === "string") return message;
1901
- return safeToString(message);
1902
- }
1903
- };
1904
- LogixiaLoggerService = _LogixiaLoggerService = __decorate([Injectable({ scope: Scope.TRANSIENT }), __decorateMetadata("design:paramtypes", [Object])], LogixiaLoggerService);
1905
-
1906
- //#endregion
1907
- //#region src/core/kafka-trace.interceptor.ts
1908
- var _KafkaTraceInterceptor;
1909
- let KafkaTraceInterceptor = class KafkaTraceInterceptor$1 {
1910
- static {
1911
- _KafkaTraceInterceptor = this;
1912
- }
1913
- static #_ = this.metrics = {
1914
- accepted: 0,
1915
- acceptedWithoutTrace: 0,
1916
- dropped: 0
1917
- };
1918
- /** Reset counters (tests). */
1919
- static resetMetrics() {
1920
- _KafkaTraceInterceptor.metrics.accepted = 0;
1921
- _KafkaTraceInterceptor.metrics.acceptedWithoutTrace = 0;
1922
- _KafkaTraceInterceptor.metrics.dropped = 0;
1923
- }
1924
- /**
1925
- * @param config - TraceIdConfig options (extractor keys, contextKey, etc.)
1926
- * @param requireTraceId - When true, messages with no traceId are silently skipped
1927
- * (EMPTY Observable — message is ack'd, consumer stays alive).
1928
- * A WARN is logged AND `KafkaTraceInterceptor.metrics.dropped`
1929
- * increments so the missing traceId is observable end-to-end.
1930
- * Default: false (handler runs without trace context).
1931
- */
1932
- constructor(config, requireTraceId = false) {
1933
- this.config = config;
1934
- this.requireTraceId = requireTraceId;
1935
- this.ctx = TraceContext.instance;
1936
- this.config = {
1937
- enabled: true,
1938
- contextKey: "traceId",
1939
- extractor: {
1940
- body: [
1941
- "traceId",
1942
- "trace_id",
1943
- "x-trace-id"
1944
- ],
1945
- header: ["x-trace-id", "trace-id"]
1946
- },
1947
- ...config
1948
- };
1949
- }
1950
- intercept(context, next) {
1951
- var _this$config;
1952
- if (!((_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.enabled)) return next.handle();
1953
- const rpcContext = context.switchToRpc();
1954
- const data = rpcContext.getData();
1955
- const rpcData = rpcContext.getContext();
1956
- let traceId;
1957
- if (this.config.extractor) traceId = extractTraceId({
1958
- body: data,
1959
- headers: (rpcData === null || rpcData === void 0 ? void 0 : rpcData.headers) ?? {},
1960
- query: {},
1961
- params: {}
1962
- }, this.config.extractor);
1963
- if (!traceId) traceId = this.ctx.getCurrentTraceId();
1964
- if (!traceId) {
1965
- if (this.requireTraceId) {
1966
- var _LogixiaLoggerModule$;
1967
- _KafkaTraceInterceptor.metrics.dropped++;
1968
- (_LogixiaLoggerModule$ = LogixiaLoggerModule.getGlobalLogger()) === null || _LogixiaLoggerModule$ === void 0 || _LogixiaLoggerModule$.warn(`[KafkaTraceInterceptor] Missing traceId on topic "${rpcData === null || rpcData === void 0 ? void 0 : rpcData.topic}" — message skipped.`);
1969
- return EMPTY;
1970
- }
1971
- _KafkaTraceInterceptor.metrics.acceptedWithoutTrace++;
1972
- return next.handle();
1973
- }
1974
- _KafkaTraceInterceptor.metrics.accepted++;
1975
- const kafkaContext = {
1976
- messageType: "kafka",
1977
- topic: rpcData === null || rpcData === void 0 ? void 0 : rpcData.topic,
1978
- partition: rpcData === null || rpcData === void 0 ? void 0 : rpcData.partition,
1979
- offset: rpcData === null || rpcData === void 0 ? void 0 : rpcData.offset,
1980
- key: rpcData === null || rpcData === void 0 ? void 0 : rpcData.key,
1981
- timestamp: rpcData === null || rpcData === void 0 ? void 0 : rpcData.timestamp
1982
- };
1983
- return new Observable((subscriber) => {
1984
- let inner;
1985
- this.ctx.run(traceId, () => {
1986
- inner = next.handle().subscribe({
1987
- next: (value) => subscriber.next(value),
1988
- error: (err) => subscriber.error(err),
1989
- complete: () => subscriber.complete()
1990
- });
1991
- }, kafkaContext);
1992
- return () => inner === null || inner === void 0 ? void 0 : inner.unsubscribe();
1993
- });
1994
- }
1995
- };
1996
- KafkaTraceInterceptor = _KafkaTraceInterceptor = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [Object, Boolean])], KafkaTraceInterceptor);
1997
-
1998
- //#endregion
1999
- //#region \0@oxc-project+runtime@0.95.0/helpers/decorateParam.js
2000
- function __decorateParam(paramIndex, decorator) {
2001
- return function(target, key) {
2002
- decorator(target, key, paramIndex);
2003
- };
2004
- }
2005
-
2006
- //#endregion
2007
- //#region src/core/trace.middleware.ts
2008
- /** Default response header used to echo the resolved traceId back to the caller. */
2009
- const DEFAULT_TRACE_RESPONSE_HEADER = "X-Trace-Id";
2010
- /**
2011
- * Resolve the response header name from config.
2012
- * - `undefined` → default `'X-Trace-Id'`
2013
- * - `string` → user's custom header
2014
- * - `false` → `null` (suppress entirely)
2015
- */
2016
- function resolveResponseHeader(config) {
2017
- if ((config === null || config === void 0 ? void 0 : config.responseHeader) === false) return null;
2018
- return (config === null || config === void 0 ? void 0 : config.responseHeader) ?? DEFAULT_TRACE_RESPONSE_HEADER;
2019
- }
2020
- /**
2021
- * Echo the trace ID on the response, tolerating non-Express responses and
2022
- * already-sent headers. NestJS can run on Fastify (reply.header() instead of
2023
- * res.setHeader()), and on a closed/sent response setHeader throws — neither
2024
- * should crash the request. The trace ID is still propagated via async context.
2025
- */
2026
- function writeTraceHeader(res, header, traceId) {
2027
- const r = res;
2028
- if (r.headersSent) return;
2029
- try {
2030
- if (typeof r.setHeader === "function") r.setHeader(header, traceId);
2031
- else if (typeof r.header === "function") r.header(header, traceId);
2032
- } catch {}
2033
- }
2034
- let TraceMiddleware = class TraceMiddleware$1 {
2035
- constructor(config) {
2036
- this.config = config;
2037
- this.ctx = TraceContext.instance;
2038
- const defaultExtractor = {
2039
- header: DEFAULT_TRACE_HEADERS,
2040
- query: ["traceId", "trace_id"]
2041
- };
2042
- this.config = {
2043
- enabled: true,
2044
- generator: () => this.ctx.generate(),
2045
- contextKey: "traceId",
2046
- ...config,
2047
- extractor: (config === null || config === void 0 ? void 0 : config.extractor) ? {
2048
- ...defaultExtractor,
2049
- ...config.extractor
2050
- } : defaultExtractor
2051
- };
2052
- if (this.config.enabled) this.ctx.setContextKey(this.config.contextKey ?? "traceId");
2053
- }
2054
- use(req, res, next) {
2055
- var _this$config, _req$socket, _req$connection;
2056
- if (!((_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.enabled)) return next();
2057
- let traceId;
2058
- if (this.config.extractor) traceId = extractTraceId(req, this.config.extractor);
2059
- if (!traceId && this.config.generator) {
2060
- const candidate = this.config.generator();
2061
- if (typeof candidate === "string" && candidate.trim().length > 0) traceId = candidate;
2062
- else internalWarn("TraceIdConfig.generator returned a non-string/empty value — using built-in generator.");
2063
- }
2064
- if (!traceId) traceId = this.ctx.generate();
2065
- req.traceId = traceId;
2066
- const header = resolveResponseHeader(this.config);
2067
- if (header) writeTraceHeader(res, header, traceId);
2068
- this.ctx.run(traceId, () => next(), {
2069
- method: req.method,
2070
- url: req.url,
2071
- userAgent: req.get("User-Agent"),
2072
- ip: req.ip || ((_req$socket = req.socket) === null || _req$socket === void 0 ? void 0 : _req$socket.remoteAddress) || ((_req$connection = req.connection) === null || _req$connection === void 0 ? void 0 : _req$connection.remoteAddress)
2073
- });
2074
- }
2075
- };
2076
- TraceMiddleware = __decorate([
2077
- Injectable(),
2078
- __decorateParam(0, Optional()),
2079
- __decorateMetadata("design:paramtypes", [Object])
2080
- ], TraceMiddleware);
2081
-
2082
- //#endregion
2083
- //#region src/core/websocket-trace.interceptor.ts
2084
- let WebSocketTraceInterceptor = class WebSocketTraceInterceptor$1 {
2085
- constructor(config) {
2086
- this.config = config;
2087
- this.ctx = TraceContext.instance;
2088
- this.config = {
2089
- enabled: true,
2090
- contextKey: "traceId",
2091
- extractor: {
2092
- body: [
2093
- "traceId",
2094
- "trace_id",
2095
- "x-trace-id"
2096
- ],
2097
- header: ["x-trace-id", "trace-id"],
2098
- query: ["traceId", "trace_id"]
2099
- },
2100
- ...config
2101
- };
2102
- }
2103
- intercept(context, next) {
2104
- var _this$config, _client$handshake3;
2105
- if (!((_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.enabled)) return next.handle();
2106
- const wsContext = context.switchToWs();
2107
- const data = wsContext.getData();
2108
- const client = wsContext.getClient();
2109
- let traceId;
2110
- if (this.config.extractor) {
2111
- var _client$handshake, _client$handshake2;
2112
- traceId = extractTraceId({
2113
- body: data,
2114
- headers: (client === null || client === void 0 || (_client$handshake = client.handshake) === null || _client$handshake === void 0 ? void 0 : _client$handshake.headers) || {},
2115
- query: (client === null || client === void 0 || (_client$handshake2 = client.handshake) === null || _client$handshake2 === void 0 ? void 0 : _client$handshake2.query) || {},
2116
- params: {}
2117
- }, this.config.extractor);
2118
- }
2119
- if (!traceId) traceId = this.ctx.getCurrentTraceId();
2120
- if (!traceId) return next.handle();
2121
- const wsContextData = {
2122
- messageType: "websocket",
2123
- event: data === null || data === void 0 ? void 0 : data.event,
2124
- socketId: client === null || client === void 0 ? void 0 : client.id,
2125
- rooms: (client === null || client === void 0 ? void 0 : client.rooms) ? Array.from(client.rooms) : [],
2126
- clientAddress: client === null || client === void 0 || (_client$handshake3 = client.handshake) === null || _client$handshake3 === void 0 ? void 0 : _client$handshake3.address
2127
- };
2128
- return new Observable((observer) => {
2129
- let inner;
2130
- this.ctx.run(traceId, () => {
2131
- inner = next.handle().subscribe({
2132
- next: (value) => observer.next(value),
2133
- error: (err) => observer.error(err),
2134
- complete: () => observer.complete()
2135
- });
2136
- }, wsContextData);
2137
- return () => inner === null || inner === void 0 ? void 0 : inner.unsubscribe();
2138
- });
2139
- }
2140
- };
2141
- WebSocketTraceInterceptor = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [Object])], WebSocketTraceInterceptor);
2142
-
2143
- //#endregion
2144
- //#region src/core/logitron-logger.module.ts
2145
- var _LogixiaLoggerModule;
2146
- const DEFAULT_ROUTES = [{
2147
- path: "*",
2148
- method: RequestMethod.ALL
2149
- }];
2150
- const LOGIXIA_LOGGER_CONFIG = "LOGIXIA_LOGGER_CONFIG";
2151
- const LOGIXIA_TRACE_CONFIG = "TRACE_CONFIG";
2152
- const LOGIXIA_LOGGER_PREFIX = "LOGIXIA_LOGGER_";
2153
- let LogixiaLoggerModule = class LogixiaLoggerModule$1 {
2154
- static {
2155
- _LogixiaLoggerModule = this;
2156
- }
2157
- constructor() {
2158
- this.config = {};
2159
- }
2160
- static #_ = this.loggerConfig = {};
2161
- static #_2 = this._globalLogger = null;
2162
- /**
2163
- * @internal Set the global logger exactly once.
2164
- *
2165
- * Called from the module's forRoot / forRootAsync factory. If the module is
2166
- * initialised more than once in the same process (nested DI context, test
2167
- * harness creating multiple apps, hot reload, etc.) a warning is written to
2168
- * stderr and the first logger wins — silently overwriting would allow the
2169
- * newer instance's transport config to replace the live one while the old
2170
- * one is still being used by registered shutdown hooks, decorators, etc.
2171
- *
2172
- * Use {@link _resetGlobalLogger} in tests to reset between runs.
2173
- */
2174
- static _setGlobalLogger(service) {
2175
- if (_LogixiaLoggerModule._globalLogger !== null) {
2176
- internalWarn("LogixiaLoggerModule.forRoot() was called more than once — ignoring the second init. If this is intentional (e.g. in tests), call LogixiaLoggerModule._resetGlobalLogger() first.");
2177
- return;
2178
- }
2179
- _LogixiaLoggerModule._globalLogger = service;
2180
- }
2181
- /** @internal Clear the global logger. Tests only. */
2182
- static _resetGlobalLogger() {
2183
- _LogixiaLoggerModule._globalLogger = null;
2184
- }
2185
- /**
2186
- * Returns the global LogixiaLoggerService instance that was created when the
2187
- * module booted. Useful for logging outside of NestJS DI — utility functions,
2188
- * plain scripts, decorators — without injecting the service everywhere.
2189
- *
2190
- * Returns `null` if called before `LogixiaLoggerModule.forRoot[Async]()` has
2191
- * been initialised (i.e. before the NestJS app has started).
2192
- *
2193
- * @example
2194
- * ```ts
2195
- * // some-util.ts
2196
- * import { LogixiaLoggerModule } from 'logixia/nest';
2197
- *
2198
- * export function doSomething() {
2199
- * LogixiaLoggerModule.getGlobalLogger()?.info('doing something');
2200
- * }
2201
- * ```
2202
- */
2203
- static getGlobalLogger() {
2204
- return _LogixiaLoggerModule._globalLogger;
2205
- }
2206
- configure(consumer) {
2207
- const { forRoutes = DEFAULT_ROUTES, exclude } = this.config;
2208
- let resolvedTraceConfig;
2209
- if (typeof _LogixiaLoggerModule.loggerConfig.traceId === "object") resolvedTraceConfig = _LogixiaLoggerModule.loggerConfig.traceId;
2210
- else if (_LogixiaLoggerModule.loggerConfig.traceId === true) resolvedTraceConfig = {
2211
- enabled: true,
2212
- contextKey: "traceId",
2213
- generator: () => TraceContext.instance.generate()
2214
- };
2215
- const middleware = new TraceMiddleware(resolvedTraceConfig);
2216
- const middlewareConfig = (req, res, next) => middleware.use(req, res, next);
2217
- if (exclude) consumer.apply(middlewareConfig).exclude(...exclude).forRoutes(...forRoutes);
2218
- else consumer.apply(middlewareConfig).forRoutes(...forRoutes);
2219
- }
2220
- /**
2221
- * Configure the module with synchronous options
2222
- */
2223
- static forRoot(config) {
2224
- _LogixiaLoggerModule.loggerConfig = config || {};
2225
- const traceConfig = (config === null || config === void 0 ? void 0 : config.traceId) && typeof config.traceId === "object" ? config.traceId : { enabled: !!(config === null || config === void 0 ? void 0 : config.traceId) };
2226
- return {
2227
- module: _LogixiaLoggerModule,
2228
- providers: [
2229
- {
2230
- provide: LOGIXIA_LOGGER_CONFIG,
2231
- useValue: config || {}
2232
- },
2233
- {
2234
- provide: LOGIXIA_TRACE_CONFIG,
2235
- useValue: traceConfig
2236
- },
2237
- {
2238
- provide: LogixiaLoggerService,
2239
- useFactory: (loggerConfig) => {
2240
- const service = new LogixiaLoggerService({
2241
- level: "info",
2242
- service: "NestJSApp",
2243
- environment: "development",
2244
- fields: {},
2245
- formatters: ["text"],
2246
- outputs: ["console"],
2247
- levelOptions: {
2248
- level: "info",
2249
- levels: {
2250
- error: 0,
2251
- warn: 1,
2252
- info: 2,
2253
- debug: 3,
2254
- verbose: 4
2255
- },
2256
- colors: {
2257
- error: "red",
2258
- warn: "yellow",
2259
- info: "green",
2260
- debug: "blue",
2261
- verbose: "cyan"
2262
- }
2263
- },
2264
- ...loggerConfig
2265
- });
2266
- _LogixiaLoggerModule._setGlobalLogger(service);
2267
- return service;
2268
- },
2269
- inject: [LOGIXIA_LOGGER_CONFIG]
2270
- },
2271
- {
2272
- provide: KafkaTraceInterceptor,
2273
- useFactory: (traceConfig$1) => new KafkaTraceInterceptor(traceConfig$1),
2274
- inject: [LOGIXIA_TRACE_CONFIG]
2275
- },
2276
- {
2277
- provide: WebSocketTraceInterceptor,
2278
- useFactory: (traceConfig$1) => new WebSocketTraceInterceptor(traceConfig$1),
2279
- inject: [LOGIXIA_TRACE_CONFIG]
2280
- }
2281
- ],
2282
- exports: [
2283
- LogixiaLoggerService,
2284
- LOGIXIA_LOGGER_CONFIG,
2285
- KafkaTraceInterceptor,
2286
- WebSocketTraceInterceptor
2287
- ],
2288
- global: true
2289
- };
2290
- }
2291
- /**
2292
- * Configure the module with asynchronous options
2293
- */
2294
- static forRootAsync(options) {
2295
- return {
2296
- module: _LogixiaLoggerModule,
2297
- imports: options.imports || [],
2298
- providers: [
2299
- ...this.createAsyncProviders(options),
2300
- {
2301
- provide: LOGIXIA_TRACE_CONFIG,
2302
- useFactory: (loggerConfig) => {
2303
- return typeof (loggerConfig === null || loggerConfig === void 0 ? void 0 : loggerConfig.traceId) === "object" ? loggerConfig.traceId : { enabled: !!(loggerConfig === null || loggerConfig === void 0 ? void 0 : loggerConfig.traceId) };
2304
- },
2305
- inject: [LOGIXIA_LOGGER_CONFIG]
2306
- },
2307
- {
2308
- provide: LogixiaLoggerService,
2309
- useFactory: (loggerConfig) => {
2310
- const defaultConfig = {
2311
- level: "info",
2312
- service: "NestJSApp",
2313
- environment: "development",
2314
- fields: {},
2315
- formatters: ["text"],
2316
- outputs: ["console"],
2317
- levelOptions: {
2318
- level: "info",
2319
- levels: {
2320
- error: 0,
2321
- warn: 1,
2322
- info: 2,
2323
- debug: 3,
2324
- verbose: 4
2325
- },
2326
- colors: {
2327
- error: "red",
2328
- warn: "yellow",
2329
- info: "green",
2330
- debug: "blue",
2331
- verbose: "cyan"
2332
- }
2333
- },
2334
- ...loggerConfig
2335
- };
2336
- _LogixiaLoggerModule.loggerConfig = defaultConfig;
2337
- const service = new LogixiaLoggerService(defaultConfig);
2338
- _LogixiaLoggerModule._setGlobalLogger(service);
2339
- return service;
2340
- },
2341
- inject: [LOGIXIA_LOGGER_CONFIG]
2342
- },
2343
- {
2344
- provide: KafkaTraceInterceptor,
2345
- useFactory: (traceConfig) => new KafkaTraceInterceptor(traceConfig),
2346
- inject: [LOGIXIA_TRACE_CONFIG]
2347
- },
2348
- {
2349
- provide: WebSocketTraceInterceptor,
2350
- useFactory: (traceConfig) => new WebSocketTraceInterceptor(traceConfig),
2351
- inject: [LOGIXIA_TRACE_CONFIG]
2352
- }
2353
- ],
2354
- exports: [
2355
- LogixiaLoggerService,
2356
- LOGIXIA_LOGGER_CONFIG,
2357
- KafkaTraceInterceptor,
2358
- WebSocketTraceInterceptor
2359
- ],
2360
- global: true
2361
- };
2362
- }
2363
- /**
2364
- * Create feature-specific logger instances
2365
- */
2366
- static forFeature(context) {
2367
- const providerToken = `${LOGIXIA_LOGGER_PREFIX}${context.toUpperCase()}`;
2368
- return {
2369
- module: _LogixiaLoggerModule,
2370
- providers: [{
2371
- provide: providerToken,
2372
- useFactory: (baseLogger) => {
2373
- return baseLogger.child(context);
2374
- },
2375
- inject: [LogixiaLoggerService]
2376
- }],
2377
- exports: [providerToken]
2378
- };
2379
- }
2380
- static createAsyncProviders(options) {
2381
- if (options.useExisting || options.useFactory) return [this.createAsyncOptionsProvider(options)];
2382
- return [this.createAsyncOptionsProvider(options), {
2383
- provide: options.useClass,
2384
- useClass: options.useClass
2385
- }];
2386
- }
2387
- static createAsyncOptionsProvider(options) {
2388
- if (options.useFactory) return {
2389
- provide: LOGIXIA_LOGGER_CONFIG,
2390
- useFactory: options.useFactory,
2391
- inject: options.inject || []
2392
- };
2393
- return {
2394
- provide: LOGIXIA_LOGGER_CONFIG,
2395
- useFactory: async (optionsFactory) => await optionsFactory.createLogixiaOptions(),
2396
- inject: [options.useExisting || options.useClass]
2397
- };
2398
- }
2399
- };
2400
- LogixiaLoggerModule = _LogixiaLoggerModule = __decorate([Module({})], LogixiaLoggerModule);
2401
-
2402
- //#endregion
2403
- //#region src/exceptions/exception.ts
1867
+ // src/exceptions/exception.ts
2404
1868
  var LogixiaException = class extends Error {
2405
1869
  constructor(options) {
2406
1870
  super(options.message, { cause: options.cause });
@@ -2431,9 +1895,21 @@ var LogixiaException = class extends Error {
2431
1895
  function isLogixiaException(value) {
2432
1896
  return value instanceof LogixiaException;
2433
1897
  }
2434
-
2435
- //#endregion
2436
- //#region src/exceptions/builder.ts
1898
+ // src/exceptions/builder.ts
1899
+ /**
1900
+ * ErrorResponseBuilder — turns any exception into a `LogixiaErrorResponse`.
1901
+ *
1902
+ * Priority order:
1903
+ * 1. `LogixiaException` — typed fields used directly
1904
+ * 2. NestJS `HttpException` — duck-typed; status + message extracted
1905
+ * 3. Plain `Error` / unknown — falls back to 500 `server_error`
1906
+ *
1907
+ * The builder **always** populates `debug` when possible.
1908
+ * Your exception filter is responsible for stripping it in production:
1909
+ * ```ts
1910
+ * if (process.env.NODE_ENV === 'production') delete response.debug;
1911
+ * ```
1912
+ */
2437
1913
  /**
2438
1914
  * Generates a trace ID via the shared {@link TraceContext} generator.
2439
1915
  *
@@ -2535,7 +2011,7 @@ var ErrorResponseBuilder = class {
2535
2011
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
2536
2012
  const durationMs = startTime !== void 0 ? Date.now() - startTime : void 0;
2537
2013
  if (isLogixiaException(exception)) {
2538
- const debug$1 = buildDebug(exception, service, durationMs, expose);
2014
+ const debug = buildDebug(exception, service, durationMs, expose);
2539
2015
  const errorBlock = {
2540
2016
  type: exception.errorType,
2541
2017
  code: exception.errorCode,
@@ -2554,7 +2030,7 @@ var ErrorResponseBuilder = class {
2554
2030
  path,
2555
2031
  status: exception.httpStatus
2556
2032
  },
2557
- ...debug$1 !== void 0 ? { debug: debug$1 } : {}
2033
+ ...debug !== void 0 ? { debug } : {}
2558
2034
  },
2559
2035
  httpStatus: exception.httpStatus
2560
2036
  };
@@ -2570,7 +2046,7 @@ var ErrorResponseBuilder = class {
2570
2046
  } else message = exception.message;
2571
2047
  const type = httpStatusToType(status);
2572
2048
  const code = `HTTP_${status}`;
2573
- const debug$1 = buildDebug(exception, service, durationMs, expose);
2049
+ const debug = buildDebug(exception, service, durationMs, expose);
2574
2050
  return {
2575
2051
  response: {
2576
2052
  success: false,
@@ -2585,7 +2061,7 @@ var ErrorResponseBuilder = class {
2585
2061
  path,
2586
2062
  status
2587
2063
  },
2588
- ...debug$1 !== void 0 ? { debug: debug$1 } : {}
2064
+ ...debug !== void 0 ? { debug } : {}
2589
2065
  },
2590
2066
  httpStatus: status
2591
2067
  };
@@ -2611,168 +2087,6 @@ var ErrorResponseBuilder = class {
2611
2087
  };
2612
2088
  }
2613
2089
  };
2090
+ export { globalPluginRegistry as C, DEFAULT_LOG_LEVELS as D, DEFAULT_LOG_COLORS as E, LogLevel as O, PluginRegistry as S, DEFAULT_CONFIG as T, getOtelMetaFields as _, isLogixiaException as a, normalizeError as b, _shutdownRegistrySize as c, registerForShutdown as d, resetShutdownHandlers as f, getActiveOtelContext as g, disableOtelBridge as h, LogixiaException as i, deregisterFromShutdown as l, redactObject as m, generateRequestId as n, LogixiaLogger as o, applyRedaction as p, generateTraceId as r, createLogger as s, ErrorResponseBuilder as t, flushOnExit as u, initOtelBridge as v, usePlugin as w, serializeError as x, isError as y };
2614
2091
 
2615
- //#endregion
2616
- //#region src/core/nestjs-extras.ts
2617
- var _ref;
2618
- /**
2619
- * Inject the Logixia logger registered in the current NestJS DI container.
2620
- *
2621
- * Equivalent to `@Inject(LOGIXIA_LOGGER_TOKEN)` but without needing to import
2622
- * the internal token constant yourself.
2623
- *
2624
- * @example
2625
- * ```ts
2626
- * constructor(@InjectLogger() private readonly logger: LogixiaLoggerService) {}
2627
- * ```
2628
- */
2629
- const InjectLogger = () => Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`);
2630
- /**
2631
- * Method decorator that auto-logs entry, exit, duration, and errors.
2632
- *
2633
- * Preserves the original method's sync/async contract: a synchronous method
2634
- * stays synchronous (returns its value directly, with logs emitted
2635
- * fire-and-forget), and an async method is awaited so exit/error logs reflect
2636
- * the resolved result. Attaches to the logger found on the class instance via a
2637
- * `logger` property (the conventional NestJS name).
2638
- *
2639
- * @example
2640
- * ```ts
2641
- * @LogMethod({ level: 'info', logArgs: true })
2642
- * async processPayment(orderId: string): Promise<void> { … }
2643
- * ```
2644
- */
2645
- function LogMethod(options = {}) {
2646
- const { level = "debug", logArgs = true, logResult = false, logErrors = true } = options;
2647
- return function(target, propertyKey, descriptor) {
2648
- var _constructor;
2649
- const originalMethod = descriptor.value;
2650
- if (typeof originalMethod !== "function") return descriptor;
2651
- const methodName = String(propertyKey);
2652
- const className = ((_constructor = target.constructor) === null || _constructor === void 0 ? void 0 : _constructor.name) ?? "Unknown";
2653
- const label = options.label ?? `${className}.${methodName}`;
2654
- let _warnedNoLogger = false;
2655
- const reportLogFailure = (phase, err) => {
2656
- internalError(`@LogMethod(${label}) ${phase} log failed: ${String(err)}`);
2657
- };
2658
- const emit = (logger, phase, message, data) => {
2659
- const logFnRaw = logger[level];
2660
- const p = (typeof logFnRaw === "function" ? logFnRaw : logger.debug).bind(logger)(message, data);
2661
- if (p && typeof p.catch === "function") p.catch((e) => reportLogFailure(phase, e));
2662
- };
2663
- const emitError = (logger, error, start) => {
2664
- const err = error instanceof Error ? error : new Error(String(error));
2665
- const errLog = logger.error(err, {
2666
- method: label,
2667
- durationMs: Date.now() - start
2668
- });
2669
- if (errLog && typeof errLog.catch === "function") errLog.catch((e) => reportLogFailure("error", e));
2670
- };
2671
- descriptor.value = function(...args) {
2672
- const logger = this.logger ?? LogixiaLoggerModule._globalLogger ?? void 0;
2673
- if (!logger && !_warnedNoLogger) {
2674
- _warnedNoLogger = true;
2675
- internalWarn(`@LogMethod on ${label}: no logger available. Either inject LogixiaLoggerService as this.logger or ensure LogixiaLoggerModule is initialised.`);
2676
- }
2677
- const start = Date.now();
2678
- const entry = { method: label };
2679
- if (logArgs && args.length > 0) entry["args"] = args;
2680
- if (logger) emit(logger, "entry", `→ ${label}`, entry);
2681
- const buildExit = (result$1) => {
2682
- const exit = {
2683
- method: label,
2684
- durationMs: Date.now() - start
2685
- };
2686
- if (logResult) exit["result"] = result$1;
2687
- return exit;
2688
- };
2689
- let result;
2690
- try {
2691
- result = originalMethod.apply(this, args);
2692
- } catch (error) {
2693
- if (logger && logErrors) emitError(logger, error, start);
2694
- throw error;
2695
- }
2696
- if (result && typeof result.then === "function") return result.then((resolved) => {
2697
- if (logger) emit(logger, "exit", `← ${label}`, buildExit(resolved));
2698
- return resolved;
2699
- }, (error) => {
2700
- if (logger && logErrors) emitError(logger, error, start);
2701
- throw error;
2702
- });
2703
- if (logger) emit(logger, "exit", `← ${label}`, buildExit(result));
2704
- return result;
2705
- };
2706
- return descriptor;
2707
- };
2708
- }
2709
- /** Injection token for {@link LogixiaExceptionFilterOptions}. */
2710
- const LOGIXIA_EXCEPTION_FILTER_OPTIONS = "LOGIXIA_EXCEPTION_FILTER_OPTIONS";
2711
- let LogixiaExceptionFilter = class LogixiaExceptionFilter$1 {
2712
- constructor(logger, loggerConfig, options) {
2713
- this._options = options ?? {};
2714
- this._logger = logger ?? LogixiaLoggerModule._globalLogger ?? void 0;
2715
- this._traceConfig = typeof (loggerConfig === null || loggerConfig === void 0 ? void 0 : loggerConfig.traceId) === "object" ? loggerConfig.traceId : void 0;
2716
- }
2717
- catch(exception, host) {
2718
- var _request$headers;
2719
- const ctx = host.switchToHttp();
2720
- const request = ctx.getRequest();
2721
- const response = ctx.getResponse();
2722
- const traceId = TraceContext.instance.getCurrentTraceId() ?? sanitizeIncomingId((_request$headers = request.headers) === null || _request$headers === void 0 ? void 0 : _request$headers["x-trace-id"]) ?? sanitizeIncomingId(request.id) ?? void 0;
2723
- const { response: errorResponse, httpStatus } = ErrorResponseBuilder.build({
2724
- exception,
2725
- traceId,
2726
- path: request.url ?? "/",
2727
- startTime: request.startTime,
2728
- exposeDebug: this._options.exposeDebug === true,
2729
- exposeCause: this._options.exposeCause === true
2730
- });
2731
- if (this._logger) {
2732
- const requestMeta = {
2733
- method: request.method ?? "",
2734
- url: request.url ?? "",
2735
- status: httpStatus,
2736
- ...errorResponse.meta.trace_id !== void 0 ? { trace_id: errorResponse.meta.trace_id } : {}
2737
- };
2738
- const onLogFailure = (err) => {
2739
- internalError(`ExceptionFilter failed to write log entry: ${String(err)}`);
2740
- };
2741
- let logPromise;
2742
- if (httpStatus >= 500) {
2743
- const err = exception instanceof Error ? exception : new Error(String(exception));
2744
- logPromise = this._logger.error(err, requestMeta);
2745
- } else if (isLogixiaException(exception)) logPromise = this._logger.warn(`[${errorResponse.error.code}] ${errorResponse.error.message}`, requestMeta);
2746
- else logPromise = this._logger.warn(`[${httpStatus}] ${errorResponse.error.message}`, requestMeta);
2747
- if (logPromise && typeof logPromise.catch === "function") logPromise.catch(onLogFailure);
2748
- }
2749
- if (errorResponse.meta.trace_id) {
2750
- const traceHeader = resolveResponseHeader(this._traceConfig);
2751
- if (traceHeader) try {
2752
- response.setHeader(traceHeader, errorResponse.meta.trace_id);
2753
- } catch {}
2754
- }
2755
- if (httpStatus === 429) try {
2756
- response.setHeader("Retry-After", "60");
2757
- } catch {}
2758
- response.status(httpStatus).json(errorResponse);
2759
- }
2760
- };
2761
- LogixiaExceptionFilter = __decorate([
2762
- Catch(),
2763
- __decorateParam(0, Optional()),
2764
- __decorateParam(0, Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`)),
2765
- __decorateParam(1, Optional()),
2766
- __decorateParam(1, Inject(LOGIXIA_LOGGER_CONFIG)),
2767
- __decorateParam(2, Optional()),
2768
- __decorateParam(2, Inject(LOGIXIA_EXCEPTION_FILTER_OPTIONS)),
2769
- __decorateMetadata("design:paramtypes", [
2770
- Object,
2771
- typeof (_ref = typeof Partial !== "undefined" && Partial) === "function" ? _ref : Object,
2772
- Object
2773
- ])
2774
- ], LogixiaExceptionFilter);
2775
-
2776
- //#endregion
2777
- export { initOtelBridge as A, registerForShutdown as C, disableOtelBridge as D, redactObject as E, DEFAULT_LOG_LEVELS as F, LogLevel as I, PluginRegistry as L, normalizeError as M, serializeError as N, getActiveOtelContext as O, DEFAULT_LOG_COLORS as P, globalPluginRegistry as R, flushOnExit as S, applyRedaction as T, LogixiaLoggerService as _, ErrorResponseBuilder as a, _shutdownRegistrySize as b, LogixiaException as c, LOGIXIA_LOGGER_PREFIX as d, LOGIXIA_TRACE_CONFIG as f, KafkaTraceInterceptor as g, TraceMiddleware as h, LogixiaExceptionFilter as i, isError as j, getOtelMetaFields as k, isLogixiaException as l, WebSocketTraceInterceptor as m, LOGIXIA_EXCEPTION_FILTER_OPTIONS as n, generateRequestId as o, LogixiaLoggerModule as p, LogMethod as r, generateTraceId as s, InjectLogger as t, LOGIXIA_LOGGER_CONFIG as u, LogixiaLogger as v, resetShutdownHandlers as w, deregisterFromShutdown as x, createLogger as y, usePlugin as z };
2778
- //# sourceMappingURL=nestjs-extras-ImbuDhs1.mjs.map
2092
+ //# sourceMappingURL=builder-D70z6kjj.mjs.map