@logbrew/sdk 0.1.3 → 0.1.5

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/index.cjs CHANGED
@@ -1,1337 +1,4 @@
1
- const SEVERITY_ALIASES = new Map([
2
- ["trace", "info"],
3
- ["debug", "info"],
4
- ["info", "info"],
5
- ["warn", "warning"],
6
- ["warning", "warning"],
7
- ["error", "error"],
8
- ["fatal", "critical"],
9
- ["critical", "critical"]
10
- ]);
11
- const SEVERITY_VALUES = new Set(SEVERITY_ALIASES.keys());
12
- const SPAN_STATUSES = new Set(["ok", "error"]);
13
- const ACTION_STATUSES = new Set(["queued", "running", "success", "failure"]);
14
- const METRIC_KINDS = new Set(["counter", "gauge", "histogram"]);
15
- const NON_NEGATIVE_METRIC_KINDS = new Set(["counter", "histogram"]);
16
- const METRIC_TEMPORALITIES_BY_KIND = new Map([
17
- ["counter", new Set(["delta", "cumulative"])],
18
- ["gauge", new Set(["instant"])],
19
- ["histogram", new Set(["delta", "cumulative"])]
20
- ]);
21
- const CONSOLE_METHODS = new Set(["debug", "info", "log", "warn", "error"]);
22
- const DEFAULT_CONSOLE_LEVELS = ["debug", "info", "log", "warn", "error"];
23
- const PINO_HOST_FIELD = ["host", "name"].join("");
24
- const PINO_RESERVED_FIELDS = new Set(["level", "time", "timestamp", "msg", "message", "err", "error", "pid", PINO_HOST_FIELD, "v"]);
25
- const WINSTON_RESERVED_FIELDS = new Set(["level", "message", "timestamp", "time", "err", "error", "stack"]);
26
- const TRACEPARENT_PATTERN = /^([0-9a-fA-F]{2})-([0-9a-fA-F]{32})-([0-9a-fA-F]{16})-([0-9a-fA-F]{2})$/u;
27
- const ZERO_TRACE_ID = "00000000000000000000000000000000";
28
- const ZERO_SPAN_ID = "0000000000000000";
1
+ const core = require("./core.cjs");
2
+ const winston = require("./winston.cjs");
29
3
 
