@djangocfg/monitor 2.1.216

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.
Files changed (62) hide show
  1. package/README.md +341 -0
  2. package/dist/client.cjs +1273 -0
  3. package/dist/client.cjs.map +1 -0
  4. package/dist/client.d.cts +123 -0
  5. package/dist/client.d.ts +123 -0
  6. package/dist/client.mjs +1243 -0
  7. package/dist/client.mjs.map +1 -0
  8. package/dist/index.cjs +18 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.cts +101 -0
  11. package/dist/index.d.ts +101 -0
  12. package/dist/index.mjs +1 -0
  13. package/dist/index.mjs.map +1 -0
  14. package/dist/server.cjs +947 -0
  15. package/dist/server.cjs.map +1 -0
  16. package/dist/server.d.cts +117 -0
  17. package/dist/server.d.ts +117 -0
  18. package/dist/server.mjs +917 -0
  19. package/dist/server.mjs.map +1 -0
  20. package/package.json +82 -0
  21. package/src/.claude/.sidecar/activity.jsonl +1 -0
  22. package/src/.claude/.sidecar/map_cache.json +38 -0
  23. package/src/.claude/.sidecar/usage.json +5 -0
  24. package/src/.claude/project-map.md +29 -0
  25. package/src/_api/BaseClient.ts +18 -0
  26. package/src/_api/generated/cfg_monitor/CLAUDE.md +60 -0
  27. package/src/_api/generated/cfg_monitor/_utils/fetchers/index.ts +30 -0
  28. package/src/_api/generated/cfg_monitor/_utils/fetchers/monitor.ts +51 -0
  29. package/src/_api/generated/cfg_monitor/_utils/hooks/index.ts +30 -0
  30. package/src/_api/generated/cfg_monitor/_utils/hooks/monitor.ts +43 -0
  31. package/src/_api/generated/cfg_monitor/_utils/schemas/FrontendEventIngestRequest.schema.ts +34 -0
  32. package/src/_api/generated/cfg_monitor/_utils/schemas/IngestBatchRequest.schema.ts +20 -0
  33. package/src/_api/generated/cfg_monitor/_utils/schemas/index.ts +22 -0
  34. package/src/_api/generated/cfg_monitor/api-instance.ts +181 -0
  35. package/src/_api/generated/cfg_monitor/client.ts +322 -0
  36. package/src/_api/generated/cfg_monitor/enums.ts +36 -0
  37. package/src/_api/generated/cfg_monitor/errors.ts +118 -0
  38. package/src/_api/generated/cfg_monitor/http.ts +137 -0
  39. package/src/_api/generated/cfg_monitor/index.ts +317 -0
  40. package/src/_api/generated/cfg_monitor/logger.ts +261 -0
  41. package/src/_api/generated/cfg_monitor/monitor/client.ts +25 -0
  42. package/src/_api/generated/cfg_monitor/monitor/index.ts +4 -0
  43. package/src/_api/generated/cfg_monitor/monitor/models.ts +48 -0
  44. package/src/_api/generated/cfg_monitor/retry.ts +177 -0
  45. package/src/_api/generated/cfg_monitor/schema.json +184 -0
  46. package/src/_api/generated/cfg_monitor/storage.ts +163 -0
  47. package/src/_api/generated/cfg_monitor/validation-events.ts +135 -0
  48. package/src/_api/index.ts +6 -0
  49. package/src/client/capture/console.ts +72 -0
  50. package/src/client/capture/fingerprint.ts +27 -0
  51. package/src/client/capture/js-errors.ts +70 -0
  52. package/src/client/capture/network.ts +47 -0
  53. package/src/client/capture/session.ts +33 -0
  54. package/src/client/capture/validation.ts +38 -0
  55. package/src/client/index.ts +72 -0
  56. package/src/client/store/index.ts +41 -0
  57. package/src/client/transport/ingest.ts +31 -0
  58. package/src/index.ts +12 -0
  59. package/src/server/index.ts +85 -0
  60. package/src/types/config.ts +33 -0
  61. package/src/types/events.ts +5 -0
  62. package/src/types/index.ts +6 -0
