@catbee/utils 0.0.6 → 0.0.7

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 (122) hide show
  1. package/README.md +51 -1106
  2. package/build/esm/config.d.ts +5 -13
  3. package/build/esm/config.js +0 -12
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/servers/server.builder.d.ts +1 -118
  6. package/build/esm/servers/server.builder.js +0 -20
  7. package/build/esm/servers/server.builder.js.map +1 -1
  8. package/build/esm/servers/server.d.ts +2 -2
  9. package/build/esm/servers/server.js +3 -13
  10. package/build/esm/servers/server.js.map +1 -1
  11. package/build/esm/types/api-response.d.ts +28 -0
  12. package/build/esm/types/api-response.js +10 -1
  13. package/build/esm/types/api-response.js.map +1 -1
  14. package/build/esm/types/server.d.ts +0 -17
  15. package/build/esm/types/server.js.map +1 -1
  16. package/build/esm/utils/async.utils.d.ts +91 -0
  17. package/build/esm/utils/async.utils.js +244 -0
  18. package/build/esm/utils/async.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +3 -0
  20. package/build/esm/utils/context-store.utils.js +9 -6
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/date.utils.d.ts +159 -0
  23. package/build/esm/utils/date.utils.js +389 -0
  24. package/build/esm/utils/date.utils.js.map +1 -0
  25. package/build/esm/utils/logger.utils.d.ts +3 -9
  26. package/build/esm/utils/logger.utils.js +3 -9
  27. package/build/esm/utils/logger.utils.js.map +1 -1
  28. package/build/esm/utils/middleware.utils.js +2 -1
  29. package/build/esm/utils/middleware.utils.js.map +1 -1
  30. package/build/esm/utils/performance.utils.d.ts +136 -0
  31. package/build/esm/utils/performance.utils.js +376 -0
  32. package/build/esm/utils/performance.utils.js.map +1 -0
  33. package/build/esm/utils/request.utils.d.ts +9 -0
  34. package/build/esm/utils/request.utils.js +32 -5
  35. package/build/esm/utils/request.utils.js.map +1 -1
  36. package/build/esm/utils/stream.utils.d.ts +88 -0
  37. package/build/esm/utils/stream.utils.js +284 -0
  38. package/build/esm/utils/stream.utils.js.map +1 -0
  39. package/build/esm/utils/type.utils.d.ts +90 -0
  40. package/build/esm/utils/type.utils.js +190 -0
  41. package/build/esm/utils/type.utils.js.map +1 -0
  42. package/build/esnext/config.d.ts +5 -13
  43. package/build/esnext/config.js +0 -12
  44. package/build/esnext/config.js.map +1 -1
  45. package/build/esnext/servers/server.builder.d.ts +1 -118
  46. package/build/esnext/servers/server.builder.js +0 -20
  47. package/build/esnext/servers/server.builder.js.map +1 -1
  48. package/build/esnext/servers/server.d.ts +2 -2
  49. package/build/esnext/servers/server.js +3 -13
  50. package/build/esnext/servers/server.js.map +1 -1
  51. package/build/esnext/types/api-response.d.ts +28 -0
  52. package/build/esnext/types/api-response.js +10 -1
  53. package/build/esnext/types/api-response.js.map +1 -1
  54. package/build/esnext/types/server.d.ts +0 -17
  55. package/build/esnext/types/server.js.map +1 -1
  56. package/build/esnext/utils/async.utils.d.ts +91 -0
  57. package/build/esnext/utils/async.utils.js +190 -0
  58. package/build/esnext/utils/async.utils.js.map +1 -1
  59. package/build/esnext/utils/context-store.utils.d.ts +3 -0
  60. package/build/esnext/utils/context-store.utils.js +9 -6
  61. package/build/esnext/utils/context-store.utils.js.map +1 -1
  62. package/build/esnext/utils/date.utils.d.ts +159 -0
  63. package/build/esnext/utils/date.utils.js +384 -0
  64. package/build/esnext/utils/date.utils.js.map +1 -0
  65. package/build/esnext/utils/logger.utils.d.ts +3 -9
  66. package/build/esnext/utils/logger.utils.js +3 -9
  67. package/build/esnext/utils/logger.utils.js.map +1 -1
  68. package/build/esnext/utils/middleware.utils.js +2 -1
  69. package/build/esnext/utils/middleware.utils.js.map +1 -1
  70. package/build/esnext/utils/performance.utils.d.ts +136 -0
  71. package/build/esnext/utils/performance.utils.js +271 -0
  72. package/build/esnext/utils/performance.utils.js.map +1 -0
  73. package/build/esnext/utils/request.utils.d.ts +9 -0
  74. package/build/esnext/utils/request.utils.js +23 -5
  75. package/build/esnext/utils/request.utils.js.map +1 -1
  76. package/build/esnext/utils/stream.utils.d.ts +88 -0
  77. package/build/esnext/utils/stream.utils.js +210 -0
  78. package/build/esnext/utils/stream.utils.js.map +1 -0
  79. package/build/esnext/utils/type.utils.d.ts +90 -0
  80. package/build/esnext/utils/type.utils.js +187 -0
  81. package/build/esnext/utils/type.utils.js.map +1 -0
  82. package/build/src/config.d.ts +5 -13
  83. package/build/src/config.js +0 -12
  84. package/build/src/config.js.map +1 -1
  85. package/build/src/servers/server.builder.d.ts +1 -118
  86. package/build/src/servers/server.builder.js +0 -20
  87. package/build/src/servers/server.builder.js.map +1 -1
  88. package/build/src/servers/server.d.ts +2 -2
  89. package/build/src/servers/server.js +2 -12
  90. package/build/src/servers/server.js.map +1 -1
  91. package/build/src/types/api-response.d.ts +28 -0
  92. package/build/src/types/api-response.js +11 -0
  93. package/build/src/types/api-response.js.map +1 -1
  94. package/build/src/types/server.d.ts +0 -17
  95. package/build/src/types/server.js.map +1 -1
  96. package/build/src/utils/async.utils.d.ts +91 -0
  97. package/build/src/utils/async.utils.js +194 -0
  98. package/build/src/utils/async.utils.js.map +1 -1
  99. package/build/src/utils/context-store.utils.d.ts +3 -0
  100. package/build/src/utils/context-store.utils.js +9 -6
  101. package/build/src/utils/context-store.utils.js.map +1 -1
  102. package/build/src/utils/date.utils.d.ts +159 -0
  103. package/build/src/utils/date.utils.js +396 -0
  104. package/build/src/utils/date.utils.js.map +1 -0
  105. package/build/src/utils/logger.utils.d.ts +3 -9
  106. package/build/src/utils/logger.utils.js +4 -10
  107. package/build/src/utils/logger.utils.js.map +1 -1
  108. package/build/src/utils/middleware.utils.js +2 -1
  109. package/build/src/utils/middleware.utils.js.map +1 -1
  110. package/build/src/utils/performance.utils.d.ts +136 -0
  111. package/build/src/utils/performance.utils.js +278 -0
  112. package/build/src/utils/performance.utils.js.map +1 -0
  113. package/build/src/utils/request.utils.d.ts +9 -0
  114. package/build/src/utils/request.utils.js +25 -5
  115. package/build/src/utils/request.utils.js.map +1 -1
  116. package/build/src/utils/stream.utils.d.ts +88 -0
  117. package/build/src/utils/stream.utils.js +218 -0
  118. package/build/src/utils/stream.utils.js.map +1 -0
  119. package/build/src/utils/type.utils.d.ts +90 -0
  120. package/build/src/utils/type.utils.js +196 -0
  121. package/build/src/utils/type.utils.js.map +1 -0
  122. package/package.json +6 -2
