@djangocfg/monitor 2.1.216 → 2.1.218

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/client.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import * as react from 'react';
2
+ import * as zustand_vanilla from 'zustand/vanilla';
3
+
1
4
  /**
2
5
  * * `ERROR` - Error
3
6
  * * `WARNING` - Warning
@@ -92,6 +95,60 @@ declare function monitoredFetch(input: RequestInfo | URL, init?: RequestInit): P
92
95
 
93
96
  declare function getSessionId(): string;
94
97
 
98
+ interface MonitorProviderProps extends MonitorConfig {
99
+ /** Optional: render children inside the provider (or use as a standalone leaf) */
100
+ children?: React.ReactNode;
101
+ }
102
+ declare function MonitorProvider({ children, ...config }: MonitorProviderProps): react.ReactNode;
103
+
104
+ /**
105
+ * window.monitor — global debug API for browser console testing.
106
+ *
107
+ * Automatically installed by MonitorProvider after FrontendMonitor.init().
108
+ * Allows manual event firing from DevTools without importing the module.
109
+ *
110
+ * @example
111
+ * // In browser DevTools console:
112
+ * window.monitor.error('Something broke')
113
+ * window.monitor.warn('Low disk space', { extra: 'context' })
114
+ * window.monitor.network(404, 'GET', '/api/users/')
115
+ * window.monitor.flush()
116
+ * window.monitor.status()
117
+ */
118
+
119
+ interface WindowMonitorAPI {
120
+ /** Capture a custom error event */
121
+ error(message: string, extra?: Record<string, unknown>): void;
122
+ /** Capture a custom warning event */
123
+ warn(message: string, extra?: Record<string, unknown>): void;
124
+ /** Capture a custom info event */
125
+ info(message: string, extra?: Record<string, unknown>): void;
126
+ /** Capture a network error event */
127
+ network(status: number, method: string, url: string, extra?: Record<string, unknown>): void;
128
+ /** Capture a raw event (full control) */
129
+ capture(event: FrontendEventIngestRequest): void;
130
+ /** Force-flush the event buffer to backend */
131
+ flush(): void;
132
+ /** Show current monitor state (config + buffer size) */
133
+ status(): void;
134
+ }
135
+ declare global {
136
+ interface Window {
137
+ monitor?: WindowMonitorAPI;
138
+ }
139
+ }
140
+ declare function initWindowMonitor(): void;
141
+
142
+ interface MonitorState {
143
+ config: MonitorConfig;
144
+ buffer: FrontendEventIngestRequest[];
145
+ initialized: boolean;
146
+ push: (event: FrontendEventIngestRequest) => void;
147
+ flush: (useBeacon?: boolean) => void;
148
+ setConfig: (config: MonitorConfig) => void;
149
+ }
150
+ declare const monitorStore: zustand_vanilla.StoreApi<MonitorState>;
151
+
95
152
  /**
96
153
  * @djangocfg/monitor/client
97
154
  *
@@ -120,4 +177,4 @@ declare const FrontendMonitor: {
120
177
  destroy(): void;
121
178
  };
122
179
 
123
- export { FrontendEventIngestRequestLevel as EventLevel, FrontendEventIngestRequestEventType as EventType, FrontendMonitor, type MonitorConfig, type FrontendEventIngestRequest as MonitorEvent, getSessionId, monitoredFetch };
180
+ export { FrontendEventIngestRequestLevel as EventLevel, FrontendEventIngestRequestEventType as EventType, FrontendMonitor, type MonitorConfig, type FrontendEventIngestRequest as MonitorEvent, MonitorProvider, type MonitorProviderProps, type WindowMonitorAPI, getSessionId, initWindowMonitor, monitorStore, monitoredFetch };
package/dist/client.mjs CHANGED
@@ -1,6 +1,259 @@
1
1
  "use client";
2
+ var __create = Object.create;
2
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;
3
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
30
+ var require_retry_operation = __commonJS({
31
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
32
+ function RetryOperation(timeouts, options) {
33
+ if (typeof options === "boolean") {
34
+ options = { forever: options };
35
+ }
36
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
37
+ this._timeouts = timeouts;
38
+ this._options = options || {};
39
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
40
+ this._fn = null;
41
+ this._errors = [];
42
+ this._attempts = 1;
43
+ this._operationTimeout = null;
44
+ this._operationTimeoutCb = null;
45
+ this._timeout = null;
46
+ this._operationStart = null;
47
+ this._timer = null;
48
+ if (this._options.forever) {
49
+ this._cachedTimeouts = this._timeouts.slice(0);
50
+ }
51
+ }
52
+ __name(RetryOperation, "RetryOperation");
53
+ module.exports = RetryOperation;
54
+ RetryOperation.prototype.reset = function() {
55
+ this._attempts = 1;
56
+ this._timeouts = this._originalTimeouts.slice(0);
57
+ };
58
+ RetryOperation.prototype.stop = function() {
59
+ if (this._timeout) {
60
+ clearTimeout(this._timeout);
61
+ }
62
+ if (this._timer) {
63
+ clearTimeout(this._timer);
64
+ }
65
+ this._timeouts = [];
66
+ this._cachedTimeouts = null;
67
+ };
68
+ RetryOperation.prototype.retry = function(err) {
69
+ if (this._timeout) {
70
+ clearTimeout(this._timeout);
71
+ }
72
+ if (!err) {
73
+ return false;
74
+ }
75
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
76
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
77
+ this._errors.push(err);
78
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
79
+ return false;
80
+ }
81
+ this._errors.push(err);
82
+ var timeout = this._timeouts.shift();
83
+ if (timeout === void 0) {
84
+ if (this._cachedTimeouts) {
85
+ this._errors.splice(0, this._errors.length - 1);
86
+ timeout = this._cachedTimeouts.slice(-1);
87
+ } else {
88
+ return false;
89
+ }
90
+ }
91
+ var self = this;
92
+ this._timer = setTimeout(function() {
93
+ self._attempts++;
94
+ if (self._operationTimeoutCb) {
95
+ self._timeout = setTimeout(function() {
96
+ self._operationTimeoutCb(self._attempts);
97
+ }, self._operationTimeout);
98
+ if (self._options.unref) {
99
+ self._timeout.unref();
100
+ }
101
+ }
102
+ self._fn(self._attempts);
103
+ }, timeout);
104
+ if (this._options.unref) {
105
+ this._timer.unref();
106
+ }
107
+ return true;
108
+ };
109
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
110
+ this._fn = fn;
111
+ if (timeoutOps) {
112
+ if (timeoutOps.timeout) {
113
+ this._operationTimeout = timeoutOps.timeout;
114
+ }
115
+ if (timeoutOps.cb) {
116
+ this._operationTimeoutCb = timeoutOps.cb;
117
+ }
118
+ }
119
+ var self = this;
120
+ if (this._operationTimeoutCb) {
121
+ this._timeout = setTimeout(function() {
122
+ self._operationTimeoutCb();
123
+ }, self._operationTimeout);
124
+ }
125
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
126
+ this._fn(this._attempts);
127
+ };
128
+ RetryOperation.prototype.try = function(fn) {
129
+ console.log("Using RetryOperation.try() is deprecated");
130
+ this.attempt(fn);
131
+ };
132
+ RetryOperation.prototype.start = function(fn) {
133
+ console.log("Using RetryOperation.start() is deprecated");
134
+ this.attempt(fn);
135
+ };
136
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
137
+ RetryOperation.prototype.errors = function() {
138
+ return this._errors;
139
+ };
140
+ RetryOperation.prototype.attempts = function() {
141
+ return this._attempts;
142
+ };
143
+ RetryOperation.prototype.mainError = function() {
144
+ if (this._errors.length === 0) {
145
+ return null;
146
+ }
147
+ var counts = {};
148
+ var mainError = null;
149
+ var mainErrorCount = 0;
150
+ for (var i = 0; i < this._errors.length; i++) {
151
+ var error = this._errors[i];
152
+ var message = error.message;
153
+ var count = (counts[message] || 0) + 1;
154
+ counts[message] = count;
155
+ if (count >= mainErrorCount) {
156
+ mainError = error;
157
+ mainErrorCount = count;
158
+ }
159
+ }
160
+ return mainError;
161
+ };
162
+ }
163
+ });
164
+
165
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
166
+ var require_retry = __commonJS({
167
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
168
+ var RetryOperation = require_retry_operation();
169
+ exports.operation = function(options) {
170
+ var timeouts = exports.timeouts(options);
171
+ return new RetryOperation(timeouts, {
172
+ forever: options && (options.forever || options.retries === Infinity),
173
+ unref: options && options.unref,
174
+ maxRetryTime: options && options.maxRetryTime
175
+ });
176
+ };
177
+ exports.timeouts = function(options) {
178
+ if (options instanceof Array) {
179
+ return [].concat(options);
180
+ }
181
+ var opts = {
182
+ retries: 10,
183
+ factor: 2,
184
+ minTimeout: 1 * 1e3,
185
+ maxTimeout: Infinity,
186
+ randomize: false
187
+ };
188
+ for (var key in options) {
189
+ opts[key] = options[key];
190
+ }
191
+ if (opts.minTimeout > opts.maxTimeout) {
192
+ throw new Error("minTimeout is greater than maxTimeout");
193
+ }
194
+ var timeouts = [];
195
+ for (var i = 0; i < opts.retries; i++) {
196
+ timeouts.push(this.createTimeout(i, opts));
197
+ }
198
+ if (options && options.forever && !timeouts.length) {
199
+ timeouts.push(this.createTimeout(i, opts));
200
+ }
201
+ timeouts.sort(function(a, b) {
202
+ return a - b;
203
+ });
204
+ return timeouts;
205
+ };
206
+ exports.createTimeout = function(attempt, opts) {
207
+ var random = opts.randomize ? Math.random() + 1 : 1;
208
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
209
+ timeout = Math.min(timeout, opts.maxTimeout);
210
+ return timeout;
211
+ };
212
+ exports.wrap = function(obj, options, methods) {
213
+ if (options instanceof Array) {
214
+ methods = options;
215
+ options = null;
216
+ }
217
+ if (!methods) {
218
+ methods = [];
219
+ for (var key in obj) {
220
+ if (typeof obj[key] === "function") {
221
+ methods.push(key);
222
+ }
223
+ }
224
+ }
225
+ for (var i = 0; i < methods.length; i++) {
226
+ var method = methods[i];
227
+ var original = obj[method];
228
+ obj[method] = (/* @__PURE__ */ __name(function retryWrapper(original2) {
229
+ var op = exports.operation(options);
230
+ var args = Array.prototype.slice.call(arguments, 1);
231
+ var callback = args.pop();
232
+ args.push(function(err) {
233
+ if (op.retry(err)) {
234
+ return;
235
+ }
236
+ if (err) {
237
+ arguments[0] = op.mainError();
238
+ }
239
+ callback.apply(this, arguments);
240
+ });
241
+ op.attempt(function() {
242
+ original2.apply(obj, args);
243
+ });
244
+ }, "retryWrapper")).bind(obj, original);
245
+ obj[method].options = options;
246
+ }
247
+ };
248
+ }
249
+ });
250
+
251
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
252
+ var require_retry2 = __commonJS({
253
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
254
+ module.exports = require_retry();
255
+ }
256
+ });
4
257
 
