reportli 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24,662 +24,348 @@ __export(src_exports, {
24
24
  default: () => src_default
25
25
  });
26
26
  module.exports = __toCommonJS(src_exports);
27
- var ENDPOINT_URL = "https://fahikyfmgdyzejdfftox.supabase.co/functions/v1/rapid-processor";
28
- var ReportliTracker = class {
29
- constructor() {
30
- this.config = null;
31
- this.isInitialized = false;
32
- /**
33
- * Express error handler middleware
34
- */
35
- this.expressErrorHandler = (err, req, res, next) => {
36
- if (this.isInitialized && this.config) {
37
- try {
38
- const errorObject = this.normalizeError(err);
39
- const { errorType, severity } = this.classifyError(errorObject, "express");
40
- const payload = {
41
- apiKey: this.config.apiKey,
42
- projectId: this.config.projectId || "express-server",
43
- projectName: this.config.projectName || "Express App",
44
- errorType: errorType || "Route handler error",
45
- errorMessage: `${req.method} ${req.url} - ${errorObject.message}`,
46
- errorStack: errorObject.stack || "",
47
- framework: this.config.framework || "Express",
48
- user_email: this.config.userEmail || req.user?.email || "anonymous",
49
- severity: severity || "high",
50
- status: "open"
51
- };
52
- this.sendCrashReport(payload);
53
- } catch (e) {
54
- console.error("[Reportli SDK] Failed to process express exception:", e);
55
- }
56
- }
57
- next(err);
58
- };
27
+ var ENDPOINT = "https://fahikyfmgdyzejdfftox.supabase.co/functions/v1/rapid-processor";
28
+ var isBrowser = typeof window !== "undefined";
29
+ var isNode = typeof process !== "undefined" && !!process.versions?.node;
30
+ var _apiKey = "";
31
+ function getEnvironment() {
32
+ return isBrowser ? "browser" : "server";
33
+ }
34
+ function getUrl() {
35
+ if (isBrowser)
36
+ return window.location.href;
37
+ try {
38
+ return require("os").hostname();
39
+ } catch {
40
+ return "server";
59
41
  }
60
- /**
61
- * Initializes the Reportli tracker with your secure project credentials.
62
- */
63
- init(config) {
64
- if (!config || !config.apiKey) {
65
- console.error("[Reportli SDK] Initialization failed: 'apiKey' is required.");
66
- return;
67
- }
68
- if (this.isInitialized) {
69
- return;
70
- }
71
- this.config = {
72
- environment: "production",
73
- captureUnhandledRejections: true,
74
- autoCreateGitHubIssues: true,
75
- ...config
76
- };
77
- this.isInitialized = true;
78
- const isBrowser = typeof window !== "undefined";
79
- const isNode = typeof process !== "undefined" && process.versions && process.versions.node;
80
- this.sendRegistrationWebhook(isBrowser);
81
- if (isBrowser) {
82
- this.setupBrowserListeners();
83
- } else if (isNode) {
84
- this.setupNodeListeners();
85
- }
86
- console.log("[Reportli SDK] Exception listener successfully initialized.");
87
- }
88
- /**
89
- * Manually captures and files a custom application exception with custom severity.
90
- */
91
- captureException(error, severityInput) {
92
- if (!this.isInitialized || !this.config) {
93
- console.warn("[Reportli SDK] Capture failed: SDK is not initialized yet.");
94
- return;
95
- }
96
- const errorObject = this.normalizeError(error);
97
- const { errorType, severity } = this.classifyError(errorObject);
98
- const payload = {
99
- apiKey: this.config.apiKey,
100
- projectId: this.config.projectId || "proj-sandbox",
101
- projectName: this.config.projectName || "SaaS App",
102
- errorType,
103
- errorMessage: errorObject.message || "Manual trace reported",
104
- errorStack: errorObject.stack || "",
105
- framework: this.config.framework || (typeof window !== "undefined" ? "React/Next.js Client" : "Node.js Server"),
106
- user_email: this.config.userEmail || "anonymous",
107
- severity: severityInput || severity,
108
- status: "open"
42
+ }
43
+ function getBrowser() {
44
+ if (isBrowser)
45
+ return navigator.userAgent;
46
+ return `Node.js ${typeof process !== "undefined" ? process.version : "unknown"}`;
47
+ }
48
+ function parseStack(stack) {
49
+ if (!stack)
50
+ return { file: "unknown", line: 0, column: 0 };
51
+ const match = stack.match(/at .+ \((.+):(\d+):(\d+)\)/) || stack.match(/at (.+):(\d+):(\d+)/);
52
+ return {
53
+ file: match?.[1]?.split("/")?.pop() || "unknown",
54
+ line: parseInt(match?.[2] || "0"),
55
+ column: parseInt(match?.[3] || "0")
56
+ };
57
+ }
58
+ function getErrorCode(error) {
59
+ return error?.code || error?.status?.toString() || error?.statusCode?.toString() || error?.name || "ERR_UNKNOWN";
60
+ }
61
+ function classifyError(error, context) {
62
+ const msg = String(error?.message || error || "").toLowerCase();
63
+ const name = String(error?.name || "").toLowerCase();
64
+ if (name.includes("quotaexceeded") || msg.includes("quota exceeded") || msg.includes("localstorage") || msg.includes("indexeddb"))
65
+ return { errorType: "localStorage quota exceeded", severity: "medium" };
66
+ if (msg.includes("hydration") || msg.includes("does not match server"))
67
+ return { errorType: "React hydration error", severity: "high" };
68
+ if (msg.includes("invalid hook call") || msg.includes("rules of hooks"))
69
+ return { errorType: "Invalid hook call error", severity: "critical" };
70
+ if (msg.includes("failed prop type") || msg.includes("invalid prop"))
71
+ return { errorType: "Props type error", severity: "low" };
72
+ if (msg.includes("render") || msg.includes("react error boundary"))
73
+ return { errorType: "Component render error", severity: "critical" };
74
+ if (msg.includes("route not found") || msg.includes("404 route"))
75
+ return { errorType: "Route not found error", severity: "medium" };
76
+ if (msg.includes("failed to fetch dynamically imported") || msg.includes("dynamic import"))
77
+ return { errorType: "Dynamic import error", severity: "high" };
78
+ if (msg.includes("suspense"))
79
+ return { errorType: "Suspense boundary error", severity: "medium" };
80
+ if (name === "typeerror" || msg.startsWith("typeerror"))
81
+ return { errorType: "TypeError", severity: "high" };
82
+ if (name === "referenceerror")
83
+ return { errorType: "ReferenceError", severity: "critical" };
84
+ if (name === "rangeerror" || msg.includes("maximum call stack"))
85
+ return { errorType: "Stack overflow error", severity: "critical" };
86
+ if (name === "syntaxerror")
87
+ return { errorType: "SyntaxError", severity: "high" };
88
+ if (msg.includes("stripe") && (msg.includes("init") || msg.includes("key")))
89
+ return { errorType: "Stripe initialization error", severity: "critical" };
90
+ if (msg.includes("payment") || msg.includes("card declined"))
91
+ return { errorType: "Payment processing error", severity: "critical" };
92
+ if (msg.includes("checkout session"))
93
+ return { errorType: "Checkout session error", severity: "high" };
94
+ if (msg.includes("refund failed"))
95
+ return { errorType: "Refund failed error", severity: "high" };
96
+ if (msg.includes("supabase") || msg.includes("postgresterror"))
97
+ return { errorType: "Supabase query error", severity: "critical" };
98
+ if (msg.includes("unique constraint") || msg.includes("duplicate key"))
99
+ return { errorType: "Unique constraint error", severity: "high" };
100
+ if (msg.includes("foreign key"))
101
+ return { errorType: "Foreign key error", severity: "high" };
102
+ if (msg.includes("transaction failed") || msg.includes("rollback"))
103
+ return { errorType: "Transaction failed error", severity: "critical" };
104
+ if (msg.includes("connection lost") || msg.includes("econnrefused"))
105
+ return { errorType: "Connection lost error", severity: "critical" };
106
+ if (msg.includes("query timeout"))
107
+ return { errorType: "Query timeout error", severity: "high" };
108
+ if (msg.includes("jwt expired") || msg.includes("token expired"))
109
+ return { errorType: "JWT expired error", severity: "high" };
110
+ if (msg.includes("jwt") && msg.includes("invalid"))
111
+ return { errorType: "JWT verification error", severity: "high" };
112
+ if (msg.includes("firebase admin"))
113
+ return { errorType: "Firebase admin error", severity: "critical" };
114
+ if (msg.includes("unauthorized") || msg.includes("permission denied"))
115
+ return { errorType: "Unauthorized access error", severity: "high" };
116
+ if (msg.includes("login failed") || msg.includes("invalid credentials"))
117
+ return { errorType: "Login failed error", severity: "medium" };
118
+ if (msg.includes("session ended") || msg.includes("session expired"))
119
+ return { errorType: "Session ended error", severity: "medium" };
120
+ if (msg.includes("oauth"))
121
+ return { errorType: "OAuth callback error", severity: "high" };
122
+ if (msg.includes("cron job") || msg.includes("cron failed"))
123
+ return { errorType: "Cron job failed", severity: "high" };
124
+ if (msg.includes("queue processing") || msg.includes("bullmq"))
125
+ return { errorType: "Queue processing error", severity: "high" };
126
+ if (msg.includes("webhook"))
127
+ return { errorType: "Webhook delivery failed", severity: "high" };
128
+ if (msg.includes("retry limit"))
129
+ return { errorType: "Retry limit exceeded", severity: "high" };
130
+ if (msg.includes("out of memory") || msg.includes("heap limit"))
131
+ return { errorType: "Out of memory error", severity: "critical" };
132
+ if (msg.includes("cannot find module"))
133
+ return { errorType: "Module not found error", severity: "critical" };
134
+ if (msg.includes("email") || msg.includes("smtp") || msg.includes("sendgrid") || msg.includes("nodemailer"))
135
+ return { errorType: "Email sending failed", severity: "high" };
136
+ if (msg.includes("onesignal") || msg.includes("push notification"))
137
+ return { errorType: "OneSignal API error", severity: "high" };
138
+ if (msg.includes("file upload") || msg.includes("upload failed"))
139
+ return { errorType: "File upload failed", severity: "high" };
140
+ if (msg.includes("file size exceeded") || msg.includes("payload too large"))
141
+ return { errorType: "File size exceeded", severity: "medium" };
142
+ if (msg.includes("invalid file type") || msg.includes("mime type"))
143
+ return { errorType: "Invalid file type", severity: "medium" };
144
+ if (msg.includes("cors") || msg.includes("cross-origin"))
145
+ return { errorType: "CORS error", severity: "high" };
146
+ if (msg.includes("fetch failed") || msg.includes("failed to fetch"))
147
+ return { errorType: "Fetch failed error", severity: "high" };
148
+ if (msg.includes("timeout") || msg.includes("timed out") || msg.includes("etimedout"))
149
+ return { errorType: "Request timeout error", severity: "medium" };
150
+ if (msg.includes("websocket"))
151
+ return { errorType: "WebSocket connection error", severity: "high" };
152
+ if (context === "unhandledrejection")
153
+ return { errorType: "Unhandled promise rejection", severity: "medium" };
154
+ if (context === "uncaughtexception")
155
+ return { errorType: "Uncaught exception", severity: "high" };
156
+ if (context === "express")
157
+ return { errorType: "Route handler error", severity: "high" };
158
+ return { errorType: "Uncaught exception", severity: "medium" };
159
+ }
160
+ function normalizeError(err) {
161
+ if (err instanceof Error)
162
+ return { name: err.name, message: err.message, stack: err.stack };
163
+ if (typeof err === "string")
164
+ return { name: "Error", message: err, stack: new Error(err).stack };
165
+ if (err && typeof err === "object")
166
+ return {
167
+ name: err.name || err.code || "Error",
168
+ message: err.message || err.reason || JSON.stringify(err),
169
+ stack: err.stack || new Error(err.message).stack
109
170
  };
110
- this.sendCrashReport(payload);
111
- }
112
- /**
113
- * Registers global window listeners for DOM-based exceptions.
114
- */
115
- setupBrowserListeners() {
116
- if (typeof window === "undefined")
171
+ return { name: "Error", message: "Unknown error", stack: new Error().stack };
172
+ }
173
+ async function send(payload) {
174
+ try {
175
+ if (payload.message?.includes("rapid-processor"))
117
176
  return;
118
- window.addEventListener("error", (event) => {
119
- if (event.filename && event.filename.includes("rapid-processor"))
120
- return;
121
- try {
122
- const error = event.error || {
123
- message: event.message,
124
- filename: event.filename,
125
- lineno: event.lineno,
126
- colno: event.colno,
127
- stack: `${event.message} at ${event.filename}:${event.lineno}:${event.colno}`
128
- };
129
- const errorObject = this.normalizeError(error);
130
- const { errorType, severity } = this.classifyError(errorObject);
131
- const payload = {
132
- apiKey: this.config?.apiKey || "",
133
- projectId: this.config?.projectId || "proj-sandbox",
134
- projectName: this.config?.projectName || "SaaS App",
135
- errorType,
136
- errorMessage: errorObject.message,
137
- errorStack: errorObject.stack || "",
138
- framework: this.config?.framework || "React/Next.js Client",
139
- user_email: this.config?.userEmail || "anonymous",
140
- severity,
141
- status: "open"
142
- };
143
- this.sendCrashReport(payload);
144
- } catch (err) {
145
- console.error("[Reportli SDK] Inner listener exception:", err);
146
- }
147
- });
148
- window.addEventListener("unhandledrejection", (event) => {
149
- try {
150
- const reason = event.reason;
151
- const errorObject = this.normalizeError(reason);
152
- const { errorType, severity } = this.classifyError(errorObject, "unhandledrejection");
153
- const payload = {
154
- apiKey: this.config?.apiKey || "",
155
- projectId: this.config?.projectId || "proj-sandbox",
156
- projectName: this.config?.projectName || "SaaS App",
157
- errorType,
158
- errorMessage: `Unhandled Promise: ${errorObject.message}`,
159
- errorStack: errorObject.stack || "",
160
- framework: this.config?.framework || "React/Next.js Client",
161
- user_email: this.config?.userEmail || "anonymous",
162
- severity,
163
- status: "open"
164
- };
165
- this.sendCrashReport(payload);
166
- } catch (err) {
167
- console.error("[Reportli SDK] Promise rejection listener exception:", err);
168
- }
169
- });
170
- window.addEventListener(
171
- "error",
172
- (event) => {
173
- try {
174
- const target = event.target || event.srcElement;
175
- if (!target)
176
- return;
177
- const tagName = target.tagName;
178
- if (!tagName)
179
- return;
180
- let resourceType = "";
181
- let sourceUrl = "";
182
- if (tagName === "IMG") {
183
- resourceType = "Image failed to load";
184
- sourceUrl = target.src;
185
- } else if (tagName === "SCRIPT") {
186
- resourceType = "Script failed to load";
187
- sourceUrl = target.src;
188
- } else if (tagName === "LINK") {
189
- resourceType = "CSS failed to load";
190
- sourceUrl = target.href;
191
- } else if (tagName === "VIDEO" || tagName === "AUDIO") {
192
- resourceType = "Video failed to load";
193
- sourceUrl = target.src;
194
- }
195
- if (resourceType) {
196
- const payload = {
197
- apiKey: this.config?.apiKey || "",
198
- projectId: this.config?.projectId || "proj-sandbox",
199
- projectName: this.config?.projectName || "SaaS App",
200
- errorType: resourceType,
201
- errorMessage: `Failed to load static resource asset: ${sourceUrl}`,
202
- errorStack: `HTML Tag: <${tagName.toLowerCase()}> failed to download at location ${window.location.href}`,
203
- framework: this.config?.framework || "React/Next.js Client",
204
- user_email: this.config?.userEmail || "anonymous",
205
- severity: "low",
206
- status: "open"
207
- };
208
- this.sendCrashReport(payload);
209
- }
210
- } catch (err) {
211
- console.error("[Reportli SDK] Resource load listener failure:", err);
212
- }
177
+ await fetch(ENDPOINT, {
178
+ method: "POST",
179
+ headers: {
180
+ "Content-Type": "application/json",
181
+ "x-api-key": _apiKey
213
182
  },
214
- true
215
- // capture phase is required for element errors
216
- );
217
- this.interceptFetch();
218
- this.interceptXhr();
219
- }
220
- /**
221
- * Registers node process listeners for server instances.
222
- */
223
- setupNodeListeners() {
224
- if (typeof process === "undefined")
225
- return;
226
- process.on("uncaughtException", (error) => {
227
- try {
228
- const errorObject = this.normalizeError(error);
229
- const { errorType, severity } = this.classifyError(errorObject, "uncaughtexception");
230
- const payload = {
231
- apiKey: this.config?.apiKey || "",
232
- projectId: this.config?.projectId || "node-server",
233
- projectName: this.config?.projectName || "Node Server",
234
- errorType,
235
- errorMessage: `Uncaught Exception: ${errorObject.message}`,
236
- errorStack: errorObject.stack || "",
237
- framework: this.config?.framework || "NodeJS backend",
238
- user_email: this.config?.userEmail || "anonymous",
239
- severity,
240
- status: "open"
241
- };
242
- this.sendCrashReport(payload);
243
- } catch (err) {
244
- console.error("[Reportli SDK] Node fatal uncaughtexception logging failed:", err);
245
- }
246
- });
247
- process.on("unhandledRejection", (reason) => {
248
- try {
249
- const errorObject = this.normalizeError(reason);
250
- const { errorType, severity } = this.classifyError(errorObject, "unhandledrejection");
251
- const payload = {
252
- apiKey: this.config?.apiKey || "",
253
- projectId: this.config?.projectId || "node-server",
254
- projectName: this.config?.projectName || "Node Server",
255
- errorType,
256
- errorMessage: `Unhandled Rejection: ${errorObject.message}`,
257
- errorStack: errorObject.stack || "",
258
- framework: this.config?.framework || "NodeJS backend",
259
- user_email: this.config?.userEmail || "anonymous",
260
- severity,
261
- status: "open"
262
- };
263
- this.sendCrashReport(payload);
264
- } catch (err) {
265
- console.error("[Reportli SDK] Node fatal unhandledrejection logging failed:", err);
266
- }
183
+ body: JSON.stringify(payload)
267
184
  });
185
+ } catch {
268
186
  }
269
- /**
270
- * Safe payload sender with retry limits.
271
- */
272
- async sendCrashReport(payload) {
273
- try {
274
- if (payload.errorMessage && (payload.errorMessage.includes("rapid-processor") || payload.errorMessage.includes("supabase"))) {
275
- return;
276
- }
277
- await fetch(ENDPOINT_URL, {
278
- method: "POST",
279
- headers: {
280
- "Content-Type": "application/json"
281
- },
282
- body: JSON.stringify(payload)
283
- });
284
- } catch (err) {
285
- console.warn("[Reportli SDK] Failed to synchronized crash traces to diagnostics server:", err);
286
- }
287
- }
288
- /**
289
- * Sends registration verification to user edge function on first install.
290
- */
291
- sendRegistrationWebhook(isBrowser) {
292
- if (!this.config)
187
+ }
188
+ function buildErrorPayload(error, context) {
189
+ const normalized = normalizeError(error);
190
+ const { file, line, column } = parseStack(normalized.stack);
191
+ const { errorType, severity } = classifyError(normalized, context);
192
+ return {
193
+ type: "ERROR",
194
+ apiKey: _apiKey,
195
+ message: normalized.message,
196
+ code: getErrorCode(error),
197
+ stack: normalized.stack || "",
198
+ file,
199
+ line,
200
+ column,
201
+ url: getUrl(),
202
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
203
+ environment: getEnvironment(),
204
+ browser: getBrowser(),
205
+ error_category: errorType,
206
+ severity,
207
+ status: "open"
208
+ };
209
+ }
210
+ function activateBrowserListeners() {
211
+ window.addEventListener("error", (event) => {
212
+ if (event.filename?.includes("rapid-processor"))
293
213
  return;
294
- const key = `reportli_initialized_success_${this.config.apiKey}`;
295
- if (isBrowser && typeof localStorage !== "undefined") {
296
- if (localStorage.getItem(key)) {
214
+ const target = event.target;
215
+ if (target && target.tagName) {
216
+ const tag = target.tagName;
217
+ const src = target.src || target.href || "";
218
+ if (["IMG", "SCRIPT", "LINK", "VIDEO", "AUDIO", "SOURCE"].includes(tag)) {
219
+ send(buildErrorPayload({
220
+ name: "ResourceError",
221
+ message: `${tag} failed to load: ${src}`,
222
+ stack: `at ${window.location.href}`
223
+ }));
297
224
  return;
298
225
  }
299
- localStorage.setItem(key, "true");
300
226
  }
301
- const deviceDetails = isBrowser ? typeof navigator !== "undefined" ? navigator.userAgent : "Browser sandbox" : typeof process !== "undefined" ? `NodeJS environment: ${process.version}` : "Cloud instance";
302
- const welcomePayload = {
303
- apiKey: this.config.apiKey,
304
- projectId: this.config.projectId || "proj-sandbox",
305
- projectName: this.config.projectName || "SaaS App Component",
306
- errorType: "SDK_INITIALIZED",
307
- errorMessage: "Reportli SDK successfully initialized! Error listener is active.",
308
- errorStack: `SDK Active Diagnostics: Success registration from execution agent. Device context: ${deviceDetails}`,
309
- framework: this.config.framework || (isBrowser ? "React/Next.js Client" : "Node.js Server"),
310
- user_email: this.config.userEmail || "anonymous",
311
- severity: "low",
312
- status: "info"
227
+ const err = event.error || {
228
+ name: "Error",
229
+ message: event.message,
230
+ stack: `${event.message} at ${event.filename}:${event.lineno}:${event.colno}`
313
231
  };
314
- this.sendCrashReport(welcomePayload);
315
- }
316
- /**
317
- * Capture fetch network status deviations.
318
- */
319
- interceptFetch() {
320
- if (typeof window === "undefined" || typeof window.fetch !== "function")
321
- return;
322
- const originalFetch = window.fetch;
323
- const self = this;
324
- window.fetch = async function(input, init) {
325
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
326
- if (url.includes("rapid-processor") || url.includes("supabase.co/functions")) {
327
- return originalFetch.apply(this, arguments);
232
+ send(buildErrorPayload(err));
233
+ }, true);
234
+ window.addEventListener("unhandledrejection", (event) => {
235
+ send(buildErrorPayload(event.reason || { message: "Unhandled Promise Rejection" }, "unhandledrejection"));
236
+ });
237
+ const originalFetch = window.fetch;
238
+ window.fetch = async function(input, init) {
239
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
240
+ if (url.includes("rapid-processor") || url.includes("supabase.co/functions")) {
241
+ return originalFetch.apply(this, arguments);
242
+ }
243
+ try {
244
+ const response = await originalFetch.apply(this, arguments);
245
+ if (!response.ok) {
246
+ send(buildErrorPayload({
247
+ name: `API ${response.status} Error`,
248
+ message: `HTTP ${response.status}: ${init?.method || "GET"} ${url}`,
249
+ stack: `${init?.method || "GET"} ${url} \u2192 ${response.status} ${response.statusText}`,
250
+ status: response.status
251
+ }));
328
252
  }
329
- try {
330
- const response = await originalFetch.apply(this, arguments);
331
- if (response && !response.ok) {
332
- self.logNetworkError(url, response.status, response.statusText, init?.method || "GET");
333
- }
334
- return response;
335
- } catch (err) {
336
- self.logNetworkFailure(url, err, init?.method || "GET");
337
- throw err;
253
+ return response;
254
+ } catch (err) {
255
+ send(buildErrorPayload({
256
+ name: "FetchError",
257
+ message: `Fetch failed: ${init?.method || "GET"} ${url} \u2014 ${err.message}`,
258
+ stack: err.stack
259
+ }));
260
+ throw err;
261
+ }
262
+ };
263
+ const originalOpen = XMLHttpRequest.prototype.open;
264
+ const originalSend = XMLHttpRequest.prototype.send;
265
+ XMLHttpRequest.prototype.open = function(method, url) {
266
+ this._r_method = method;
267
+ this._r_url = url;
268
+ return originalOpen.apply(this, arguments);
269
+ };
270
+ XMLHttpRequest.prototype.send = function() {
271
+ this.addEventListener("loadend", () => {
272
+ const url = this._r_url || "";
273
+ const method = this._r_method || "GET";
274
+ if (url.includes("rapid-processor"))
275
+ return;
276
+ if (this.status >= 400 || this.status === 0) {
277
+ send(buildErrorPayload({
278
+ name: `XHR ${this.status} Error`,
279
+ message: `XHR ${this.status}: ${method} ${url}`,
280
+ stack: `${method} ${url} \u2192 ${this.status} ${this.statusText}`,
281
+ status: this.status
282
+ }));
338
283
  }
339
- };
340
- }
341
- /**
342
- * Trace XHR status failures.
343
- */
344
- interceptXhr() {
345
- if (typeof window === "undefined" || typeof XMLHttpRequest === "undefined")
284
+ });
285
+ return originalSend.apply(this, arguments);
286
+ };
287
+ window.addEventListener("beforeunload", () => {
288
+ try {
289
+ navigator.sendBeacon(ENDPOINT, JSON.stringify({
290
+ type: "SDK_DISCONNECTED",
291
+ apiKey: _apiKey,
292
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
293
+ environment: "browser",
294
+ url: getUrl()
295
+ }));
296
+ } catch {
297
+ }
298
+ });
299
+ }
300
+ function activateServerListeners() {
301
+ process.on("uncaughtException", (error) => {
302
+ send(buildErrorPayload(error, "uncaughtexception"));
303
+ });
304
+ process.on("unhandledRejection", (reason) => {
305
+ send(buildErrorPayload(
306
+ reason instanceof Error ? reason : { name: "UnhandledRejection", message: String(reason), stack: "" },
307
+ "unhandledrejection"
308
+ ));
309
+ });
310
+ const shutdown = async () => {
311
+ await send({
312
+ type: "SDK_DISCONNECTED",
313
+ apiKey: _apiKey,
314
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
315
+ environment: "server",
316
+ url: getUrl()
317
+ });
318
+ process.exit(0);
319
+ };
320
+ process.on("SIGTERM", shutdown);
321
+ process.on("SIGINT", shutdown);
322
+ }
323
+ var Reportli = {
324
+ init({ apiKey }) {
325
+ if (!apiKey || _apiKey)
346
326
  return;
347
- const originalOpen = XMLHttpRequest.prototype.open;
348
- const originalSend = XMLHttpRequest.prototype.send;
349
- const self = this;
350
- XMLHttpRequest.prototype.open = function(method, url) {
351
- this._reportli_method = method;
352
- this._reportli_url = url;
353
- return originalOpen.apply(this, arguments);
354
- };
355
- XMLHttpRequest.prototype.send = function() {
356
- const xhrInstance = this;
357
- xhrInstance.addEventListener("loadend", () => {
358
- try {
359
- const url = xhrInstance._reportli_url || "";
360
- const method = xhrInstance._reportli_method || "GET";
361
- const status = xhrInstance.status;
362
- if (url.includes("rapid-processor") || url.includes("supabase.co/functions")) {
363
- return;
364
- }
365
- if (status >= 400 || status === 0) {
366
- if (status === 0) {
367
- self.logNetworkFailure(url, new Error("CORS or Connection Refused"), method);
368
- } else {
369
- self.logNetworkError(url, status, xhrInstance.statusText || "XHR Error", method);
370
- }
371
- }
372
- } catch (e) {
373
- console.error("[Reportli SDK] Failed to extract XHR statistics:", e);
374
- }
327
+ _apiKey = apiKey;
328
+ if (isBrowser && typeof localStorage !== "undefined") {
329
+ const key = `reportli_init_${apiKey}`;
330
+ if (!localStorage.getItem(key)) {
331
+ localStorage.setItem(key, "true");
332
+ send({
333
+ type: "SDK_INITIALIZED",
334
+ apiKey: _apiKey,
335
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
336
+ environment: getEnvironment(),
337
+ url: getUrl(),
338
+ browser: getBrowser()
339
+ });
340
+ }
341
+ } else {
342
+ send({
343
+ type: "SDK_INITIALIZED",
344
+ apiKey: _apiKey,
345
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
346
+ environment: getEnvironment(),
347
+ url: getUrl(),
348
+ browser: getBrowser()
375
349
  });
376
- return originalSend.apply(this, arguments);
377
- };
378
- }
379
- logNetworkError(url, status, statusText, method) {
380
- let errorType = `API ${status} Error`;
381
- let severity = "medium";
382
- if (status === 400)
383
- errorType = "API 400 Bad Request";
384
- else if (status === 401) {
385
- errorType = "API 401 Unauthorized";
386
- severity = "high";
387
- } else if (status === 403) {
388
- errorType = "API 403 Forbidden";
389
- severity = "high";
390
- } else if (status === 404)
391
- errorType = "API 404 Not Found";
392
- else if (status === 500) {
393
- errorType = "API 500 Internal Server Error";
394
- severity = "high";
395
- } else if (status === 503) {
396
- errorType = "API 503 Service Unavailable";
397
- severity = "high";
398
- }
399
- const payload = {
400
- apiKey: this.config?.apiKey || "",
401
- projectId: this.config?.projectId || "proj-sandbox",
402
- projectName: this.config?.projectName || "SaaS App",
403
- errorType,
404
- errorMessage: `HTTP API failed with code ${status}: ${method} ${url}`,
405
- errorStack: `Network Request Header Context: [Method: ${method}] Url: ${url} Response Description: ${statusText || "Dev server returned error."}`,
406
- framework: this.config?.framework || "React/Next.js Client",
407
- user_email: this.config?.userEmail || "anonymous",
408
- severity,
409
- status: "open"
410
- };
411
- this.sendCrashReport(payload);
412
- }
413
- logNetworkFailure(url, error, method) {
414
- const errorMsg = String(error.message || error || "");
415
- let errorType = "Fetch failed error";
416
- let severity = "high";
417
- if (errorMsg.includes("timeout") || errorMsg.includes("abort")) {
418
- errorType = "Request timeout error";
419
- severity = "medium";
420
- } else if (errorMsg.includes("CORS") || errorMsg.includes("origin") || errorMsg.includes("Access-Control")) {
421
- errorType = "CORS error";
422
- }
423
- const payload = {
424
- apiKey: this.config?.apiKey || "",
425
- projectId: this.config?.projectId || "proj-sandbox",
426
- projectName: this.config?.projectName || "SaaS App",
427
- errorType,
428
- errorMessage: `Failed to complete HTTP request: [${method}] ${url}`,
429
- errorStack: `Network crash context: ${errorMsg}
430
- Connection status: Failed to resolve.`,
431
- framework: this.config?.framework || "React/Next.js Client",
432
- user_email: this.config?.userEmail || "anonymous",
433
- severity,
434
- status: "open"
435
- };
436
- this.sendCrashReport(payload);
437
- }
438
- /**
439
- * Helper to safely format raw objects / strings into structured Errors
440
- */
441
- normalizeError(err) {
442
- if (err instanceof Error) {
443
- return {
444
- name: err.name,
445
- message: err.message,
446
- stack: err.stack
447
- };
448
- }
449
- if (typeof err === "string") {
450
- return {
451
- name: "Error",
452
- message: err,
453
- stack: new Error(err).stack
454
- };
455
350
  }
456
- if (err && typeof err === "object") {
457
- return {
458
- name: err.name || err.code || "Error",
459
- message: err.message || err.reason || JSON.stringify(err),
460
- stack: err.stack || err.traceback || new Error(err.message).stack
461
- };
351
+ if (isBrowser) {
352
+ activateBrowserListeners();
353
+ } else if (isNode) {
354
+ activateServerListeners();
462
355
  }
463
- return {
464
- name: "Error",
465
- message: "An unhandled execution trace slipped past standard boundaries.",
466
- stack: new Error().stack
356
+ },
357
+ capture(error) {
358
+ if (!_apiKey)
359
+ return;
360
+ send(buildErrorPayload(error, "manual"));
361
+ },
362
+ errorHandler() {
363
+ return function(err, _req, _res, next) {
364
+ send(buildErrorPayload(err, "express"));
365
+ next(err);
467
366
  };
468
367
  }
469
- /**
470
- * Comprehensive classification rules checking substring and classifications
471
- */
472
- classifyError(error, context) {
473
- const msg = String(error.message || error || "").toLowerCase();
474
- const name = String(error.name || "").toLowerCase();
475
- if (name.includes("quotaexceeded") || msg.includes("quota exceeded") || msg.includes("localstorage") || msg.includes("sessionstorage") || msg.includes("indexeddb")) {
476
- return { errorType: "localStorage quota exceeded", severity: "medium" };
477
- }
478
- if (msg.includes("hydration") || msg.includes("does not match server") || msg.includes("text content did not match")) {
479
- return { errorType: "React hydration error", severity: "high" };
480
- }
481
- if (msg.includes("invalid hook call") || msg.includes("rules of hooks")) {
482
- return { errorType: "Invalid hook call error", severity: "critical" };
483
- }
484
- if (msg.includes("failed prop type") || msg.includes("invalid prop")) {
485
- return { errorType: "Props type error", severity: "low" };
486
- }
487
- if (msg.includes("render") || msg.includes("react error boundary") || msg.includes("component render")) {
488
- return { errorType: "Component render error", severity: "critical" };
489
- }
490
- if (msg.includes("route not found") || msg.includes("cannot find route") || msg.includes("404 route")) {
491
- return { errorType: "Route not found error", severity: "medium" };
492
- }
493
- if (msg.includes("failed to fetch dynamically imported") || msg.includes("dynamic import")) {
494
- return { errorType: "Dynamic import error", severity: "high" };
495
- }
496
- if (msg.includes("suspense") || msg.includes("fallback")) {
497
- return { errorType: "Suspense boundary error", severity: "medium" };
498
- }
499
- if (name === "typeerror" || msg.startsWith("typeerror")) {
500
- return { errorType: "TypeError", severity: "high" };
501
- }
502
- if (name === "referenceerror" || msg.startsWith("referenceerror")) {
503
- return { errorType: "ReferenceError", severity: "critical" };
504
- }
505
- if (name === "rangeerror" || msg.startsWith("rangeerror")) {
506
- if (msg.includes("maximum call stack") || msg.includes("stack overflow")) {
507
- return { errorType: "Stack overflow error", severity: "critical" };
508
- }
509
- return { errorType: "RangeError", severity: "high" };
510
- }
511
- if (name === "syntaxerror" || msg.startsWith("syntaxerror")) {
512
- return { errorType: "SyntaxError", severity: "high" };
513
- }
514
- if (name === "evalerror") {
515
- return { errorType: "EvalError", severity: "medium" };
516
- }
517
- if (name === "urierror") {
518
- return { errorType: "URIError", severity: "medium" };
519
- }
520
- if (msg.includes("stripe") && (msg.includes("key") || msg.includes("init") || msg.includes("key is required") || msg.includes("is not defined"))) {
521
- return { errorType: "Stripe initialization error", severity: "critical" };
522
- }
523
- if (msg.includes("stripe") && (msg.includes("payment") || msg.includes("processing") || msg.includes("charge"))) {
524
- return { errorType: "Payment processing error", severity: "critical" };
525
- }
526
- if (msg.includes("card declined") || msg.includes("card_declined") || msg.includes("declined")) {
527
- return { errorType: "Card declined error", severity: "high" };
528
- }
529
- if (msg.includes("checkout session") || msg.includes("create checkout")) {
530
- return { errorType: "Checkout session error", severity: "high" };
531
- }
532
- if (msg.includes("refund failed") || msg.includes("refund_failed")) {
533
- return { errorType: "Refund failed error", severity: "high" };
534
- }
535
- if (msg.includes("supabase query") || msg.includes("postgresterror")) {
536
- return { errorType: "Supabase query error", severity: "critical" };
537
- }
538
- if (msg.includes("unique constraint") || msg.includes("duplicate key")) {
539
- return { errorType: "Unique constraint error", severity: "high" };
540
- }
541
- if (msg.includes("foreign key")) {
542
- return { errorType: "Foreign key error", severity: "high" };
543
- }
544
- if (msg.includes("transaction failed") || msg.includes("rollback")) {
545
- return { errorType: "Transaction failed error", severity: "critical" };
546
- }
547
- if (msg.includes("connection lost") || msg.includes("db connection") || msg.includes("connection refused") || msg.includes("econnrefused")) {
548
- return { errorType: "Connection lost error", severity: "critical" };
549
- }
550
- if (msg.includes("query timeout") || msg.includes("statement timeout")) {
551
- return { errorType: "Query timeout error", severity: "high" };
552
- }
553
- if (msg.includes("jwt expired") || msg.includes("token expired") || msg.includes("jsonwebtokenexpired")) {
554
- return { errorType: "JWT expired error", severity: "high" };
555
- }
556
- if (msg.includes("jwt verification") || msg.includes("invalid signature") || msg.includes("jwt malformed")) {
557
- return { errorType: "JWT verification error", severity: "high" };
558
- }
559
- if (msg.includes("firebase-admin") || msg.includes("firebase admin")) {
560
- return { errorType: "Firebase admin error", severity: "critical" };
561
- }
562
- if (msg.includes("session creation") || msg.includes("create session")) {
563
- return { errorType: "Session creation error", severity: "high" };
564
- }
565
- if (msg.includes("password hash") || msg.includes("bcrypt") || msg.includes("argon2")) {
566
- return { errorType: "Password hash error", severity: "critical" };
567
- }
568
- if (msg.includes("auth/id-token-expired") || msg.includes("id token expired")) {
569
- return { errorType: "Token expired error", severity: "high" };
570
- }
571
- if (msg.includes("invalid-credential") || msg.includes("auth/invalid-credential") || msg.includes("invalid token")) {
572
- return { errorType: "Invalid token error", severity: "high" };
573
- }
574
- if (msg.includes("session ended") || msg.includes("session expired")) {
575
- return { errorType: "Session ended error", severity: "medium" };
576
- }
577
- if (msg.includes("oauth callback") || msg.includes("oauth error")) {
578
- return { errorType: "OAuth callback error", severity: "high" };
579
- }
580
- if (msg.includes("login failed") || msg.includes("invalid credentials")) {
581
- return { errorType: "Login failed error", severity: "medium" };
582
- }
583
- if (msg.includes("unauthorized") || msg.includes("permission denied") || msg.includes("forbidden") || msg.includes("unauthorized access") || msg.includes("permission_denied")) {
584
- return { errorType: "Unauthorized access error", severity: "high" };
585
- }
586
- if (msg.includes("cron job") || msg.includes("cron_failed") || msg.includes("cron failed")) {
587
- return { errorType: "Cron job failed", severity: "high" };
588
- }
589
- if (msg.includes("queue processing") || msg.includes("bullmq") || msg.includes("redis queue") || msg.includes("celery error")) {
590
- return { errorType: "Queue processing error", severity: "high" };
591
- }
592
- if (msg.includes("webhook delivery") || msg.includes("webhook_failed") || msg.includes("webhook failed")) {
593
- return { errorType: "Webhook delivery failed", severity: "high" };
594
- }
595
- if (msg.includes("retry limit exceeded") || msg.includes("max retries")) {
596
- return { errorType: "Retry limit exceeded", severity: "high" };
597
- }
598
- if (msg.includes("out of memory") || msg.includes("oom") || msg.includes("heap limit") || msg.includes("heap out of memory")) {
599
- return { errorType: "Out of memory error", severity: "critical" };
600
- }
601
- if (msg.includes("cannot find module") || msg.includes("module_not_found") || msg.includes("module not found")) {
602
- return { errorType: "Module not found error", severity: "critical" };
603
- }
604
- if (msg.includes("process crash") || msg.includes("sigterm") || msg.includes("sigint") || msg.includes("process.exit")) {
605
- return { errorType: "Process crash error", severity: "critical" };
606
- }
607
- if (context === "express" || msg.includes("route handler") || msg.includes("api router")) {
608
- return { errorType: "Route handler error", severity: "high" };
609
- }
610
- if (msg.includes("middleware")) {
611
- return { errorType: "Middleware error", severity: "high" };
612
- }
613
- if (msg.includes("validation error") || msg.includes("zoderror") || msg.includes("joi validation")) {
614
- return { errorType: "Request validation error", severity: "medium" };
615
- }
616
- if (msg.includes("body parser") || msg.includes("multer") || msg.includes("multipart") || msg.includes("body-parser")) {
617
- return { errorType: "Body parser error", severity: "high" };
618
- }
619
- if (msg.includes("too many requests") || msg.includes("rate limit") || msg.includes("429")) {
620
- return { errorType: "Rate limit error", severity: "high" };
621
- }
622
- if (msg.includes("file upload") || msg.includes("upload failed") || msg.includes("cloudinary") || msg.includes("s3 upload") || msg.includes("multipart upload")) {
623
- return { errorType: "File upload failed", severity: "high" };
624
- }
625
- if (msg.includes("file size exceeded") || msg.includes("payload too large") || msg.includes("size validation")) {
626
- return { errorType: "File size exceeded", severity: "medium" };
627
- }
628
- if (msg.includes("invalid file type") || msg.includes("mime type mismatch") || msg.includes("file format")) {
629
- return { errorType: "Invalid file type", severity: "medium" };
630
- }
631
- if (msg.includes("storage quota exceeded") || msg.includes("bucket quota") || msg.includes("exhausted quota")) {
632
- return { errorType: "Storage quota exceeded", severity: "high" };
633
- }
634
- if (msg.includes("cdn ") || msg.includes("upload to cdn") || msg.includes("cdn distribution")) {
635
- return { errorType: "CDN upload failed", severity: "high" };
636
- }
637
- if (msg.includes("email sending failed") || msg.includes("sendgrid") || msg.includes("nodemailer") || msg.includes("resend")) {
638
- return { errorType: "Email sending failed", severity: "high" };
639
- }
640
- if (msg.includes("smtp connection") || msg.includes("smtp error") || msg.includes("mail connection")) {
641
- return { errorType: "SMTP connection error", severity: "high" };
642
- }
643
- if (msg.includes("template rendering") || msg.includes("mjml") || msg.includes("pug render")) {
644
- return { errorType: "Template rendering error", severity: "medium" };
645
- }
646
- if (msg.includes("onesignal") || msg.includes("push notification") || msg.includes("fcm payload")) {
647
- return { errorType: "OneSignal API error", severity: "high" };
648
- }
649
- if (msg.includes("cors") || msg.includes("cross-origin") || msg.includes("preflight") || msg.includes("access-control-allow")) {
650
- return { errorType: "CORS error", severity: "high" };
651
- }
652
- if (msg.includes("fetch failed") || msg.includes("failed to fetch")) {
653
- return { errorType: "Fetch failed error", severity: "high" };
654
- }
655
- if (msg.includes("timeout") || msg.includes("aborted") || msg.includes("timed out") || msg.includes("etimedout")) {
656
- return { errorType: "Request timeout error", severity: "medium" };
657
- }
658
- if (msg.includes("websocket connection") || msg.includes("ws connection failed") || msg.includes("ws://") || msg.includes("wss://")) {
659
- return { errorType: "WebSocket connection error", severity: "high" };
660
- }
661
- if (msg.includes("websocket closed") || msg.includes("websocket disconnected") || msg.includes("ws.close")) {
662
- return { errorType: "WebSocket disconnect error", severity: "medium" };
663
- }
664
- if (context === "unhandledrejection") {
665
- return { errorType: "Unhandled promise rejection", severity: "medium" };
666
- }
667
- if (msg.includes("async") && msg.includes("await")) {
668
- return { errorType: "Async await failure", severity: "high" };
669
- }
670
- if (msg.includes("promise chain") || msg.includes("promise.all") || msg.includes("promise.race")) {
671
- return { errorType: "Promise chain error", severity: "high" };
672
- }
673
- if (msg.includes("promise timed out") || msg.includes("promise timeout")) {
674
- return { errorType: "Promise timeout error", severity: "medium" };
675
- }
676
- if (context === "uncaughtexception") {
677
- return { errorType: "Uncaught exception", severity: "high" };
678
- }
679
- return { errorType: "Uncaught exception", severity: "medium" };
680
- }
681
368
  };
682
- var Reportli = new ReportliTracker();
683
369
  var src_default = Reportli;
684
370
  // Annotate the CommonJS export names for ESM import in node:
685
371
  0 && (module.exports = {