@@ -0,0 +1,384 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ /**
25
+ * Format a date according to the specified format pattern.
26
+ *
27
+ * @param date - Date to format
28
+ * @param options - Formatting options
29
+ * @returns Formatted date string
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * // Format as ISO date
34
+ * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'
35
+ *
36
+ * // Format with time
37
+ * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'
38
+ *
39
+ * // Format with locale
40
+ * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'
41
+ * ```
42
+ */
43
+ export function formatDate(date, options = {}) {
44
+ const { format = 'yyyy-MM-dd', locale, timeZone } = options;
45
+ const d = date instanceof Date ? date : new Date(date);
46
+ // Custom formatter for common patterns
47
+ if (format === 'yyyy-MM-dd') {
48
+ const yyyy = d.getFullYear();
49
+ const mm = String(d.getMonth() + 1).padStart(2, '0');
50
+ const dd = String(d.getDate()).padStart(2, '0');
51
+ return `${yyyy}-${mm}-${dd}`;
52
+ }
53
+ if (format === 'yyyy-MM-dd HH:mm:ss') {
54
+ const yyyy = d.getFullYear();
55
+ const mm = String(d.getMonth() + 1).padStart(2, '0');
56
+ const dd = String(d.getDate()).padStart(2, '0');
57
+ const HH = String(d.getHours()).padStart(2, '0');
58
+ const MM = String(d.getMinutes()).padStart(2, '0');
59
+ const SS = String(d.getSeconds()).padStart(2, '0');
60
+ return `${yyyy}-${mm}-${dd} ${HH}:${MM}:${SS}`;
61
+ }
62
+ if (format === 'relative') {
63
+ return formatRelativeTime(date);
64
+ }
65
+ // Fallback to Intl.DateTimeFormat for other formats
66
+ return new Intl.DateTimeFormat(locale, {
67
+ timeZone,
68
+ year: format.includes('yyyy') || format.includes('y') ? 'numeric' : undefined,
69
+ month: format.includes('MM') || format.includes('M') ? 'numeric' : undefined,
70
+ day: format.includes('dd') || format.includes('d') ? 'numeric' : undefined,
71
+ hour: format.includes('HH') || format.includes('H') ? 'numeric' : undefined,
72
+ minute: format.includes('mm') || format.includes('m') ? 'numeric' : undefined,
73
+ second: format.includes('ss') || format.includes('s') ? 'numeric' : undefined,
74
+ hour12: !format.includes('HH') && !format.includes('H')
75
+ }).format(d);
76
+ }
77
+ /**
78
+ * Format a date as relative time (e.g., "5 minutes ago", "in 3 days").
79
+ *
80
+ * @param date - Date to format
81
+ * @param now - Reference date (default: current time)
82
+ * @param locale - Locale to use for formatting
83
+ * @returns Formatted relative time string
84
+ */
85
+ export function formatRelativeTime(date, now = new Date(), locale) {
86
+ const d1 = date instanceof Date ? date : new Date(date);
87
+ const d2 = now instanceof Date ? now : new Date(now);
88
+ const diffMs = d1.getTime() - d2.getTime();
89
+ const diffSecs = Math.round(diffMs / 1000);
90
+ const diffMins = Math.round(diffSecs / 60);
91
+ const diffHours = Math.round(diffMins / 60);
92
+ const diffDays = Math.round(diffHours / 24);
93
+ const diffMonths = Math.round(diffDays / 30);
94
+ const diffYears = Math.round(diffDays / 365);
95
+ const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
96
+ if (Math.abs(diffSecs) < 60)
97
+ return formatter.format(diffSecs, 'second');
98
+ if (Math.abs(diffMins) < 60)
99
+ return formatter.format(diffMins, 'minute');
100
+ if (Math.abs(diffHours) < 24)
101
+ return formatter.format(diffHours, 'hour');
102
+ if (Math.abs(diffDays) < 30)
103
+ return formatter.format(diffDays, 'day');
104
+ if (Math.abs(diffMonths) < 12)
105
+ return formatter.format(diffMonths, 'month');
106
+ return formatter.format(diffYears, 'year');
107
+ }
108
+ /**
109
+ * Parse a date string or timestamp into a Date object.
110
+ *
111
+ * @param input - Date string or timestamp to parse
112
+ * @param fallback - Fallback date if parsing fails
113
+ * @returns Parsed Date object or fallback
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * parseDate('2023-05-15'); // Date object for May 15, 2023
118
+ * parseDate('invalid', new Date()); // Returns current date as fallback
119
+ * ```
120
+ */
121
+ export function parseDate(input, fallback) {
122
+ if (typeof input === 'number') {
123
+ return new Date(input);
124
+ }
125
+ try {
126
+ const date = new Date(input);
127
+ // Check if date is valid
128
+ if (isNaN(date.getTime())) {
129
+ return fallback || null;
130
+ }
131
+ return date;
132
+ }
133
+ catch (_a) {
134
+ return fallback || null;
135
+ }
136
+ }
137
+ /**
138
+ * Calculate the difference between two dates in the specified unit.
139
+ *
140
+ * @param date1 - First date
141
+ * @param date2 - Second date (default: current time)
142
+ * @param unit - Unit of time for the difference
143
+ * @returns Difference in the specified unit
144
+ *
145
+ * @example
146
+ * ```typescript
147
+ * // Get difference in days
148
+ * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5
149
+ *
150
+ * // Get difference in hours
151
+ * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4
152
+ * ```
153
+ */
154
+ export function dateDiff(date1, date2 = new Date(), unit = 'days') {
155
+ const d1 = date1 instanceof Date ? date1 : new Date(date1);
156
+ const d2 = date2 instanceof Date ? date2 : new Date(date2);
157
+ const diffMs = d1.getTime() - d2.getTime();
158
+ switch (unit) {
159
+ case 'milliseconds':
160
+ return diffMs;
161
+ case 'seconds':
162
+ return diffMs / 1000;
163
+ case 'minutes':
164
+ return diffMs / (1000 * 60);
165
+ case 'hours':
166
+ return diffMs / (1000 * 60 * 60);
167
+ case 'days':
168
+ return diffMs / (1000 * 60 * 60 * 24);
169
+ case 'months':
170
+ return (d1.getFullYear() - d2.getFullYear()) * 12 + d1.getMonth() - d2.getMonth();
171
+ case 'years':
172
+ return d1.getFullYear() - d2.getFullYear();
173
+ default:
174
+ throw new Error(`Unsupported unit: ${unit}`);
175
+ }
176
+ }
177
+ /**
178
+ * Add a specified amount of time to a date.
179
+ *
180
+ * @param date - Base date
181
+ * @param amount - Amount to add (can be negative)
182
+ * @param unit - Unit of time to add
183
+ * @returns New date with the addition
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * // Add 5 days
188
+ * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023
189
+ *
190
+ * // Subtract 2 hours
191
+ * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00
192
+ * ```
193
+ */
194
+ export function addToDate(date, amount, unit) {
195
+ const d = date instanceof Date ? new Date(date) : new Date(date);
196
+ switch (unit) {
197
+ case 'milliseconds':
198
+ d.setMilliseconds(d.getMilliseconds() + amount);
199
+ break;
200
+ case 'seconds':
201
+ d.setSeconds(d.getSeconds() + amount);
202
+ break;
203
+ case 'minutes':
204
+ d.setMinutes(d.getMinutes() + amount);
205
+ break;
206
+ case 'hours':
207
+ d.setHours(d.getHours() + amount);
208
+ break;
209
+ case 'days':
210
+ d.setDate(d.getDate() + amount);
211
+ break;
212
+ case 'months': {
213
+ const origDate = d.getDate();
214
+ const origMonth = d.getMonth();
215
+ d.setDate(1); // Prevent overflow
216
+ d.setMonth(origMonth + amount);
217
+ const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
218
+ d.setDate(Math.min(origDate, lastDay));
219
+ break;
220
+ }
221
+ case 'years':
222
+ d.setFullYear(d.getFullYear() + amount);
223
+ break;
224
+ default:
225
+ throw new Error(`Unsupported unit: ${unit}`);
226
+ }
227
+ return d;
228
+ }
229
+ /**
230
+ * Get the start of a time period containing the specified date.
231
+ *
232
+ * @param date - Date to get the start from
233
+ * @param unit - Time unit
234
+ * @returns Date object representing the start of the time unit
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * // Get start of day (midnight)
239
+ * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00
240
+ *
241
+ * // Get start of month
242
+ * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023
243
+ * ```
244
+ */
245
+ export function startOf(date, unit) {
246
+ const d = date instanceof Date ? new Date(date) : new Date(date);
247
+ switch (unit) {
248
+ case 'second':
249
+ d.setMilliseconds(0);
250
+ break;
251
+ case 'minute':
252
+ d.setSeconds(0, 0);
253
+ break;
254
+ case 'hour':
255
+ d.setMinutes(0, 0, 0);
256
+ break;
257
+ case 'day':
258
+ d.setHours(0, 0, 0, 0);
259
+ break;
260
+ case 'week':
261
+ d.setHours(0, 0, 0, 0);
262
+ d.setDate(d.getDate() - d.getDay());
263
+ break;
264
+ case 'month':
265
+ d.setDate(1);
266
+ d.setHours(0, 0, 0, 0);
267
+ break;
268
+ case 'quarter':
269
+ d.setMonth(Math.floor(d.getMonth() / 3) * 3, 1);
270
+ d.setHours(0, 0, 0, 0);
271
+ break;
272
+ case 'year':
273
+ d.setMonth(0, 1);
274
+ d.setHours(0, 0, 0, 0);
275
+ break;
276
+ default:
277
+ throw new Error(`Unsupported unit: ${unit}`);
278
+ }
279
+ return d;
280
+ }
281
+ /**
282
+ * Get the end of a time period containing the specified date.
283
+ *
284
+ * @param date - Date to get the end from
285
+ * @param unit - Time unit
286
+ * @returns Date object representing the end of the time unit
287
+ *
288
+ * @example
289
+ * ```typescript
290
+ * // Get end of day (23:59:59.999)
291
+ * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999
292
+ *
293
+ * // Get end of month
294
+ * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999
295
+ * ```
296
+ */
297
+ export function endOf(date, unit) {
298
+ const d = date instanceof Date ? new Date(date) : new Date(date);
299
+ switch (unit) {
300
+ case 'second':
301
+ d.setMilliseconds(999);
302
+ break;
303
+ case 'minute':
304
+ d.setSeconds(59, 999);
305
+ break;
306
+ case 'hour':
307
+ d.setMinutes(59, 59, 999);
308
+ break;
309
+ case 'day':
310
+ d.setHours(23, 59, 59, 999);
311
+ break;
312
+ case 'week':
313
+ d.setDate(d.getDate() - d.getDay() + 6);
314
+ d.setHours(23, 59, 59, 999);
315
+ break;
316
+ case 'month':
317
+ d.setMonth(d.getMonth() + 1, 0);
318
+ d.setHours(23, 59, 59, 999);
319
+ break;
320
+ case 'quarter':
321
+ d.setMonth(Math.floor(d.getMonth() / 3) * 3 + 3, 0);
322
+ d.setHours(23, 59, 59, 999);
323
+ break;
324
+ case 'year':
325
+ d.setMonth(11, 31);
326
+ d.setHours(23, 59, 59, 999);
327
+ break;
328
+ default:
329
+ throw new Error(`Unsupported unit: ${unit}`);
330
+ }
331
+ return d;
332
+ }
333
+ /**
334
+ * Check if a date is between two other dates.
335
+ *
336
+ * @param date - Date to check
337
+ * @param start - Start date of the range
338
+ * @param end - End date of the range
339
+ * @param inclusive - Whether the comparison should be inclusive of start/end
340
+ * @returns True if the date is within the range
341
+ *
342
+ * @example
343
+ * ```typescript
344
+ * const date = new Date('2023-05-15');
345
+ * const start = new Date('2023-05-10');
346
+ * const end = new Date('2023-05-20');
347
+ *
348
+ * isBetween(date, start, end); // true
349
+ * ```
350
+ */
351
+ export function isBetween(date, start, end, inclusive = true) {
352
+ const d = date instanceof Date ? date.getTime() : date;
353
+ const s = start instanceof Date ? start.getTime() : start;
354
+ const e = end instanceof Date ? end.getTime() : end;
355
+ return inclusive ? d >= s && d <= e : d > s && d < e;
356
+ }
357
+ /**
358
+ * Check if a year is a leap year.
359
+ *
360
+ * @param year - Year to check (or date object)
361
+ * @returns True if the year is a leap year
362
+ */
363
+ export function isLeapYear(year) {
364
+ const y = year instanceof Date ? year.getFullYear() : year;
365
+ return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
366
+ }
367
+ /**
368
+ * Get the number of days in a month.
369
+ *
370
+ * @param year - Year
371
+ * @param month - Month (0-11)
372
+ * @returns Number of days in the month
373
+ */
374
+ export function daysInMonth(year, month) {
375
+ if (year instanceof Date) {
376
+ month = year.getMonth();
377
+ year = year.getFullYear();
378
+ }
379
+ if (month === undefined) {
380
+ throw new Error('Month is required when year is a number');
381
+ }
382
+ return new Date(year, month + 1, 0).getDate();
383
+ }
384
+ //# sourceMappingURL=date.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date.utils.js","sourceRoot":"","sources":["../../../src/utils/date.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAcH;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,UAAU,CAAC,IAAmB,EAAE,UAA6B,EAAE;IAC7E,MAAM,EAAE,MAAM,GAAG,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IAC5D,MAAM,C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D,MAAM,CAAC,GAAG,GAAG,YAAY,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAEpD,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACvD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,IAAmB;IAC5C,MAAM,CAAC,GAAG,IAAI,YAAY,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3D,OAAO,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC;AACzD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,IAAmB,EAAE,KAAc;IAC7D,IAAI,IAAI,YAAY,IAAI,EAAE,CAAC;QACzB,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QACxB,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;IAC5B,CAAC;IAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;IAED,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;AAChD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Format options for the formatDate function\n */\nexport interface DateFormatOptions {\n /** Date format pattern (default: 'yyyy-MM-dd') */\n format?: string;\n /** Locale to use for formatting (default: system locale) */\n locale?: string | string[];\n /** Time zone to use (default: system time zone) */\n timeZone?: string;\n}\n\n/**\n * Format a date according to the specified format pattern.\n *\n * @param date - Date to format\n * @param options - Formatting options\n * @returns Formatted date string\n *\n * @example\n * ```typescript\n * // Format as ISO date\n * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'\n *\n * // Format with time\n * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'\n *\n * // Format with locale\n * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'\n * ```\n */\nexport function formatDate(date: Date | number, options: DateFormatOptions = {}): string {\n const { format = 'yyyy-MM-dd', locale, timeZone } = options;\n const d = date instanceof Date ? date : new Date(date);\n\n // Custom formatter for common patterns\n if (format === 'yyyy-MM-dd') {\n const yyyy = d.getFullYear();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n return `${yyyy}-${mm}-${dd}`;\n }\n if (format === 'yyyy-MM-dd HH:mm:ss') {\n const yyyy = d.getFullYear();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n const HH = String(d.getHours()).padStart(2, '0');\n const MM = String(d.getMinutes()).padStart(2, '0');\n const SS = String(d.getSeconds()).padStart(2, '0');\n return `${yyyy}-${mm}-${dd} ${HH}:${MM}:${SS}`;\n }\n if (format === 'relative') {\n return formatRelativeTime(date);\n }\n\n // Fallback to Intl.DateTimeFormat for other formats\n return new Intl.DateTimeFormat(locale, {\n timeZone,\n year: format.includes('yyyy') || format.includes('y') ? 'numeric' : undefined,\n month: format.includes('MM') || format.includes('M') ? 'numeric' : undefined,\n day: format.includes('dd') || format.includes('d') ? 'numeric' : undefined,\n hour: format.includes('HH') || format.includes('H') ? 'numeric' : undefined,\n minute: format.includes('mm') || format.includes('m') ? 'numeric' : undefined,\n second: format.includes('ss') || format.includes('s') ? 'numeric' : undefined,\n hour12: !format.includes('HH') && !format.includes('H')\n }).format(d);\n}\n\n/**\n * Format a date as relative time (e.g., \"5 minutes ago\", \"in 3 days\").\n *\n * @param date - Date to format\n * @param now - Reference date (default: current time)\n * @param locale - Locale to use for formatting\n * @returns Formatted relative time string\n */\nexport function formatRelativeTime(\n date: Date | number,\n now: Date | number = new Date(),\n locale?: string | string[]\n): string {\n const d1 = date instanceof Date ? date : new Date(date);\n const d2 = now instanceof Date ? now : new Date(now);\n\n const diffMs = d1.getTime() - d2.getTime();\n const diffSecs = Math.round(diffMs / 1000);\n const diffMins = Math.round(diffSecs / 60);\n const diffHours = Math.round(diffMins / 60);\n const diffDays = Math.round(diffHours / 24);\n const diffMonths = Math.round(diffDays / 30);\n const diffYears = Math.round(diffDays / 365);\n\n const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });\n\n if (Math.abs(diffSecs) < 60) return formatter.format(diffSecs, 'second');\n if (Math.abs(diffMins) < 60) return formatter.format(diffMins, 'minute');\n if (Math.abs(diffHours) < 24) return formatter.format(diffHours, 'hour');\n if (Math.abs(diffDays) < 30) return formatter.format(diffDays, 'day');\n if (Math.abs(diffMonths) < 12) return formatter.format(diffMonths, 'month');\n return formatter.format(diffYears, 'year');\n}\n\n/**\n * Parse a date string or timestamp into a Date object.\n *\n * @param input - Date string or timestamp to parse\n * @param fallback - Fallback date if parsing fails\n * @returns Parsed Date object or fallback\n *\n * @example\n * ```typescript\n * parseDate('2023-05-15'); // Date object for May 15, 2023\n * parseDate('invalid', new Date()); // Returns current date as fallback\n * ```\n */\nexport function parseDate(input: string | number, fallback?: Date): Date | null {\n if (typeof input === 'number') {\n return new Date(input);\n }\n\n try {\n const date = new Date(input);\n // Check if date is valid\n if (isNaN(date.getTime())) {\n return fallback || null;\n }\n return date;\n } catch {\n return fallback || null;\n }\n}\n\n/**\n * Calculate the difference between two dates in the specified unit.\n *\n * @param date1 - First date\n * @param date2 - Second date (default: current time)\n * @param unit - Unit of time for the difference\n * @returns Difference in the specified unit\n *\n * @example\n * ```typescript\n * // Get difference in days\n * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5\n *\n * // Get difference in hours\n * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4\n * ```\n */\nexport function dateDiff(\n date1: Date | number,\n date2: Date | number = new Date(),\n unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years' = 'days'\n): number {\n const d1 = date1 instanceof Date ? date1 : new Date(date1);\n const d2 = date2 instanceof Date ? date2 : new Date(date2);\n\n const diffMs = d1.getTime() - d2.getTime();\n\n switch (unit) {\n case 'milliseconds':\n return diffMs;\n case 'seconds':\n return diffMs / 1000;\n case 'minutes':\n return diffMs / (1000 * 60);\n case 'hours':\n return diffMs / (1000 * 60 * 60);\n case 'days':\n return diffMs / (1000 * 60 * 60 * 24);\n case 'months':\n return (d1.getFullYear() - d2.getFullYear()) * 12 + d1.getMonth() - d2.getMonth();\n case 'years':\n return d1.getFullYear() - d2.getFullYear();\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n}\n\n/**\n * Add a specified amount of time to a date.\n *\n * @param date - Base date\n * @param amount - Amount to add (can be negative)\n * @param unit - Unit of time to add\n * @returns New date with the addition\n *\n * @example\n * ```typescript\n * // Add 5 days\n * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023\n *\n * // Subtract 2 hours\n * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00\n * ```\n */\nexport function addToDate(\n date: Date | number,\n amount: number,\n unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'milliseconds':\n d.setMilliseconds(d.getMilliseconds() + amount);\n break;\n case 'seconds':\n d.setSeconds(d.getSeconds() + amount);\n break;\n case 'minutes':\n d.setMinutes(d.getMinutes() + amount);\n break;\n case 'hours':\n d.setHours(d.getHours() + amount);\n break;\n case 'days':\n d.setDate(d.getDate() + amount);\n break;\n case 'months': {\n const origDate = d.getDate();\n const origMonth = d.getMonth();\n d.setDate(1); // Prevent overflow\n d.setMonth(origMonth + amount);\n const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();\n d.setDate(Math.min(origDate, lastDay));\n break;\n }\n case 'years':\n d.setFullYear(d.getFullYear() + amount);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Get the start of a time period containing the specified date.\n *\n * @param date - Date to get the start from\n * @param unit - Time unit\n * @returns Date object representing the start of the time unit\n *\n * @example\n * ```typescript\n * // Get start of day (midnight)\n * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00\n *\n * // Get start of month\n * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023\n * ```\n */\nexport function startOf(\n date: Date | number,\n unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'second':\n d.setMilliseconds(0);\n break;\n case 'minute':\n d.setSeconds(0, 0);\n break;\n case 'hour':\n d.setMinutes(0, 0, 0);\n break;\n case 'day':\n d.setHours(0, 0, 0, 0);\n break;\n case 'week':\n d.setHours(0, 0, 0, 0);\n d.setDate(d.getDate() - d.getDay());\n break;\n case 'month':\n d.setDate(1);\n d.setHours(0, 0, 0, 0);\n break;\n case 'quarter':\n d.setMonth(Math.floor(d.getMonth() / 3) * 3, 1);\n d.setHours(0, 0, 0, 0);\n break;\n case 'year':\n d.setMonth(0, 1);\n d.setHours(0, 0, 0, 0);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Get the end of a time period containing the specified date.\n *\n * @param date - Date to get the end from\n * @param unit - Time unit\n * @returns Date object representing the end of the time unit\n *\n * @example\n * ```typescript\n * // Get end of day (23:59:59.999)\n * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999\n *\n * // Get end of month\n * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999\n * ```\n */\nexport function endOf(\n date: Date | number,\n unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'second':\n d.setMilliseconds(999);\n break;\n case 'minute':\n d.setSeconds(59, 999);\n break;\n case 'hour':\n d.setMinutes(59, 59, 999);\n break;\n case 'day':\n d.setHours(23, 59, 59, 999);\n break;\n case 'week':\n d.setDate(d.getDate() - d.getDay() + 6);\n d.setHours(23, 59, 59, 999);\n break;\n case 'month':\n d.setMonth(d.getMonth() + 1, 0);\n d.setHours(23, 59, 59, 999);\n break;\n case 'quarter':\n d.setMonth(Math.floor(d.getMonth() / 3) * 3 + 3, 0);\n d.setHours(23, 59, 59, 999);\n break;\n case 'year':\n d.setMonth(11, 31);\n d.setHours(23, 59, 59, 999);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Check if a date is between two other dates.\n *\n * @param date - Date to check\n * @param start - Start date of the range\n * @param end - End date of the range\n * @param inclusive - Whether the comparison should be inclusive of start/end\n * @returns True if the date is within the range\n *\n * @example\n * ```typescript\n * const date = new Date('2023-05-15');\n * const start = new Date('2023-05-10');\n * const end = new Date('2023-05-20');\n *\n * isBetween(date, start, end); // true\n * ```\n */\nexport function isBetween(\n date: Date | number,\n start: Date | number,\n end: Date | number,\n inclusive: boolean = true\n): boolean {\n const d = date instanceof Date ? date.getTime() : date;\n const s = start instanceof Date ? start.getTime() : start;\n const e = end instanceof Date ? end.getTime() : end;\n\n return inclusive ? d >= s && d <= e : d > s && d < e;\n}\n\n/**\n * Check if a year is a leap year.\n *\n * @param year - Year to check (or date object)\n * @returns True if the year is a leap year\n */\nexport function isLeapYear(year: number | Date): boolean {\n const y = year instanceof Date ? year.getFullYear() : year;\n return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;\n}\n\n/**\n * Get the number of days in a month.\n *\n * @param year - Year\n * @param month - Month (0-11)\n * @returns Number of days in the month\n */\nexport function daysInMonth(year: number | Date, month?: number): number {\n if (year instanceof Date) {\n month = year.getMonth();\n year = year.getFullYear();\n }\n\n if (month === undefined) {\n throw new Error('Month is required when year is a number');\n }\n\n return new Date(year, month + 1, 0).getDate();\n}\n"]}
@@ -129,16 +129,10 @@ export declare const _globalThis: typeof globalThis;
129
129
  */
