voltlog-io 1.0.5 → 1.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.
package/dist/index.mjs CHANGED
@@ -1,40 +1,418 @@
1
- import {
2
- LogLevel,
3
- LogLevelNameMap,
4
- LogLevelValueMap,
5
- aiEnrichmentMiddleware,
6
- alertMiddleware,
7
- batchTransport,
8
- browserJsonStreamTransport,
9
- consoleTransport,
10
- createHttpLogger,
11
- createLogger,
12
- createMiddleware,
13
- createOpenAiErrorAnalyzer,
14
- createTransport,
15
- datadogTransport,
16
- deduplicationMiddleware,
17
- discordTransport,
18
- heapUsageMiddleware,
19
- ipMiddleware,
20
- levelOverrideMiddleware,
21
- lokiTransport,
22
- nodeHttpMappers,
23
- ocppMiddleware,
24
- otelTraceMiddleware,
25
- otelTransport,
26
- prettyTransport,
27
- redactionMiddleware,
28
- resolveLevel,
29
- ringBufferTransport,
30
- samplingMiddleware,
31
- sentryTransport,
32
- shouldIncludeStack,
33
- shouldLog,
34
- slackTransport,
35
- userAgentMiddleware,
36
- webhookTransport
37
- } from "./chunk-DAFMRCAN.mjs";
1
+ // src/core/types.ts
2
+ var LogLevel = {
3
+ TRACE: 10,
4
+ DEBUG: 20,
5
+ INFO: 30,
6
+ WARN: 40,
7
+ ERROR: 50,
8
+ FATAL: 60,
9
+ SILENT: Infinity
10
+ };
11
+ var LogLevelNameMap = Object.fromEntries(
12
+ Object.entries(LogLevel).map(([k, v]) => [k.toLowerCase(), v])
13
+ );
14
+ var LogLevelValueMap = Object.fromEntries(
15
+ Object.entries(LogLevel).filter(([, v]) => Number.isFinite(v)).map(([k, v]) => [v, k])
16
+ );
17
+
18
+ // src/core/levels.ts
19
+ function resolveLevel(level) {
20
+ const n = LogLevelNameMap[level.toLowerCase()];
21
+ return n !== void 0 ? n : LogLevel.INFO;
22
+ }
23
+ function shouldLog(entryLevel, filterLevel) {
24
+ return entryLevel >= filterLevel;
25
+ }
26
+ function shouldIncludeStack(entryLevel, includeStack) {
27
+ if (typeof includeStack === "boolean") return includeStack;
28
+ return entryLevel >= resolveLevel(includeStack);
29
+ }
30
+
31
+ // src/core/pipeline.ts
32
+ function composeMiddleware(middleware, final) {
33
+ if (middleware.length === 0) return final;
34
+ return (entry) => {
35
+ let index = 0;
36
+ const next = (e) => {
37
+ if (index < middleware.length) {
38
+ const mw = middleware[index++];
39
+ mw(e, next);
40
+ } else {
41
+ final(e);
42
+ }
43
+ };
44
+ next(entry);
45
+ };
46
+ }
47
+ function fanOutToTransports(entry, transports, loggerLevel) {
48
+ for (const t of transports) {
49
+ const tLevel = t.level ? resolveLevel(t.level) : loggerLevel;
50
+ if (!shouldLog(entry.level, tLevel)) continue;
51
+ try {
52
+ const result = t.write(entry);
53
+ if (result && typeof result.catch === "function") {
54
+ result.catch(() => {
55
+ });
56
+ }
57
+ } catch {
58
+ }
59
+ }
60
+ }
61
+
62
+ // src/core/logger.ts
63
+ var randomUUID = typeof globalThis.crypto?.randomUUID === "function" ? () => globalThis.crypto.randomUUID() : () => "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
64
+ const r = Math.random() * 16 | 0;
65
+ return (c === "x" ? r : r & 3 | 8).toString(16);
66
+ });
67
+ var LoggerImpl = class {
68
+ _level;
69
+ _transports;
70
+ _middlewareList;
71
+ _pipeline;
72
+ _context;
73
+ _includeStack;
74
+ _timestampFn;
75
+ _idFn;
76
+ constructor(options = {}) {
77
+ this._level = resolveLevel(options.level ?? "INFO");
78
+ this._transports = [...options.transports ?? []];
79
+ this._middlewareList = [...options.middleware ?? []];
80
+ this._context = options.context ? { ...options.context } : {};
81
+ this._includeStack = options.includeStack ?? "ERROR";
82
+ this._timestampFn = options.timestamp ?? Date.now;
83
+ this._idFn = options.idGenerator !== void 0 ? options.idGenerator : randomUUID;
84
+ this._pipeline = this._buildPipeline();
85
+ }
86
+ // ─── Log Methods ────────────────────────────────────────────
87
+ trace(message, meta) {
88
+ if (10 < this._level) return;
89
+ this._log(10, "TRACE", message, meta);
90
+ }
91
+ debug(message, meta) {
92
+ if (20 < this._level) return;
93
+ this._log(20, "DEBUG", message, meta);
94
+ }
95
+ info(message, meta) {
96
+ if (30 < this._level) return;
97
+ this._log(30, "INFO", message, meta);
98
+ }
99
+ warn(message, meta) {
100
+ if (40 < this._level) return;
101
+ this._log(40, "WARN", message, meta);
102
+ }
103
+ error(message, metaOrError, error) {
104
+ if (50 < this._level) return;
105
+ if (metaOrError instanceof Error) {
106
+ this._log(50, "ERROR", message, void 0, metaOrError);
107
+ } else {
108
+ this._log(50, "ERROR", message, metaOrError, error);
109
+ }
110
+ }
111
+ fatal(message, metaOrError, error) {
112
+ if (metaOrError instanceof Error) {
113
+ this._log(60, "FATAL", message, void 0, metaOrError);
114
+ } else {
115
+ this._log(60, "FATAL", message, metaOrError, error);
116
+ }
117
+ }
118
+ // ─── Child Logger ───────────────────────────────────────────
119
+ child(context) {
120
+ return new ChildLoggerImpl(this, { ...this._context, ...context });
121
+ }
122
+ // ─── Dynamic Configuration ─────────────────────────────────
123
+ addTransport(transport) {
124
+ this._transports.push(transport);
125
+ }
126
+ removeTransport(name) {
127
+ this._transports = this._transports.filter((t) => t.name !== name);
128
+ }
129
+ addMiddleware(middleware) {
130
+ this._middlewareList.push(middleware);
131
+ this._pipeline = this._buildPipeline();
132
+ }
133
+ removeMiddleware(middleware) {
134
+ this._middlewareList = this._middlewareList.filter((m) => m !== middleware);
135
+ this._pipeline = this._buildPipeline();
136
+ }
137
+ // ─── Level Control ─────────────────────────────────────────
138
+ setLevel(level) {
139
+ this._level = resolveLevel(level);
140
+ }
141
+ getLevel() {
142
+ return LogLevelValueMap[this._level] ?? "INFO";
143
+ }
144
+ isLevelEnabled(level) {
145
+ return resolveLevel(level) >= this._level;
146
+ }
147
+ // ─── Timer ─────────────────────────────────────────────────
148
+ startTimer(level) {
149
+ const start = performance.now();
150
+ const logLevel = level ?? "INFO";
151
+ return {
152
+ done: (message, meta) => {
153
+ const durationMs = Math.round(performance.now() - start);
154
+ const merged = { ...meta, durationMs };
155
+ const methodKey = logLevel.toLowerCase();
156
+ this[methodKey](message, merged);
157
+ },
158
+ elapsed: () => Math.round(performance.now() - start)
159
+ };
160
+ }
161
+ // ─── Lifecycle ──────────────────────────────────────────────
162
+ async flush() {
163
+ await Promise.all(this._transports.map((t) => t.flush?.()).filter(Boolean));
164
+ }
165
+ async close() {
166
+ await this.flush();
167
+ await Promise.all(this._transports.map((t) => t.close?.()).filter(Boolean));
168
+ }
169
+ // ─── Internal ───────────────────────────────────────────────
170
+ /** @internal */
171
+ _log(level, levelName, message, meta, error) {
172
+ this._logWithContext(level, levelName, message, this._context, meta, error);
173
+ }
174
+ /** @internal — used by child loggers to inject bound context */
175
+ _logWithContext(level, levelName, message, context, meta, error) {
176
+ if (!shouldLog(level, this._level)) return;
177
+ const entry = {
178
+ id: this._idFn ? this._idFn() : "",
179
+ level,
180
+ levelName,
181
+ message,
182
+ timestamp: this._timestampFn(),
183
+ meta: meta ?? {},
184
+ context: Object.keys(context).length > 0 ? context : void 0
185
+ };
186
+ if (error) {
187
+ entry.error = serializeError(
188
+ error,
189
+ shouldIncludeStack(level, this._includeStack)
190
+ );
191
+ }
192
+ this._pipeline(entry);
193
+ }
194
+ _buildPipeline() {
195
+ return composeMiddleware(this._middlewareList, (entry) => {
196
+ fanOutToTransports(entry, this._transports, this._level);
197
+ });
198
+ }
199
+ };
200
+ function serializeError(error, includeStack, depth = 0) {
201
+ const logError = {
202
+ message: error.message,
203
+ name: error.name,
204
+ code: error.code
205
+ };
206
+ if (includeStack) {
207
+ logError.stack = error.stack;
208
+ }
209
+ if (error.cause instanceof Error && depth < 5) {
210
+ logError.cause = serializeError(error.cause, includeStack, depth + 1);
211
+ }
212
+ return logError;
213
+ }
214
+ var ChildLoggerImpl = class _ChildLoggerImpl {
215
+ constructor(_parent, _context) {
216
+ this._parent = _parent;
217
+ this._context = _context;
218
+ }
219
+ trace(message, meta) {
220
+ this._parent._logWithContext(10, "TRACE", message, this._context, meta);
221
+ }
222
+ debug(message, meta) {
223
+ this._parent._logWithContext(20, "DEBUG", message, this._context, meta);
224
+ }
225
+ info(message, meta) {
226
+ this._parent._logWithContext(30, "INFO", message, this._context, meta);
227
+ }
228
+ warn(message, meta) {
229
+ this._parent._logWithContext(40, "WARN", message, this._context, meta);
230
+ }
231
+ error(message, metaOrError, error) {
232
+ if (metaOrError instanceof Error) {
233
+ this._parent._logWithContext(
234
+ 50,
235
+ "ERROR",
236
+ message,
237
+ this._context,
238
+ void 0,
239
+ metaOrError
240
+ );
241
+ } else {
242
+ this._parent._logWithContext(
243
+ 50,
244
+ "ERROR",
245
+ message,
246
+ this._context,
247
+ metaOrError,
248
+ error
249
+ );
250
+ }
251
+ }
252
+ fatal(message, metaOrError, error) {
253
+ if (metaOrError instanceof Error) {
254
+ this._parent._logWithContext(
255
+ 60,
256
+ "FATAL",
257
+ message,
258
+ this._context,
259
+ void 0,
260
+ metaOrError
261
+ );
262
+ } else {
263
+ this._parent._logWithContext(
264
+ 60,
265
+ "FATAL",
266
+ message,
267
+ this._context,
268
+ metaOrError,
269
+ error
270
+ );
271
+ }
272
+ }
273
+ child(context) {
274
+ return new _ChildLoggerImpl(this._parent, {
275
+ ...this._context,
276
+ ...context
277
+ });
278
+ }
279
+ addTransport(transport) {
280
+ this._parent.addTransport(transport);
281
+ }
282
+ removeTransport(name) {
283
+ this._parent.removeTransport(name);
284
+ }
285
+ addMiddleware(middleware) {
286
+ this._parent.addMiddleware(middleware);
287
+ }
288
+ removeMiddleware(middleware) {
289
+ this._parent.removeMiddleware(middleware);
290
+ }
291
+ setLevel(level) {
292
+ this._parent.setLevel(level);
293
+ }
294
+ getLevel() {
295
+ return this._parent.getLevel();
296
+ }
297
+ isLevelEnabled(level) {
298
+ return this._parent.isLevelEnabled(level);
299
+ }
300
+ startTimer(level) {
301
+ return this._parent.startTimer(level);
302
+ }
303
+ flush() {
304
+ return this._parent.flush();
305
+ }
306
+ close() {
307
+ return this._parent.close();
308
+ }
309
+ };
310
+ function createLogger(options) {
311
+ return new LoggerImpl(options);
312
+ }
313
+
314
+ // src/middleware/ai-enrichment.ts
315
+ function aiEnrichmentMiddleware(options) {
316
+ const minLevel = resolveLevel(options.level ?? "ERROR");
317
+ const timeoutMs = options.timeout ?? 2e3;
318
+ const swallow = options.swallowErrors ?? true;
319
+ const fieldName = options.targetField ?? "ai_analysis";
320
+ return async (entry, next) => {
321
+ if (entry.level < minLevel) {
322
+ next(entry);
323
+ return;
324
+ }
325
+ try {
326
+ const analysisPromise = options.analyzer(entry);
327
+ const timeoutPromise = new Promise(
328
+ (_, reject) => setTimeout(() => reject(new Error("AI Analysis Timeout")), timeoutMs)
329
+ );
330
+ const result = await Promise.race([analysisPromise, timeoutPromise]);
331
+ if (result) {
332
+ entry.meta = {
333
+ ...entry.meta,
334
+ [fieldName]: result
335
+ };
336
+ }
337
+ } catch (err) {
338
+ if (!swallow) {
339
+ throw err;
340
+ }
341
+ }
342
+ next(entry);
343
+ };
344
+ }
345
+ function createOpenAiErrorAnalyzer(apiKey, model = "gpt-3.5-turbo", systemPrompt = "You are a log analyzer. Explain this error briefly and suggest a fix in 1 sentence.") {
346
+ return async (entry) => {
347
+ try {
348
+ const response = await fetch(
349
+ "https://api.openai.com/v1/chat/completions",
350
+ {
351
+ method: "POST",
352
+ headers: {
353
+ "Content-Type": "application/json",
354
+ Authorization: `Bearer ${apiKey}`
355
+ },
356
+ body: JSON.stringify({
357
+ model,
358
+ messages: [
359
+ { role: "system", content: systemPrompt },
360
+ {
361
+ role: "user",
362
+ content: `Error Message: ${entry.message}
363
+ Context: ${JSON.stringify(entry.meta)}`
364
+ }
365
+ ],
366
+ max_tokens: 150
367
+ })
368
+ }
369
+ );
370
+ if (!response.ok) return null;
371
+ const data = await response.json();
372
+ return data.choices?.[0]?.message?.content ?? null;
373
+ } catch {
374
+ return null;
375
+ }
376
+ };
377
+ }
378
+
379
+ // src/middleware/alert.ts
380
+ function alertMiddleware(rules) {
381
+ const states = /* @__PURE__ */ new Map();
382
+ for (const rule of rules) {
383
+ states.set(rule.name, { entries: [], lastFired: -Infinity });
384
+ }
385
+ return (entry, next) => {
386
+ const now = entry.timestamp;
387
+ for (const rule of rules) {
388
+ if (!rule.when(entry)) continue;
389
+ const state = states.get(rule.name);
390
+ const windowMs = rule.windowMs ?? Infinity;
391
+ const threshold = rule.threshold ?? 1;
392
+ const cooldownMs = rule.cooldownMs ?? 0;
393
+ if (Number.isFinite(windowMs)) {
394
+ state.entries = state.entries.filter(
395
+ (e) => now - e.timestamp < windowMs
396
+ );
397
+ }
398
+ state.entries.push(entry);
399
+ if (state.entries.length >= threshold && now - state.lastFired >= cooldownMs) {
400
+ const alertEntries = [...state.entries];
401
+ state.entries = [];
402
+ state.lastFired = now;
403
+ try {
404
+ const result = rule.onAlert(alertEntries);
405
+ if (result && typeof result.catch === "function") {
406
+ result.catch(() => {
407
+ });
408
+ }
409
+ } catch {
410
+ }
411
+ }
412
+ }
413
+ next(entry);
414
+ };
415
+ }
38
416
 
