aissue 0.0.0-stage → 2.0.0

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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +390 -2
  3. package/dist/cjs/browser.d.ts +16 -0
  4. package/dist/cjs/browser.js +80 -0
  5. package/dist/cjs/core/breadcrumbs.d.ts +48 -0
  6. package/dist/cjs/core/breadcrumbs.js +313 -0
  7. package/dist/cjs/core/client.d.ts +54 -0
  8. package/dist/cjs/core/client.js +293 -0
  9. package/dist/cjs/core/env.d.ts +19 -0
  10. package/dist/cjs/core/env.js +71 -0
  11. package/dist/cjs/core/event.d.ts +35 -0
  12. package/dist/cjs/core/event.js +187 -0
  13. package/dist/cjs/core/hub.d.ts +20 -0
  14. package/dist/cjs/core/hub.js +21 -0
  15. package/dist/cjs/core/instrument-browser.d.ts +16 -0
  16. package/dist/cjs/core/instrument-browser.js +208 -0
  17. package/dist/cjs/core/instrument-node.d.ts +5 -0
  18. package/dist/cjs/core/instrument-node.js +250 -0
  19. package/dist/cjs/core/instrument.d.ts +12 -0
  20. package/dist/cjs/core/instrument.js +137 -0
  21. package/dist/cjs/core/privacy.d.ts +25 -0
  22. package/dist/cjs/core/privacy.js +269 -0
  23. package/dist/cjs/core/stack.d.ts +13 -0
  24. package/dist/cjs/core/stack.js +147 -0
  25. package/dist/cjs/core/transport.d.ts +31 -0
  26. package/dist/cjs/core/transport.js +154 -0
  27. package/dist/cjs/core/types.d.ts +149 -0
  28. package/dist/cjs/core/types.js +2 -0
  29. package/dist/cjs/core/version.d.ts +2 -0
  30. package/dist/cjs/core/version.js +6 -0
  31. package/dist/cjs/index.d.ts +27 -0
  32. package/dist/cjs/index.js +83 -0
  33. package/dist/cjs/nextjs/client.d.ts +10 -0
  34. package/dist/cjs/nextjs/client.js +99 -0
  35. package/dist/cjs/nextjs/index.d.ts +31 -0
  36. package/dist/cjs/nextjs/index.js +99 -0
  37. package/dist/cjs/node.d.ts +48 -0
  38. package/dist/cjs/node.js +223 -0
  39. package/dist/cjs/package.json +3 -0
  40. package/dist/cjs/react.d.ts +40 -0
  41. package/dist/cjs/react.js +90 -0
  42. package/dist/esm/browser.d.ts +16 -0
  43. package/dist/esm/browser.js +71 -0
  44. package/dist/esm/cli.d.ts +2 -0
  45. package/dist/esm/cli.js +386 -0
  46. package/dist/esm/core/breadcrumbs.d.ts +48 -0
  47. package/dist/esm/core/breadcrumbs.js +296 -0
  48. package/dist/esm/core/client.d.ts +54 -0
  49. package/dist/esm/core/client.js +285 -0
  50. package/dist/esm/core/env.d.ts +19 -0
  51. package/dist/esm/core/env.js +62 -0
  52. package/dist/esm/core/event.d.ts +35 -0
  53. package/dist/esm/core/event.js +179 -0
  54. package/dist/esm/core/hub.d.ts +20 -0
  55. package/dist/esm/core/hub.js +17 -0
  56. package/dist/esm/core/instrument-browser.d.ts +16 -0
  57. package/dist/esm/core/instrument-browser.js +203 -0
  58. package/dist/esm/core/instrument-node.d.ts +5 -0
  59. package/dist/esm/core/instrument-node.js +214 -0
  60. package/dist/esm/core/instrument.d.ts +12 -0
  61. package/dist/esm/core/instrument.js +132 -0
  62. package/dist/esm/core/privacy.d.ts +25 -0
  63. package/dist/esm/core/privacy.js +257 -0
  64. package/dist/esm/core/stack.d.ts +13 -0
  65. package/dist/esm/core/stack.js +140 -0
  66. package/dist/esm/core/transport.d.ts +31 -0
  67. package/dist/esm/core/transport.js +149 -0
  68. package/dist/esm/core/types.d.ts +149 -0
  69. package/dist/esm/core/types.js +1 -0
  70. package/dist/esm/core/version.d.ts +2 -0
  71. package/dist/esm/core/version.js +3 -0
  72. package/dist/esm/index.d.ts +27 -0
  73. package/dist/esm/index.js +72 -0
  74. package/dist/esm/nextjs/client.d.ts +10 -0
  75. package/dist/esm/nextjs/client.js +90 -0
  76. package/dist/esm/nextjs/index.d.ts +31 -0
  77. package/dist/esm/nextjs/index.js +88 -0
  78. package/dist/esm/node.d.ts +48 -0
  79. package/dist/esm/node.js +210 -0
  80. package/dist/esm/react.d.ts +40 -0
  81. package/dist/esm/react.js +47 -0
  82. package/package.json +141 -4
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_BREADCRUMB_MESSAGE = exports.MAX_BREADCRUMBS = exports.DEFAULT_MAX_BREADCRUMBS = void 0;
4
+ exports.clip = clip;
5
+ exports.describeValue = describeValue;
6
+ exports.normalizeBreadcrumb = normalizeBreadcrumb;
7
+ exports.currentBuffer = currentBuffer;
8
+ exports.breadcrumbsActive = breadcrumbsActive;
9
+ exports.recordBreadcrumb = recordBreadcrumb;
10
+ exports.snapshotBreadcrumbs = snapshotBreadcrumbs;
11
+ exports.clearCurrentBreadcrumbs = clearCurrentBreadcrumbs;
12
+ exports.runWithBreadcrumbScope = runWithBreadcrumbScope;
13
+ exports.isWrapped = isWrapped;
14
+ exports.markWrapped = markWrapped;
15
+ exports.wrapMethod = wrapMethod;
16
+ exports.isAIssueUrl = isAIssueUrl;
17
+ exports.levelForStatus = levelForStatus;
18
+ const hub_js_1 = require("./hub.js");
19
+ const privacy_js_1 = require("./privacy.js");
20
+ exports.DEFAULT_MAX_BREADCRUMBS = 50;
21
+ /** Protocol limit: at most 100 breadcrumbs per event. */
22
+ exports.MAX_BREADCRUMBS = 100;
23
+ exports.MAX_BREADCRUMB_MESSAGE = 1000;
24
+ const MAX_DATA_KEYS = 20;
25
+ const MAX_DATA_VALUE = 1000;
26
+ const MAX_CATEGORY = 100;
27
+ const TYPES = ['default', 'http', 'navigation', 'ui', 'log', 'query'];
28
+ const LEVELS = {
29
+ debug: 'debug',
30
+ trace: 'debug',
31
+ info: 'info',
32
+ log: 'info',
33
+ warning: 'warning',
34
+ warn: 'warning',
35
+ error: 'error',
36
+ fatal: 'error',
37
+ critical: 'error',
38
+ };
39
+ /** Cut to `max` characters, ellipsis included. */
40
+ function clip(value, max) {
41
+ return value.length > max ? value.slice(0, Math.max(0, max - 3)) + '...' : value;
42
+ }
43
+ /** Short, safe text for any value (used for console arguments and nested data values). */
44
+ function describeValue(value, max = 4000) {
45
+ try {
46
+ if (typeof value === 'string')
47
+ return value.length > max ? value.slice(0, max) : value;
48
+ if (value === undefined)
49
+ return 'undefined';
50
+ if (value === null)
51
+ return 'null';
52
+ if (typeof value === 'function')
53
+ return '[Function]';
54
+ if (typeof value === 'symbol' || typeof value === 'bigint')
55
+ return String(value);
56
+ if (typeof value !== 'object')
57
+ return String(value);
58
+ const v = value;
59
+ if (value instanceof Error || (typeof v.message === 'string' && typeof v.name === 'string')) {
60
+ return `${String(v.name || 'Error')}: ${String(v.message)}`;
61
+ }
62
+ const json = JSON.stringify((0, privacy_js_1.scrub)(value));
63
+ return json === undefined ? String(value) : json.length > max ? json.slice(0, max) : json;
64
+ }
65
+ catch {
66
+ return '[unserializable]';
67
+ }
68
+ }
69
+ function toTimestamp(input) {
70
+ try {
71
+ let ms;
72
+ if (input instanceof Date)
73
+ ms = input.getTime();
74
+ else if (typeof input === 'number')
75
+ ms = input < 1e11 ? input * 1000 : input; // seconds or milliseconds
76
+ else if (typeof input === 'string')
77
+ ms = Date.parse(input);
78
+ else
79
+ ms = Date.now();
80
+ if (!Number.isFinite(ms))
81
+ ms = Date.now();
82
+ return new Date(ms).toISOString();
83
+ }
84
+ catch {
85
+ return new Date().toISOString();
86
+ }
87
+ }
88
+ function dataValue(value) {
89
+ if (value === undefined || value === null)
90
+ return undefined;
91
+ switch (typeof value) {
92
+ case 'boolean':
93
+ return value;
94
+ case 'number':
95
+ return Number.isFinite(value) ? value : String(value);
96
+ case 'string':
97
+ return clip((0, privacy_js_1.scrubText)(value), MAX_DATA_VALUE);
98
+ case 'function':
99
+ case 'symbol':
100
+ return undefined;
101
+ default:
102
+ return clip((0, privacy_js_1.scrubText)(describeValue(value)), MAX_DATA_VALUE);
103
+ }
104
+ }
105
+ /**
106
+ * Turn user or instrumentation input into a protocol breadcrumb: valid type / level, ISO timestamp,
107
+ * message <= 1000 chars, flat data (<= 20 keys). Sensitive keys and secrets / emails in strings are filtered.
108
+ */
109
+ function normalizeBreadcrumb(input) {
110
+ if (!input || typeof input !== 'object')
111
+ return null;
112
+ const rawType = typeof input.type === 'string' ? input.type.toLowerCase() : '';
113
+ const type = TYPES.includes(rawType) ? rawType : 'default';
114
+ const level = (typeof input.level === 'string' && LEVELS[input.level.toLowerCase()]) || 'info';
115
+ const rawCategory = typeof input.category === 'string' ? input.category.trim() : '';
116
+ const category = clip((0, privacy_js_1.scrubText)(rawCategory), MAX_CATEGORY) || (type === 'default' ? 'manual' : type);
117
+ const message = input.message === undefined || input.message === null
118
+ ? ''
119
+ : clip((0, privacy_js_1.scrubText)(describeValue(input.message)), exports.MAX_BREADCRUMB_MESSAGE);
120
+ const data = {};
121
+ if (input.data && typeof input.data === 'object' && !Array.isArray(input.data)) {
122
+ let count = 0;
123
+ for (const key of Object.keys(input.data)) {
124
+ if (count >= MAX_DATA_KEYS)
125
+ break;
126
+ const value = (0, privacy_js_1.isSensitiveKey)(key) ? privacy_js_1.FILTERED : dataValue(input.data[key]);
127
+ if (value === undefined)
128
+ continue;
129
+ data[clip(key, MAX_CATEGORY)] = value;
130
+ count++;
131
+ }
132
+ }
133
+ return { timestamp: toTimestamp(input.timestamp), type, category, level, message, data };
134
+ }
135
+ function storage() {
136
+ return (0, hub_js_1.getHub)().breadcrumbStorage;
137
+ }
138
+ /** The buffer breadcrumbs go to right now: the current request's (Node) or the global one. */
139
+ function currentBuffer() {
140
+ const hub = (0, hub_js_1.getHub)();
141
+ try {
142
+ const store = hub.breadcrumbStorage?.getStore();
143
+ if (Array.isArray(store))
144
+ return store;
145
+ }
146
+ catch {
147
+ // fall back to the global buffer
148
+ }
149
+ if (!Array.isArray(hub.breadcrumbs))
150
+ hub.breadcrumbs = [];
151
+ return hub.breadcrumbs;
152
+ }
153
+ /** True when a client is enabled and keeps breadcrumbs (optionally: and this automatic source is on). */
154
+ function breadcrumbsActive(kind) {
155
+ try {
156
+ const client = (0, hub_js_1.getHub)().client;
157
+ if (!client || !client.enabled || client.config.maxBreadcrumbs <= 0)
158
+ return false;
159
+ if (!kind)
160
+ return true;
161
+ const auto = client.config.autoBreadcrumbs;
162
+ return auto !== false && !(typeof auto === 'object' && auto !== null && auto[kind] === false);
163
+ }
164
+ catch {
165
+ return false;
166
+ }
167
+ }
168
+ let recording = false;
169
+ /**
170
+ * Store a breadcrumb in `buffer` (default: the current one). Runs beforeBreadcrumb.
171
+ * Never throws; ignored when the SDK is disabled or while another breadcrumb is being recorded
172
+ * (so a console.log inside beforeBreadcrumb cannot loop).
173
+ */
174
+ function recordBreadcrumb(input, buffer) {
175
+ if (recording)
176
+ return;
177
+ recording = true;
178
+ try {
179
+ const client = (0, hub_js_1.getHub)().client;
180
+ if (!client || !client.enabled)
181
+ return;
182
+ const max = client.config.maxBreadcrumbs;
183
+ if (max <= 0)
184
+ return;
185
+ let crumb = normalizeBreadcrumb(input);
186
+ if (!crumb)
187
+ return;
188
+ const before = client.config.beforeBreadcrumb;
189
+ if (before) {
190
+ let result;
191
+ try {
192
+ result = before(crumb);
193
+ }
194
+ catch {
195
+ return; // a throwing beforeBreadcrumb drops the breadcrumb
196
+ }
197
+ if (!result)
198
+ return;
199
+ crumb = normalizeBreadcrumb(result); // re-validate whatever the hook returned
200
+ if (!crumb)
201
+ return;
202
+ }
203
+ const target = buffer || currentBuffer();
204
+ target.push(crumb);
205
+ if (target.length > max)
206
+ target.splice(0, target.length - max);
207
+ }
208
+ catch {
209
+ // never throw into the host app
210
+ }
211
+ finally {
212
+ recording = false;
213
+ }
214
+ }
215
+ /** Copy of the current breadcrumbs (oldest first) for an event. */
216
+ function snapshotBreadcrumbs() {
217
+ try {
218
+ const client = (0, hub_js_1.getHub)().client;
219
+ const max = client ? Math.min(client.config.maxBreadcrumbs, exports.MAX_BREADCRUMBS) : exports.MAX_BREADCRUMBS;
220
+ if (max <= 0)
221
+ return [];
222
+ return currentBuffer()
223
+ .slice(-max)
224
+ .map((c) => ({ ...c, data: { ...c.data } }));
225
+ }
226
+ catch {
227
+ return [];
228
+ }
229
+ }
230
+ /** Empty the current buffer (the current request's in Node, otherwise the global one). */
231
+ function clearCurrentBreadcrumbs() {
232
+ try {
233
+ currentBuffer().length = 0;
234
+ }
235
+ catch {
236
+ // ignore
237
+ }
238
+ }
239
+ /** Run `fn` with its own, empty breadcrumb buffer (Node AsyncLocalStorage); plain call elsewhere. */
240
+ function runWithBreadcrumbScope(fn) {
241
+ const s = storage();
242
+ return s ? s.run([], fn) : fn();
243
+ }
244
+ // --- wrapping helpers shared by the instrumentation -------------------------------------------------
245
+ const WRAPPED = Symbol.for('aissue.wrapped');
246
+ function isWrapped(fn) {
247
+ return typeof fn === 'function' && !!fn[WRAPPED];
248
+ }
249
+ /**
250
+ * Mark `wrapper` as ours and copy the original's own properties (e.g. Next.js' `__nextPatched` on fetch)
251
+ * so code that inspects the function keeps working.
252
+ */
253
+ function markWrapped(wrapper, original) {
254
+ try {
255
+ for (const key of Reflect.ownKeys(original)) {
256
+ if (key === 'length' || key === 'name' || key === 'prototype' || key === 'caller' || key === 'arguments')
257
+ continue;
258
+ if (Object.prototype.hasOwnProperty.call(wrapper, key))
259
+ continue;
260
+ const desc = Object.getOwnPropertyDescriptor(original, key);
261
+ if (desc)
262
+ Object.defineProperty(wrapper, key, desc);
263
+ }
264
+ }
265
+ catch {
266
+ // ignore
267
+ }
268
+ try {
269
+ Object.defineProperty(wrapper, WRAPPED, { value: original, configurable: true });
270
+ Object.defineProperty(wrapper, 'name', { value: original.name, configurable: true });
271
+ }
272
+ catch {
273
+ // ignore
274
+ }
275
+ return wrapper;
276
+ }
277
+ /** Replace obj[name] with makeWrapper(original) unless it is already our wrapper. Never throws. */
278
+ function wrapMethod(obj, name, makeWrapper) {
279
+ try {
280
+ if (!obj || (typeof obj !== 'object' && typeof obj !== 'function'))
281
+ return false;
282
+ const target = obj;
283
+ const original = target[name];
284
+ if (typeof original !== 'function' || isWrapped(original))
285
+ return false;
286
+ target[name] = markWrapped(makeWrapper(original), original);
287
+ return true;
288
+ }
289
+ catch {
290
+ return false;
291
+ }
292
+ }
293
+ /** True for URLs that point at the AIssue host itself (the SDK's own requests). */
294
+ function isAIssueUrl(url) {
295
+ try {
296
+ const base = (0, hub_js_1.getHub)().client?.config.baseUrl;
297
+ if (!base || !url)
298
+ return false;
299
+ return url === base || url.startsWith(base + '/') || url.startsWith(base + '?');
300
+ }
301
+ catch {
302
+ return false;
303
+ }
304
+ }
305
+ function levelForStatus(status) {
306
+ if (!status)
307
+ return 'error';
308
+ if (status >= 500)
309
+ return 'error';
310
+ if (status >= 400)
311
+ return 'warning';
312
+ return 'info';
313
+ }
@@ -0,0 +1,54 @@
1
+ import { type BuildExtras } from './event.js';
2
+ import { Transport, type TransportMode } from './transport.js';
3
+ import type { AIssueOptions, CaptureContext, Platform } from './types.js';
4
+ export declare const DEDUPE_WINDOW_MS = 5000;
5
+ /** Browser noise that is never worth an alert. */
6
+ export declare const BROWSER_DEFAULT_IGNORE: Array<string | RegExp>;
7
+ export interface SetupSettings {
8
+ /** 'browser': key in ?api_key=, text/plain, keepalive, page defaults. 'server': X-API-Key header. */
9
+ runtime?: TransportMode;
10
+ platform?: Platform;
11
+ }
12
+ export interface ResolvedConfig {
13
+ apiKey?: string;
14
+ baseUrl?: string;
15
+ release?: string;
16
+ environment?: string;
17
+ enabled: boolean;
18
+ debug: boolean;
19
+ runtime: TransportMode;
20
+ platform: Platform;
21
+ ignoreErrors: Array<string | RegExp>;
22
+ maxEventsPerMinute: number;
23
+ beforeSend?: AIssueOptions['beforeSend'];
24
+ maxBreadcrumbs: number;
25
+ beforeBreadcrumb?: AIssueOptions['beforeBreadcrumb'];
26
+ autoBreadcrumbs: AIssueOptions['autoBreadcrumbs'];
27
+ }
28
+ /** "https://<key>@host[:port]/<domain id>" -> { apiKey, baseUrl } */
29
+ export declare function parseDsn(dsn: string | undefined): {
30
+ apiKey: string;
31
+ baseUrl: string;
32
+ } | undefined;
33
+ export declare function resolveConfig(options?: AIssueOptions, settings?: SetupSettings): ResolvedConfig;
34
+ export declare class Client {
35
+ readonly config: ResolvedConfig;
36
+ readonly transport?: Transport;
37
+ private readonly sentAt;
38
+ private readonly recent;
39
+ private readonly captured;
40
+ constructor(config: ResolvedConfig);
41
+ get enabled(): boolean;
42
+ log(message: string): void;
43
+ private defaults;
44
+ private isIgnored;
45
+ private isDuplicate;
46
+ private takeRateLimitSlot;
47
+ /** Build, filter and send one event. Never throws. Returns true when the event was handed to fetch. */
48
+ capture(error: unknown, context?: CaptureContext, extras?: BuildExtras): boolean;
49
+ flush(timeoutMs?: number): Promise<boolean>;
50
+ }
51
+ /** Create the client and make it current. Used by every entry point's init(). */
52
+ export declare function setupClient(options?: AIssueOptions, settings?: SetupSettings): Client | undefined;
53
+ /** captureException with internal extras (used by the React boundary). */
54
+ export declare function captureWithExtras(error: unknown, context?: CaptureContext, extras?: BuildExtras): void;
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Client = exports.BROWSER_DEFAULT_IGNORE = exports.DEDUPE_WINDOW_MS = void 0;
4
+ exports.parseDsn = parseDsn;
5
+ exports.resolveConfig = resolveConfig;
6
+ exports.setupClient = setupClient;
7
+ exports.captureWithExtras = captureWithExtras;
8
+ const breadcrumbs_js_1 = require("./breadcrumbs.js");
9
+ const env_js_1 = require("./env.js");
10
+ const event_js_1 = require("./event.js");
11
+ const hub_js_1 = require("./hub.js");
12
+ const stack_js_1 = require("./stack.js");
13
+ const transport_js_1 = require("./transport.js");
14
+ exports.DEDUPE_WINDOW_MS = 5000;
15
+ const RATE_WINDOW_MS = 60000;
16
+ const DEFAULT_MAX_EVENTS_PER_MINUTE = 10;
17
+ /** Browser noise that is never worth an alert. */
18
+ exports.BROWSER_DEFAULT_IGNORE = [
19
+ 'ResizeObserver loop limit exceeded',
20
+ 'ResizeObserver loop completed with undelivered notifications',
21
+ /^Script error\.?$/,
22
+ ];
23
+ function log(debug, message) {
24
+ if (!debug)
25
+ return;
26
+ try {
27
+ console.log(`[aissue] ${message}`);
28
+ }
29
+ catch {
30
+ // ignore
31
+ }
32
+ }
33
+ function warn(message) {
34
+ try {
35
+ console.warn(`[aissue] ${message}`);
36
+ }
37
+ catch {
38
+ // ignore
39
+ }
40
+ }
41
+ /** "https://<key>@host[:port]/<domain id>" -> { apiKey, baseUrl } */
42
+ function parseDsn(dsn) {
43
+ if (!dsn)
44
+ return undefined;
45
+ try {
46
+ const url = new URL(dsn);
47
+ if (!url.username || !url.host || !/^https?:$/.test(url.protocol))
48
+ return undefined;
49
+ return { apiKey: decodeURIComponent(url.username), baseUrl: `${url.protocol}//${url.host}` };
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ function str(value) {
56
+ if (typeof value !== 'string')
57
+ return undefined;
58
+ const trimmed = value.trim();
59
+ return trimmed || undefined;
60
+ }
61
+ function resolveConfig(options = {}, settings = {}) {
62
+ const runtime = settings.runtime ?? ((0, env_js_1.isBrowser)() ? 'browser' : 'server');
63
+ // Environment variables are only read on servers; browser bundles get explicit options.
64
+ const env = runtime === 'server' ? env_js_1.readEnv : () => undefined;
65
+ const fromDsn = parseDsn(str(options.dsn));
66
+ let apiKey = str(options.apiKey) || fromDsn?.apiKey || env('AISSUE_API_KEY');
67
+ let baseUrl = str(options.baseUrl) || fromDsn?.baseUrl || env('AISSUE_BASE_URL');
68
+ if (!apiKey || !baseUrl) {
69
+ const envDsn = parseDsn(env('AISSUE_DSN'));
70
+ apiKey = apiKey || envDsn?.apiKey;
71
+ baseUrl = baseUrl || envDsn?.baseUrl;
72
+ }
73
+ const mode = (0, env_js_1.nodeEnv)();
74
+ const enabled = options.enabled ?? !(mode === 'development' || mode === 'test');
75
+ const platform = settings.platform ?? (runtime === 'browser' ? 'browser' : (0, env_js_1.isNode)() ? 'node' : 'javascript');
76
+ const max = options.maxEventsPerMinute;
77
+ const maxCrumbs = options.maxBreadcrumbs;
78
+ return {
79
+ apiKey,
80
+ baseUrl: baseUrl ? baseUrl.replace(/\/+$/, '') : undefined,
81
+ release: str(options.release) || (runtime === 'server' ? (0, env_js_1.detectRelease)() : undefined),
82
+ environment: str(options.environment) || env('AISSUE_ENVIRONMENT') || (runtime === 'server' ? mode : undefined),
83
+ enabled: !!enabled,
84
+ debug: !!options.debug,
85
+ runtime,
86
+ platform,
87
+ ignoreErrors: [
88
+ ...(runtime === 'browser' ? exports.BROWSER_DEFAULT_IGNORE : []),
89
+ ...(Array.isArray(options.ignoreErrors)
90
+ ? options.ignoreErrors.filter((p) => typeof p === 'string' || p instanceof RegExp)
91
+ : []),
92
+ ],
93
+ maxEventsPerMinute: typeof max === 'number' && max >= 0 ? max : DEFAULT_MAX_EVENTS_PER_MINUTE,
94
+ beforeSend: typeof options.beforeSend === 'function' ? options.beforeSend : undefined,
95
+ maxBreadcrumbs: typeof maxCrumbs === 'number' && Number.isFinite(maxCrumbs)
96
+ ? Math.min(breadcrumbs_js_1.MAX_BREADCRUMBS, Math.max(0, Math.floor(maxCrumbs)))
97
+ : breadcrumbs_js_1.DEFAULT_MAX_BREADCRUMBS,
98
+ beforeBreadcrumb: typeof options.beforeBreadcrumb === 'function' ? options.beforeBreadcrumb : undefined,
99
+ autoBreadcrumbs: options.autoBreadcrumbs === false || (options.autoBreadcrumbs && typeof options.autoBreadcrumbs === 'object')
100
+ ? options.autoBreadcrumbs
101
+ : true,
102
+ };
103
+ }
104
+ function matches(pattern, text) {
105
+ if (typeof pattern === 'string')
106
+ return pattern !== '' && text.includes(pattern);
107
+ try {
108
+ pattern.lastIndex = 0;
109
+ return pattern.test(text);
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ class Client {
116
+ constructor(config) {
117
+ this.config = config;
118
+ this.sentAt = [];
119
+ this.recent = new Map();
120
+ this.captured = new WeakSet();
121
+ if (config.enabled && config.apiKey && config.baseUrl) {
122
+ this.transport = new transport_js_1.Transport({
123
+ baseUrl: config.baseUrl,
124
+ apiKey: config.apiKey,
125
+ mode: config.runtime,
126
+ log: (m) => log(config.debug, m),
127
+ warn,
128
+ });
129
+ }
130
+ }
131
+ get enabled() {
132
+ return !!this.transport;
133
+ }
134
+ log(message) {
135
+ log(this.config.debug, message);
136
+ }
137
+ defaults() {
138
+ const { config } = this;
139
+ const defaults = {
140
+ platform: config.platform,
141
+ errorCode: config.runtime === 'browser' ? 0 : 500,
142
+ release: config.release,
143
+ environment: config.environment,
144
+ userId: (0, hub_js_1.getHub)().userId,
145
+ };
146
+ if (config.runtime === 'browser') {
147
+ try {
148
+ const g = globalThis;
149
+ if (g.location && typeof g.location.pathname === 'string')
150
+ defaults.path = g.location.pathname;
151
+ if (g.navigator && typeof g.navigator.userAgent === 'string') {
152
+ defaults.headers = { 'User-Agent': g.navigator.userAgent };
153
+ }
154
+ }
155
+ catch {
156
+ // ignore
157
+ }
158
+ }
159
+ return defaults;
160
+ }
161
+ isIgnored(event) {
162
+ const { type, message } = event.exception;
163
+ const full = `${type}: ${message}`;
164
+ for (const pattern of this.config.ignoreErrors) {
165
+ if (matches(pattern, message) || matches(pattern, full))
166
+ return true;
167
+ }
168
+ if (this.config.runtime === 'browser' && event.frames.length > 0) {
169
+ if (event.frames.every((f) => (0, stack_js_1.isExtensionUrl)(f.filename)))
170
+ return true;
171
+ }
172
+ return false;
173
+ }
174
+ isDuplicate(event, now) {
175
+ for (const [key, at] of this.recent) {
176
+ if (now - at >= exports.DEDUPE_WINDOW_MS)
177
+ this.recent.delete(key);
178
+ }
179
+ const top = event.frames[event.frames.length - 1];
180
+ const key = [
181
+ event.exception.type,
182
+ event.exception.message,
183
+ top ? `${top.filename}:${top.lineno ?? ''}:${top.colno ?? ''}` : '',
184
+ ].join('\u0000');
185
+ if (this.recent.has(key))
186
+ return true;
187
+ if (this.recent.size >= 100)
188
+ this.recent.clear();
189
+ this.recent.set(key, now);
190
+ return false;
191
+ }
192
+ takeRateLimitSlot(now) {
193
+ while (this.sentAt.length && now - this.sentAt[0] >= RATE_WINDOW_MS)
194
+ this.sentAt.shift();
195
+ if (this.sentAt.length >= this.config.maxEventsPerMinute)
196
+ return false;
197
+ this.sentAt.push(now);
198
+ return true;
199
+ }
200
+ /** Build, filter and send one event. Never throws. Returns true when the event was handed to fetch. */
201
+ capture(error, context, extras) {
202
+ try {
203
+ const transport = this.transport;
204
+ if (!transport)
205
+ return false;
206
+ if (error !== null && typeof error === 'object') {
207
+ if (this.captured.has(error)) {
208
+ this.log('error object already captured; skipping');
209
+ return false;
210
+ }
211
+ }
212
+ let event = (0, event_js_1.buildEvent)(error, context || {}, this.defaults(), extras);
213
+ if (this.isIgnored(event)) {
214
+ this.log(`ignored: ${event.exception.type}: ${event.exception.message}`);
215
+ return false;
216
+ }
217
+ const now = Date.now();
218
+ if (this.isDuplicate(event, now)) {
219
+ this.log('duplicate event within 5s; dropped');
220
+ return false;
221
+ }
222
+ if (error !== null && typeof error === 'object')
223
+ this.captured.add(error);
224
+ const breadcrumbs = (0, breadcrumbs_js_1.snapshotBreadcrumbs)();
225
+ if (breadcrumbs.length)
226
+ event.breadcrumbs = breadcrumbs;
227
+ if (this.config.beforeSend) {
228
+ try {
229
+ event = this.config.beforeSend(event);
230
+ }
231
+ catch {
232
+ warn('beforeSend threw; dropping the event');
233
+ return false;
234
+ }
235
+ if (!event) {
236
+ this.log('beforeSend dropped the event');
237
+ return false;
238
+ }
239
+ }
240
+ if (transport.isPaused(now)) {
241
+ this.log('paused after a 429 from the server; dropped');
242
+ return false;
243
+ }
244
+ if (!this.takeRateLimitSlot(now)) {
245
+ this.log(`more than ${this.config.maxEventsPerMinute} events this minute; dropped`);
246
+ return false;
247
+ }
248
+ const body = (0, event_js_1.serializeEvent)(event);
249
+ if (body === null) {
250
+ this.log('event over 256 KB even after trimming; dropped');
251
+ return false;
252
+ }
253
+ transport.send(body);
254
+ return true;
255
+ }
256
+ catch {
257
+ return false;
258
+ }
259
+ }
260
+ flush(timeoutMs) {
261
+ return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
262
+ }
263
+ }
264
+ exports.Client = Client;
265
+ /** Create the client and make it current. Used by every entry point's init(). */
266
+ function setupClient(options = {}, settings = {}) {
267
+ try {
268
+ const config = resolveConfig(options || {}, settings);
269
+ const client = new Client(config);
270
+ (0, hub_js_1.getHub)().client = client;
271
+ if (config.enabled && !client.enabled) {
272
+ warn('apiKey and baseUrl (or dsn) are required; the SDK is disabled.');
273
+ }
274
+ else {
275
+ client.log(client.enabled
276
+ ? `initialised (platform ${config.platform}, environment ${config.environment ?? '-'}, release ${config.release ?? '-'})`
277
+ : 'disabled (enabled: false, or NODE_ENV is development/test)');
278
+ }
279
+ return client;
280
+ }
281
+ catch {
282
+ return undefined;
283
+ }
284
+ }
285
+ /** captureException with internal extras (used by the React boundary). */
286
+ function captureWithExtras(error, context, extras) {
287
+ try {
288
+ (0, hub_js_1.getHub)().client?.capture(error, context, extras);
289
+ }
290
+ catch {
291
+ // never throw into the host app
292
+ }
293
+ }
@@ -0,0 +1,19 @@
1
+ /** Release env vars, first one set wins (ingestion protocol "Release detection"). */
2
+ export declare const RELEASE_ENV_VARS: readonly ["AISSUE_RELEASE", "VERCEL_GIT_COMMIT_SHA", "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", "RENDER_GIT_COMMIT", "RAILWAY_GIT_COMMIT_SHA", "HEROKU_SLUG_COMMIT", "SOURCE_VERSION", "CF_PAGES_COMMIT_SHA", "GITHUB_SHA", "COMMIT_SHA", "GIT_SHA", "GIT_COMMIT"];
3
+ type ProcessLike = {
4
+ env?: Record<string, string | undefined>;
5
+ versions?: Record<string, string | undefined>;
6
+ };
7
+ /** The global `process`, if any (looked up dynamically so bundlers and edge runtimes don't complain). */
8
+ export declare function getProcess(): ProcessLike | undefined;
9
+ /** Read a server-side environment variable (trimmed; undefined when empty). */
10
+ export declare function readEnv(name: string): string | undefined;
11
+ export declare function detectRelease(): string | undefined;
12
+ /**
13
+ * NODE_ENV. `process.env.NODE_ENV` is referenced literally so bundlers (webpack, Next.js, Vite)
14
+ * can inline it in browser builds; a missing `process` global is caught.
15
+ */
16
+ export declare function nodeEnv(): string | undefined;
17
+ export declare function isBrowser(): boolean;
18
+ export declare function isNode(): boolean;
19
+ export {};