130
130
  export declare function getLogger(): PinoLogger;
131
131
  /**
132
- * Alias for the current logger instance.
133
- * - Returns a request-scoped logger from AsyncLocalStorage if available
134
- * - Falls back to the global (singleton) logger
135
- * - Initializes the global logger if not created yet
136
- */
137
- export declare const logger: typeof getLogger;
138
- /**
139
- * Global logger instance.
132
+ * Logger instance for the global context.
133
+ * This logger is used for logging messages that are not tied to a specific request.
140
134
  */
141
- export declare const globalLogger: PinoLogger;
135
+ export declare const logger: PinoLogger;
142
136
  /**
143
137
  * Creates a child logger with additional context.
144
138
  *
@@ -251,16 +251,10 @@ export function getLogger() {
251
251
  return _global[GLOBAL_LOGGER_KEY];
252
252
  }
253
253
  /**
254
- * Alias for the current logger instance.
255
- * - Returns a request-scoped logger from AsyncLocalStorage if available
256
- * - Falls back to the global (singleton) logger
257
- * - Initializes the global logger if not created yet
258
- */
259
- export const logger = getLogger;
260
- /**
261
- * Global logger instance.
254
+ * Logger instance for the global context.
255
+ * This logger is used for logging messages that are not tied to a specific request.
262
256
  */
