@statly/observe 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2837 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/span.ts
34
+ var Span, TraceContext;
35
+ var init_span = __esm({
36
+ "src/span.ts"() {
37
+ "use strict";
38
+ Span = class {
39
+ constructor(name, context, tags) {
40
+ this._status = "ok" /* OK */;
41
+ this._tags = {};
42
+ this._metadata = {};
43
+ this._finished = false;
44
+ this.name = name;
45
+ this.context = context;
46
+ this.startTime = Date.now();
47
+ if (tags) this._tags = { ...tags };
48
+ }
49
+ /**
50
+ * Finish the span and calculate duration
51
+ */
52
+ finish(endTime) {
53
+ if (this._finished) return;
54
+ this._endTime = endTime || Date.now();
55
+ this._durationMs = this._endTime - this.startTime;
56
+ this._finished = true;
57
+ }
58
+ setTag(key, value) {
59
+ this._tags[key] = value;
60
+ return this;
61
+ }
62
+ setMetadata(key, value) {
63
+ this._metadata[key] = value;
64
+ return this;
65
+ }
66
+ setStatus(status) {
67
+ this._status = status;
68
+ return this;
69
+ }
70
+ get status() {
71
+ return this._status;
72
+ }
73
+ get tags() {
74
+ return { ...this._tags };
75
+ }
76
+ get durationMs() {
77
+ return this._durationMs;
78
+ }
79
+ toDict() {
80
+ return {
81
+ name: this.name,
82
+ traceId: this.context.traceId,
83
+ spanId: this.context.spanId,
84
+ parentId: this.context.parentId,
85
+ startTime: this.startTime,
86
+ endTime: this._endTime,
87
+ durationMs: this._durationMs,
88
+ status: this._status,
89
+ tags: this._tags,
90
+ metadata: this._metadata
91
+ };
92
+ }
93
+ };
94
+ TraceContext = class {
95
+ static getActiveSpan() {
96
+ return this.currentSpan;
97
+ }
98
+ static setActiveSpan(span) {
99
+ this.currentSpan = span;
100
+ }
101
+ };
102
+ TraceContext.currentSpan = null;
103
+ }
104
+ });
105
+
106
+ // src/telemetry.ts
107
+ var telemetry_exports = {};
108
+ __export(telemetry_exports, {
109
+ TelemetryProvider: () => TelemetryProvider,
110
+ trace: () => trace
111
+ });
112
+ async function trace(name, operation, tags) {
113
+ const provider = TelemetryProvider.getInstance();
114
+ const span = provider.startSpan(name, tags);
115
+ try {
116
+ const result = await operation(span);
117
+ return result;
118
+ } catch (error2) {
119
+ span.setStatus("error" /* ERROR */);
120
+ span.setTag("error", "true");
121
+ if (error2 instanceof Error) {
122
+ span.setTag("exception.type", error2.name);
123
+ span.setTag("exception.message", error2.message);
124
+ }
125
+ throw error2;
126
+ } finally {
127
+ provider.finishSpan(span);
128
+ }
129
+ }
130
+ var TelemetryProvider;
131
+ var init_telemetry = __esm({
132
+ "src/telemetry.ts"() {
133
+ "use strict";
134
+ init_span();
135
+ TelemetryProvider = class _TelemetryProvider {
136
+ constructor() {
137
+ this.client = null;
138
+ }
139
+ static getInstance() {
140
+ if (!_TelemetryProvider.instance) {
141
+ _TelemetryProvider.instance = new _TelemetryProvider();
142
+ }
143
+ return _TelemetryProvider.instance;
144
+ }
145
+ setClient(client2) {
146
+ this.client = client2;
147
+ }
148
+ /**
149
+ * Start a new span
150
+ */
151
+ startSpan(name, tags) {
152
+ const parent = TraceContext.getActiveSpan();
153
+ const traceId = parent ? parent.context.traceId : this.generateId();
154
+ const parentId = parent ? parent.context.spanId : null;
155
+ const span = new Span(name, {
156
+ traceId,
157
+ spanId: this.generateId(),
158
+ parentId
159
+ }, tags);
160
+ TraceContext.setActiveSpan(span);
161
+ return span;
162
+ }
163
+ /**
164
+ * Finish and report a span
165
+ */
166
+ finishSpan(span) {
167
+ span.finish();
168
+ if (TraceContext.getActiveSpan() === span) {
169
+ TraceContext.setActiveSpan(null);
170
+ }
171
+ if (this.client) {
172
+ this.client.captureSpan(span);
173
+ }
174
+ }
175
+ generateId() {
176
+ return Math.random().toString(16).substring(2, 18);
177
+ }
178
+ };
179
+ }
180
+ });
181
+
182
+ // src/index.ts
183
+ var index_exports = {};
184
+ __export(index_exports, {
185
+ AIFeatures: () => AIFeatures,
186
+ ConsoleDestination: () => ConsoleDestination,
187
+ DEFAULT_LEVELS: () => DEFAULT_LEVELS,
188
+ EXTENDED_LEVELS: () => EXTENDED_LEVELS,
189
+ FileDestination: () => FileDestination,
190
+ LOG_LEVELS: () => LOG_LEVELS,
191
+ Logger: () => Logger,
192
+ ObserveDestination: () => ObserveDestination,
193
+ REDACTED: () => REDACTED,
194
+ SCRUB_PATTERNS: () => SCRUB_PATTERNS,
195
+ SENSITIVE_KEYS: () => SENSITIVE_KEYS,
196
+ Scrubber: () => Scrubber,
197
+ Statly: () => Statly,
198
+ StatlyClient: () => StatlyClient,
199
+ addBreadcrumb: () => addBreadcrumb,
200
+ captureException: () => captureException,
201
+ captureMessage: () => captureMessage,
202
+ captureNextJsError: () => captureNextJsError,
203
+ captureSpan: () => captureSpan,
204
+ close: () => close,
205
+ createRequestCapture: () => createRequestCapture,
206
+ expressErrorHandler: () => expressErrorHandler,
207
+ flush: () => flush,
208
+ formatJson: () => formatJson,
209
+ formatJsonPretty: () => formatJsonPretty,
210
+ formatPretty: () => formatPretty,
211
+ getClient: () => getClient,
212
+ getConsoleMethod: () => getConsoleMethod,
213
+ getDefaultLogger: () => getDefaultLogger,
214
+ init: () => init,
215
+ isSensitiveKey: () => isSensitiveKey,
216
+ logAudit: () => audit,
217
+ logDebug: () => debug,
218
+ logError: () => error,
219
+ logFatal: () => fatal,
220
+ logInfo: () => info,
221
+ logTrace: () => trace2,
222
+ logWarn: () => warn,
223
+ requestHandler: () => requestHandler,
224
+ setDefaultLogger: () => setDefaultLogger,
225
+ setTag: () => setTag,
226
+ setTags: () => setTags,
227
+ setUser: () => setUser,
228
+ startSpan: () => startSpan,
229
+ statlyFastifyPlugin: () => statlyFastifyPlugin,
230
+ statlyPlugin: () => statlyPlugin,
231
+ trace: () => trace3,
232
+ withStatly: () => withStatly,
233
+ withStatlyGetServerSideProps: () => withStatlyGetServerSideProps,
234
+ withStatlyGetStaticProps: () => withStatlyGetStaticProps,
235
+ withStatlyPagesApi: () => withStatlyPagesApi,
236
+ withStatlyServerAction: () => withStatlyServerAction
237
+ });
238
+ module.exports = __toCommonJS(index_exports);
239
+
240
+ // src/transport.ts
241
+ var Transport = class {
242
+ constructor(options) {
243
+ this.queue = [];
244
+ this.isSending = false;
245
+ this.maxQueueSize = 100;
246
+ this.flushInterval = 5e3;
247
+ this.dsn = options.dsn;
248
+ this.debug = options.debug ?? false;
249
+ this.endpoint = this.parseEndpoint(options.dsn);
250
+ this.startFlushTimer();
251
+ }
252
+ parseEndpoint(dsn) {
253
+ try {
254
+ const url = new URL(dsn);
255
+ return `${url.protocol}//${url.host}/api/v1/observe/ingest`;
256
+ } catch {
257
+ return `https://statly.live/api/v1/observe/ingest`;
258
+ }
259
+ }
260
+ startFlushTimer() {
261
+ if (typeof window !== "undefined") {
262
+ this.flushTimer = setInterval(() => {
263
+ this.flush();
264
+ }, this.flushInterval);
265
+ }
266
+ }
267
+ /**
268
+ * Add an event to the queue
269
+ */
270
+ enqueue(event) {
271
+ if (this.queue.length >= this.maxQueueSize) {
272
+ this.queue.shift();
273
+ if (this.debug) {
274
+ console.warn("[Statly] Event queue full, dropping oldest event");
275
+ }
276
+ }
277
+ this.queue.push(event);
278
+ if (this.queue.length >= 10) {
279
+ this.flush();
280
+ }
281
+ }
282
+ /**
283
+ * Send a single event immediately
284
+ */
285
+ async send(event) {
286
+ return this.sendBatch([event]);
287
+ }
288
+ /**
289
+ * Flush all queued events
290
+ */
291
+ async flush() {
292
+ if (this.isSending || this.queue.length === 0) {
293
+ return;
294
+ }
295
+ this.isSending = true;
296
+ const events = [...this.queue];
297
+ this.queue = [];
298
+ try {
299
+ await this.sendBatch(events);
300
+ } catch (error2) {
301
+ this.queue = [...events, ...this.queue].slice(0, this.maxQueueSize);
302
+ if (this.debug) {
303
+ console.error("[Statly] Failed to send events:", error2);
304
+ }
305
+ } finally {
306
+ this.isSending = false;
307
+ }
308
+ }
309
+ /**
310
+ * Send a batch of events
311
+ */
312
+ async sendBatch(events) {
313
+ if (events.length === 0) {
314
+ return { success: true };
315
+ }
316
+ const payload = events.length === 1 ? events[0] : { events };
317
+ try {
318
+ const response = await fetch(this.endpoint, {
319
+ method: "POST",
320
+ headers: {
321
+ "Content-Type": "application/json",
322
+ "X-Statly-DSN": this.dsn
323
+ },
324
+ body: JSON.stringify(payload),
325
+ // Use keepalive for better reliability during page unload
326
+ keepalive: true
327
+ });
328
+ if (!response.ok) {
329
+ const errorText = await response.text().catch(() => "Unknown error");
330
+ if (this.debug) {
331
+ console.error("[Statly] API error:", response.status, errorText);
332
+ }
333
+ return {
334
+ success: false,
335
+ status: response.status,
336
+ error: errorText
337
+ };
338
+ }
339
+ if (this.debug) {
340
+ console.log(`[Statly] Sent ${events.length} event(s)`);
341
+ }
342
+ return { success: true, status: response.status };
343
+ } catch (error2) {
344
+ if (this.debug) {
345
+ console.error("[Statly] Network error:", error2);
346
+ }
347
+ return {
348
+ success: false,
349
+ error: error2 instanceof Error ? error2.message : "Network error"
350
+ };
351
+ }
352
+ }
353
+ /**
354
+ * Clean up resources
355
+ */
356
+ destroy() {
357
+ if (this.flushTimer) {
358
+ clearInterval(this.flushTimer);
359
+ }
360
+ this.flush();
361
+ }
362
+ };
363
+
364
+ // src/breadcrumbs.ts
365
+ var BreadcrumbManager = class {
366
+ constructor(maxBreadcrumbs = 100) {
367
+ this.breadcrumbs = [];
368
+ this.maxBreadcrumbs = maxBreadcrumbs;
369
+ }
370
+ /**
371
+ * Add a breadcrumb
372
+ */
373
+ add(breadcrumb) {
374
+ const crumb = {
375
+ timestamp: Date.now(),
376
+ ...breadcrumb
377
+ };
378
+ this.breadcrumbs.push(crumb);
379
+ if (this.breadcrumbs.length > this.maxBreadcrumbs) {
380
+ this.breadcrumbs = this.breadcrumbs.slice(-this.maxBreadcrumbs);
381
+ }
382
+ }
383
+ /**
384
+ * Get all breadcrumbs
385
+ */
386
+ getAll() {
387
+ return [...this.breadcrumbs];
388
+ }
389
+ /**
390
+ * Clear all breadcrumbs
391
+ */
392
+ clear() {
393
+ this.breadcrumbs = [];
394
+ }
395
+ /**
396
+ * Set maximum breadcrumbs to keep
397
+ */
398
+ setMaxBreadcrumbs(max) {
399
+ this.maxBreadcrumbs = max;
400
+ if (this.breadcrumbs.length > max) {
401
+ this.breadcrumbs = this.breadcrumbs.slice(-max);
402
+ }
403
+ }
404
+ };
405
+
406
+ // src/integrations/global-handlers.ts
407
+ var GlobalHandlers = class {
408
+ constructor(options = {}) {
409
+ this.originalOnError = null;
410
+ this.originalOnUnhandledRejection = null;
411
+ this.errorCallback = null;
412
+ this.handleUnhandledRejection = (event) => {
413
+ if (!this.errorCallback) {
414
+ return;
415
+ }
416
+ let error2;
417
+ if (event.reason instanceof Error) {
418
+ error2 = event.reason;
419
+ } else if (typeof event.reason === "string") {
420
+ error2 = new Error(event.reason);
421
+ } else {
422
+ error2 = new Error("Unhandled Promise Rejection");
423
+ error2.reason = event.reason;
424
+ }
425
+ this.errorCallback(error2, {
426
+ mechanism: { type: "onunhandledrejection", handled: false }
427
+ });
428
+ };
429
+ this.options = {
430
+ onerror: options.onerror !== false,
431
+ onunhandledrejection: options.onunhandledrejection !== false
432
+ };
433
+ }
434
+ /**
435
+ * Install global error handlers
436
+ */
437
+ install(callback) {
438
+ this.errorCallback = callback;
439
+ if (typeof window === "undefined") {
440
+ return;
441
+ }
442
+ if (this.options.onerror) {
443
+ this.installOnError();
444
+ }
445
+ if (this.options.onunhandledrejection) {
446
+ this.installOnUnhandledRejection();
447
+ }
448
+ }
449
+ /**
450
+ * Uninstall global error handlers
451
+ */
452
+ uninstall() {
453
+ if (typeof window === "undefined") {
454
+ return;
455
+ }
456
+ if (this.originalOnError !== null) {
457
+ window.onerror = this.originalOnError;
458
+ this.originalOnError = null;
459
+ }
460
+ if (this.originalOnUnhandledRejection !== null) {
461
+ window.removeEventListener("unhandledrejection", this.handleUnhandledRejection);
462
+ this.originalOnUnhandledRejection = null;
463
+ }
464
+ this.errorCallback = null;
465
+ }
466
+ installOnError() {
467
+ this.originalOnError = window.onerror;
468
+ window.onerror = (message, source, lineno, colno, error2) => {
469
+ if (this.originalOnError) {
470
+ this.originalOnError.call(window, message, source, lineno, colno, error2);
471
+ }
472
+ if (this.errorCallback) {
473
+ const errorObj = error2 || new Error(String(message));
474
+ if (!error2 && source) {
475
+ errorObj.filename = source;
476
+ errorObj.lineno = lineno;
477
+ errorObj.colno = colno;
478
+ }
479
+ this.errorCallback(errorObj, {
480
+ mechanism: { type: "onerror", handled: false },
481
+ source,
482
+ lineno,
483
+ colno
484
+ });
485
+ }
486
+ return false;
487
+ };
488
+ }
489
+ installOnUnhandledRejection() {
490
+ this.originalOnUnhandledRejection = this.handleUnhandledRejection.bind(this);
491
+ window.addEventListener("unhandledrejection", this.handleUnhandledRejection);
492
+ }
493
+ };
494
+
495
+ // src/integrations/console.ts
496
+ var ConsoleIntegration = class {
497
+ constructor() {
498
+ this.originalMethods = {};
499
+ this.callback = null;
500
+ this.levels = ["debug", "info", "warn", "error", "log"];
501
+ }
502
+ /**
503
+ * Install console breadcrumb tracking
504
+ */
505
+ install(callback, levels) {
506
+ this.callback = callback;
507
+ if (levels) {
508
+ this.levels = levels;
509
+ }
510
+ if (typeof console === "undefined") {
511
+ return;
512
+ }
513
+ for (const level of this.levels) {
514
+ this.wrapConsoleMethod(level);
515
+ }
516
+ }
517
+ /**
518
+ * Uninstall console breadcrumb tracking
519
+ */
520
+ uninstall() {
521
+ if (typeof console === "undefined") {
522
+ return;
523
+ }
524
+ for (const level of this.levels) {
525
+ if (this.originalMethods[level]) {
526
+ console[level] = this.originalMethods[level];
527
+ delete this.originalMethods[level];
528
+ }
529
+ }
530
+ this.callback = null;
531
+ }
532
+ wrapConsoleMethod(level) {
533
+ const originalMethod = console[level];
534
+ if (!originalMethod) {
535
+ return;
536
+ }
537
+ this.originalMethods[level] = originalMethod;
538
+ console[level] = (...args) => {
539
+ if (this.callback) {
540
+ this.callback({
541
+ category: "console",
542
+ message: this.formatArgs(args),
543
+ level: this.mapLevel(level),
544
+ data: args.length > 1 ? { arguments: args } : void 0
545
+ });
546
+ }
547
+ originalMethod.apply(console, args);
548
+ };
549
+ }
550
+ formatArgs(args) {
551
+ return args.map((arg) => {
552
+ if (typeof arg === "string") {
553
+ return arg;
554
+ }
555
+ if (arg instanceof Error) {
556
+ return arg.message;
557
+ }
558
+ try {
559
+ return JSON.stringify(arg);
560
+ } catch {
561
+ return String(arg);
562
+ }
563
+ }).join(" ");
564
+ }
565
+ mapLevel(consoleLevel) {
566
+ switch (consoleLevel) {
567
+ case "debug":
568
+ return "debug";
569
+ case "info":
570
+ case "log":
571
+ return "info";
572
+ case "warn":
573
+ return "warning";
574
+ case "error":
575
+ return "error";
576
+ default:
577
+ return "info";
578
+ }
579
+ }
580
+ };
581
+
582
+ // src/client.ts
583
+ init_telemetry();
584
+ var SDK_NAME = "@statly/observe-sdk";
585
+ var SDK_VERSION = "0.1.0";
586
+ var StatlyClient = class {
587
+ constructor(options) {
588
+ this.user = null;
589
+ this.initialized = false;
590
+ this.options = this.mergeOptions(options);
591
+ this.transport = new Transport({
592
+ dsn: this.options.dsn,
593
+ debug: this.options.debug
594
+ });
595
+ this.breadcrumbs = new BreadcrumbManager(this.options.maxBreadcrumbs);
596
+ this.globalHandlers = new GlobalHandlers();
597
+ this.consoleIntegration = new ConsoleIntegration();
598
+ TelemetryProvider.getInstance().setClient(this);
599
+ }
600
+ mergeOptions(options) {
601
+ return {
602
+ dsn: options.dsn,
603
+ release: options.release ?? "",
604
+ environment: options.environment ?? this.detectEnvironment(),
605
+ debug: options.debug ?? false,
606
+ sampleRate: options.sampleRate ?? 1,
607
+ maxBreadcrumbs: options.maxBreadcrumbs ?? 100,
608
+ autoCapture: options.autoCapture !== false,
609
+ captureConsole: options.captureConsole !== false,
610
+ captureNetwork: options.captureNetwork ?? false,
611
+ tags: options.tags ?? {},
612
+ beforeSend: options.beforeSend ?? ((e) => e)
613
+ };
614
+ }
615
+ detectEnvironment() {
616
+ if (typeof window !== "undefined") {
617
+ if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") {
618
+ return "development";
619
+ }
620
+ if (window.location.hostname.includes("staging") || window.location.hostname.includes("stage")) {
621
+ return "staging";
622
+ }
623
+ }
624
+ return "production";
625
+ }
626
+ /**
627
+ * Initialize the SDK
628
+ */
629
+ init() {
630
+ if (this.initialized) {
631
+ if (this.options.debug) {
632
+ console.warn("[Statly] SDK already initialized");
633
+ }
634
+ return;
635
+ }
636
+ this.initialized = true;
637
+ if (this.options.autoCapture) {
638
+ this.globalHandlers.install((error2, context) => {
639
+ this.captureError(error2, context);
640
+ });
641
+ }
642
+ if (this.options.captureConsole) {
643
+ this.consoleIntegration.install((breadcrumb) => {
644
+ this.breadcrumbs.add(breadcrumb);
645
+ });
646
+ }
647
+ this.addBreadcrumb({
648
+ category: "navigation",
649
+ message: "SDK initialized",
650
+ level: "info"
651
+ });
652
+ if (this.options.debug) {
653
+ console.log("[Statly] SDK initialized", {
654
+ environment: this.options.environment,
655
+ release: this.options.release
656
+ });
657
+ }
658
+ }
659
+ /**
660
+ * Capture an exception/error
661
+ */
662
+ captureException(error2, context) {
663
+ let errorObj;
664
+ if (error2 instanceof Error) {
665
+ errorObj = error2;
666
+ } else if (typeof error2 === "string") {
667
+ errorObj = new Error(error2);
668
+ } else {
669
+ errorObj = new Error("Unknown error");
670
+ errorObj.originalError = error2;
671
+ }
672
+ return this.captureError(errorObj, context);
673
+ }
674
+ /**
675
+ * Capture a message
676
+ */
677
+ captureMessage(message, level = "info") {
678
+ const event = this.buildEvent({
679
+ message,
680
+ level
681
+ });
682
+ return this.sendEvent(event);
683
+ }
684
+ /**
685
+ * Capture a completed span
686
+ */
687
+ captureSpan(span) {
688
+ const event = this.buildEvent({
689
+ message: `Span: ${span.name}`,
690
+ level: "span",
691
+ span: span.toDict()
692
+ });
693
+ return this.sendEvent(event);
694
+ }
695
+ /**
696
+ * Start a new tracing span
697
+ */
698
+ startSpan(name, tags) {
699
+ return TelemetryProvider.getInstance().startSpan(name, tags);
700
+ }
701
+ /**
702
+ * Execute a function within a trace span
703
+ */
704
+ async trace(name, operation, tags) {
705
+ const { trace: traceFn } = await Promise.resolve().then(() => (init_telemetry(), telemetry_exports));
706
+ return traceFn(name, operation, tags);
707
+ }
708
+ /**
709
+ * Internal method to capture an error
710
+ */
711
+ captureError(error2, context) {
712
+ if (Math.random() > this.options.sampleRate) {
713
+ return "";
714
+ }
715
+ const event = this.buildEvent({
716
+ message: error2.message,
717
+ level: "error",
718
+ stack: error2.stack,
719
+ exception: {
720
+ type: error2.name,
721
+ value: error2.message,
722
+ stacktrace: this.parseStackTrace(error2.stack)
723
+ },
724
+ extra: context
725
+ });
726
+ return this.sendEvent(event);
727
+ }
728
+ /**
729
+ * Build a complete event from partial data
730
+ */
731
+ buildEvent(partial) {
732
+ const event = {
733
+ message: partial.message || "Unknown error",
734
+ timestamp: Date.now(),
735
+ level: partial.level || "error",
736
+ environment: this.options.environment,
737
+ release: this.options.release || void 0,
738
+ url: typeof window !== "undefined" ? window.location.href : void 0,
739
+ user: this.user || void 0,
740
+ tags: { ...this.options.tags, ...partial.tags },
741
+ extra: partial.extra,
742
+ breadcrumbs: this.breadcrumbs.getAll(),
743
+ browser: this.getBrowserInfo(),
744
+ os: this.getOSInfo(),
745
+ sdk: {
746
+ name: SDK_NAME,
747
+ version: SDK_VERSION
748
+ },
749
+ ...partial
750
+ };
751
+ return event;
752
+ }
753
+ /**
754
+ * Parse a stack trace string into structured frames
755
+ */
756
+ parseStackTrace(stack) {
757
+ if (!stack) {
758
+ return void 0;
759
+ }
760
+ const frames = [];
761
+ const lines = stack.split("\n");
762
+ for (const line of lines) {
763
+ const chromeMatch = line.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
764
+ if (chromeMatch) {
765
+ frames.push({
766
+ function: chromeMatch[1] || "<anonymous>",
767
+ filename: chromeMatch[2],
768
+ lineno: parseInt(chromeMatch[3], 10),
769
+ colno: parseInt(chromeMatch[4], 10)
770
+ });
771
+ continue;
772
+ }
773
+ const firefoxMatch = line.match(/^(.+?)@(.+?):(\d+):(\d+)$/);
774
+ if (firefoxMatch) {
775
+ frames.push({
776
+ function: firefoxMatch[1] || "<anonymous>",
777
+ filename: firefoxMatch[2],
778
+ lineno: parseInt(firefoxMatch[3], 10),
779
+ colno: parseInt(firefoxMatch[4], 10)
780
+ });
781
+ }
782
+ }
783
+ return frames.length > 0 ? { frames } : void 0;
784
+ }
785
+ /**
786
+ * Send an event to the server
787
+ */
788
+ sendEvent(event) {
789
+ const processed = this.options.beforeSend(event);
790
+ if (!processed) {
791
+ if (this.options.debug) {
792
+ console.log("[Statly] Event dropped by beforeSend");
793
+ }
794
+ return "";
795
+ }
796
+ const eventId = this.generateEventId();
797
+ this.breadcrumbs.add({
798
+ category: "statly",
799
+ message: `Captured ${event.level}: ${event.message.slice(0, 50)}`,
800
+ level: "info"
801
+ });
802
+ this.transport.enqueue(processed);
803
+ if (this.options.debug) {
804
+ console.log("[Statly] Event captured:", eventId, event.message);
805
+ }
806
+ return eventId;
807
+ }
808
+ generateEventId() {
809
+ return crypto.randomUUID?.() || "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
810
+ const r = Math.random() * 16 | 0;
811
+ const v = c === "x" ? r : r & 3 | 8;
812
+ return v.toString(16);
813
+ });
814
+ }
815
+ /**
816
+ * Set user context
817
+ */
818
+ setUser(user) {
819
+ this.user = user;
820
+ if (this.options.debug && user) {
821
+ console.log("[Statly] User set:", user.id || user.email);
822
+ }
823
+ }
824
+ /**
825
+ * Set a single tag
826
+ */
827
+ setTag(key, value) {
828
+ this.options.tags[key] = value;
829
+ }
830
+ /**
831
+ * Set multiple tags
832
+ */
833
+ setTags(tags) {
834
+ Object.assign(this.options.tags, tags);
835
+ }
836
+ /**
837
+ * Add a breadcrumb
838
+ */
839
+ addBreadcrumb(breadcrumb) {
840
+ this.breadcrumbs.add(breadcrumb);
841
+ }
842
+ /**
843
+ * Get browser info
844
+ */
845
+ getBrowserInfo() {
846
+ if (typeof navigator === "undefined") {
847
+ return void 0;
848
+ }
849
+ const ua = navigator.userAgent;
850
+ let name = "Unknown";
851
+ let version = "";
852
+ if (ua.includes("Firefox/")) {
853
+ name = "Firefox";
854
+ version = ua.split("Firefox/")[1]?.split(" ")[0] || "";
855
+ } else if (ua.includes("Chrome/")) {
856
+ name = "Chrome";
857
+ version = ua.split("Chrome/")[1]?.split(" ")[0] || "";
858
+ } else if (ua.includes("Safari/") && !ua.includes("Chrome")) {
859
+ name = "Safari";
860
+ version = ua.split("Version/")[1]?.split(" ")[0] || "";
861
+ } else if (ua.includes("Edge/") || ua.includes("Edg/")) {
862
+ name = "Edge";
863
+ version = ua.split(/Edg?e?\//)[1]?.split(" ")[0] || "";
864
+ }
865
+ return { name, version };
866
+ }
867
+ /**
868
+ * Get OS info
869
+ */
870
+ getOSInfo() {
871
+ if (typeof navigator === "undefined") {
872
+ return void 0;
873
+ }
874
+ const ua = navigator.userAgent;
875
+ let name = "Unknown";
876
+ let version = "";
877
+ if (ua.includes("Windows")) {
878
+ name = "Windows";
879
+ const match = ua.match(/Windows NT (\d+\.\d+)/);
880
+ if (match) version = match[1];
881
+ } else if (ua.includes("Mac OS X")) {
882
+ name = "macOS";
883
+ const match = ua.match(/Mac OS X (\d+[._]\d+)/);
884
+ if (match) version = match[1].replace("_", ".");
885
+ } else if (ua.includes("Linux")) {
886
+ name = "Linux";
887
+ } else if (ua.includes("Android")) {
888
+ name = "Android";
889
+ const match = ua.match(/Android (\d+\.\d+)/);
890
+ if (match) version = match[1];
891
+ } else if (ua.includes("iOS") || ua.includes("iPhone") || ua.includes("iPad")) {
892
+ name = "iOS";
893
+ const match = ua.match(/OS (\d+_\d+)/);
894
+ if (match) version = match[1].replace("_", ".");
895
+ }
896
+ return { name, version };
897
+ }
898
+ /**
899
+ * Flush pending events and clean up
900
+ */
901
+ async close() {
902
+ this.globalHandlers.uninstall();
903
+ this.consoleIntegration.uninstall();
904
+ await this.transport.flush();
905
+ this.transport.destroy();
906
+ this.initialized = false;
907
+ }
908
+ /**
909
+ * Force flush pending events
910
+ */
911
+ async flush() {
912
+ await this.transport.flush();
913
+ }
914
+ };
915
+
916
+ // src/integrations/express.ts
917
+ function requestHandler() {
918
+ return (req, res, next) => {
919
+ req.statlyContext = {
920
+ transactionName: `${req.method} ${req.path || req.url}`,
921
+ startTime: Date.now()
922
+ };
923
+ Statly.addBreadcrumb({
924
+ category: "http",
925
+ message: `${req.method} ${req.originalUrl || req.url}`,
926
+ level: "info",
927
+ data: {
928
+ method: req.method,
929
+ url: req.originalUrl || req.url
930
+ }
931
+ });
932
+ if (req.user) {
933
+ Statly.setUser({
934
+ id: req.user.id?.toString(),
935
+ email: req.user.email?.toString()
936
+ });
937
+ }
938
+ res.on("finish", () => {
939
+ const duration = req.statlyContext?.startTime ? Date.now() - req.statlyContext.startTime : void 0;
940
+ Statly.addBreadcrumb({
941
+ category: "http",
942
+ message: `Response ${res.statusCode}`,
943
+ level: res.statusCode >= 400 ? "error" : "info",
944
+ data: {
945
+ statusCode: res.statusCode,
946
+ duration
947
+ }
948
+ });
949
+ });
950
+ next();
951
+ };
952
+ }
953
+ function expressErrorHandler(options = {}) {
954
+ return (err, req, res, next) => {
955
+ const error2 = err instanceof Error ? err : new Error(String(err));
956
+ if (options.shouldHandleError && !options.shouldHandleError(error2)) {
957
+ return next(err);
958
+ }
959
+ const context = {
960
+ request: {
961
+ method: req.method,
962
+ url: req.originalUrl || req.url,
963
+ headers: sanitizeHeaders(req.headers),
964
+ query: req.query,
965
+ data: sanitizeBody(req.body)
966
+ }
967
+ };
968
+ if (req.ip) {
969
+ context.ip = req.ip;
970
+ }
971
+ if (req.user) {
972
+ Statly.setUser({
973
+ id: req.user.id?.toString(),
974
+ email: req.user.email?.toString()
975
+ });
976
+ }
977
+ if (req.statlyContext?.transactionName) {
978
+ Statly.setTag("transaction", req.statlyContext.transactionName);
979
+ }
980
+ Statly.captureException(error2, context);
981
+ next(err);
982
+ };
983
+ }
984
+ function sanitizeHeaders(headers) {
985
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
986
+ const sanitized = {};
987
+ for (const [key, value] of Object.entries(headers)) {
988
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
989
+ sanitized[key] = "[Filtered]";
990
+ } else {
991
+ sanitized[key] = value;
992
+ }
993
+ }
994
+ return sanitized;
995
+ }
996
+ function sanitizeBody(body) {
997
+ if (!body || typeof body !== "object") {
998
+ return body;
999
+ }
1000
+ const sensitiveFields = ["password", "secret", "token", "apiKey", "api_key", "credit_card", "creditCard", "ssn"];
1001
+ const sanitized = {};
1002
+ for (const [key, value] of Object.entries(body)) {
1003
+ if (sensitiveFields.some((field) => key.toLowerCase().includes(field.toLowerCase()))) {
1004
+ sanitized[key] = "[Filtered]";
1005
+ } else if (typeof value === "object" && value !== null) {
1006
+ sanitized[key] = sanitizeBody(value);
1007
+ } else {
1008
+ sanitized[key] = value;
1009
+ }
1010
+ }
1011
+ return sanitized;
1012
+ }
1013
+
1014
+ // src/integrations/nextjs.ts
1015
+ function withStatlyPagesApi(handler) {
1016
+ return async (req, res) => {
1017
+ return Statly.trace(`${req.method} ${req.url}`, async (span) => {
1018
+ span.setTag("component", "nextjs-pages-api");
1019
+ span.setTag("http.method", req.method || "GET");
1020
+ span.setTag("http.url", req.url || "unknown");
1021
+ Statly.addBreadcrumb({
1022
+ category: "http",
1023
+ message: `${req.method} ${req.url}`,
1024
+ level: "info",
1025
+ data: {
1026
+ method: req.method,
1027
+ url: req.url
1028
+ }
1029
+ });
1030
+ try {
1031
+ const result = await handler(req, res);
1032
+ return result;
1033
+ } catch (error2) {
1034
+ const context = {
1035
+ request: {
1036
+ method: req.method,
1037
+ url: req.url,
1038
+ headers: sanitizeHeaders2(req.headers),
1039
+ query: req.query
1040
+ }
1041
+ };
1042
+ Statly.captureException(error2, context);
1043
+ throw error2;
1044
+ }
1045
+ });
1046
+ };
1047
+ }
1048
+ function withStatly(handler) {
1049
+ const wrappedHandler = async (request, context) => {
1050
+ return Statly.trace(`${request.method} ${request.nextUrl?.pathname || request.url}`, async (span) => {
1051
+ span.setTag("component", "nextjs-app-router");
1052
+ span.setTag("http.method", request.method);
1053
+ span.setTag("http.url", request.nextUrl?.pathname || request.url);
1054
+ Statly.addBreadcrumb({
1055
+ category: "http",
1056
+ message: `${request.method} ${request.nextUrl?.pathname || request.url}`,
1057
+ level: "info",
1058
+ data: {
1059
+ method: request.method,
1060
+ url: request.nextUrl?.pathname || request.url
1061
+ }
1062
+ });
1063
+ try {
1064
+ const result = await handler(request, context);
1065
+ if (result instanceof Response) {
1066
+ span.setTag("http.status_code", result.status.toString());
1067
+ }
1068
+ return result;
1069
+ } catch (error2) {
1070
+ const headers = {};
1071
+ request.headers.forEach((value, key) => {
1072
+ headers[key] = value;
1073
+ });
1074
+ const errorContext = {
1075
+ request: {
1076
+ method: request.method,
1077
+ url: request.nextUrl?.pathname || request.url,
1078
+ headers: sanitizeHeaders2(headers),
1079
+ searchParams: request.nextUrl?.searchParams?.toString()
1080
+ }
1081
+ };
1082
+ if (context?.params) {
1083
+ try {
1084
+ errorContext.params = await context.params;
1085
+ } catch {
1086
+ }
1087
+ }
1088
+ Statly.captureException(error2, errorContext);
1089
+ throw error2;
1090
+ }
1091
+ });
1092
+ };
1093
+ return wrappedHandler;
1094
+ }
1095
+ function captureNextJsError(error2, context) {
1096
+ return Statly.captureException(error2, {
1097
+ ...context,
1098
+ digest: error2.digest,
1099
+ source: "nextjs-error-boundary"
1100
+ });
1101
+ }
1102
+ function withStatlyGetServerSideProps(handler) {
1103
+ return async (context) => {
1104
+ try {
1105
+ return await handler(context);
1106
+ } catch (error2) {
1107
+ Statly.captureException(error2, {
1108
+ source: "getServerSideProps",
1109
+ url: context.req?.url || context.resolvedUrl
1110
+ });
1111
+ throw error2;
1112
+ }
1113
+ };
1114
+ }
1115
+ function withStatlyGetStaticProps(handler) {
1116
+ return async (context) => {
1117
+ try {
1118
+ return await handler(context);
1119
+ } catch (error2) {
1120
+ Statly.captureException(error2, {
1121
+ source: "getStaticProps",
1122
+ params: context.params
1123
+ });
1124
+ throw error2;
1125
+ }
1126
+ };
1127
+ }
1128
+ function withStatlyServerAction(action, actionName) {
1129
+ return async (...args) => {
1130
+ return Statly.trace(`Action: ${actionName || "unknown"}`, async (span) => {
1131
+ span.setTag("component", "nextjs-server-action");
1132
+ span.setTag("action.name", actionName || "unknown");
1133
+ Statly.addBreadcrumb({
1134
+ category: "action",
1135
+ message: `Server action: ${actionName || "unknown"}`,
1136
+ level: "info"
1137
+ });
1138
+ try {
1139
+ return await action(...args);
1140
+ } catch (error2) {
1141
+ Statly.captureException(error2, {
1142
+ source: "server-action",
1143
+ actionName
1144
+ });
1145
+ throw error2;
1146
+ }
1147
+ });
1148
+ };
1149
+ }
1150
+ function sanitizeHeaders2(headers) {
1151
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
1152
+ const sanitized = {};
1153
+ for (const [key, value] of Object.entries(headers)) {
1154
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
1155
+ sanitized[key] = "[Filtered]";
1156
+ } else {
1157
+ sanitized[key] = value;
1158
+ }
1159
+ }
1160
+ return sanitized;
1161
+ }
1162
+
1163
+ // src/integrations/fastify.ts
1164
+ function statlyFastifyPlugin(fastify, options, done) {
1165
+ const {
1166
+ captureValidationErrors = true,
1167
+ shouldCapture,
1168
+ skipStatusCodes = [400, 401, 403, 404]
1169
+ } = options;
1170
+ fastify.addHook("onRequest", (request, _reply, hookDone) => {
1171
+ request.statlyStartTime = Date.now();
1172
+ Statly.addBreadcrumb({
1173
+ category: "http",
1174
+ message: `${request.method} ${request.routerPath || request.url}`,
1175
+ level: "info",
1176
+ data: {
1177
+ method: request.method,
1178
+ url: request.url,
1179
+ routerPath: request.routerPath,
1180
+ requestId: request.id
1181
+ }
1182
+ });
1183
+ hookDone();
1184
+ });
1185
+ fastify.addHook("onResponse", (request, reply, hookDone) => {
1186
+ const startTime = request.statlyStartTime;
1187
+ const duration = startTime ? Date.now() - startTime : void 0;
1188
+ Statly.addBreadcrumb({
1189
+ category: "http",
1190
+ message: `Response ${reply.statusCode}`,
1191
+ level: reply.statusCode >= 400 ? "error" : "info",
1192
+ data: {
1193
+ statusCode: reply.statusCode,
1194
+ duration,
1195
+ requestId: request.id
1196
+ }
1197
+ });
1198
+ hookDone();
1199
+ });
1200
+ fastify.setErrorHandler((error2, request, reply) => {
1201
+ const statusCode = error2.statusCode || 500;
1202
+ if (skipStatusCodes.includes(statusCode)) {
1203
+ throw error2;
1204
+ }
1205
+ if (!captureValidationErrors && error2.validation) {
1206
+ throw error2;
1207
+ }
1208
+ if (shouldCapture && !shouldCapture(error2)) {
1209
+ throw error2;
1210
+ }
1211
+ const context = {
1212
+ request: {
1213
+ id: request.id,
1214
+ method: request.method,
1215
+ url: request.url,
1216
+ routerPath: request.routerPath,
1217
+ headers: sanitizeHeaders3(request.headers),
1218
+ query: request.query,
1219
+ params: request.params
1220
+ },
1221
+ error: {
1222
+ statusCode: error2.statusCode,
1223
+ code: error2.code
1224
+ }
1225
+ };
1226
+ if (request.ip) {
1227
+ context.ip = request.ip;
1228
+ }
1229
+ if (error2.validation) {
1230
+ context.validation = error2.validation;
1231
+ }
1232
+ Statly.setTag("http.method", request.method);
1233
+ Statly.setTag("http.url", request.routerPath || request.url);
1234
+ Statly.setTag("http.status_code", String(statusCode));
1235
+ Statly.captureException(error2, context);
1236
+ throw error2;
1237
+ });
1238
+ done();
1239
+ }
1240
+ var statlyPlugin = statlyFastifyPlugin;
1241
+ function createRequestCapture(request) {
1242
+ return (error2, additionalContext) => {
1243
+ const context = {
1244
+ request: {
1245
+ id: request.id,
1246
+ method: request.method,
1247
+ url: request.url,
1248
+ routerPath: request.routerPath
1249
+ },
1250
+ ...additionalContext
1251
+ };
1252
+ return Statly.captureException(error2, context);
1253
+ };
1254
+ }
1255
+ function sanitizeHeaders3(headers) {
1256
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
1257
+ const sanitized = {};
1258
+ for (const [key, value] of Object.entries(headers)) {
1259
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
1260
+ sanitized[key] = "[Filtered]";
1261
+ } else {
1262
+ sanitized[key] = value;
1263
+ }
1264
+ }
1265
+ return sanitized;
1266
+ }
1267
+
1268
+ // src/logger/types.ts
1269
+ var LOG_LEVELS = {
1270
+ trace: 0,
1271
+ debug: 1,
1272
+ info: 2,
1273
+ warn: 3,
1274
+ error: 4,
1275
+ fatal: 5,
1276
+ audit: 6
1277
+ // Special: always logged, never sampled
1278
+ };
1279
+ var DEFAULT_LEVELS = ["debug", "info", "warn", "error", "fatal"];
1280
+ var EXTENDED_LEVELS = ["trace", "debug", "info", "warn", "error", "fatal", "audit"];
1281
+
1282
+ // src/logger/scrubbing/patterns.ts
1283
+ var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
1284
+ "password",
1285
+ "passwd",
1286
+ "pwd",
1287
+ "secret",
1288
+ "api_key",
1289
+ "apikey",
1290
+ "api-key",
1291
+ "token",
1292
+ "access_token",
1293
+ "accesstoken",
1294
+ "refresh_token",
1295
+ "auth",
1296
+ "authorization",
1297
+ "bearer",
1298
+ "credential",
1299
+ "credentials",
1300
+ "private_key",
1301
+ "privatekey",
1302
+ "private-key",
1303
+ "secret_key",
1304
+ "secretkey",
1305
+ "secret-key",
1306
+ "session_id",
1307
+ "sessionid",
1308
+ "session-id",
1309
+ "session",
1310
+ "cookie",
1311
+ "x-api-key",
1312
+ "x-auth-token",
1313
+ "x-access-token"
1314
+ ]);
1315
+ var SCRUB_PATTERNS = {
1316
+ apiKey: {
1317
+ regex: /(?:api[_-]?key|apikey)\s*[=:]\s*["']?([a-zA-Z0-9_-]{20,})["']?/gi,
1318
+ description: "API keys in various formats"
1319
+ },
1320
+ password: {
1321
+ regex: /(?:password|passwd|pwd|secret)\s*[=:]\s*["']?([^"'\s]{3,})["']?/gi,
1322
+ description: "Passwords and secrets"
1323
+ },
1324
+ token: {
1325
+ regex: /(?:bearer\s+|token\s*[=:]\s*["']?)([a-zA-Z0-9._-]{20,})["']?/gi,
1326
+ description: "Bearer tokens and auth tokens"
1327
+ },
1328
+ creditCard: {
1329
+ // Visa, Mastercard, Amex, Discover, etc.
1330
+ regex: /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})\b/g,
1331
+ description: "Credit card numbers"
1332
+ },
1333
+ ssn: {
1334
+ regex: /\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/g,
1335
+ description: "US Social Security Numbers"
1336
+ },
1337
+ email: {
1338
+ regex: /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g,
1339
+ description: "Email addresses"
1340
+ },
1341
+ ipAddress: {
1342
+ regex: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,
1343
+ description: "IPv4 addresses"
1344
+ },
1345
+ awsKey: {
1346
+ regex: /(?:AKIA|ABIA|ACCA)[A-Z0-9]{16}/g,
1347
+ description: "AWS Access Key IDs"
1348
+ },
1349
+ privateKey: {
1350
+ regex: /-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA )?PRIVATE KEY-----/g,
1351
+ description: "Private keys in PEM format"
1352
+ },
1353
+ jwt: {
1354
+ regex: /eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,
1355
+ description: "JSON Web Tokens"
1356
+ }
1357
+ };
1358
+ var REDACTED = "[REDACTED]";
1359
+ function isSensitiveKey(key) {
1360
+ const lowerKey = key.toLowerCase();
1361
+ return SENSITIVE_KEYS.has(lowerKey);
1362
+ }
1363
+
1364
+ // src/logger/scrubbing/scrubber.ts
1365
+ var Scrubber = class {
1366
+ constructor(config = {}) {
1367
+ this.enabled = config.enabled !== false;
1368
+ this.patterns = /* @__PURE__ */ new Map();
1369
+ this.customPatterns = config.customPatterns || [];
1370
+ this.allowlist = new Set((config.allowlist || []).map((k) => k.toLowerCase()));
1371
+ this.customScrubber = config.customScrubber;
1372
+ const patternNames = config.patterns || [
1373
+ "apiKey",
1374
+ "password",
1375
+ "token",
1376
+ "creditCard",
1377
+ "ssn",
1378
+ "awsKey",
1379
+ "privateKey",
1380
+ "jwt"
1381
+ ];
1382
+ for (const name of patternNames) {
1383
+ const pattern = SCRUB_PATTERNS[name];
1384
+ if (pattern) {
1385
+ this.patterns.set(name, new RegExp(pattern.regex.source, pattern.regex.flags));
1386
+ }
1387
+ }
1388
+ }
1389
+ /**
1390
+ * Scrub sensitive data from a value
1391
+ */
1392
+ scrub(value) {
1393
+ if (!this.enabled) {
1394
+ return value;
1395
+ }
1396
+ return this.scrubValue(value, "");
1397
+ }
1398
+ /**
1399
+ * Scrub a log message string
1400
+ */
1401
+ scrubMessage(message) {
1402
+ if (!this.enabled) {
1403
+ return message;
1404
+ }
1405
+ let result = message;
1406
+ for (const [, regex] of this.patterns) {
1407
+ result = result.replace(regex, REDACTED);
1408
+ }
1409
+ for (const regex of this.customPatterns) {
1410
+ result = result.replace(regex, REDACTED);
1411
+ }
1412
+ return result;
1413
+ }
1414
+ /**
1415
+ * Recursively scrub sensitive data
1416
+ */
1417
+ scrubValue(value, key) {
1418
+ if (key && this.allowlist.has(key.toLowerCase())) {
1419
+ return value;
1420
+ }
1421
+ if (this.customScrubber && key) {
1422
+ const result = this.customScrubber(key, value);
1423
+ if (result !== value) {
1424
+ return result;
1425
+ }
1426
+ }
1427
+ if (key && isSensitiveKey(key)) {
1428
+ return REDACTED;
1429
+ }
1430
+ if (value === null || value === void 0) {
1431
+ return value;
1432
+ }
1433
+ if (typeof value === "string") {
1434
+ return this.scrubString(value);
1435
+ }
1436
+ if (Array.isArray(value)) {
1437
+ return value.map((item, index) => this.scrubValue(item, String(index)));
1438
+ }
1439
+ if (typeof value === "object") {
1440
+ return this.scrubObject(value);
1441
+ }
1442
+ return value;
1443
+ }
1444
+ /**
1445
+ * Scrub sensitive patterns from a string
1446
+ */
1447
+ scrubString(value) {
1448
+ let result = value;
1449
+ for (const [, regex] of this.patterns) {
1450
+ regex.lastIndex = 0;
1451
+ result = result.replace(regex, REDACTED);
1452
+ }
1453
+ for (const regex of this.customPatterns) {
1454
+ const newRegex = new RegExp(regex.source, regex.flags);
1455
+ result = result.replace(newRegex, REDACTED);
1456
+ }
1457
+ return result;
1458
+ }
1459
+ /**
1460
+ * Scrub sensitive data from an object
1461
+ */
1462
+ scrubObject(obj) {
1463
+ const result = {};
1464
+ for (const [key, value] of Object.entries(obj)) {
1465
+ result[key] = this.scrubValue(value, key);
1466
+ }
1467
+ return result;
1468
+ }
1469
+ /**
1470
+ * Add a custom pattern at runtime
1471
+ */
1472
+ addPattern(pattern) {
1473
+ this.customPatterns.push(pattern);
1474
+ }
1475
+ /**
1476
+ * Add a key to the allowlist
1477
+ */
1478
+ addToAllowlist(key) {
1479
+ this.allowlist.add(key.toLowerCase());
1480
+ }
1481
+ /**
1482
+ * Check if scrubbing is enabled
1483
+ */
1484
+ isEnabled() {
1485
+ return this.enabled;
1486
+ }
1487
+ /**
1488
+ * Enable or disable scrubbing
1489
+ */
1490
+ setEnabled(enabled) {
1491
+ this.enabled = enabled;
1492
+ }
1493
+ };
1494
+
1495
+ // src/logger/formatters/console.ts
1496
+ var COLORS = {
1497
+ reset: "\x1B[0m",
1498
+ bold: "\x1B[1m",
1499
+ dim: "\x1B[2m",
1500
+ // Foreground colors
1501
+ black: "\x1B[30m",
1502
+ red: "\x1B[31m",
1503
+ green: "\x1B[32m",
1504
+ yellow: "\x1B[33m",
1505
+ blue: "\x1B[34m",
1506
+ magenta: "\x1B[35m",
1507
+ cyan: "\x1B[36m",
1508
+ white: "\x1B[37m",
1509
+ gray: "\x1B[90m",
1510
+ // Background colors
1511
+ bgRed: "\x1B[41m",
1512
+ bgYellow: "\x1B[43m"
1513
+ };
1514
+ var LEVEL_COLORS = {
1515
+ trace: COLORS.gray,
1516
+ debug: COLORS.cyan,
1517
+ info: COLORS.green,
1518
+ warn: COLORS.yellow,
1519
+ error: COLORS.red,
1520
+ fatal: `${COLORS.bgRed}${COLORS.white}`,
1521
+ audit: COLORS.magenta
1522
+ };
1523
+ var LEVEL_LABELS = {
1524
+ trace: "TRACE",
1525
+ debug: "DEBUG",
1526
+ info: "INFO ",
1527
+ warn: "WARN ",
1528
+ error: "ERROR",
1529
+ fatal: "FATAL",
1530
+ audit: "AUDIT"
1531
+ };
1532
+ function formatPretty(entry, options = {}) {
1533
+ const {
1534
+ colors = true,
1535
+ timestamps = true,
1536
+ showLevel = true,
1537
+ showLogger = true,
1538
+ showContext = true,
1539
+ showSource = false
1540
+ } = options;
1541
+ const parts = [];
1542
+ if (timestamps) {
1543
+ const date = new Date(entry.timestamp);
1544
+ const time = date.toISOString().replace("T", " ").replace("Z", "");
1545
+ parts.push(colors ? `${COLORS.dim}${time}${COLORS.reset}` : time);
1546
+ }
1547
+ if (showLevel) {
1548
+ const levelColor = colors ? LEVEL_COLORS[entry.level] : "";
1549
+ const levelLabel = LEVEL_LABELS[entry.level];
1550
+ parts.push(colors ? `${levelColor}${levelLabel}${COLORS.reset}` : levelLabel);
1551
+ }
1552
+ if (showLogger && entry.loggerName) {
1553
+ parts.push(colors ? `${COLORS.blue}[${entry.loggerName}]${COLORS.reset}` : `[${entry.loggerName}]`);
1554
+ }
1555
+ parts.push(entry.message);
1556
+ if (showSource && entry.source) {
1557
+ const { file, line, function: fn } = entry.source;
1558
+ const loc = [file, line, fn].filter(Boolean).join(":");
1559
+ if (loc) {
1560
+ parts.push(colors ? `${COLORS.dim}(${loc})${COLORS.reset}` : `(${loc})`);
1561
+ }
1562
+ }
1563
+ let result = parts.join(" ");
1564
+ if (showContext && entry.context && Object.keys(entry.context).length > 0) {
1565
+ const contextStr = JSON.stringify(entry.context, null, 2);
1566
+ result += "\n" + (colors ? `${COLORS.dim}${contextStr}${COLORS.reset}` : contextStr);
1567
+ }
1568
+ return result;
1569
+ }
1570
+ function formatJson(entry) {
1571
+ return JSON.stringify(entry);
1572
+ }
1573
+ function formatJsonPretty(entry) {
1574
+ return JSON.stringify(entry, null, 2);
1575
+ }
1576
+ function getConsoleMethod(level) {
1577
+ switch (level) {
1578
+ case "trace":
1579
+ return "trace";
1580
+ case "debug":
1581
+ return "debug";
1582
+ case "info":
1583
+ return "info";
1584
+ case "warn":
1585
+ return "warn";
1586
+ case "error":
1587
+ case "fatal":
1588
+ return "error";
1589
+ case "audit":
1590
+ return "info";
1591
+ default:
1592
+ return "log";
1593
+ }
1594
+ }
1595
+
1596
+ // src/logger/destinations/console.ts
1597
+ var ConsoleDestination = class {
1598
+ constructor(config = {}) {
1599
+ this.name = "console";
1600
+ this.config = {
1601
+ enabled: config.enabled !== false,
1602
+ colors: config.colors !== false,
1603
+ format: config.format || "pretty",
1604
+ timestamps: config.timestamps !== false,
1605
+ levels: config.levels || ["trace", "debug", "info", "warn", "error", "fatal", "audit"]
1606
+ };
1607
+ this.minLevel = 0;
1608
+ }
1609
+ /**
1610
+ * Write a log entry to the console
1611
+ */
1612
+ write(entry) {
1613
+ if (!this.config.enabled) {
1614
+ return;
1615
+ }
1616
+ if (!this.config.levels.includes(entry.level)) {
1617
+ return;
1618
+ }
1619
+ if (LOG_LEVELS[entry.level] < this.minLevel) {
1620
+ return;
1621
+ }
1622
+ let output;
1623
+ if (this.config.format === "json") {
1624
+ output = formatJson(entry);
1625
+ } else {
1626
+ output = formatPretty(entry, {
1627
+ colors: this.config.colors && this.supportsColors(),
1628
+ timestamps: this.config.timestamps
1629
+ });
1630
+ }
1631
+ const method = getConsoleMethod(entry.level);
1632
+ console[method](output);
1633
+ }
1634
+ /**
1635
+ * Check if the environment supports colors
1636
+ */
1637
+ supportsColors() {
1638
+ if (typeof window !== "undefined") {
1639
+ return true;
1640
+ }
1641
+ if (typeof process !== "undefined") {
1642
+ if (process.stdout && "isTTY" in process.stdout) {
1643
+ return Boolean(process.stdout.isTTY);
1644
+ }
1645
+ const env = process.env;
1646
+ if (env.FORCE_COLOR !== void 0) {
1647
+ return env.FORCE_COLOR !== "0";
1648
+ }
1649
+ if (env.NO_COLOR !== void 0) {
1650
+ return false;
1651
+ }
1652
+ if (env.TERM === "dumb") {
1653
+ return false;
1654
+ }
1655
+ return true;
1656
+ }
1657
+ return false;
1658
+ }
1659
+ /**
1660
+ * Set minimum log level
1661
+ */
1662
+ setMinLevel(level) {
1663
+ this.minLevel = LOG_LEVELS[level];
1664
+ }
1665
+ /**
1666
+ * Enable or disable the destination
1667
+ */
1668
+ setEnabled(enabled) {
1669
+ this.config.enabled = enabled;
1670
+ }
1671
+ /**
1672
+ * Set color mode
1673
+ */
1674
+ setColors(enabled) {
1675
+ this.config.colors = enabled;
1676
+ }
1677
+ /**
1678
+ * Set output format
1679
+ */
1680
+ setFormat(format) {
1681
+ this.config.format = format;
1682
+ }
1683
+ };
1684
+
1685
+ // src/logger/destinations/observe.ts
1686
+ var DEFAULT_BATCH_SIZE = 50;
1687
+ var DEFAULT_FLUSH_INTERVAL = 5e3;
1688
+ var DEFAULT_SAMPLING = {
1689
+ trace: 0.01,
1690
+ // 1%
1691
+ debug: 0.1,
1692
+ // 10%
1693
+ info: 0.5,
1694
+ // 50%
1695
+ warn: 1,
1696
+ // 100%
1697
+ error: 1,
1698
+ // 100%
1699
+ fatal: 1,
1700
+ // 100%
1701
+ audit: 1
1702
+ // 100% - never sampled
1703
+ };
1704
+ var ObserveDestination = class {
1705
+ constructor(dsn, config = {}) {
1706
+ this.name = "observe";
1707
+ this.queue = [];
1708
+ this.isFlushing = false;
1709
+ this.minLevel = 0;
1710
+ this.dsn = dsn;
1711
+ this.endpoint = this.parseEndpoint(dsn);
1712
+ this.config = {
1713
+ enabled: config.enabled !== false,
1714
+ batchSize: config.batchSize || DEFAULT_BATCH_SIZE,
1715
+ flushInterval: config.flushInterval || DEFAULT_FLUSH_INTERVAL,
1716
+ sampling: { ...DEFAULT_SAMPLING, ...config.sampling },
1717
+ levels: config.levels || ["trace", "debug", "info", "warn", "error", "fatal", "audit"]
1718
+ };
1719
+ this.startFlushTimer();
1720
+ }
1721
+ /**
1722
+ * Parse DSN to construct endpoint
1723
+ */
1724
+ parseEndpoint(dsn) {
1725
+ try {
1726
+ const url = new URL(dsn);
1727
+ return `${url.protocol}//${url.host}/api/v1/logs/ingest`;
1728
+ } catch {
1729
+ return "https://statly.live/api/v1/logs/ingest";
1730
+ }
1731
+ }
1732
+ /**
1733
+ * Start the flush timer
1734
+ */
1735
+ startFlushTimer() {
1736
+ if (this.flushTimer) {
1737
+ clearInterval(this.flushTimer);
1738
+ }
1739
+ if (typeof setInterval !== "undefined") {
1740
+ this.flushTimer = setInterval(() => {
1741
+ this.flush();
1742
+ }, this.config.flushInterval);
1743
+ }
1744
+ }
1745
+ /**
1746
+ * Write a log entry (queues for batching)
1747
+ */
1748
+ write(entry) {
1749
+ if (!this.config.enabled) {
1750
+ return;
1751
+ }
1752
+ if (!this.config.levels.includes(entry.level)) {
1753
+ return;
1754
+ }
1755
+ if (LOG_LEVELS[entry.level] < this.minLevel) {
1756
+ return;
1757
+ }
1758
+ if (entry.level !== "audit") {
1759
+ const sampleRate = this.config.sampling[entry.level] ?? 1;
1760
+ if (Math.random() > sampleRate) {
1761
+ return;
1762
+ }
1763
+ }
1764
+ this.queue.push(entry);
1765
+ if (this.queue.length >= this.config.batchSize) {
1766
+ this.flush();
1767
+ }
1768
+ }
1769
+ /**
1770
+ * Flush all queued entries to the server
1771
+ */
1772
+ async flush() {
1773
+ if (this.isFlushing || this.queue.length === 0) {
1774
+ return;
1775
+ }
1776
+ this.isFlushing = true;
1777
+ const entries = [...this.queue];
1778
+ this.queue = [];
1779
+ try {
1780
+ await this.sendBatch(entries);
1781
+ } catch (error2) {
1782
+ const maxQueue = this.config.batchSize * 3;
1783
+ this.queue = [...entries, ...this.queue].slice(0, maxQueue);
1784
+ console.error("[Statly Logger] Failed to send logs:", error2);
1785
+ } finally {
1786
+ this.isFlushing = false;
1787
+ }
1788
+ }
1789
+ /**
1790
+ * Send a batch of entries to the server
1791
+ */
1792
+ async sendBatch(entries) {
1793
+ if (entries.length === 0) {
1794
+ return;
1795
+ }
1796
+ const response = await fetch(this.endpoint, {
1797
+ method: "POST",
1798
+ headers: {
1799
+ "Content-Type": "application/json",
1800
+ "X-Statly-DSN": this.dsn
1801
+ },
1802
+ body: JSON.stringify({ logs: entries }),
1803
+ keepalive: true
1804
+ });
1805
+ if (!response.ok) {
1806
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1807
+ }
1808
+ }
1809
+ /**
1810
+ * Close the destination
1811
+ */
1812
+ async close() {
1813
+ if (this.flushTimer) {
1814
+ clearInterval(this.flushTimer);
1815
+ }
1816
+ await this.flush();
1817
+ }
1818
+ /**
1819
+ * Set minimum log level
1820
+ */
1821
+ setMinLevel(level) {
1822
+ this.minLevel = LOG_LEVELS[level];
1823
+ }
1824
+ /**
1825
+ * Set sampling rate for a level
1826
+ */
1827
+ setSamplingRate(level, rate) {
1828
+ this.config.sampling[level] = Math.max(0, Math.min(1, rate));
1829
+ }
1830
+ /**
1831
+ * Enable or disable the destination
1832
+ */
1833
+ setEnabled(enabled) {
1834
+ this.config.enabled = enabled;
1835
+ }
1836
+ /**
1837
+ * Get the current queue size
1838
+ */
1839
+ getQueueSize() {
1840
+ return this.queue.length;
1841
+ }
1842
+ };
1843
+
1844
+ // src/logger/destinations/file.ts
1845
+ function parseSize(size) {
1846
+ const match = size.match(/^(\d+(?:\.\d+)?)\s*(KB|MB|GB|B)?$/i);
1847
+ if (!match) return 10 * 1024 * 1024;
1848
+ const value = parseFloat(match[1]);
1849
+ const unit = (match[2] || "B").toUpperCase();
1850
+ switch (unit) {
1851
+ case "KB":
1852
+ return value * 1024;
1853
+ case "MB":
1854
+ return value * 1024 * 1024;
1855
+ case "GB":
1856
+ return value * 1024 * 1024 * 1024;
1857
+ default:
1858
+ return value;
1859
+ }
1860
+ }
1861
+ function formatDate(date) {
1862
+ return date.toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
1863
+ }
1864
+ var FileDestination = class {
1865
+ constructor(config) {
1866
+ this.name = "file";
1867
+ this.minLevel = 0;
1868
+ this.buffer = [];
1869
+ this.currentSize = 0;
1870
+ this.writePromise = Promise.resolve();
1871
+ // File system operations (injected for Node.js compatibility)
1872
+ this.fs = null;
1873
+ this.config = {
1874
+ enabled: config.enabled !== false,
1875
+ path: config.path,
1876
+ format: config.format || "json",
1877
+ rotation: config.rotation || { type: "size", maxSize: "10MB", maxFiles: 5 },
1878
+ levels: config.levels || ["trace", "debug", "info", "warn", "error", "fatal", "audit"]
1879
+ };
1880
+ this.maxSize = parseSize(this.config.rotation.maxSize || "10MB");
1881
+ this.lastRotation = /* @__PURE__ */ new Date();
1882
+ this.rotationInterval = this.getRotationInterval();
1883
+ this.initFileSystem();
1884
+ }
1885
+ /**
1886
+ * Initialize file system operations
1887
+ */
1888
+ async initFileSystem() {
1889
+ if (typeof process !== "undefined" && process.versions?.node) {
1890
+ try {
1891
+ const fs = await import("fs/promises");
1892
+ const path = await import("path");
1893
+ const fsOps = {
1894
+ appendFile: fs.appendFile,
1895
+ rename: fs.rename,
1896
+ stat: fs.stat,
1897
+ mkdir: (p, opts) => fs.mkdir(p, opts),
1898
+ readdir: fs.readdir,
1899
+ unlink: fs.unlink
1900
+ };
1901
+ this.fs = fsOps;
1902
+ const dir = path.dirname(this.config.path);
1903
+ await fsOps.mkdir(dir, { recursive: true });
1904
+ } catch {
1905
+ console.warn("[Statly Logger] File destination not available (not Node.js)");
1906
+ this.config.enabled = false;
1907
+ }
1908
+ } else {
1909
+ this.config.enabled = false;
1910
+ }
1911
+ }
1912
+ /**
1913
+ * Get rotation interval in milliseconds
1914
+ */
1915
+ getRotationInterval() {
1916
+ const { interval } = this.config.rotation;
1917
+ switch (interval) {
1918
+ case "hourly":
1919
+ return 60 * 60 * 1e3;
1920
+ case "daily":
1921
+ return 24 * 60 * 60 * 1e3;
1922
+ case "weekly":
1923
+ return 7 * 24 * 60 * 60 * 1e3;
1924
+ default:
1925
+ return Infinity;
1926
+ }
1927
+ }
1928
+ /**
1929
+ * Write a log entry
1930
+ */
1931
+ write(entry) {
1932
+ if (!this.config.enabled || !this.fs) {
1933
+ return;
1934
+ }
1935
+ if (!this.config.levels.includes(entry.level)) {
1936
+ return;
1937
+ }
1938
+ if (LOG_LEVELS[entry.level] < this.minLevel) {
1939
+ return;
1940
+ }
1941
+ let line;
1942
+ if (this.config.format === "json") {
1943
+ line = formatJson(entry);
1944
+ } else {
1945
+ const date = new Date(entry.timestamp).toISOString();
1946
+ line = `${date} [${entry.level.toUpperCase()}] ${entry.loggerName ? `[${entry.loggerName}] ` : ""}${entry.message}`;
1947
+ if (entry.context && Object.keys(entry.context).length > 0) {
1948
+ line += ` ${JSON.stringify(entry.context)}`;
1949
+ }
1950
+ }
1951
+ this.buffer.push(line + "\n");
1952
+ this.currentSize += line.length + 1;
1953
+ if (this.buffer.length >= 100 || this.currentSize >= 64 * 1024) {
1954
+ this.scheduleWrite();
1955
+ }
1956
+ }
1957
+ /**
1958
+ * Schedule a buffered write
1959
+ */
1960
+ scheduleWrite() {
1961
+ this.writePromise = this.writePromise.then(() => this.writeBuffer());
1962
+ }
1963
+ /**
1964
+ * Write buffer to file
1965
+ */
1966
+ async writeBuffer() {
1967
+ if (!this.fs || this.buffer.length === 0) {
1968
+ return;
1969
+ }
1970
+ await this.checkRotation();
1971
+ const data = this.buffer.join("");
1972
+ this.buffer = [];
1973
+ this.currentSize = 0;
1974
+ try {
1975
+ await this.fs.appendFile(this.config.path, data);
1976
+ } catch (error2) {
1977
+ console.error("[Statly Logger] Failed to write to file:", error2);
1978
+ }
1979
+ }
1980
+ /**
1981
+ * Check if rotation is needed
1982
+ */
1983
+ async checkRotation() {
1984
+ if (!this.fs) return;
1985
+ const { type } = this.config.rotation;
1986
+ let shouldRotate = false;
1987
+ if (type === "size") {
1988
+ try {
1989
+ const stats = await this.fs.stat(this.config.path);
1990
+ shouldRotate = stats.size >= this.maxSize;
1991
+ } catch {
1992
+ }
1993
+ } else if (type === "time") {
1994
+ const now = /* @__PURE__ */ new Date();
1995
+ shouldRotate = now.getTime() - this.lastRotation.getTime() >= this.rotationInterval;
1996
+ }
1997
+ if (shouldRotate) {
1998
+ await this.rotate();
1999
+ }
2000
+ }
2001
+ /**
2002
+ * Rotate the log file
2003
+ */
2004
+ async rotate() {
2005
+ if (!this.fs) return;
2006
+ try {
2007
+ const rotatedPath = `${this.config.path}.${formatDate(/* @__PURE__ */ new Date())}`;
2008
+ await this.fs.rename(this.config.path, rotatedPath);
2009
+ this.lastRotation = /* @__PURE__ */ new Date();
2010
+ await this.cleanupOldFiles();
2011
+ } catch (error2) {
2012
+ console.error("[Statly Logger] Failed to rotate file:", error2);
2013
+ }
2014
+ }
2015
+ /**
2016
+ * Clean up old rotated files
2017
+ */
2018
+ async cleanupOldFiles() {
2019
+ if (!this.fs) return;
2020
+ const { maxFiles, retentionDays } = this.config.rotation;
2021
+ try {
2022
+ const path = await import("path");
2023
+ const dir = path.dirname(this.config.path);
2024
+ const basename = path.basename(this.config.path);
2025
+ const files = await this.fs.readdir(dir);
2026
+ const rotatedFiles = files.filter((f) => f.startsWith(basename + ".")).map((f) => ({ name: f, path: path.join(dir, f) })).sort((a, b) => b.name.localeCompare(a.name));
2027
+ if (maxFiles) {
2028
+ for (const file of rotatedFiles.slice(maxFiles)) {
2029
+ await this.fs.unlink(file.path);
2030
+ }
2031
+ }
2032
+ if (retentionDays) {
2033
+ const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1e3;
2034
+ for (const file of rotatedFiles) {
2035
+ const match = file.name.match(/\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})$/);
2036
+ if (match) {
2037
+ const fileDate = new Date(match[1].replace("_", "T").replace(/-/g, ":"));
2038
+ if (fileDate.getTime() < cutoff) {
2039
+ await this.fs.unlink(file.path);
2040
+ }
2041
+ }
2042
+ }
2043
+ }
2044
+ } catch (error2) {
2045
+ console.error("[Statly Logger] Failed to cleanup old files:", error2);
2046
+ }
2047
+ }
2048
+ /**
2049
+ * Flush buffered writes
2050
+ */
2051
+ async flush() {
2052
+ this.scheduleWrite();
2053
+ await this.writePromise;
2054
+ }
2055
+ /**
2056
+ * Close the destination
2057
+ */
2058
+ async close() {
2059
+ await this.flush();
2060
+ }
2061
+ /**
2062
+ * Set minimum log level
2063
+ */
2064
+ setMinLevel(level) {
2065
+ this.minLevel = LOG_LEVELS[level];
2066
+ }
2067
+ /**
2068
+ * Enable or disable the destination
2069
+ */
2070
+ setEnabled(enabled) {
2071
+ this.config.enabled = enabled;
2072
+ }
2073
+ };
2074
+
2075
+ // src/logger/ai/index.ts
2076
+ var AIFeatures = class {
2077
+ constructor(dsn, config = {}) {
2078
+ this.dsn = dsn;
2079
+ this.config = {
2080
+ enabled: config.enabled ?? true,
2081
+ apiKey: config.apiKey || "",
2082
+ model: config.model || "claude-3-haiku-20240307",
2083
+ endpoint: config.endpoint || this.parseEndpoint(dsn)
2084
+ };
2085
+ }
2086
+ /**
2087
+ * Parse DSN to construct AI endpoint
2088
+ */
2089
+ parseEndpoint(dsn) {
2090
+ try {
2091
+ const url = new URL(dsn);
2092
+ return `${url.protocol}//${url.host}/api/v1/logs/ai`;
2093
+ } catch {
2094
+ return "https://statly.live/api/v1/logs/ai";
2095
+ }
2096
+ }
2097
+ /**
2098
+ * Explain an error using AI
2099
+ */
2100
+ async explainError(error2) {
2101
+ if (!this.config.enabled) {
2102
+ return {
2103
+ summary: "AI features are disabled",
2104
+ possibleCauses: []
2105
+ };
2106
+ }
2107
+ const errorData = this.normalizeError(error2);
2108
+ try {
2109
+ const response = await fetch(`${this.config.endpoint}/explain`, {
2110
+ method: "POST",
2111
+ headers: {
2112
+ "Content-Type": "application/json",
2113
+ "X-Statly-DSN": this.dsn,
2114
+ ...this.config.apiKey && { "X-AI-API-Key": this.config.apiKey }
2115
+ },
2116
+ body: JSON.stringify({
2117
+ error: errorData,
2118
+ model: this.config.model
2119
+ })
2120
+ });
2121
+ if (!response.ok) {
2122
+ throw new Error(`HTTP ${response.status}`);
2123
+ }
2124
+ return await response.json();
2125
+ } catch (err) {
2126
+ console.error("[Statly Logger AI] Failed to explain error:", err);
2127
+ return {
2128
+ summary: "Failed to get AI explanation",
2129
+ possibleCauses: []
2130
+ };
2131
+ }
2132
+ }
2133
+ /**
2134
+ * Suggest fixes for an error using AI
2135
+ */
2136
+ async suggestFix(error2, context) {
2137
+ if (!this.config.enabled) {
2138
+ return {
2139
+ summary: "AI features are disabled",
2140
+ suggestedFixes: []
2141
+ };
2142
+ }
2143
+ const errorData = this.normalizeError(error2);
2144
+ try {
2145
+ const response = await fetch(`${this.config.endpoint}/suggest-fix`, {
2146
+ method: "POST",
2147
+ headers: {
2148
+ "Content-Type": "application/json",
2149
+ "X-Statly-DSN": this.dsn,
2150
+ ...this.config.apiKey && { "X-AI-API-Key": this.config.apiKey }
2151
+ },
2152
+ body: JSON.stringify({
2153
+ error: errorData,
2154
+ context,
2155
+ model: this.config.model
2156
+ })
2157
+ });
2158
+ if (!response.ok) {
2159
+ throw new Error(`HTTP ${response.status}`);
2160
+ }
2161
+ return await response.json();
2162
+ } catch (err) {
2163
+ console.error("[Statly Logger AI] Failed to suggest fix:", err);
2164
+ return {
2165
+ summary: "Failed to get AI fix suggestion",
2166
+ suggestedFixes: []
2167
+ };
2168
+ }
2169
+ }
2170
+ /**
2171
+ * Analyze a batch of logs for patterns
2172
+ */
2173
+ async analyzePatterns(logs) {
2174
+ if (!this.config.enabled) {
2175
+ return {
2176
+ patterns: [],
2177
+ summary: "AI features are disabled",
2178
+ recommendations: []
2179
+ };
2180
+ }
2181
+ try {
2182
+ const response = await fetch(`${this.config.endpoint}/analyze-patterns`, {
2183
+ method: "POST",
2184
+ headers: {
2185
+ "Content-Type": "application/json",
2186
+ "X-Statly-DSN": this.dsn,
2187
+ ...this.config.apiKey && { "X-AI-API-Key": this.config.apiKey }
2188
+ },
2189
+ body: JSON.stringify({
2190
+ logs: logs.slice(0, 1e3),
2191
+ // Limit to 1000 logs
2192
+ model: this.config.model
2193
+ })
2194
+ });
2195
+ if (!response.ok) {
2196
+ throw new Error(`HTTP ${response.status}`);
2197
+ }
2198
+ return await response.json();
2199
+ } catch (err) {
2200
+ console.error("[Statly Logger AI] Failed to analyze patterns:", err);
2201
+ return {
2202
+ patterns: [],
2203
+ summary: "Failed to analyze patterns",
2204
+ recommendations: []
2205
+ };
2206
+ }
2207
+ }
2208
+ /**
2209
+ * Normalize error input to a standard format
2210
+ */
2211
+ normalizeError(error2) {
2212
+ if (typeof error2 === "string") {
2213
+ return { message: error2 };
2214
+ }
2215
+ if (error2 instanceof Error) {
2216
+ return {
2217
+ message: error2.message,
2218
+ stack: error2.stack,
2219
+ type: error2.name
2220
+ };
2221
+ }
2222
+ return {
2223
+ message: error2.message,
2224
+ type: error2.level,
2225
+ context: error2.context
2226
+ };
2227
+ }
2228
+ /**
2229
+ * Set API key for AI features
2230
+ */
2231
+ setApiKey(apiKey) {
2232
+ this.config.apiKey = apiKey;
2233
+ }
2234
+ /**
2235
+ * Enable or disable AI features
2236
+ */
2237
+ setEnabled(enabled) {
2238
+ this.config.enabled = enabled;
2239
+ }
2240
+ /**
2241
+ * Check if AI features are enabled
2242
+ */
2243
+ isEnabled() {
2244
+ return this.config.enabled;
2245
+ }
2246
+ };
2247
+
2248
+ // src/logger/logger.ts
2249
+ var SDK_NAME2 = "@statly/observe";
2250
+ var SDK_VERSION2 = "1.1.0";
2251
+ var Logger = class _Logger {
2252
+ constructor(config = {}) {
2253
+ this.destinations = [];
2254
+ this.ai = null;
2255
+ this.context = {};
2256
+ this.tags = {};
2257
+ this.name = config.loggerName || "default";
2258
+ this.config = config;
2259
+ this.minLevel = LOG_LEVELS[config.level || "debug"];
2260
+ this.enabledLevels = this.parseLevelSet(config.levels || "default");
2261
+ this.scrubber = new Scrubber(config.scrubbing);
2262
+ this.context = config.context || {};
2263
+ this.tags = config.tags || {};
2264
+ this.sessionId = this.generateId();
2265
+ this.initDestinations();
2266
+ if (config.dsn) {
2267
+ this.ai = new AIFeatures(config.dsn);
2268
+ }
2269
+ }
2270
+ /**
2271
+ * Parse level set configuration
2272
+ */
2273
+ parseLevelSet(levels) {
2274
+ if (levels === "default") {
2275
+ return new Set(DEFAULT_LEVELS);
2276
+ }
2277
+ if (levels === "extended") {
2278
+ return new Set(EXTENDED_LEVELS);
2279
+ }
2280
+ return new Set(levels);
2281
+ }
2282
+ /**
2283
+ * Initialize destinations from config
2284
+ */
2285
+ initDestinations() {
2286
+ const { destinations } = this.config;
2287
+ if (!destinations || destinations.console?.enabled !== false) {
2288
+ this.destinations.push(new ConsoleDestination(destinations?.console));
2289
+ }
2290
+ if (destinations?.file?.enabled && destinations.file.path) {
2291
+ this.destinations.push(new FileDestination(destinations.file));
2292
+ }
2293
+ if (this.config.dsn && destinations?.observe?.enabled !== false) {
2294
+ this.destinations.push(new ObserveDestination(this.config.dsn, destinations?.observe));
2295
+ }
2296
+ }
2297
+ /**
2298
+ * Generate a unique ID
2299
+ */
2300
+ generateId() {
2301
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
2302
+ return crypto.randomUUID();
2303
+ }
2304
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
2305
+ const r = Math.random() * 16 | 0;
2306
+ const v = c === "x" ? r : r & 3 | 8;
2307
+ return v.toString(16);
2308
+ });
2309
+ }
2310
+ /**
2311
+ * Check if a level should be logged
2312
+ */
2313
+ shouldLog(level) {
2314
+ if (level === "audit") {
2315
+ return true;
2316
+ }
2317
+ if (LOG_LEVELS[level] < this.minLevel) {
2318
+ return false;
2319
+ }
2320
+ return this.enabledLevels.has(level);
2321
+ }
2322
+ /**
2323
+ * Get source location (if available)
2324
+ */
2325
+ getSource() {
2326
+ try {
2327
+ const err = new Error();
2328
+ const stack = err.stack?.split("\n");
2329
+ if (!stack || stack.length < 5) return void 0;
2330
+ for (let i = 3; i < stack.length; i++) {
2331
+ const frame = stack[i];
2332
+ if (!frame.includes("logger.ts") && !frame.includes("Logger.")) {
2333
+ const match = frame.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+)(?::\d+)?\)?/);
2334
+ if (match) {
2335
+ return {
2336
+ function: match[1] || void 0,
2337
+ file: match[2],
2338
+ line: parseInt(match[3], 10)
2339
+ };
2340
+ }
2341
+ }
2342
+ }
2343
+ } catch {
2344
+ }
2345
+ return void 0;
2346
+ }
2347
+ /**
2348
+ * Create a log entry
2349
+ */
2350
+ createEntry(level, message, context) {
2351
+ return {
2352
+ level,
2353
+ message: this.scrubber.scrubMessage(message),
2354
+ timestamp: Date.now(),
2355
+ loggerName: this.name,
2356
+ context: context ? this.scrubber.scrub({ ...this.context, ...context }) : this.scrubber.scrub(this.context),
2357
+ tags: this.tags,
2358
+ source: this.getSource(),
2359
+ traceId: this.traceId,
2360
+ spanId: this.spanId,
2361
+ sessionId: this.sessionId,
2362
+ environment: this.config.environment,
2363
+ release: this.config.release,
2364
+ sdkName: SDK_NAME2,
2365
+ sdkVersion: SDK_VERSION2
2366
+ };
2367
+ }
2368
+ /**
2369
+ * Write to all destinations
2370
+ */
2371
+ write(entry) {
2372
+ for (const dest of this.destinations) {
2373
+ try {
2374
+ dest.write(entry);
2375
+ } catch (error2) {
2376
+ console.error(`[Statly Logger] Failed to write to ${dest.name}:`, error2);
2377
+ }
2378
+ }
2379
+ }
2380
+ // ==================== Public Logging Methods ====================
2381
+ /**
2382
+ * Log a trace message
2383
+ */
2384
+ trace(message, context) {
2385
+ if (!this.shouldLog("trace")) return;
2386
+ this.write(this.createEntry("trace", message, context));
2387
+ }
2388
+ /**
2389
+ * Log a debug message
2390
+ */
2391
+ debug(message, context) {
2392
+ if (!this.shouldLog("debug")) return;
2393
+ this.write(this.createEntry("debug", message, context));
2394
+ }
2395
+ /**
2396
+ * Log an info message
2397
+ */
2398
+ info(message, context) {
2399
+ if (!this.shouldLog("info")) return;
2400
+ this.write(this.createEntry("info", message, context));
2401
+ }
2402
+ /**
2403
+ * Log a warning message
2404
+ */
2405
+ warn(message, context) {
2406
+ if (!this.shouldLog("warn")) return;
2407
+ this.write(this.createEntry("warn", message, context));
2408
+ }
2409
+ error(messageOrError, context) {
2410
+ if (!this.shouldLog("error")) return;
2411
+ if (messageOrError instanceof Error) {
2412
+ const entry = this.createEntry("error", messageOrError.message, {
2413
+ ...context,
2414
+ stack: messageOrError.stack,
2415
+ errorType: messageOrError.name
2416
+ });
2417
+ this.write(entry);
2418
+ } else {
2419
+ this.write(this.createEntry("error", messageOrError, context));
2420
+ }
2421
+ }
2422
+ fatal(messageOrError, context) {
2423
+ if (!this.shouldLog("fatal")) return;
2424
+ if (messageOrError instanceof Error) {
2425
+ const entry = this.createEntry("fatal", messageOrError.message, {
2426
+ ...context,
2427
+ stack: messageOrError.stack,
2428
+ errorType: messageOrError.name
2429
+ });
2430
+ this.write(entry);
2431
+ } else {
2432
+ this.write(this.createEntry("fatal", messageOrError, context));
2433
+ }
2434
+ }
2435
+ /**
2436
+ * Log an audit message (always logged, never sampled)
2437
+ */
2438
+ audit(message, context) {
2439
+ this.write(this.createEntry("audit", message, context));
2440
+ }
2441
+ /**
2442
+ * Log at a specific level
2443
+ */
2444
+ log(level, message, context) {
2445
+ if (!this.shouldLog(level)) return;
2446
+ this.write(this.createEntry(level, message, context));
2447
+ }
2448
+ // ==================== Context & Tags ====================
2449
+ /**
2450
+ * Set persistent context
2451
+ */
2452
+ setContext(context) {
2453
+ this.context = { ...this.context, ...context };
2454
+ }
2455
+ /**
2456
+ * Clear context
2457
+ */
2458
+ clearContext() {
2459
+ this.context = {};
2460
+ }
2461
+ /**
2462
+ * Set a tag
2463
+ */
2464
+ setTag(key, value) {
2465
+ this.tags[key] = value;
2466
+ }
2467
+ /**
2468
+ * Set multiple tags
2469
+ */
2470
+ setTags(tags) {
2471
+ this.tags = { ...this.tags, ...tags };
2472
+ }
2473
+ /**
2474
+ * Clear tags
2475
+ */
2476
+ clearTags() {
2477
+ this.tags = {};
2478
+ }
2479
+ // ==================== Tracing ====================
2480
+ /**
2481
+ * Set trace ID for distributed tracing
2482
+ */
2483
+ setTraceId(traceId) {
2484
+ this.traceId = traceId;
2485
+ }
2486
+ /**
2487
+ * Set span ID
2488
+ */
2489
+ setSpanId(spanId) {
2490
+ this.spanId = spanId;
2491
+ }
2492
+ /**
2493
+ * Clear tracing context
2494
+ */
2495
+ clearTracing() {
2496
+ this.traceId = void 0;
2497
+ this.spanId = void 0;
2498
+ }
2499
+ // ==================== Child Loggers ====================
2500
+ /**
2501
+ * Create a child logger with additional context
2502
+ */
2503
+ child(options = {}) {
2504
+ const childConfig = {
2505
+ ...this.config,
2506
+ loggerName: options.name || `${this.name}.child`,
2507
+ context: { ...this.context, ...options.context },
2508
+ tags: { ...this.tags, ...options.tags }
2509
+ };
2510
+ const child = new _Logger(childConfig);
2511
+ child.traceId = this.traceId;
2512
+ child.spanId = this.spanId;
2513
+ child.sessionId = this.sessionId;
2514
+ return child;
2515
+ }
2516
+ // ==================== AI Features ====================
2517
+ /**
2518
+ * Explain an error using AI
2519
+ */
2520
+ async explainError(error2) {
2521
+ if (!this.ai) {
2522
+ return {
2523
+ summary: "AI features not available (no DSN configured)",
2524
+ possibleCauses: []
2525
+ };
2526
+ }
2527
+ return this.ai.explainError(error2);
2528
+ }
2529
+ /**
2530
+ * Suggest fixes for an error using AI
2531
+ */
2532
+ async suggestFix(error2, context) {
2533
+ if (!this.ai) {
2534
+ return {
2535
+ summary: "AI features not available (no DSN configured)",
2536
+ suggestedFixes: []
2537
+ };
2538
+ }
2539
+ return this.ai.suggestFix(error2, context);
2540
+ }
2541
+ /**
2542
+ * Configure AI features
2543
+ */
2544
+ configureAI(config) {
2545
+ if (this.ai) {
2546
+ if (config.apiKey) this.ai.setApiKey(config.apiKey);
2547
+ if (config.enabled !== void 0) this.ai.setEnabled(config.enabled);
2548
+ }
2549
+ }
2550
+ // ==================== Destination Management ====================
2551
+ /**
2552
+ * Add a custom destination
2553
+ */
2554
+ addDestination(destination) {
2555
+ this.destinations.push(destination);
2556
+ }
2557
+ /**
2558
+ * Remove a destination by name
2559
+ */
2560
+ removeDestination(name) {
2561
+ this.destinations = this.destinations.filter((d) => d.name !== name);
2562
+ }
2563
+ /**
2564
+ * Get all destinations
2565
+ */
2566
+ getDestinations() {
2567
+ return [...this.destinations];
2568
+ }
2569
+ // ==================== Level Configuration ====================
2570
+ /**
2571
+ * Set minimum log level
2572
+ */
2573
+ setLevel(level) {
2574
+ this.minLevel = LOG_LEVELS[level];
2575
+ }
2576
+ /**
2577
+ * Get current minimum level
2578
+ */
2579
+ getLevel() {
2580
+ const entries = Object.entries(LOG_LEVELS);
2581
+ const entry = entries.find(([, value]) => value === this.minLevel);
2582
+ return entry ? entry[0] : "debug";
2583
+ }
2584
+ /**
2585
+ * Check if a level is enabled
2586
+ */
2587
+ isLevelEnabled(level) {
2588
+ return this.shouldLog(level);
2589
+ }
2590
+ // ==================== Lifecycle ====================
2591
+ /**
2592
+ * Flush all destinations
2593
+ */
2594
+ async flush() {
2595
+ await Promise.all(
2596
+ this.destinations.filter((d) => d.flush).map((d) => d.flush())
2597
+ );
2598
+ }
2599
+ /**
2600
+ * Close the logger and all destinations
2601
+ */
2602
+ async close() {
2603
+ await Promise.all(
2604
+ this.destinations.filter((d) => d.close).map((d) => d.close())
2605
+ );
2606
+ }
2607
+ /**
2608
+ * Get logger name
2609
+ */
2610
+ getName() {
2611
+ return this.name;
2612
+ }
2613
+ /**
2614
+ * Get session ID
2615
+ */
2616
+ getSessionId() {
2617
+ return this.sessionId;
2618
+ }
2619
+ };
2620
+
2621
+ // src/logger/index.ts
2622
+ var defaultLogger = null;
2623
+ function getDefaultLogger() {
2624
+ if (!defaultLogger) {
2625
+ defaultLogger = new Logger();
2626
+ }
2627
+ return defaultLogger;
2628
+ }
2629
+ function setDefaultLogger(logger) {
2630
+ defaultLogger = logger;
2631
+ }
2632
+ function trace2(message, context) {
2633
+ getDefaultLogger().trace(message, context);
2634
+ }
2635
+ function debug(message, context) {
2636
+ getDefaultLogger().debug(message, context);
2637
+ }
2638
+ function info(message, context) {
2639
+ getDefaultLogger().info(message, context);
2640
+ }
2641
+ function warn(message, context) {
2642
+ getDefaultLogger().warn(message, context);
2643
+ }
2644
+ function error(messageOrError, context) {
2645
+ if (messageOrError instanceof Error) {
2646
+ getDefaultLogger().error(messageOrError, context);
2647
+ } else {
2648
+ getDefaultLogger().error(messageOrError, context);
2649
+ }
2650
+ }
2651
+ function fatal(messageOrError, context) {
2652
+ if (messageOrError instanceof Error) {
2653
+ getDefaultLogger().fatal(messageOrError, context);
2654
+ } else {
2655
+ getDefaultLogger().fatal(messageOrError, context);
2656
+ }
2657
+ }
2658
+ function audit(message, context) {
2659
+ getDefaultLogger().audit(message, context);
2660
+ }
2661
+
2662
+ // src/index.ts
2663
+ var client = null;
2664
+ function loadDsnFromEnv() {
2665
+ if (typeof process !== "undefined" && process.env) {
2666
+ return process.env.STATLY_DSN || process.env.NEXT_PUBLIC_STATLY_DSN || process.env.STATLY_OBSERVE_DSN;
2667
+ }
2668
+ return void 0;
2669
+ }
2670
+ function loadEnvironmentFromEnv() {
2671
+ if (typeof process !== "undefined" && process.env) {
2672
+ return process.env.STATLY_ENVIRONMENT || process.env.NODE_ENV;
2673
+ }
2674
+ return void 0;
2675
+ }
2676
+ function init(options) {
2677
+ if (client) {
2678
+ console.warn("[Statly] SDK already initialized. Call close() first to reinitialize.");
2679
+ return;
2680
+ }
2681
+ const dsn = options?.dsn || loadDsnFromEnv();
2682
+ if (!dsn) {
2683
+ console.error("[Statly] No DSN provided. Set STATLY_DSN in your environment or pass dsn to init().");
2684
+ console.error("[Statly] Get your DSN at https://statly.live/dashboard/observe/setup");
2685
+ return;
2686
+ }
2687
+ const environment = options?.environment || loadEnvironmentFromEnv();
2688
+ const finalOptions = {
2689
+ ...options,
2690
+ dsn,
2691
+ environment
2692
+ };
2693
+ client = new StatlyClient(finalOptions);
2694
+ client.init();
2695
+ }
2696
+ function captureException(error2, context) {
2697
+ if (!client) {
2698
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
2699
+ return "";
2700
+ }
2701
+ return client.captureException(error2, context);
2702
+ }
2703
+ function captureMessage(message, level = "info") {
2704
+ if (!client) {
2705
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
2706
+ return "";
2707
+ }
2708
+ return client.captureMessage(message, level);
2709
+ }
2710
+ function setUser(user) {
2711
+ if (!client) {
2712
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
2713
+ return;
2714
+ }
2715
+ client.setUser(user);
2716
+ }
2717
+ function setTag(key, value) {
2718
+ if (!client) {
2719
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
2720
+ return;
2721
+ }
2722
+ client.setTag(key, value);
2723
+ }
2724
+ function setTags(tags) {
2725
+ if (!client) {
2726
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
2727
+ return;
2728
+ }
2729
+ client.setTags(tags);
2730
+ }
2731
+ function addBreadcrumb(breadcrumb) {
2732
+ if (!client) {
2733
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
2734
+ return;
2735
+ }
2736
+ client.addBreadcrumb(breadcrumb);
2737
+ }
2738
+ async function flush() {
2739
+ if (!client) {
2740
+ return;
2741
+ }
2742
+ await client.flush();
2743
+ }
2744
+ async function close() {
2745
+ if (!client) {
2746
+ return;
2747
+ }
2748
+ await client.close();
2749
+ client = null;
2750
+ }
2751
+ function getClient() {
2752
+ return client;
2753
+ }
2754
+ async function trace3(name, operation, tags) {
2755
+ if (!client) {
2756
+ return operation(null);
2757
+ }
2758
+ return client.trace(name, operation, tags);
2759
+ }
2760
+ function startSpan(name, tags) {
2761
+ if (!client) return null;
2762
+ return client.startSpan(name, tags);
2763
+ }
2764
+ function captureSpan(span) {
2765
+ if (!client) return "";
2766
+ return client.captureSpan(span);
2767
+ }
2768
+ var Statly = {
2769
+ init,
2770
+ captureException,
2771
+ captureMessage,
2772
+ setUser,
2773
+ setTag,
2774
+ setTags,
2775
+ addBreadcrumb,
2776
+ flush,
2777
+ close,
2778
+ getClient,
2779
+ trace: trace3,
2780
+ startSpan,
2781
+ captureSpan
2782
+ };
2783
+ // Annotate the CommonJS export names for ESM import in node:
2784
+ 0 && (module.exports = {
2785
+ AIFeatures,
2786
+ ConsoleDestination,
2787
+ DEFAULT_LEVELS,
2788
+ EXTENDED_LEVELS,
2789
+ FileDestination,
2790
+ LOG_LEVELS,
2791
+ Logger,
2792
+ ObserveDestination,
2793
+ REDACTED,
2794
+ SCRUB_PATTERNS,
2795
+ SENSITIVE_KEYS,
2796
+ Scrubber,
2797
+ Statly,
2798
+ StatlyClient,
2799
+ addBreadcrumb,
2800
+ captureException,
2801
+ captureMessage,
2802
+ captureNextJsError,
2803
+ captureSpan,
2804
+ close,
2805
+ createRequestCapture,
2806
+ expressErrorHandler,
2807
+ flush,
2808
+ formatJson,
2809
+ formatJsonPretty,
2810
+ formatPretty,
2811
+ getClient,
2812
+ getConsoleMethod,
2813
+ getDefaultLogger,
2814
+ init,
2815
+ isSensitiveKey,
2816
+ logAudit,
2817
+ logDebug,
2818
+ logError,
2819
+ logFatal,
2820
+ logInfo,
2821
+ logTrace,
2822
+ logWarn,
2823
+ requestHandler,
2824
+ setDefaultLogger,
2825
+ setTag,
2826
+ setTags,
2827
+ setUser,
2828
+ startSpan,
2829
+ statlyFastifyPlugin,
2830
+ statlyPlugin,
2831
+ trace,
2832
+ withStatly,
2833
+ withStatlyGetServerSideProps,
2834
+ withStatlyGetStaticProps,
2835
+ withStatlyPagesApi,
2836
+ withStatlyServerAction
2837
+ });