@@ -0,0 +1,1273 @@
1
+ "use client";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/client/index.ts
32
+ var client_exports = {};
33
+ __export(client_exports, {
34
+ FrontendMonitor: () => FrontendMonitor,
35
+ getSessionId: () => getSessionId,
36
+ monitoredFetch: () => monitoredFetch
37
+ });
38
+ module.exports = __toCommonJS(client_exports);
39
+
40
+ // src/client/capture/fingerprint.ts
41
+ function simpleHash(str) {
42
+ let hash = 0;
43
+ for (let i = 0; i < str.length; i++) {
44
+ hash = (hash << 5) - hash + str.charCodeAt(i);
45
+ hash = hash & hash;
46
+ }
47
+ return Math.abs(hash).toString(16).padStart(8, "0");
48
+ }
49
+ __name(simpleHash, "simpleHash");
50
+ async function computeFingerprint(message, stack, url) {
51
+ const raw = `${message}|${stack}|${url}`;
52
+ if (typeof crypto !== "undefined" && crypto.subtle) {
53
+ try {
54
+ const data = new TextEncoder().encode(raw);
55
+ const buf = await crypto.subtle.digest("SHA-256", data);
56
+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 64);
57
+ } catch {
58
+ }
59
+ }
60
+ return simpleHash(raw);
61
+ }
62
+ __name(computeFingerprint, "computeFingerprint");
63
+
64
+ // src/client/capture/session.ts
65
+ var SESSION_KEY = "fm_session_id";
66
+ var COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
67
+ function generateUUID() {
68
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
69
+ return crypto.randomUUID();
70
+ }
71
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
72
+ const r = Math.random() * 16 | 0;
73
+ return (c === "x" ? r : r & 3 | 8).toString(16);
74
+ });
75
+ }
76
+ __name(generateUUID, "generateUUID");
77
+ function setCookie(name, value) {
78
+ if (typeof document === "undefined") return;
79
+ document.cookie = `${name}=${value}; path=/; SameSite=Lax; max-age=${COOKIE_MAX_AGE}`;
80
+ }
81
+ __name(setCookie, "setCookie");
82
+ function getSessionId() {
83
+ if (typeof localStorage === "undefined") return "";
84
+ let id = localStorage.getItem(SESSION_KEY);
85
+ if (!id) {
86
+ id = generateUUID();
87
+ localStorage.setItem(SESSION_KEY, id);
88
+ setCookie(SESSION_KEY, id);
89
+ }
90
+ return id;
91
+ }
92
+ __name(getSessionId, "getSessionId");
93
+ function ensureSessionCookie() {
94
+ const id = getSessionId();
95
+ if (id) setCookie(SESSION_KEY, id);
96
+ }
97
+ __name(ensureSessionCookie, "ensureSessionCookie");
98
+
99
+ // src/client/store/index.ts
100
+ var import_vanilla = require("zustand/vanilla");
101
+
102
+ // src/_api/generated/cfg_monitor/monitor/client.ts
103
+ var _Monitor = class _Monitor {
104
+ constructor(client) {
105
+ this.client = client;
106
+ }
107
+ /**
108
+ * Ingest browser events
109
+ *
110
+ * Accepts a batch of up to 50 frontend events. No authentication required.
111
+ */
112
+ async ingestCreate(data) {
113
+ const response = await this.client.request("POST", "/cfg/monitor/ingest/", { body: data });
114
+ return response;
115
+ }
116
+ };
117
+ __name(_Monitor, "Monitor");
118
+ var Monitor = _Monitor;
119
+
120
+ // src/_api/generated/cfg_monitor/http.ts
121
+ var _FetchAdapter = class _FetchAdapter {
122
+ async request(request) {
123
+ const { method, url, headers, body, params, formData, binaryBody } = request;
124
+ let finalUrl = url;
125
+ if (params) {
126
+ const searchParams = new URLSearchParams();
127
+ Object.entries(params).forEach(([key, value]) => {
128
+ if (value !== null && value !== void 0) {
129
+ searchParams.append(key, String(value));
130
+ }
131
+ });
132
+ const queryString = searchParams.toString();
133
+ if (queryString) {
134
+ finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
135
+ }
136
+ }
137
+ const finalHeaders = { ...headers };
138
+ let requestBody;
139
+ if (formData) {
140
+ requestBody = formData;
141
+ } else if (binaryBody) {
142
+ finalHeaders["Content-Type"] = "application/octet-stream";
143
+ requestBody = binaryBody;
144
+ } else if (body) {
145
+ finalHeaders["Content-Type"] = "application/json";
146
+ requestBody = JSON.stringify(body);
147
+ }
148
+ const response = await fetch(finalUrl, {
149
+ method,
150
+ headers: finalHeaders,
151
+ body: requestBody,
152
+ credentials: "include"
153
+ // Include Django session cookies
154
+ });
155
+ let data = null;
156
+ const contentType = response.headers.get("content-type");
157
+ if (response.status !== 204 && contentType?.includes("application/json")) {
158
+ data = await response.json();
159
+ } else if (response.status !== 204) {
160
+ data = await response.text();
161
+ }
162
+ const responseHeaders = {};
163
+ response.headers.forEach((value, key) => {
164
+ responseHeaders[key] = value;
165
+ });
166
+ return {
167
+ data,
168
+ status: response.status,
169
+ statusText: response.statusText,
170
+ headers: responseHeaders
171
+ };
172
+ }
173
+ };
174
+ __name(_FetchAdapter, "FetchAdapter");
175
+ var FetchAdapter = _FetchAdapter;
176
+ var _KeepAliveFetchAdapter = class _KeepAliveFetchAdapter extends FetchAdapter {
177
+ async request(request) {
178
+ const origFetch = globalThis.fetch;
179
+ globalThis.fetch = (input, init) => origFetch(input, { ...init, keepalive: true });
180
+ try {
181
+ return await super.request(request);
182
+ } finally {
183
+ globalThis.fetch = origFetch;
184
+ }
185
+ }
186
+ };
187
+ __name(_KeepAliveFetchAdapter, "KeepAliveFetchAdapter");
188
+ var KeepAliveFetchAdapter = _KeepAliveFetchAdapter;
189
+
190
+ // src/_api/generated/cfg_monitor/errors.ts
191
+ var _APIError = class _APIError extends Error {
192
+ constructor(statusCode, statusText, response, url, message) {
193
+ super(message || `HTTP ${statusCode}: ${statusText}`);
194
+ this.statusCode = statusCode;
195
+ this.statusText = statusText;
196
+ this.response = response;
197
+ this.url = url;
198
+ this.name = "APIError";
199
+ }
200
+ /**
201
+ * Get error details from response.
202
+ * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
203
+ */
204
+ get details() {
205
+ if (typeof this.response === "object" && this.response !== null) {
206
+ return this.response;
207
+ }
208
+ return null;
209
+ }
210
+ /**
211
+ * Get field-specific validation errors from DRF.
212
+ * Returns: { "field_name": ["error1", "error2"], ... }
213
+ */
214
+ get fieldErrors() {
215
+ const details = this.details;
216
+ if (!details) return null;
217
+ const fieldErrors = {};
218
+ for (const [key, value] of Object.entries(details)) {
219
+ if (Array.isArray(value)) {
220
+ fieldErrors[key] = value;
221
+ }
222
+ }
223
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
224
+ }
225
+ /**
226
+ * Get single error message from DRF.
227
+ * Checks for "detail", "message", or first field error.
228
+ */
229
+ get errorMessage() {
230
+ const details = this.details;
231
+ if (!details) return this.message;
232
+ if (details.detail) {
233
+ return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
234
+ }
235
+ if (details.message) {
236
+ return String(details.message);
237
+ }
238
+ const fieldErrors = this.fieldErrors;
239
+ if (fieldErrors) {
240
+ const firstField = Object.keys(fieldErrors)[0];
241
+ if (firstField) {
242
+ return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
243
+ }
244
+ }
245
+ return this.message;
246
+ }
247
+ // Helper methods for common HTTP status codes
248
+ get isValidationError() {
249
+ return this.statusCode === 400;
250
+ }
251
+ get isAuthError() {
252
+ return this.statusCode === 401;
253
+ }
254
+ get isPermissionError() {
255
+ return this.statusCode === 403;
256
+ }
257
+ get isNotFoundError() {
258
+ return this.statusCode === 404;
259
+ }
260
+ get isServerError() {
261
+ return this.statusCode >= 500 && this.statusCode < 600;
262
+ }
263
+ };
264
+ __name(_APIError, "APIError");
265
+ var APIError = _APIError;
266
+ var _NetworkError = class _NetworkError extends Error {
267
+ constructor(message, url, originalError) {
268
+ super(message);
269
+ this.url = url;
270
+ this.originalError = originalError;
271
+ this.name = "NetworkError";
272
+ }
273
+ };
274
+ __name(_NetworkError, "NetworkError");
275
+ var NetworkError = _NetworkError;
276
+
277
+ // src/_api/generated/cfg_monitor/logger.ts
278
+ var import_consola = require("consola");
279
+ var DEFAULT_CONFIG = {
280
+ enabled: true,
281
+ logRequests: true,
282
+ logResponses: true,
283
+ logErrors: true,
284
+ logBodies: true,
285
+ logHeaders: false
286
+ };
287
+ var SENSITIVE_HEADERS = [
288
+ "authorization",
289
+ "cookie",
290
+ "set-cookie",
291
+ "x-api-key",
292
+ "x-csrf-token"
293
+ ];
294
+ var _APILogger = class _APILogger {
295
+ constructor(config = {}) {
296
+ this.config = { ...DEFAULT_CONFIG, ...config };
297
+ this.consola = config.consola || (0, import_consola.createConsola)({
298
+ level: this.config.enabled ? 4 : 0
299
+ });
300
+ }
301
+ /**
302
+ * Enable logging
303
+ */
304
+ enable() {
305
+ this.config.enabled = true;
306
+ }
307
+ /**
308
+ * Disable logging
309
+ */
310
+ disable() {
311
+ this.config.enabled = false;
312
+ }
313
+ /**
314
+ * Update configuration
315
+ */
316
+ setConfig(config) {
317
+ this.config = { ...this.config, ...config };
318
+ }
319
+ /**
320
+ * Filter sensitive headers
321
+ */
322
+ filterHeaders(headers) {
323
+ if (!headers) return {};
324
+ const filtered = {};
325
+ Object.keys(headers).forEach((key) => {
326
+ const lowerKey = key.toLowerCase();
327
+ if (SENSITIVE_HEADERS.includes(lowerKey)) {
328
+ filtered[key] = "***";
329
+ } else {
330
+ filtered[key] = headers[key] || "";
331
+ }
332
+ });
333
+ return filtered;
334
+ }
335
+ /**
336
+ * Log request
337
+ */
338
+ logRequest(request) {
339
+ if (!this.config.enabled || !this.config.logRequests) return;
340
+ const { method, url, headers, body } = request;
341
+ this.consola.start(`${method} ${url}`);
342
+ if (this.config.logHeaders && headers) {
343
+ this.consola.debug("Headers:", this.filterHeaders(headers));
344
+ }
345
+ if (this.config.logBodies && body) {
346
+ this.consola.debug("Body:", body);
347
+ }
348
+ }
349
+ /**
350
+ * Log response
351
+ */
352
+ logResponse(request, response) {
353
+ if (!this.config.enabled || !this.config.logResponses) return;
354
+ const { method, url } = request;
355
+ const { status, statusText, data, duration } = response;
356
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
357
+ this.consola.success(
358
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
359
+ );
360
+ if (this.config.logBodies && data) {
361
+ this.consola.debug("Response:", data);
362
+ }
363
+ }
364
+ /**
365
+ * Log error
366
+ */
367
+ logError(request, error) {
368
+ if (!this.config.enabled || !this.config.logErrors) return;
369
+ const { method, url } = request;
370
+ const { message, statusCode, fieldErrors, duration } = error;
371
+ this.consola.error(
372
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
373
+ );
374
+ this.consola.error("Message:", message);
375
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
376
+ this.consola.error("Field Errors:");
377
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
378
+ errors.forEach((err) => {
379
+ this.consola.error(` \u2022 ${field}: ${err}`);
380
+ });
381
+ });
382
+ }
383
+ }
384
+ /**
385
+ * Log general info
386
+ */
387
+ info(message, ...args) {
388
+ if (!this.config.enabled) return;
389
+ this.consola.info(message, ...args);
390
+ }
391
+ /**
392
+ * Log warning
393
+ */
394
+ warn(message, ...args) {
395
+ if (!this.config.enabled) return;
396
+ this.consola.warn(message, ...args);
397
+ }
398
+ /**
399
+ * Log error
400
+ */
401
+ error(message, ...args) {
402
+ if (!this.config.enabled) return;
403
+ this.consola.error(message, ...args);
404
+ }
405
+ /**
406
+ * Log debug
407
+ */
408
+ debug(message, ...args) {
409
+ if (!this.config.enabled) return;
410
+ this.consola.debug(message, ...args);
411
+ }
412
+ /**
413
+ * Log success
414
+ */
415
+ success(message, ...args) {
416
+ if (!this.config.enabled) return;
417
+ this.consola.success(message, ...args);
418
+ }
419
+ /**
420
+ * Create a sub-logger with prefix
421
+ */
422
+ withTag(tag) {
423
+ return this.consola.withTag(tag);
424
+ }
425
+ };
426
+ __name(_APILogger, "APILogger");
427
+ var APILogger = _APILogger;
428
+ var defaultLogger = new APILogger();
429
+
430
+ // src/_api/generated/cfg_monitor/retry.ts
431
+ var import_p_retry = __toESM(require("p-retry"), 1);
432
+ var DEFAULT_RETRY_CONFIG = {
433
+ retries: 3,
434
+ factor: 2,
435
+ minTimeout: 1e3,
436
+ maxTimeout: 6e4,
437
+ randomize: true,
438
+ onFailedAttempt: /* @__PURE__ */ __name(() => {
439
+ }, "onFailedAttempt")
440
+ };
441
+ function shouldRetry(error) {
442
+ if (error instanceof NetworkError) {
443
+ return true;
444
+ }
445
+ if (error instanceof APIError) {
446
+ const status = error.statusCode;
447
+ if (status >= 500 && status < 600) {
448
+ return true;
449
+ }
450
+ if (status === 429) {
451
+ return true;
452
+ }
453
+ return false;
454
+ }
455
+ return true;
456
+ }
457
+ __name(shouldRetry, "shouldRetry");
458
+ async function withRetry(fn, config) {
459
+ const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
460
+ return (0, import_p_retry.default)(
461
+ async () => {
462
+ try {
463
+ return await fn();
464
+ } catch (error) {
465
+ if (!shouldRetry(error)) {
466
+ throw new import_p_retry.AbortError(error);
467
+ }
468
+ throw error;
469
+ }
470
+ },
471
+ {
472
+ retries: finalConfig.retries,
473
+ factor: finalConfig.factor,
474
+ minTimeout: finalConfig.minTimeout,
475
+ maxTimeout: finalConfig.maxTimeout,
476
+ randomize: finalConfig.randomize,
477
+ onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
478
+ const pRetryError = error;
479
+ finalConfig.onFailedAttempt({
480
+ error: pRetryError,
481
+ attemptNumber: pRetryError.attemptNumber,
482
+ retriesLeft: pRetryError.retriesLeft
483
+ });
484
+ } : void 0
485
+ }
486
+ );
487
+ }
488
+ __name(withRetry, "withRetry");
489
+
490
+ // src/_api/generated/cfg_monitor/client.ts
491
+ var _APIClient = class _APIClient {
492
+ constructor(baseUrl, options) {
493
+ this.logger = null;
494
+ this.retryConfig = null;
495
+ this.tokenGetter = null;
496
+ this.baseUrl = baseUrl.replace(/\/$/, "");
497
+ this.httpClient = options?.httpClient || new FetchAdapter();
498
+ this.tokenGetter = options?.tokenGetter || null;
499
+ if (options?.loggerConfig !== void 0) {
500
+ this.logger = new APILogger(options.loggerConfig);
501
+ }
502
+ if (options?.retryConfig !== void 0) {
503
+ this.retryConfig = options.retryConfig;
504
+ }
505
+ this.monitor = new Monitor(this);
506
+ }
507
+ /**
508
+ * Get CSRF token from cookies (for SessionAuthentication).
509
+ *
510
+ * Returns null if cookie doesn't exist (JWT-only auth).
511
+ */
512
+ getCsrfToken() {
513
+ const name = "csrftoken";
514
+ const value = `; ${document.cookie}`;
515
+ const parts = value.split(`; ${name}=`);
516
+ if (parts.length === 2) {
517
+ return parts.pop()?.split(";").shift() || null;
518
+ }
519
+ return null;
520
+ }
521
+ /**
522
+ * Get the base URL for building streaming/download URLs.
523
+ */
524
+ getBaseUrl() {
525
+ return this.baseUrl;
526
+ }
527
+ /**
528
+ * Get JWT token for URL authentication (used in streaming endpoints).
529
+ * Returns null if no token getter is configured or no token is available.
530
+ */
531
+ getToken() {
532
+ return this.tokenGetter ? this.tokenGetter() : null;
533
+ }
534
+ /**
535
+ * Make HTTP request with Django CSRF and session handling.
536
+ * Automatically retries on network errors and 5xx server errors.
537
+ */
538
+ async request(method, path, options) {
539
+ if (this.retryConfig) {
540
+ return withRetry(() => this._makeRequest(method, path, options), {
541
+ ...this.retryConfig,
542
+ onFailedAttempt: /* @__PURE__ */ __name((info) => {
543
+ if (this.logger) {
544
+ this.logger.warn(
545
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
546
+ );
547
+ }
548
+ this.retryConfig?.onFailedAttempt?.(info);
549
+ }, "onFailedAttempt")
550
+ });
551
+ }
552
+ return this._makeRequest(method, path, options);
553
+ }
554
+ /**
555
+ * Internal request method (without retry wrapper).
556
+ * Used by request() method with optional retry logic.
557
+ */
558
+ async _makeRequest(method, path, options) {
559
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
560
+ const startTime = Date.now();
561
+ const headers = {
562
+ ...options?.headers || {}
563
+ };
564
+ if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
565
+ headers["Content-Type"] = "application/json";
566
+ }
567
+ if (this.logger) {
568
+ this.logger.logRequest({
569
+ method,
570
+ url,
571
+ headers,
572
+ body: options?.formData || options?.body,
573
+ timestamp: startTime
574
+ });
575
+ }
576
+ try {
577
+ const response = await this.httpClient.request({
578
+ method,
579
+ url,
580
+ headers,
581
+ params: options?.params,
582
+ body: options?.body,
583
+ formData: options?.formData,
584
+ binaryBody: options?.binaryBody
585
+ });
586
+ const duration = Date.now() - startTime;
587
+ if (response.status >= 400) {
588
+ const error = new APIError(
589
+ response.status,
590
+ response.statusText,
591
+ response.data,
592
+ url
593
+ );
594
+ if (this.logger) {
595
+ this.logger.logError(
596
+ {
597
+ method,
598
+ url,
599
+ headers,
600
+ body: options?.formData || options?.body,
601
+ timestamp: startTime
602
+ },
603
+ {
604
+ message: error.message,
605
+ statusCode: response.status,
606
+ duration,
607
+ timestamp: Date.now()
608
+ }
609
+ );
610
+ }
611
+ throw error;
612
+ }
613
+ if (this.logger) {
614
+ this.logger.logResponse(
615
+ {
616
+ method,
617
+ url,
618
+ headers,
619
+ body: options?.formData || options?.body,
620
+ timestamp: startTime
621
+ },
622
+ {
623
+ status: response.status,
624
+ statusText: response.statusText,
625
+ data: response.data,
626
+ duration,
627
+ timestamp: Date.now()
628
+ }
629
+ );
630
+ }
631
+ return response.data;
632
+ } catch (error) {
633
+ const duration = Date.now() - startTime;
634
+ if (error instanceof APIError) {
635
+ throw error;
636
+ }
637
+ const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
638
+ if (this.logger) {
639
+ if (isCORSError) {
640
+ this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
641
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
642
+ this.logger.error(` \u2192 Configure security_domains parameter on the server`);
643
+ } else {
644
+ this.logger.error(`\u26A0\uFE0F Network Error: ${method} ${url}`);
645
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
646
+ }
647
+ }
648
+ if (typeof window !== "undefined") {
649
+ try {
650
+ if (isCORSError) {
651
+ window.dispatchEvent(new CustomEvent("cors-error", {
652
+ detail: {
653
+ url,
654
+ method,
655
+ error: error instanceof Error ? error.message : String(error),
656
+ timestamp: /* @__PURE__ */ new Date()
657
+ },
658
+ bubbles: true,
659
+ cancelable: false
660
+ }));
661
+ } else {
662
+ window.dispatchEvent(new CustomEvent("network-error", {
663
+ detail: {
664
+ url,
665
+ method,
666
+ error: error instanceof Error ? error.message : String(error),
667
+ timestamp: /* @__PURE__ */ new Date()
668
+ },
669
+ bubbles: true,
670
+ cancelable: false
671
+ }));
672
+ }
673
+ } catch (eventError) {
674
+ }
675
+ }
676
+ const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
677
+ if (this.logger) {
678
+ this.logger.logError(
679
+ {
680
+ method,
681
+ url,
682
+ headers,
683
+ body: options?.formData || options?.body,
684
+ timestamp: startTime
685
+ },
686
+ {
687
+ message: networkError.message,
688
+ duration,
689
+ timestamp: Date.now()
690
+ }
691
+ );
692
+ }
693
+ throw networkError;
694
+ }
695
+ }
696
+ };
697
+ __name(_APIClient, "APIClient");
698
+ var APIClient = _APIClient;
699
+
700
+ // src/_api/generated/cfg_monitor/storage.ts
701
+ var _LocalStorageAdapter = class _LocalStorageAdapter {
702
+ constructor(logger) {
703
+ this.logger = logger;
704
+ }
705
+ getItem(key) {
706
+ try {
707
+ if (typeof window !== "undefined" && window.localStorage) {
708
+ const value = localStorage.getItem(key);
709
+ this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
710
+ return value;
711
+ }
712
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
713
+ } catch (error) {
714
+ this.logger?.error("LocalStorage.getItem failed:", error);
715
+ }
716
+ return null;
717
+ }
718
+ setItem(key, value) {
719
+ try {
720
+ if (typeof window !== "undefined" && window.localStorage) {
721
+ localStorage.setItem(key, value);
722
+ this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
723
+ } else {
724
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
725
+ }
726
+ } catch (error) {
727
+ this.logger?.error("LocalStorage.setItem failed:", error);
728
+ }
729
+ }
730
+ removeItem(key) {
731
+ try {
732
+ if (typeof window !== "undefined" && window.localStorage) {
733
+ localStorage.removeItem(key);
734
+ this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
735
+ } else {
736
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
737
+ }
738
+ } catch (error) {
739
+ this.logger?.error("LocalStorage.removeItem failed:", error);
740
+ }
741
+ }
742
+ };
743
+ __name(_LocalStorageAdapter, "LocalStorageAdapter");
744
+ var LocalStorageAdapter = _LocalStorageAdapter;
745
+ var _MemoryStorageAdapter = class _MemoryStorageAdapter {
746
+ constructor(logger) {
747
+ this.storage = /* @__PURE__ */ new Map();
748
+ this.logger = logger;
749
+ }
750
+ getItem(key) {
751
+ const value = this.storage.get(key) || null;
752
+ this.logger?.debug(`MemoryStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
753
+ return value;
754
+ }
755
+ setItem(key, value) {
756
+ this.storage.set(key, value);
757
+ this.logger?.debug(`MemoryStorage.setItem("${key}"): success`);
758
+ }
759
+ removeItem(key) {
760
+ this.storage.delete(key);
761
+ this.logger?.debug(`MemoryStorage.removeItem("${key}"): success`);
762
+ }
763
+ };
764
+ __name(_MemoryStorageAdapter, "MemoryStorageAdapter");
765
+ var MemoryStorageAdapter = _MemoryStorageAdapter;
766
+
767
+ // src/_api/generated/cfg_monitor/enums.ts
768
+ var FrontendEventIngestRequestEventType = /* @__PURE__ */ ((FrontendEventIngestRequestEventType2) => {
769
+ FrontendEventIngestRequestEventType2["ERROR"] = "ERROR";
770
+ FrontendEventIngestRequestEventType2["WARNING"] = "WARNING";
771
+ FrontendEventIngestRequestEventType2["INFO"] = "INFO";
772
+ FrontendEventIngestRequestEventType2["PAGE_VIEW"] = "PAGE_VIEW";
773
+ FrontendEventIngestRequestEventType2["PERFORMANCE"] = "PERFORMANCE";
774
+ FrontendEventIngestRequestEventType2["NETWORK_ERROR"] = "NETWORK_ERROR";
775
+ FrontendEventIngestRequestEventType2["JS_ERROR"] = "JS_ERROR";
776
+ FrontendEventIngestRequestEventType2["CONSOLE"] = "CONSOLE";
777
+ return FrontendEventIngestRequestEventType2;
778
+ })(FrontendEventIngestRequestEventType || {});
779
+ var FrontendEventIngestRequestLevel = /* @__PURE__ */ ((FrontendEventIngestRequestLevel2) => {
780
+ FrontendEventIngestRequestLevel2["ERROR"] = "error";
781
+ FrontendEventIngestRequestLevel2["WARN"] = "warn";
782
+ FrontendEventIngestRequestLevel2["INFO"] = "info";
783
+ FrontendEventIngestRequestLevel2["DEBUG"] = "debug";
784
+ return FrontendEventIngestRequestLevel2;
785
+ })(FrontendEventIngestRequestLevel || {});
786
+
787
+ // src/_api/generated/cfg_monitor/_utils/schemas/FrontendEventIngestRequest.schema.ts
788
+ var import_zod = require("zod");
789
+ var FrontendEventIngestRequestSchema = import_zod.z.object({
790
+ event_type: import_zod.z.nativeEnum(FrontendEventIngestRequestEventType),
791
+ message: import_zod.z.string().min(1).max(5e3),
792
+ level: import_zod.z.nativeEnum(FrontendEventIngestRequestLevel).optional(),
793
+ stack_trace: import_zod.z.string().max(2e4).optional(),
794
+ url: import_zod.z.string().max(2e3).optional(),
795
+ fingerprint: import_zod.z.string().max(64).optional(),
796
+ http_status: import_zod.z.number().int().nullable().optional(),
797
+ http_method: import_zod.z.string().max(10).optional(),
798
+ http_url: import_zod.z.string().max(2e3).optional(),
799
+ user_agent: import_zod.z.string().max(500).optional(),
800
+ session_id: import_zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
801
+ browser_fingerprint: import_zod.z.string().max(64).optional(),
802
+ extra: import_zod.z.record(import_zod.z.string(), import_zod.z.any()).optional(),
803
+ project_name: import_zod.z.string().max(100).optional(),
804
+ environment: import_zod.z.string().max(20).optional()
805
+ });
806
+
807
+ // src/_api/generated/cfg_monitor/_utils/schemas/IngestBatchRequest.schema.ts
808
+ var import_zod2 = require("zod");
809
+ var IngestBatchRequestSchema = import_zod2.z.object({
810
+ events: import_zod2.z.array(FrontendEventIngestRequestSchema)
811
+ });
812
+
813
+ // src/_api/generated/cfg_monitor/index.ts
814
+ var TOKEN_KEY = "auth_token";
815
+ var REFRESH_TOKEN_KEY = "refresh_token";
816
+ function detectLocale() {
817
+ try {
818
+ if (typeof document !== "undefined") {
819
+ const match = document.cookie.match(/(?:^|;\s*)NEXT_LOCALE=([^;]*)/);
820
+ if (match) return match[1];
821
+ }
822
+ if (typeof navigator !== "undefined" && navigator.language) {
823
+ return navigator.language;
824
+ }
825
+ } catch {
826
+ }
827
+ return null;
828
+ }
829
+ __name(detectLocale, "detectLocale");
830
+ var _API = class _API {
831
+ constructor(baseUrl, options) {
832
+ this._token = null;
833
+ this._refreshToken = null;
834
+ this._locale = null;
835
+ this.baseUrl = baseUrl;
836
+ this.options = options;
837
+ const logger = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
838
+ this.storage = options?.storage || new LocalStorageAdapter(logger);
839
+ this._locale = options?.locale || null;
840
+ this._loadTokensFromStorage();
841
+ this._client = new APIClient(this.baseUrl, {
842
+ httpClient: this.options?.httpClient,
843
+ retryConfig: this.options?.retryConfig,
844
+ loggerConfig: this.options?.loggerConfig,
845
+ tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
846
+ });
847
+ this._injectAuthHeader();
848
+ this.monitor = this._client.monitor;
849
+ }
850
+ _loadTokensFromStorage() {
851
+ this._token = this.storage.getItem(TOKEN_KEY);
852
+ this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
853
+ }
854
+ _reinitClients() {
855
+ this._client = new APIClient(this.baseUrl, {
856
+ httpClient: this.options?.httpClient,
857
+ retryConfig: this.options?.retryConfig,
858
+ loggerConfig: this.options?.loggerConfig,
859
+ tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
860
+ });
861
+ this._injectAuthHeader();
862
+ this.monitor = this._client.monitor;
863
+ }
864
+ _injectAuthHeader() {
865
+ const originalRequest = this._client.request.bind(this._client);
866
+ this._client.request = async (method, path, options) => {
867
+ const token = this.getToken();
868
+ const locale = this._locale || detectLocale();
869
+ const mergedOptions = {
870
+ ...options,
871
+ headers: {
872
+ ...options?.headers || {},
873
+ ...token ? { "Authorization": `Bearer ${token}` } : {},
874
+ ...locale ? { "Accept-Language": locale } : {}
875
+ }
876
+ };
877
+ return originalRequest(method, path, mergedOptions);
878
+ };
879
+ }
880
+ /**
881
+ * Get current JWT token
882
+ */
883
+ getToken() {
884
+ return this.storage.getItem(TOKEN_KEY);
885
+ }
886
+ /**
887
+ * Get current refresh token
888
+ */
889
+ getRefreshToken() {
890
+ return this.storage.getItem(REFRESH_TOKEN_KEY);
891
+ }
892
+ /**
893
+ * Set JWT token and refresh token
894
+ * @param token - JWT access token
895
+ * @param refreshToken - JWT refresh token (optional)
896
+ */
897
+ setToken(token, refreshToken) {
898
+ this._token = token;
899
+ this.storage.setItem(TOKEN_KEY, token);
900
+ if (refreshToken) {
901
+ this._refreshToken = refreshToken;
902
+ this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
903
+ }
904
+ this._reinitClients();
905
+ }
906
+ /**
907
+ * Clear all tokens
908
+ */
909
+ clearTokens() {
910
+ this._token = null;
911
+ this._refreshToken = null;
912
+ this.storage.removeItem(TOKEN_KEY);
913
+ this.storage.removeItem(REFRESH_TOKEN_KEY);
914
+ this._reinitClients();
915
+ }
916
+ /**
917
+ * Check if user is authenticated
918
+ */
919
+ isAuthenticated() {
920
+ return !!this.getToken();
921
+ }
922
+ /**
923
+ * Update base URL and reinitialize clients
924
+ * @param url - New base URL
925
+ */
926
+ setBaseUrl(url) {
927
+ this.baseUrl = url;
928
+ this._reinitClients();
929
+ }
930
+ /**
931
+ * Get current base URL
932
+ */
933
+ getBaseUrl() {
934
+ return this.baseUrl;
935
+ }
936
+ /**
937
+ * Set locale for Accept-Language header
938
+ * @param locale - Locale string (e.g. 'en', 'ko', 'ru') or null to clear
939
+ */
940
+ setLocale(locale) {
941
+ this._locale = locale;
942
+ }
943
+ /**
944
+ * Get current locale
945
+ */
946
+ getLocale() {
947
+ return this._locale;
948
+ }
949
+ /**
950
+ * Get OpenAPI schema path
951
+ * @returns Path to the OpenAPI schema JSON file
952
+ *
953
+ * Note: The OpenAPI schema is available in the schema.json file.
954
+ * You can load it dynamically using:
955
+ * ```typescript
956
+ * const schema = await fetch('./schema.json').then(r => r.json());
957
+ * // or using fs in Node.js:
958
+ * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
959
+ * ```
960
+ */
961
+ getSchemaPath() {
962
+ return "./schema.json";
963
+ }
964
+ };
965
+ __name(_API, "API");
966
+ var API = _API;
967
+
968
+ // src/_api/BaseClient.ts
969
+ var monitorApi = new API("", { storage: new MemoryStorageAdapter() });
970
+ function configureMonitorApi(baseUrl) {
971
+ monitorApi.setBaseUrl(baseUrl);
972
+ }
973
+ __name(configureMonitorApi, "configureMonitorApi");
974
+ var _BaseClient = class _BaseClient {
975
+ };
976
+ __name(_BaseClient, "BaseClient");
977
+ _BaseClient.monitorApi = monitorApi;
978
+ var BaseClient = _BaseClient;
979
+
980
+ // src/client/transport/ingest.ts
981
+ var monitorApiBeacon = new API("", {
982
+ storage: new MemoryStorageAdapter(),
983
+ httpClient: new KeepAliveFetchAdapter()
984
+ });
985
+ function syncBeaconBaseUrl() {
986
+ monitorApiBeacon.setBaseUrl(monitorApi.getBaseUrl());
987
+ }
988
+ __name(syncBeaconBaseUrl, "syncBeaconBaseUrl");
989
+ async function sendBatch(batch, useBeacon = false) {
990
+ if (batch.events.length === 0) return;
991
+ try {
992
+ if (useBeacon) {
993
+ syncBeaconBaseUrl();
994
+ await monitorApiBeacon.monitor.ingestCreate(batch);
995
+ } else {
996
+ await monitorApi.monitor.ingestCreate(batch);
997
+ }
998
+ } catch {
999
+ }
1000
+ }
1001
+ __name(sendBatch, "sendBatch");
1002
+
1003
+ // src/client/store/index.ts
1004
+ var monitorStore = (0, import_vanilla.createStore)((set, get) => ({
1005
+ config: {},
1006
+ buffer: [],
1007
+ initialized: false,
1008
+ push(event) {
1009
+ const { config, buffer } = get();
1010
+ const maxSize = config.maxBufferSize ?? 20;
1011
+ const next = [...buffer, event];
1012
+ set({ buffer: next });
1013
+ if (next.length >= maxSize || event.level === "error") {
1014
+ get().flush();
1015
+ }
1016
+ },
1017
+ flush(useBeacon = false) {
1018
+ const { buffer } = get();
1019
+ if (buffer.length === 0) return;
1020
+ const batch = buffer.slice(0, 50);
1021
+ set({ buffer: buffer.slice(50) });
1022
+ sendBatch({ events: batch }, useBeacon);
1023
+ },
1024
+ setConfig(config) {
1025
+ set({ config, initialized: true });
1026
+ }
1027
+ }));
1028
+
1029
+ // src/client/capture/js-errors.ts
1030
+ function installJsErrorCapture() {
1031
+ if (typeof window === "undefined") return () => {
1032
+ };
1033
+ const onError = /* @__PURE__ */ __name(async (message, source, lineno, colno, error) => {
1034
+ try {
1035
+ const msg = typeof message === "string" ? message : String(message);
1036
+ const stack = error?.stack ?? `at ${source}:${lineno}:${colno}`;
1037
+ const url = window.location.href;
1038
+ const fingerprint = await computeFingerprint(msg, stack, url);
1039
+ const { config } = monitorStore.getState();
1040
+ monitorStore.getState().push({
1041
+ event_type: "JS_ERROR" /* JS_ERROR */,
1042
+ level: "error" /* ERROR */,
1043
+ message: msg,
1044
+ stack_trace: stack,
1045
+ url,
1046
+ fingerprint,
1047
+ session_id: getSessionId(),
1048
+ user_agent: navigator.userAgent,
1049
+ project_name: config.project,
1050
+ environment: config.environment
1051
+ });
1052
+ } catch {
1053
+ }
1054
+ }, "onError");
1055
+ const onUnhandledRejection = /* @__PURE__ */ __name(async (e) => {
1056
+ try {
1057
+ const reason = e.reason;
1058
+ const msg = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection";
1059
+ const stack = reason instanceof Error ? reason.stack ?? "" : "";
1060
+ const url = window.location.href;
1061
+ const fingerprint = await computeFingerprint(msg, stack, url);
1062
+ const { config } = monitorStore.getState();
1063
+ monitorStore.getState().push({
1064
+ event_type: "JS_ERROR" /* JS_ERROR */,
1065
+ level: "error" /* ERROR */,
1066
+ message: msg,
1067
+ stack_trace: stack,
1068
+ url,
1069
+ fingerprint,
1070
+ session_id: getSessionId(),
1071
+ user_agent: navigator.userAgent,
1072
+ project_name: config.project,
1073
+ environment: config.environment
1074
+ });
1075
+ } catch {
1076
+ }
1077
+ }, "onUnhandledRejection");
1078
+ const errHandler = /* @__PURE__ */ __name((e) => onError(e.message, e.filename, e.lineno, e.colno, e.error), "errHandler");
1079
+ window.addEventListener("error", errHandler);
1080
+ window.addEventListener("unhandledrejection", onUnhandledRejection);
1081
+ return () => {
1082
+ window.removeEventListener("error", errHandler);
1083
+ window.removeEventListener("unhandledrejection", onUnhandledRejection);
1084
+ };
1085
+ }
1086
+ __name(installJsErrorCapture, "installJsErrorCapture");
1087
+
1088
+ // src/client/capture/console.ts
1089
+ var levelMap = {
1090
+ warn: "warn" /* WARN */,
1091
+ error: "error" /* ERROR */
1092
+ };
1093
+ var typeMap = {
1094
+ warn: "WARNING" /* WARNING */,
1095
+ error: "ERROR" /* ERROR */
1096
+ };
1097
+ function stringify(args) {
1098
+ return args.map((a) => {
1099
+ if (typeof a === "string") return a;
1100
+ if (a instanceof Error) return a.message;
1101
+ try {
1102
+ return JSON.stringify(a);
1103
+ } catch {
1104
+ return String(a);
1105
+ }
1106
+ }).join(" ");
1107
+ }
1108
+ __name(stringify, "stringify");
1109
+ async function captureConsoleEvent(level, args) {
1110
+ try {
1111
+ const message = stringify(args);
1112
+ const url = typeof window !== "undefined" ? window.location.href : "";
1113
+ const fingerprint = await computeFingerprint(message, "", url);
1114
+ const { config } = monitorStore.getState();
1115
+ monitorStore.getState().push({
1116
+ event_type: typeMap[level],
1117
+ level: levelMap[level],
1118
+ message,
1119
+ url,
1120
+ fingerprint,
1121
+ session_id: getSessionId(),
1122
+ user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
1123
+ project_name: config.project,
1124
+ environment: config.environment
1125
+ });
1126
+ } catch {
1127
+ }
1128
+ }
1129
+ __name(captureConsoleEvent, "captureConsoleEvent");
1130
+ function installConsoleCapture() {
1131
+ if (typeof window === "undefined") return () => {
1132
+ };
1133
+ try {
1134
+ const g = globalThis;
1135
+ if (g.consola && typeof g.consola.addReporter === "function") {
1136
+ const consolaInst = g.consola;
1137
+ const reporter = {
1138
+ log(logObj) {
1139
+ if (logObj.level === 1) captureConsoleEvent("error", logObj.args);
1140
+ else if (logObj.level === 2) captureConsoleEvent("warn", logObj.args);
1141
+ }
1142
+ };
1143
+ consolaInst.addReporter(reporter);
1144
+ return () => consolaInst.removeReporter(reporter);
1145
+ }
1146
+ } catch {
1147
+ }
1148
+ const origWarn = console.warn.bind(console);
1149
+ const origError = console.error.bind(console);
1150
+ console.warn = (...args) => {
1151
+ origWarn(...args);
1152
+ captureConsoleEvent("warn", args);
1153
+ };
1154
+ console.error = (...args) => {
1155
+ origError(...args);
1156
+ captureConsoleEvent("error", args);
1157
+ };
1158
+ return () => {
1159
+ console.warn = origWarn;
1160
+ console.error = origError;
1161
+ };
1162
+ }
1163
+ __name(installConsoleCapture, "installConsoleCapture");
1164
+
1165
+ // src/client/capture/validation.ts
1166
+ function installValidationCapture() {
1167
+ if (typeof window === "undefined") return () => {
1168
+ };
1169
+ const handler = /* @__PURE__ */ __name((event) => {
1170
+ if (!(event instanceof CustomEvent)) return;
1171
+ try {
1172
+ const detail = event.detail;
1173
+ const { config } = monitorStore.getState();
1174
+ monitorStore.getState().push({
1175
+ event_type: "WARNING" /* WARNING */,
1176
+ level: "warn" /* WARN */,
1177
+ message: `Zod validation error in ${detail.operation}: ${detail.error?.message ?? "unknown"}`,
1178
+ url: window.location.href,
1179
+ http_method: detail.method,
1180
+ http_url: detail.path,
1181
+ session_id: getSessionId(),
1182
+ user_agent: navigator.userAgent,
1183
+ project_name: config.project,
1184
+ environment: config.environment,
1185
+ extra: { operation: detail.operation, path: detail.path, method: detail.method }
1186
+ });
1187
+ } catch {
1188
+ }
1189
+ }, "handler");
1190
+ window.addEventListener("zod-validation-error", handler);
1191
+ return () => window.removeEventListener("zod-validation-error", handler);
1192
+ }
1193
+ __name(installValidationCapture, "installValidationCapture");
1194
+
1195
+ // src/client/capture/network.ts
1196
+ async function monitoredFetch(input, init) {
1197
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
1198
+ const method = (init?.method ?? "GET").toUpperCase();
1199
+ try {
1200
+ const response = await fetch(input, init);
1201
+ if (!response.ok) {
1202
+ const { config } = monitorStore.getState();
1203
+ monitorStore.getState().push({
1204
+ event_type: "NETWORK_ERROR" /* NETWORK_ERROR */,
1205
+ level: response.status >= 500 ? "error" /* ERROR */ : "warn" /* WARN */,
1206
+ message: `HTTP ${response.status} ${response.statusText} \u2014 ${method} ${url}`,
1207
+ url: typeof window !== "undefined" ? window.location.href : "",
1208
+ http_status: response.status,
1209
+ http_method: method,
1210
+ http_url: url,
1211
+ session_id: getSessionId(),
1212
+ user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
1213
+ project_name: config.project,
1214
+ environment: config.environment
1215
+ });
1216
+ }
1217
+ return response;
1218
+ } catch (err) {
1219
+ const { config } = monitorStore.getState();
1220
+ monitorStore.getState().push({
1221
+ event_type: "NETWORK_ERROR" /* NETWORK_ERROR */,
1222
+ level: "error" /* ERROR */,
1223
+ message: err instanceof Error ? err.message : `Network error \u2014 ${method} ${url}`,
1224
+ url: typeof window !== "undefined" ? window.location.href : "",
1225
+ http_method: method,
1226
+ http_url: url,
1227
+ session_id: getSessionId(),
1228
+ user_agent: typeof navigator !== "undefined" ? navigator.userAgent : "",
1229
+ project_name: config.project,
1230
+ environment: config.environment
1231
+ });
1232
+ throw err;
1233
+ }
1234
+ }
1235
+ __name(monitoredFetch, "monitoredFetch");
1236
+
1237
+ // src/client/index.ts
1238
+ var flushInterval = null;
1239
+ var cleanupFns = [];
1240
+ var FrontendMonitor = {
1241
+ init(config = {}) {
1242
+ if (typeof window === "undefined") return;
1243
+ if (config.baseUrl) configureMonitorApi(config.baseUrl);
1244
+ monitorStore.getState().setConfig(config);
1245
+ ensureSessionCookie();
1246
+ if (config.captureJsErrors !== false) cleanupFns.push(installJsErrorCapture());
1247
+ if (config.captureConsole !== false) cleanupFns.push(installConsoleCapture());
1248
+ cleanupFns.push(installValidationCapture());
1249
+ const interval = config.flushInterval ?? 5e3;
1250
+ flushInterval = setInterval(() => monitorStore.getState().flush(), interval);
1251
+ const onHide = /* @__PURE__ */ __name(() => {
1252
+ if (document.visibilityState === "hidden") monitorStore.getState().flush(true);
1253
+ }, "onHide");
1254
+ window.addEventListener("visibilitychange", onHide);
1255
+ window.addEventListener("beforeunload", () => monitorStore.getState().flush(true));
1256
+ if (config.debug) console.info("[FrontendMonitor] initialized", config);
1257
+ },
1258
+ capture(event) {
1259
+ monitorStore.getState().push(event);
1260
+ },
1261
+ flush() {
1262
+ monitorStore.getState().flush();
1263
+ },
1264
+ destroy() {
1265
+ if (flushInterval !== null) {
1266
+ clearInterval(flushInterval);
1267
+ flushInterval = null;
1268
+ }
1269
+ cleanupFns.forEach((fn) => fn());
1270
+ cleanupFns.length = 0;
1271
+ }
1272
+ };
1273
+ //# sourceMappingURL=client.cjs.map