263
- export const globalLogger = getLogger();
257
+ export const logger = getLogger();
264
258
  /**
265
259
  * Creates a child logger with additional context.
266
260
  *
@@ -1 +1 @@
1
- {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAElC;;GAEG;AACH,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C,2BAA2B;AAC3B,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,UAAU;IACV,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,SAAS;IACT,MAAM;IACN,KAAK;IACL,cAAc;IACd,eAAe;IACf,eAAe;IACf,eAAe;CAChB,CAAC;AAEF;;GAEG;AACH,IAAI,kBAAkB,GAA2E,CAC/F,KAAK,EACL,IAAI,EACJ,eAAe,GAAG,sBAAsB,EACxC,EAAE;IACF,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;I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AC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { Env } from './env.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n// Default sensitive fields\nexport const defaultSensitiveFields = [\n 'password',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'auth',\n 'jwt',\n 'access_token',\n 'client_secret',\n 'session_token',\n 'refresh_token'\n];\n\n/**\n * The global censor function used by the logger.\n */\nlet globalRedactCensor: (value: unknown, path: string[], sensitiveFields?: string[]) => string = (\n value,\n path,\n sensitiveFields = defaultSensitiveFields\n) => {\n if (typeof value !== 'string') return '***';\n\n const lowerPath = path.map(p => p.toLowerCase());\n const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());\n\n if (lowerPath.some(p => lowerSensitiveFields.includes(p))) return '***';\n\n // Redact URLs\n if (lowerPath[0] === 'url') {\n return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');\n }\n\n if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {\n return value.replace(/^(\\S+)\\s+.+$/, '$1 ***') || '***';\n }\n\n // Redact sensitive fields - check each path segment against each sensitive field\n if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {\n return '***';\n }\n\n if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {\n return value;\n }\n\n return value;\n};\n\n/**\n * Sets the global redaction censor function used throughout the application for log redaction.\n *\n * Use this function to customize how sensitive data is redacted in logs. The provided function\n * will replace the default censor implementation.\n *\n * @example\n * ```typescript\n * // Custom censor that redacts only specific values\n * setRedactCensor((value, path, sensitiveFields) => {\n * if (path.includes('password')) return '***';\n * return value;\n * });\n * ```\n *\n * @param fn - The redaction censor function to use globally. This function receives:\n * - value: The data value to potentially redact\n * - path: Array of strings representing the path to the value in the object\n * - sensitiveFields: Optional array of field names to consider sensitive\n * @returns void\n */\nexport function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string) {\n globalRedactCensor = fn;\n}\n\n/**\n * Gets the current global redaction censor function used for log redaction.\n *\n * This function is called internally by the logger when determining how to redact\n * sensitive information. It can also be used to access the current censor implementation\n * for composition or extension.\n *\n * @example\n * ```typescript\n * const currentCensor = getRedactCensor();\n * // Create an enhanced censor that extends the current one\n * setRedactCensor((value, path, fields) => {\n * // Add custom logic before delegating to current censor\n * if (someCondition) return customHandling();\n * return currentCensor(value, path, fields);\n * });\n * ```\n *\n * @returns The current redaction censor function\n */\nexport function getRedactCensor() {\n return globalRedactCensor;\n}\n\n/**\n * Convenience function to redact sensitive data using the current global redact censor.\n *\n * This is a direct wrapper around the global censor function that simplifies usage\n * in application code without needing to access the censor function directly.\n *\n * @example\n * ```typescript\n * // Redact a potential sensitive value\n * const safeValue = redact(value, ['user', 'apiKey']);\n * ```\n *\n * @param value - The value to potentially redact\n * @param path - Array of strings representing the path to the value in the object\n * @param sensitiveFields - Optional array of field names to consider sensitive\n * @returns The redacted string value or \"***\" for redacted content\n */\nexport function redact(value: unknown, path: string[], sensitiveFields?: string[]) {\n return globalRedactCensor(value, path, sensitiveFields);\n}\n\n/**\n * Extends the current redaction function with additional fields to redact.\n *\n * This function wraps the existing censor while adding more fields to be considered\n * sensitive without replacing the entire redaction logic.\n *\n * @example\n * ```typescript\n * // Add custom fields to be redacted in all future redaction operations\n * addRedactFields(['customerId', 'accountNumber']);\n * ```\n *\n * @param fields - Array of additional field names to redact\n */\nexport function addRedactFields(fields: string[]) {\n const prev = globalRedactCensor;\n globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) =>\n prev(value, path, [...(sensitiveFields || []), ...fields]);\n}\n\n/**\n * Replaces the default list of sensitive fields with a new list.\n *\n * This is useful when you want complete control over what fields are considered\n * sensitive by default, rather than using the library's built-in list.\n *\n * @example\n * ```typescript\n * // Replace default sensitive fields with a custom list\n * setSensitiveFields(['password', 'ssn', 'creditCard']);\n * ```\n *\n * @param fields - Array of field names to set as the new default sensitive fields\n */\nexport function setSensitiveFields(fields: string[]) {\n defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);\n}\n\n/**\n * Adds additional field names to the default sensitive fields list.\n *\n * This preserves the existing sensitive fields while adding new ones for\n * application-specific sensitive data.\n *\n * @example\n * ```typescript\n * // Add domain-specific sensitive fields to the default list\n * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);\n * ```\n *\n * @param fields - Array of additional field names to add to the sensitive fields list\n */\nexport function addSensitiveFields(fields: string[]) {\n defaultSensitiveFields.push(...fields);\n}\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: config.logger.name || '@catbee/utils',\n level: config.logger.level || 'info',\n redact: {\n paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],\n censor: (value, path) => redact(value, path)\n },\n // serializers: {\n // req: pino.stdSerializers.req,\n // request: pino.stdSerializers.req,\n // res: pino.stdSerializers.res,\n // response: pino.stdSerializers.res,\n // err: pino.stdSerializers.err,\n // error: pino.stdSerializers.err\n // },\n timestamp: stdTimeFunctions.isoTime\n };\n\n const logger =\n config.logger.pretty && Env.isDev()\n ? pino(\n logParams,\n pino.transport({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname',\n singleLine: config.logger.singleLine,\n levelFirst: true\n }\n })\n )\n : pino(logParams);\n\n _global[GLOBAL_LOGGER_KEY] = logger;\n _global[GLOBAL_LOGGER_KEY]?.debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Alias for the current logger instance.\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n */\nexport const logger = getLogger;\n\n/**\n * Global logger instance.\n */\nexport const globalLogger = getLogger();\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n error: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
1
+ {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,M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AC9C,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;IACxF,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,MAAM,UAAU,mCACX,OAAO,KACV,KAAK,EAAE,MAAM,GACd,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { Env } from './env.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n// Default sensitive fields\nexport const defaultSensitiveFields = [\n 'password',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'auth',\n 'jwt',\n 'access_token',\n 'client_secret',\n 'session_token',\n 'refresh_token'\n];\n\n/**\n * The global censor function used by the logger.\n */\nlet globalRedactCensor: (value: unknown, path: string[], sensitiveFields?: string[]) => string = (\n value,\n path,\n sensitiveFields = defaultSensitiveFields\n) => {\n if (typeof value !== 'string') return '***';\n\n const lowerPath = path.map(p => p.toLowerCase());\n const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());\n\n if (lowerPath.some(p => lowerSensitiveFields.includes(p))) return '***';\n\n // Redact URLs\n if (lowerPath[0] === 'url') {\n return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');\n }\n\n if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {\n return value.replace(/^(\\S+)\\s+.+$/, '$1 ***') || '***';\n }\n\n // Redact sensitive fields - check each path segment against each sensitive field\n if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {\n return '***';\n }\n\n if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {\n return value;\n }\n\n return value;\n};\n\n/**\n * Sets the global redaction censor function used throughout the application for log redaction.\n *\n * Use this function to customize how sensitive data is redacted in logs. The provided function\n * will replace the default censor implementation.\n *\n * @example\n * ```typescript\n * // Custom censor that redacts only specific values\n * setRedactCensor((value, path, sensitiveFields) => {\n * if (path.includes('password')) return '***';\n * return value;\n * });\n * ```\n *\n * @param fn - The redaction censor function to use globally. This function receives:\n * - value: The data value to potentially redact\n * - path: Array of strings representing the path to the value in the object\n * - sensitiveFields: Optional array of field names to consider sensitive\n * @returns void\n */\nexport function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string) {\n globalRedactCensor = fn;\n}\n\n/**\n * Gets the current global redaction censor function used for log redaction.\n *\n * This function is called internally by the logger when determining how to redact\n * sensitive information. It can also be used to access the current censor implementation\n * for composition or extension.\n *\n * @example\n * ```typescript\n * const currentCensor = getRedactCensor();\n * // Create an enhanced censor that extends the current one\n * setRedactCensor((value, path, fields) => {\n * // Add custom logic before delegating to current censor\n * if (someCondition) return customHandling();\n * return currentCensor(value, path, fields);\n * });\n * ```\n *\n * @returns The current redaction censor function\n */\nexport function getRedactCensor() {\n return globalRedactCensor;\n}\n\n/**\n * Convenience function to redact sensitive data using the current global redact censor.\n *\n * This is a direct wrapper around the global censor function that simplifies usage\n * in application code without needing to access the censor function directly.\n *\n * @example\n * ```typescript\n * // Redact a potential sensitive value\n * const safeValue = redact(value, ['user', 'apiKey']);\n * ```\n *\n * @param value - The value to potentially redact\n * @param path - Array of strings representing the path to the value in the object\n * @param sensitiveFields - Optional array of field names to consider sensitive\n * @returns The redacted string value or \"***\" for redacted content\n */\nexport function redact(value: unknown, path: string[], sensitiveFields?: string[]) {\n return globalRedactCensor(value, path, sensitiveFields);\n}\n\n/**\n * Extends the current redaction function with additional fields to redact.\n *\n * This function wraps the existing censor while adding more fields to be considered\n * sensitive without replacing the entire redaction logic.\n *\n * @example\n * ```typescript\n * // Add custom fields to be redacted in all future redaction operations\n * addRedactFields(['customerId', 'accountNumber']);\n * ```\n *\n * @param fields - Array of additional field names to redact\n */\nexport function addRedactFields(fields: string[]) {\n const prev = globalRedactCensor;\n globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) =>\n prev(value, path, [...(sensitiveFields || []), ...fields]);\n}\n\n/**\n * Replaces the default list of sensitive fields with a new list.\n *\n * This is useful when you want complete control over what fields are considered\n * sensitive by default, rather than using the library's built-in list.\n *\n * @example\n * ```typescript\n * // Replace default sensitive fields with a custom list\n * setSensitiveFields(['password', 'ssn', 'creditCard']);\n * ```\n *\n * @param fields - Array of field names to set as the new default sensitive fields\n */\nexport function setSensitiveFields(fields: string[]) {\n defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);\n}\n\n/**\n * Adds additional field names to the default sensitive fields list.\n *\n * This preserves the existing sensitive fields while adding new ones for\n * application-specific sensitive data.\n *\n * @example\n * ```typescript\n * // Add domain-specific sensitive fields to the default list\n * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);\n * ```\n *\n * @param fields - Array of additional field names to add to the sensitive fields list\n */\nexport function addSensitiveFields(fields: string[]) {\n defaultSensitiveFields.push(...fields);\n}\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: config.logger.name || '@catbee/utils',\n level: config.logger.level || 'info',\n redact: {\n paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],\n censor: (value, path) => redact(value, path)\n },\n // serializers: {\n // req: pino.stdSerializers.req,\n // request: pino.stdSerializers.req,\n // res: pino.stdSerializers.res,\n // response: pino.stdSerializers.res,\n // err: pino.stdSerializers.err,\n // error: pino.stdSerializers.err\n // },\n timestamp: stdTimeFunctions.isoTime\n };\n\n const logger =\n config.logger.pretty && Env.isDev()\n ? pino(\n logParams,\n pino.transport({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname',\n singleLine: config.logger.singleLine,\n levelFirst: true\n }\n })\n )\n : pino(logParams);\n\n _global[GLOBAL_LOGGER_KEY] = logger;\n _global[GLOBAL_LOGGER_KEY]?.debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Logger instance for the global context.\n * This logger is used for logging messages that are not tied to a specific request.\n */\nexport const logger = getLogger();\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n error: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
@@ -129,10 +129,11 @@ export function setupRequestContext(options = {}) {
129
129
  method: req.method,
130
130
  url: req.originalUrl || req.url
131
131
  });