30
- class SdkError extends Error {
31
- constructor(code, message) {
32
- super(message);
33
- this.name = "SdkError";
34
- this.code = code;
35
- }
36
- }
37
-
38
- class TransportError extends Error {
39
- constructor(code, message, retryable = false) {
40
- super(message);
41
- this.name = "TransportError";
42
- this.code = code;
43
- this.retryable = retryable;
44
- }
45
-
46
- static network(message) {
47
- return new TransportError("network_failure", message, true);
48
- }
49
- }
50
-
51
- class RecordingTransport {
52
- constructor(scriptedResponses = [{ statusCode: 202 }]) {
53
- this.scriptedResponses = [...scriptedResponses];
54
- this.sentBodies = [];
55
- }
56
-
57
- static alwaysAccept() {
58
- return new RecordingTransport([{ statusCode: 202 }]);
59
- }
60
-
61
- lastBody() {
62
- return this.sentBodies.at(-1) ?? null;
63
- }
64
-
65
- async send(apiKey, body) {
66
- requireNonEmpty("apiKey", apiKey);
67
- this.sentBodies.push(body);
68
-
69
- const next = this.scriptedResponses.length > 0
70
- ? this.scriptedResponses.shift()
71
- : { statusCode: 202 };
72
-
73
- if (next instanceof Error) {
74
- throw next;
75
- }
76
-
77
- return { statusCode: next.statusCode, attempts: 1 };
78
- }
79
- }
80
-
81
- class LogBrewClient {
82
- static create({ apiKey, sdkName, sdkVersion, maxRetries = 2, eventFilter }) {
83
- requireNonEmpty("apiKey", apiKey);
84
- requireNonEmpty("sdkName", sdkName);
85
- requireNonEmpty("sdkVersion", sdkVersion);
86
- if (eventFilter !== undefined && typeof eventFilter !== "function") {
87
- throw new SdkError("validation_error", "eventFilter must be a function");
88
- }
89
-
90
- return new LogBrewClient({
91
- apiKey,
92
- eventFilter,
93
- sdk: {
94
- name: sdkName,
95
- language: "javascript",
96
- version: sdkVersion
97
- },
98
- maxRetries
99
- });
100
- }
101
-
102
- constructor({ apiKey, sdk, maxRetries, eventFilter }) {
103
- this.apiKey = apiKey;
104
- this.eventFilter = eventFilter;
105
- this.sdk = sdk;
106
- this.maxRetries = maxRetries;
107
- this.events = [];
108
- this.closed = false;
109
- }
110
-
111
- pendingEvents() {
112
- return this.events.length;
113
- }
114
-
115
- previewJson() {
116
- return JSON.stringify({ sdk: this.sdk, events: this.events }, null, 2);
117
- }
118
-
119
- release(id, timestamp, attributes) {
120
- this.#pushEvent("release", id, timestamp, validateRelease(attributes));
121
- }
122
-
123
- environment(id, timestamp, attributes) {
124
- this.#pushEvent("environment", id, timestamp, validateEnvironment(attributes));
125
- }
126
-
127
- issue(id, timestamp, attributes) {
128
- this.#pushEvent("issue", id, timestamp, validateIssue(attributes));
129
- }
130
-
131
- log(id, timestamp, attributes) {
132
- this.#pushEvent("log", id, timestamp, validateLog(attributes));
133
- }
134
-
135
- span(id, timestamp, attributes) {
136
- this.#pushEvent("span", id, timestamp, validateSpan(attributes));
137
- }
138
-
139
- action(id, timestamp, attributes) {
140
- this.#pushEvent("action", id, timestamp, validateAction(attributes));
141
- }
142
-
143
- metric(id, timestamp, attributes) {
144
- this.#pushEvent("metric", id, timestamp, validateMetric(attributes));
145
- }
146
-
147
- async flush(transport) {
148
- if (this.closed) {
149
- throw new SdkError("shutdown_error", "client is already shut down");
150
- }
151
- return this.#flushInternal(transport);
152
- }
153
-
154
- async shutdown(transport) {
155
- if (this.closed) {
156
- throw new SdkError("shutdown_error", "client is already shut down");
157
- }
158
- const response = await this.#flushInternal(transport);
159
- this.closed = true;
160
- return response;
161
- }
162
-
163
- #pushEvent(eventType, id, timestamp, attributes) {
164
- if (this.closed) {
165
- throw new SdkError("shutdown_error", "client is already shut down");
166
- }
167
- requireNonEmpty("event id", id);
168
- requireTimestamp(timestamp);
169
- const event = { type: eventType, id, timestamp, attributes };
170
- if (this.eventFilter && this.eventFilter(cloneEvent(event)) === false) {
171
- return;
172
- }
173
- this.events.push(event);
174
- }
175
-
176
- async #flushInternal(transport) {
177
- if (this.events.length === 0) {
178
- return { statusCode: 204, attempts: 0 };
179
- }
180
-
181
- const body = this.previewJson();
182
- const maxAttempts = this.maxRetries + 1;
183
- let attempts = 0;
184
-
185
- while (attempts < maxAttempts) {
186
- attempts += 1;
187
- try {
188
- const response = await transport.send(this.apiKey, body);
189
- if (response.statusCode === 401) {
190
- throw new SdkError("unauthenticated", "transport rejected the API key");
191
- }
192
- if (response.statusCode >= 200 && response.statusCode < 300) {
193
- this.events = [];
194
- return { statusCode: response.statusCode, attempts };
195
- }
196
- if (response.statusCode >= 500 && attempts < maxAttempts) {
197
- continue;
198
- }
199
- throw new SdkError("transport_error", `unexpected transport status ${response.statusCode}`);
200
- } catch (error) {
201
- if (error instanceof SdkError) {
202
- throw error;
203
- }
204
- if (error instanceof TransportError && error.retryable && attempts < maxAttempts) {
205
- continue;
206
- }
207
- if (error instanceof TransportError) {
208
- throw new SdkError(error.code, error.message);
209
- }
210
- throw error;
211
- }
212
- }
213
-
214
- throw new SdkError("transport_error", "exhausted retries");
215
- }
216
- }
217
-
218
- function installLogBrewConsoleCapture(config) {
219
- if (!config || typeof config !== "object") {
220
- throw new SdkError("validation_error", "console capture config must be an object");
221
- }
222
-
223
- const client = config.client;
224
- if (!(client instanceof LogBrewClient)) {
225
- throw new SdkError("validation_error", "console capture client must be a LogBrewClient");
226
- }
227
-
228
- const targetConsole = config.console ?? globalThis.console;
229
- if (!targetConsole || typeof targetConsole !== "object") {
230
- throw new SdkError("validation_error", "console capture target must be an object");
231
- }
232
-
233
- const transport = config.transport;
234
- const flushOnCapture = config.flushOnCapture === true;
235
- const includeErrorStack = config.includeErrorStack === true;
236
- const logger = config.logger ?? "console";
237
- const metadata = compactMetadata(config.metadata);
238
- const timestamp = typeof config.timestamp === "function"
239
- ? config.timestamp
240
- : () => new Date().toISOString();
241
- const eventIdPrefix = config.eventIdPrefix ?? "console";
242
- const onError = typeof config.onError === "function" ? config.onError : () => {};
243
- const levels = normalizeConsoleLevels(config.levels);
244
- const originals = new Map();
245
- const state = {
246
- installed: true,
247
- captured: 0,
248
- pendingFlush: Promise.resolve(null)
249
- };
250
-
251
- for (const method of levels) {
252
- const original = targetConsole[method];
253
- if (typeof original !== "function") {
254
- continue;
255
- }
256
- originals.set(method, original);
257
- targetConsole[method] = createConsoleCaptureMethod({
258
- client,
259
- eventIdPrefix,
260
- flushOnCapture,
261
- includeErrorStack,
262
- logger,
263
- metadata,
264
- method,
265
- onError,
266
- original,
267
- state,
268
- timestamp,
269
- transport
270
- });
271
- }
272
-
273
- return {
274
- async flush() {
275
- if (transport && client.pendingEvents() > 0) {
276
- state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
277
- onError(error);
278
- return null;
279
- });
280
- }
281
- return state.pendingFlush;
282
- },
283
- uninstall() {
284
- if (!state.installed) {
285
- return;
286
- }
287
- state.installed = false;
288
- for (const [method, original] of originals.entries()) {
289
- targetConsole[method] = original;
290
- }
291
- originals.clear();
292
- }
293
- };
294
- }
295
-
296
- function createConsoleCaptureMethod(config) {
297
- return function logBrewConsoleMethod(...args) {
298
- config.original.apply(this, args);
299
- if (!config.state.installed) {
300
- return;
301
- }
302
- try {
303
- config.state.captured += 1;
304
- config.client.log(
305
- `${config.eventIdPrefix}_${config.state.captured}`,
306
- config.timestamp(),
307
- logAttributesFromConsoleArgs(config.method, args, {
308
- includeErrorStack: config.includeErrorStack,
309
- logger: config.logger,
310
- metadata: config.metadata
311
- })
312
- );
313
- if (config.flushOnCapture && config.transport) {
314
- config.state.pendingFlush = Promise.resolve(config.client.flush(config.transport)).catch((error) => {
315
- config.onError(error);
316
- return null;
317
- });
318
- }
319
- } catch (error) {
320
- config.onError(error);
321
- }
322
- };
323
- }
324
-
325
- function logAttributesFromConsoleArgs(method, args, options = {}) {
326
- const logLevel = logbrewLevelFromConsoleMethod(method);
327
- const includeErrorStack = options.includeErrorStack === true;
328
- const message = consoleMessage(args, includeErrorStack);
329
- const metadata = {
330
- ...compactMetadata(options.metadata),
331
- consoleMethod: method,
332
- argumentCount: Array.isArray(args) ? args.length : 0
333
- };
334
- for (const value of Array.isArray(args) ? args : []) {
335
- if (value instanceof Error) {
336
- metadata.errorName = value.name || "Error";
337
- if (value.message) {
338
- metadata.errorMessage = value.message;
339
- }
340
- if (includeErrorStack && value.stack) {
341
- metadata.errorStack = value.stack;
342
- }
343
- break;
344
- }
345
- }
346
-
347
- return {
348
- message,
349
- level: logLevel,
350
- ...(options.logger ? { logger: options.logger } : {}),
351
- metadata
352
- };
353
- }
354
-
355
- function logbrewLevelFromConsoleMethod(method) {
356
- switch (method) {
357
- case "debug":
358
- return "info";
359
- case "warn":
360
- return "warning";
361
- case "error":
362
- return "error";
363
- case "info":
364
- case "log":
365
- return "info";
366
- default:
367
- throw new SdkError("validation_error", `console method must be one of: ${Array.from(CONSOLE_METHODS).join(", ")}`);
368
- }
369
- }
370
-
371
- function createProductActionAttributes(action, options = {}) {
372
- const details = productActionDetails(action);
373
- return {
374
- name: details.name,
375
- status: details.status,
376
- metadata: compactMetadata({
377
- source: "product.action",
378
- ...compactMetadata(options.metadata),
379
- ...compactMetadata(details.metadata),
380
- routeTemplate: sanitizeRouteTemplate(details.routeTemplate),
381
- sessionId: stringOrUndefined(details.sessionId),
382
- traceId: stringOrUndefined(details.traceId),
383
- screen: stringOrUndefined(details.screen),
384
- funnel: stringOrUndefined(details.funnel),
385
- step: stringOrUndefined(details.step)
386
- })
387
- };
388
- }
389
-
390
- function createNetworkMilestoneAttributes(request, options = {}) {
391
- const details = networkMilestoneDetails(request);
392
- return {
393
- name: details.name,
394
- status: details.status,
395
- metadata: compactMetadata({
396
- source: "network.milestone",
397
- ...compactMetadata(options.metadata),
398
- ...compactMetadata(details.metadata),
399
- routeTemplate: details.routeTemplate,
400
- method: details.method,
401
- statusCode: details.statusCode,
402
- durationMs: details.durationMs,
403
- sessionId: stringOrUndefined(details.sessionId),
404
- traceId: stringOrUndefined(details.traceId)
405
- })
406
- };
407
- }
408
-
409
- function parseTraceparent(traceparent) {
410
- if (typeof traceparent !== "string" || traceparent.trim() === "") {
411
- throw new SdkError("validation_error", "traceparent must be non-empty");
412
- }
413
-
414
- const match = TRACEPARENT_PATTERN.exec(traceparent.trim());
415
- if (!match) {
416
- throw new SdkError("validation_error", "traceparent must use W3C version-traceId-parentSpanId-traceFlags format");
417
- }
418
-
419
- const version = match[1].toLowerCase();
420
- const traceId = match[2].toLowerCase();
421
- const parentSpanId = match[3].toLowerCase();
422
- const traceFlags = match[4].toLowerCase();
423
- if (version === "ff") {
424
- throw new SdkError("validation_error", "traceparent version ff is not allowed");
425
- }
426
- if (traceId === ZERO_TRACE_ID) {
427
- throw new SdkError("validation_error", "traceparent traceId must not be all zeros");
428
- }
429
- if (parentSpanId === ZERO_SPAN_ID) {
430
- throw new SdkError("validation_error", "traceparent parentSpanId must not be all zeros");
431
- }
432
-
433
- return {
434
- version,
435
- traceId,
436
- parentSpanId,
437
- traceFlags,
438
- sampled: (Number.parseInt(traceFlags, 16) & 1) === 1
439
- };
440
- }
441
-
442
- function createTraceparent({ traceId, spanId, traceFlags = "01" }) {
443
- requireTraceId(traceId);
444
- requireSpanId("spanId", spanId);
445
- requireTraceFlags(traceFlags);
446
- return `00-${traceId.toLowerCase()}-${spanId.toLowerCase()}-${traceFlags.toLowerCase()}`;
447
- }
448
-
449
- function createTraceparentHeaders(input) {
450
- return { traceparent: createTraceparent(input) };
451
- }
452
-
453
- function spanAttributesFromTraceparent(traceparent, attributes) {
454
- if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") {
455
- throw new SdkError("validation_error", "span attributes must be an object");
456
- }
457
- const context = parseTraceparent(traceparent);
458
- requireNonEmpty("span name", attributes.name);
459
- requireSpanId("spanId", attributes.spanId);
460
- requireAllowedValue("span status", attributes.status, SPAN_STATUSES);
461
- if (attributes.durationMs !== undefined) {
462
- if (typeof attributes.durationMs !== "number" || Number.isNaN(attributes.durationMs) || attributes.durationMs < 0) {
463
- throw new SdkError("validation_error", "span durationMs must be non-negative");
464
- }
465
- }
466
-
467
- return {
468
- name: attributes.name,
469
- traceId: context.traceId,
470
- spanId: attributes.spanId.toLowerCase(),
471
- parentSpanId: context.parentSpanId,
472
- status: attributes.status,
473
- ...(attributes.durationMs !== undefined ? { durationMs: attributes.durationMs } : {}),
474
- ...(attributes.metadata !== undefined ? { metadata: compactMetadata(attributes.metadata) } : {})
475
- };
476
- }
477
-
478
- function createLogBrewPinoDestination(config) {
479
- if (!config || typeof config !== "object") {
480
- throw new SdkError("validation_error", "Pino destination config must be an object");
481
- }
482
-
483
- const client = config.client;
484
- if (!(client instanceof LogBrewClient)) {
485
- throw new SdkError("validation_error", "Pino destination client must be a LogBrewClient");
486
- }
487
-
488
- const transport = config.transport;
489
- const flushOnWrite = config.flushOnWrite === true;
490
- const includeErrorStack = config.includeErrorStack === true;
491
- const logger = config.logger ?? "pino";
492
- const metadata = compactMetadata(config.metadata);
493
- const timestamp = typeof config.timestamp === "function"
494
- ? config.timestamp
495
- : () => new Date().toISOString();
496
- const eventIdPrefix = config.eventIdPrefix ?? "pino";
497
- const onError = typeof config.onError === "function" ? config.onError : () => {};
498
- const state = {
499
- captured: 0,
500
- pendingFlush: Promise.resolve(null)
501
- };
502
-
503
- return {
504
- write(chunk) {
505
- const lines = String(chunk).split(/\r?\n/u).filter((line) => line.trim() !== "");
506
- for (const line of lines) {
507
- try {
508
- const record = JSON.parse(line);
509
- state.captured += 1;
510
- client.log(
511
- `${eventIdPrefix}_${state.captured}`,
512
- timestampFromPinoRecord(record, timestamp),
513
- logAttributesFromPinoRecord(record, {
514
- includeErrorStack,
515
- logger,
516
- metadata
517
- })
518
- );
519
- if (flushOnWrite && transport) {
520
- state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
521
- onError(error);
522
- return null;
523
- });
524
- }
525
- } catch (error) {
526
- onError(error);
527
- }
528
- }
529
- return true;
530
- },
531
- async flush() {
532
- if (transport && client.pendingEvents() > 0) {
533
- state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
534
- onError(error);
535
- return null;
536
- });
537
- }
538
- return state.pendingFlush;
539
- },
540
- end() {
541
- return this.flush();
542
- }
543
- };
544
- }
545
-
546
- function logAttributesFromPinoRecord(record, options = {}) {
547
- if (!record || Array.isArray(record) || typeof record !== "object") {
548
- throw new SdkError("validation_error", "Pino record must be an object");
549
- }
550
-
551
- const level = logbrewLevelFromPinoLevel(record.level);
552
- const metadata = {
553
- ...compactMetadata(options.metadata),
554
- pinoLevel: pinoLevelLabel(record.level),
555
- ...pinoContextMetadata(record)
556
- };
557
- if (typeof record.level === "number" && Number.isFinite(record.level)) {
558
- metadata.pinoLevelNumber = record.level;
559
- }
560
- addPinoErrorMetadata(metadata, record.err ?? record.error, options.includeErrorStack === true);
561
-
562
- return {
563
- message: pinoMessage(record),
564
- level,
565
- ...(options.logger ? { logger: options.logger } : {}),
566
- metadata
567
- };
568
- }
569
-
570
- function createLogBrewWinstonTransport(config) {
571
- if (!config || typeof config !== "object") {
572
- throw new SdkError("validation_error", "Winston transport config must be an object");
573
- }
574
-
575
- const client = config.client;
576
- if (!(client instanceof LogBrewClient)) {
577
- throw new SdkError("validation_error", "Winston transport client must be a LogBrewClient");
578
- }
579
-
580
- const transport = config.transport;
581
- const flushOnWrite = config.flushOnWrite === true;
582
- const includeErrorStack = config.includeErrorStack === true;
583
- const logger = config.logger ?? "winston";
584
- const metadata = compactMetadata(config.metadata);
585
- const timestamp = typeof config.timestamp === "function"
586
- ? config.timestamp
587
- : () => new Date().toISOString();
588
- const eventIdPrefix = config.eventIdPrefix ?? "winston";
589
- const onError = typeof config.onError === "function" ? config.onError : () => {};
590
- const state = {
591
- captured: 0,
592
- pendingFlush: Promise.resolve(null)
593
- };
594
- const { Writable } = require("node:stream");
595
-
596
- const winstonTransport = new Writable({
597
- objectMode: true,
598
- write(info, _encoding, callback) {
599
- try {
600
- captureWinstonInfo({
601
- client,
602
- eventIdPrefix,
603
- flushOnWrite,
604
- includeErrorStack,
605
- info,
606
- logger,
607
- metadata,
608
- onError,
609
- state,
610
- timestamp,
611
- transport
612
- });
613
- } catch (error) {
614
- onError(error);
615
- } finally {
616
- callback();
617
- }
618
- }
619
- });
620
-
621
- winstonTransport.log = function log(info, callback) {
622
- this.write(info);
623
- if (typeof callback === "function") {
624
- callback();
625
- }
626
- };
627
- winstonTransport.flush = async () => {
628
- if (transport && client.pendingEvents() > 0) {
629
- state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
630
- onError(error);
631
- return null;
632
- });
633
- }
634
- return state.pendingFlush;
635
- };
636
- if (typeof config.level === "string" && config.level.trim() !== "") {
637
- winstonTransport.level = config.level;
638
- }
639
- if (config.name !== undefined) {
640
- winstonTransport.name = String(config.name);
641
- }
642
- if (config.silent === true) {
643
- winstonTransport.silent = true;
644
- }
645
- if (config.handleExceptions === true) {
646
- winstonTransport.handleExceptions = true;
647
- }
648
- if (config.handleRejections === true) {
649
- winstonTransport.handleRejections = true;
650
- }
651
-
652
- return winstonTransport;
653
- }
654
-
655
- function captureWinstonInfo(config) {
656
- if (config.info?.silent === true) {
657
- return;
658
- }
659
- config.state.captured += 1;
660
- config.client.log(
661
- `${config.eventIdPrefix}_${config.state.captured}`,
662
- timestampFromWinstonInfo(config.info, config.timestamp),
663
- logAttributesFromWinstonInfo(config.info, {
664
- includeErrorStack: config.includeErrorStack,
665
- logger: config.logger,
666
- metadata: config.metadata
667
- })
668
- );
669
- if (config.flushOnWrite && config.transport) {
670
- config.state.pendingFlush = Promise.resolve(config.client.flush(config.transport)).catch((error) => {
671
- config.onError(error);
672
- return null;
673
- });
674
- }
675
- }
676
-
677
- function logAttributesFromWinstonInfo(info, options = {}) {
678
- if (!info || Array.isArray(info) || typeof info !== "object") {
679
- throw new SdkError("validation_error", "Winston info must be an object");
680
- }
681
-
682
- const level = logbrewLevelFromWinstonLevel(info.level);
683
- const metadata = {
684
- ...compactMetadata(options.metadata),
685
- winstonLevel: winstonLevelLabel(info.level),
686
- ...winstonContextMetadata(info)
687
- };
688
- addWinstonErrorMetadata(metadata, info, options.includeErrorStack === true);
689
-
690
- return {
691
- message: winstonMessage(info),
692
- level,
693
- ...(options.logger ? { logger: options.logger } : {}),
694
- metadata
695
- };
696
- }
697
-
698
- function timestampFromWinstonInfo(info, fallbackTimestamp) {
699
- const value = info?.timestamp ?? info?.time;
700
- if (typeof value === "number" && Number.isFinite(value)) {
701
- return new Date(value).toISOString();
702
- }
703
- if (typeof value === "string" && value.trim() !== "") {
704
- const parsed = new Date(value);
705
- if (!Number.isNaN(parsed.valueOf())) {
706
- return parsed.toISOString();
707
- }
708
- return value;
709
- }
710
- if (value instanceof Date && !Number.isNaN(value.valueOf())) {
711
- return value.toISOString();
712
- }
713
- return fallbackTimestamp();
714
- }
715
-
716
- function logbrewLevelFromWinstonLevel(level) {
717
- switch (String(level).toLowerCase()) {
718
- case "debug":
719
- case "silly":
720
- return "info";
721
- case "warn":
722
- case "warning":
723
- return "warning";
724
- case "error":
725
- return "error";
726
- case "crit":
727
- case "critical":
728
- case "fatal":
729
- return "critical";
730
- case "http":
731
- case "verbose":
732
- case "info":
733
- default:
734
- return "info";
735
- }
736
- }
737
-
738
- function winstonLevelLabel(level) {
739
- return typeof level === "string" && level.trim() !== "" ? level : "info";
740
- }
741
-
742
- function winstonMessage(info) {
743
- if (typeof info.message === "string" && info.message.trim() !== "") {
744
- return info.message;
745
- }
746
- const error = info.err ?? info.error;
747
- if (error && typeof error === "object" && typeof error.message === "string" && error.message.trim() !== "") {
748
- return error.message;
749
- }
750
- return "winston event";
751
- }
752
-
753
- function winstonContextMetadata(info) {
754
- const metadata = {};
755
- for (const [key, value] of Object.entries(info)) {
756
- if (!WINSTON_RESERVED_FIELDS.has(key) && isMetadataValue(value)) {
757
- metadata[`context.${key}`] = value;
758
- }
759
- }
760
- return metadata;
761
- }
762
-
763
- function addWinstonErrorMetadata(metadata, info, includeErrorStack) {
764
- const error = info.err ?? info.error;
765
- addWinstonNestedErrorMetadata(metadata, error, includeErrorStack);
766
- if (typeof info.stack === "string" && info.stack.trim() !== "") {
767
- const firstLine = info.stack.split(/\r?\n/u)[0] ?? "";
768
- const match = /^([A-Za-z][A-Za-z0-9_.]*(?:Error|Exception)?):\s*(.*)$/u.exec(firstLine);
769
- if (match && metadata.errorName === undefined) {
770
- metadata.errorName = match[1];
771
- }
772
- if (match && match[2] && metadata.errorMessage === undefined) {
773
- metadata.errorMessage = match[2];
774
- }
775
- if (includeErrorStack) {
776
- metadata.errorStack = info.stack;
777
- }
778
- }
779
- }
780
-
781
- function addWinstonNestedErrorMetadata(metadata, error, includeErrorStack) {
782
- if (!error) {
783
- return;
784
- }
785
- if (error instanceof Error) {
786
- metadata.errorName = error.name || "Error";
787
- if (error.message) {
788
- metadata.errorMessage = error.message;
789
- }
790
- if (includeErrorStack && error.stack) {
791
- metadata.errorStack = error.stack;
792
- }
793
- return;
794
- }
795
- if (typeof error === "object") {
796
- const name = error.type ?? error.name;
797
- const message = error.message;
798
- const stack = error.stack;
799
- if (typeof name === "string" && name.trim() !== "") {
800
- metadata.errorName = name;
801
- }
802
- if (typeof message === "string" && message.trim() !== "") {
803
- metadata.errorMessage = message;
804
- }
805
- if (includeErrorStack && typeof stack === "string" && stack.trim() !== "") {
806
- metadata.errorStack = stack;
807
- }
808
- return;
809
- }
810
- if (typeof error === "string" && error.trim() !== "") {
811
- metadata.errorMessage = error;
812
- }
813
- }
814
-
815
- function timestampFromPinoRecord(record, fallbackTimestamp) {
816
- const value = record?.time ?? record?.timestamp;
817
- if (typeof value === "number" && Number.isFinite(value)) {
818
- return new Date(value).toISOString();
819
- }
820
- if (typeof value === "string" && value.trim() !== "") {
821
- const parsed = new Date(value);
822
- if (!Number.isNaN(parsed.valueOf())) {
823
- return parsed.toISOString();
824
- }
825
- return value;
826
- }
827
- return fallbackTimestamp();
828
- }
829
-
830
- function logbrewLevelFromPinoLevel(level) {
831
- if (typeof level === "number" && Number.isFinite(level)) {
832
- if (level >= 60) {
833
- return "critical";
834
- }
835
- if (level >= 50) {
836
- return "error";
837
- }
838
- if (level >= 40) {
839
- return "warning";
840
- }
841
- if (level >= 30) {
842
- return "info";
843
- }
844
- return "info";
845
- }
846
-
847
- switch (String(level).toLowerCase()) {
848
- case "trace":
849
- case "debug":
850
- return "info";
851
- case "warn":
852
- case "warning":
853
- return "warning";
854
- case "error":
855
- return "error";
856
- case "fatal":
857
- case "critical":
858
- return "critical";
859
- case "info":
860
- default:
861
- return "info";
862
- }
863
- }
864
-
865
- function pinoLevelLabel(level) {
866
- if (typeof level === "string" && level.trim() !== "") {
867
- return level;
868
- }
869
- switch (level) {
870
- case 10:
871
- return "trace";
872
- case 20:
873
- return "debug";
874
- case 30:
875
- return "info";
876
- case 40:
877
- return "warn";
878
- case 50:
879
- return "error";
880
- case 60:
881
- return "fatal";
882
- default:
883
- return typeof level === "number" && Number.isFinite(level) ? String(level) : "info";
884
- }
885
- }
886
-
887
- function pinoMessage(record) {
888
- if (typeof record.msg === "string" && record.msg.trim() !== "") {
889
- return record.msg;
890
- }
891
- if (typeof record.message === "string" && record.message.trim() !== "") {
892
- return record.message;
893
- }
894
- const error = record.err ?? record.error;
895
- if (error && typeof error === "object" && typeof error.message === "string" && error.message.trim() !== "") {
896
- return error.message;
897
- }
898
- return "pino event";
899
- }
900
-
901
- function pinoContextMetadata(record) {
902
- const metadata = {};
903
- for (const [key, value] of Object.entries(record)) {
904
- if (!PINO_RESERVED_FIELDS.has(key) && isMetadataValue(value)) {
905
- metadata[`context.${key}`] = value;
906
- }
907
- }
908
- return metadata;
909
- }
910
-
911
- function addPinoErrorMetadata(metadata, error, includeErrorStack) {
912
- if (!error) {
913
- return;
914
- }
915
- if (error instanceof Error) {
916
- metadata.errorName = error.name || "Error";
917
- if (error.message) {
918
- metadata.errorMessage = error.message;
919
- }
920
- if (includeErrorStack && error.stack) {
921
- metadata.errorStack = error.stack;
922
- }
923
- return;
924
- }
925
- if (typeof error === "object") {
926
- const name = error.type ?? error.name;
927
- const message = error.message;
928
- const stack = error.stack;
929
- if (typeof name === "string" && name.trim() !== "") {
930
- metadata.errorName = name;
931
- }
932
- if (typeof message === "string" && message.trim() !== "") {
933
- metadata.errorMessage = message;
934
- }
935
- if (includeErrorStack && typeof stack === "string" && stack.trim() !== "") {
936
- metadata.errorStack = stack;
937
- }
938
- return;
939
- }
940
- if (typeof error === "string" && error.trim() !== "") {
941
- metadata.errorMessage = error;
942
- }
943
- }
944
-
945
- function requireNonEmpty(label, value) {
946
- if (typeof value !== "string" || value.trim() === "") {
947
- throw new SdkError("validation_error", `${label} must be non-empty`);
948
- }
949
- }
950
-
951
- function requireAllowedValue(label, value, allowedValues) {
952
- requireNonEmpty(label, value);
953
- if (!allowedValues.has(value)) {
954
- throw new SdkError(
955
- "validation_error",
956
- `${label} must be one of: ${Array.from(allowedValues).join(", ")}`
957
- );
958
- }
959
- }
960
-
961
- function requireFiniteNumber(label, value) {
962
- if (typeof value !== "number" || !Number.isFinite(value)) {
963
- throw new SdkError("validation_error", `${label} must be a finite number`);
964
- }
965
- }
966
-
967
- function requireTraceId(traceId) {
968
- if (typeof traceId !== "string" || !/^[0-9a-fA-F]{32}$/u.test(traceId)) {
969
- throw new SdkError("validation_error", "traceId must be 32 lowercase or uppercase hex characters");
970
- }
971
- if (traceId.toLowerCase() === ZERO_TRACE_ID) {
972
- throw new SdkError("validation_error", "traceId must not be all zeros");
973
- }
974
- }
975
-
976
- function requireSpanId(label, spanId) {
977
- if (typeof spanId !== "string" || !/^[0-9a-fA-F]{16}$/u.test(spanId)) {
978
- throw new SdkError("validation_error", `${label} must be 16 lowercase or uppercase hex characters`);
979
- }
980
- if (spanId.toLowerCase() === ZERO_SPAN_ID) {
981
- throw new SdkError("validation_error", `${label} must not be all zeros`);
982
- }
983
- }
984
-
985
- function requireTraceFlags(traceFlags) {
986
- if (typeof traceFlags !== "string" || !/^[0-9a-fA-F]{2}$/u.test(traceFlags)) {
987
- throw new SdkError("validation_error", "traceFlags must be 2 lowercase or uppercase hex characters");
988
- }
989
- }
990
-
991
- function requireTimestamp(timestamp) {
992
- requireNonEmpty("timestamp", timestamp);
993
- if (timestamp.endsWith("Z")) {
994
- return;
995
- }
996
- const timePortion = timestamp.split("T")[1];
997
- if (timePortion && (timePortion.includes("+") || /.+-.+/.test(timePortion))) {
998
- return;
999
- }
1000
- throw new SdkError(
1001
- "validation_error",
1002
- `timestamp must include a timezone offset: ${timestamp}`
1003
- );
1004
- }
1005
-
1006
- function cloneMetadata(metadata) {
1007
- if (metadata === undefined) {
1008
- return undefined;
1009
- }
1010
- if (!metadata || Array.isArray(metadata) || typeof metadata !== "object") {
1011
- throw new SdkError("validation_error", "metadata must be an object");
1012
- }
1013
- return { ...metadata };
1014
- }
1015
-
1016
- function cloneEvent(event) {
1017
- const attributes = event.attributes.metadata === undefined
1018
- ? { ...event.attributes }
1019
- : { ...event.attributes, metadata: { ...event.attributes.metadata } };
1020
- return { ...event, attributes };
1021
- }
1022
-
1023
- function validateRelease(attributes) {
1024
- requireNonEmpty("release version", attributes.version);
1025
- if (attributes.commit !== undefined) {
1026
- requireNonEmpty("release commit", attributes.commit);
1027
- }
1028
- return withMetadata({
1029
- version: attributes.version,
1030
- ...(attributes.commit ? { commit: attributes.commit } : {}),
1031
- ...(attributes.notes !== undefined ? { notes: attributes.notes } : {})
1032
- }, attributes.metadata);
1033
- }
1034
-
1035
- function validateEnvironment(attributes) {
1036
- requireNonEmpty("environment name", attributes.name);
1037
- return withMetadata({
1038
- name: attributes.name,
1039
- ...(attributes.region !== undefined ? { region: attributes.region } : {})
1040
- }, attributes.metadata);
1041
- }
1042
-
1043
- function validateIssue(attributes) {
1044
- requireNonEmpty("issue title", attributes.title);
1045
- const level = normalizeSeverity("issue level", attributes.level);
1046
- return withMetadata({
1047
- title: attributes.title,
1048
- level,
1049
- ...(attributes.message !== undefined ? { message: attributes.message } : {})
1050
- }, attributes.metadata);
1051
- }
1052
-
1053
- function validateLog(attributes) {
1054
- requireNonEmpty("log message", attributes.message);
1055
- const level = normalizeSeverity("log level", attributes.level);
1056
- return withMetadata({
1057
- message: attributes.message,
1058
- level,
1059
- ...(attributes.logger !== undefined ? { logger: attributes.logger } : {})
1060
- }, attributes.metadata);
1061
- }
1062
-
1063
- function normalizeSeverity(label, value) {
1064
- requireAllowedValue(label, value, SEVERITY_VALUES);
1065
- return SEVERITY_ALIASES.get(value);
1066
- }
1067
-
1068
- function validateSpan(attributes) {
1069
- requireNonEmpty("span name", attributes.name);
1070
- requireNonEmpty("span traceId", attributes.traceId);
1071
- requireNonEmpty("span spanId", attributes.spanId);
1072
- requireAllowedValue("span status", attributes.status, SPAN_STATUSES);
1073
- if (attributes.parentSpanId !== undefined) {
1074
- requireNonEmpty("span parentSpanId", attributes.parentSpanId);
1075
- }
1076
- if (attributes.durationMs !== undefined) {
1077
- if (typeof attributes.durationMs !== "number" || Number.isNaN(attributes.durationMs) || attributes.durationMs < 0) {
1078
- throw new SdkError("validation_error", "span durationMs must be non-negative");
1079
- }
1080
- }
1081
- return withMetadata({
1082
- name: attributes.name,
1083
- traceId: attributes.traceId,
1084
- spanId: attributes.spanId,
1085
- status: attributes.status,
1086
- ...(attributes.parentSpanId !== undefined ? { parentSpanId: attributes.parentSpanId } : {}),
1087
- ...(attributes.durationMs !== undefined ? { durationMs: attributes.durationMs } : {})
1088
- }, attributes.metadata);
1089
- }
1090
-
1091
- function validateAction(attributes) {
1092
- requireNonEmpty("action name", attributes.name);
1093
- requireAllowedValue("action status", attributes.status, ACTION_STATUSES);
1094
- return withMetadata({
1095
- name: attributes.name,
1096
- status: attributes.status
1097
- }, attributes.metadata);
1098
- }
1099
-
1100
- function validateMetric(attributes) {
1101
- requireNonEmpty("metric name", attributes.name);
1102
- requireAllowedValue("metric kind", attributes.kind, METRIC_KINDS);
1103
- requireFiniteNumber("metric value", attributes.value);
1104
- requireNonEmpty("metric unit", attributes.unit);
1105
-
1106
- const allowedTemporalities = METRIC_TEMPORALITIES_BY_KIND.get(attributes.kind);
1107
- requireAllowedValue(`metric temporality for ${attributes.kind}`, attributes.temporality, allowedTemporalities);
1108
- if (NON_NEGATIVE_METRIC_KINDS.has(attributes.kind) && attributes.value < 0) {
1109
- throw new SdkError("validation_error", `metric ${attributes.kind} value must be non-negative`);
1110
- }
1111
-
1112
- return withMetadata({
1113
- name: attributes.name,
1114
- kind: attributes.kind,
1115
- value: attributes.value,
1116
- unit: attributes.unit,
1117
- temporality: attributes.temporality
1118
- }, attributes.metadata);
1119
- }
1120
-
1121
- function productActionDetails(action) {
1122
- if (typeof action === "string") {
1123
- return { name: action, status: "success" };
1124
- }
1125
- if (!action || Array.isArray(action) || typeof action !== "object") {
1126
- throw new SdkError("validation_error", "product action must be a string or object");
1127
- }
1128
- requireNonEmpty("product action name", action.name);
1129
- const status = action.status === undefined ? "success" : action.status;
1130
- requireAllowedValue("product action status", status, ACTION_STATUSES);
1131
- return {
1132
- funnel: action.funnel,
1133
- metadata: action.metadata,
1134
- name: action.name,
1135
- routeTemplate: action.routeTemplate,
1136
- screen: action.screen,
1137
- sessionId: action.sessionId,
1138
- status,
1139
- step: action.step,
1140
- traceId: action.traceId
1141
- };
1142
- }
1143
-
1144
- function networkMilestoneDetails(request) {
1145
- if (typeof request === "string") {
1146
- return networkMilestoneDetails({ routeTemplate: request });
1147
- }
1148
- if (!request || Array.isArray(request) || typeof request !== "object") {
1149
- throw new SdkError("validation_error", "network milestone must be a string or object");
1150
- }
1151
-
1152
- const routeTemplate = sanitizeRouteTemplate(request.routeTemplate);
1153
- requireNonEmpty("network milestone routeTemplate", routeTemplate);
1154
- const method = normalizeHttpMethod(request.method);
1155
- const statusCode = statusCodeOrUndefined(request.statusCode);
1156
- const status = request.status === undefined
1157
- ? statusFromStatusCode(statusCode)
1158
- : request.status;
1159
- requireAllowedValue("network milestone status", status, ACTION_STATUSES);
1160
- const durationMs = nonNegativeNumberOrUndefined("network milestone durationMs", request.durationMs);
1161
- const name = typeof request.name === "string" && request.name.trim() !== ""
1162
- ? request.name
1163
- : `network.${method.toLowerCase()} ${routeTemplate}`;
1164
-
1165
- return {
1166
- durationMs,
1167
- metadata: request.metadata,
1168
- method,
1169
- name,
1170
- routeTemplate,
1171
- sessionId: request.sessionId,
1172
- status,
1173
- statusCode,
1174
- traceId: request.traceId
1175
- };
1176
- }
1177
-
1178
- function sanitizeRouteTemplate(routeTemplate) {
1179
- if (routeTemplate === undefined) {
1180
- return undefined;
1181
- }
1182
- if (typeof routeTemplate !== "string") {
1183
- throw new SdkError("validation_error", "routeTemplate must be a string");
1184
- }
1185
- const trimmed = routeTemplate.trim();
1186
- if (trimmed === "") {
1187
- return "";
1188
- }
1189
- try {
1190
- const url = new URL(trimmed, "https://logbrew.example");
1191
- return url.pathname || "/";
1192
- } catch {
1193
- return trimmed.split(/[?#]/u)[0] || "/";
1194
- }
1195
- }
1196
-
1197
- function normalizeHttpMethod(method) {
1198
- const value = method === undefined ? "GET" : method;
1199
- if (typeof value !== "string" || value.trim() === "") {
1200
- throw new SdkError("validation_error", "network milestone method must be a non-empty string");
1201
- }
1202
- const normalized = value.trim().toUpperCase();
1203
- if (!/^[A-Z][A-Z0-9_-]*$/u.test(normalized)) {
1204
- throw new SdkError("validation_error", "network milestone method must be a valid HTTP method");
1205
- }
1206
- return normalized;
1207
- }
1208
-
1209
- function statusCodeOrUndefined(value) {
1210
- if (value === undefined) {
1211
- return undefined;
1212
- }
1213
- if (!Number.isInteger(value) || value < 100 || value > 599) {
1214
- throw new SdkError("validation_error", "network milestone statusCode must be an integer from 100 to 599");
1215
- }
1216
- return value;
1217
- }
1218
-
1219
- function statusFromStatusCode(statusCode) {
1220
- if (statusCode !== undefined && statusCode >= 400) {
1221
- return "failure";
1222
- }
1223
- return "success";
1224
- }
1225
-
1226
- function nonNegativeNumberOrUndefined(label, value) {
1227
- if (value === undefined) {
1228
- return undefined;
1229
- }
1230
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
1231
- throw new SdkError("validation_error", `${label} must be a non-negative number`);
1232
- }
1233
- return value;
1234
- }
1235
-
1236
- function stringOrUndefined(value) {
1237
- return typeof value === "string" && value.trim() !== "" ? value : undefined;
1238
- }
1239
-
1240
- function withMetadata(attributes, metadata) {
1241
- const safeMetadata = cloneMetadata(metadata);
1242
- return safeMetadata === undefined
1243
- ? attributes
1244
- : { ...attributes, metadata: safeMetadata };
1245
- }
1246
-
1247
- function compactMetadata(metadata) {
1248
- if (metadata === undefined) {
1249
- return {};
1250
- }
1251
- if (!metadata || Array.isArray(metadata) || typeof metadata !== "object") {
1252
- throw new SdkError("validation_error", "metadata must be an object");
1253
- }
1254
- const safeMetadata = {};
1255
- for (const [key, value] of Object.entries(metadata)) {
1256
- if (isMetadataValue(value)) {
1257
- safeMetadata[key] = value;
1258
- }
1259
- }
1260
- return safeMetadata;
1261
- }
1262
-
1263
- function isMetadataValue(value) {
1264
- return (
1265
- value === null
1266
- || typeof value === "string"
1267
- || typeof value === "number" && Number.isFinite(value)
1268
- || typeof value === "boolean"
1269
- );
1270
- }
1271
-
1272
- function normalizeConsoleLevels(levels) {
1273
- const requestedLevels = levels === undefined ? DEFAULT_CONSOLE_LEVELS : levels;
1274
- if (!Array.isArray(requestedLevels)) {
1275
- throw new SdkError("validation_error", "console capture levels must be an array");
1276
- }
1277
- const normalized = [];
1278
- for (const method of requestedLevels) {
1279
- if (!CONSOLE_METHODS.has(method)) {
1280
- throw new SdkError("validation_error", `console method must be one of: ${Array.from(CONSOLE_METHODS).join(", ")}`);
1281
- }
1282
- if (!normalized.includes(method)) {
1283
- normalized.push(method);
1284
- }
1285
- }
1286
- return normalized;
1287
- }
1288
-
1289
- function consoleMessage(args, includeErrorStack) {
1290
- const values = Array.isArray(args) ? args : [];
1291
- const message = values.map((value) => formatConsoleArgument(value, includeErrorStack)).join(" ");
1292
- return message.trim() === "" ? "console event" : message;
1293
- }
1294
-
1295
- function formatConsoleArgument(value, includeErrorStack) {
1296
- if (value instanceof Error) {
1297
- if (includeErrorStack && value.stack) {
1298
- return value.stack;
1299
- }
1300
- return value.message ? `${value.name}: ${value.message}` : value.name;
1301
- }
1302
- if (typeof value === "string") {
1303
- return value;
1304
- }
1305
- if (typeof value === "number" || typeof value === "boolean" || value === null || value === undefined) {
1306
- return String(value);
1307
- }
1308
- if (typeof value === "bigint" || typeof value === "symbol") {
1309
- return String(value);
1310
- }
1311
- try {
1312
- const json = JSON.stringify(value);
1313
- return json === undefined ? String(value) : json;
1314
- } catch {
1315
- return Object.prototype.toString.call(value);
1316
- }
1317
- }
1318
-
1319
- module.exports = {
1320
- createNetworkMilestoneAttributes,
1321
- createProductActionAttributes,
1322
- createTraceparent,
1323
- createTraceparentHeaders,
1324
- createLogBrewPinoDestination,
1325
- createLogBrewWinstonTransport,
1326
- installLogBrewConsoleCapture,
1327
- LogBrewClient,
1328
- logAttributesFromConsoleArgs,
1329
- logAttributesFromPinoRecord,
1330
- logAttributesFromWinstonInfo,
1331
- logbrewLevelFromConsoleMethod,
1332
- parseTraceparent,
1333
- RecordingTransport,
1334
- SdkError,
1335
- spanAttributesFromTraceparent,
1336
- TransportError
1337
- };
4
+ module.exports = { ...core, ...winston };