aissue 0.0.0-stage → 2.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.
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,269 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EMAIL_PLACEHOLDER = exports.FILTERED = void 0;
4
+ exports.isSensitiveKey = isSensitiveKey;
5
+ exports.truncate = truncate;
6
+ exports.stripQuery = stripQuery;
7
+ exports.queryOf = queryOf;
8
+ exports.filterHeaders = filterHeaders;
9
+ exports.filterQuery = filterQuery;
10
+ exports.scrub = scrub;
11
+ exports.scrubText = scrubText;
12
+ exports.sanitizeUrl = sanitizeUrl;
13
+ exports.FILTERED = '[Filtered]';
14
+ /** Same rule as the Python SDK (sdks/python/aissue/client.py `_SENSITIVE_KEY_RE`). */
15
+ const SENSITIVE_KEY_RE = /passw(?:or)?d|passwd|pwd|secret|token|api[-_]?key|apikey|(?:private|access|secret|signing|encryption)[-_]?key|authoriz|session|cookie|csrf|credential|signature|credit[-_]?card|card[-_]?(?:number|num|no)|cvv|cvc|iban|ssn|^auth$|^cc$/i;
16
+ function isSensitiveKey(key) {
17
+ return typeof key === 'string' && SENSITIVE_KEY_RE.test(key);
18
+ }
19
+ /** Only these request headers are ever sent (lower-case name -> canonical name). */
20
+ const HEADER_ALLOWLIST = {
21
+ 'user-agent': 'User-Agent',
22
+ 'content-type': 'Content-Type',
23
+ 'content-length': 'Content-Length',
24
+ accept: 'Accept',
25
+ 'accept-language': 'Accept-Language',
26
+ 'accept-encoding': 'Accept-Encoding',
27
+ host: 'Host',
28
+ origin: 'Origin',
29
+ referer: 'Referer',
30
+ };
31
+ const MAX_HEADER_VALUE = 1024;
32
+ const MAX_QUERY_KEYS = 50;
33
+ const MAX_QUERY_VALUES = 20;
34
+ const MAX_QUERY_VALUE_LENGTH = 1024;
35
+ function truncate(value, max) {
36
+ return value.length > max ? value.slice(0, max) + '...' : value;
37
+ }
38
+ /** "/a/b?x=1#y" -> "/a/b". Also used for Referer. */
39
+ function stripQuery(value) {
40
+ const q = value.indexOf('?');
41
+ const h = value.indexOf('#');
42
+ let end = value.length;
43
+ if (q !== -1)
44
+ end = q;
45
+ if (h !== -1 && h < end)
46
+ end = h;
47
+ return value.slice(0, end);
48
+ }
49
+ /** The query part of a path or URL ("" when there is none), without the fragment. */
50
+ function queryOf(value) {
51
+ const q = value.indexOf('?');
52
+ if (q === -1)
53
+ return '';
54
+ const rest = value.slice(q + 1);
55
+ const h = rest.indexOf('#');
56
+ return h === -1 ? rest : rest.slice(0, h);
57
+ }
58
+ function pairs(input) {
59
+ const out = [];
60
+ if (!input || typeof input !== 'object')
61
+ return out;
62
+ if (Array.isArray(input)) {
63
+ for (const item of input) {
64
+ if (Array.isArray(item) && item.length >= 2)
65
+ out.push([String(item[0]), item[1]]);
66
+ }
67
+ return out;
68
+ }
69
+ const forEach = input.forEach;
70
+ if (typeof forEach === 'function') {
71
+ // Headers / URLSearchParams / Map-like: callback(value, key)
72
+ forEach.call(input, (value, key) => {
73
+ out.push([String(key), value]);
74
+ });
75
+ return out;
76
+ }
77
+ for (const key of Object.keys(input))
78
+ out.push([key, input[key]]);
79
+ return out;
80
+ }
81
+ /** Keep only allowlisted headers, with canonical names; strip the query string from Referer. */
82
+ function filterHeaders(input) {
83
+ const headers = {};
84
+ try {
85
+ for (const [name, raw] of pairs(input)) {
86
+ const lowered = name.toLowerCase();
87
+ const canonical = HEADER_ALLOWLIST[lowered];
88
+ if (!canonical || isSensitiveKey(lowered) || raw === undefined || raw === null)
89
+ continue;
90
+ let value = Array.isArray(raw) ? raw.map(String).join(', ') : String(raw);
91
+ if (lowered === 'referer')
92
+ value = stripQuery(value);
93
+ headers[canonical] = truncate(value, MAX_HEADER_VALUE);
94
+ }
95
+ }
96
+ catch {
97
+ // never throw into the host app
98
+ }
99
+ return headers;
100
+ }
101
+ function parseQueryString(query) {
102
+ const out = [];
103
+ const q = query.charAt(0) === '?' ? query.slice(1) : query;
104
+ for (const part of q.split('&')) {
105
+ if (!part)
106
+ continue;
107
+ const eq = part.indexOf('=');
108
+ const rawKey = eq === -1 ? part : part.slice(0, eq);
109
+ const rawValue = eq === -1 ? '' : part.slice(eq + 1);
110
+ out.push([decode(rawKey), decode(rawValue)]);
111
+ }
112
+ return out;
113
+ }
114
+ function decode(value) {
115
+ try {
116
+ return decodeURIComponent(value.replace(/\+/g, ' '));
117
+ }
118
+ catch {
119
+ return value;
120
+ }
121
+ }
122
+ /**
123
+ * Query parameters as {key: [values]}. Values under sensitive-looking keys become ["[Filtered]"].
124
+ * Accepts "a=1&b=2", "?a=1", URLSearchParams, or an object such as Express' req.query.
125
+ */
126
+ function filterQuery(input) {
127
+ const result = {};
128
+ try {
129
+ const entries = typeof input === 'string' ? parseQueryString(input) : pairs(input);
130
+ let keys = 0;
131
+ for (const [key, value] of entries) {
132
+ if (!(key in result)) {
133
+ if (keys >= MAX_QUERY_KEYS)
134
+ continue;
135
+ keys++;
136
+ result[key] = [];
137
+ }
138
+ if (isSensitiveKey(key)) {
139
+ result[key] = [exports.FILTERED];
140
+ continue;
141
+ }
142
+ const list = result[key];
143
+ const values = Array.isArray(value) ? value : [value];
144
+ for (const v of values) {
145
+ if (list.length >= MAX_QUERY_VALUES)
146
+ break;
147
+ list.push(truncate(queryValueToString(v), MAX_QUERY_VALUE_LENGTH));
148
+ }
149
+ }
150
+ }
151
+ catch {
152
+ // never throw into the host app
153
+ }
154
+ return result;
155
+ }
156
+ function queryValueToString(value) {
157
+ if (value === undefined || value === null)
158
+ return '';
159
+ if (typeof value === 'object')
160
+ return '[Object]';
161
+ return String(value);
162
+ }
163
+ /**
164
+ * JSON-safe copy of arbitrary context: sensitive-looking keys filtered (recursively),
165
+ * depth / size limited, functions and cycles dropped.
166
+ */
167
+ function scrub(value, depth = 0, seen = new WeakSet()) {
168
+ if (value === null || value === undefined)
169
+ return value ?? null;
170
+ const type = typeof value;
171
+ if (type === 'string')
172
+ return truncate(value, 4096);
173
+ if (type === 'number')
174
+ return Number.isFinite(value) ? value : String(value);
175
+ if (type === 'boolean')
176
+ return value;
177
+ if (type === 'bigint' || type === 'symbol')
178
+ return String(value);
179
+ if (type === 'function')
180
+ return '[Function]';
181
+ if (depth >= 6)
182
+ return '[Object]';
183
+ const obj = value;
184
+ if (seen.has(obj))
185
+ return '[Circular]';
186
+ seen.add(obj);
187
+ if (Array.isArray(obj))
188
+ return obj.slice(0, 50).map((v) => scrub(v, depth + 1, seen));
189
+ if (obj instanceof Date)
190
+ return isNaN(obj.getTime()) ? String(obj) : obj.toISOString();
191
+ const out = {};
192
+ let count = 0;
193
+ for (const key of Object.keys(obj)) {
194
+ if (count++ >= 100)
195
+ break;
196
+ out[key] = isSensitiveKey(key) ? exports.FILTERED : scrub(obj[key], depth + 1, seen);
197
+ }
198
+ return out;
199
+ }
200
+ // --- free-text scrubbing (port of the server's app/utils/scrubbing.py `scrub_text`) ----------------
201
+ exports.EMAIL_PLACEHOLDER = '[email]';
202
+ const SENSITIVE_NAME_IN_TEXT = 'passw(?:or)?d|passwd|pwd|secret|token|api[-_]?key|apikey|(?:private|access|secret|signing|encryption)[-_]?key' +
203
+ '|authoriz|session[-_]?id|sessionid|session[-_]?key|cookie|csrf|credential|signature' +
204
+ '|credit[-_]?card|card[-_]?(?:number|num|no)|cvv|cvc|iban|ssn';
205
+ const KEY_IN_TEXT = `[\\w-]*?(?:${SENSITIVE_NAME_IN_TEXT})[\\w-]*`;
206
+ // "password": "x" / 'api_key': 'x'
207
+ const QUOTED_PAIR_RE = new RegExp(`(["'])(${KEY_IN_TEXT})\\1(\\s*:\\s*)(["'])(?:\\\\.|(?!\\4).)*\\4`, 'gi');
208
+ // "password": 123 (unquoted value after a quoted key)
209
+ const QUOTED_KEY_BARE_VALUE_RE = new RegExp(`(["'])(${KEY_IN_TEXT})\\1(\\s*:\\s*)(?!["'\\[{])([^\\s,}\\]]+)`, 'gi');
210
+ // password=x (query strings, form bodies)
211
+ const ASSIGNMENT_RE = new RegExp(`\\b(${KEY_IN_TEXT})=(?!\\[Filtered\\])([^\\s&;,'")\\]}]+)`, 'gi');
212
+ // "Cookie: a=b" header lines
213
+ const HEADER_LINE_RE = /^(\s*(?:cookie|set-cookie|authorization|proxy-authorization|x-api-key)\s*:\s*).+$/gim;
214
+ const TOKEN_PATTERNS = [
215
+ /\beyJ[A-Za-z0-9_-]{5,}\.eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g, // JWT
216
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
217
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, // AWS access key ids
218
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g, // Stripe-style keys
219
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g, // GitHub tokens
220
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
221
+ /\bxox[abprs]-[A-Za-z0-9-]{10,}/g, // Slack tokens
222
+ /\bAIza[0-9A-Za-z_-]{30,}/g, // Google API keys
223
+ /\baissue_pat_[A-Za-z0-9_-]{8,}/g, // AIssue account tokens
224
+ ];
225
+ // "Bearer <token>" / "Basic <base64>" (needs a digit so prose like "Basic authentication" survives)
226
+ const AUTH_SCHEME_RE = /\b(Bearer|Basic|Token)\s+(?=[A-Za-z0-9\-._~+/]*\d)[A-Za-z0-9\-._~+/]{8,}=*/gi;
227
+ const EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
228
+ const CARD_CANDIDATE_RE = /\b(?:\d[ -]?){12,18}\d\b/g;
229
+ function luhnValid(digits) {
230
+ let total = 0;
231
+ for (let i = 0; i < digits.length; i++) {
232
+ let n = digits.charCodeAt(digits.length - 1 - i) - 48;
233
+ if (i % 2 === 1) {
234
+ n *= 2;
235
+ if (n > 9)
236
+ n -= 9;
237
+ }
238
+ total += n;
239
+ }
240
+ return total % 10 === 0;
241
+ }
242
+ /** Redact credentials, card numbers and email addresses from free text. Never throws. */
243
+ function scrubText(text) {
244
+ if (typeof text !== 'string' || !text)
245
+ return text;
246
+ try {
247
+ let out = text;
248
+ for (const pattern of TOKEN_PATTERNS)
249
+ out = out.replace(pattern, exports.FILTERED);
250
+ out = out.replace(AUTH_SCHEME_RE, (_m, scheme) => `${scheme} ${exports.FILTERED}`);
251
+ out = out.replace(HEADER_LINE_RE, (_m, prefix) => `${prefix}${exports.FILTERED}`);
252
+ out = out.replace(QUOTED_PAIR_RE, (_m, q, key, sep, vq) => `${q}${key}${q}${sep}${vq}${exports.FILTERED}${vq}`);
253
+ out = out.replace(QUOTED_KEY_BARE_VALUE_RE, (_m, q, key, sep) => `${q}${key}${q}${sep}${exports.FILTERED}`);
254
+ out = out.replace(ASSIGNMENT_RE, (_m, key) => `${key}=${exports.FILTERED}`);
255
+ out = out.replace(CARD_CANDIDATE_RE, (m) => {
256
+ const digits = m.replace(/\D/g, '');
257
+ return digits.length >= 13 && digits.length <= 19 && luhnValid(digits) ? exports.FILTERED : m;
258
+ });
259
+ out = out.replace(EMAIL_RE, exports.EMAIL_PLACEHOLDER);
260
+ return out;
261
+ }
262
+ catch {
263
+ return '';
264
+ }
265
+ }
266
+ /** "https://user:pass@host/a/b?x=1#y" -> "https://host/a/b" (no credentials, query or fragment). */
267
+ function sanitizeUrl(url) {
268
+ return stripQuery(String(url)).replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, '$1');
269
+ }
@@ -0,0 +1,13 @@
1
+ import type { StackFrame } from './types.js';
2
+ export declare const MAX_FRAMES = 50;
3
+ /** Frames from browser extensions (and Safari's masked extension URLs). */
4
+ export declare function isExtensionUrl(filename: string): boolean;
5
+ /** false for library code, runtime internals and browser extensions. */
6
+ export declare function isInApp(filename: string): boolean;
7
+ /**
8
+ * Parse error.stack (V8, Firefox or Safari format) into frames,
9
+ * oldest call first and innermost (where it failed) last. At most 50 frames (the innermost ones).
10
+ */
11
+ export declare function parseStack(stack: unknown): StackFrame[];
12
+ /** True when the stack looks like V8's, which already starts with "Type: message". */
13
+ export declare function isV8Stack(stack: string): boolean;
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_FRAMES = void 0;
4
+ exports.isExtensionUrl = isExtensionUrl;
5
+ exports.isInApp = isInApp;
6
+ exports.parseStack = parseStack;
7
+ exports.isV8Stack = isV8Stack;
8
+ exports.MAX_FRAMES = 50;
9
+ const MAX_STACK_LINES = 1000;
10
+ const EXTENSION_RE = /^(?:chrome|moz|safari|safari-web|ms-browser)-extension:\/\//i;
11
+ /** Frames from browser extensions (and Safari's masked extension URLs). */
12
+ function isExtensionUrl(filename) {
13
+ return EXTENSION_RE.test(filename) || filename.startsWith('webkit-masked-url:');
14
+ }
15
+ /** false for library code, runtime internals and browser extensions. */
16
+ function isInApp(filename) {
17
+ if (!filename)
18
+ return false;
19
+ if (/[\\/]node_modules[\\/]/.test(filename))
20
+ return false;
21
+ if (filename.startsWith('node:') || filename.startsWith('internal/'))
22
+ return false;
23
+ if (filename === '<anonymous>' || filename === 'native' || filename === '[native code]')
24
+ return false;
25
+ if (/^index \d+$/.test(filename))
26
+ return false; // e.g. "at Promise.all (index 0)"
27
+ if (isExtensionUrl(filename))
28
+ return false;
29
+ return true;
30
+ }
31
+ function normalizeFilename(filename) {
32
+ let name = filename.trim();
33
+ if (name.startsWith('file://')) {
34
+ try {
35
+ name = decodeURIComponent(name.slice('file://'.length));
36
+ if (/^\/[A-Za-z]:[\\/]/.test(name))
37
+ name = name.slice(1); // file:///C:/app -> C:/app
38
+ }
39
+ catch {
40
+ name = name.slice('file://'.length);
41
+ }
42
+ }
43
+ else if (/^https?:\/\//i.test(name)) {
44
+ // Script URLs: drop query strings / fragments (cache busters, occasionally tokens).
45
+ name = name.replace(/[?#].*$/, '');
46
+ }
47
+ return name.length > 1024 ? name.slice(0, 1024) : name;
48
+ }
49
+ function splitLocation(location) {
50
+ const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(location.trim());
51
+ if (!m)
52
+ return { filename: location.trim() };
53
+ return {
54
+ filename: m[1],
55
+ lineno: parseInt(m[2], 10),
56
+ colno: m[3] !== undefined ? parseInt(m[3], 10) : undefined,
57
+ };
58
+ }
59
+ function makeFrame(fn, location) {
60
+ const filename = normalizeFilename(location.filename);
61
+ const frame = {
62
+ filename,
63
+ function: (fn || '<anonymous>').slice(0, 512),
64
+ in_app: isInApp(filename),
65
+ };
66
+ if (location.lineno !== undefined && !isNaN(location.lineno))
67
+ frame.lineno = location.lineno;
68
+ if (location.colno !== undefined && !isNaN(location.colno))
69
+ frame.colno = location.colno;
70
+ return frame;
71
+ }
72
+ const V8_FRAME = /^\s+at\s+(.+?)\s*$/;
73
+ /** " at fn (file:1:2)", " at file:1:2", " at async fn (file:1:2)", " at new X (...)" */
74
+ function parseV8Line(line) {
75
+ const match = V8_FRAME.exec(line);
76
+ if (!match)
77
+ return null;
78
+ const rest = match[1];
79
+ let fn = '';
80
+ let location = rest;
81
+ if (rest.endsWith(')')) {
82
+ // Find the "(" matching the final ")"; locations can contain parentheses (eval frames).
83
+ let depth = 0;
84
+ for (let i = rest.length - 1; i >= 0; i--) {
85
+ const c = rest[i];
86
+ if (c === ')')
87
+ depth++;
88
+ else if (c === '(') {
89
+ depth--;
90
+ if (depth === 0) {
91
+ fn = rest.slice(0, i).trim();
92
+ location = rest.slice(i + 1, -1);
93
+ break;
94
+ }
95
+ }
96
+ }
97
+ }
98
+ if (fn.startsWith('async '))
99
+ fn = fn.slice(6).trim();
100
+ if (!fn && location.startsWith('async '))
101
+ location = location.slice(6).trim();
102
+ if (location.startsWith('eval at ')) {
103
+ // "eval at fn (file.js:1:2), <anonymous>:1:1" -> use the file that called eval
104
+ const inner = /\(([^()]*:\d+:\d+)\)/.exec(location);
105
+ location = inner ? inner[1] : '<anonymous>';
106
+ }
107
+ return makeFrame(fn, splitLocation(location));
108
+ }
109
+ /** Firefox / Safari: "fn@file:1:2", "@file:1:2", "fn@[native code]" */
110
+ function parseGeckoLine(line) {
111
+ const trimmed = line.trim();
112
+ const at = trimmed.indexOf('@');
113
+ if (at === -1)
114
+ return null;
115
+ const fn = trimmed.slice(0, at);
116
+ let location = trimmed.slice(at + 1);
117
+ if (!location)
118
+ return null;
119
+ // Firefox eval / Function frames: "file.js line 2 > eval:1:5" -> file.js:2
120
+ const evalMatch = /^(.*?) line (\d+)(?: > [\w ]+)+:\d+:\d+$/.exec(location);
121
+ if (evalMatch)
122
+ location = `${evalMatch[1]}:${evalMatch[2]}`;
123
+ return makeFrame(fn, splitLocation(location));
124
+ }
125
+ /**
126
+ * Parse error.stack (V8, Firefox or Safari format) into frames,
127
+ * oldest call first and innermost (where it failed) last. At most 50 frames (the innermost ones).
128
+ */
129
+ function parseStack(stack) {
130
+ if (typeof stack !== 'string' || !stack)
131
+ return [];
132
+ const lines = stack.split('\n', MAX_STACK_LINES);
133
+ const isV8 = lines.some((l) => V8_FRAME.test(l));
134
+ const frames = [];
135
+ for (const line of lines) {
136
+ const frame = isV8 ? parseV8Line(line) : parseGeckoLine(line);
137
+ if (frame)
138
+ frames.push(frame);
139
+ }
140
+ // Runtimes print the innermost frame first; the protocol wants it last.
141
+ frames.reverse();
142
+ return frames.length > exports.MAX_FRAMES ? frames.slice(frames.length - exports.MAX_FRAMES) : frames;
143
+ }
144
+ /** True when the stack looks like V8's, which already starts with "Type: message". */
145
+ function isV8Stack(stack) {
146
+ return /^\s+at\s/m.test(stack);
147
+ }
@@ -0,0 +1,31 @@
1
+ export type TransportMode = 'browser' | 'server';
2
+ export interface TransportOptions {
3
+ baseUrl: string;
4
+ apiKey: string;
5
+ mode: TransportMode;
6
+ timeoutMs?: number;
7
+ log: (message: string) => void;
8
+ warn: (message: string) => void;
9
+ }
10
+ /** Parse Retry-After (seconds or an HTTP date) into milliseconds. */
11
+ export declare function parseRetryAfter(value: string | null | undefined, now?: number): number;
12
+ /**
13
+ * Sends JSON bodies to POST {baseUrl}/api/errors/. Never throws, never retries, never queues:
14
+ * events are dropped on failure (ingestion protocol "Responses").
15
+ */
16
+ export declare class Transport {
17
+ private readonly options;
18
+ private readonly inflight;
19
+ private pausedUntil;
20
+ private warnedUnauthorized;
21
+ readonly url: string;
22
+ constructor(options: TransportOptions);
23
+ /** True while the server asked us to back off (429 Retry-After). */
24
+ isPaused(now?: number): boolean;
25
+ get pending(): number;
26
+ send(body: string): void;
27
+ private request;
28
+ private handleResponse;
29
+ /** Resolves true when every in-flight send finished, false when the timeout passed first. */
30
+ flush(timeoutMs?: number): Promise<boolean>;
31
+ }
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = void 0;
4
+ exports.parseRetryAfter = parseRetryAfter;
5
+ const event_js_1 = require("./event.js");
6
+ const version_js_1 = require("./version.js");
7
+ /** Browsers refuse keepalive requests with bodies over 64 KB. */
8
+ const KEEPALIVE_MAX_BYTES = 60000;
9
+ const DEFAULT_RETRY_AFTER_SECONDS = 60;
10
+ /** Parse Retry-After (seconds or an HTTP date) into milliseconds. */
11
+ function parseRetryAfter(value, now = Date.now()) {
12
+ if (value) {
13
+ const seconds = Number(value.trim());
14
+ if (Number.isFinite(seconds) && seconds >= 0)
15
+ return seconds * 1000;
16
+ const date = Date.parse(value);
17
+ if (!isNaN(date))
18
+ return Math.max(0, date - now);
19
+ }
20
+ return DEFAULT_RETRY_AFTER_SECONDS * 1000;
21
+ }
22
+ /**
23
+ * Sends JSON bodies to POST {baseUrl}/api/errors/. Never throws, never retries, never queues:
24
+ * events are dropped on failure (ingestion protocol "Responses").
25
+ */
26
+ class Transport {
27
+ constructor(options) {
28
+ this.options = options;
29
+ this.inflight = new Set();
30
+ this.pausedUntil = 0;
31
+ this.warnedUnauthorized = false;
32
+ const base = options.baseUrl.replace(/\/+$/, '');
33
+ this.url =
34
+ options.mode === 'browser'
35
+ ? `${base}/api/errors/?api_key=${encodeURIComponent(options.apiKey)}`
36
+ : `${base}/api/errors/`;
37
+ }
38
+ /** True while the server asked us to back off (429 Retry-After). */
39
+ isPaused(now = Date.now()) {
40
+ return now < this.pausedUntil;
41
+ }
42
+ get pending() {
43
+ return this.inflight.size;
44
+ }
45
+ send(body) {
46
+ try {
47
+ if (this.isPaused()) {
48
+ this.options.log('rate limited by the server; dropping event');
49
+ return;
50
+ }
51
+ const fetchFn = globalThis.fetch;
52
+ if (typeof fetchFn !== 'function') {
53
+ this.options.log('fetch is not available; dropping event');
54
+ return;
55
+ }
56
+ const promise = this.request(fetchFn, body)
57
+ .catch((error) => {
58
+ this.options.log(`failed to send event: ${error instanceof Error ? error.name : 'error'}`);
59
+ })
60
+ .then(() => {
61
+ this.inflight.delete(promise);
62
+ });
63
+ this.inflight.add(promise);
64
+ }
65
+ catch {
66
+ // never throw into the host app
67
+ }
68
+ }
69
+ async request(fetchFn, body) {
70
+ const { mode } = this.options;
71
+ const init = { method: 'POST', body };
72
+ if (mode === 'browser') {
73
+ // text/plain + key in the query string = a "simple" CORS request (no preflight).
74
+ init.headers = { 'Content-Type': 'text/plain;charset=UTF-8' };
75
+ init.keepalive = (0, event_js_1.byteLength)(body) <= KEEPALIVE_MAX_BYTES;
76
+ init.credentials = 'omit';
77
+ }
78
+ else {
79
+ init.headers = {
80
+ 'Content-Type': 'application/json',
81
+ 'X-API-Key': this.options.apiKey,
82
+ 'User-Agent': `${version_js_1.SDK_NAME}/${version_js_1.SDK_VERSION}`,
83
+ };
84
+ }
85
+ let timer;
86
+ const Controller = globalThis.AbortController;
87
+ if (Controller) {
88
+ const controller = new Controller();
89
+ init.signal = controller.signal;
90
+ timer = setTimeout(() => controller.abort(), this.options.timeoutMs ?? 5000);
91
+ timer.unref?.();
92
+ }
93
+ try {
94
+ const response = await fetchFn(this.url, init);
95
+ this.handleResponse(response);
96
+ try {
97
+ response.body?.cancel?.();
98
+ }
99
+ catch {
100
+ // ignore
101
+ }
102
+ }
103
+ finally {
104
+ if (timer !== undefined)
105
+ clearTimeout(timer);
106
+ }
107
+ }
108
+ handleResponse(response) {
109
+ const { status } = response;
110
+ if (status >= 200 && status < 300) {
111
+ this.options.log(`event sent (${status})`);
112
+ return;
113
+ }
114
+ if (status === 429) {
115
+ let retryAfter = null;
116
+ try {
117
+ retryAfter = response.headers?.get('Retry-After') ?? null;
118
+ }
119
+ catch {
120
+ retryAfter = null;
121
+ }
122
+ const ms = parseRetryAfter(retryAfter);
123
+ this.pausedUntil = Date.now() + ms;
124
+ this.options.warn(`AIssue rate limit reached; pausing for ${Math.round(ms / 1000)}s`);
125
+ return;
126
+ }
127
+ if (status === 401) {
128
+ if (!this.warnedUnauthorized) {
129
+ this.warnedUnauthorized = true;
130
+ this.options.warn('AIssue rejected the API key (401). Check apiKey / AISSUE_API_KEY.');
131
+ }
132
+ return;
133
+ }
134
+ this.options.log(`event dropped by the server (${status})`);
135
+ }
136
+ /** Resolves true when every in-flight send finished, false when the timeout passed first. */
137
+ flush(timeoutMs = 2000) {
138
+ if (this.inflight.size === 0)
139
+ return Promise.resolve(true);
140
+ return new Promise((resolve) => {
141
+ const timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
142
+ const settleAll = () => {
143
+ if (this.inflight.size === 0) {
144
+ clearTimeout(timer);
145
+ resolve(true);
146
+ return;
147
+ }
148
+ Promise.all(Array.from(this.inflight)).then(settleAll, settleAll);
149
+ };
150
+ settleAll();
151
+ });
152
+ }
153
+ }
154
+ exports.Transport = Transport;