132
+ req.logger = childLogger;
132
133
  // Store logger in context
133
134
  ContextStore.set(StoreKeys.LOGGER, childLogger);
134
135
  if (autoLog) {
135
- childLogger.info('Request context initialized');
136
+ req.logger.info('Request context initialized');
136
137
  }
137
138
  next();
138
139
  });
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D;;;;;;;;;GASG;AACH,MAAM,UAAU,SAAS,CAAC,OAIzB;IACC,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IACrD,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KAAI,IAAI,CAAC;IAE9C,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAAC,OA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AAC,OAAO,IAAI,eAAe,EAAE,CAAC,CAAC;QAClE,CAAC;QAED,0DAA0D;QAC1D,IAAI,GAAG,YAAY,aAAa,EAAE,CAAC;YACjC,MAAM,MAAM,GAAqB;gBAC/B,KAAK,EAAE,IAAI;gBACX,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,SAAS,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,SAAS,MAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,EAAE,CAAA,IAAI,IAAI,EAAE;gBAC9C,MAAM;gBACN,IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC;YAEF,IAAI,cAAc,KAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,KAAK,CAAA,EAAE,CAAC;gBACjC,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzC,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG;aACP,MAAM,CAAC,MAAM,CAAC;aACd,IAAI,CAAC,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;IACnH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { createFinalErrorResponse, ErrorResponse } from './response.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { RequestTimeoutException } from './exception.utils';\nimport { ApiErrorResponse } from '../types/api-response';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @param {() => string} [options.generator] - Custom ID generator function\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n generator?: () => string;\n}): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n const generateId = options?.generator || uuid;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || generateId();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n // Function to calculate duration\n const getDuration = () => {\n const diff = process.hrtime(start);\n return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);\n };\n\n if (addHeader) {\n // Ensure header is set before response is sent\n const originalWriteHead = res.writeHead;\n res.writeHead = function (...args: any[]) {\n res.setHeader('X-Response-Time', `${getDuration()}ms`);\n return originalWriteHead.apply(this, args as any);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = 30000): Middleware {\n return (_req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n const response = new RequestTimeoutException('Request timed out');\n res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} options - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n const result: ApiErrorResponse = {\n error: true,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n if (includeDetails && err?.stack) {\n result.stack = err.stack.split('\\n').map((line: string) => line.trim());\n }\n return res.status(status).json(result);\n }\n\n // Handle any other errors\n return res\n .status(status)\n .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));\n };\n}\n"]}
1
+ {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D;;;;;;;;;GASG;AACH,MAAM,UAAU,SAAS,CAAC,OAIzB;IACC,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IACrD,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KAAI,IAAI,CAAC;IAE9C,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;QACzD,MAAM,EAAE,GAAI,UAAqB,IAAI,UAAU,EAAE,CAA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ClE,CAAC;QAED,0DAA0D;QAC1D,IAAI,GAAG,YAAY,aAAa,EAAE,CAAC;YACjC,MAAM,MAAM,GAAqB;gBAC/B,KAAK,EAAE,IAAI;gBACX,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,SAAS,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,SAAS,MAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,EAAE,CAAA,IAAI,IAAI,EAAE;gBAC9C,MAAM;gBACN,IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC;YAEF,IAAI,cAAc,KAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,KAAK,CAAA,EAAE,CAAC;gBACjC,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzC,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG;aACP,MAAM,CAAC,MAAM,CAAC;aACd,IAAI,CAAC,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;IACnH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { createFinalErrorResponse, ErrorResponse } from './response.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { RequestTimeoutException } from './exception.utils';\nimport { ApiErrorResponse } from '../types/api-response';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @param {() => string} [options.generator] - Custom ID generator function\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n generator?: () => string;\n}): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n const generateId = options?.generator || uuid;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || generateId();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n // Function to calculate duration\n const getDuration = () => {\n const diff = process.hrtime(start);\n return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);\n };\n\n if (addHeader) {\n // Ensure header is set before response is sent\n const originalWriteHead = res.writeHead;\n res.writeHead = function (...args: any[]) {\n res.setHeader('X-Response-Time', `${getDuration()}ms`);\n return originalWriteHead.apply(this, args as any);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = 30000): Middleware {\n return (_req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n const response = new RequestTimeoutException('Request timed out');\n res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n req.logger = childLogger;\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n req.logger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} options - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n const result: ApiErrorResponse = {\n error: true,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n if (includeDetails && err?.stack) {\n result.stack = err.stack.split('\\n').map((line: string) => line.trim());\n }\n return res.status(status).json(result);\n }\n\n // Handle any other errors\n return res\n .status(status)\n .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));\n };\n}\n"]}