5
258
  // src/client/capture/fingerprint.ts
6
259
  function simpleHash(str) {
@@ -392,8 +645,127 @@ __name(_APILogger, "APILogger");
392
645
  var APILogger = _APILogger;
393
646
  var defaultLogger = new APILogger();
394
647
 
648
+ // ../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
649
+ var import_retry = __toESM(require_retry2(), 1);
650
+
651
+ // ../../node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.js
652
+ var objectToString = Object.prototype.toString;
653
+ var isError = /* @__PURE__ */ __name((value) => objectToString.call(value) === "[object Error]", "isError");
654
+ var errorMessages = /* @__PURE__ */ new Set([
655
+ "network error",
656
+ // Chrome
657
+ "Failed to fetch",
658
+ // Chrome
659
+ "NetworkError when attempting to fetch resource.",
660
+ // Firefox
661
+ "The Internet connection appears to be offline.",
662
+ // Safari 16
663
+ "Network request failed",
664
+ // `cross-fetch`
665
+ "fetch failed",
666
+ // Undici (Node.js)
667
+ "terminated",
668
+ // Undici (Node.js)
669
+ " A network error occurred.",
670
+ // Bun (WebKit)
671
+ "Network connection lost"
672
+ // Cloudflare Workers (fetch)
673
+ ]);
674
+ function isNetworkError(error) {
675
+ const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
676
+ if (!isValid) {
677
+ return false;
678
+ }
679
+ const { message, stack } = error;
680
+ if (message === "Load failed") {
681
+ return stack === void 0 || "__sentry_captured__" in error;
682
+ }
683
+ if (message.startsWith("error sending request for url")) {
684
+ return true;
685
+ }
686
+ return errorMessages.has(message);
687
+ }
688
+ __name(isNetworkError, "isNetworkError");
689
+
690
+ // ../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
691
+ var _AbortError = class _AbortError extends Error {
692
+ constructor(message) {
693
+ super();
694
+ if (message instanceof Error) {
695
+ this.originalError = message;
696
+ ({ message } = message);
697
+ } else {
698
+ this.originalError = new Error(message);
699
+ this.originalError.stack = this.stack;
700
+ }
701
+ this.name = "AbortError";
702
+ this.message = message;
703
+ }
704
+ };
705
+ __name(_AbortError, "AbortError");
706
+ var AbortError = _AbortError;
707
+ var decorateErrorWithCounts = /* @__PURE__ */ __name((error, attemptNumber, options) => {
708
+ const retriesLeft = options.retries - (attemptNumber - 1);
709
+ error.attemptNumber = attemptNumber;
710
+ error.retriesLeft = retriesLeft;
711
+ return error;
712
+ }, "decorateErrorWithCounts");
713
+ async function pRetry(input, options) {
714
+ return new Promise((resolve, reject) => {
715
+ options = { ...options };
716
+ options.onFailedAttempt ?? (options.onFailedAttempt = () => {
717
+ });
718
+ options.shouldRetry ?? (options.shouldRetry = () => true);
719
+ options.retries ?? (options.retries = 10);
720
+ const operation = import_retry.default.operation(options);
721
+ const abortHandler = /* @__PURE__ */ __name(() => {
722
+ operation.stop();
723
+ reject(options.signal?.reason);
724
+ }, "abortHandler");
725
+ if (options.signal && !options.signal.aborted) {
726
+ options.signal.addEventListener("abort", abortHandler, { once: true });
727
+ }
728
+ const cleanUp = /* @__PURE__ */ __name(() => {
729
+ options.signal?.removeEventListener("abort", abortHandler);
730
+ operation.stop();
731
+ }, "cleanUp");
732
+ operation.attempt(async (attemptNumber) => {
733
+ try {
734
+ const result = await input(attemptNumber);
735
+ cleanUp();
736
+ resolve(result);
737
+ } catch (error) {
738
+ try {
739
+ if (!(error instanceof Error)) {
740
+ throw new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
741
+ }
742
+ if (error instanceof AbortError) {
743
+ throw error.originalError;
744
+ }
745
+ if (error instanceof TypeError && !isNetworkError(error)) {
746
+ throw error;
747
+ }
748
+ decorateErrorWithCounts(error, attemptNumber, options);
749
+ if (!await options.shouldRetry(error)) {
750
+ operation.stop();
751
+ reject(error);
752
+ }
753
+ await options.onFailedAttempt(error);
754
+ if (!operation.retry(error)) {
755
+ throw operation.mainError();
756
+ }
757
+ } catch (finalError) {
758
+ decorateErrorWithCounts(finalError, attemptNumber, options);
759
+ cleanUp();
760
+ reject(finalError);
761
+ }
762
+ }
763
+ });
764
+ });
765
+ }
766
+ __name(pRetry, "pRetry");
767
+
395
768
  // src/_api/generated/cfg_monitor/retry.ts
396
- import pRetry, { AbortError } from "p-retry";
397
769
  var DEFAULT_RETRY_CONFIG = {
398
770
  retries: 3,
399
771
  factor: 2,
@@ -1199,13 +1571,92 @@ async function monitoredFetch(input, init) {
1199
1571
  }
1200
1572
  __name(monitoredFetch, "monitoredFetch");
1201
1573
 
1574
+ // src/client/MonitorProvider.tsx
1575
+ import { useEffect } from "react";
1576
+
1577
+ // src/client/window.ts
1578
+ function makeEvent(type, level, message, extra) {
1579
+ const state = monitorStore.getState();
1580
+ const cfg = state.config;
1581
+ return {
1582
+ event_type: type,
1583
+ level,
1584
+ message,
1585
+ session_id: getSessionId(),
1586
+ url: window.location.href,
1587
+ user_agent: navigator.userAgent,
1588
+ project_name: cfg.project ?? "",
1589
+ environment: cfg.environment ?? "",
1590
+ ...extra ? { extra } : {}
1591
+ };
1592
+ }
1593
+ __name(makeEvent, "makeEvent");
1594
+ function initWindowMonitor() {
1595
+ if (typeof window === "undefined") return;
1596
+ const api = {
1597
+ error(message, extra) {
1598
+ monitorStore.getState().push(makeEvent("JS_ERROR" /* JS_ERROR */, "error" /* ERROR */, message, extra));
1599
+ console.log("[monitor] error captured \u2192", message);
1600
+ },
1601
+ warn(message, extra) {
1602
+ monitorStore.getState().push(makeEvent("WARNING" /* WARNING */, "warn" /* WARN */, message, extra));
1603
+ console.log("[monitor] warn captured \u2192", message);
1604
+ },
1605
+ info(message, extra) {
1606
+ monitorStore.getState().push(makeEvent("INFO" /* INFO */, "info" /* INFO */, message, extra));
1607
+ console.log("[monitor] info captured \u2192", message);
1608
+ },
1609
+ network(status, method, url, extra) {
1610
+ const event = makeEvent(
1611
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1612
+ status >= 500 ? "error" /* ERROR */ : "warn" /* WARN */,
1613
+ `${method} ${url} \u2192 ${status}`,
1614
+ extra
1615
+ );
1616
+ monitorStore.getState().push({ ...event, http_status: status, http_method: method, http_url: url });
1617
+ console.log("[monitor] network captured \u2192", method, url, status);
1618
+ },
1619
+ capture(event) {
1620
+ monitorStore.getState().push(event);
1621
+ console.log("[monitor] event captured \u2192", event);
1622
+ },
1623
+ flush() {
1624
+ monitorStore.getState().flush();
1625
+ console.log("[monitor] flushed");
1626
+ },
1627
+ status() {
1628
+ const state = monitorStore.getState();
1629
+ console.group("[monitor] status");
1630
+ console.log("config:", state.config);
1631
+ console.log("buffer size:", state.buffer.length);
1632
+ console.log("initialized:", state.initialized);
1633
+ console.log("session_id:", getSessionId());
1634
+ console.groupEnd();
1635
+ }
1636
+ };
1637
+ window.monitor = api;
1638
+ }
1639
+ __name(initWindowMonitor, "initWindowMonitor");
1640
+
1641
+ // src/client/MonitorProvider.tsx
1642
+ function MonitorProvider({ children, ...config }) {
1643
+ useEffect(() => {
1644
+ FrontendMonitor.init(config);
1645
+ initWindowMonitor();
1646
+ return () => FrontendMonitor.destroy();
1647
+ }, []);
1648
+ return children ?? null;
1649
+ }
1650
+ __name(MonitorProvider, "MonitorProvider");
1651
+
1202
1652
  // src/client/index.ts
1203
1653
  var flushInterval = null;
1204
1654
  var cleanupFns = [];
1205
1655
  var FrontendMonitor = {
1206
1656
  init(config = {}) {
1207
1657
  if (typeof window === "undefined") return;
1208
- if (config.baseUrl) configureMonitorApi(config.baseUrl);
1658
+ const baseUrl = config.baseUrl ?? process.env.NEXT_PUBLIC_API_URL ?? "";
1659
+ if (baseUrl) configureMonitorApi(baseUrl);
1209
1660
  monitorStore.getState().setConfig(config);
1210
1661
  ensureSessionCookie();
1211
1662
  if (config.captureJsErrors !== false) cleanupFns.push(installJsErrorCapture());
@@ -1237,7 +1688,10 @@ var FrontendMonitor = {
1237
1688
  };
1238
1689
  export {
1239
1690
  FrontendMonitor,
1691
+ MonitorProvider,
1240
1692
  getSessionId,
1693
+ initWindowMonitor,
1694
+ monitorStore,
1241
1695
  monitoredFetch
1242
1696
  };
1243
1697
  //# sourceMappingURL=client.mjs.map