@moonwatch/js 0.1.8

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.js ADDED
@@ -0,0 +1,889 @@
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 __typeError = (msg) => {
7
+ throw TypeError(msg);
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
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
23
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
24
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
25
+
26
+ // src/index.ts
27
+ var index_exports = {};
28
+ __export(index_exports, {
29
+ Logger: () => Logger,
30
+ createLogger: () => createLogger,
31
+ default: () => index_default
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // ../node_modules/non-error/index.js
36
+ var isNonErrorSymbol = /* @__PURE__ */ Symbol("isNonError");
37
+ function defineProperty(object, key, value) {
38
+ Object.defineProperty(object, key, {
39
+ value,
40
+ writable: false,
41
+ enumerable: false,
42
+ configurable: false
43
+ });
44
+ }
45
+ function stringify(value) {
46
+ if (value === void 0) {
47
+ return "undefined";
48
+ }
49
+ if (value === null) {
50
+ return "null";
51
+ }
52
+ if (typeof value === "string") {
53
+ return value;
54
+ }
55
+ if (typeof value === "number" || typeof value === "boolean") {
56
+ return String(value);
57
+ }
58
+ if (typeof value === "bigint") {
59
+ return `${value}n`;
60
+ }
61
+ if (typeof value === "symbol") {
62
+ return value.toString();
63
+ }
64
+ if (typeof value === "function") {
65
+ return `[Function${value.name ? ` ${value.name}` : " (anonymous)"}]`;
66
+ }
67
+ if (value instanceof Error) {
68
+ try {
69
+ return String(value);
70
+ } catch {
71
+ return "<Unserializable error>";
72
+ }
73
+ }
74
+ try {
75
+ return JSON.stringify(value);
76
+ } catch {
77
+ try {
78
+ return String(value);
79
+ } catch {
80
+ return "<Unserializable value>";
81
+ }
82
+ }
83
+ }
84
+ var _NonError_static, handleCallback_fn;
85
+ var _NonError = class _NonError extends Error {
86
+ constructor(value, { superclass: Superclass = Error } = {}) {
87
+ if (_NonError.isNonError(value)) {
88
+ return value;
89
+ }
90
+ if (value instanceof Error) {
91
+ throw new TypeError("Do not pass Error instances to NonError. Throw the error directly instead.");
92
+ }
93
+ super(`Non-error value: ${stringify(value)}`);
94
+ if (Superclass !== Error) {
95
+ Object.setPrototypeOf(this, Superclass.prototype);
96
+ }
97
+ defineProperty(this, "name", "NonError");
98
+ defineProperty(this, isNonErrorSymbol, true);
99
+ defineProperty(this, "isNonError", true);
100
+ defineProperty(this, "value", value);
101
+ }
102
+ static isNonError(value) {
103
+ return value?.[isNonErrorSymbol] === true;
104
+ }
105
+ static try(callback) {
106
+ var _a;
107
+ return __privateMethod(_a = _NonError, _NonError_static, handleCallback_fn).call(_a, callback, []);
108
+ }
109
+ static wrap(callback) {
110
+ return (...arguments_) => {
111
+ var _a;
112
+ return __privateMethod(_a = _NonError, _NonError_static, handleCallback_fn).call(_a, callback, arguments_);
113
+ };
114
+ }
115
+ // This makes instanceof work even when using the `superclass` option
116
+ static [Symbol.hasInstance](instance) {
117
+ return _NonError.isNonError(instance);
118
+ }
119
+ };
120
+ _NonError_static = new WeakSet();
121
+ handleCallback_fn = function(callback, arguments_) {
122
+ try {
123
+ const result = callback(...arguments_);
124
+ if (result && typeof result.then === "function") {
125
+ return (async () => {
126
+ try {
127
+ return await result;
128
+ } catch (error) {
129
+ if (error instanceof Error) {
130
+ throw error;
131
+ }
132
+ throw new _NonError(error);
133
+ }
134
+ })();
135
+ }
136
+ return result;
137
+ } catch (error) {
138
+ if (error instanceof Error) {
139
+ throw error;
140
+ }
141
+ throw new _NonError(error);
142
+ }
143
+ };
144
+ __privateAdd(_NonError, _NonError_static);
145
+ var NonError = _NonError;
146
+
147
+ // ../node_modules/serialize-error/error-constructors.js
148
+ var list = [
149
+ // Native ES errors https://262.ecma-international.org/12.0/#sec-well-known-intrinsic-objects
150
+ Error,
151
+ EvalError,
152
+ RangeError,
153
+ ReferenceError,
154
+ SyntaxError,
155
+ TypeError,
156
+ URIError,
157
+ AggregateError,
158
+ // Built-in errors
159
+ globalThis.DOMException,
160
+ // Node-specific errors
161
+ // https://nodejs.org/api/errors.html
162
+ globalThis.AssertionError,
163
+ globalThis.SystemError
164
+ ].filter(Boolean).map((constructor) => [constructor.name, constructor]);
165
+ var errorConstructors = new Map(list);
166
+ var errorFactories = /* @__PURE__ */ new Map();
167
+
168
+ // ../node_modules/serialize-error/index.js
169
+ var errorProperties = [
170
+ {
171
+ property: "name",
172
+ enumerable: false
173
+ },
174
+ {
175
+ property: "message",
176
+ enumerable: false
177
+ },
178
+ {
179
+ property: "stack",
180
+ enumerable: false
181
+ },
182
+ {
183
+ property: "code",
184
+ enumerable: true
185
+ },
186
+ {
187
+ property: "cause",
188
+ enumerable: false
189
+ },
190
+ {
191
+ property: "errors",
192
+ enumerable: false
193
+ }
194
+ ];
195
+ var toJsonWasCalled = /* @__PURE__ */ new WeakSet();
196
+ var toJSON = (from) => {
197
+ toJsonWasCalled.add(from);
198
+ const json = from.toJSON();
199
+ toJsonWasCalled.delete(from);
200
+ return json;
201
+ };
202
+ var newError = (name) => {
203
+ if (name === "NonError") {
204
+ return new NonError();
205
+ }
206
+ const factory = errorFactories.get(name);
207
+ if (factory) {
208
+ return factory();
209
+ }
210
+ const ErrorConstructor = errorConstructors.get(name) ?? Error;
211
+ return ErrorConstructor === AggregateError ? new ErrorConstructor([]) : new ErrorConstructor();
212
+ };
213
+ var destroyCircular = ({
214
+ from,
215
+ seen,
216
+ to,
217
+ forceEnumerable,
218
+ maxDepth,
219
+ depth,
220
+ useToJSON,
221
+ serialize
222
+ }) => {
223
+ if (!to) {
224
+ if (Array.isArray(from)) {
225
+ to = [];
226
+ } else if (!serialize && isErrorLike(from)) {
227
+ to = newError(from.name);
228
+ } else {
229
+ to = {};
230
+ }
231
+ }
232
+ seen.add(from);
233
+ if (depth >= maxDepth) {
234
+ seen.delete(from);
235
+ return to;
236
+ }
237
+ if (useToJSON && typeof from.toJSON === "function" && !toJsonWasCalled.has(from)) {
238
+ seen.delete(from);
239
+ return toJSON(from);
240
+ }
241
+ const continueDestroyCircular = (value) => destroyCircular({
242
+ from: value,
243
+ seen,
244
+ forceEnumerable,
245
+ maxDepth,
246
+ depth: depth + 1,
247
+ useToJSON,
248
+ serialize
249
+ });
250
+ for (const key of Object.keys(from)) {
251
+ const value = from[key];
252
+ if (value && value instanceof Uint8Array && value.constructor.name === "Buffer") {
253
+ to[key] = serialize ? "[object Buffer]" : value;
254
+ continue;
255
+ }
256
+ if (value !== null && typeof value === "object" && typeof value.pipe === "function") {
257
+ to[key] = serialize ? "[object Stream]" : value;
258
+ continue;
259
+ }
260
+ if (typeof value === "function") {
261
+ if (!serialize) {
262
+ to[key] = value;
263
+ }
264
+ continue;
265
+ }
266
+ if (serialize && typeof value === "bigint") {
267
+ to[key] = `${value}n`;
268
+ continue;
269
+ }
270
+ if (!value || typeof value !== "object") {
271
+ try {
272
+ to[key] = value;
273
+ } catch {
274
+ }
275
+ continue;
276
+ }
277
+ if (!seen.has(value)) {
278
+ to[key] = continueDestroyCircular(value);
279
+ continue;
280
+ }
281
+ to[key] = "[Circular]";
282
+ }
283
+ if (serialize || to instanceof Error) {
284
+ for (const { property, enumerable } of errorProperties) {
285
+ const value = from[property];
286
+ if (value === void 0 || value === null) {
287
+ continue;
288
+ }
289
+ const descriptor = Object.getOwnPropertyDescriptor(to, property);
290
+ if (descriptor?.configurable === false) {
291
+ continue;
292
+ }
293
+ let processedValue = value;
294
+ if (typeof value === "object") {
295
+ processedValue = seen.has(value) ? "[Circular]" : continueDestroyCircular(value);
296
+ }
297
+ Object.defineProperty(to, property, {
298
+ value: processedValue,
299
+ enumerable: forceEnumerable || enumerable,
300
+ configurable: true,
301
+ writable: true
302
+ });
303
+ }
304
+ }
305
+ seen.delete(from);
306
+ return to;
307
+ };
308
+ function serializeError(value, options = {}) {
309
+ const {
310
+ maxDepth = Number.POSITIVE_INFINITY,
311
+ useToJSON = true
312
+ } = options;
313
+ if (typeof value === "object" && value !== null) {
314
+ return destroyCircular({
315
+ from: value,
316
+ seen: /* @__PURE__ */ new Set(),
317
+ forceEnumerable: true,
318
+ maxDepth,
319
+ depth: 0,
320
+ useToJSON,
321
+ serialize: true
322
+ });
323
+ }
324
+ if (typeof value === "function") {
325
+ value = "<Function>";
326
+ }
327
+ return destroyCircular({
328
+ from: new NonError(value),
329
+ seen: /* @__PURE__ */ new Set(),
330
+ forceEnumerable: true,
331
+ maxDepth,
332
+ depth: 0,
333
+ useToJSON,
334
+ serialize: true
335
+ });
336
+ }
337
+ function isErrorLike(value) {
338
+ return Boolean(value) && typeof value === "object" && typeof value.name === "string" && typeof value.message === "string" && typeof value.stack === "string";
339
+ }
340
+
341
+ // src/index.ts
342
+ var RELEASE_ID = typeof __MOONWATCH_RELEASE__ !== "undefined" ? __MOONWATCH_RELEASE__ : void 0;
343
+ var LEVEL_ORDER = {
344
+ DEBUG: 0,
345
+ INFO: 1,
346
+ WARN: 2,
347
+ ERROR: 3,
348
+ FATAL: 4
349
+ };
350
+ var SDK_VERSION = "0.1.4";
351
+ var DEFAULT_BASE_URL = "https://log.terodato.com";
352
+ var BATCH_SIZE = 50;
353
+ var MAX_BUFFER_SIZE = 1e3;
354
+ var FLUSH_INTERVAL_MS = 1e3;
355
+ var FETCH_TIMEOUT_MS = 1e4;
356
+ var batchCounter = 0;
357
+ var generateBatchId = () => `${Date.now()}-${++batchCounter}`;
358
+ var originalConsole = {
359
+ log: console.log.bind(console),
360
+ info: console.info.bind(console),
361
+ warn: console.warn.bind(console),
362
+ error: console.error.bind(console),
363
+ debug: console.debug.bind(console)
364
+ };
365
+ function resolveLevel(level) {
366
+ if (!level) return "DEBUG";
367
+ if (level in LEVEL_ORDER) return level;
368
+ return "INFO";
369
+ }
370
+ function safeStringify(value) {
371
+ try {
372
+ return JSON.stringify(value);
373
+ } catch {
374
+ const seen = /* @__PURE__ */ new WeakSet();
375
+ return JSON.stringify(value, (_key, val) => {
376
+ if (typeof val === "object" && val !== null) {
377
+ if (seen.has(val)) return "[Circular]";
378
+ seen.add(val);
379
+ }
380
+ return val;
381
+ });
382
+ }
383
+ }
384
+ var _Logger = class _Logger {
385
+ constructor(config) {
386
+ this.buffer = [];
387
+ this.flushTimer = null;
388
+ this.flushPromise = null;
389
+ this.consoleIntercepted = false;
390
+ this.httpBackoffMs = 0;
391
+ this.maxBackoffMs = 6e4;
392
+ this.consecutiveHttpFailures = 0;
393
+ // Error capture via window event listeners (no console.error wrapping to
394
+ // avoid polluting stack traces shown in Next.js / React error overlays)
395
+ this._onError = null;
396
+ this._onUnhandledRejection = null;
397
+ // WebSocket state
398
+ this.ws = null;
399
+ this.wsState = "disconnected";
400
+ this.wsReconnectTimer = null;
401
+ this.wsReconnectAttempts = 0;
402
+ this.maxWsReconnectAttempts = 5;
403
+ // Browser lifecycle hooks for best-effort flush on page unload
404
+ this._onVisibilityChange = null;
405
+ this._onBeforeUnload = null;
406
+ this.config = {
407
+ logId: config.logId,
408
+ apiKey: config.apiKey,
409
+ group: config.group,
410
+ level: resolveLevel(config.level),
411
+ onError: config.onError,
412
+ traceId: config.traceId,
413
+ silent: config.silent ?? false,
414
+ debug: config.debug ?? false
415
+ };
416
+ this.proxyMode = !!config._ingestUrl;
417
+ const baseUrl = config._endpoint ?? DEFAULT_BASE_URL;
418
+ this.baseUrl = baseUrl;
419
+ const wsBaseUrl = config._wsEndpoint ?? baseUrl;
420
+ this.httpIngestUrl = config._ingestUrl ?? `${baseUrl}/ingest/http`;
421
+ this.wsIngestUrl = `${wsBaseUrl.replace(/^http/, "ws")}/ingest/ws`;
422
+ this.startFlushTimer();
423
+ if (!this.proxyMode && typeof WebSocket !== "undefined") {
424
+ this.connectWebSocket();
425
+ } else if (this.proxyMode) {
426
+ this.debugLog("Proxy mode enabled, using HTTP transport only");
427
+ } else {
428
+ this.debugLog("WebSocket not available, using HTTP transport only");
429
+ }
430
+ this.registerLifecycleHooks();
431
+ }
432
+ debugLog(msg, ...args) {
433
+ if (this.config.debug) {
434
+ originalConsole.debug("[Moonwatch]", msg, ...args);
435
+ }
436
+ }
437
+ connectWebSocket() {
438
+ if (this.wsState === "connecting" || this.wsState === "connected") {
439
+ return;
440
+ }
441
+ this.wsState = "connecting";
442
+ this.debugLog("WebSocket connecting to", this.wsIngestUrl);
443
+ try {
444
+ this.ws = new WebSocket(this.wsIngestUrl, ["api_key", this.config.apiKey]);
445
+ this.ws.onopen = () => {
446
+ this.wsReconnectAttempts = 0;
447
+ this.wsState = "connected";
448
+ this.debugLog("WebSocket connected");
449
+ };
450
+ this.ws.onmessage = (event) => {
451
+ try {
452
+ const msg = JSON.parse(event.data);
453
+ if (!msg.success) {
454
+ originalConsole.error("[Moonwatch] WebSocket log ingestion failed:", msg.error);
455
+ }
456
+ } catch {
457
+ }
458
+ };
459
+ this.ws.onerror = () => {
460
+ };
461
+ this.ws.onclose = () => {
462
+ this.wsState = "disconnected";
463
+ this.ws = null;
464
+ if (this.wsReconnectAttempts < this.maxWsReconnectAttempts) {
465
+ const delay = Math.min(1e3 * Math.pow(2, this.wsReconnectAttempts), 3e4);
466
+ this.wsReconnectAttempts++;
467
+ this.debugLog(`WebSocket disconnected, reconnecting in ${delay}ms (attempt ${this.wsReconnectAttempts}/${this.maxWsReconnectAttempts})`);
468
+ this.wsReconnectTimer = setTimeout(() => this.connectWebSocket(), delay);
469
+ } else {
470
+ this.debugLog("WebSocket max reconnect attempts reached, using HTTP only");
471
+ }
472
+ };
473
+ } catch {
474
+ this.wsState = "failed";
475
+ this.debugLog("WebSocket connection failed");
476
+ }
477
+ }
478
+ startFlushTimer() {
479
+ if (this.flushTimer) {
480
+ clearInterval(this.flushTimer);
481
+ }
482
+ this.flushTimer = setInterval(() => {
483
+ this.flush();
484
+ }, FLUSH_INTERVAL_MS);
485
+ }
486
+ shouldLog(level) {
487
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[this.config.level];
488
+ }
489
+ formatArgs(args) {
490
+ return args.map((arg) => {
491
+ if (typeof arg === "string") return arg;
492
+ if (arg instanceof Error) return `${arg.message}
493
+ ${arg.stack}`;
494
+ try {
495
+ return JSON.stringify(arg, null, 2);
496
+ } catch {
497
+ return String(arg);
498
+ }
499
+ }).join(" ");
500
+ }
501
+ log(level, message, options) {
502
+ if (!this.shouldLog(level)) return;
503
+ if (!this.config.silent) {
504
+ const method = _Logger.CONSOLE_METHOD[level];
505
+ const consoleArgs = [message];
506
+ if (options?.metadata && Object.keys(options.metadata).length > 0) {
507
+ consoleArgs.push(options.metadata);
508
+ }
509
+ if (options?.stack) {
510
+ consoleArgs.push("\n" + options.stack);
511
+ }
512
+ originalConsole[method](...consoleArgs);
513
+ }
514
+ const entry = {
515
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
516
+ level,
517
+ message,
518
+ logId: this.config.logId,
519
+ group: options?.group ?? this.config.group,
520
+ trace_id: options?.traceId ?? this.config.traceId,
521
+ stack: options?.stack,
522
+ error_type: options?.errorType,
523
+ release_id: RELEASE_ID,
524
+ watcher_id: options?.watcherId,
525
+ metadata: options?.metadata
526
+ };
527
+ this.buffer.push(entry);
528
+ if (this.buffer.length > MAX_BUFFER_SIZE) {
529
+ const dropped = this.buffer.length - MAX_BUFFER_SIZE;
530
+ this.buffer.splice(0, dropped);
531
+ this.debugLog(`Buffer full, dropped ${dropped} oldest logs`);
532
+ }
533
+ if (this.buffer.length >= BATCH_SIZE) {
534
+ this.flush();
535
+ }
536
+ }
537
+ parseArgs(msgOrObj, metadata) {
538
+ if (typeof msgOrObj === "object") {
539
+ return {
540
+ message: msgOrObj.message,
541
+ options: { traceId: msgOrObj.traceId, group: msgOrObj.group, watcherId: msgOrObj.watcherId, metadata: msgOrObj.metadata }
542
+ };
543
+ }
544
+ if (metadata !== void 0) {
545
+ return { message: msgOrObj, options: { metadata } };
546
+ }
547
+ return { message: msgOrObj };
548
+ }
549
+ debug(msgOrObj, metadata) {
550
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
551
+ this.log("DEBUG", message, options);
552
+ }
553
+ info(msgOrObj, metadata) {
554
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
555
+ this.log("INFO", message, options);
556
+ }
557
+ warn(msgOrObj, metadata) {
558
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
559
+ this.log("WARN", message, options);
560
+ }
561
+ error(msgOrObj, metadata) {
562
+ if (msgOrObj instanceof Error) {
563
+ this.log("ERROR", msgOrObj.message, {
564
+ metadata,
565
+ stack: msgOrObj.stack,
566
+ errorType: msgOrObj.name
567
+ });
568
+ return;
569
+ }
570
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
571
+ this.log("ERROR", message, options);
572
+ }
573
+ fatal(msgOrObj, metadata) {
574
+ if (msgOrObj instanceof Error) {
575
+ this.log("FATAL", msgOrObj.message, {
576
+ metadata,
577
+ stack: msgOrObj.stack,
578
+ errorType: msgOrObj.name
579
+ });
580
+ return;
581
+ }
582
+ const { message, options } = this.parseArgs(msgOrObj, metadata);
583
+ this.log("FATAL", message, options);
584
+ }
585
+ withTraceId(traceId) {
586
+ return new ScopedLogger(this, void 0, traceId, void 0);
587
+ }
588
+ withGroup(group) {
589
+ return new ScopedLogger(this, group, void 0, void 0);
590
+ }
591
+ withWatcher(watcherId) {
592
+ return new ScopedLogger(this, void 0, void 0, watcherId);
593
+ }
594
+ setTraceId(traceId) {
595
+ this.config.traceId = traceId;
596
+ }
597
+ setGroup(group) {
598
+ this.config.group = group;
599
+ }
600
+ interceptConsole(group, options) {
601
+ if (this.consoleIntercepted) return;
602
+ this.consoleIntercepted = true;
603
+ const self = this;
604
+ const logGroup = group ?? "console";
605
+ const wrap = (original, level) => {
606
+ const wrapped = (...args) => {
607
+ let stack;
608
+ let errorType;
609
+ if (level === "ERROR") {
610
+ const errArg = args.find((a) => isErrorLike(a));
611
+ if (errArg) {
612
+ const serialized = serializeError(errArg);
613
+ stack = serialized.stack;
614
+ errorType = serialized.name;
615
+ } else {
616
+ const lines = new Error().stack?.split("\n");
617
+ if (lines) {
618
+ const isV8 = lines[0]?.trimStart().startsWith("Error");
619
+ stack = lines.slice(isV8 ? 2 : 1).join("\n");
620
+ }
621
+ }
622
+ }
623
+ queueMicrotask(() => {
624
+ self.log(level, self.formatArgs(args), { group: logGroup, stack, errorType });
625
+ });
626
+ return original.apply(console, args);
627
+ };
628
+ Object.defineProperty(wrapped, "name", { value: original.name });
629
+ return wrapped;
630
+ };
631
+ console.debug = wrap(originalConsole.debug, "DEBUG");
632
+ console.log = wrap(originalConsole.log, "INFO");
633
+ console.info = wrap(originalConsole.info, "INFO");
634
+ console.warn = wrap(originalConsole.warn, "WARN");
635
+ if (options?.wrapErrors !== false) {
636
+ console.error = wrap(originalConsole.error, "ERROR");
637
+ }
638
+ if (typeof window !== "undefined") {
639
+ this._onError = (event) => {
640
+ self.log("ERROR", event.message, {
641
+ group: logGroup,
642
+ stack: event.error?.stack,
643
+ errorType: event.error?.name
644
+ });
645
+ };
646
+ this._onUnhandledRejection = (event) => {
647
+ const err = event.reason;
648
+ const message = err instanceof Error ? err.message : String(err);
649
+ self.log("ERROR", message, {
650
+ group: logGroup,
651
+ stack: err instanceof Error ? err.stack : void 0,
652
+ errorType: err instanceof Error ? err.name : "UnhandledRejection"
653
+ });
654
+ };
655
+ window.addEventListener("error", this._onError);
656
+ window.addEventListener("unhandledrejection", this._onUnhandledRejection);
657
+ }
658
+ }
659
+ restoreConsole() {
660
+ if (!this.consoleIntercepted) return;
661
+ this.consoleIntercepted = false;
662
+ console.debug = originalConsole.debug;
663
+ console.log = originalConsole.log;
664
+ console.info = originalConsole.info;
665
+ console.warn = originalConsole.warn;
666
+ if (console.error !== originalConsole.error) {
667
+ console.error = originalConsole.error;
668
+ }
669
+ if (typeof window !== "undefined") {
670
+ if (this._onError) {
671
+ window.removeEventListener("error", this._onError);
672
+ this._onError = null;
673
+ }
674
+ if (this._onUnhandledRejection) {
675
+ window.removeEventListener("unhandledrejection", this._onUnhandledRejection);
676
+ this._onUnhandledRejection = null;
677
+ }
678
+ }
679
+ }
680
+ async flush() {
681
+ if (this.flushPromise) {
682
+ await this.flushPromise;
683
+ }
684
+ if (this.buffer.length === 0) return;
685
+ const logs = this.buffer.splice(0, this.buffer.length);
686
+ this.flushPromise = this.doFlush(logs);
687
+ try {
688
+ await this.flushPromise;
689
+ } finally {
690
+ this.flushPromise = null;
691
+ }
692
+ }
693
+ async doFlush(logs) {
694
+ const batchId = generateBatchId();
695
+ if (this.wsState === "connected" && typeof WebSocket !== "undefined") {
696
+ const sent = this.sendViaWebSocket(logs, batchId);
697
+ if (sent) return;
698
+ }
699
+ await this.sendViaHttp(logs, batchId);
700
+ }
701
+ sendViaWebSocket(logs, batchId) {
702
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
703
+ return false;
704
+ }
705
+ try {
706
+ this.ws.send(safeStringify({ type: "logs", batchId, logs }));
707
+ this.debugLog(`Flushed ${logs.length} logs via WebSocket (batch ${batchId})`);
708
+ return true;
709
+ } catch {
710
+ this.debugLog("WebSocket send failed, falling back to HTTP");
711
+ return false;
712
+ }
713
+ }
714
+ async sendViaHttp(logs, batchId) {
715
+ if (this.httpBackoffMs > 0) {
716
+ await new Promise((resolve) => setTimeout(resolve, this.httpBackoffMs));
717
+ }
718
+ const controller = new AbortController();
719
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
720
+ try {
721
+ const headers = {
722
+ "Content-Type": "application/json",
723
+ "X-Batch-Id": batchId,
724
+ "X-SDK-Version": SDK_VERSION
725
+ };
726
+ if (this.config.apiKey) {
727
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
728
+ }
729
+ const response = await fetch(this.httpIngestUrl, {
730
+ method: "POST",
731
+ headers,
732
+ body: safeStringify(logs),
733
+ signal: controller.signal
734
+ });
735
+ if (!response.ok) {
736
+ const error = await response.json().catch(() => ({ error: "Unknown error" }));
737
+ throw new Error(error.error || `HTTP ${response.status}`);
738
+ }
739
+ this.httpBackoffMs = 0;
740
+ this.consecutiveHttpFailures = 0;
741
+ this.debugLog(`Flushed ${logs.length} logs via HTTP (batch ${batchId})`);
742
+ } catch (err) {
743
+ this.buffer.unshift(...logs);
744
+ this.consecutiveHttpFailures++;
745
+ this.httpBackoffMs = Math.min(
746
+ Math.pow(2, this.consecutiveHttpFailures - 1) * 1e3,
747
+ this.maxBackoffMs
748
+ );
749
+ this.debugLog(`HTTP flush failed (retry in ${this.httpBackoffMs / 1e3}s):`, err);
750
+ if (this.config.onError) {
751
+ this.config.onError(err, logs);
752
+ } else {
753
+ originalConsole.error(
754
+ `[Moonwatch] Failed to flush logs (retry in ${this.httpBackoffMs / 1e3}s):`,
755
+ err
756
+ );
757
+ }
758
+ } finally {
759
+ clearTimeout(timeout);
760
+ }
761
+ }
762
+ /** Fire-and-forget flush using fetch with keepalive (works during page unload) */
763
+ flushSync() {
764
+ if (this.buffer.length === 0) return;
765
+ const logs = this.buffer.splice(0, this.buffer.length);
766
+ try {
767
+ const headers = {
768
+ "Content-Type": "application/json",
769
+ "X-Batch-Id": generateBatchId(),
770
+ "X-SDK-Version": SDK_VERSION
771
+ };
772
+ if (this.config.apiKey) {
773
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
774
+ }
775
+ fetch(this.httpIngestUrl, {
776
+ method: "POST",
777
+ headers,
778
+ body: safeStringify(logs),
779
+ keepalive: true
780
+ });
781
+ } catch {
782
+ }
783
+ }
784
+ registerLifecycleHooks() {
785
+ if (typeof window !== "undefined") {
786
+ this._onVisibilityChange = () => {
787
+ if (document.visibilityState === "hidden") {
788
+ this.flushSync();
789
+ }
790
+ };
791
+ document.addEventListener("visibilitychange", this._onVisibilityChange);
792
+ this._onBeforeUnload = () => {
793
+ this.flushSync();
794
+ };
795
+ window.addEventListener("beforeunload", this._onBeforeUnload);
796
+ }
797
+ }
798
+ /** Check server connectivity and API key validity */
799
+ async ping() {
800
+ const start = Date.now();
801
+ const controller = new AbortController();
802
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
803
+ try {
804
+ const headers = {};
805
+ if (this.config.apiKey) {
806
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
807
+ }
808
+ const response = await fetch(`${this.baseUrl}/health`, {
809
+ headers,
810
+ signal: controller.signal
811
+ });
812
+ const latencyMs = Date.now() - start;
813
+ if (!response.ok) {
814
+ const body = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
815
+ return { ok: false, latencyMs, error: body.error || `HTTP ${response.status}` };
816
+ }
817
+ return { ok: true, latencyMs };
818
+ } catch (err) {
819
+ return { ok: false, latencyMs: Date.now() - start, error: err.message };
820
+ } finally {
821
+ clearTimeout(timeout);
822
+ }
823
+ }
824
+ /** Get current connection status */
825
+ getConnectionStatus() {
826
+ if (this.wsState === "connected") {
827
+ return { transport: "websocket", state: "connected" };
828
+ }
829
+ return { transport: "http", state: "connected" };
830
+ }
831
+ };
832
+ _Logger.CONSOLE_METHOD = {
833
+ DEBUG: "debug",
834
+ INFO: "info",
835
+ WARN: "warn",
836
+ ERROR: "error",
837
+ FATAL: "error"
838
+ };
839
+ var Logger = _Logger;
840
+ var ScopedLogger = class _ScopedLogger {
841
+ constructor(parent, group, traceId, watcherId) {
842
+ this.parent = parent;
843
+ this.group = group;
844
+ this.traceId = traceId;
845
+ this.watcherId = watcherId;
846
+ }
847
+ withGroup(group) {
848
+ return new _ScopedLogger(this.parent, group, this.traceId, this.watcherId);
849
+ }
850
+ withTraceId(traceId) {
851
+ return new _ScopedLogger(this.parent, this.group, traceId, this.watcherId);
852
+ }
853
+ withWatcher(watcherId) {
854
+ return new _ScopedLogger(this.parent, this.group, this.traceId, watcherId);
855
+ }
856
+ opts(message, metadata) {
857
+ return {
858
+ message,
859
+ ...this.group && { group: this.group },
860
+ ...this.traceId && { traceId: this.traceId },
861
+ ...this.watcherId && { watcherId: this.watcherId },
862
+ ...metadata && { metadata }
863
+ };
864
+ }
865
+ debug(message, metadata) {
866
+ this.parent.debug(this.opts(message, metadata));
867
+ }
868
+ info(message, metadata) {
869
+ this.parent.info(this.opts(message, metadata));
870
+ }
871
+ warn(message, metadata) {
872
+ this.parent.warn(this.opts(message, metadata));
873
+ }
874
+ error(message, metadata) {
875
+ this.parent.error(this.opts(message, metadata));
876
+ }
877
+ fatal(message, metadata) {
878
+ this.parent.fatal(this.opts(message, metadata));
879
+ }
880
+ };
881
+ function createLogger(config) {
882
+ return new Logger(config);
883
+ }
884
+ var index_default = createLogger;
885
+ // Annotate the CommonJS export names for ESM import in node:
886
+ 0 && (module.exports = {
887
+ Logger,
888
+ createLogger
889
+ });