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