@logbrew/sdk 0.1.4 → 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/core.cjs ADDED
@@ -0,0 +1,2338 @@
1
+ const { buildCreateSupportTicketDraft } = require("./support-ticket.cjs");
2
+ const { buildIssueStackHelpers } = require("./issue-stack.cjs");
3
+ const { buildLogContextHelpers } = require("./log-context.cjs");
4
+ const { buildOpenTelemetryHelpers } = require("./opentelemetry.cjs");
5
+ const { buildTraceContextHelpers } = require("./trace-context.cjs");
6
+
7
+ const SEVERITY_ALIASES = new Map([
8
+ ["trace", "info"],
9
+ ["debug", "info"],
10
+ ["info", "info"],
11
+ ["warn", "warning"],
12
+ ["warning", "warning"],
13
+ ["error", "error"],
14
+ ["fatal", "critical"],
15
+ ["critical", "critical"]
16
+ ]);
17
+ const SEVERITY_VALUES = new Set(SEVERITY_ALIASES.keys());
18
+ const SPAN_STATUSES = new Set(["ok", "error"]);
19
+ const ACTION_STATUSES = new Set(["queued", "running", "success", "failure"]);
20
+ const METRIC_KINDS = new Set(["counter", "gauge", "histogram"]);
21
+ const NON_NEGATIVE_METRIC_KINDS = new Set(["counter", "histogram"]);
22
+ const METRIC_TEMPORALITIES_BY_KIND = new Map([
23
+ ["counter", new Set(["delta", "cumulative"])],
24
+ ["gauge", new Set(["instant"])],
25
+ ["histogram", new Set(["delta", "cumulative"])]
26
+ ]);
27
+ const CONSOLE_METHODS = new Set(["debug", "info", "log", "warn", "error"]);
28
+ const DEFAULT_CONSOLE_LEVELS = ["debug", "info", "log", "warn", "error"];
29
+ const PINO_HOST_FIELD = ["host", "name"].join("");
30
+ const PINO_RESERVED_FIELDS = new Set(["level", "time", "timestamp", "msg", "message", "err", "error", "pid", PINO_HOST_FIELD, "v"]);
31
+ const TRACEPARENT_PATTERN = /^([0-9a-fA-F]{2})-([0-9a-fA-F]{32})-([0-9a-fA-F]{16})-([0-9a-fA-F]{2})$/u;
32
+ const ZERO_TRACE_ID = "00000000000000000000000000000000";
33
+ const ZERO_SPAN_ID = "0000000000000000";
34
+ const DEFAULT_MAX_QUEUE_SIZE = 1000;
35
+ const DEFAULT_MAX_QUEUE_BYTES = 4 * 1024 * 1024;
36
+ const DEFAULT_MAX_BATCH_EVENTS = 100;
37
+ const DEFAULT_MAX_BATCH_BYTES = 256 * 1024;
38
+ const DEFAULT_DELIVERY_INTERVAL_MS = 5000;
39
+ const MAX_DELIVERY_INTERVAL_MS = 60 * 1000;
40
+ const DEFAULT_DELIVERY_QUEUE_THRESHOLD = 50;
41
+ const DELIVERY_HEALTH_SCHEMA_VERSION = 1;
42
+ const EVENT_QUEUE_FACTORY = Symbol.for("@logbrew/sdk.eventQueueFactory");
43
+ const MAX_ERROR_CAUSES = 5;
44
+ const BUILTIN_ERROR_NAMES = new Set([
45
+ "AggregateError",
46
+ "Error",
47
+ "EvalError",
48
+ "RangeError",
49
+ "ReferenceError",
50
+ "SyntaxError",
51
+ "TypeError",
52
+ "URIError"
53
+ ]);
54
+ const MAX_SPAN_EVENTS = 8;
55
+ const MAX_SPAN_LINKS = 8;
56
+ const EVENT_VALIDATORS = new Map([
57
+ ["release", validateRelease],
58
+ ["environment", validateEnvironment],
59
+ ["issue", validateIssue],
60
+ ["log", validateLog],
61
+ ["span", validateSpan],
62
+ ["action", validateAction],
63
+ ["metric", validateMetric]
64
+ ]);
65
+ class SdkError extends Error {
66
+ constructor(code, message, details = {}) {
67
+ super(message);
68
+ this.name = "SdkError";
69
+ this.code = code;
70
+ const retryAfterMs = retryAfterMsOrUndefined(details?.retryAfterMs);
71
+ if (retryAfterMs !== undefined) {
72
+ this.retryAfterMs = retryAfterMs;
73
+ }
74
+ if (details?.retryable === true) {
75
+ this.retryable = true;
76
+ }
77
+ }
78
+ }
79
+
80
+ const {
81
+ compactMetadata,
82
+ isMetadataValue,
83
+ normalizeLogTraceContext,
84
+ traceFromProvider,
85
+ traceMetadataFromLogContext
86
+ } = buildLogContextHelpers({ SdkError });
87
+
88
+ const { javascriptStackFrames, validateIssueStackFrames } = buildIssueStackHelpers({ SdkError });
89
+
90
+ class TransportError extends Error {
91
+ constructor(code, message, retryable = false) {
92
+ super(message);
93
+ this.name = "TransportError";
94
+ this.code = code;
95
+ this.retryable = retryable;
96
+ }
97
+
98
+ static network(message) {
99
+ return new TransportError("network_failure", message, true);
100
+ }
101
+ }
102
+
103
+ class RecordingTransport {
104
+ constructor(scriptedResponses = [{ statusCode: 202 }]) {
105
+ this.scriptedResponses = [...scriptedResponses];
106
+ this.sentBodies = [];
107
+ }
108
+
109
+ static alwaysAccept() {
110
+ return new RecordingTransport([{ statusCode: 202 }]);
111
+ }
112
+
113
+ lastBody() {
114
+ return this.sentBodies.at(-1) ?? null;
115
+ }
116
+
117
+ async send(apiKey, body) {
118
+ requireNonEmpty("apiKey", apiKey);
119
+ this.sentBodies.push(body);
120
+
121
+ const next = this.scriptedResponses.length > 0
122
+ ? this.scriptedResponses.shift()
123
+ : { statusCode: 202 };
124
+
125
+ if (next instanceof Error) {
126
+ throw next;
127
+ }
128
+
129
+ const retryAfterMs = retryAfterMsOrUndefined(next.retryAfterMs);
130
+ return retryAfterMs === undefined
131
+ ? { statusCode: next.statusCode, attempts: 1 }
132
+ : { statusCode: next.statusCode, attempts: 1, retryAfterMs };
133
+ }
134
+ }
135
+
136
+ class LogBrewClient {
137
+ static create({
138
+ apiKey,
139
+ sdkName,
140
+ sdkVersion,
141
+ maxRetries = 2,
142
+ eventFilter,
143
+ maxQueueSize = DEFAULT_MAX_QUEUE_SIZE,
144
+ maxQueueBytes = DEFAULT_MAX_QUEUE_BYTES,
145
+ maxBatchEvents = DEFAULT_MAX_BATCH_EVENTS,
146
+ maxBatchBytes = DEFAULT_MAX_BATCH_BYTES,
147
+ onEventDropped,
148
+ eventStore,
149
+ [EVENT_QUEUE_FACTORY]: eventQueueFactory,
150
+ transport,
151
+ automaticDelivery = transport !== undefined,
152
+ deliveryIntervalMs = DEFAULT_DELIVERY_INTERVAL_MS,
153
+ deliveryQueueThreshold = Math.min(DEFAULT_DELIVERY_QUEUE_THRESHOLD, maxQueueSize)
154
+ }) {
155
+ requireNonEmpty("apiKey", apiKey);
156
+ requireNonEmpty("sdkName", sdkName);
157
+ requireNonEmpty("sdkVersion", sdkVersion);
158
+ requireNonNegativeInteger("maxRetries", maxRetries);
159
+ if (eventFilter !== undefined && typeof eventFilter !== "function") {
160
+ throw new SdkError("validation_error", "eventFilter must be a function");
161
+ }
162
+ requirePositiveInteger("maxQueueSize", maxQueueSize);
163
+ requirePositiveInteger("maxQueueBytes", maxQueueBytes);
164
+ requirePositiveInteger("maxBatchEvents", maxBatchEvents);
165
+ requirePositiveInteger("maxBatchBytes", maxBatchBytes);
166
+ if (onEventDropped !== undefined && typeof onEventDropped !== "function") {
167
+ throw new SdkError("validation_error", "onEventDropped must be a function");
168
+ }
169
+ validateEventStore(eventStore);
170
+ if (eventQueueFactory !== undefined && typeof eventQueueFactory !== "function") {
171
+ throw new SdkError("validation_error", "event queue factory must be a function");
172
+ }
173
+ if (eventStore !== undefined && eventQueueFactory !== undefined) {
174
+ throw new SdkError("validation_error", "eventStore and event queue factory are mutually exclusive");
175
+ }
176
+ validateTransport(transport);
177
+ if (typeof automaticDelivery !== "boolean") {
178
+ throw new SdkError("validation_error", "automaticDelivery must be a boolean");
179
+ }
180
+ if (automaticDelivery && transport === undefined) {
181
+ throw new SdkError("validation_error", "automaticDelivery requires transport");
182
+ }
183
+ requirePositiveInteger("deliveryIntervalMs", deliveryIntervalMs);
184
+ if (deliveryIntervalMs > MAX_DELIVERY_INTERVAL_MS) {
185
+ throw new SdkError("validation_error", `deliveryIntervalMs must be at most ${MAX_DELIVERY_INTERVAL_MS}`);
186
+ }
187
+ requirePositiveInteger("deliveryQueueThreshold", deliveryQueueThreshold);
188
+ if (deliveryQueueThreshold > maxQueueSize) {
189
+ throw new SdkError("validation_error", "deliveryQueueThreshold must not exceed maxQueueSize");
190
+ }
191
+
192
+ return new LogBrewClient({
193
+ apiKey,
194
+ automaticDelivery,
195
+ deliveryIntervalMs,
196
+ deliveryQueueThreshold,
197
+ eventStore,
198
+ eventQueueFactory,
199
+ eventFilter,
200
+ maxBatchBytes,
201
+ maxBatchEvents,
202
+ maxQueueBytes,
203
+ maxQueueSize,
204
+ onEventDropped,
205
+ sdk: {
206
+ name: sdkName,
207
+ language: "javascript",
208
+ version: sdkVersion
209
+ },
210
+ maxRetries,
211
+ transport
212
+ });
213
+ }
214
+
215
+ constructor({
216
+ apiKey,
217
+ sdk,
218
+ maxRetries,
219
+ eventFilter,
220
+ maxBatchBytes,
221
+ maxBatchEvents,
222
+ maxQueueBytes,
223
+ maxQueueSize,
224
+ onEventDropped,
225
+ eventStore,
226
+ eventQueueFactory,
227
+ transport,
228
+ automaticDelivery,
229
+ deliveryIntervalMs,
230
+ deliveryQueueThreshold
231
+ }) {
232
+ this.apiKey = apiKey;
233
+ this.automaticDelivery = automaticDelivery;
234
+ this.deliveryIntervalMs = deliveryIntervalMs;
235
+ this.deliveryQueueThreshold = deliveryQueueThreshold;
236
+ this.eventFilter = eventFilter;
237
+ this.maxBatchBytes = maxBatchBytes;
238
+ this.maxBatchEvents = maxBatchEvents;
239
+ this.maxQueueBytes = maxQueueBytes;
240
+ this.maxQueueSize = maxQueueSize;
241
+ this.onEventDropped = onEventDropped;
242
+ this.transport = transport;
243
+ this.sdk = sdk;
244
+ this.maxRetries = maxRetries;
245
+ this.batchPrefix = `{"sdk":${JSON.stringify(this.sdk)},"events":[`;
246
+ this.batchPrefixBytes = utf8ByteLength(this.batchPrefix);
247
+ this.batchSuffix = "]}";
248
+ this.batchSuffixBytes = utf8ByteLength(this.batchSuffix);
249
+ const ownsEventStore = eventQueueFactory !== undefined;
250
+ const resolvedEventStore = ownsEventStore
251
+ ? createEventStoreFromQueueFactory(eventQueueFactory, {
252
+ batchPrefixBytes: this.batchPrefixBytes,
253
+ batchSuffixBytes: this.batchSuffixBytes,
254
+ maxBatchBytes,
255
+ maxQueueBytes,
256
+ maxQueueSize
257
+ })
258
+ : eventStore;
259
+ this.eventStore = resolvedEventStore;
260
+ let recovered;
261
+ try {
262
+ recovered = loadStoredEvents({
263
+ batchPrefixBytes: this.batchPrefixBytes,
264
+ batchSuffixBytes: this.batchSuffixBytes,
265
+ eventStore: resolvedEventStore,
266
+ maxBatchBytes,
267
+ maxQueueBytes,
268
+ maxQueueSize
269
+ });
270
+ } catch (error) {
271
+ if (ownsEventStore) {
272
+ try {
273
+ requireSynchronousStoreResult("close", resolvedEventStore.close());
274
+ } catch {
275
+ // Preserve the queue construction or recovery failure.
276
+ }
277
+ }
278
+ throw error;
279
+ }
280
+ this.events = recovered.events;
281
+ this.serializedEvents = recovered.serializedEvents;
282
+ this.serializedEventBytes = recovered.serializedEventBytes;
283
+ this.queuedEventBytes = recovered.queuedEventBytes;
284
+ this.operationTail = Promise.resolve();
285
+ this.pendingOperations = 0;
286
+ this.closing = false;
287
+ this.closed = false;
288
+ this.droppedEventCount = 0;
289
+ this.droppedEventsByReason = {
290
+ event_too_large: 0,
291
+ queue_bytes_overflow: 0,
292
+ queue_overflow: 0
293
+ };
294
+ this.lastDropReason = "none";
295
+ this.storage = resolvedEventStore ? "persistent" : "memory";
296
+ this.hydratedEventCount = recovered.events.length;
297
+ this.hydratedEventBytes = recovered.queuedEventBytes;
298
+ this.deliveryTimer = undefined;
299
+ this.automaticFlushActive = false;
300
+ this.automaticFlushPending = false;
301
+ this.deliveryInFlight = false;
302
+ this.lastDeliveryOutcome = "idle";
303
+ this.automaticPauseReason = "none";
304
+ this.consecutiveDeliveryFailures = 0;
305
+ this.retryDelayMs = 0;
306
+ this.successfulFlushCount = 0;
307
+ this.failedFlushCount = 0;
308
+ this.deliveryAttemptCount = 0;
309
+ this.acceptedBatchCount = 0;
310
+ this.acceptedEventCount = 0;
311
+ this.lastStatusClass = "none";
312
+ this.lastAttemptAtUnixMs = 0;
313
+ this.lastAcceptedAtUnixMs = 0;
314
+ this.lastDroppedAtUnixMs = 0;
315
+ this.failedBatch = undefined;
316
+ this.#scheduleAutomaticDelivery();
317
+ }
318
+
319
+ pendingEvents() {
320
+ return this.events.length;
321
+ }
322
+
323
+ pendingBytes() {
324
+ return this.queuedEventBytes;
325
+ }
326
+
327
+ droppedEvents() {
328
+ return this.droppedEventCount;
329
+ }
330
+
331
+ deliveryHealth() {
332
+ const droppedByReason = Object.freeze({ ...this.droppedEventsByReason });
333
+ return Object.freeze({
334
+ schemaVersion: DELIVERY_HEALTH_SCHEMA_VERSION,
335
+ automaticDelivery: this.automaticDelivery,
336
+ lifecycle: this.closed ? "closed" : this.closing ? "shutting_down" : "active",
337
+ deliveryState: this.#deliveryState(),
338
+ storage: this.storage,
339
+ queueEvents: this.events.length,
340
+ queueBytes: this.queuedEventBytes,
341
+ hydratedEvents: this.hydratedEventCount,
342
+ hydratedBytes: this.hydratedEventBytes,
343
+ droppedEvents: this.droppedEventCount,
344
+ droppedByReason,
345
+ lastDropReason: this.lastDropReason,
346
+ scheduled: this.deliveryTimer !== undefined,
347
+ inFlight: this.deliveryInFlight,
348
+ coalesced: this.automaticFlushPending,
349
+ pendingOperations: this.pendingOperations,
350
+ lastOutcome: this.lastDeliveryOutcome,
351
+ lastStatusClass: this.lastStatusClass,
352
+ pausedReason: this.automaticPauseReason,
353
+ consecutiveFailures: this.consecutiveDeliveryFailures,
354
+ retryDelayMs: this.retryDelayMs,
355
+ flushes: this.successfulFlushCount,
356
+ failures: this.failedFlushCount,
357
+ attempts: this.deliveryAttemptCount,
358
+ batches: this.acceptedBatchCount,
359
+ acceptedEvents: this.acceptedEventCount,
360
+ lastAttemptAtUnixMs: this.lastAttemptAtUnixMs,
361
+ lastAcceptedAtUnixMs: this.lastAcceptedAtUnixMs,
362
+ lastDroppedAtUnixMs: this.lastDroppedAtUnixMs
363
+ });
364
+ }
365
+
366
+ #deliveryState() {
367
+ if (this.deliveryInFlight) {
368
+ return "in_flight";
369
+ }
370
+ if (this.retryDelayMs > 0) {
371
+ return "retrying";
372
+ }
373
+ if (this.automaticPauseReason !== "none") {
374
+ return "paused";
375
+ }
376
+ if (this.events.length > 0) {
377
+ return this.deliveryTimer !== undefined ? "scheduled" : "queued";
378
+ }
379
+ if (this.lastDeliveryOutcome === "accepted") {
380
+ return "accepted";
381
+ }
382
+ if (this.lastDeliveryOutcome === "failed") {
383
+ return "failed";
384
+ }
385
+ if (this.droppedEventCount > 0) {
386
+ return "dropped";
387
+ }
388
+ return "idle";
389
+ }
390
+
391
+ previewJson() {
392
+ return JSON.stringify({ sdk: this.sdk, events: this.events }, null, 2);
393
+ }
394
+
395
+ purgePendingEvents() {
396
+ if (this.closed) {
397
+ throw new SdkError("shutdown_error", "client is already shut down");
398
+ }
399
+ if (this.closing) {
400
+ throw new SdkError("shutdown_error", "client is shutting down");
401
+ }
402
+ if (this.pendingOperations > 0 || this.automaticFlushActive) {
403
+ throw new SdkError("persistence_error", "cannot purge while a delivery operation is active");
404
+ }
405
+ const purgedEvents = this.events.length;
406
+ if (this.eventStore) {
407
+ requireSynchronousStoreResult("purge", this.eventStore.purge());
408
+ }
409
+ this.#clearDeliveryTimer();
410
+ this.automaticFlushPending = false;
411
+ this.failedBatch = undefined;
412
+ this.events.splice(0, this.events.length);
413
+ this.serializedEvents.splice(0, this.serializedEvents.length);
414
+ this.serializedEventBytes.splice(0, this.serializedEventBytes.length);
415
+ this.queuedEventBytes = 0;
416
+ return purgedEvents;
417
+ }
418
+
419
+ release(id, timestamp, attributes) {
420
+ this.#pushEvent("release", id, timestamp, validateRelease(attributes));
421
+ }
422
+
423
+ environment(id, timestamp, attributes) {
424
+ this.#pushEvent("environment", id, timestamp, validateEnvironment(attributes));
425
+ }
426
+
427
+ issue(id, timestamp, attributes) {
428
+ this.#pushEvent("issue", id, timestamp, validateIssue(attributes));
429
+ }
430
+
431
+ log(id, timestamp, attributes) {
432
+ this.#pushEvent("log", id, timestamp, validateLog(attributes));
433
+ }
434
+
435
+ span(id, timestamp, attributes) {
436
+ this.#pushEvent("span", id, timestamp, validateSpan(attributes));
437
+ }
438
+
439
+ action(id, timestamp, attributes) {
440
+ this.#pushEvent("action", id, timestamp, validateAction(attributes));
441
+ }
442
+
443
+ metric(id, timestamp, attributes) {
444
+ this.#pushEvent("metric", id, timestamp, validateMetric(attributes));
445
+ }
446
+
447
+ async flush(transport) {
448
+ if (this.closed) {
449
+ throw new SdkError("shutdown_error", "client is already shut down");
450
+ }
451
+ if (this.closing) {
452
+ throw new SdkError("shutdown_error", "client is shutting down");
453
+ }
454
+ const resolvedTransport = this.#resolveTransport(transport);
455
+ const controlsAutomaticDelivery = this.automaticDelivery && resolvedTransport === this.transport;
456
+ this.#clearDeliveryTimer();
457
+ return this.#runSerialized(async () => {
458
+ this.#clearDeliveryTimer();
459
+ try {
460
+ const response = await this.#flushWithHealth(resolvedTransport);
461
+ if (controlsAutomaticDelivery) {
462
+ this.#recordAutomaticSuccess();
463
+ }
464
+ return response;
465
+ } catch (error) {
466
+ if (controlsAutomaticDelivery) {
467
+ this.#recordAutomaticFailure(error);
468
+ }
469
+ throw error;
470
+ } finally {
471
+ if (this.automaticDelivery && !this.closed && !this.closing) {
472
+ this.#resumeAutomaticDelivery();
473
+ }
474
+ }
475
+ });
476
+ }
477
+
478
+ async shutdown(transport) {
479
+ if (this.closed) {
480
+ throw new SdkError("shutdown_error", "client is already shut down");
481
+ }
482
+ if (this.closing) {
483
+ throw new SdkError("shutdown_error", "client is shutting down");
484
+ }
485
+ const resolvedTransport = this.#resolveTransport(transport);
486
+ const controlsAutomaticDelivery = this.automaticDelivery && resolvedTransport === this.transport;
487
+ this.#clearDeliveryTimer();
488
+ this.automaticFlushPending = false;
489
+ this.closing = true;
490
+ try {
491
+ const response = await this.#runSerialized(() => this.#flushWithHealth(resolvedTransport));
492
+ if (controlsAutomaticDelivery) {
493
+ this.#recordAutomaticSuccess();
494
+ }
495
+ if (this.eventStore) {
496
+ try {
497
+ requireSynchronousStoreResult("close", this.eventStore.close());
498
+ } catch (error) {
499
+ this.closed = true;
500
+ throw error;
501
+ }
502
+ }
503
+ this.closed = true;
504
+ return response;
505
+ } catch (error) {
506
+ if (!this.closed) {
507
+ this.closing = false;
508
+ if (controlsAutomaticDelivery) {
509
+ this.#recordAutomaticFailure(error);
510
+ }
511
+ this.#resumeAutomaticDelivery();
512
+ }
513
+ throw error;
514
+ }
515
+ }
516
+
517
+ #pushEvent(eventType, id, timestamp, attributes) {
518
+ if (this.closed) {
519
+ throw new SdkError("shutdown_error", "client is already shut down");
520
+ }
521
+ if (this.closing) {
522
+ throw new SdkError("shutdown_error", "client is shutting down");
523
+ }
524
+ requireNonEmpty("event id", id);
525
+ requireTimestamp(timestamp);
526
+ const event = { type: eventType, id, timestamp, attributes };
527
+ if (this.eventFilter && this.eventFilter(cloneEvent(event)) === false) {
528
+ return;
529
+ }
530
+ const serializedEvent = JSON.stringify(event);
531
+ const eventBytes = utf8ByteLength(serializedEvent);
532
+ if (this.batchPrefixBytes + eventBytes + this.batchSuffixBytes > this.maxBatchBytes) {
533
+ this.#recordDroppedEvent(event, "event_too_large");
534
+ return;
535
+ }
536
+ if (this.events.length >= this.maxQueueSize) {
537
+ this.#recordDroppedEvent(event, "queue_overflow");
538
+ return;
539
+ }
540
+ if (this.queuedEventBytes + eventBytes > this.maxQueueBytes) {
541
+ this.#recordDroppedEvent(event, "queue_bytes_overflow");
542
+ return;
543
+ }
544
+ if (this.eventStore) {
545
+ requireSynchronousStoreResult("append", this.eventStore.append({
546
+ event: cloneEvent(event),
547
+ eventBytes,
548
+ serializedEvent
549
+ }));
550
+ }
551
+ this.events.push(event);
552
+ this.serializedEvents.push(serializedEvent);
553
+ this.serializedEventBytes.push(eventBytes);
554
+ this.queuedEventBytes += eventBytes;
555
+ this.#scheduleAutomaticDelivery();
556
+ }
557
+
558
+ #recordDroppedEvent(event, reason) {
559
+ this.droppedEventCount = incrementBounded(this.droppedEventCount);
560
+ this.droppedEventsByReason[reason] = incrementBounded(this.droppedEventsByReason[reason]);
561
+ this.lastDropReason = reason;
562
+ this.lastDroppedAtUnixMs = nextBoundedTimestamp(this.lastDroppedAtUnixMs);
563
+ if (!this.onEventDropped) {
564
+ return;
565
+ }
566
+ try {
567
+ this.onEventDropped({
568
+ droppedEvents: this.droppedEventCount,
569
+ eventId: event.id,
570
+ eventType: event.type,
571
+ reason
572
+ });
573
+ } catch {
574
+ // Drop callbacks are advisory and must not interrupt application logging.
575
+ }
576
+ }
577
+
578
+ #runSerialized(operation) {
579
+ this.pendingOperations = incrementBounded(this.pendingOperations);
580
+ const result = this.operationTail.then(operation).finally(() => {
581
+ this.pendingOperations = Math.max(0, this.pendingOperations - 1);
582
+ });
583
+ this.operationTail = result.then(
584
+ () => undefined,
585
+ () => undefined
586
+ );
587
+ return result;
588
+ }
589
+
590
+ #resolveTransport(transport) {
591
+ const resolved = transport ?? this.transport;
592
+ if (resolved === undefined) {
593
+ throw new SdkError("validation_error", "flush and shutdown require transport");
594
+ }
595
+ validateTransport(resolved);
596
+ return resolved;
597
+ }
598
+
599
+ async #flushWithHealth(transport) {
600
+ this.deliveryInFlight = true;
601
+ try {
602
+ const response = await this.#flushSnapshot(transport);
603
+ this.successfulFlushCount = incrementBounded(this.successfulFlushCount);
604
+ this.lastDeliveryOutcome = response.batches === 0 ? "empty" : "accepted";
605
+ return response;
606
+ } catch (error) {
607
+ this.failedFlushCount = incrementBounded(this.failedFlushCount);
608
+ this.lastDeliveryOutcome = "failed";
609
+ throw error;
610
+ } finally {
611
+ this.deliveryInFlight = false;
612
+ }
613
+ }
614
+
615
+ #scheduleAutomaticDelivery() {
616
+ if (!this.automaticDelivery || this.closed || this.closing || this.events.length === 0 || this.automaticPauseReason !== "none") {
617
+ return;
618
+ }
619
+ if (this.automaticFlushActive) {
620
+ this.automaticFlushPending = true;
621
+ return;
622
+ }
623
+ if (this.retryDelayMs > 0) {
624
+ this.#armAutomaticDeliveryTimer(this.retryDelayMs);
625
+ return;
626
+ }
627
+ if (this.events.length >= this.deliveryQueueThreshold) {
628
+ this.#requestAutomaticFlush();
629
+ return;
630
+ }
631
+ this.#armAutomaticDeliveryTimer();
632
+ }
633
+
634
+ #armAutomaticDeliveryTimer(delayMs = this.deliveryIntervalMs) {
635
+ if (!this.automaticDelivery || this.closed || this.closing || this.events.length === 0 || this.automaticPauseReason !== "none") {
636
+ return;
637
+ }
638
+ if (this.deliveryTimer !== undefined) {
639
+ return;
640
+ }
641
+ const timer = setTimeout(() => {
642
+ if (this.deliveryTimer !== timer) {
643
+ return;
644
+ }
645
+ this.deliveryTimer = undefined;
646
+ this.retryDelayMs = 0;
647
+ this.#requestAutomaticFlush();
648
+ }, delayMs);
649
+ this.deliveryTimer = timer;
650
+ if (timer && typeof timer === "object" && typeof timer.unref === "function") {
651
+ timer.unref();
652
+ }
653
+ }
654
+
655
+ #clearDeliveryTimer() {
656
+ if (this.deliveryTimer === undefined) {
657
+ return;
658
+ }
659
+ globalThis.clearTimeout(this.deliveryTimer);
660
+ this.deliveryTimer = undefined;
661
+ }
662
+
663
+ #requestAutomaticFlush() {
664
+ if (!this.automaticDelivery || this.closed || this.closing || this.events.length === 0 || this.automaticPauseReason !== "none") {
665
+ return;
666
+ }
667
+ this.#clearDeliveryTimer();
668
+ if (this.automaticFlushActive) {
669
+ this.automaticFlushPending = true;
670
+ return;
671
+ }
672
+ this.automaticFlushActive = true;
673
+ void Promise.resolve().then(() => this.#runAutomaticFlush());
674
+ }
675
+
676
+ async #runAutomaticFlush() {
677
+ if (this.closed || this.closing) {
678
+ this.automaticFlushActive = false;
679
+ this.automaticFlushPending = false;
680
+ return;
681
+ }
682
+ let succeeded = false;
683
+ try {
684
+ await this.#runSerialized(() => this.#flushWithHealth(this.transport));
685
+ this.#recordAutomaticSuccess();
686
+ succeeded = true;
687
+ } catch (error) {
688
+ this.#recordAutomaticFailure(error);
689
+ } finally {
690
+ this.automaticFlushActive = false;
691
+ if (this.closed || this.closing) {
692
+ this.automaticFlushPending = false;
693
+ } else {
694
+ const drainCoalesced = succeeded && this.automaticFlushPending && this.events.length > 0;
695
+ this.automaticFlushPending = false;
696
+ if (drainCoalesced) {
697
+ this.#requestAutomaticFlush();
698
+ } else if (!succeeded) {
699
+ this.#resumeAutomaticDelivery();
700
+ } else {
701
+ this.#scheduleAutomaticDelivery();
702
+ }
703
+ }
704
+ }
705
+ }
706
+
707
+ async #flushSnapshot(transport) {
708
+ let remainingEvents = this.events.length;
709
+ if (remainingEvents === 0) {
710
+ return { statusCode: 204, attempts: 0, batches: 0 };
711
+ }
712
+
713
+ let attempts = 0;
714
+ let batches = 0;
715
+ let statusCode = 204;
716
+ while (remainingEvents > 0) {
717
+ const batch = this.failedBatch ?? this.#nextBatch(Math.min(remainingEvents, this.maxBatchEvents));
718
+ let response;
719
+ try {
720
+ response = await this.#sendBatch(transport, batch.body);
721
+ } catch (error) {
722
+ this.failedBatch ??= Object.freeze({ body: batch.body, eventsCount: batch.eventsCount });
723
+ throw error;
724
+ }
725
+ this.failedBatch = undefined;
726
+ this.#acknowledge(batch.eventsCount);
727
+ this.acceptedBatchCount = incrementBounded(this.acceptedBatchCount);
728
+ remainingEvents -= batch.eventsCount;
729
+ attempts += response.attempts;
730
+ batches += 1;
731
+ statusCode = response.statusCode;
732
+ }
733
+
734
+ return { statusCode, attempts, batches };
735
+ }
736
+
737
+ #nextBatch(maxEvents) {
738
+ let bodyBytes = this.batchPrefixBytes + this.batchSuffixBytes;
739
+ let eventsCount = 0;
740
+ for (let index = 0; index < maxEvents; index += 1) {
741
+ const separatorBytes = eventsCount === 0 ? 0 : 1;
742
+ const nextBodyBytes = bodyBytes + separatorBytes + this.serializedEventBytes[index];
743
+ if (nextBodyBytes > this.maxBatchBytes) {
744
+ break;
745
+ }
746
+ bodyBytes = nextBodyBytes;
747
+ eventsCount += 1;
748
+ }
749
+ if (eventsCount === 0) {
750
+ throw new SdkError("transport_error", "queued event cannot fit the configured batch byte limit");
751
+ }
752
+ return {
753
+ body: `${this.batchPrefix}${this.serializedEvents.slice(0, eventsCount).join(",")}${this.batchSuffix}`,
754
+ eventsCount
755
+ };
756
+ }
757
+
758
+ #acknowledge(eventsCount) {
759
+ if (this.eventStore) {
760
+ requireSynchronousStoreResult("acknowledge", this.eventStore.acknowledge(eventsCount));
761
+ }
762
+ let acknowledgedBytes = 0;
763
+ for (let index = 0; index < eventsCount; index += 1) {
764
+ acknowledgedBytes += this.serializedEventBytes[index];
765
+ }
766
+ this.events.splice(0, eventsCount);
767
+ this.serializedEvents.splice(0, eventsCount);
768
+ this.serializedEventBytes.splice(0, eventsCount);
769
+ this.queuedEventBytes -= acknowledgedBytes;
770
+ this.acceptedEventCount = addBounded(this.acceptedEventCount, eventsCount);
771
+ this.lastAcceptedAtUnixMs = nextBoundedTimestamp(Math.max(
772
+ this.lastAcceptedAtUnixMs,
773
+ this.lastAttemptAtUnixMs
774
+ ));
775
+ }
776
+
777
+ #recordAutomaticSuccess() {
778
+ this.automaticPauseReason = "none";
779
+ this.consecutiveDeliveryFailures = 0;
780
+ this.retryDelayMs = 0;
781
+ }
782
+
783
+ #recordAutomaticFailure(error) {
784
+ this.consecutiveDeliveryFailures = incrementBounded(this.consecutiveDeliveryFailures);
785
+ this.retryDelayMs = 0;
786
+ if (error instanceof SdkError && error.code === "unauthenticated") {
787
+ this.automaticPauseReason = "authentication";
788
+ return;
789
+ }
790
+ if (error instanceof SdkError && error.code === "rate_limited") {
791
+ this.automaticPauseReason = "rate_limit";
792
+ return;
793
+ }
794
+ if (error instanceof SdkError && error.retryable === true) {
795
+ this.automaticPauseReason = "none";
796
+ this.retryDelayMs = automaticRetryDelayMs(this.deliveryIntervalMs, this.consecutiveDeliveryFailures);
797
+ return;
798
+ }
799
+ this.automaticPauseReason = "non_retryable";
800
+ }
801
+
802
+ #resumeAutomaticDelivery() {
803
+ if (this.automaticPauseReason !== "none") {
804
+ return;
805
+ }
806
+ if (this.retryDelayMs > 0) {
807
+ this.#armAutomaticDeliveryTimer(this.retryDelayMs);
808
+ return;
809
+ }
810
+ this.#scheduleAutomaticDelivery();
811
+ }
812
+
813
+ async #sendBatch(transport, body) {
814
+ const maxAttempts = this.maxRetries + 1;
815
+ let attempts = 0;
816
+
817
+ while (attempts < maxAttempts) {
818
+ attempts += 1;
819
+ this.deliveryAttemptCount = incrementBounded(this.deliveryAttemptCount);
820
+ this.lastAttemptAtUnixMs = nextBoundedTimestamp(this.lastAttemptAtUnixMs);
821
+ this.lastStatusClass = "transport_error";
822
+ try {
823
+ const response = await transport.send(this.apiKey, body);
824
+ if (
825
+ !response
826
+ || Array.isArray(response)
827
+ || typeof response !== "object"
828
+ || !Number.isSafeInteger(response.statusCode)
829
+ || response.statusCode < 100
830
+ || response.statusCode > 599
831
+ ) {
832
+ this.lastStatusClass = "invalid_response";
833
+ throw new SdkError("transport_error", "invalid transport response");
834
+ }
835
+ this.lastStatusClass = statusClass(response.statusCode);
836
+ if (response.statusCode === 401) {
837
+ throw new SdkError("unauthenticated", "transport rejected the API key");
838
+ }
839
+ if (response.statusCode === 429) {
840
+ throw new SdkError("rate_limited", "transport rate limited the batch", {
841
+ retryAfterMs: response.retryAfterMs
842
+ });
843
+ }
844
+ if (response.statusCode >= 200 && response.statusCode < 300) {
845
+ return { statusCode: response.statusCode, attempts };
846
+ }
847
+ const retryableStatus = response.statusCode === 408 || response.statusCode >= 500;
848
+ if (retryableStatus && attempts < maxAttempts) {
849
+ continue;
850
+ }
851
+ throw new SdkError("transport_error", `unexpected transport status ${response.statusCode}`, {
852
+ retryable: retryableStatus
853
+ });
854
+ } catch (error) {
855
+ if (error instanceof SdkError) {
856
+ throw error;
857
+ }
858
+ if (error instanceof TransportError && error.retryable && attempts < maxAttempts) {
859
+ this.lastStatusClass = "network_error";
860
+ continue;
861
+ }
862
+ if (error instanceof TransportError) {
863
+ this.lastStatusClass = "network_error";
864
+ throw new SdkError(error.code, error.message, { retryable: error.retryable });
865
+ }
866
+ throw error;
867
+ }
868
+ }
869
+
870
+ throw new SdkError("transport_error", "exhausted retries");
871
+ }
872
+ }
873
+
874
+ function automaticRetryDelayMs(deliveryIntervalMs, consecutiveFailures) {
875
+ const exponent = Math.min(consecutiveFailures - 1, 30);
876
+ const maximumDelay = Math.min(MAX_DELIVERY_INTERVAL_MS, deliveryIntervalMs * (2 ** exponent));
877
+ const minimumDelay = Math.ceil(maximumDelay / 2);
878
+ return minimumDelay + Math.floor(Math.random() * (maximumDelay - minimumDelay + 1));
879
+ }
880
+
881
+ function statusClass(statusCode) {
882
+ if (statusCode >= 200 && statusCode < 300) {
883
+ return "success";
884
+ }
885
+ if (statusCode >= 400 && statusCode < 500) {
886
+ return "client_error";
887
+ }
888
+ if (statusCode >= 500) {
889
+ return "server_error";
890
+ }
891
+ return "other_status";
892
+ }
893
+
894
+ function nextBoundedTimestamp(previous) {
895
+ const now = Date.now();
896
+ if (!Number.isFinite(now)) {
897
+ return previous;
898
+ }
899
+ const bounded = Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.floor(now)));
900
+ return Math.max(previous, bounded);
901
+ }
902
+
903
+ function addBounded(current, increment) {
904
+ return Math.min(Number.MAX_SAFE_INTEGER, current + increment);
905
+ }
906
+
907
+ function utf8ByteLength(value) {
908
+ let bytes = 0;
909
+ for (let index = 0; index < value.length; index += 1) {
910
+ const codeUnit = value.charCodeAt(index);
911
+ if (codeUnit < 0x80) {
912
+ bytes += 1;
913
+ } else if (codeUnit < 0x800) {
914
+ bytes += 2;
915
+ } else if (codeUnit >= 0xd800 && codeUnit <= 0xdbff && index + 1 < value.length) {
916
+ const nextCodeUnit = value.charCodeAt(index + 1);
917
+ if (nextCodeUnit >= 0xdc00 && nextCodeUnit <= 0xdfff) {
918
+ bytes += 4;
919
+ index += 1;
920
+ } else {
921
+ bytes += 3;
922
+ }
923
+ } else {
924
+ bytes += 3;
925
+ }
926
+ }
927
+ return bytes;
928
+ }
929
+
930
+ function incrementBounded(value) {
931
+ return value >= Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : value + 1;
932
+ }
933
+
934
+ function validateTransport(transport) {
935
+ if (transport === undefined) {
936
+ return;
937
+ }
938
+ if (!transport || Array.isArray(transport) || typeof transport !== "object" || typeof transport.send !== "function") {
939
+ throw new SdkError("validation_error", "transport.send must be a function");
940
+ }
941
+ }
942
+
943
+ function validateEventStore(eventStore) {
944
+ if (eventStore === undefined) {
945
+ return;
946
+ }
947
+ if (!eventStore || Array.isArray(eventStore) || typeof eventStore !== "object") {
948
+ throw new SdkError("validation_error", "eventStore must be an object");
949
+ }
950
+ for (const method of ["load", "append", "acknowledge", "purge", "close"]) {
951
+ if (typeof eventStore[method] !== "function") {
952
+ throw new SdkError("validation_error", `eventStore.${method} must be a function`);
953
+ }
954
+ }
955
+ }
956
+
957
+ function createEventStoreFromQueueFactory(eventQueueFactory, config) {
958
+ const queue = eventQueueFactory({
959
+ ...config,
960
+ restoreEvent: restoreStoredEvent
961
+ });
962
+ validateEventQueue(queue);
963
+ return {
964
+ load() {
965
+ const events = queue.events();
966
+ const count = queue.length();
967
+ if (!Array.isArray(events) || events.length !== count) {
968
+ throw invalidStoredRecord();
969
+ }
970
+ return events.map((event, index) => ({
971
+ event,
972
+ eventBytes: queue.eventBytesAt(index),
973
+ serializedEvent: queue.serializedAt(index)
974
+ }));
975
+ },
976
+ append(record) {
977
+ return queue.append({
978
+ event: record.event,
979
+ byteCount: record.eventBytes,
980
+ serialized: record.serializedEvent
981
+ });
982
+ },
983
+ acknowledge(count) {
984
+ return queue.acknowledge(count);
985
+ },
986
+ purge() {
987
+ return queue.acknowledge(queue.length());
988
+ },
989
+ close() {
990
+ return queue.close();
991
+ }
992
+ };
993
+ }
994
+
995
+ function validateEventQueue(queue) {
996
+ const methods = [
997
+ "acknowledge",
998
+ "append",
999
+ "byteCount",
1000
+ "close",
1001
+ "eventBytesAt",
1002
+ "events",
1003
+ "length",
1004
+ "serializedAt"
1005
+ ];
1006
+ if (!queue || Array.isArray(queue) || typeof queue !== "object" || methods.some((method) => typeof queue[method] !== "function")) {
1007
+ throw new SdkError("validation_error", "event queue factory returned an invalid queue");
1008
+ }
1009
+ }
1010
+
1011
+ function restoreStoredEvent(serializedEvent) {
1012
+ if (typeof serializedEvent !== "string" || serializedEvent === "") {
1013
+ throw invalidStoredRecord();
1014
+ }
1015
+ let event;
1016
+ try {
1017
+ event = JSON.parse(serializedEvent);
1018
+ } catch {
1019
+ throw invalidStoredRecord();
1020
+ }
1021
+ return normalizeStoredRecord({
1022
+ event,
1023
+ eventBytes: utf8ByteLength(serializedEvent),
1024
+ serializedEvent
1025
+ }).event;
1026
+ }
1027
+
1028
+ function requireSynchronousStoreResult(operation, result) {
1029
+ if (result && typeof result.then === "function") {
1030
+ throw new SdkError("persistence_error", `eventStore.${operation} must complete synchronously`);
1031
+ }
1032
+ return result;
1033
+ }
1034
+
1035
+ function loadStoredEvents({
1036
+ batchPrefixBytes,
1037
+ batchSuffixBytes,
1038
+ eventStore,
1039
+ maxBatchBytes,
1040
+ maxQueueBytes,
1041
+ maxQueueSize
1042
+ }) {
1043
+ if (!eventStore) {
1044
+ return {
1045
+ events: [],
1046
+ queuedEventBytes: 0,
1047
+ serializedEventBytes: [],
1048
+ serializedEvents: []
1049
+ };
1050
+ }
1051
+
1052
+ const records = requireSynchronousStoreResult("load", eventStore.load());
1053
+ if (!Array.isArray(records)) {
1054
+ throw invalidStoredRecord();
1055
+ }
1056
+ if (records.length > maxQueueSize) {
1057
+ throw new SdkError("persistence_error", "recovered event count exceeds maxQueueSize");
1058
+ }
1059
+
1060
+ const events = [];
1061
+ const serializedEvents = [];
1062
+ const serializedEventBytes = [];
1063
+ let queuedEventBytes = 0;
1064
+ for (const record of records) {
1065
+ const normalized = normalizeStoredRecord(record);
1066
+ if (batchPrefixBytes + normalized.eventBytes + batchSuffixBytes > maxBatchBytes) {
1067
+ throw new SdkError("persistence_error", "recovered event exceeds maxBatchBytes");
1068
+ }
1069
+ queuedEventBytes += normalized.eventBytes;
1070
+ if (queuedEventBytes > maxQueueBytes) {
1071
+ throw new SdkError("persistence_error", "recovered event bytes exceed maxQueueBytes");
1072
+ }
1073
+ events.push(normalized.event);
1074
+ serializedEvents.push(normalized.serializedEvent);
1075
+ serializedEventBytes.push(normalized.eventBytes);
1076
+ }
1077
+ return { events, queuedEventBytes, serializedEventBytes, serializedEvents };
1078
+ }
1079
+
1080
+ function normalizeStoredRecord(record) {
1081
+ try {
1082
+ if (!record || Array.isArray(record) || typeof record !== "object") {
1083
+ throw invalidStoredRecord();
1084
+ }
1085
+ const { event, eventBytes, serializedEvent } = record;
1086
+ if (!event || Array.isArray(event) || typeof event !== "object") {
1087
+ throw invalidStoredRecord();
1088
+ }
1089
+ const validator = EVENT_VALIDATORS.get(event.type);
1090
+ if (!validator || !Number.isSafeInteger(eventBytes) || eventBytes <= 0 || typeof serializedEvent !== "string") {
1091
+ throw invalidStoredRecord();
1092
+ }
1093
+ requireNonEmpty("event id", event.id);
1094
+ requireTimestamp(event.timestamp);
1095
+ if (!event.attributes || Array.isArray(event.attributes) || typeof event.attributes !== "object") {
1096
+ throw invalidStoredRecord();
1097
+ }
1098
+ const normalizedEvent = {
1099
+ type: event.type,
1100
+ id: event.id,
1101
+ timestamp: event.timestamp,
1102
+ attributes: validator(event.attributes)
1103
+ };
1104
+ if (JSON.stringify(normalizedEvent) !== serializedEvent || utf8ByteLength(serializedEvent) !== eventBytes) {
1105
+ throw invalidStoredRecord();
1106
+ }
1107
+ return {
1108
+ event: cloneEvent(normalizedEvent),
1109
+ eventBytes,
1110
+ serializedEvent
1111
+ };
1112
+ } catch (error) {
1113
+ if (error instanceof SdkError && error.code === "persistence_error") {
1114
+ throw error;
1115
+ }
1116
+ throw invalidStoredRecord();
1117
+ }
1118
+ }
1119
+
1120
+ function invalidStoredRecord() {
1121
+ return new SdkError("persistence_error", "event store returned an invalid record");
1122
+ }
1123
+
1124
+ function installLogBrewConsoleCapture(config) {
1125
+ if (!config || typeof config !== "object") {
1126
+ throw new SdkError("validation_error", "console capture config must be an object");
1127
+ }
1128
+
1129
+ const client = config.client;
1130
+ if (!(client instanceof LogBrewClient)) {
1131
+ throw new SdkError("validation_error", "console capture client must be a LogBrewClient");
1132
+ }
1133
+
1134
+ const targetConsole = config.console ?? globalThis.console;
1135
+ if (!targetConsole || typeof targetConsole !== "object") {
1136
+ throw new SdkError("validation_error", "console capture target must be an object");
1137
+ }
1138
+
1139
+ const transport = config.transport;
1140
+ const flushOnCapture = config.flushOnCapture === true;
1141
+ const includeErrorStack = config.includeErrorStack === true;
1142
+ const logger = config.logger ?? "console";
1143
+ const metadata = compactMetadata(config.metadata);
1144
+ const timestamp = typeof config.timestamp === "function"
1145
+ ? config.timestamp
1146
+ : () => new Date().toISOString();
1147
+ const eventIdPrefix = config.eventIdPrefix ?? "console";
1148
+ const onError = typeof config.onError === "function" ? config.onError : () => {};
1149
+ const levels = normalizeConsoleLevels(config.levels);
1150
+ const originals = new Map();
1151
+ const state = {
1152
+ installed: true,
1153
+ captured: 0,
1154
+ pendingFlush: Promise.resolve(null)
1155
+ };
1156
+
1157
+ for (const method of levels) {
1158
+ const original = targetConsole[method];
1159
+ if (typeof original !== "function") {
1160
+ continue;
1161
+ }
1162
+ originals.set(method, original);
1163
+ targetConsole[method] = createConsoleCaptureMethod({
1164
+ client,
1165
+ eventIdPrefix,
1166
+ flushOnCapture,
1167
+ includeErrorStack,
1168
+ logger,
1169
+ metadata,
1170
+ method,
1171
+ onError,
1172
+ original,
1173
+ state,
1174
+ timestamp,
1175
+ transport
1176
+ });
1177
+ }
1178
+
1179
+ return {
1180
+ async flush() {
1181
+ if (transport && client.pendingEvents() > 0) {
1182
+ state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
1183
+ onError(error);
1184
+ return null;
1185
+ });
1186
+ }
1187
+ return state.pendingFlush;
1188
+ },
1189
+ uninstall() {
1190
+ if (!state.installed) {
1191
+ return;
1192
+ }
1193
+ state.installed = false;
1194
+ for (const [method, original] of originals.entries()) {
1195
+ targetConsole[method] = original;
1196
+ }
1197
+ originals.clear();
1198
+ }
1199
+ };
1200
+ }
1201
+
1202
+ function createConsoleCaptureMethod(config) {
1203
+ return function logBrewConsoleMethod(...args) {
1204
+ config.original.apply(this, args);
1205
+ if (!config.state.installed) {
1206
+ return;
1207
+ }
1208
+ try {
1209
+ config.state.captured += 1;
1210
+ config.client.log(
1211
+ `${config.eventIdPrefix}_${config.state.captured}`,
1212
+ config.timestamp(),
1213
+ logAttributesFromConsoleArgs(config.method, args, {
1214
+ includeErrorStack: config.includeErrorStack,
1215
+ logger: config.logger,
1216
+ metadata: config.metadata
1217
+ })
1218
+ );
1219
+ if (config.flushOnCapture && config.transport) {
1220
+ config.state.pendingFlush = Promise.resolve(config.client.flush(config.transport)).catch((error) => {
1221
+ config.onError(error);
1222
+ return null;
1223
+ });
1224
+ }
1225
+ } catch (error) {
1226
+ config.onError(error);
1227
+ }
1228
+ };
1229
+ }
1230
+
1231
+ function logAttributesFromConsoleArgs(method, args, options = {}) {
1232
+ const logLevel = logbrewLevelFromConsoleMethod(method);
1233
+ const includeErrorStack = options.includeErrorStack === true;
1234
+ const message = consoleMessage(args, includeErrorStack);
1235
+ const metadata = {
1236
+ ...compactMetadata(options.metadata),
1237
+ consoleMethod: method,
1238
+ argumentCount: Array.isArray(args) ? args.length : 0
1239
+ };
1240
+ for (const value of Array.isArray(args) ? args : []) {
1241
+ if (value instanceof Error) {
1242
+ metadata.errorName = value.name || "Error";
1243
+ if (value.message) {
1244
+ metadata.errorMessage = value.message;
1245
+ }
1246
+ if (includeErrorStack && value.stack) {
1247
+ metadata.errorStack = value.stack;
1248
+ }
1249
+ break;
1250
+ }
1251
+ }
1252
+
1253
+ return {
1254
+ message,
1255
+ level: logLevel,
1256
+ ...(options.logger ? { logger: options.logger } : {}),
1257
+ metadata
1258
+ };
1259
+ }
1260
+
1261
+ function createIssueAttributesFromError(error, options = {}) {
1262
+ if (!options || Array.isArray(options) || typeof options !== "object") {
1263
+ throw new SdkError("validation_error", "error issue options must be an object");
1264
+ }
1265
+ const details = errorDetails(error);
1266
+ const stackFrames = javascriptStackFrames(details.stack, options.debugIdMap);
1267
+ const frame = stackFrames[0] ?? null;
1268
+ const source = stringOrUndefined(options.source) ?? "javascript.error";
1269
+ const metadata = {
1270
+ ...compactMetadata(options.metadata),
1271
+ source,
1272
+ errorName: details.name,
1273
+ ...(details.message ? { errorMessage: details.message } : {}),
1274
+ ...(frame ? {
1275
+ errorFrameFile: frame.filename,
1276
+ errorFrameLine: frame.line,
1277
+ errorFrameColumn: frame.column
1278
+ } : {}),
1279
+ ...issueGroupingMetadata(source, details, frame, options.fingerprint),
1280
+ ...errorCauseMetadata(error),
1281
+ ...(stringOrUndefined(options.release) ? { release: options.release } : {}),
1282
+ ...(stringOrUndefined(options.environment) ? { environment: options.environment } : {}),
1283
+ ...(stringOrUndefined(options.service) ? { service: options.service } : {}),
1284
+ ...(stringOrUndefined(options.runtime) ? { runtime: options.runtime } : {}),
1285
+ ...(stringOrUndefined(options.platform) ? { platform: options.platform } : {}),
1286
+ ...traceMetadata(options.trace),
1287
+ ...releaseArtifactMetadata(frame),
1288
+ ...(options.includeErrorStack === true && details.stack ? { errorStack: details.stack } : {})
1289
+ };
1290
+
1291
+ return {
1292
+ title: stringOrUndefined(options.title) ?? details.name,
1293
+ level: normalizeSeverity("issue level", options.level ?? "error"),
1294
+ ...(stringOrUndefined(options.message) ? { message: options.message } : details.message ? { message: details.message } : {}),
1295
+ ...(stackFrames.length > 0 ? { stackFrames } : {}),
1296
+ metadata: compactMetadata(metadata)
1297
+ };
1298
+ }
1299
+
1300
+ function errorDetails(error) {
1301
+ if (error instanceof Error) {
1302
+ return {
1303
+ name: stringOrUndefined(error.name) ?? "Error",
1304
+ message: stringOrUndefined(error.message),
1305
+ stack: typeof error.stack === "string" && error.stack.trim() !== "" ? error.stack : undefined
1306
+ };
1307
+ }
1308
+ if (error && typeof error === "object") {
1309
+ const name = typeof error.name === "string" && error.name.trim() !== "" ? error.name : "Error";
1310
+ const message = typeof error.message === "string" && error.message.trim() !== "" ? error.message : undefined;
1311
+ const stack = typeof error.stack === "string" && error.stack.trim() !== "" ? error.stack : undefined;
1312
+ return { name, message, stack };
1313
+ }
1314
+ if (typeof error === "string" && error.trim() !== "") {
1315
+ return { name: "Error", message: error };
1316
+ }
1317
+ return { name: "Error" };
1318
+ }
1319
+
1320
+ function issueGroupingMetadata(source, details, frame, fingerprint) {
1321
+ const groupingKey = frame
1322
+ ? `${source}:${details.name}:${frame.filename}`
1323
+ : `${source}:${details.name}`;
1324
+ const explicitFingerprint = issueFingerprintOrUndefined(fingerprint);
1325
+ return {
1326
+ issueGroupingKey: groupingKey,
1327
+ issueGroupingSource: explicitFingerprint ? "explicit_fingerprint" : frame ? "error_type_and_frame" : "error_type",
1328
+ ...(explicitFingerprint ? { issueFingerprint: explicitFingerprint } : {})
1329
+ };
1330
+ }
1331
+
1332
+ function issueFingerprintOrUndefined(value) {
1333
+ if (value === undefined || value === null) {
1334
+ return undefined;
1335
+ }
1336
+ if (typeof value !== "string" || value.trim() === "") {
1337
+ throw new SdkError("validation_error", "issue fingerprint must be a non-empty string");
1338
+ }
1339
+ return value.trim();
1340
+ }
1341
+
1342
+ function errorCauseMetadata(error) {
1343
+ const state = {
1344
+ items: [],
1345
+ seen: new Set(),
1346
+ sawExceptionGroup: false,
1347
+ truncated: false
1348
+ };
1349
+ if (isObjectLike(error)) {
1350
+ state.seen.add(error);
1351
+ collectNestedErrorCauses(error, state);
1352
+ }
1353
+ if (state.items.length === 0) {
1354
+ return {};
1355
+ }
1356
+ return {
1357
+ errorCauseCount: state.items.length,
1358
+ errorCauseTypes: state.items.map((item) => item.type).join(","),
1359
+ errorCauseSources: state.items.map((item) => item.source).join(","),
1360
+ ...(state.sawExceptionGroup ? { errorExceptionGroup: true } : {}),
1361
+ ...(state.truncated ? { errorCauseTruncated: true } : {})
1362
+ };
1363
+ }
1364
+
1365
+ function collectNestedErrorCauses(parent, state) {
1366
+ if (!isObjectLike(parent)) {
1367
+ return;
1368
+ }
1369
+ if ("cause" in parent) {
1370
+ collectErrorCause(parent.cause, "cause", state);
1371
+ }
1372
+ if (Array.isArray(parent.errors)) {
1373
+ state.sawExceptionGroup = true;
1374
+ for (const [index, child] of parent.errors.entries()) {
1375
+ collectErrorCause(child, `errors[${index}]`, state);
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ function collectErrorCause(value, source, state) {
1381
+ if (value === undefined || value === null) {
1382
+ return;
1383
+ }
1384
+ if (state.items.length >= MAX_ERROR_CAUSES) {
1385
+ state.truncated = true;
1386
+ return;
1387
+ }
1388
+ if (isObjectLike(value)) {
1389
+ if (state.seen.has(value)) {
1390
+ state.truncated = true;
1391
+ return;
1392
+ }
1393
+ state.seen.add(value);
1394
+ }
1395
+ state.items.push({
1396
+ source,
1397
+ type: errorCauseType(value)
1398
+ });
1399
+ collectNestedErrorCauses(value, state);
1400
+ }
1401
+
1402
+ function errorCauseType(value) {
1403
+ if (isObjectLike(value)) {
1404
+ const constructorName = safeCauseTypeName(value.constructor?.name);
1405
+ if (value instanceof Error) {
1406
+ if (constructorName && constructorName !== "Error") {
1407
+ return constructorName;
1408
+ }
1409
+ const builtinName = BUILTIN_ERROR_NAMES.has(value.name) ? value.name : undefined;
1410
+ return builtinName ?? constructorName ?? "Error";
1411
+ }
1412
+ return constructorName ?? "Object";
1413
+ }
1414
+ return "NonError";
1415
+ }
1416
+
1417
+ function safeCauseTypeName(value) {
1418
+ return typeof value === "string" && /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/u.test(value) ? value : undefined;
1419
+ }
1420
+
1421
+ function isObjectLike(value) {
1422
+ return value !== null && (typeof value === "object" || typeof value === "function");
1423
+ }
1424
+
1425
+ function traceMetadata(trace) {
1426
+ if (trace === undefined || trace === null) {
1427
+ return {};
1428
+ }
1429
+ const normalized = normalizeLogTraceContext(trace);
1430
+ if (!normalized) {
1431
+ return {};
1432
+ }
1433
+ return {
1434
+ traceId: normalized.traceId,
1435
+ spanId: normalized.spanId,
1436
+ ...(normalized.parentSpanId ? { parentSpanId: normalized.parentSpanId } : {}),
1437
+ ...(normalized.sampled !== undefined ? { sampled: normalized.sampled } : {})
1438
+ };
1439
+ }
1440
+
1441
+ function releaseArtifactMetadata(frame) {
1442
+ if (!frame?.debugId) {
1443
+ return {};
1444
+ }
1445
+ return {
1446
+ releaseArtifactType: "sourcemap",
1447
+ releaseArtifactCodeFile: frame.filename,
1448
+ releaseArtifactDebugId: frame.debugId
1449
+ };
1450
+ }
1451
+
1452
+ function logbrewLevelFromConsoleMethod(method) {
1453
+ switch (method) {
1454
+ case "debug":
1455
+ return "info";
1456
+ case "warn":
1457
+ return "warning";
1458
+ case "error":
1459
+ return "error";
1460
+ case "info":
1461
+ case "log":
1462
+ return "info";
1463
+ default:
1464
+ throw new SdkError("validation_error", `console method must be one of: ${Array.from(CONSOLE_METHODS).join(", ")}`);
1465
+ }
1466
+ }
1467
+
1468
+ function createProductActionAttributes(action, options = {}) {
1469
+ const details = productActionDetails(action);
1470
+ return {
1471
+ name: details.name,
1472
+ status: details.status,
1473
+ metadata: compactMetadata({
1474
+ source: "product.action",
1475
+ ...compactMetadata(options.metadata),
1476
+ ...compactMetadata(details.metadata),
1477
+ routeTemplate: sanitizeRouteTemplate(details.routeTemplate),
1478
+ sessionId: stringOrUndefined(details.sessionId),
1479
+ traceId: stringOrUndefined(details.traceId),
1480
+ screen: stringOrUndefined(details.screen),
1481
+ funnel: stringOrUndefined(details.funnel),
1482
+ step: stringOrUndefined(details.step)
1483
+ })
1484
+ };
1485
+ }
1486
+
1487
+ function createNetworkMilestoneAttributes(request, options = {}) {
1488
+ const details = networkMilestoneDetails(request);
1489
+ return {
1490
+ name: details.name,
1491
+ status: details.status,
1492
+ metadata: compactMetadata({
1493
+ source: "network.milestone",
1494
+ ...compactMetadata(options.metadata),
1495
+ ...compactMetadata(details.metadata),
1496
+ routeTemplate: details.routeTemplate,
1497
+ method: details.method,
1498
+ statusCode: details.statusCode,
1499
+ durationMs: details.durationMs,
1500
+ sessionId: stringOrUndefined(details.sessionId),
1501
+ traceId: stringOrUndefined(details.traceId)
1502
+ })
1503
+ };
1504
+ }
1505
+
1506
+ function parseTraceparent(traceparent) {
1507
+ if (typeof traceparent !== "string" || traceparent.trim() === "") {
1508
+ throw new SdkError("validation_error", "traceparent must be non-empty");
1509
+ }
1510
+
1511
+ const match = TRACEPARENT_PATTERN.exec(traceparent.trim());
1512
+ if (!match) {
1513
+ throw new SdkError("validation_error", "traceparent must use W3C version-traceId-parentSpanId-traceFlags format");
1514
+ }
1515
+
1516
+ const version = match[1].toLowerCase();
1517
+ const traceId = match[2].toLowerCase();
1518
+ const parentSpanId = match[3].toLowerCase();
1519
+ const traceFlags = match[4].toLowerCase();
1520
+ if (version === "ff") {
1521
+ throw new SdkError("validation_error", "traceparent version ff is not allowed");
1522
+ }
1523
+ if (traceId === ZERO_TRACE_ID) {
1524
+ throw new SdkError("validation_error", "traceparent traceId must not be all zeros");
1525
+ }
1526
+ if (parentSpanId === ZERO_SPAN_ID) {
1527
+ throw new SdkError("validation_error", "traceparent parentSpanId must not be all zeros");
1528
+ }
1529
+
1530
+ return {
1531
+ version,
1532
+ traceId,
1533
+ parentSpanId,
1534
+ traceFlags,
1535
+ sampled: (Number.parseInt(traceFlags, 16) & 1) === 1
1536
+ };
1537
+ }
1538
+
1539
+ function createTraceparent({ traceId, spanId, traceFlags = "01" }) {
1540
+ requireTraceId(traceId);
1541
+ requireSpanId("spanId", spanId);
1542
+ requireTraceFlags(traceFlags);
1543
+ return `00-${traceId.toLowerCase()}-${spanId.toLowerCase()}-${traceFlags.toLowerCase()}`;
1544
+ }
1545
+
1546
+ function createTraceparentHeaders(input) {
1547
+ return { traceparent: createTraceparent(input) };
1548
+ }
1549
+
1550
+ const {
1551
+ createBaggage,
1552
+ createTraceContextHeaders,
1553
+ createTracestate,
1554
+ parseBaggage,
1555
+ parseTracestate
1556
+ } = buildTraceContextHelpers({
1557
+ SdkError,
1558
+ createTraceparent
1559
+ });
1560
+
1561
+ const createSupportTicketDraft = buildCreateSupportTicketDraft({
1562
+ SdkError,
1563
+ requireAllowedValue,
1564
+ requireNonEmpty,
1565
+ requireTraceId
1566
+ });
1567
+
1568
+ const {
1569
+ createLogBrewOpenTelemetrySpanExporter,
1570
+ createLogBrewOpenTelemetrySpanProcessor,
1571
+ logbrewTraceContextFromCurrentOpenTelemetrySpan,
1572
+ logbrewTraceContextFromOpenTelemetrySpan,
1573
+ logbrewTraceContextFromOpenTelemetrySpanContext,
1574
+ spanAttributesFromOpenTelemetryReadableSpan
1575
+ } = buildOpenTelemetryHelpers({
1576
+ compactMetadata,
1577
+ isMetadataValue,
1578
+ LogBrewClient,
1579
+ maxSpanEvents: MAX_SPAN_EVENTS,
1580
+ maxSpanLinks: MAX_SPAN_LINKS,
1581
+ requireNonEmpty,
1582
+ requireSpanId,
1583
+ requireTraceId,
1584
+ SdkError,
1585
+ stringOrUndefined
1586
+ });
1587
+
1588
+ function spanAttributesFromTraceparent(traceparent, attributes) {
1589
+ if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") {
1590
+ throw new SdkError("validation_error", "span attributes must be an object");
1591
+ }
1592
+ const context = parseTraceparent(traceparent);
1593
+ requireNonEmpty("span name", attributes.name);
1594
+ requireSpanId("spanId", attributes.spanId);
1595
+ requireAllowedValue("span status", attributes.status, SPAN_STATUSES);
1596
+ if (attributes.durationMs !== undefined) {
1597
+ if (typeof attributes.durationMs !== "number" || Number.isNaN(attributes.durationMs) || attributes.durationMs < 0) {
1598
+ throw new SdkError("validation_error", "span durationMs must be non-negative");
1599
+ }
1600
+ }
1601
+ const events = validateSpanEvents(attributes.events);
1602
+ const links = validateSpanLinks(attributes.links);
1603
+
1604
+ return {
1605
+ name: attributes.name,
1606
+ traceId: context.traceId,
1607
+ spanId: attributes.spanId.toLowerCase(),
1608
+ parentSpanId: context.parentSpanId,
1609
+ status: attributes.status,
1610
+ ...(attributes.durationMs !== undefined ? { durationMs: attributes.durationMs } : {}),
1611
+ ...(events !== undefined ? { events } : {}),
1612
+ ...(links !== undefined ? { links } : {}),
1613
+ ...(attributes.metadata !== undefined ? { metadata: compactMetadata(attributes.metadata) } : {})
1614
+ };
1615
+ }
1616
+
1617
+ function createLogBrewPinoDestination(config) {
1618
+ if (!config || typeof config !== "object") {
1619
+ throw new SdkError("validation_error", "Pino destination config must be an object");
1620
+ }
1621
+
1622
+ const client = config.client;
1623
+ if (!(client instanceof LogBrewClient)) {
1624
+ throw new SdkError("validation_error", "Pino destination client must be a LogBrewClient");
1625
+ }
1626
+
1627
+ const transport = config.transport;
1628
+ const flushOnWrite = config.flushOnWrite === true;
1629
+ const includeErrorStack = config.includeErrorStack === true;
1630
+ const logger = config.logger ?? "pino";
1631
+ const metadata = compactMetadata(config.metadata);
1632
+ const timestamp = typeof config.timestamp === "function"
1633
+ ? config.timestamp
1634
+ : () => new Date().toISOString();
1635
+ const eventIdPrefix = config.eventIdPrefix ?? "pino";
1636
+ const onError = typeof config.onError === "function" ? config.onError : () => {};
1637
+ const traceProvider = typeof config.traceProvider === "function" ? config.traceProvider : null;
1638
+ const state = {
1639
+ captured: 0,
1640
+ pendingFlush: Promise.resolve(null)
1641
+ };
1642
+
1643
+ return {
1644
+ write(chunk) {
1645
+ const lines = String(chunk).split(/\r?\n/u).filter((line) => line.trim() !== "");
1646
+ for (const line of lines) {
1647
+ try {
1648
+ const record = JSON.parse(line);
1649
+ state.captured += 1;
1650
+ client.log(
1651
+ `${eventIdPrefix}_${state.captured}`,
1652
+ timestampFromPinoRecord(record, timestamp),
1653
+ logAttributesFromPinoRecord(record, {
1654
+ includeErrorStack,
1655
+ logger,
1656
+ metadata,
1657
+ trace: traceFromProvider(traceProvider, onError)
1658
+ })
1659
+ );
1660
+ if (flushOnWrite && transport) {
1661
+ state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
1662
+ onError(error);
1663
+ return null;
1664
+ });
1665
+ }
1666
+ } catch (error) {
1667
+ onError(error);
1668
+ }
1669
+ }
1670
+ return true;
1671
+ },
1672
+ async flush() {
1673
+ if (transport && client.pendingEvents() > 0) {
1674
+ state.pendingFlush = Promise.resolve(client.flush(transport)).catch((error) => {
1675
+ onError(error);
1676
+ return null;
1677
+ });
1678
+ }
1679
+ return state.pendingFlush;
1680
+ },
1681
+ end() {
1682
+ return this.flush();
1683
+ }
1684
+ };
1685
+ }
1686
+
1687
+ function logAttributesFromPinoRecord(record, options = {}) {
1688
+ if (!record || Array.isArray(record) || typeof record !== "object") {
1689
+ throw new SdkError("validation_error", "Pino record must be an object");
1690
+ }
1691
+
1692
+ const level = logbrewLevelFromPinoLevel(record.level);
1693
+ const metadata = {
1694
+ ...compactMetadata(options.metadata),
1695
+ pinoLevel: pinoLevelLabel(record.level),
1696
+ ...pinoContextMetadata(record),
1697
+ ...traceMetadataFromLogContext(options.trace)
1698
+ };
1699
+ if (typeof record.level === "number" && Number.isFinite(record.level)) {
1700
+ metadata.pinoLevelNumber = record.level;
1701
+ }
1702
+ addPinoErrorMetadata(metadata, record.err ?? record.error, options.includeErrorStack === true);
1703
+
1704
+ return {
1705
+ message: pinoMessage(record),
1706
+ level,
1707
+ ...(options.logger ? { logger: options.logger } : {}),
1708
+ metadata
1709
+ };
1710
+ }
1711
+
1712
+ function timestampFromPinoRecord(record, fallbackTimestamp) {
1713
+ const value = record?.time ?? record?.timestamp;
1714
+ if (typeof value === "number" && Number.isFinite(value)) {
1715
+ return new Date(value).toISOString();
1716
+ }
1717
+ if (typeof value === "string" && value.trim() !== "") {
1718
+ const parsed = new Date(value);
1719
+ if (!Number.isNaN(parsed.valueOf())) {
1720
+ return parsed.toISOString();
1721
+ }
1722
+ return value;
1723
+ }
1724
+ return fallbackTimestamp();
1725
+ }
1726
+
1727
+ function logbrewLevelFromPinoLevel(level) {
1728
+ if (typeof level === "number" && Number.isFinite(level)) {
1729
+ if (level >= 60) {
1730
+ return "critical";
1731
+ }
1732
+ if (level >= 50) {
1733
+ return "error";
1734
+ }
1735
+ if (level >= 40) {
1736
+ return "warning";
1737
+ }
1738
+ if (level >= 30) {
1739
+ return "info";
1740
+ }
1741
+ return "info";
1742
+ }
1743
+
1744
+ switch (String(level).toLowerCase()) {
1745
+ case "trace":
1746
+ case "debug":
1747
+ return "info";
1748
+ case "warn":
1749
+ case "warning":
1750
+ return "warning";
1751
+ case "error":
1752
+ return "error";
1753
+ case "fatal":
1754
+ case "critical":
1755
+ return "critical";
1756
+ case "info":
1757
+ default:
1758
+ return "info";
1759
+ }
1760
+ }
1761
+
1762
+ function pinoLevelLabel(level) {
1763
+ if (typeof level === "string" && level.trim() !== "") {
1764
+ return level;
1765
+ }
1766
+ switch (level) {
1767
+ case 10:
1768
+ return "trace";
1769
+ case 20:
1770
+ return "debug";
1771
+ case 30:
1772
+ return "info";
1773
+ case 40:
1774
+ return "warn";
1775
+ case 50:
1776
+ return "error";
1777
+ case 60:
1778
+ return "fatal";
1779
+ default:
1780
+ return typeof level === "number" && Number.isFinite(level) ? String(level) : "info";
1781
+ }
1782
+ }
1783
+
1784
+ function pinoMessage(record) {
1785
+ if (typeof record.msg === "string" && record.msg.trim() !== "") {
1786
+ return record.msg;
1787
+ }
1788
+ if (typeof record.message === "string" && record.message.trim() !== "") {
1789
+ return record.message;
1790
+ }
1791
+ const error = record.err ?? record.error;
1792
+ if (error && typeof error === "object" && typeof error.message === "string" && error.message.trim() !== "") {
1793
+ return error.message;
1794
+ }
1795
+ return "pino event";
1796
+ }
1797
+
1798
+ function pinoContextMetadata(record) {
1799
+ const metadata = {};
1800
+ for (const [key, value] of Object.entries(record)) {
1801
+ if (!PINO_RESERVED_FIELDS.has(key) && isMetadataValue(value)) {
1802
+ metadata[`context.${key}`] = value;
1803
+ }
1804
+ }
1805
+ return metadata;
1806
+ }
1807
+
1808
+ function addPinoErrorMetadata(metadata, error, includeErrorStack) {
1809
+ if (!error) {
1810
+ return;
1811
+ }
1812
+ if (error instanceof Error) {
1813
+ metadata.errorName = error.name || "Error";
1814
+ if (error.message) {
1815
+ metadata.errorMessage = error.message;
1816
+ }
1817
+ if (includeErrorStack && error.stack) {
1818
+ metadata.errorStack = error.stack;
1819
+ }
1820
+ return;
1821
+ }
1822
+ if (typeof error === "object") {
1823
+ const name = error.type ?? error.name;
1824
+ const message = error.message;
1825
+ const stack = error.stack;
1826
+ if (typeof name === "string" && name.trim() !== "") {
1827
+ metadata.errorName = name;
1828
+ }
1829
+ if (typeof message === "string" && message.trim() !== "") {
1830
+ metadata.errorMessage = message;
1831
+ }
1832
+ if (includeErrorStack && typeof stack === "string" && stack.trim() !== "") {
1833
+ metadata.errorStack = stack;
1834
+ }
1835
+ return;
1836
+ }
1837
+ if (typeof error === "string" && error.trim() !== "") {
1838
+ metadata.errorMessage = error;
1839
+ }
1840
+ }
1841
+
1842
+ function requireNonEmpty(label, value) {
1843
+ if (typeof value !== "string" || value.trim() === "") {
1844
+ throw new SdkError("validation_error", `${label} must be non-empty`);
1845
+ }
1846
+ }
1847
+
1848
+ function requireAllowedValue(label, value, allowedValues) {
1849
+ requireNonEmpty(label, value);
1850
+ if (!allowedValues.has(value)) {
1851
+ throw new SdkError(
1852
+ "validation_error",
1853
+ `${label} must be one of: ${Array.from(allowedValues).join(", ")}`
1854
+ );
1855
+ }
1856
+ }
1857
+
1858
+ function requireFiniteNumber(label, value) {
1859
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1860
+ throw new SdkError("validation_error", `${label} must be a finite number`);
1861
+ }
1862
+ }
1863
+
1864
+ function requirePositiveInteger(label, value) {
1865
+ if (!Number.isSafeInteger(value) || value <= 0) {
1866
+ throw new SdkError("validation_error", `${label} must be a positive integer`);
1867
+ }
1868
+ }
1869
+
1870
+ function requireNonNegativeInteger(label, value) {
1871
+ if (!Number.isSafeInteger(value) || value < 0) {
1872
+ throw new SdkError("validation_error", `${label} must be a non-negative integer`);
1873
+ }
1874
+ }
1875
+
1876
+ function retryAfterMsOrUndefined(value) {
1877
+ if (value === undefined) {
1878
+ return undefined;
1879
+ }
1880
+ return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
1881
+ }
1882
+
1883
+ function requireTraceId(traceId) {
1884
+ if (typeof traceId !== "string" || !/^[0-9a-fA-F]{32}$/u.test(traceId)) {
1885
+ throw new SdkError("validation_error", "traceId must be 32 lowercase or uppercase hex characters");
1886
+ }
1887
+ if (traceId.toLowerCase() === ZERO_TRACE_ID) {
1888
+ throw new SdkError("validation_error", "traceId must not be all zeros");
1889
+ }
1890
+ }
1891
+
1892
+ function requireSpanId(label, spanId) {
1893
+ if (typeof spanId !== "string" || !/^[0-9a-fA-F]{16}$/u.test(spanId)) {
1894
+ throw new SdkError("validation_error", `${label} must be 16 lowercase or uppercase hex characters`);
1895
+ }
1896
+ if (spanId.toLowerCase() === ZERO_SPAN_ID) {
1897
+ throw new SdkError("validation_error", `${label} must not be all zeros`);
1898
+ }
1899
+ }
1900
+
1901
+ function requireTraceFlags(traceFlags) {
1902
+ if (typeof traceFlags !== "string" || !/^[0-9a-fA-F]{2}$/u.test(traceFlags)) {
1903
+ throw new SdkError("validation_error", "traceFlags must be 2 lowercase or uppercase hex characters");
1904
+ }
1905
+ }
1906
+
1907
+ function requireTimestamp(timestamp) {
1908
+ requireNonEmpty("timestamp", timestamp);
1909
+ if (timestamp.endsWith("Z")) {
1910
+ return;
1911
+ }
1912
+ const timePortion = timestamp.split("T")[1];
1913
+ if (timePortion && (timePortion.includes("+") || /.+-.+/.test(timePortion))) {
1914
+ return;
1915
+ }
1916
+ throw new SdkError(
1917
+ "validation_error",
1918
+ `timestamp must include a timezone offset: ${timestamp}`
1919
+ );
1920
+ }
1921
+
1922
+ function cloneMetadata(metadata) {
1923
+ if (metadata === undefined) {
1924
+ return undefined;
1925
+ }
1926
+ if (!metadata || Array.isArray(metadata) || typeof metadata !== "object") {
1927
+ throw new SdkError("validation_error", "metadata must be an object");
1928
+ }
1929
+ return { ...metadata };
1930
+ }
1931
+
1932
+ function cloneSpanEvents(events) {
1933
+ return events.map((event) => event.metadata === undefined
1934
+ ? { ...event }
1935
+ : { ...event, metadata: { ...event.metadata } });
1936
+ }
1937
+
1938
+ function cloneSpanLinks(links) {
1939
+ return links.map((link) => link.metadata === undefined
1940
+ ? { ...link }
1941
+ : { ...link, metadata: { ...link.metadata } });
1942
+ }
1943
+
1944
+ function cloneEvent(event) {
1945
+ const attributes = { ...event.attributes };
1946
+ if (event.attributes.metadata !== undefined) {
1947
+ attributes.metadata = { ...event.attributes.metadata };
1948
+ }
1949
+ if (Array.isArray(event.attributes.events)) {
1950
+ attributes.events = cloneSpanEvents(event.attributes.events);
1951
+ }
1952
+ if (Array.isArray(event.attributes.links)) {
1953
+ attributes.links = cloneSpanLinks(event.attributes.links);
1954
+ }
1955
+ return { ...event, attributes };
1956
+ }
1957
+
1958
+ function validateRelease(attributes) {
1959
+ requireNonEmpty("release version", attributes.version);
1960
+ if (attributes.commit !== undefined) {
1961
+ requireNonEmpty("release commit", attributes.commit);
1962
+ }
1963
+ return withMetadata({
1964
+ version: attributes.version,
1965
+ ...(attributes.commit ? { commit: attributes.commit } : {}),
1966
+ ...(attributes.notes !== undefined ? { notes: attributes.notes } : {})
1967
+ }, attributes.metadata);
1968
+ }
1969
+
1970
+ function validateEnvironment(attributes) {
1971
+ requireNonEmpty("environment name", attributes.name);
1972
+ return withMetadata({
1973
+ name: attributes.name,
1974
+ ...(attributes.region !== undefined ? { region: attributes.region } : {})
1975
+ }, attributes.metadata);
1976
+ }
1977
+
1978
+ function validateIssue(attributes) {
1979
+ requireNonEmpty("issue title", attributes.title);
1980
+ const level = normalizeSeverity("issue level", attributes.level);
1981
+ const stackFrames = validateIssueStackFrames(attributes.stackFrames);
1982
+ return withMetadata({
1983
+ title: attributes.title,
1984
+ level,
1985
+ ...(attributes.message !== undefined ? { message: attributes.message } : {}),
1986
+ ...(stackFrames !== undefined ? { stackFrames } : {})
1987
+ }, attributes.metadata);
1988
+ }
1989
+
1990
+ function validateLog(attributes) {
1991
+ requireNonEmpty("log message", attributes.message);
1992
+ const level = normalizeSeverity("log level", attributes.level);
1993
+ return withMetadata({
1994
+ message: attributes.message,
1995
+ level,
1996
+ ...(attributes.logger !== undefined ? { logger: attributes.logger } : {})
1997
+ }, attributes.metadata);
1998
+ }
1999
+
2000
+ function normalizeSeverity(label, value) {
2001
+ requireAllowedValue(label, value, SEVERITY_VALUES);
2002
+ return SEVERITY_ALIASES.get(value);
2003
+ }
2004
+
2005
+ function validateSpan(attributes) {
2006
+ requireNonEmpty("span name", attributes.name);
2007
+ requireNonEmpty("span traceId", attributes.traceId);
2008
+ requireNonEmpty("span spanId", attributes.spanId);
2009
+ requireAllowedValue("span status", attributes.status, SPAN_STATUSES);
2010
+ if (attributes.parentSpanId !== undefined) {
2011
+ requireNonEmpty("span parentSpanId", attributes.parentSpanId);
2012
+ }
2013
+ if (attributes.durationMs !== undefined) {
2014
+ if (typeof attributes.durationMs !== "number" || Number.isNaN(attributes.durationMs) || attributes.durationMs < 0) {
2015
+ throw new SdkError("validation_error", "span durationMs must be non-negative");
2016
+ }
2017
+ }
2018
+ const events = validateSpanEvents(attributes.events);
2019
+ const links = validateSpanLinks(attributes.links);
2020
+ return withMetadata({
2021
+ name: attributes.name,
2022
+ traceId: attributes.traceId,
2023
+ spanId: attributes.spanId,
2024
+ status: attributes.status,
2025
+ ...(attributes.parentSpanId !== undefined ? { parentSpanId: attributes.parentSpanId } : {}),
2026
+ ...(attributes.durationMs !== undefined ? { durationMs: attributes.durationMs } : {}),
2027
+ ...(events !== undefined ? { events } : {}),
2028
+ ...(links !== undefined ? { links } : {})
2029
+ }, attributes.metadata);
2030
+ }
2031
+
2032
+ function validateSpanEvents(events) {
2033
+ if (events === undefined) {
2034
+ return undefined;
2035
+ }
2036
+ if (!Array.isArray(events)) {
2037
+ throw new SdkError("validation_error", "span events must be an array");
2038
+ }
2039
+ if (events.length > MAX_SPAN_EVENTS) {
2040
+ throw new SdkError("validation_error", `span events must contain at most ${MAX_SPAN_EVENTS} entries`);
2041
+ }
2042
+ if (events.length === 0) {
2043
+ return undefined;
2044
+ }
2045
+
2046
+ return events.map((event) => {
2047
+ if (!event || Array.isArray(event) || typeof event !== "object") {
2048
+ throw new SdkError("validation_error", "span event must be an object");
2049
+ }
2050
+ requireNonEmpty("span event name", event.name);
2051
+ if (event.timestamp !== undefined) {
2052
+ requireTimestamp(event.timestamp);
2053
+ }
2054
+ const summary = {
2055
+ name: event.name,
2056
+ ...(event.timestamp !== undefined ? { timestamp: event.timestamp } : {})
2057
+ };
2058
+ if (event.metadata !== undefined) {
2059
+ const metadata = compactMetadata(event.metadata);
2060
+ if (Object.keys(metadata).length > 0) {
2061
+ summary.metadata = metadata;
2062
+ }
2063
+ }
2064
+ return summary;
2065
+ });
2066
+ }
2067
+
2068
+ function validateSpanLinks(links) {
2069
+ if (links === undefined) {
2070
+ return undefined;
2071
+ }
2072
+ if (!Array.isArray(links)) {
2073
+ throw new SdkError("validation_error", "span links must be an array");
2074
+ }
2075
+ if (links.length > MAX_SPAN_LINKS) {
2076
+ throw new SdkError("validation_error", `span links must contain at most ${MAX_SPAN_LINKS} entries`);
2077
+ }
2078
+ if (links.length === 0) {
2079
+ return undefined;
2080
+ }
2081
+
2082
+ return links.map((link) => {
2083
+ if (!link || Array.isArray(link) || typeof link !== "object") {
2084
+ throw new SdkError("validation_error", "span link must be an object");
2085
+ }
2086
+ requireTraceId(link.traceId);
2087
+ requireSpanId("span link spanId", link.spanId);
2088
+ if (link.sampled !== undefined && typeof link.sampled !== "boolean") {
2089
+ throw new SdkError("validation_error", "span link sampled must be a boolean");
2090
+ }
2091
+ const summary = {
2092
+ traceId: link.traceId.toLowerCase(),
2093
+ spanId: link.spanId.toLowerCase(),
2094
+ ...(link.sampled !== undefined ? { sampled: link.sampled } : {})
2095
+ };
2096
+ if (link.metadata !== undefined) {
2097
+ const metadata = compactMetadata(link.metadata);
2098
+ if (Object.keys(metadata).length > 0) {
2099
+ summary.metadata = metadata;
2100
+ }
2101
+ }
2102
+ return summary;
2103
+ });
2104
+ }
2105
+
2106
+ function validateAction(attributes) {
2107
+ requireNonEmpty("action name", attributes.name);
2108
+ requireAllowedValue("action status", attributes.status, ACTION_STATUSES);
2109
+ return withMetadata({
2110
+ name: attributes.name,
2111
+ status: attributes.status
2112
+ }, attributes.metadata);
2113
+ }
2114
+
2115
+ function validateMetric(attributes) {
2116
+ requireNonEmpty("metric name", attributes.name);
2117
+ requireAllowedValue("metric kind", attributes.kind, METRIC_KINDS);
2118
+ requireFiniteNumber("metric value", attributes.value);
2119
+ requireNonEmpty("metric unit", attributes.unit);
2120
+
2121
+ const allowedTemporalities = METRIC_TEMPORALITIES_BY_KIND.get(attributes.kind);
2122
+ requireAllowedValue(`metric temporality for ${attributes.kind}`, attributes.temporality, allowedTemporalities);
2123
+ if (NON_NEGATIVE_METRIC_KINDS.has(attributes.kind) && attributes.value < 0) {
2124
+ throw new SdkError("validation_error", `metric ${attributes.kind} value must be non-negative`);
2125
+ }
2126
+
2127
+ return withMetadata({
2128
+ name: attributes.name,
2129
+ kind: attributes.kind,
2130
+ value: attributes.value,
2131
+ unit: attributes.unit,
2132
+ temporality: attributes.temporality
2133
+ }, attributes.metadata);
2134
+ }
2135
+
2136
+ function productActionDetails(action) {
2137
+ if (typeof action === "string") {
2138
+ return { name: action, status: "success" };
2139
+ }
2140
+ if (!action || Array.isArray(action) || typeof action !== "object") {
2141
+ throw new SdkError("validation_error", "product action must be a string or object");
2142
+ }
2143
+ requireNonEmpty("product action name", action.name);
2144
+ const status = action.status === undefined ? "success" : action.status;
2145
+ requireAllowedValue("product action status", status, ACTION_STATUSES);
2146
+ return {
2147
+ funnel: action.funnel,
2148
+ metadata: action.metadata,
2149
+ name: action.name,
2150
+ routeTemplate: action.routeTemplate,
2151
+ screen: action.screen,
2152
+ sessionId: action.sessionId,
2153
+ status,
2154
+ step: action.step,
2155
+ traceId: action.traceId
2156
+ };
2157
+ }
2158
+
2159
+ function networkMilestoneDetails(request) {
2160
+ if (typeof request === "string") {
2161
+ return networkMilestoneDetails({ routeTemplate: request });
2162
+ }
2163
+ if (!request || Array.isArray(request) || typeof request !== "object") {
2164
+ throw new SdkError("validation_error", "network milestone must be a string or object");
2165
+ }
2166
+
2167
+ const routeTemplate = sanitizeRouteTemplate(request.routeTemplate);
2168
+ requireNonEmpty("network milestone routeTemplate", routeTemplate);
2169
+ const method = normalizeHttpMethod(request.method);
2170
+ const statusCode = statusCodeOrUndefined(request.statusCode);
2171
+ const status = request.status === undefined
2172
+ ? statusFromStatusCode(statusCode)
2173
+ : request.status;
2174
+ requireAllowedValue("network milestone status", status, ACTION_STATUSES);
2175
+ const durationMs = nonNegativeNumberOrUndefined("network milestone durationMs", request.durationMs);
2176
+ const name = typeof request.name === "string" && request.name.trim() !== ""
2177
+ ? request.name
2178
+ : `network.${method.toLowerCase()} ${routeTemplate}`;
2179
+
2180
+ return {
2181
+ durationMs,
2182
+ metadata: request.metadata,
2183
+ method,
2184
+ name,
2185
+ routeTemplate,
2186
+ sessionId: request.sessionId,
2187
+ status,
2188
+ statusCode,
2189
+ traceId: request.traceId
2190
+ };
2191
+ }
2192
+
2193
+ function sanitizeRouteTemplate(routeTemplate) {
2194
+ if (routeTemplate === undefined) {
2195
+ return undefined;
2196
+ }
2197
+ if (typeof routeTemplate !== "string") {
2198
+ throw new SdkError("validation_error", "routeTemplate must be a string");
2199
+ }
2200
+ const trimmed = routeTemplate.trim();
2201
+ if (trimmed === "") {
2202
+ return "";
2203
+ }
2204
+ try {
2205
+ const url = new URL(trimmed, "https://logbrew.example");
2206
+ return url.pathname || "/";
2207
+ } catch {
2208
+ return trimmed.split(/[?#]/u)[0] || "/";
2209
+ }
2210
+ }
2211
+
2212
+ function normalizeHttpMethod(method) {
2213
+ const value = method === undefined ? "GET" : method;
2214
+ if (typeof value !== "string" || value.trim() === "") {
2215
+ throw new SdkError("validation_error", "network milestone method must be a non-empty string");
2216
+ }
2217
+ const normalized = value.trim().toUpperCase();
2218
+ if (!/^[A-Z][A-Z0-9_-]*$/u.test(normalized)) {
2219
+ throw new SdkError("validation_error", "network milestone method must be a valid HTTP method");
2220
+ }
2221
+ return normalized;
2222
+ }
2223
+
2224
+ function statusCodeOrUndefined(value) {
2225
+ if (value === undefined) {
2226
+ return undefined;
2227
+ }
2228
+ if (!Number.isInteger(value) || value < 100 || value > 599) {
2229
+ throw new SdkError("validation_error", "network milestone statusCode must be an integer from 100 to 599");
2230
+ }
2231
+ return value;
2232
+ }
2233
+
2234
+ function statusFromStatusCode(statusCode) {
2235
+ if (statusCode !== undefined && statusCode >= 400) {
2236
+ return "failure";
2237
+ }
2238
+ return "success";
2239
+ }
2240
+
2241
+ function nonNegativeNumberOrUndefined(label, value) {
2242
+ if (value === undefined) {
2243
+ return undefined;
2244
+ }
2245
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
2246
+ throw new SdkError("validation_error", `${label} must be a non-negative number`);
2247
+ }
2248
+ return value;
2249
+ }
2250
+
2251
+ function stringOrUndefined(value) {
2252
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
2253
+ }
2254
+
2255
+ function withMetadata(attributes, metadata) {
2256
+ const safeMetadata = cloneMetadata(metadata);
2257
+ return safeMetadata === undefined
2258
+ ? attributes
2259
+ : { ...attributes, metadata: safeMetadata };
2260
+ }
2261
+
2262
+ function normalizeConsoleLevels(levels) {
2263
+ const requestedLevels = levels === undefined ? DEFAULT_CONSOLE_LEVELS : levels;
2264
+ if (!Array.isArray(requestedLevels)) {
2265
+ throw new SdkError("validation_error", "console capture levels must be an array");
2266
+ }
2267
+ const normalized = [];
2268
+ for (const method of requestedLevels) {
2269
+ if (!CONSOLE_METHODS.has(method)) {
2270
+ throw new SdkError("validation_error", `console method must be one of: ${Array.from(CONSOLE_METHODS).join(", ")}`);
2271
+ }
2272
+ if (!normalized.includes(method)) {
2273
+ normalized.push(method);
2274
+ }
2275
+ }
2276
+ return normalized;
2277
+ }
2278
+
2279
+ function consoleMessage(args, includeErrorStack) {
2280
+ const values = Array.isArray(args) ? args : [];
2281
+ const message = values.map((value) => formatConsoleArgument(value, includeErrorStack)).join(" ");
2282
+ return message.trim() === "" ? "console event" : message;
2283
+ }
2284
+
2285
+ function formatConsoleArgument(value, includeErrorStack) {
2286
+ if (value instanceof Error) {
2287
+ if (includeErrorStack && value.stack) {
2288
+ return value.stack;
2289
+ }
2290
+ return value.message ? `${value.name}: ${value.message}` : value.name;
2291
+ }
2292
+ if (typeof value === "string") {
2293
+ return value;
2294
+ }
2295
+ if (typeof value === "number" || typeof value === "boolean" || value === null || value === undefined) {
2296
+ return String(value);
2297
+ }
2298
+ if (typeof value === "bigint" || typeof value === "symbol") {
2299
+ return String(value);
2300
+ }
2301
+ try {
2302
+ const json = JSON.stringify(value);
2303
+ return json === undefined ? String(value) : json;
2304
+ } catch {
2305
+ return Object.prototype.toString.call(value);
2306
+ }
2307
+ }
2308
+
2309
+ module.exports = {
2310
+ createBaggage,
2311
+ createIssueAttributesFromError,
2312
+ createNetworkMilestoneAttributes,
2313
+ createProductActionAttributes,
2314
+ createLogBrewOpenTelemetrySpanExporter,
2315
+ createLogBrewOpenTelemetrySpanProcessor,
2316
+ createSupportTicketDraft,
2317
+ createTraceContextHeaders,
2318
+ createTraceparent,
2319
+ createTraceparentHeaders,
2320
+ createTracestate,
2321
+ createLogBrewPinoDestination,
2322
+ installLogBrewConsoleCapture,
2323
+ LogBrewClient,
2324
+ logbrewTraceContextFromCurrentOpenTelemetrySpan,
2325
+ logbrewTraceContextFromOpenTelemetrySpan,
2326
+ logbrewTraceContextFromOpenTelemetrySpanContext,
2327
+ logAttributesFromConsoleArgs,
2328
+ logAttributesFromPinoRecord,
2329
+ logbrewLevelFromConsoleMethod,
2330
+ parseBaggage,
2331
+ parseTraceparent,
2332
+ parseTracestate,
2333
+ RecordingTransport,
2334
+ SdkError,
2335
+ spanAttributesFromOpenTelemetryReadableSpan,
2336
+ spanAttributesFromTraceparent,
2337
+ TransportError
2338
+ };