@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.
@@ -0,0 +1,1108 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __esm = (fn, res) => function __init() {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ };
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+
23
+ // src/span.ts
24
+ var Span, TraceContext;
25
+ var init_span = __esm({
26
+ "src/span.ts"() {
27
+ "use strict";
28
+ Span = class {
29
+ constructor(name, context, tags) {
30
+ this._status = "ok" /* OK */;
31
+ this._tags = {};
32
+ this._metadata = {};
33
+ this._finished = false;
34
+ this.name = name;
35
+ this.context = context;
36
+ this.startTime = Date.now();
37
+ if (tags) this._tags = { ...tags };
38
+ }
39
+ /**
40
+ * Finish the span and calculate duration
41
+ */
42
+ finish(endTime) {
43
+ if (this._finished) return;
44
+ this._endTime = endTime || Date.now();
45
+ this._durationMs = this._endTime - this.startTime;
46
+ this._finished = true;
47
+ }
48
+ setTag(key, value) {
49
+ this._tags[key] = value;
50
+ return this;
51
+ }
52
+ setMetadata(key, value) {
53
+ this._metadata[key] = value;
54
+ return this;
55
+ }
56
+ setStatus(status) {
57
+ this._status = status;
58
+ return this;
59
+ }
60
+ get status() {
61
+ return this._status;
62
+ }
63
+ get tags() {
64
+ return { ...this._tags };
65
+ }
66
+ get durationMs() {
67
+ return this._durationMs;
68
+ }
69
+ toDict() {
70
+ return {
71
+ name: this.name,
72
+ traceId: this.context.traceId,
73
+ spanId: this.context.spanId,
74
+ parentId: this.context.parentId,
75
+ startTime: this.startTime,
76
+ endTime: this._endTime,
77
+ durationMs: this._durationMs,
78
+ status: this._status,
79
+ tags: this._tags,
80
+ metadata: this._metadata
81
+ };
82
+ }
83
+ };
84
+ TraceContext = class {
85
+ static getActiveSpan() {
86
+ return this.currentSpan;
87
+ }
88
+ static setActiveSpan(span) {
89
+ this.currentSpan = span;
90
+ }
91
+ };
92
+ TraceContext.currentSpan = null;
93
+ }
94
+ });
95
+
96
+ // src/telemetry.ts
97
+ var telemetry_exports = {};
98
+ __export(telemetry_exports, {
99
+ TelemetryProvider: () => TelemetryProvider,
100
+ trace: () => trace
101
+ });
102
+ async function trace(name, operation, tags) {
103
+ const provider = TelemetryProvider.getInstance();
104
+ const span = provider.startSpan(name, tags);
105
+ try {
106
+ const result = await operation(span);
107
+ return result;
108
+ } catch (error2) {
109
+ span.setStatus("error" /* ERROR */);
110
+ span.setTag("error", "true");
111
+ if (error2 instanceof Error) {
112
+ span.setTag("exception.type", error2.name);
113
+ span.setTag("exception.message", error2.message);
114
+ }
115
+ throw error2;
116
+ } finally {
117
+ provider.finishSpan(span);
118
+ }
119
+ }
120
+ var TelemetryProvider;
121
+ var init_telemetry = __esm({
122
+ "src/telemetry.ts"() {
123
+ "use strict";
124
+ init_span();
125
+ TelemetryProvider = class _TelemetryProvider {
126
+ constructor() {
127
+ this.client = null;
128
+ }
129
+ static getInstance() {
130
+ if (!_TelemetryProvider.instance) {
131
+ _TelemetryProvider.instance = new _TelemetryProvider();
132
+ }
133
+ return _TelemetryProvider.instance;
134
+ }
135
+ setClient(client2) {
136
+ this.client = client2;
137
+ }
138
+ /**
139
+ * Start a new span
140
+ */
141
+ startSpan(name, tags) {
142
+ const parent = TraceContext.getActiveSpan();
143
+ const traceId = parent ? parent.context.traceId : this.generateId();
144
+ const parentId = parent ? parent.context.spanId : null;
145
+ const span = new Span(name, {
146
+ traceId,
147
+ spanId: this.generateId(),
148
+ parentId
149
+ }, tags);
150
+ TraceContext.setActiveSpan(span);
151
+ return span;
152
+ }
153
+ /**
154
+ * Finish and report a span
155
+ */
156
+ finishSpan(span) {
157
+ span.finish();
158
+ if (TraceContext.getActiveSpan() === span) {
159
+ TraceContext.setActiveSpan(null);
160
+ }
161
+ if (this.client) {
162
+ this.client.captureSpan(span);
163
+ }
164
+ }
165
+ generateId() {
166
+ return Math.random().toString(16).substring(2, 18);
167
+ }
168
+ };
169
+ }
170
+ });
171
+
172
+ // src/integrations/express.ts
173
+ var express_exports = {};
174
+ __export(express_exports, {
175
+ expressErrorHandler: () => expressErrorHandler,
176
+ requestHandler: () => requestHandler
177
+ });
178
+ module.exports = __toCommonJS(express_exports);
179
+
180
+ // src/transport.ts
181
+ var Transport = class {
182
+ constructor(options) {
183
+ this.queue = [];
184
+ this.isSending = false;
185
+ this.maxQueueSize = 100;
186
+ this.flushInterval = 5e3;
187
+ this.dsn = options.dsn;
188
+ this.debug = options.debug ?? false;
189
+ this.endpoint = this.parseEndpoint(options.dsn);
190
+ this.startFlushTimer();
191
+ }
192
+ parseEndpoint(dsn) {
193
+ try {
194
+ const url = new URL(dsn);
195
+ return `${url.protocol}//${url.host}/api/v1/observe/ingest`;
196
+ } catch {
197
+ return `https://statly.live/api/v1/observe/ingest`;
198
+ }
199
+ }
200
+ startFlushTimer() {
201
+ if (typeof window !== "undefined") {
202
+ this.flushTimer = setInterval(() => {
203
+ this.flush();
204
+ }, this.flushInterval);
205
+ }
206
+ }
207
+ /**
208
+ * Add an event to the queue
209
+ */
210
+ enqueue(event) {
211
+ if (this.queue.length >= this.maxQueueSize) {
212
+ this.queue.shift();
213
+ if (this.debug) {
214
+ console.warn("[Statly] Event queue full, dropping oldest event");
215
+ }
216
+ }
217
+ this.queue.push(event);
218
+ if (this.queue.length >= 10) {
219
+ this.flush();
220
+ }
221
+ }
222
+ /**
223
+ * Send a single event immediately
224
+ */
225
+ async send(event) {
226
+ return this.sendBatch([event]);
227
+ }
228
+ /**
229
+ * Flush all queued events
230
+ */
231
+ async flush() {
232
+ if (this.isSending || this.queue.length === 0) {
233
+ return;
234
+ }
235
+ this.isSending = true;
236
+ const events = [...this.queue];
237
+ this.queue = [];
238
+ try {
239
+ await this.sendBatch(events);
240
+ } catch (error2) {
241
+ this.queue = [...events, ...this.queue].slice(0, this.maxQueueSize);
242
+ if (this.debug) {
243
+ console.error("[Statly] Failed to send events:", error2);
244
+ }
245
+ } finally {
246
+ this.isSending = false;
247
+ }
248
+ }
249
+ /**
250
+ * Send a batch of events
251
+ */
252
+ async sendBatch(events) {
253
+ if (events.length === 0) {
254
+ return { success: true };
255
+ }
256
+ const payload = events.length === 1 ? events[0] : { events };
257
+ try {
258
+ const response = await fetch(this.endpoint, {
259
+ method: "POST",
260
+ headers: {
261
+ "Content-Type": "application/json",
262
+ "X-Statly-DSN": this.dsn
263
+ },
264
+ body: JSON.stringify(payload),
265
+ // Use keepalive for better reliability during page unload
266
+ keepalive: true
267
+ });
268
+ if (!response.ok) {
269
+ const errorText = await response.text().catch(() => "Unknown error");
270
+ if (this.debug) {
271
+ console.error("[Statly] API error:", response.status, errorText);
272
+ }
273
+ return {
274
+ success: false,
275
+ status: response.status,
276
+ error: errorText
277
+ };
278
+ }
279
+ if (this.debug) {
280
+ console.log(`[Statly] Sent ${events.length} event(s)`);
281
+ }
282
+ return { success: true, status: response.status };
283
+ } catch (error2) {
284
+ if (this.debug) {
285
+ console.error("[Statly] Network error:", error2);
286
+ }
287
+ return {
288
+ success: false,
289
+ error: error2 instanceof Error ? error2.message : "Network error"
290
+ };
291
+ }
292
+ }
293
+ /**
294
+ * Clean up resources
295
+ */
296
+ destroy() {
297
+ if (this.flushTimer) {
298
+ clearInterval(this.flushTimer);
299
+ }
300
+ this.flush();
301
+ }
302
+ };
303
+
304
+ // src/breadcrumbs.ts
305
+ var BreadcrumbManager = class {
306
+ constructor(maxBreadcrumbs = 100) {
307
+ this.breadcrumbs = [];
308
+ this.maxBreadcrumbs = maxBreadcrumbs;
309
+ }
310
+ /**
311
+ * Add a breadcrumb
312
+ */
313
+ add(breadcrumb) {
314
+ const crumb = {
315
+ timestamp: Date.now(),
316
+ ...breadcrumb
317
+ };
318
+ this.breadcrumbs.push(crumb);
319
+ if (this.breadcrumbs.length > this.maxBreadcrumbs) {
320
+ this.breadcrumbs = this.breadcrumbs.slice(-this.maxBreadcrumbs);
321
+ }
322
+ }
323
+ /**
324
+ * Get all breadcrumbs
325
+ */
326
+ getAll() {
327
+ return [...this.breadcrumbs];
328
+ }
329
+ /**
330
+ * Clear all breadcrumbs
331
+ */
332
+ clear() {
333
+ this.breadcrumbs = [];
334
+ }
335
+ /**
336
+ * Set maximum breadcrumbs to keep
337
+ */
338
+ setMaxBreadcrumbs(max) {
339
+ this.maxBreadcrumbs = max;
340
+ if (this.breadcrumbs.length > max) {
341
+ this.breadcrumbs = this.breadcrumbs.slice(-max);
342
+ }
343
+ }
344
+ };
345
+
346
+ // src/integrations/global-handlers.ts
347
+ var GlobalHandlers = class {
348
+ constructor(options = {}) {
349
+ this.originalOnError = null;
350
+ this.originalOnUnhandledRejection = null;
351
+ this.errorCallback = null;
352
+ this.handleUnhandledRejection = (event) => {
353
+ if (!this.errorCallback) {
354
+ return;
355
+ }
356
+ let error2;
357
+ if (event.reason instanceof Error) {
358
+ error2 = event.reason;
359
+ } else if (typeof event.reason === "string") {
360
+ error2 = new Error(event.reason);
361
+ } else {
362
+ error2 = new Error("Unhandled Promise Rejection");
363
+ error2.reason = event.reason;
364
+ }
365
+ this.errorCallback(error2, {
366
+ mechanism: { type: "onunhandledrejection", handled: false }
367
+ });
368
+ };
369
+ this.options = {
370
+ onerror: options.onerror !== false,
371
+ onunhandledrejection: options.onunhandledrejection !== false
372
+ };
373
+ }
374
+ /**
375
+ * Install global error handlers
376
+ */
377
+ install(callback) {
378
+ this.errorCallback = callback;
379
+ if (typeof window === "undefined") {
380
+ return;
381
+ }
382
+ if (this.options.onerror) {
383
+ this.installOnError();
384
+ }
385
+ if (this.options.onunhandledrejection) {
386
+ this.installOnUnhandledRejection();
387
+ }
388
+ }
389
+ /**
390
+ * Uninstall global error handlers
391
+ */
392
+ uninstall() {
393
+ if (typeof window === "undefined") {
394
+ return;
395
+ }
396
+ if (this.originalOnError !== null) {
397
+ window.onerror = this.originalOnError;
398
+ this.originalOnError = null;
399
+ }
400
+ if (this.originalOnUnhandledRejection !== null) {
401
+ window.removeEventListener("unhandledrejection", this.handleUnhandledRejection);
402
+ this.originalOnUnhandledRejection = null;
403
+ }
404
+ this.errorCallback = null;
405
+ }
406
+ installOnError() {
407
+ this.originalOnError = window.onerror;
408
+ window.onerror = (message, source, lineno, colno, error2) => {
409
+ if (this.originalOnError) {
410
+ this.originalOnError.call(window, message, source, lineno, colno, error2);
411
+ }
412
+ if (this.errorCallback) {
413
+ const errorObj = error2 || new Error(String(message));
414
+ if (!error2 && source) {
415
+ errorObj.filename = source;
416
+ errorObj.lineno = lineno;
417
+ errorObj.colno = colno;
418
+ }
419
+ this.errorCallback(errorObj, {
420
+ mechanism: { type: "onerror", handled: false },
421
+ source,
422
+ lineno,
423
+ colno
424
+ });
425
+ }
426
+ return false;
427
+ };
428
+ }
429
+ installOnUnhandledRejection() {
430
+ this.originalOnUnhandledRejection = this.handleUnhandledRejection.bind(this);
431
+ window.addEventListener("unhandledrejection", this.handleUnhandledRejection);
432
+ }
433
+ };
434
+
435
+ // src/integrations/console.ts
436
+ var ConsoleIntegration = class {
437
+ constructor() {
438
+ this.originalMethods = {};
439
+ this.callback = null;
440
+ this.levels = ["debug", "info", "warn", "error", "log"];
441
+ }
442
+ /**
443
+ * Install console breadcrumb tracking
444
+ */
445
+ install(callback, levels) {
446
+ this.callback = callback;
447
+ if (levels) {
448
+ this.levels = levels;
449
+ }
450
+ if (typeof console === "undefined") {
451
+ return;
452
+ }
453
+ for (const level of this.levels) {
454
+ this.wrapConsoleMethod(level);
455
+ }
456
+ }
457
+ /**
458
+ * Uninstall console breadcrumb tracking
459
+ */
460
+ uninstall() {
461
+ if (typeof console === "undefined") {
462
+ return;
463
+ }
464
+ for (const level of this.levels) {
465
+ if (this.originalMethods[level]) {
466
+ console[level] = this.originalMethods[level];
467
+ delete this.originalMethods[level];
468
+ }
469
+ }
470
+ this.callback = null;
471
+ }
472
+ wrapConsoleMethod(level) {
473
+ const originalMethod = console[level];
474
+ if (!originalMethod) {
475
+ return;
476
+ }
477
+ this.originalMethods[level] = originalMethod;
478
+ console[level] = (...args) => {
479
+ if (this.callback) {
480
+ this.callback({
481
+ category: "console",
482
+ message: this.formatArgs(args),
483
+ level: this.mapLevel(level),
484
+ data: args.length > 1 ? { arguments: args } : void 0
485
+ });
486
+ }
487
+ originalMethod.apply(console, args);
488
+ };
489
+ }
490
+ formatArgs(args) {
491
+ return args.map((arg) => {
492
+ if (typeof arg === "string") {
493
+ return arg;
494
+ }
495
+ if (arg instanceof Error) {
496
+ return arg.message;
497
+ }
498
+ try {
499
+ return JSON.stringify(arg);
500
+ } catch {
501
+ return String(arg);
502
+ }
503
+ }).join(" ");
504
+ }
505
+ mapLevel(consoleLevel) {
506
+ switch (consoleLevel) {
507
+ case "debug":
508
+ return "debug";
509
+ case "info":
510
+ case "log":
511
+ return "info";
512
+ case "warn":
513
+ return "warning";
514
+ case "error":
515
+ return "error";
516
+ default:
517
+ return "info";
518
+ }
519
+ }
520
+ };
521
+
522
+ // src/client.ts
523
+ init_telemetry();
524
+ var SDK_NAME = "@statly/observe-sdk";
525
+ var SDK_VERSION = "0.1.0";
526
+ var StatlyClient = class {
527
+ constructor(options) {
528
+ this.user = null;
529
+ this.initialized = false;
530
+ this.options = this.mergeOptions(options);
531
+ this.transport = new Transport({
532
+ dsn: this.options.dsn,
533
+ debug: this.options.debug
534
+ });
535
+ this.breadcrumbs = new BreadcrumbManager(this.options.maxBreadcrumbs);
536
+ this.globalHandlers = new GlobalHandlers();
537
+ this.consoleIntegration = new ConsoleIntegration();
538
+ TelemetryProvider.getInstance().setClient(this);
539
+ }
540
+ mergeOptions(options) {
541
+ return {
542
+ dsn: options.dsn,
543
+ release: options.release ?? "",
544
+ environment: options.environment ?? this.detectEnvironment(),
545
+ debug: options.debug ?? false,
546
+ sampleRate: options.sampleRate ?? 1,
547
+ maxBreadcrumbs: options.maxBreadcrumbs ?? 100,
548
+ autoCapture: options.autoCapture !== false,
549
+ captureConsole: options.captureConsole !== false,
550
+ captureNetwork: options.captureNetwork ?? false,
551
+ tags: options.tags ?? {},
552
+ beforeSend: options.beforeSend ?? ((e) => e)
553
+ };
554
+ }
555
+ detectEnvironment() {
556
+ if (typeof window !== "undefined") {
557
+ if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") {
558
+ return "development";
559
+ }
560
+ if (window.location.hostname.includes("staging") || window.location.hostname.includes("stage")) {
561
+ return "staging";
562
+ }
563
+ }
564
+ return "production";
565
+ }
566
+ /**
567
+ * Initialize the SDK
568
+ */
569
+ init() {
570
+ if (this.initialized) {
571
+ if (this.options.debug) {
572
+ console.warn("[Statly] SDK already initialized");
573
+ }
574
+ return;
575
+ }
576
+ this.initialized = true;
577
+ if (this.options.autoCapture) {
578
+ this.globalHandlers.install((error2, context) => {
579
+ this.captureError(error2, context);
580
+ });
581
+ }
582
+ if (this.options.captureConsole) {
583
+ this.consoleIntegration.install((breadcrumb) => {
584
+ this.breadcrumbs.add(breadcrumb);
585
+ });
586
+ }
587
+ this.addBreadcrumb({
588
+ category: "navigation",
589
+ message: "SDK initialized",
590
+ level: "info"
591
+ });
592
+ if (this.options.debug) {
593
+ console.log("[Statly] SDK initialized", {
594
+ environment: this.options.environment,
595
+ release: this.options.release
596
+ });
597
+ }
598
+ }
599
+ /**
600
+ * Capture an exception/error
601
+ */
602
+ captureException(error2, context) {
603
+ let errorObj;
604
+ if (error2 instanceof Error) {
605
+ errorObj = error2;
606
+ } else if (typeof error2 === "string") {
607
+ errorObj = new Error(error2);
608
+ } else {
609
+ errorObj = new Error("Unknown error");
610
+ errorObj.originalError = error2;
611
+ }
612
+ return this.captureError(errorObj, context);
613
+ }
614
+ /**
615
+ * Capture a message
616
+ */
617
+ captureMessage(message, level = "info") {
618
+ const event = this.buildEvent({
619
+ message,
620
+ level
621
+ });
622
+ return this.sendEvent(event);
623
+ }
624
+ /**
625
+ * Capture a completed span
626
+ */
627
+ captureSpan(span) {
628
+ const event = this.buildEvent({
629
+ message: `Span: ${span.name}`,
630
+ level: "span",
631
+ span: span.toDict()
632
+ });
633
+ return this.sendEvent(event);
634
+ }
635
+ /**
636
+ * Start a new tracing span
637
+ */
638
+ startSpan(name, tags) {
639
+ return TelemetryProvider.getInstance().startSpan(name, tags);
640
+ }
641
+ /**
642
+ * Execute a function within a trace span
643
+ */
644
+ async trace(name, operation, tags) {
645
+ const { trace: traceFn } = await Promise.resolve().then(() => (init_telemetry(), telemetry_exports));
646
+ return traceFn(name, operation, tags);
647
+ }
648
+ /**
649
+ * Internal method to capture an error
650
+ */
651
+ captureError(error2, context) {
652
+ if (Math.random() > this.options.sampleRate) {
653
+ return "";
654
+ }
655
+ const event = this.buildEvent({
656
+ message: error2.message,
657
+ level: "error",
658
+ stack: error2.stack,
659
+ exception: {
660
+ type: error2.name,
661
+ value: error2.message,
662
+ stacktrace: this.parseStackTrace(error2.stack)
663
+ },
664
+ extra: context
665
+ });
666
+ return this.sendEvent(event);
667
+ }
668
+ /**
669
+ * Build a complete event from partial data
670
+ */
671
+ buildEvent(partial) {
672
+ const event = {
673
+ message: partial.message || "Unknown error",
674
+ timestamp: Date.now(),
675
+ level: partial.level || "error",
676
+ environment: this.options.environment,
677
+ release: this.options.release || void 0,
678
+ url: typeof window !== "undefined" ? window.location.href : void 0,
679
+ user: this.user || void 0,
680
+ tags: { ...this.options.tags, ...partial.tags },
681
+ extra: partial.extra,
682
+ breadcrumbs: this.breadcrumbs.getAll(),
683
+ browser: this.getBrowserInfo(),
684
+ os: this.getOSInfo(),
685
+ sdk: {
686
+ name: SDK_NAME,
687
+ version: SDK_VERSION
688
+ },
689
+ ...partial
690
+ };
691
+ return event;
692
+ }
693
+ /**
694
+ * Parse a stack trace string into structured frames
695
+ */
696
+ parseStackTrace(stack) {
697
+ if (!stack) {
698
+ return void 0;
699
+ }
700
+ const frames = [];
701
+ const lines = stack.split("\n");
702
+ for (const line of lines) {
703
+ const chromeMatch = line.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
704
+ if (chromeMatch) {
705
+ frames.push({
706
+ function: chromeMatch[1] || "<anonymous>",
707
+ filename: chromeMatch[2],
708
+ lineno: parseInt(chromeMatch[3], 10),
709
+ colno: parseInt(chromeMatch[4], 10)
710
+ });
711
+ continue;
712
+ }
713
+ const firefoxMatch = line.match(/^(.+?)@(.+?):(\d+):(\d+)$/);
714
+ if (firefoxMatch) {
715
+ frames.push({
716
+ function: firefoxMatch[1] || "<anonymous>",
717
+ filename: firefoxMatch[2],
718
+ lineno: parseInt(firefoxMatch[3], 10),
719
+ colno: parseInt(firefoxMatch[4], 10)
720
+ });
721
+ }
722
+ }
723
+ return frames.length > 0 ? { frames } : void 0;
724
+ }
725
+ /**
726
+ * Send an event to the server
727
+ */
728
+ sendEvent(event) {
729
+ const processed = this.options.beforeSend(event);
730
+ if (!processed) {
731
+ if (this.options.debug) {
732
+ console.log("[Statly] Event dropped by beforeSend");
733
+ }
734
+ return "";
735
+ }
736
+ const eventId = this.generateEventId();
737
+ this.breadcrumbs.add({
738
+ category: "statly",
739
+ message: `Captured ${event.level}: ${event.message.slice(0, 50)}`,
740
+ level: "info"
741
+ });
742
+ this.transport.enqueue(processed);
743
+ if (this.options.debug) {
744
+ console.log("[Statly] Event captured:", eventId, event.message);
745
+ }
746
+ return eventId;
747
+ }
748
+ generateEventId() {
749
+ return crypto.randomUUID?.() || "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
750
+ const r = Math.random() * 16 | 0;
751
+ const v = c === "x" ? r : r & 3 | 8;
752
+ return v.toString(16);
753
+ });
754
+ }
755
+ /**
756
+ * Set user context
757
+ */
758
+ setUser(user) {
759
+ this.user = user;
760
+ if (this.options.debug && user) {
761
+ console.log("[Statly] User set:", user.id || user.email);
762
+ }
763
+ }
764
+ /**
765
+ * Set a single tag
766
+ */
767
+ setTag(key, value) {
768
+ this.options.tags[key] = value;
769
+ }
770
+ /**
771
+ * Set multiple tags
772
+ */
773
+ setTags(tags) {
774
+ Object.assign(this.options.tags, tags);
775
+ }
776
+ /**
777
+ * Add a breadcrumb
778
+ */
779
+ addBreadcrumb(breadcrumb) {
780
+ this.breadcrumbs.add(breadcrumb);
781
+ }
782
+ /**
783
+ * Get browser info
784
+ */
785
+ getBrowserInfo() {
786
+ if (typeof navigator === "undefined") {
787
+ return void 0;
788
+ }
789
+ const ua = navigator.userAgent;
790
+ let name = "Unknown";
791
+ let version = "";
792
+ if (ua.includes("Firefox/")) {
793
+ name = "Firefox";
794
+ version = ua.split("Firefox/")[1]?.split(" ")[0] || "";
795
+ } else if (ua.includes("Chrome/")) {
796
+ name = "Chrome";
797
+ version = ua.split("Chrome/")[1]?.split(" ")[0] || "";
798
+ } else if (ua.includes("Safari/") && !ua.includes("Chrome")) {
799
+ name = "Safari";
800
+ version = ua.split("Version/")[1]?.split(" ")[0] || "";
801
+ } else if (ua.includes("Edge/") || ua.includes("Edg/")) {
802
+ name = "Edge";
803
+ version = ua.split(/Edg?e?\//)[1]?.split(" ")[0] || "";
804
+ }
805
+ return { name, version };
806
+ }
807
+ /**
808
+ * Get OS info
809
+ */
810
+ getOSInfo() {
811
+ if (typeof navigator === "undefined") {
812
+ return void 0;
813
+ }
814
+ const ua = navigator.userAgent;
815
+ let name = "Unknown";
816
+ let version = "";
817
+ if (ua.includes("Windows")) {
818
+ name = "Windows";
819
+ const match = ua.match(/Windows NT (\d+\.\d+)/);
820
+ if (match) version = match[1];
821
+ } else if (ua.includes("Mac OS X")) {
822
+ name = "macOS";
823
+ const match = ua.match(/Mac OS X (\d+[._]\d+)/);
824
+ if (match) version = match[1].replace("_", ".");
825
+ } else if (ua.includes("Linux")) {
826
+ name = "Linux";
827
+ } else if (ua.includes("Android")) {
828
+ name = "Android";
829
+ const match = ua.match(/Android (\d+\.\d+)/);
830
+ if (match) version = match[1];
831
+ } else if (ua.includes("iOS") || ua.includes("iPhone") || ua.includes("iPad")) {
832
+ name = "iOS";
833
+ const match = ua.match(/OS (\d+_\d+)/);
834
+ if (match) version = match[1].replace("_", ".");
835
+ }
836
+ return { name, version };
837
+ }
838
+ /**
839
+ * Flush pending events and clean up
840
+ */
841
+ async close() {
842
+ this.globalHandlers.uninstall();
843
+ this.consoleIntegration.uninstall();
844
+ await this.transport.flush();
845
+ this.transport.destroy();
846
+ this.initialized = false;
847
+ }
848
+ /**
849
+ * Force flush pending events
850
+ */
851
+ async flush() {
852
+ await this.transport.flush();
853
+ }
854
+ };
855
+
856
+ // src/logger/formatters/console.ts
857
+ var COLORS = {
858
+ reset: "\x1B[0m",
859
+ bold: "\x1B[1m",
860
+ dim: "\x1B[2m",
861
+ // Foreground colors
862
+ black: "\x1B[30m",
863
+ red: "\x1B[31m",
864
+ green: "\x1B[32m",
865
+ yellow: "\x1B[33m",
866
+ blue: "\x1B[34m",
867
+ magenta: "\x1B[35m",
868
+ cyan: "\x1B[36m",
869
+ white: "\x1B[37m",
870
+ gray: "\x1B[90m",
871
+ // Background colors
872
+ bgRed: "\x1B[41m",
873
+ bgYellow: "\x1B[43m"
874
+ };
875
+ var LEVEL_COLORS = {
876
+ trace: COLORS.gray,
877
+ debug: COLORS.cyan,
878
+ info: COLORS.green,
879
+ warn: COLORS.yellow,
880
+ error: COLORS.red,
881
+ fatal: `${COLORS.bgRed}${COLORS.white}`,
882
+ audit: COLORS.magenta
883
+ };
884
+
885
+ // src/index.ts
886
+ var client = null;
887
+ function loadDsnFromEnv() {
888
+ if (typeof process !== "undefined" && process.env) {
889
+ return process.env.STATLY_DSN || process.env.NEXT_PUBLIC_STATLY_DSN || process.env.STATLY_OBSERVE_DSN;
890
+ }
891
+ return void 0;
892
+ }
893
+ function loadEnvironmentFromEnv() {
894
+ if (typeof process !== "undefined" && process.env) {
895
+ return process.env.STATLY_ENVIRONMENT || process.env.NODE_ENV;
896
+ }
897
+ return void 0;
898
+ }
899
+ function init(options) {
900
+ if (client) {
901
+ console.warn("[Statly] SDK already initialized. Call close() first to reinitialize.");
902
+ return;
903
+ }
904
+ const dsn = options?.dsn || loadDsnFromEnv();
905
+ if (!dsn) {
906
+ console.error("[Statly] No DSN provided. Set STATLY_DSN in your environment or pass dsn to init().");
907
+ console.error("[Statly] Get your DSN at https://statly.live/dashboard/observe/setup");
908
+ return;
909
+ }
910
+ const environment = options?.environment || loadEnvironmentFromEnv();
911
+ const finalOptions = {
912
+ ...options,
913
+ dsn,
914
+ environment
915
+ };
916
+ client = new StatlyClient(finalOptions);
917
+ client.init();
918
+ }
919
+ function captureException(error2, context) {
920
+ if (!client) {
921
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
922
+ return "";
923
+ }
924
+ return client.captureException(error2, context);
925
+ }
926
+ function captureMessage(message, level = "info") {
927
+ if (!client) {
928
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
929
+ return "";
930
+ }
931
+ return client.captureMessage(message, level);
932
+ }
933
+ function setUser(user) {
934
+ if (!client) {
935
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
936
+ return;
937
+ }
938
+ client.setUser(user);
939
+ }
940
+ function setTag(key, value) {
941
+ if (!client) {
942
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
943
+ return;
944
+ }
945
+ client.setTag(key, value);
946
+ }
947
+ function setTags(tags) {
948
+ if (!client) {
949
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
950
+ return;
951
+ }
952
+ client.setTags(tags);
953
+ }
954
+ function addBreadcrumb(breadcrumb) {
955
+ if (!client) {
956
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
957
+ return;
958
+ }
959
+ client.addBreadcrumb(breadcrumb);
960
+ }
961
+ async function flush() {
962
+ if (!client) {
963
+ return;
964
+ }
965
+ await client.flush();
966
+ }
967
+ async function close() {
968
+ if (!client) {
969
+ return;
970
+ }
971
+ await client.close();
972
+ client = null;
973
+ }
974
+ function getClient() {
975
+ return client;
976
+ }
977
+ async function trace3(name, operation, tags) {
978
+ if (!client) {
979
+ return operation(null);
980
+ }
981
+ return client.trace(name, operation, tags);
982
+ }
983
+ function startSpan(name, tags) {
984
+ if (!client) return null;
985
+ return client.startSpan(name, tags);
986
+ }
987
+ function captureSpan(span) {
988
+ if (!client) return "";
989
+ return client.captureSpan(span);
990
+ }
991
+ var Statly = {
992
+ init,
993
+ captureException,
994
+ captureMessage,
995
+ setUser,
996
+ setTag,
997
+ setTags,
998
+ addBreadcrumb,
999
+ flush,
1000
+ close,
1001
+ getClient,
1002
+ trace: trace3,
1003
+ startSpan,
1004
+ captureSpan
1005
+ };
1006
+
1007
+ // src/integrations/express.ts
1008
+ function requestHandler() {
1009
+ return (req, res, next) => {
1010
+ req.statlyContext = {
1011
+ transactionName: `${req.method} ${req.path || req.url}`,
1012
+ startTime: Date.now()
1013
+ };
1014
+ Statly.addBreadcrumb({
1015
+ category: "http",
1016
+ message: `${req.method} ${req.originalUrl || req.url}`,
1017
+ level: "info",
1018
+ data: {
1019
+ method: req.method,
1020
+ url: req.originalUrl || req.url
1021
+ }
1022
+ });
1023
+ if (req.user) {
1024
+ Statly.setUser({
1025
+ id: req.user.id?.toString(),
1026
+ email: req.user.email?.toString()
1027
+ });
1028
+ }
1029
+ res.on("finish", () => {
1030
+ const duration = req.statlyContext?.startTime ? Date.now() - req.statlyContext.startTime : void 0;
1031
+ Statly.addBreadcrumb({
1032
+ category: "http",
1033
+ message: `Response ${res.statusCode}`,
1034
+ level: res.statusCode >= 400 ? "error" : "info",
1035
+ data: {
1036
+ statusCode: res.statusCode,
1037
+ duration
1038
+ }
1039
+ });
1040
+ });
1041
+ next();
1042
+ };
1043
+ }
1044
+ function expressErrorHandler(options = {}) {
1045
+ return (err, req, res, next) => {
1046
+ const error2 = err instanceof Error ? err : new Error(String(err));
1047
+ if (options.shouldHandleError && !options.shouldHandleError(error2)) {
1048
+ return next(err);
1049
+ }
1050
+ const context = {
1051
+ request: {
1052
+ method: req.method,
1053
+ url: req.originalUrl || req.url,
1054
+ headers: sanitizeHeaders(req.headers),
1055
+ query: req.query,
1056
+ data: sanitizeBody(req.body)
1057
+ }
1058
+ };
1059
+ if (req.ip) {
1060
+ context.ip = req.ip;
1061
+ }
1062
+ if (req.user) {
1063
+ Statly.setUser({
1064
+ id: req.user.id?.toString(),
1065
+ email: req.user.email?.toString()
1066
+ });
1067
+ }
1068
+ if (req.statlyContext?.transactionName) {
1069
+ Statly.setTag("transaction", req.statlyContext.transactionName);
1070
+ }
1071
+ Statly.captureException(error2, context);
1072
+ next(err);
1073
+ };
1074
+ }
1075
+ function sanitizeHeaders(headers) {
1076
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
1077
+ const sanitized = {};
1078
+ for (const [key, value] of Object.entries(headers)) {
1079
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
1080
+ sanitized[key] = "[Filtered]";
1081
+ } else {
1082
+ sanitized[key] = value;
1083
+ }
1084
+ }
1085
+ return sanitized;
1086
+ }
1087
+ function sanitizeBody(body) {
1088
+ if (!body || typeof body !== "object") {
1089
+ return body;
1090
+ }
1091
+ const sensitiveFields = ["password", "secret", "token", "apiKey", "api_key", "credit_card", "creditCard", "ssn"];
1092
+ const sanitized = {};
1093
+ for (const [key, value] of Object.entries(body)) {
1094
+ if (sensitiveFields.some((field) => key.toLowerCase().includes(field.toLowerCase()))) {
1095
+ sanitized[key] = "[Filtered]";
1096
+ } else if (typeof value === "object" && value !== null) {
1097
+ sanitized[key] = sanitizeBody(value);
1098
+ } else {
1099
+ sanitized[key] = value;
1100
+ }
1101
+ }
1102
+ return sanitized;
1103
+ }
1104
+ // Annotate the CommonJS export names for ESM import in node:
1105
+ 0 && (module.exports = {
1106
+ expressErrorHandler,
1107
+ requestHandler
1108
+ });