39
417
  // src/middleware/async-context.ts
40
418
  import { AsyncLocalStorage } from "async_hooks";
@@ -75,10 +453,10 @@ function asyncContextMiddleware() {
75
453
  }
76
454
 
77
455
  // src/middleware/correlation-id.ts
78
- import { randomUUID } from "crypto";
456
+ var _randomUUID = () => globalThis.crypto.randomUUID();
79
457
  function correlationIdMiddleware(options = {}) {
80
458
  const header = options.header ?? "x-correlation-id";
81
- const generate = options.generator ?? randomUUID;
459
+ const generate = options.generator ?? _randomUUID;
82
460
  return (entry, next) => {
83
461
  if (entry.correlationId) {
84
462
  return next(entry);
@@ -96,6 +474,559 @@ function correlationIdMiddleware(options = {}) {
96
474
  };
97
475
  }
98
476
 
477
+ // src/middleware/create-middleware.ts
478
+ function createMiddleware(fn) {
479
+ return fn;
480
+ }
481
+
482
+ // src/middleware/deduplication.ts
483
+ function deduplicationMiddleware(options = {}) {
484
+ const windowMs = options.windowMs ?? 1e3;
485
+ const keyFn = options.keyFn ?? ((e) => `${e.level}:${e.message}:${e.error?.message ?? ""}`);
486
+ const buffer = /* @__PURE__ */ new Map();
487
+ return (entry, next) => {
488
+ const key = keyFn(entry);
489
+ if (buffer.has(key)) {
490
+ const state = buffer.get(key);
491
+ state.count++;
492
+ return;
493
+ }
494
+ const timer = setTimeout(() => {
495
+ const state = buffer.get(key);
496
+ if (state) {
497
+ buffer.delete(key);
498
+ if (state.count > 1) {
499
+ state.entry.meta = {
500
+ ...state.entry.meta,
501
+ duplicateCount: state.count
502
+ };
503
+ }
504
+ next(state.entry);
505
+ }
506
+ }, windowMs);
507
+ buffer.set(key, {
508
+ entry,
509
+ count: 1,
510
+ timer
511
+ });
512
+ };
513
+ }
514
+
515
+ // src/middleware/heap-usage.ts
516
+ function heapUsageMiddleware(options = {}) {
517
+ const fieldName = options.fieldName ?? "memory";
518
+ return (entry, next) => {
519
+ if (typeof process !== "undefined" && process.memoryUsage) {
520
+ const memory = process.memoryUsage();
521
+ entry.meta = {
522
+ ...entry.meta,
523
+ [fieldName]: {
524
+ rss: memory.rss,
525
+ heapTotal: memory.heapTotal,
526
+ heapUsed: memory.heapUsed
527
+ }
528
+ };
529
+ }
530
+ next(entry);
531
+ };
532
+ }
533
+
534
+ // src/middleware/http.ts
535
+ var nodeHttpMappers = {
536
+ req: {
537
+ getMethod: (req) => req.method || "UNKNOWN",
538
+ getUrl: (req) => req.originalUrl || req.url || "/",
539
+ getIp: (req) => req.ip || req.socket?.remoteAddress || req.headers?.["x-forwarded-for"] || void 0,
540
+ getUserAgent: (req) => req.headers?.["user-agent"] || void 0,
541
+ getHeader: (req, name) => req.headers?.[name] || void 0
542
+ },
543
+ res: {
544
+ getStatusCode: (res) => res.statusCode || 200,
545
+ onFinish: (res, callback) => {
546
+ if (typeof res.on === "function") {
547
+ res.on("finish", callback);
548
+ res.on("close", callback);
549
+ } else {
550
+ callback();
551
+ }
552
+ }
553
+ }
554
+ };
555
+ function createHttpLogger(logger, options) {
556
+ const {
557
+ reqMapper,
558
+ resMapper,
559
+ level = "INFO",
560
+ skip,
561
+ extractContext
562
+ } = options;
563
+ return (req, res) => {
564
+ if (skip?.(req)) {
565
+ return;
566
+ }
567
+ const startTime = performance.now();
568
+ let finished = false;
569
+ resMapper.onFinish(res, () => {
570
+ if (finished) return;
571
+ finished = true;
572
+ const durationMs = Math.round(performance.now() - startTime);
573
+ const statusCode = resMapper.getStatusCode(res);
574
+ const method = reqMapper.getMethod(req);
575
+ const url = reqMapper.getUrl(req);
576
+ const meta = {
577
+ method,
578
+ url,
579
+ statusCode,
580
+ durationMs,
581
+ ip: reqMapper.getIp ? reqMapper.getIp(req) : void 0,
582
+ userAgent: reqMapper.getUserAgent ? reqMapper.getUserAgent(req) : void 0
583
+ };
584
+ if (extractContext) {
585
+ Object.assign(meta, extractContext(req, res));
586
+ }
587
+ let finalLevel = level;
588
+ if (statusCode >= 500) finalLevel = "ERROR";
589
+ else if (statusCode >= 400 && level === "INFO") finalLevel = "WARN";
590
+ const methodKey = finalLevel.toLowerCase();
591
+ logger[methodKey](
592
+ `${method} ${url} - ${statusCode} (${durationMs}ms)`,
593
+ meta
594
+ );
595
+ });
596
+ };
597
+ }
598
+
599
+ // src/middleware/ip.ts
600
+ function ipMiddleware(options = {}) {
601
+ const targetField = options.fieldName ?? "ip";
602
+ const keysToCheck = options.headerKeys ?? [
603
+ "x-forwarded-for",
604
+ "x-real-ip",
605
+ "req.ip",
606
+ "ip",
607
+ "x-client-ip"
608
+ ];
609
+ return (entry, next) => {
610
+ const meta = entry.meta;
611
+ const headers = meta.headers || {};
612
+ const req = meta.req || {};
613
+ let foundIp;
614
+ for (const key of keysToCheck) {
615
+ if (typeof meta[key] === "string") {
616
+ foundIp = meta[key];
617
+ break;
618
+ }
619
+ if (typeof headers[key] === "string") {
620
+ foundIp = headers[key];
621
+ break;
622
+ }
623
+ if (typeof req[key] === "string") {
624
+ foundIp = req[key];
625
+ break;
626
+ }
627
+ if (key === "req.ip" && typeof req.ip === "string") {
628
+ foundIp = req.ip;
629
+ break;
630
+ }
631
+ }
632
+ if (foundIp) {
633
+ const firstIp = typeof foundIp === "string" ? foundIp.split(",")[0].trim() : String(foundIp);
634
+ entry.meta = {
635
+ ...entry.meta,
636
+ [targetField]: firstIp
637
+ };
638
+ }
639
+ next(entry);
640
+ };
641
+ }
642
+
643
+ // src/middleware/level-override.ts
644
+ function levelOverrideMiddleware(options = {}) {
645
+ const key = options.key ?? "x-log-level";
646
+ const cleanup = options.cleanup ?? true;
647
+ return (entry, next) => {
648
+ const meta = entry.meta;
649
+ const context = entry.context;
650
+ const levelName = meta[key] || context?.[key] || meta.headers?.[key];
651
+ if (levelName && typeof levelName === "string") {
652
+ const upperName = levelName.toUpperCase();
653
+ if (LogLevel[upperName]) {
654
+ entry.level = LogLevel[upperName];
655
+ entry.levelName = upperName;
656
+ if (cleanup) {
657
+ delete meta[key];
658
+ if (meta.headers) {
659
+ delete meta.headers[key];
660
+ }
661
+ }
662
+ }
663
+ }
664
+ next(entry);
665
+ };
666
+ }
667
+
668
+ // src/middleware/ocpp.ts
669
+ function ocppMiddleware(options = {}) {
670
+ const autoPayloadSize = options.autoPayloadSize ?? true;
671
+ const propagateCorrelationId = options.propagateCorrelationId ?? true;
672
+ return (entry, next) => {
673
+ const enriched = { ...entry, meta: { ...entry.meta } };
674
+ if (autoPayloadSize && enriched.meta.payloadSize === void 0 && enriched.meta.action) {
675
+ try {
676
+ enriched.meta.payloadSize = JSON.stringify(enriched.meta).length;
677
+ } catch {
678
+ }
679
+ }
680
+ if (propagateCorrelationId && enriched.meta.correlationId && !enriched.correlationId) {
681
+ enriched.correlationId = enriched.meta.correlationId;
682
+ }
683
+ next(enriched);
684
+ };
685
+ }
686
+
687
+ // src/middleware/otel-trace.ts
688
+ function otelTraceMiddleware(options = {}) {
689
+ let traceApi = options.traceApi ?? null;
690
+ let resolved = !!traceApi;
691
+ let resolvePromise = null;
692
+ function ensureResolved() {
693
+ if (resolved || resolvePromise) return resolvePromise ?? Promise.resolve();
694
+ resolvePromise = import("@opentelemetry/api").then((api) => {
695
+ traceApi = api;
696
+ resolved = true;
697
+ }).catch(() => {
698
+ resolved = true;
699
+ });
700
+ return resolvePromise;
701
+ }
702
+ return (entry, next) => {
703
+ ensureResolved().catch(() => {
704
+ });
705
+ if (resolved && traceApi?.trace) {
706
+ try {
707
+ const activeSpan = traceApi.trace.getActiveSpan?.();
708
+ if (activeSpan) {
709
+ const spanContext = activeSpan.spanContext?.();
710
+ if (spanContext) {
711
+ const meta = entry.meta;
712
+ meta.traceId = spanContext.traceId;
713
+ meta.spanId = spanContext.spanId;
714
+ meta.traceFlags = spanContext.traceFlags;
715
+ if (!entry.correlationId) {
716
+ entry.correlationId = spanContext.traceId;
717
+ }
718
+ }
719
+ }
720
+ } catch {
721
+ }
722
+ }
723
+ next(entry);
724
+ };
725
+ }
726
+
727
+ // src/middleware/redaction.ts
728
+ var DEFAULT_REDACT_VALUE = "[REDACTED]";
729
+ function redactionMiddleware(options) {
730
+ const paths = new Set(options.paths.map((p) => p.toLowerCase()));
731
+ const replacement = options.replacement ?? DEFAULT_REDACT_VALUE;
732
+ const deep = options.deep ?? true;
733
+ function redactObject(obj) {
734
+ const result = {};
735
+ for (const [key, value] of Object.entries(obj)) {
736
+ if (paths.has(key.toLowerCase())) {
737
+ result[key] = replacement;
738
+ } else if (deep && value !== null && typeof value === "object" && !Array.isArray(value)) {
739
+ result[key] = redactObject(value);
740
+ } else {
741
+ result[key] = value;
742
+ }
743
+ }
744
+ return result;
745
+ }
746
+ return (entry, next) => {
747
+ const redacted = { ...entry };
748
+ if (entry.meta && typeof entry.meta === "object") {
749
+ redacted.meta = redactObject(
750
+ entry.meta
751
+ );
752
+ }
753
+ if (entry.context && typeof entry.context === "object") {
754
+ redacted.context = redactObject(entry.context);
755
+ }
756
+ next(redacted);
757
+ };
758
+ }
759
+
760
+ // src/middleware/sampling.ts
761
+ function samplingMiddleware(options = {}) {
762
+ const keyFn = options.keyFn ?? ((entry) => entry.message);
763
+ const maxPerWindow = options.maxPerWindow ?? 100;
764
+ const windowMs = options.windowMs ?? 6e4;
765
+ const sampleRate = options.sampleRate ?? 1;
766
+ const priorityLevel = options.priorityLevel ?? 40;
767
+ const buckets = /* @__PURE__ */ new Map();
768
+ return (entry, next) => {
769
+ if (entry.level >= priorityLevel) {
770
+ return next(entry);
771
+ }
772
+ if (sampleRate < 1 && Math.random() > sampleRate) {
773
+ return;
774
+ }
775
+ const key = keyFn(entry);
776
+ const now = entry.timestamp;
777
+ let bucket = buckets.get(key);
778
+ if (!bucket || now - bucket.windowStart >= windowMs) {
779
+ bucket = { count: 0, windowStart: now };
780
+ buckets.set(key, bucket);
781
+ }
782
+ if (bucket.count < maxPerWindow) {
783
+ bucket.count++;
784
+ next(entry);
785
+ }
786
+ if (buckets.size > 2e3) {
787
+ const expireBefore = now - windowMs * 2;
788
+ for (const [k, b] of buckets) {
789
+ if (b.windowStart < expireBefore) {
790
+ buckets.delete(k);
791
+ }
792
+ }
793
+ }
794
+ };
795
+ }
796
+
797
+ // src/middleware/user-agent.ts
798
+ function userAgentMiddleware(options = {}) {
799
+ const sourceField = options.sourceField;
800
+ const targetField = options.targetField ?? "client";
801
+ return (entry, next) => {
802
+ const meta = entry.meta;
803
+ const context = entry.context;
804
+ const ua = (sourceField ? meta[sourceField] : void 0) || meta.userAgent || meta["user-agent"] || context?.userAgent || context?.["user-agent"];
805
+ if (ua) {
806
+ const info = parseUserAgent(ua);
807
+ entry.meta = {
808
+ ...entry.meta,
809
+ [targetField]: info
810
+ };
811
+ }
812
+ next(entry);
813
+ };
814
+ }
815
+ function parseUserAgent(ua) {
816
+ const browser = /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i.exec(ua) || [];
817
+ let name = browser[1] ? browser[1].toLowerCase() : "unknown";
818
+ let version = browser[2] || "unknown";
819
+ if (/trident/i.test(name)) {
820
+ name = "ie";
821
+ } else if (name === "chrome") {
822
+ const edge = /edg(e)?\/(\d+)/i.exec(ua);
823
+ if (edge) {
824
+ name = "edge";
825
+ version = edge[2];
826
+ }
827
+ }
828
+ const osResult = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.exec(
829
+ ua
830
+ );
831
+ const os = osResult ? osResult[0].toLowerCase() : "desktop";
832
+ return { browser: name, version, os };
833
+ }
834
+
835
+ // src/transports/batch.ts
836
+ function batchTransport(inner, options = {}) {
837
+ const batchSize = options.batchSize ?? 100;
838
+ const flushIntervalMs = options.flushIntervalMs ?? 5e3;
839
+ let buffer = [];
840
+ let flushTimer = null;
841
+ function scheduleFlush() {
842
+ if (flushTimer) return;
843
+ flushTimer = setTimeout(() => {
844
+ flushTimer = null;
845
+ doFlush();
846
+ }, flushIntervalMs);
847
+ }
848
+ function doFlush() {
849
+ if (buffer.length === 0) return;
850
+ const batch = buffer;
851
+ buffer = [];
852
+ for (const entry of batch) {
853
+ try {
854
+ const result = inner.write(entry);
855
+ if (result && typeof result.catch === "function") {
856
+ result.catch(() => {
857
+ });
858
+ }
859
+ } catch {
860
+ }
861
+ }
862
+ }
863
+ return {
864
+ name: `batch(${inner.name})`,
865
+ level: inner.level,
866
+ write(entry) {
867
+ buffer.push(entry);
868
+ if (buffer.length >= batchSize) {
869
+ doFlush();
870
+ } else {
871
+ scheduleFlush();
872
+ }
873
+ },
874
+ async flush() {
875
+ if (flushTimer) {
876
+ clearTimeout(flushTimer);
877
+ flushTimer = null;
878
+ }
879
+ doFlush();
880
+ await inner.flush?.();
881
+ },
882
+ async close() {
883
+ await this.flush?.();
884
+ await inner.close?.();
885
+ }
886
+ };
887
+ }
888
+
889
+ // src/transports/console.ts
890
+ function consoleTransport(options = {}) {
891
+ const useConsoleLevels = options.useConsoleLevels ?? true;
892
+ const formatter = options.formatter ?? ((entry) => JSON.stringify(entry));
893
+ return {
894
+ name: "console",
895
+ level: options.level,
896
+ write(entry) {
897
+ const output = formatter(entry);
898
+ if (!useConsoleLevels) {
899
+ console.log(output);
900
+ return;
901
+ }
902
+ if (entry.level >= LogLevel.FATAL) {
903
+ console.error(output);
904
+ } else if (entry.level >= LogLevel.ERROR) {
905
+ console.error(output);
906
+ } else if (entry.level >= LogLevel.WARN) {
907
+ console.warn(output);
908
+ } else if (entry.level >= LogLevel.INFO) {
909
+ console.info(output);
910
+ } else if (entry.level >= LogLevel.DEBUG) {
911
+ console.debug(output);
912
+ } else {
913
+ console.log(output);
914
+ }
915
+ }
916
+ };
917
+ }
918
+
919
+ // src/transports/create-transport.ts
920
+ function createTransport(name, write, options = {}) {
921
+ return {
922
+ name,
923
+ write,
924
+ ...options
925
+ };
926
+ }
927
+
928
+ // src/transports/datadog.ts
929
+ function datadogTransport(options) {
930
+ const {
931
+ apiKey,
932
+ site = "datadoghq.com",
933
+ service,
934
+ ddSource = "nodejs",
935
+ hostname,
936
+ tags,
937
+ level
938
+ } = options;
939
+ const url = `https://http-intake.logs.${site}/api/v2/logs`;
940
+ return {
941
+ name: "datadog",
942
+ level,
943
+ async write(entry) {
944
+ const payload = {
945
+ ddsource: ddSource,
946
+ ddtags: tags,
947
+ hostname,
948
+ service,
949
+ message: entry.message,
950
+ status: entry.levelName.toLowerCase(),
951
+ // Datadog uses lowercase status
952
+ ...entry.meta,
953
+ timestamp: entry.timestamp
954
+ // Datadog auto-parses this
955
+ };
956
+ try {
957
+ await fetch(url, {
958
+ method: "POST",
959
+ headers: {
960
+ "Content-Type": "application/json",
961
+ "DD-API-KEY": apiKey
962
+ },
963
+ body: JSON.stringify(payload)
964
+ });
965
+ } catch (err) {
966
+ console.error("[voltlog] Datadog push failed", err);
967
+ }
968
+ }
969
+ };
970
+ }
971
+
972
+ // src/transports/discord.ts
973
+ function discordTransport(options) {
974
+ const { webhookUrl, username, avatarUrl, level = "ERROR" } = options;
975
+ return {
976
+ name: "discord",
977
+ level,
978
+ async write(entry) {
979
+ try {
980
+ await fetch(webhookUrl, {
981
+ method: "POST",
982
+ headers: { "Content-Type": "application/json" },
983
+ body: JSON.stringify(
984
+ formatDiscordPayload(entry, username, avatarUrl)
985
+ )
986
+ });
987
+ } catch (_err) {
988
+ }
989
+ }
990
+ };
991
+ }
992
+ function formatDiscordPayload(entry, username, avatar_url) {
993
+ const color = getLevelColor(entry.level);
994
+ return {
995
+ username: username || "VoltLog",
996
+ avatar_url,
997
+ embeds: [
998
+ {
999
+ title: `${entry.levelName} - ${entry.message}`,
1000
+ color,
1001
+ timestamp: new Date(entry.timestamp).toISOString(),
1002
+ fields: [
1003
+ {
1004
+ name: "Meta",
1005
+ value: `\`\`\`json
1006
+ ${JSON.stringify(entry.meta, null, 2).slice(
1007
+ 0,
1008
+ 1e3
1009
+ )}
1010
+ \`\`\``
1011
+ },
1012
+ entry.error?.stack ? {
1013
+ name: "Stack",
1014
+ value: `\`\`\`js
1015
+ ${entry.error.stack.slice(0, 1e3)}
1016
+ \`\`\``
1017
+ } : null
1018
+ ].filter(Boolean)
1019
+ }
1020
+ ]
1021
+ };
1022
+ }
1023
+ function getLevelColor(level) {
1024
+ if (level >= 50) return 15158332;
1025
+ if (level >= 40) return 16776960;
1026
+ if (level >= 30) return 3447003;
1027
+ return 9807270;
1028
+ }
1029
+
99
1030
  // src/transports/file.ts
100
1031
  import fs from "fs";
101
1032
  import path from "path";
@@ -207,6 +1138,431 @@ function jsonStreamTransport(options) {
207
1138
  };
208
1139
  }
209
1140
 
1141
+ // src/transports/loki.ts
1142
+ function lokiTransport(options) {
1143
+ const { host, level } = options;
1144
+ const staticLabels = options.labels ?? { app: "voltlog" };
1145
+ const batchSize = options.batchSize ?? 10;
1146
+ const interval = options.interval ?? 5e3;
1147
+ const includeMetadata = options.includeMetadata !== false;
1148
+ const retryEnabled = options.retry ?? false;
1149
+ const maxRetries = options.maxRetries ?? 3;
1150
+ const url = `${host.replace(/\/$/, "")}/loki/api/v1/push`;
1151
+ const headers = {
1152
+ "Content-Type": "application/json"
1153
+ };
1154
+ if (options.basicAuthUser && options.basicAuthPassword) {
1155
+ const creds = btoa(`${options.basicAuthUser}:${options.basicAuthPassword}`);
1156
+ headers.Authorization = `Basic ${creds}`;
1157
+ }
1158
+ if (options.tenantId) {
1159
+ headers["X-Scope-OrgID"] = options.tenantId;
1160
+ }
1161
+ let buffer = [];
1162
+ let timer = null;
1163
+ function buildLogLine(entry) {
1164
+ const payload = {
1165
+ level: entry.levelName,
1166
+ message: entry.message,
1167
+ ...entry.meta
1168
+ };
1169
+ if (includeMetadata) {
1170
+ if (entry.correlationId) {
1171
+ payload.correlationId = entry.correlationId;
1172
+ }
1173
+ if (entry.context) {
1174
+ payload.context = entry.context;
1175
+ }
1176
+ if (entry.error) {
1177
+ payload.error = entry.error;
1178
+ }
1179
+ }
1180
+ return JSON.stringify(payload);
1181
+ }
1182
+ function buildStreams(batch) {
1183
+ if (!options.dynamicLabels) {
1184
+ return [
1185
+ {
1186
+ stream: staticLabels,
1187
+ values: batch.map((e) => [
1188
+ String(e.timestamp * 1e6),
1189
+ // Loki wants nanoseconds
1190
+ buildLogLine(e)
1191
+ ])
1192
+ }
1193
+ ];
1194
+ }
1195
+ const grouped = /* @__PURE__ */ new Map();
1196
+ for (const entry of batch) {
1197
+ const dynamic = options.dynamicLabels(entry);
1198
+ const merged = { ...staticLabels };
1199
+ for (const [k, v] of Object.entries(dynamic)) {
1200
+ if (v !== void 0) merged[k] = v;
1201
+ }
1202
+ const key = JSON.stringify(merged);
1203
+ let group = grouped.get(key);
1204
+ if (!group) {
1205
+ group = { labels: merged, values: [] };
1206
+ grouped.set(key, group);
1207
+ }
1208
+ group.values.push([
1209
+ String(entry.timestamp * 1e6),
1210
+ buildLogLine(entry)
1211
+ ]);
1212
+ }
1213
+ return Array.from(grouped.values()).map((g) => ({
1214
+ stream: g.labels,
1215
+ values: g.values
1216
+ }));
1217
+ }
1218
+ async function pushWithRetry(batch) {
1219
+ const body = JSON.stringify({ streams: buildStreams(batch) });
1220
+ let lastError;
1221
+ const attempts = retryEnabled ? maxRetries : 1;
1222
+ for (let attempt = 0; attempt < attempts; attempt++) {
1223
+ try {
1224
+ const response = await fetch(url, { method: "POST", headers, body });
1225
+ if (response.ok) return;
1226
+ if (response.status >= 400 && response.status < 500) {
1227
+ console.error(`[voltlog] Loki push failed: ${response.status}`);
1228
+ return;
1229
+ }
1230
+ lastError = new Error(`Loki HTTP ${response.status}`);
1231
+ } catch (err) {
1232
+ lastError = err;
1233
+ }
1234
+ if (attempt < attempts - 1) {
1235
+ await new Promise((r) => setTimeout(r, 100 * 2 ** attempt));
1236
+ }
1237
+ }
1238
+ console.error("[voltlog] Loki push failed after retries", lastError);
1239
+ }
1240
+ const doFlush = async () => {
1241
+ if (buffer.length === 0) return;
1242
+ const batch = buffer;
1243
+ buffer = [];
1244
+ await pushWithRetry(batch);
1245
+ };
1246
+ const schedule = () => {
1247
+ if (!timer) {
1248
+ timer = setTimeout(() => {
1249
+ timer = null;
1250
+ doFlush();
1251
+ }, interval);
1252
+ }
1253
+ };
1254
+ return {
1255
+ name: "loki",
1256
+ level,
1257
+ write(entry) {
1258
+ buffer.push(entry);
1259
+ if (buffer.length >= batchSize) {
1260
+ if (timer) clearTimeout(timer);
1261
+ timer = null;
1262
+ doFlush();
1263
+ } else {
1264
+ schedule();
1265
+ }
1266
+ },
1267
+ async flush() {
1268
+ if (timer) clearTimeout(timer);
1269
+ await doFlush();
1270
+ },
1271
+ async close() {
1272
+ await this.flush?.();
1273
+ }
1274
+ };
1275
+ }
1276
+
1277
+ // src/transports/otel.ts
1278
+ var OTEL_SEVERITY_MAP = {
1279
+ TRACE: { number: 1, text: "TRACE" },
1280
+ DEBUG: { number: 5, text: "DEBUG" },
1281
+ INFO: { number: 9, text: "INFO" },
1282
+ WARN: { number: 13, text: "WARN" },
1283
+ ERROR: { number: 17, text: "ERROR" },
1284
+ FATAL: { number: 21, text: "FATAL" }
1285
+ };
1286
+ function otelTransport(options) {
1287
+ const { endpoint, serviceName, level, resource = {} } = options;
1288
+ const batchSize = options.batchSize ?? 20;
1289
+ const interval = options.interval ?? 5e3;
1290
+ const url = `${endpoint.replace(/\/$/, "")}/v1/logs`;
1291
+ const headers = {
1292
+ "Content-Type": "application/json",
1293
+ ...options.headers
1294
+ };
1295
+ const resourceAttributes = [
1296
+ { key: "service.name", value: { stringValue: serviceName } },
1297
+ ...Object.entries(resource).map(([key, val]) => ({
1298
+ key,
1299
+ value: { stringValue: val }
1300
+ }))
1301
+ ];
1302
+ let buffer = [];
1303
+ let timer = null;
1304
+ function toOtlpLogRecord(entry) {
1305
+ const severity = OTEL_SEVERITY_MAP[entry.levelName] ?? OTEL_SEVERITY_MAP.INFO;
1306
+ const attributes = [];
1307
+ if (entry.meta && typeof entry.meta === "object") {
1308
+ for (const [key, val] of Object.entries(entry.meta)) {
1309
+ if (key === "traceId" || key === "spanId" || key === "traceFlags")
1310
+ continue;
1311
+ if (val !== void 0 && val !== null) {
1312
+ attributes.push({
1313
+ key,
1314
+ value: typeof val === "number" ? { intValue: val } : { stringValue: String(val) }
1315
+ });
1316
+ }
1317
+ }
1318
+ }
1319
+ if (entry.context) {
1320
+ for (const [key, val] of Object.entries(entry.context)) {
1321
+ if (val !== void 0 && val !== null) {
1322
+ attributes.push({
1323
+ key: `context.${key}`,
1324
+ value: { stringValue: String(val) }
1325
+ });
1326
+ }
1327
+ }
1328
+ }
1329
+ if (entry.error) {
1330
+ attributes.push({
1331
+ key: "error.message",
1332
+ value: { stringValue: entry.error.message }
1333
+ });
1334
+ if (entry.error.name) {
1335
+ attributes.push({
1336
+ key: "error.type",
1337
+ value: { stringValue: entry.error.name }
1338
+ });
1339
+ }
1340
+ if (entry.error.stack) {
1341
+ attributes.push({
1342
+ key: "error.stack",
1343
+ value: { stringValue: entry.error.stack }
1344
+ });
1345
+ }
1346
+ }
1347
+ const record = {
1348
+ timeUnixNano: String(entry.timestamp * 1e6),
1349
+ // ms → ns
1350
+ severityNumber: severity?.number,
1351
+ severityText: severity?.text,
1352
+ body: { stringValue: entry.message },
1353
+ attributes
1354
+ };
1355
+ const meta = entry.meta;
1356
+ if (meta?.traceId) {
1357
+ record.traceId = meta.traceId;
1358
+ }
1359
+ if (meta?.spanId) {
1360
+ record.spanId = meta.spanId;
1361
+ }
1362
+ if (meta?.traceFlags !== void 0) {
1363
+ record.flags = meta.traceFlags;
1364
+ }
1365
+ return record;
1366
+ }
1367
+ async function sendBatch(batch) {
1368
+ const payload = {
1369
+ resourceLogs: [
1370
+ {
1371
+ resource: { attributes: resourceAttributes },
1372
+ scopeLogs: [
1373
+ {
1374
+ scope: { name: "voltlog-io" },
1375
+ logRecords: batch.map(toOtlpLogRecord)
1376
+ }
1377
+ ]
1378
+ }
1379
+ ]
1380
+ };
1381
+ try {
1382
+ const response = await fetch(url, {
1383
+ method: "POST",
1384
+ headers,
1385
+ body: JSON.stringify(payload)
1386
+ });
1387
+ if (!response.ok) {
1388
+ console.error(
1389
+ `[voltlog] OTLP push failed: ${response.status} ${response.statusText}`
1390
+ );
1391
+ }
1392
+ } catch (err) {
1393
+ console.error("[voltlog] OTLP push failed", err);
1394
+ }
1395
+ }
1396
+ function flush() {
1397
+ if (buffer.length === 0) return;
1398
+ const batch = buffer;
1399
+ buffer = [];
1400
+ sendBatch(batch).catch(() => {
1401
+ });
1402
+ }
1403
+ function schedule() {
1404
+ if (!timer) {
1405
+ timer = setTimeout(() => {
1406
+ timer = null;
1407
+ flush();
1408
+ }, interval);
1409
+ }
1410
+ }
1411
+ return {
1412
+ name: "otel",
1413
+ level,
1414
+ write(entry) {
1415
+ buffer.push(entry);
1416
+ if (buffer.length >= batchSize) {
1417
+ if (timer) clearTimeout(timer);
1418
+ timer = null;
1419
+ flush();
1420
+ } else {
1421
+ schedule();
1422
+ }
1423
+ },
1424
+ async flush() {
1425
+ if (timer) clearTimeout(timer);
1426
+ timer = null;
1427
+ if (buffer.length === 0) return;
1428
+ const batch = buffer;
1429
+ buffer = [];
1430
+ await sendBatch(batch);
1431
+ },
1432
+ async close() {
1433
+ await this.flush?.();
1434
+ }
1435
+ };
1436
+ }
1437
+
1438
+ // src/transports/pretty.ts
1439
+ var RESET = "\x1B[0m";
1440
+ var DIM = "\x1B[2m";
1441
+ var BOLD = "\x1B[1m";
1442
+ var COLORS = {
1443
+ TRACE: "\x1B[90m",
1444
+ // gray
1445
+ DEBUG: "\x1B[36m",
1446
+ // cyan
1447
+ INFO: "\x1B[32m",
1448
+ // green
1449
+ WARN: "\x1B[33m",
1450
+ // yellow
1451
+ ERROR: "\x1B[31m",
1452
+ // red
1453
+ FATAL: "\x1B[35;1m"
1454
+ // bold magenta
1455
+ };
1456
+ var ICONS = {
1457
+ TRACE: "\u{1F50D}",
1458
+ DEBUG: "\u{1F41B}",
1459
+ INFO: "\u2139",
1460
+ WARN: "\u26A0",
1461
+ ERROR: "\u2716",
1462
+ FATAL: "\u{1F480}"
1463
+ };
1464
+ var EXCHANGE_ICONS = {
1465
+ CALL: "\u26A1",
1466
+ CALLRESULT: "\u2714",
1467
+ CALLERROR: "\u{1F6A8}"
1468
+ };
1469
+ var DIRECTION_ARROWS = {
1470
+ IN: "\u2192",
1471
+ OUT: "\u2190"
1472
+ };
1473
+ function prettyTransport(options = {}) {
1474
+ const showTimestamps = options.timestamps ?? true;
1475
+ const useColors = options.colors ?? true;
1476
+ const hideMeta = options.hideMeta ?? false;
1477
+ const prettyMeta = options.prettyMeta ?? false;
1478
+ function colorize(text, color) {
1479
+ return useColors ? `${color}${text}${RESET}` : text;
1480
+ }
1481
+ function formatExchange(entry) {
1482
+ const meta = entry.meta;
1483
+ if (!meta || !meta.action || !meta.messageType) return null;
1484
+ const icon = EXCHANGE_ICONS[meta.messageType] ?? "\u2022";
1485
+ const arrow = DIRECTION_ARROWS[meta.direction ?? "IN"] ?? "\u2192";
1486
+ const cpId = meta.chargePointId ?? "unknown";
1487
+ const action = meta.action;
1488
+ const msgType = meta.messageType;
1489
+ const dir = meta.direction ?? "";
1490
+ let line = `${icon} ${colorize(cpId, BOLD)} ${arrow} ${colorize(
1491
+ action,
1492
+ BOLD
1493
+ )} [${dir}] ${colorize(msgType, DIM)}`;
1494
+ if (meta.status || meta.latencyMs !== void 0) {
1495
+ const statusIcon = meta.messageType === "CALLERROR" ? "\u274C" : "\u2714";
1496
+ const status = meta.status ?? "";
1497
+ const latency = meta.latencyMs !== void 0 ? `(${meta.latencyMs}ms)` : "";
1498
+ line += `
1499
+ ${statusIcon} ${status} ${colorize(latency, DIM)}`;
1500
+ }
1501
+ return line;
1502
+ }
1503
+ function formatStandard(entry) {
1504
+ const icon = ICONS[entry.levelName] ?? "\u2022";
1505
+ const levelColor = COLORS[entry.levelName] ?? "";
1506
+ const level = colorize(entry.levelName.padEnd(5), levelColor);
1507
+ const ts = showTimestamps ? `${colorize(new Date(entry.timestamp).toISOString(), DIM)} ` : "";
1508
+ let line = `${icon} ${ts}${level} ${entry.message}`;
1509
+ if (entry.context && Object.keys(entry.context).length > 0) {
1510
+ const kvStr = Object.entries(entry.context).map(
1511
+ ([k, v]) => `${k}:${typeof v === "string" ? v : JSON.stringify(v)}`
1512
+ ).join(" ");
1513
+ line += ` ${colorize(kvStr, DIM)}`;
1514
+ }
1515
+ if (!hideMeta && entry.meta && Object.keys(entry.meta).length > 0) {
1516
+ if (prettyMeta) {
1517
+ const metaEntries = Object.entries(
1518
+ entry.meta
1519
+ );
1520
+ const parts = metaEntries.map(([key, value]) => {
1521
+ const valStr = typeof value === "string" ? value : JSON.stringify(value);
1522
+ return `${colorize(`${key}:`, DIM)}${valStr}`;
1523
+ });
1524
+ line += ` ${parts.join(" ")}`;
1525
+ } else {
1526
+ const kvStr = Object.entries(entry.meta).map(
1527
+ ([k, v]) => `${k}:${typeof v === "string" ? v : JSON.stringify(v)}`
1528
+ ).join(" ");
1529
+ line += ` ${colorize(kvStr, DIM)}`;
1530
+ }
1531
+ }
1532
+ if (entry.error) {
1533
+ line += `
1534
+ ${colorize(
1535
+ `${entry.error.name ?? "Error"}: ${entry.error.message}`,
1536
+ COLORS.ERROR ?? ""
1537
+ )}`;
1538
+ if (entry.error.stack) {
1539
+ line += `
1540
+ ${colorize(entry.error.stack, DIM)}`;
1541
+ }
1542
+ }
1543
+ return line;
1544
+ }
1545
+ return {
1546
+ name: "pretty",
1547
+ level: options.level,
1548
+ write(entry) {
1549
+ const exchangeOutput = formatExchange(entry);
1550
+ if (exchangeOutput) {
1551
+ console.log(exchangeOutput);
1552
+ return;
1553
+ }
1554
+ const output = formatStandard(entry);
1555
+ if (entry.level >= LogLevel.ERROR) {
1556
+ console.error(output);
1557
+ } else if (entry.level >= LogLevel.WARN) {
1558
+ console.warn(output);
1559
+ } else {
1560
+ console.log(output);
1561
+ }
1562
+ }
1563
+ };
1564
+ }
1565
+
210
1566
  // src/transports/redis.ts
211
1567
  function redisTransport(options) {
212
1568
  const { client, streamKey = "logs", maxLen, level } = options;
@@ -246,6 +1602,283 @@ function redisTransport(options) {
246
1602
  }
247
1603
  };
248
1604
  }
