@mhmdhammoud/meritt-utils 1.6.1 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib/logger.ts DELETED
@@ -1,590 +0,0 @@
1
- import { Logger as PinoLogger, pino, stdTimeFunctions } from 'pino'
2
- import * as dotenv from 'dotenv'
3
- import { hostname } from 'os'
4
- import { createElasticTransport } from './elastic-transport'
5
- import { getTraceContext } from './trace-store'
6
- import { LOG_LEVEL, LogEvent, ElasticConfig } from '../types'
7
-
8
- dotenv.config()
9
-
10
- /** Convert camelCase to snake_case for Kibana/ECS-friendly field names */
11
- const toSnakeCase = (str: string): string =>
12
- str.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)
13
-
14
- /**
15
- * Elasticsearch reserves metadata fields (e.g. `_id`) and rejects documents
16
- * containing them in payload body. Remap them to safe application fields.
17
- */
18
- const RESERVED_ES_FIELD_ALIASES: Record<string, string> = {
19
- _id: 'mongo_id',
20
- _index: 'es_index',
21
- _type: 'es_type',
22
- _score: 'es_score',
23
- _source: 'es_source',
24
- _routing: 'es_routing',
25
- _seq_no: 'es_seq_no',
26
- _primary_term: 'es_primary_term',
27
- _version: 'es_version',
28
- }
29
-
30
- /** Convert arbitrary field names into ES-safe flattened keys */
31
- const toSafeElasticFieldName = (key: string): string => {
32
- const normalized = toSnakeCase(key)
33
- const mapped = RESERVED_ES_FIELD_ALIASES[normalized]
34
- if (mapped) {
35
- return mapped
36
- }
37
- // Any leading underscore can conflict with ES internals, remap defensively.
38
- return normalized.startsWith('_') ? `meta${normalized}` : normalized
39
- }
40
-
41
- const isObjectIdLike = (v: unknown): v is { toHexString: () => string } =>
42
- v !== null &&
43
- typeof v === 'object' &&
44
- 'toHexString' in v &&
45
- typeof (v as { toHexString?: unknown }).toHexString === 'function'
46
-
47
- /** Check if value is a plain object (not Error, Date, Array, null) */
48
- const isPlainObject = (v: unknown): v is Record<string, unknown> =>
49
- v !== null &&
50
- typeof v === 'object' &&
51
- !Array.isArray(v) &&
52
- !(v instanceof Error) &&
53
- !(v instanceof Date)
54
-
55
- /**
56
- * Recursively sanitize log values for Elasticsearch safety.
57
- * - Remaps reserved key names (e.g. `_id` -> `mongo_id`)
58
- * - Converts Error to a stable serializable shape
59
- * - Converts ObjectId-like objects to hex strings
60
- * - Prevents circular structure failures
61
- */
62
- const sanitizeForElastic = (
63
- value: unknown,
64
- seen: WeakSet<object> = new WeakSet<object>()
65
- ): unknown => {
66
- if (
67
- value === null ||
68
- typeof value === 'string' ||
69
- typeof value === 'number' ||
70
- typeof value === 'boolean'
71
- ) {
72
- return value
73
- }
74
-
75
- if (value instanceof Date) {
76
- return value.toISOString()
77
- }
78
-
79
- if (value instanceof Error) {
80
- return { message: value.message, type: value.constructor.name }
81
- }
82
-
83
- if (isObjectIdLike(value)) {
84
- return value.toHexString()
85
- }
86
-
87
- if (Array.isArray(value)) {
88
- return value.map((item) => sanitizeForElastic(item, seen))
89
- }
90
-
91
- if (isPlainObject(value)) {
92
- if (seen.has(value)) {
93
- return '[Circular]'
94
- }
95
- seen.add(value)
96
-
97
- const sanitizedObject: Record<string, unknown> = {}
98
- for (const [k, v] of Object.entries(value)) {
99
- sanitizedObject[toSafeElasticFieldName(k)] = sanitizeForElastic(v, seen)
100
- }
101
- return sanitizedObject
102
- }
103
-
104
- // Fallback for class instances and non-plain objects.
105
- return String(value)
106
- }
107
-
108
- /**
109
- * Captures the call site from the stack when log event is missing.
110
- * Returns file:line (e.g. product.service.ts:2266) for Kibana/Elasticsearch filtering.
111
- */
112
- const getCallSiteForMissingLog = (): string | undefined => {
113
- try {
114
- const stack = new Error().stack ?? ''
115
- const lines = stack.split('\n')
116
- // First frame outside Logger / node_modules / meritt-utils
117
- const appFrame = lines.find(
118
- (line) =>
119
- !line.includes('node_modules') &&
120
- !line.includes('meritt-utils') &&
121
- !line.includes('Logger.')
122
- )
123
- if (!appFrame) return undefined
124
- // Extract file:line e.g. "product.service.ts:2266"
125
- const match = appFrame.match(/([^/\\]+\.(?:ts|js|tsx|jsx)):(\d+)/)
126
- if (match) {
127
- return `${match[1]}:${match[2]}`
128
- }
129
- return appFrame.trim().slice(0, 100)
130
- } catch {
131
- return undefined
132
- }
133
- }
134
-
135
- /**
136
- * Pino logger backend - singleton
137
- */
138
- let pinoLogger: PinoLogger
139
-
140
- /**
141
- * Elasticsearch transport instance - kept for cleanup
142
- */
143
- let esTransport: NodeJS.ReadWriteStream | null = null
144
-
145
- /**
146
- * Flag to track if shutdown handlers are registered
147
- */
148
- let shutdownHandlersRegistered = false
149
-
150
- /**
151
- * Validates required Elasticsearch environment variables.
152
- * @throws Error if required environment variables are missing.
153
- */
154
- function validateElasticsearchEnv(): void {
155
- const required = [
156
- 'ELASTICSEARCH_NODE',
157
- 'ELASTICSEARCH_USERNAME',
158
- 'ELASTICSEARCH_PASSWORD',
159
- 'SERVER_NICKNAME',
160
- ]
161
- const missing = required.filter((key) => !process.env[key])
162
-
163
- if (missing.length > 0) {
164
- throw new Error(
165
- `Missing required Elasticsearch environment variables: ${missing.join(', ')}`
166
- )
167
- }
168
- }
169
-
170
- /**
171
- * Safely parses an integer from an environment variable.
172
- * @param envValue - The environment variable value to parse.
173
- * @param defaultValue - The default value to use if parsing fails.
174
- * @param varName - The name of the environment variable (for error messages).
175
- * @returns The parsed integer or the default value.
176
- * @throws Error if the value is not a valid number.
177
- */
178
- function parseIntEnv(
179
- envValue: string | undefined,
180
- defaultValue: number,
181
- varName: string
182
- ): number {
183
- if (!envValue) {
184
- return defaultValue
185
- }
186
-
187
- const parsed = parseInt(envValue, 10)
188
-
189
- if (isNaN(parsed)) {
190
- throw new Error(
191
- `Invalid value for ${varName}: "${envValue}" is not a valid number. Using default: ${defaultValue}`
192
- )
193
- }
194
-
195
- if (parsed < 0) {
196
- throw new Error(
197
- `Invalid value for ${varName}: "${envValue}" must be a positive number. Using default: ${defaultValue}`
198
- )
199
- }
200
-
201
- return parsed
202
- }
203
-
204
- /**
205
- * Registers shutdown handlers to flush logs before process exits.
206
- */
207
- function registerShutdownHandlers(): void {
208
- if (shutdownHandlersRegistered) {
209
- return
210
- }
211
-
212
- let isShuttingDown = false
213
-
214
- const flushAndExit = async (signal: string, exitCode = 0) => {
215
- // Prevent multiple shutdown attempts
216
- if (isShuttingDown) {
217
- return
218
- }
219
- isShuttingDown = true
220
-
221
- if (esTransport) {
222
- try {
223
- // Flush any pending logs
224
- await new Promise<void>((resolve) => {
225
- const timeout = setTimeout(() => {
226
- console.error(`[Logger] Flush timeout after 5s on ${signal}`)
227
- resolve()
228
- }, 5000) // 5 second timeout
229
-
230
- // Register listener BEFORE calling end() to avoid race condition
231
- esTransport?.once('finish', () => {
232
- clearTimeout(timeout)
233
- resolve()
234
- })
235
-
236
- // Now trigger the flush
237
- esTransport?.end()
238
- })
239
- } catch (error) {
240
- console.error(`[Logger] Error flushing logs on ${signal}:`, error)
241
- }
242
- }
243
- process.exit(exitCode)
244
- }
245
-
246
- process.on('SIGTERM', () => {
247
- flushAndExit('SIGTERM', 0).catch((err) => {
248
- console.error('[Logger] Flush and exit failed:', err)
249
- process.exit(1)
250
- })
251
- })
252
-
253
- process.on('SIGINT', () => {
254
- flushAndExit('SIGINT', 130).catch((err) => {
255
- console.error('[Logger] Flush and exit failed:', err)
256
- process.exit(1)
257
- })
258
- })
259
-
260
- process.on('beforeExit', () => {
261
- if (esTransport && !isShuttingDown) {
262
- esTransport.end()
263
- }
264
- })
265
-
266
- shutdownHandlersRegistered = true
267
- }
268
-
269
- /**
270
- * Creates a Pino logger instance with specified Elasticsearch configuration.
271
- * @param elasticConfig - Optional Elasticsearch configuration.
272
- * @returns The Pino logger instance.
273
- * @throws Error if LOG_LEVEL is invalid or required environment variables are missing.
274
- */
275
- function getLogger(elasticConfig?: ElasticConfig): PinoLogger {
276
- if (!pinoLogger) {
277
- // Validate log level - will throw if invalid
278
- const logLevel = process.env.LOG_LEVEL || 'info'
279
- isValidLogLevel(logLevel)
280
-
281
- const transports = []
282
- if (process.env.NODE_ENV !== 'local' && process.env.NODE_ENV !== 'test') {
283
- // Validate Elasticsearch environment variables
284
- validateElasticsearchEnv()
285
-
286
- // Parse flush settings from environment with validation
287
- const flushIntervalMs = parseIntEnv(
288
- process.env.ES_FLUSH_INTERVAL_MS,
289
- 2000, // Default: 2 seconds
290
- 'ES_FLUSH_INTERVAL_MS'
291
- )
292
-
293
- const flushBytes = parseIntEnv(
294
- process.env.ES_FLUSH_BYTES,
295
- 100 * 1024, // Default: 100KB
296
- 'ES_FLUSH_BYTES'
297
- )
298
-
299
- const maxRetries = parseIntEnv(
300
- process.env.ES_MAX_RETRIES,
301
- 3, // Default: 3 retries
302
- 'ES_MAX_RETRIES'
303
- )
304
-
305
- const requestTimeout = parseIntEnv(
306
- process.env.ES_REQUEST_TIMEOUT_MS,
307
- 30000, // Default: 30 seconds
308
- 'ES_REQUEST_TIMEOUT_MS'
309
- )
310
-
311
- // Safe to access after validation
312
- const esConfig: ElasticConfig = {
313
- index: process.env.SERVER_NICKNAME,
314
- node: process.env.ELASTICSEARCH_NODE,
315
- auth: {
316
- username: process.env.ELASTICSEARCH_USERNAME,
317
- password: process.env.ELASTICSEARCH_PASSWORD,
318
- },
319
- // Configurable flush settings
320
- flushInterval: flushIntervalMs,
321
- 'flush-bytes': flushBytes,
322
- // Retry configuration for connection resilience
323
- maxRetries: maxRetries,
324
- requestTimeout: requestTimeout,
325
- // Automatically reconnect on connection faults
326
- sniffOnConnectionFault: true,
327
- }
328
- if (elasticConfig) {
329
- Object.assign(esConfig, elasticConfig)
330
- }
331
-
332
- // Create transport with connection lifecycle fix (pino-elasticsearch #140)
333
- esTransport = createElasticTransport(esConfig)
334
-
335
- // Handle Elasticsearch connection errors
336
- esTransport.on('error', (err: Error) => {
337
- console.error('[Logger] Elasticsearch transport error:', err.message)
338
- console.error(
339
- '[Logger] Logs may not be reaching Kibana. Check Elasticsearch connection.'
340
- )
341
- })
342
-
343
- // Handle insert errors (document indexing failures)
344
- esTransport.on('insertError', (err: Error & { document?: unknown }) => {
345
- console.error('[Logger] Elasticsearch insert error:', err.message)
346
- console.error('[Logger] Some logs failed to index to Elasticsearch.')
347
- if (err.document) {
348
- const docStr = JSON.stringify(err.document)
349
- const preview =
350
- docStr.length > 500
351
- ? `${docStr.substring(0, 500)}... (truncated)`
352
- : docStr
353
- console.error('[Logger] Dropped document preview:', preview)
354
- }
355
- })
356
-
357
- // Log successful connection (for debugging)
358
- esTransport.on('insert', () => {
359
- // Uncomment for debugging: console.log(`[Logger] Successfully inserted log entries`)
360
- })
361
-
362
- // Register shutdown handlers to flush logs on process exit
363
- registerShutdownHandlers()
364
-
365
- transports.push(esTransport)
366
- } else {
367
- transports.push(
368
- pino.destination({
369
- minLength: 1024,
370
- sync: true,
371
- })
372
- )
373
- }
374
-
375
- pinoLogger = pino(
376
- {
377
- level: logLevel,
378
- timestamp: stdTimeFunctions.isoTime.bind(stdTimeFunctions),
379
- },
380
- ...transports
381
- )
382
- }
383
- return pinoLogger
384
- }
385
-
386
- /**
387
- * Checks if a given log level is valid.
388
- * @param level - The log level to check.
389
- * @returns Whether the log level is valid.
390
- */
391
- export function isValidLogLevel(level: string): level is LOG_LEVEL {
392
- if (!['error', 'warn', 'info', 'debug', 'trace'].includes(level)) {
393
- throw new Error(
394
- `Invalid log level "${level}": only error, warn, info, debug, trace are valid.`
395
- )
396
- }
397
- return true
398
- }
399
-
400
- /**
401
- * Logger Wrapper.
402
- * Wraps a Pino logger instance and provides logging methods.
403
- */
404
- class Logger {
405
- private readonly _name: string
406
- private readonly _logger: PinoLogger
407
-
408
- /**
409
- * Creates a new Logger instance with default configuration.
410
- * @param name - The name of the logger.
411
- */
412
- constructor(name: string)
413
-
414
- /**
415
- * Creates a new Logger instance with custom Elasticsearch configuration.
416
- * @param name - The name of the logger.
417
- * @param elasticConfig - Optional Elasticsearch configuration.
418
- */
419
- constructor(name: string, elasticConfig?: ElasticConfig)
420
-
421
- constructor(name: string, elasticConfig?: ElasticConfig) {
422
- this._name = name
423
- this._logger = getLogger(elasticConfig)
424
- }
425
-
426
- /**
427
- * Build ECS-aligned and structured log payload.
428
- * - ECS: log.level, log.logger, event.code, service.name, service.environment, message
429
- * - Structured: Single plain object flattened as top-level snake_case fields (Kibana filterable)
430
- * - Trace: trace.id when running inside runWithTrace
431
- */
432
- private buildPayload(
433
- logLevel: LOG_LEVEL,
434
- logEvent: LogEvent,
435
- args: unknown[]
436
- ) {
437
- const isLocal =
438
- process.env.NODE_ENV === 'local' || process.env.NODE_ENV === 'test'
439
-
440
- // Defensive: missing Logs constant (undefined) crashes on logEvent.code
441
- const useFallback =
442
- !logEvent || typeof logEvent !== 'object' || !('code' in logEvent)
443
- const event = useFallback
444
- ? { code: 'UNKNOWN', msg: 'Missing or invalid log event constant' }
445
- : logEvent
446
-
447
- // ECS-aligned fields for Kibana (flat names to avoid mapping conflicts with existing indices)
448
- const ecs: Record<string, unknown> = {
449
- log_level: logLevel,
450
- log_logger: this._name,
451
- event_code: event.code,
452
- message: event.msg,
453
- service_name: process.env.SERVER_NICKNAME ?? 'unknown',
454
- service_environment: process.env.NODE_ENV ?? 'development',
455
- host_name: hostname(),
456
- }
457
-
458
- // Trace context for request-scoped correlation
459
- const trace = getTraceContext()
460
- if (trace) {
461
- ecs.trace_id = trace.traceId
462
- }
463
-
464
- // Structured context: put in single 'context' field to avoid ES mapping conflicts.
465
- // Flattening to top-level caused document_parsing_exception (object vs scalar type mismatches).
466
- // Nesting in context keeps structure consistent and avoids per-field mapping conflicts.
467
- let context: Record<string, unknown> | undefined
468
- let detail: unknown
469
- if (
470
- args.length === 1 &&
471
- isPlainObject(args[0]) &&
472
- Object.keys(args[0]).length > 0
473
- ) {
474
- context = sanitizeForElastic(args[0]) as Record<string, unknown>
475
- } else {
476
- detail = isLocal ? args : JSON.stringify(sanitizeForElastic(args))
477
- }
478
-
479
- // Legacy fields for backward compatibility (component, code, msg)
480
- const base: Record<string, unknown> = {
481
- ...ecs,
482
- component: this._name,
483
- code: event.code,
484
- msg: event.msg,
485
- }
486
- if (context !== undefined) {
487
- base.context = context
488
- }
489
- if (detail !== undefined) {
490
- base.detail = detail
491
- }
492
- // When fallback used: add call site for Kibana/Elasticsearch querying
493
- if (useFallback) {
494
- const callSite = getCallSiteForMissingLog()
495
- if (callSite) {
496
- base.missing_log_call_site = callSite
497
- }
498
- }
499
- return base
500
- }
501
-
502
- private log(logLevel: LOG_LEVEL, logEvent: LogEvent, ...args: unknown[]) {
503
- const payload = this.buildPayload(logLevel, logEvent, args)
504
- this._logger[logLevel](payload)
505
- }
506
-
507
- /**
508
- * Logs an error message.
509
- * @param logEvent - The event to log.
510
- * @param args - Additional arguments to include in the log.
511
- */
512
- error(logEvent: LogEvent, ...args: unknown[]) {
513
- this.log('error', logEvent, ...args)
514
- }
515
-
516
- /**
517
- * Logs a warning message.
518
- * @param logEvent - The event to log.
519
- * @param args - Additional arguments to include in the log.
520
- */
521
- warn(logEvent: LogEvent, ...args: unknown[]) {
522
- this.log('warn', logEvent, ...args)
523
- }
524
-
525
- /**
526
- * Logs an informational message.
527
- * @param logEvent - The event to log.
528
- * @param args - Additional arguments to include in the log.
529
- */
530
- info(logEvent: LogEvent, ...args: unknown[]) {
531
- this.log('info', logEvent, ...args)
532
- }
533
-
534
- /**
535
- * Logs a debug message.
536
- * @param logEvent - The event to log.
537
- * @param args - Additional arguments to include in the log.
538
- */
539
- debug(logEvent: LogEvent, ...args: unknown[]) {
540
- this.log('debug', logEvent, ...args)
541
- }
542
-
543
- /**
544
- * Logs a trace message.
545
- * @param logEvent - The event to log.
546
- * @param args - Additional arguments to include in the log.
547
- */
548
- trace(logEvent: LogEvent, ...args: unknown[]) {
549
- this.log('trace', logEvent, ...args)
550
- }
551
-
552
- /**
553
- * Runs an async operation and logs its duration.
554
- * Adds event.duration (ms) for Kibana performance dashboards and alerts.
555
- *
556
- * @param logEvent - The event to log on completion
557
- * @param fn - Async function to execute
558
- * @param context - Optional context object (flattened as top-level fields)
559
- * @returns Result of fn
560
- */
561
- async withDuration<T>(
562
- logEvent: LogEvent,
563
- fn: () => Promise<T>,
564
- context?: Record<string, unknown>
565
- ): Promise<T> {
566
- const start = Date.now()
567
- try {
568
- const result = await fn()
569
- const durationMs = Date.now() - start
570
- const payload = this.buildPayload('info', logEvent, [
571
- { ...context, duration_ms: durationMs, success: true },
572
- ])
573
- this._logger.info(payload)
574
- return result
575
- } catch (error) {
576
- const durationMs = Date.now() - start
577
- const errObj =
578
- error instanceof Error
579
- ? { error_message: error.message, error_type: error.constructor.name }
580
- : {}
581
- const payload = this.buildPayload('error', logEvent, [
582
- { ...context, ...errObj, duration_ms: durationMs, success: false },
583
- ])
584
- this._logger.error(payload)
585
- throw error
586
- }
587
- }
588
- }
589
-
590
- export default Logger
package/src/lib/pdf.ts DELETED
@@ -1,25 +0,0 @@
1
- // import { AxiosInstance } from '../utilities'
2
- /*
3
- Author : Mustafa Halabi https://github.com/mustafahalabi
4
- Date : 2023-06-24
5
- Description : Image to PDF converter
6
- Version : 1.0
7
- */
8
- class Pdf {
9
- /**
10
- * @remarks Convert image links into base64 format
11
- * @param url - The image url
12
- * @returns string
13
- * @example
14
- * ```typescript
15
- * pdf.getBase64Images('https://fastly.picsum.photos/id/15/200/300.jpg?hmac=lozQletmrLG9PGBV1hTM1PnmvHxKEU0lAZWu8F2oL30')
16
- * // => 'Hello-World'
17
- * ```
18
- * */
19
- getBase64Images = (_url: string): string => {
20
- return ''
21
- }
22
- }
23
-
24
- const pdf = new Pdf()
25
- export default pdf
@@ -1,46 +0,0 @@
1
- import { AsyncLocalStorage } from 'async_hooks'
2
- import { randomUUID } from 'crypto'
3
-
4
- /**
5
- * Trace context for request-scoped correlation in Kibana.
6
- * Enables filtering all logs from a single request/job by trace.id.
7
- */
8
- export interface TraceContext {
9
- /** Unique ID for the entire request/job flow */
10
- traceId: string
11
- /** Optional span ID for sub-operations */
12
- spanId?: string
13
- }
14
-
15
- const traceStorage = new AsyncLocalStorage<TraceContext>()
16
-
17
- /**
18
- * Run an async function with a new trace context.
19
- * All Logger calls within the callback will automatically include trace.id.
20
- *
21
- * @param fn - Async function to run within the trace context
22
- * @param traceId - Optional trace ID (defaults to random UUID)
23
- * @returns Result of fn
24
- */
25
- export const runWithTrace = async <T>(
26
- fn: () => Promise<T>,
27
- traceId?: string
28
- ): Promise<T> => {
29
- const id = traceId ?? randomUUID()
30
- return traceStorage.run({ traceId: id }, () => fn())
31
- }
32
-
33
- /**
34
- * Run a sync function with a new trace context.
35
- */
36
- export const runWithTraceSync = <T>(fn: () => T, traceId?: string): T => {
37
- const id = traceId ?? randomUUID()
38
- return traceStorage.run({ traceId: id }, () => fn())
39
- }
40
-
41
- /**
42
- * Get the current trace context (if running inside runWithTrace).
43
- */
44
- export const getTraceContext = (): TraceContext | undefined => {
45
- return traceStorage.getStore()
46
- }
@@ -1 +0,0 @@
1
- export * from './logger'