1605
+
1606
+ // src/transports/ring-buffer.ts
1607
+ function ringBufferTransport(options = {}) {
1608
+ const maxSize = options.maxSize ?? 1e3;
1609
+ const buffer = [];
1610
+ let head = 0;
1611
+ let count = 0;
1612
+ return {
1613
+ name: "ring-buffer",
1614
+ level: options.level,
1615
+ write(entry) {
1616
+ if (count < maxSize) {
1617
+ buffer.push(entry);
1618
+ count++;
1619
+ } else {
1620
+ buffer[head] = entry;
1621
+ }
1622
+ head = (head + 1) % maxSize;
1623
+ },
1624
+ getEntries(query) {
1625
+ let entries;
1626
+ if (count < maxSize) {
1627
+ entries = buffer.slice();
1628
+ } else {
1629
+ entries = [...buffer.slice(head), ...buffer.slice(0, head)];
1630
+ }
1631
+ if (query?.level) {
1632
+ const minLevel = resolveLevel(query.level);
1633
+ entries = entries.filter((e) => e.level >= minLevel);
1634
+ }
1635
+ if (query?.since) {
1636
+ const since = query.since;
1637
+ entries = entries.filter((e) => e.timestamp >= since);
1638
+ }
1639
+ if (query?.limit) {
1640
+ entries = entries.slice(-query.limit);
1641
+ }
1642
+ return entries;
1643
+ },
1644
+ clear() {
1645
+ buffer.length = 0;
1646
+ head = 0;
1647
+ count = 0;
1648
+ },
1649
+ get size() {
1650
+ return count;
1651
+ }
1652
+ };
1653
+ }
1654
+
1655
+ // src/transports/sentry.ts
1656
+ function sentryTransport(options) {
1657
+ const { sentry } = options;
1658
+ const errorLevelValue = resolveLevel(options.errorLevel ?? "ERROR");
1659
+ const breadcrumbLevelValue = resolveLevel(options.breadcrumbLevel ?? "INFO");
1660
+ return {
1661
+ name: "sentry",
1662
+ write(entry) {
1663
+ if (entry.level >= errorLevelValue) {
1664
+ if (entry.error) {
1665
+ sentry.captureException(entry.error, {
1666
+ extra: {
1667
+ ...entry.meta,
1668
+ context: entry.context
1669
+ },
1670
+ level: "error"
1671
+ });
1672
+ } else {
1673
+ sentry.captureMessage(entry.message, "error");
1674
+ }
1675
+ }
1676
+ if (entry.level >= breadcrumbLevelValue) {
1677
+ sentry.addBreadcrumb({
1678
+ category: "log",
1679
+ message: entry.message,
1680
+ level: mapLevelToSentry(entry.level),
1681
+ data: { ...entry.meta, ...entry.context },
1682
+ timestamp: entry.timestamp / 1e3
1683
+ });
1684
+ }
1685
+ }
1686
+ };
1687
+ }
1688
+ function mapLevelToSentry(level) {
1689
+ if (level >= 60) return "fatal";
1690
+ if (level >= 50) return "error";
1691
+ if (level >= 40) return "warning";
1692
+ if (level >= 30) return "info";
1693
+ return "debug";
1694
+ }
1695
+
1696
+ // src/transports/slack.ts
1697
+ function slackTransport(options) {
1698
+ const { webhookUrl, username, iconEmoji, level } = options;
1699
+ return {
1700
+ name: "slack",
1701
+ level: level ?? "ERROR",
1702
+ // Default to ERROR to prevent spamming
1703
+ async write(entry) {
1704
+ try {
1705
+ const payload = formatSlackMessage(entry, username, iconEmoji);
1706
+ const response = await fetch(webhookUrl, {
1707
+ method: "POST",
1708
+ headers: { "Content-Type": "application/json" },
1709
+ body: JSON.stringify(payload)
1710
+ });
1711
+ if (!response.ok) {
1712
+ }
1713
+ } catch (_err) {
1714
+ }
1715
+ }
1716
+ };
1717
+ }
1718
+ function formatSlackMessage(entry, username, icon_emoji) {
1719
+ const levelEmoji = getLevelEmoji(entry.level);
1720
+ const color = getLevelColor2(entry.level);
1721
+ const blocks = [
1722
+ {
1723
+ type: "header",
1724
+ text: {
1725
+ type: "plain_text",
1726
+ text: `${levelEmoji} ${entry.levelName}: ${entry.message}`,
1727
+ emoji: true
1728
+ }
1729
+ },
1730
+ {
1731
+ type: "context",
1732
+ elements: [
1733
+ {
1734
+ type: "mrkdwn",
1735
+ text: `*Time:* ${new Date(entry.timestamp).toISOString()}`
1736
+ },
1737
+ {
1738
+ type: "mrkdwn",
1739
+ text: `*ID:* \`${entry.id}\``
1740
+ }
1741
+ ]
1742
+ }
1743
+ ];
1744
+ if (entry.correlationId) {
1745
+ blocks[1].elements.push({
1746
+ type: "mrkdwn",
1747
+ text: `*Trace:* \`${entry.correlationId}\``
1748
+ });
1749
+ }
1750
+ if (Object.keys(entry.meta).length > 0) {
1751
+ blocks.push({
1752
+ type: "section",
1753
+ text: {
1754
+ type: "mrkdwn",
1755
+ text: `*Metadata:*
1756
+ \`\`\`${JSON.stringify(entry.meta, null, 2)}\`\`\``,
1757
+ emoji: true
1758
+ }
1759
+ });
1760
+ }
1761
+ if (entry.error?.stack) {
1762
+ blocks.push({
1763
+ type: "section",
1764
+ text: {
1765
+ type: "mrkdwn",
1766
+ text: `*Error Stack:*
1767
+ \`\`\`${entry.error.stack}\`\`\``,
1768
+ emoji: true
1769
+ }
1770
+ });
1771
+ }
1772
+ return {
1773
+ username,
1774
+ icon_emoji,
1775
+ attachments: [
1776
+ {
1777
+ color,
1778
+ blocks
1779
+ }
1780
+ ]
1781
+ };
1782
+ }
1783
+ function getLevelEmoji(level) {
1784
+ if (level >= 60) return "\u{1F525}";
1785
+ if (level >= 50) return "\u{1F6A8}";
1786
+ if (level >= 40) return "\u26A0\uFE0F";
1787
+ if (level >= 30) return "\u2139\uFE0F";
1788
+ if (level >= 20) return "\u{1F41B}";
1789
+ return "\u{1F50D}";
1790
+ }
1791
+ function getLevelColor2(level) {
1792
+ if (level >= 60) return "#ff0000";
1793
+ if (level >= 50) return "#ff4444";
1794
+ if (level >= 40) return "#ffbb33";
1795
+ if (level >= 30) return "#33b5e5";
1796
+ if (level >= 20) return "#99cc00";
1797
+ return "#aa66cc";
1798
+ }
1799
+
1800
+ // src/transports/webhook.ts
1801
+ function webhookTransport(options) {
1802
+ const {
1803
+ url,
1804
+ method = "POST",
1805
+ headers = {},
1806
+ batchSize = 1,
1807
+ flushIntervalMs = 5e3,
1808
+ retry = false,
1809
+ maxRetries = 3
1810
+ } = options;
1811
+ const serialize = options.serializer ?? ((entries) => JSON.stringify({
1812
+ entries,
1813
+ count: entries.length,
1814
+ timestamp: Date.now()
1815
+ }));
1816
+ let buffer = [];
1817
+ let flushTimer = null;
1818
+ async function sendBatch(entries, attempt = 0) {
1819
+ try {
1820
+ const response = await fetch(url, {
1821
+ method,
1822
+ headers: {
1823
+ "Content-Type": "application/json",
1824
+ ...headers
1825
+ },
1826
+ body: serialize(entries)
1827
+ });
1828
+ if (!response.ok && retry && attempt < maxRetries) {
1829
+ const delay = Math.min(1e3 * 2 ** attempt, 3e4);
1830
+ await new Promise((r) => setTimeout(r, delay));
1831
+ return sendBatch(entries, attempt + 1);
1832
+ }
1833
+ } catch {
1834
+ if (retry && attempt < maxRetries) {
1835
+ const delay = Math.min(1e3 * 2 ** attempt, 3e4);
1836
+ await new Promise((r) => setTimeout(r, delay));
1837
+ return sendBatch(entries, attempt + 1);
1838
+ }
1839
+ }
1840
+ }
1841
+ function scheduleFlush() {
1842
+ if (flushTimer) return;
1843
+ flushTimer = setTimeout(() => {
1844
+ flushTimer = null;
1845
+ doFlush();
1846
+ }, flushIntervalMs);
1847
+ }
1848
+ function doFlush() {
1849
+ if (buffer.length === 0) return;
1850
+ const batch = buffer;
1851
+ buffer = [];
1852
+ sendBatch(batch).catch(() => {
1853
+ });
1854
+ }
1855
+ return {
1856
+ name: "webhook",
1857
+ level: options.level,
1858
+ write(entry) {
1859
+ buffer.push(entry);
1860
+ if (buffer.length >= batchSize) {
1861
+ doFlush();
1862
+ } else {
1863
+ scheduleFlush();
1864
+ }
1865
+ },
1866
+ async flush() {
1867
+ if (flushTimer) {
1868
+ clearTimeout(flushTimer);
1869
+ flushTimer = null;
1870
+ }
1871
+ if (buffer.length > 0) {
1872
+ const batch = buffer;
1873
+ buffer = [];
1874
+ await sendBatch(batch);
1875
+ }
1876
+ },
1877
+ async close() {
1878
+ await this.flush?.();
1879
+ }
1880
+ };
1881
+ }
249
1882
  export {
250
1883
  LogLevel,
251
1884
  LogLevelNameMap,
@@ -254,7 +1887,6 @@ export {
254
1887
  alertMiddleware,
255
1888
  asyncContextMiddleware,
256
1889
  batchTransport,
257
- browserJsonStreamTransport,
258
1890
  consoleTransport,
259
1891
  correlationIdMiddleware,
260
1892
  createHttpLogger,