@hullop/tlm 0.0.0-stage → 0.2.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.
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +365 -2
- package/dist/chunk-ECMQ35KU.js +62 -0
- package/dist/index.cjs +1342 -0
- package/dist/index.d.cts +58 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.js +1270 -0
- package/dist/rum.cjs +622 -0
- package/dist/rum.d.cts +63 -0
- package/dist/rum.d.ts +63 -0
- package/dist/rum.esm.js +2 -0
- package/dist/rum.js +592 -0
- package/dist/tlm.esm.js +7 -0
- package/dist/types-BluGo23D.d.cts +179 -0
- package/dist/types-BluGo23D.d.ts +179 -0
- package/package.json +71 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1342 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/dsn.ts
|
|
4
|
+
function parseDsn(dsn) {
|
|
5
|
+
let parsed;
|
|
6
|
+
try {
|
|
7
|
+
parsed = new URL(dsn);
|
|
8
|
+
} catch {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username === "") return null;
|
|
12
|
+
const base = parsed.origin + parsed.pathname.replace(/\/+$/, "");
|
|
13
|
+
const key = parsed.username;
|
|
14
|
+
return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, pageviewsUrl: `${base}/api/pageviews?key=${key}`, base, key };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// src/util.ts
|
|
18
|
+
function uuid4() {
|
|
19
|
+
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
20
|
+
const b = crypto.getRandomValues(new Uint8Array(16));
|
|
21
|
+
b[6] = (b[6] ?? 0) & 15 | 64;
|
|
22
|
+
b[8] = (b[8] ?? 0) & 63 | 128;
|
|
23
|
+
const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
24
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
25
|
+
}
|
|
26
|
+
function truncate(s, max) {
|
|
27
|
+
if (s.length <= max) return s;
|
|
28
|
+
const last = s.charCodeAt(max - 1);
|
|
29
|
+
return s.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
|
|
30
|
+
}
|
|
31
|
+
function safeStringify(value, max = 8192) {
|
|
32
|
+
return truncate(stringify(value), max);
|
|
33
|
+
}
|
|
34
|
+
function stringify(value) {
|
|
35
|
+
if (typeof value === "string") return value;
|
|
36
|
+
if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
|
|
37
|
+
return String(value);
|
|
38
|
+
}
|
|
39
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
40
|
+
try {
|
|
41
|
+
return JSON.stringify(value, (_key, v) => {
|
|
42
|
+
if (typeof v === "bigint") return v.toString();
|
|
43
|
+
if (typeof v === "object" && v !== null) {
|
|
44
|
+
if (seen.has(v)) return "[Circular]";
|
|
45
|
+
seen.add(v);
|
|
46
|
+
}
|
|
47
|
+
return v;
|
|
48
|
+
});
|
|
49
|
+
} catch {
|
|
50
|
+
try {
|
|
51
|
+
return String(value);
|
|
52
|
+
} catch {
|
|
53
|
+
return "[unserializable]";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function stripUrl(url) {
|
|
58
|
+
const i = url.search(/[?#]/);
|
|
59
|
+
return i === -1 ? url : url.slice(0, i);
|
|
60
|
+
}
|
|
61
|
+
var MAX_URL = 500;
|
|
62
|
+
function rumUrl(base, url) {
|
|
63
|
+
try {
|
|
64
|
+
const parsed = new URL(url, base);
|
|
65
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
|
|
66
|
+
return (parsed.origin + parsed.pathname).slice(0, MAX_URL);
|
|
67
|
+
} catch {
|
|
68
|
+
return void 0;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/stacktrace.ts
|
|
73
|
+
var MAX_FRAMES = 250;
|
|
74
|
+
var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
|
|
75
|
+
var GECKO = /^(.*?)@(.*):(\d+):(\d+)$/;
|
|
76
|
+
var V8_EVAL = /\((\S+?):(\d+):(\d+)\)/;
|
|
77
|
+
var GECKO_EVAL = /^(.*?) line (\d+) > (?:eval|Function)/;
|
|
78
|
+
var NOT_FUNCTIONS = /* @__PURE__ */ new Set(["global code", "module code", "eval code"]);
|
|
79
|
+
function parseStack(stack) {
|
|
80
|
+
const frames = [];
|
|
81
|
+
for (const text of stack.split("\n")) {
|
|
82
|
+
const frame = parseV8(text) ?? parseGecko(text);
|
|
83
|
+
if (frame) frames.push(frame);
|
|
84
|
+
}
|
|
85
|
+
return frames;
|
|
86
|
+
}
|
|
87
|
+
function parseV8(text) {
|
|
88
|
+
const m = V8.exec(text);
|
|
89
|
+
if (m?.[2] === void 0) return void 0;
|
|
90
|
+
let url = m[2];
|
|
91
|
+
let line = Number(m[3]);
|
|
92
|
+
let column = Number(m[4]);
|
|
93
|
+
if (url.startsWith("eval at ")) {
|
|
94
|
+
const inner = V8_EVAL.exec(url);
|
|
95
|
+
if (inner?.[1] === void 0) return void 0;
|
|
96
|
+
url = inner[1];
|
|
97
|
+
line = Number(inner[2]);
|
|
98
|
+
column = Number(inner[3]);
|
|
99
|
+
}
|
|
100
|
+
return { function: cleanName(m[1]), url, line, column };
|
|
101
|
+
}
|
|
102
|
+
function parseGecko(text) {
|
|
103
|
+
const m = GECKO.exec(text);
|
|
104
|
+
if (m?.[2] === void 0 || m[2] === "") return void 0;
|
|
105
|
+
let name = m[1];
|
|
106
|
+
const marker = /^([^*]*)\*(.*)$/.exec(name ?? "");
|
|
107
|
+
if (marker) {
|
|
108
|
+
if (marker[1] !== "async") return void 0;
|
|
109
|
+
name = marker[2];
|
|
110
|
+
}
|
|
111
|
+
const evalMatch = GECKO_EVAL.exec(m[2]);
|
|
112
|
+
if (evalMatch?.[1] !== void 0 && evalMatch[1] !== "") return { function: cleanName(name), url: evalMatch[1], line: Number(evalMatch[2]), column: void 0 };
|
|
113
|
+
return { function: cleanName(name), url: m[2], line: Number(m[3]), column: Number(m[4]) };
|
|
114
|
+
}
|
|
115
|
+
function cleanName(name) {
|
|
116
|
+
if (name === void 0 || name === "") return void 0;
|
|
117
|
+
if (NOT_FUNCTIONS.has(name)) return void 0;
|
|
118
|
+
const cleaned = name.replace(/^async\*/, "").replace(/^(?:async|new) /, "").replace(/ \[as [^\]]*\]$/, "").replace(/[/<]+$/, "");
|
|
119
|
+
const bare = cleaned.slice(Math.max(cleaned.lastIndexOf("."), cleaned.lastIndexOf("/")) + 1);
|
|
120
|
+
return bare !== "" && bare !== "<anonymous>" ? bare : void 0;
|
|
121
|
+
}
|
|
122
|
+
function isExtensionUrl(url) {
|
|
123
|
+
return /^(?:chrome|moz|safari|safari-web)-extension:\/\//.test(url);
|
|
124
|
+
}
|
|
125
|
+
var VENDOR_PATTERNS = [
|
|
126
|
+
/\/node_modules\//,
|
|
127
|
+
/\/\.vite\/deps\//,
|
|
128
|
+
// A vendor/ directory, or a bundle named vendor(s)…; not /vendor-portal/App.js.
|
|
129
|
+
/\/vendors?(?:\/|[-.~][^/]*$)/,
|
|
130
|
+
/chunk-vendors/,
|
|
131
|
+
/vendors~/,
|
|
132
|
+
/\/@vite\//,
|
|
133
|
+
/\/@react-refresh/,
|
|
134
|
+
/\/_next\/static\/chunks\/(?:framework|main|webpack)[-.]/
|
|
135
|
+
];
|
|
136
|
+
var HASH_SEGMENT = /[-.~]([A-Za-z0-9_]{8,}|[A-Za-z0-9_-]{8})(?=\.)/g;
|
|
137
|
+
function isHash(token) {
|
|
138
|
+
if (/\d/.test(token)) return true;
|
|
139
|
+
if (token.length !== 8) return false;
|
|
140
|
+
return /[_-]/.test(token) || /[A-Z]/.test(token) && /[a-z]/.test(token) && !/[a-z]{3}/.test(token);
|
|
141
|
+
}
|
|
142
|
+
function normalizeModule(path) {
|
|
143
|
+
const clean = stripUrl(path);
|
|
144
|
+
const slash = clean.lastIndexOf("/") + 1;
|
|
145
|
+
const name = clean.slice(slash).replace(HASH_SEGMENT, (segment, token) => isHash(token) ? "" : segment);
|
|
146
|
+
return clean.slice(0, slash) + name;
|
|
147
|
+
}
|
|
148
|
+
function toFrames(raw, opts) {
|
|
149
|
+
const frames = [];
|
|
150
|
+
for (const r of raw) {
|
|
151
|
+
if (r.function?.startsWith("__tlm") === true) continue;
|
|
152
|
+
if (frames.length === MAX_FRAMES) break;
|
|
153
|
+
frames.push(toFrame(r, opts));
|
|
154
|
+
}
|
|
155
|
+
return frames;
|
|
156
|
+
}
|
|
157
|
+
function toFrame(raw, { origin, inAppUrls, isDependency, ownUrl }) {
|
|
158
|
+
let url;
|
|
159
|
+
try {
|
|
160
|
+
url = new URL(raw.url, origin);
|
|
161
|
+
} catch {
|
|
162
|
+
url = void 0;
|
|
163
|
+
}
|
|
164
|
+
const webpackInternal = raw.url.startsWith("webpack-internal://");
|
|
165
|
+
const sameOrigin = url?.origin === origin || webpackInternal;
|
|
166
|
+
let file = stripUrl(raw.url);
|
|
167
|
+
if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
|
|
168
|
+
const absolute = url ? stripUrl(url.href) : void 0;
|
|
169
|
+
const own = absolute !== void 0 && absolute === ownUrl;
|
|
170
|
+
const dependency = absolute !== void 0 && isDependency?.(absolute) === true;
|
|
171
|
+
const inApp = !own && (inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file)) && !dependency);
|
|
172
|
+
const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
|
|
173
|
+
if (raw.line !== void 0) frame.line = raw.line;
|
|
174
|
+
if (raw.column !== void 0) frame.column = raw.column;
|
|
175
|
+
return frame;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// src/event.ts
|
|
179
|
+
var MAX_MESSAGE = 8192;
|
|
180
|
+
var LEVELS = /* @__PURE__ */ new Set(["fatal", "error", "warning", "info"]);
|
|
181
|
+
var LEVEL_ALIASES = { debug: "info", log: "info", warn: "warning", critical: "fatal" };
|
|
182
|
+
function toLevel(level) {
|
|
183
|
+
if (typeof level !== "string") return "error";
|
|
184
|
+
return LEVELS.has(level) ? level : LEVEL_ALIASES[level] ?? "error";
|
|
185
|
+
}
|
|
186
|
+
var SDK_NAME = "@hullop/tlm";
|
|
187
|
+
function isErrorLike(value) {
|
|
188
|
+
if (value instanceof Error) return true;
|
|
189
|
+
if (typeof value !== "object" || value === null) return false;
|
|
190
|
+
const v = value;
|
|
191
|
+
return typeof v.message === "string" && (typeof v.name === "string" || typeof v.stack === "string");
|
|
192
|
+
}
|
|
193
|
+
function errorType(error) {
|
|
194
|
+
if (typeof error.name === "string" && error.name !== "") return error.name;
|
|
195
|
+
const ctor = error.constructor?.name;
|
|
196
|
+
return typeof ctor === "string" && ctor !== "" && ctor !== "Object" ? ctor : "Error";
|
|
197
|
+
}
|
|
198
|
+
function eventFromException(error, env, ctx, mechanism = "manual") {
|
|
199
|
+
const event = baseEvent(env, ctx);
|
|
200
|
+
if (isErrorLike(error)) {
|
|
201
|
+
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, isDependency: env.isDependency, ownUrl: env.ownUrl }) : [];
|
|
202
|
+
event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
|
|
203
|
+
if (frames.length > 0) event.exception.frames = frames;
|
|
204
|
+
} else {
|
|
205
|
+
event.exception = {
|
|
206
|
+
type: mechanism === "onunhandledrejection" ? "UnhandledRejection" : "NonError",
|
|
207
|
+
message: safeStringify(error, MAX_MESSAGE)
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
return event;
|
|
211
|
+
}
|
|
212
|
+
function eventFromMessage(message, env, ctx) {
|
|
213
|
+
const event = baseEvent(env, ctx);
|
|
214
|
+
event.message = safeStringify(message, MAX_MESSAGE);
|
|
215
|
+
return event;
|
|
216
|
+
}
|
|
217
|
+
function injectedRelease() {
|
|
218
|
+
return typeof __TLM_RELEASE__ === "string" ? __TLM_RELEASE__ : void 0;
|
|
219
|
+
}
|
|
220
|
+
function releaseOf(options) {
|
|
221
|
+
const release = options.release ?? injectedRelease();
|
|
222
|
+
return release === "" ? void 0 : release;
|
|
223
|
+
}
|
|
224
|
+
function environmentOf(options) {
|
|
225
|
+
return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
|
|
226
|
+
}
|
|
227
|
+
function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
|
|
228
|
+
const event = {
|
|
229
|
+
v: 1,
|
|
230
|
+
uuid: uuid4(),
|
|
231
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
232
|
+
platform: "javascript",
|
|
233
|
+
level: toLevel(ctx.level),
|
|
234
|
+
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
235
|
+
sdk: { name: SDK_NAME, version: "0.2.0" }
|
|
236
|
+
};
|
|
237
|
+
const environment = environmentOf(options);
|
|
238
|
+
if (environment !== void 0) event.environment = environment;
|
|
239
|
+
const release = releaseOf(options);
|
|
240
|
+
if (release !== void 0) event.release = release;
|
|
241
|
+
if (session !== void 0) event.session = session;
|
|
242
|
+
if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
|
|
243
|
+
const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
|
|
244
|
+
if (user) event.user = user;
|
|
245
|
+
const tags = { ...scope2.tags, ...ctx.tags };
|
|
246
|
+
if (Object.keys(tags).length > 0) event.tags = tags;
|
|
247
|
+
const breadcrumbs = scope2.getBreadcrumbs();
|
|
248
|
+
if (breadcrumbs.length > 0) event.breadcrumbs = breadcrumbs;
|
|
249
|
+
return event;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// src/filters.ts
|
|
253
|
+
var DEFAULT_IGNORE = [
|
|
254
|
+
"ResizeObserver loop limit exceeded",
|
|
255
|
+
"ResizeObserver loop completed with undelivered notifications",
|
|
256
|
+
// Cross-origin scripts without CORS: the browser hides everything.
|
|
257
|
+
/^(?:Error: )?Script error\.?$/
|
|
258
|
+
];
|
|
259
|
+
function summary(event) {
|
|
260
|
+
const { exception } = event;
|
|
261
|
+
if (!exception) return event.message ?? "";
|
|
262
|
+
return exception.message !== void 0 && exception.message !== "" ? `${exception.type}: ${exception.message}` : exception.type;
|
|
263
|
+
}
|
|
264
|
+
function shouldIgnore(event, patterns) {
|
|
265
|
+
const frames = event.exception?.frames;
|
|
266
|
+
if (frames !== void 0 && frames.length > 0 && frames.every((f) => isExtensionUrl(f.file))) return true;
|
|
267
|
+
const text = summary(event);
|
|
268
|
+
return patterns.some((p) => typeof p === "string" ? text.includes(p) : p.test(text));
|
|
269
|
+
}
|
|
270
|
+
var Deduper = class {
|
|
271
|
+
constructor(windowMs = 1e3) {
|
|
272
|
+
this.windowMs = windowMs;
|
|
273
|
+
this.lastAt = 0;
|
|
274
|
+
}
|
|
275
|
+
isDuplicate(event, now) {
|
|
276
|
+
const frames = (event.exception?.frames ?? []).slice(0, 5).map((f) => `${f.file}:${String(f.line)}:${String(f.column)}`);
|
|
277
|
+
const key = `${summary(event)}
|
|
278
|
+
${frames.join("\n")}`;
|
|
279
|
+
const duplicate = key === this.last && now - this.lastAt <= this.windowMs;
|
|
280
|
+
this.last = key;
|
|
281
|
+
this.lastAt = now;
|
|
282
|
+
return duplicate;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
var RateGuard = class {
|
|
286
|
+
constructor(max = 30, windowMs = 1e4) {
|
|
287
|
+
this.max = max;
|
|
288
|
+
this.windowMs = windowMs;
|
|
289
|
+
this.times = [];
|
|
290
|
+
}
|
|
291
|
+
take(now) {
|
|
292
|
+
this.times = this.times.filter((t) => now - t < this.windowMs);
|
|
293
|
+
if (this.times.length >= this.max) return false;
|
|
294
|
+
this.times.push(now);
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
// src/handlers.ts
|
|
300
|
+
function installGlobalHandlers(win, onError, opts) {
|
|
301
|
+
const onErrorEvent = (event) => {
|
|
302
|
+
try {
|
|
303
|
+
if (typeof event.target?.nodeType === "number") return;
|
|
304
|
+
const e = event;
|
|
305
|
+
onError(e.error ?? errorFromLocation(e), "onerror");
|
|
306
|
+
} catch {
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const onRejection = (event) => {
|
|
310
|
+
try {
|
|
311
|
+
onError(event.reason, "onunhandledrejection");
|
|
312
|
+
} catch {
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
if (opts.onerror) win.addEventListener("error", onErrorEvent);
|
|
316
|
+
if (opts.onunhandledrejection) win.addEventListener("unhandledrejection", onRejection);
|
|
317
|
+
return () => {
|
|
318
|
+
win.removeEventListener("error", onErrorEvent);
|
|
319
|
+
win.removeEventListener("unhandledrejection", onRejection);
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
var THROWN_NOTHING = /^(?:Uncaught |uncaught exception: )?(null|undefined)$/;
|
|
323
|
+
function errorFromLocation(e) {
|
|
324
|
+
const nothing = THROWN_NOTHING.exec(e.message);
|
|
325
|
+
const error = new Error(nothing?.[1] ?? (e.message !== "" ? e.message : "Unknown error"));
|
|
326
|
+
if (nothing) error.name = "NonError";
|
|
327
|
+
error.stack = typeof e.filename === "string" && e.filename !== "" ? `${error.name}: ${error.message}
|
|
328
|
+
at ? (${e.filename}:${String(e.lineno)}:${String(e.colno)})` : "";
|
|
329
|
+
return error;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// src/heartbeat.ts
|
|
333
|
+
var HEARTBEAT_DELAY_MS = 5e3;
|
|
334
|
+
var STORAGE_PREFIX = "tlm:heartbeat:";
|
|
335
|
+
var sentThisPage = /* @__PURE__ */ new Set();
|
|
336
|
+
function scheduleHeartbeat(deps) {
|
|
337
|
+
let idle;
|
|
338
|
+
const run = () => {
|
|
339
|
+
void beat(deps);
|
|
340
|
+
};
|
|
341
|
+
const timer = setTimeout(() => {
|
|
342
|
+
if ("requestIdleCallback" in globalThis) idle = requestIdleCallback(run, { timeout: HEARTBEAT_DELAY_MS });
|
|
343
|
+
else run();
|
|
344
|
+
}, HEARTBEAT_DELAY_MS);
|
|
345
|
+
return () => {
|
|
346
|
+
clearTimeout(timer);
|
|
347
|
+
if (idle !== void 0) cancelIdleCallback(idle);
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
function storedMark(storageKey) {
|
|
351
|
+
try {
|
|
352
|
+
return localStorage.getItem(storageKey);
|
|
353
|
+
} catch {
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async function beat({ url, key, fetch, options, logger }) {
|
|
358
|
+
const release = releaseOf(options);
|
|
359
|
+
const environment = environmentOf(options);
|
|
360
|
+
const storageKey = STORAGE_PREFIX + key;
|
|
361
|
+
const mark = JSON.stringify([(/* @__PURE__ */ new Date()).toISOString().slice(0, 10), release ?? "", environment ?? ""]);
|
|
362
|
+
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
363
|
+
let status;
|
|
364
|
+
try {
|
|
365
|
+
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.2.0" }, environment, release });
|
|
366
|
+
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
367
|
+
({ status } = response);
|
|
368
|
+
} catch (error) {
|
|
369
|
+
logger.debug("heartbeat not sent", error);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (status === 429 || status >= 500) return;
|
|
373
|
+
try {
|
|
374
|
+
localStorage.setItem(storageKey, mark);
|
|
375
|
+
} catch {
|
|
376
|
+
sentThisPage.add(storageKey + mark);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// src/meta.ts
|
|
381
|
+
function metaContent(doc, name) {
|
|
382
|
+
const content = doc.querySelector(`meta[name="tlm-${name}"]`)?.getAttribute("content")?.trim();
|
|
383
|
+
return content === "" ? void 0 : content;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// src/importmap.ts
|
|
387
|
+
var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
|
|
388
|
+
function pinsOf(doc, base) {
|
|
389
|
+
const pins = [];
|
|
390
|
+
for (const script of doc.querySelectorAll('script[type="importmap"]')) {
|
|
391
|
+
let map;
|
|
392
|
+
try {
|
|
393
|
+
map = JSON.parse(script.textContent);
|
|
394
|
+
} catch {
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
|
|
398
|
+
if (typeof imports !== "object" || imports === null) continue;
|
|
399
|
+
for (const [specifier, target] of Object.entries(imports)) {
|
|
400
|
+
if (!isBare(specifier) || typeof target !== "string") continue;
|
|
401
|
+
try {
|
|
402
|
+
pins.push({ specifier, url: stripUrl(new URL(target, base).href) });
|
|
403
|
+
} catch {
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return pins;
|
|
408
|
+
}
|
|
409
|
+
function namedAfterPin({ specifier, url }) {
|
|
410
|
+
const name = specifier.replace(/\/$/, "");
|
|
411
|
+
const path = normalizeModule(new URL(url).pathname).replace(/\.m?js$/, "").replace(/\/$/, "");
|
|
412
|
+
return path.endsWith(`/${name}`) || path.endsWith(`/${name}/index`);
|
|
413
|
+
}
|
|
414
|
+
function listedIn(inApp, specifier) {
|
|
415
|
+
return inApp.some((entry) => entry.endsWith("/") ? specifier.startsWith(entry) || specifier === entry.slice(0, -1) : specifier === entry);
|
|
416
|
+
}
|
|
417
|
+
function importmapDependencies(doc, base) {
|
|
418
|
+
const inApp = metaContent(doc, "in-app")?.split(/\s+/);
|
|
419
|
+
const isDependency = (pin) => inApp ? !listedIn(inApp, pin.specifier) : pin.specifier.startsWith("@") || !namedAfterPin(pin);
|
|
420
|
+
const exact = /* @__PURE__ */ new Set();
|
|
421
|
+
const prefixes = [];
|
|
422
|
+
for (const pin of pinsOf(doc, base)) {
|
|
423
|
+
if (!isDependency(pin)) continue;
|
|
424
|
+
if (pin.specifier.endsWith("/")) prefixes.push(pin.url);
|
|
425
|
+
else exact.add(pin.url);
|
|
426
|
+
}
|
|
427
|
+
return (url) => exact.has(url) || prefixes.some((prefix) => url.startsWith(prefix));
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// src/describe.ts
|
|
431
|
+
var MAX_KEYS = 10;
|
|
432
|
+
var MAX_STRING = 100;
|
|
433
|
+
function describeValue(value, nested = false) {
|
|
434
|
+
if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
|
|
435
|
+
if (value === null || typeof value !== "object") {
|
|
436
|
+
return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
|
|
437
|
+
}
|
|
438
|
+
const v = value;
|
|
439
|
+
if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
|
|
440
|
+
return `${String(v.name)}: ${String(v.message)}`;
|
|
441
|
+
}
|
|
442
|
+
if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
|
|
443
|
+
if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
|
|
444
|
+
if (Array.isArray(value)) {
|
|
445
|
+
const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
|
|
446
|
+
return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
|
|
447
|
+
}
|
|
448
|
+
try {
|
|
449
|
+
const keys = Object.keys(value);
|
|
450
|
+
const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
|
|
451
|
+
return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
|
|
452
|
+
} catch {
|
|
453
|
+
return "{\u2026}";
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/instrument/common.ts
|
|
458
|
+
var ORIGINAL = "__tlm_original__";
|
|
459
|
+
function wrap(obj, name, make) {
|
|
460
|
+
const current = obj[name];
|
|
461
|
+
if (typeof current !== "function" || current[ORIGINAL] !== void 0) return () => true;
|
|
462
|
+
const wrapper = make(current);
|
|
463
|
+
Object.defineProperty(wrapper, ORIGINAL, { value: current });
|
|
464
|
+
obj[name] = wrapper;
|
|
465
|
+
return () => {
|
|
466
|
+
if (obj[name] !== wrapper) return false;
|
|
467
|
+
obj[name] = current;
|
|
468
|
+
return true;
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
function safeRecord(fn) {
|
|
472
|
+
try {
|
|
473
|
+
fn();
|
|
474
|
+
} catch {
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
function displayUrl(win, url, stripQuery) {
|
|
478
|
+
let shown = url;
|
|
479
|
+
try {
|
|
480
|
+
const parsed = new URL(url, win.location.href);
|
|
481
|
+
parsed.username = "";
|
|
482
|
+
parsed.password = "";
|
|
483
|
+
shown = parsed.origin === win.location.origin ? parsed.pathname + parsed.search + parsed.hash : parsed.href;
|
|
484
|
+
} catch {
|
|
485
|
+
}
|
|
486
|
+
return stripQuery ? stripUrl(shown) : shown;
|
|
487
|
+
}
|
|
488
|
+
function timeRequest(opts, win, method, url) {
|
|
489
|
+
const target = opts.onRequest ? rumUrl(win.location.href, url) : void 0;
|
|
490
|
+
if (target === void 0) return () => void 0;
|
|
491
|
+
const start = performance.now();
|
|
492
|
+
const token = opts.onRequestStart?.();
|
|
493
|
+
return (status) => {
|
|
494
|
+
opts.onRequest?.({ method: method.toUpperCase(), url: target, status: status ?? 0, start, end: performance.now() }, token);
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function absoluteUrl(win, url) {
|
|
498
|
+
try {
|
|
499
|
+
return new URL(url, win.location.href).href;
|
|
500
|
+
} catch {
|
|
501
|
+
return url;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function levelForStatus(status) {
|
|
505
|
+
if (status === void 0 || status >= 500) return "error";
|
|
506
|
+
return status >= 400 ? "warning" : "info";
|
|
507
|
+
}
|
|
508
|
+
function requestMessage(method, url, status) {
|
|
509
|
+
return `${method.toUpperCase()} ${url} \u2192 ${status === void 0 ? "failed" : String(status)}`;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// src/instrument/console.ts
|
|
513
|
+
var LEVELS2 = { error: "error", warn: "warning", log: "info", info: "info" };
|
|
514
|
+
function instrumentConsole(win, record, _opts) {
|
|
515
|
+
const target = win.console;
|
|
516
|
+
const restores = Object.keys(LEVELS2).map(
|
|
517
|
+
(method) => wrap(
|
|
518
|
+
target,
|
|
519
|
+
method,
|
|
520
|
+
(original) => function __tlmWrapped(...args) {
|
|
521
|
+
safeRecord(() => {
|
|
522
|
+
record({ category: "console", level: LEVELS2[method], message: truncate(args.map((a) => describeValue(a)).join(" "), 500) });
|
|
523
|
+
});
|
|
524
|
+
original.apply(this, args);
|
|
525
|
+
}
|
|
526
|
+
)
|
|
527
|
+
);
|
|
528
|
+
return () => restores.map((restore) => restore()).every(Boolean);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// src/instrument/dom.ts
|
|
532
|
+
var MAX_DEPTH = 3;
|
|
533
|
+
function describe(element) {
|
|
534
|
+
const parts = [];
|
|
535
|
+
let el = element;
|
|
536
|
+
while (el && parts.length < MAX_DEPTH && el.tagName !== "BODY" && el.tagName !== "HTML") {
|
|
537
|
+
let part = el.tagName.toLowerCase();
|
|
538
|
+
if (el.id !== "") part += `#${el.id}`;
|
|
539
|
+
for (const cls of Array.from(el.classList)) part += `.${cls}`;
|
|
540
|
+
parts.unshift(part);
|
|
541
|
+
el = el.parentElement;
|
|
542
|
+
}
|
|
543
|
+
return parts.join(" > ");
|
|
544
|
+
}
|
|
545
|
+
function instrumentDom(win, record, _opts) {
|
|
546
|
+
const onClick = (event) => {
|
|
547
|
+
safeRecord(() => {
|
|
548
|
+
const target = event.target;
|
|
549
|
+
if (target?.nodeType !== 1) return;
|
|
550
|
+
const message = describe(target);
|
|
551
|
+
if (message !== "") record({ category: "ui.click", level: "info", message });
|
|
552
|
+
});
|
|
553
|
+
};
|
|
554
|
+
win.document.addEventListener("click", onClick, true);
|
|
555
|
+
return () => {
|
|
556
|
+
win.document.removeEventListener("click", onClick, true);
|
|
557
|
+
return true;
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// src/instrument/fetch.ts
|
|
562
|
+
function describe2(input, init2) {
|
|
563
|
+
const isRequest = typeof Request !== "undefined" && input instanceof Request;
|
|
564
|
+
let url;
|
|
565
|
+
if (isRequest) url = input.url;
|
|
566
|
+
else if (input instanceof URL) url = input.href;
|
|
567
|
+
else url = String(input);
|
|
568
|
+
const method = init2?.method ?? (isRequest ? input.method : "GET");
|
|
569
|
+
return { method, url };
|
|
570
|
+
}
|
|
571
|
+
function instrumentFetch(win, record, opts) {
|
|
572
|
+
return wrap(
|
|
573
|
+
win,
|
|
574
|
+
"fetch",
|
|
575
|
+
(original) => async function __tlmWrapped(input, init2) {
|
|
576
|
+
const promise = original.apply(this, arguments);
|
|
577
|
+
let done = (_status) => void 0;
|
|
578
|
+
safeRecord(() => {
|
|
579
|
+
const { method, url } = describe2(input, init2);
|
|
580
|
+
if (opts.skipUrl(absoluteUrl(win, url))) return;
|
|
581
|
+
const shown = displayUrl(win, url, opts.stripQuery);
|
|
582
|
+
const timing = timeRequest(opts, win, method, url);
|
|
583
|
+
done = (status) => {
|
|
584
|
+
safeRecord(() => {
|
|
585
|
+
timing(status);
|
|
586
|
+
record({ category: "fetch", level: levelForStatus(status), message: requestMessage(method, shown, status) });
|
|
587
|
+
});
|
|
588
|
+
};
|
|
589
|
+
});
|
|
590
|
+
return promise.then(
|
|
591
|
+
(response) => {
|
|
592
|
+
done(response.status);
|
|
593
|
+
return response;
|
|
594
|
+
},
|
|
595
|
+
(error) => {
|
|
596
|
+
done(void 0);
|
|
597
|
+
throw error;
|
|
598
|
+
}
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// src/instrument/history.ts
|
|
605
|
+
function instrumentHistory(win, record, opts) {
|
|
606
|
+
const here = () => {
|
|
607
|
+
const shown = displayUrl(win, win.location.href, opts.stripQuery);
|
|
608
|
+
const { hash } = win.location;
|
|
609
|
+
if (!opts.stripQuery || !/^#!?\//.test(hash)) return shown;
|
|
610
|
+
return `${shown}#${stripUrl(hash.slice(1))}`;
|
|
611
|
+
};
|
|
612
|
+
let last = here();
|
|
613
|
+
const moved = () => {
|
|
614
|
+
safeRecord(() => {
|
|
615
|
+
const to = here();
|
|
616
|
+
if (to === last) return;
|
|
617
|
+
record({ category: "navigation", level: "info", message: `${last} \u2192 ${to}` });
|
|
618
|
+
last = to;
|
|
619
|
+
});
|
|
620
|
+
};
|
|
621
|
+
const wrapState = (name) => wrap(
|
|
622
|
+
win.history,
|
|
623
|
+
name,
|
|
624
|
+
(original) => function __tlmWrapped(...args) {
|
|
625
|
+
original.apply(this, args);
|
|
626
|
+
moved();
|
|
627
|
+
navigated();
|
|
628
|
+
}
|
|
629
|
+
);
|
|
630
|
+
const navigated = () => {
|
|
631
|
+
safeRecord(() => {
|
|
632
|
+
opts.onNavigate?.();
|
|
633
|
+
});
|
|
634
|
+
};
|
|
635
|
+
const popped = () => {
|
|
636
|
+
moved();
|
|
637
|
+
navigated();
|
|
638
|
+
};
|
|
639
|
+
const restores = [wrapState("pushState"), wrapState("replaceState")];
|
|
640
|
+
win.addEventListener("popstate", popped);
|
|
641
|
+
win.addEventListener("hashchange", moved);
|
|
642
|
+
return () => {
|
|
643
|
+
if (!restores.map((restore) => restore()).every(Boolean)) return false;
|
|
644
|
+
win.removeEventListener("popstate", popped);
|
|
645
|
+
win.removeEventListener("hashchange", moved);
|
|
646
|
+
return true;
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/instrument/xhr.ts
|
|
651
|
+
function instrumentXhr(win, record, opts) {
|
|
652
|
+
const Xhr = win.XMLHttpRequest;
|
|
653
|
+
if (!Xhr) return () => true;
|
|
654
|
+
const proto = Xhr.prototype;
|
|
655
|
+
const requests = /* @__PURE__ */ new WeakMap();
|
|
656
|
+
const restoreOpen = wrap(
|
|
657
|
+
proto,
|
|
658
|
+
"open",
|
|
659
|
+
(original) => function __tlmWrapped(...args) {
|
|
660
|
+
safeRecord(() => {
|
|
661
|
+
const [method, url] = args;
|
|
662
|
+
requests.set(this, { method: String(method), url: url instanceof URL ? url.href : String(url) });
|
|
663
|
+
});
|
|
664
|
+
original.apply(this, args);
|
|
665
|
+
}
|
|
666
|
+
);
|
|
667
|
+
const restoreSend = wrap(
|
|
668
|
+
proto,
|
|
669
|
+
"send",
|
|
670
|
+
(original) => function __tlmWrapped(body) {
|
|
671
|
+
safeRecord(() => {
|
|
672
|
+
const request = requests.get(this);
|
|
673
|
+
if (!request || opts.skipUrl(absoluteUrl(win, request.url))) return;
|
|
674
|
+
const shown = displayUrl(win, request.url, opts.stripQuery);
|
|
675
|
+
const timing = timeRequest(opts, win, request.method, request.url);
|
|
676
|
+
this.addEventListener("loadend", () => {
|
|
677
|
+
safeRecord(() => {
|
|
678
|
+
const status = this.status !== 0 ? this.status : void 0;
|
|
679
|
+
timing(status);
|
|
680
|
+
record({ category: "xhr", level: levelForStatus(status), message: requestMessage(request.method, shown, status) });
|
|
681
|
+
});
|
|
682
|
+
}, { once: true });
|
|
683
|
+
});
|
|
684
|
+
original.call(this, body);
|
|
685
|
+
}
|
|
686
|
+
);
|
|
687
|
+
return () => [restoreOpen(), restoreSend()].every(Boolean);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// src/logger.ts
|
|
691
|
+
function createLogger(isDebug) {
|
|
692
|
+
const warned = /* @__PURE__ */ new Set();
|
|
693
|
+
const { debug, info, warn } = console;
|
|
694
|
+
return {
|
|
695
|
+
debug(...args) {
|
|
696
|
+
if (isDebug()) debug.call(console, "[tlm]", ...args);
|
|
697
|
+
},
|
|
698
|
+
warnOnce(message) {
|
|
699
|
+
if (warned.has(message)) return;
|
|
700
|
+
warned.add(message);
|
|
701
|
+
warn.call(console, `[tlm] ${message}`);
|
|
702
|
+
},
|
|
703
|
+
info(message) {
|
|
704
|
+
info.call(console, `[tlm] ${message}`);
|
|
705
|
+
},
|
|
706
|
+
warn(message) {
|
|
707
|
+
warn.call(console, `[tlm] ${message}`);
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// src/scope.ts
|
|
713
|
+
var BREADCRUMB_MESSAGE_LENGTH = 500;
|
|
714
|
+
var Scope = class {
|
|
715
|
+
constructor() {
|
|
716
|
+
this.tags = {};
|
|
717
|
+
this.breadcrumbs = [];
|
|
718
|
+
}
|
|
719
|
+
setUser(user) {
|
|
720
|
+
this.user = user ? { id: String(user.id) } : void 0;
|
|
721
|
+
}
|
|
722
|
+
setTag(key, value) {
|
|
723
|
+
this.tags[key] = String(value);
|
|
724
|
+
}
|
|
725
|
+
setTags(tags) {
|
|
726
|
+
for (const [key, value] of Object.entries(tags)) this.setTag(key, value);
|
|
727
|
+
}
|
|
728
|
+
addBreadcrumb(crumb, max) {
|
|
729
|
+
this.breadcrumbs.push({
|
|
730
|
+
...crumb,
|
|
731
|
+
timestamp: crumb.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
732
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-conversion -- plain-JS callers
|
|
733
|
+
message: truncate(String(crumb.message), BREADCRUMB_MESSAGE_LENGTH)
|
|
734
|
+
});
|
|
735
|
+
if (this.breadcrumbs.length > max) this.breadcrumbs.splice(0, this.breadcrumbs.length - max);
|
|
736
|
+
}
|
|
737
|
+
/** Oldest first. */
|
|
738
|
+
getBreadcrumbs() {
|
|
739
|
+
return this.breadcrumbs.map((c) => ({ ...c }));
|
|
740
|
+
}
|
|
741
|
+
clear() {
|
|
742
|
+
this.user = void 0;
|
|
743
|
+
this.tags = {};
|
|
744
|
+
this.breadcrumbs = [];
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
|
|
748
|
+
// src/transport.ts
|
|
749
|
+
function answer(pending, result) {
|
|
750
|
+
const { onAnswer } = pending;
|
|
751
|
+
pending.onAnswer = void 0;
|
|
752
|
+
onAnswer?.(result);
|
|
753
|
+
}
|
|
754
|
+
var FIRST_BACKOFF = 1e3;
|
|
755
|
+
var MAX_BACKOFF = 6e4;
|
|
756
|
+
var MAX_ATTEMPTS = 8;
|
|
757
|
+
var DEFAULT_PAUSE = 60;
|
|
758
|
+
var KEEPALIVE_LIMIT = 6e4;
|
|
759
|
+
var MAX_BODY = 1e6;
|
|
760
|
+
var FRAMES_WHEN_TOO_BIG = 50;
|
|
761
|
+
var encoder = new TextEncoder();
|
|
762
|
+
var byteLength = (s) => encoder.encode(s).length;
|
|
763
|
+
var Transport = class {
|
|
764
|
+
constructor(deps) {
|
|
765
|
+
this.deps = deps;
|
|
766
|
+
this.disabled = false;
|
|
767
|
+
this.queue = [];
|
|
768
|
+
this.inFlight = false;
|
|
769
|
+
this.paused = false;
|
|
770
|
+
this.backoff = FIRST_BACKOFF;
|
|
771
|
+
this.inFlightKeepaliveBytes = 0;
|
|
772
|
+
this.idleWaiters = [];
|
|
773
|
+
this.maxQueue = deps.maxQueue ?? 30;
|
|
774
|
+
}
|
|
775
|
+
/** Queues the event. Never blocks, never throws. `onAnswer` gets the first attempt's answer. */
|
|
776
|
+
send(event, onAnswer) {
|
|
777
|
+
if (this.disabled) return;
|
|
778
|
+
if (this.queue.length >= this.maxQueue) {
|
|
779
|
+
const dropped = this.queue.shift();
|
|
780
|
+
if (dropped) answer(dropped, { error: new Error("dropped: too many events queued") });
|
|
781
|
+
this.deps.logger.debug("queue full, dropped the oldest event");
|
|
782
|
+
}
|
|
783
|
+
this.queue.push({ event, attempts: 0, ...onAnswer ? { onAnswer } : {} });
|
|
784
|
+
this.dispatch();
|
|
785
|
+
}
|
|
786
|
+
/** Resolves `true` once everything queued has been sent (or given up on), `false` after `timeoutMs`. */
|
|
787
|
+
async flush(timeoutMs = 2e3) {
|
|
788
|
+
if (this.isIdle()) return Promise.resolve(true);
|
|
789
|
+
return new Promise((resolve) => {
|
|
790
|
+
const timer = setTimeout(() => {
|
|
791
|
+
this.idleWaiters = this.idleWaiters.filter((w) => w !== done);
|
|
792
|
+
resolve(false);
|
|
793
|
+
}, timeoutMs);
|
|
794
|
+
const done = () => {
|
|
795
|
+
clearTimeout(timer);
|
|
796
|
+
resolve(true);
|
|
797
|
+
};
|
|
798
|
+
this.idleWaiters.push(done);
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* The page is going away: send everything queued at once, with keepalive
|
|
803
|
+
* while the browser's 64 KB budget lasts. Answers are ignored.
|
|
804
|
+
*/
|
|
805
|
+
sendQueuedNow() {
|
|
806
|
+
if (this.disabled || this.paused) return;
|
|
807
|
+
let budget = KEEPALIVE_LIMIT - this.inFlightKeepaliveBytes;
|
|
808
|
+
for (const { event } of this.queue.splice(0)) {
|
|
809
|
+
const body = encode(event);
|
|
810
|
+
if (body === void 0) continue;
|
|
811
|
+
const size = byteLength(body);
|
|
812
|
+
const keepalive = size <= budget;
|
|
813
|
+
if (keepalive) budget -= size;
|
|
814
|
+
try {
|
|
815
|
+
this.deps.fetch(this.deps.url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive, credentials: "omit" }).catch(() => void 0);
|
|
816
|
+
} catch {
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
this.notifyIfIdle();
|
|
820
|
+
}
|
|
821
|
+
isIdle() {
|
|
822
|
+
return !this.inFlight && (this.queue.length === 0 || this.disabled);
|
|
823
|
+
}
|
|
824
|
+
dispatch() {
|
|
825
|
+
const pending = this.inFlight || this.paused || this.disabled ? void 0 : this.queue.shift();
|
|
826
|
+
if (!pending) {
|
|
827
|
+
this.notifyIfIdle();
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
const body = encode(pending.event);
|
|
831
|
+
if (body === void 0) {
|
|
832
|
+
this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable", pending.event.uuid);
|
|
833
|
+
answer(pending, { error: new Error("dropped: over 1 MB or not JSON-encodable") });
|
|
834
|
+
this.dispatch();
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
this.inFlight = true;
|
|
838
|
+
const size = byteLength(body);
|
|
839
|
+
const keepalive = size <= KEEPALIVE_LIMIT;
|
|
840
|
+
this.inFlightKeepaliveBytes = keepalive ? size : 0;
|
|
841
|
+
let request;
|
|
842
|
+
try {
|
|
843
|
+
request = this.deps.fetch(this.deps.url, {
|
|
844
|
+
method: "POST",
|
|
845
|
+
body,
|
|
846
|
+
headers: { "Content-Type": "text/plain;charset=UTF-8" },
|
|
847
|
+
keepalive,
|
|
848
|
+
credentials: "omit"
|
|
849
|
+
});
|
|
850
|
+
} catch (error) {
|
|
851
|
+
request = Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
852
|
+
}
|
|
853
|
+
request.then(
|
|
854
|
+
(response) => {
|
|
855
|
+
this.handle(pending, response);
|
|
856
|
+
},
|
|
857
|
+
(error) => {
|
|
858
|
+
this.retry(pending, error);
|
|
859
|
+
}
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
handle(pending, response) {
|
|
863
|
+
this.inFlight = false;
|
|
864
|
+
this.inFlightKeepaliveBytes = 0;
|
|
865
|
+
const { status } = response;
|
|
866
|
+
answer(pending, { status });
|
|
867
|
+
if (status >= 200 && status < 300) {
|
|
868
|
+
this.backoff = FIRST_BACKOFF;
|
|
869
|
+
} else if (status === 429) {
|
|
870
|
+
this.backoff = FIRST_BACKOFF;
|
|
871
|
+
this.pause(retryAfter(response.headers.get("Retry-After")) * 1e3);
|
|
872
|
+
} else if (status === 401 || status === 403) {
|
|
873
|
+
this.disable(status);
|
|
874
|
+
} else if (status >= 500) {
|
|
875
|
+
this.retry(pending, `HTTP ${String(status)}`);
|
|
876
|
+
return;
|
|
877
|
+
} else {
|
|
878
|
+
const { logger } = this.deps;
|
|
879
|
+
response.text().then(
|
|
880
|
+
(body) => {
|
|
881
|
+
logger.debug(`Tlm rejected an event (HTTP ${String(status)})`, pending.event.uuid, body);
|
|
882
|
+
},
|
|
883
|
+
() => {
|
|
884
|
+
logger.debug(`Tlm rejected an event (HTTP ${String(status)})`, pending.event.uuid);
|
|
885
|
+
}
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
this.dispatch();
|
|
889
|
+
}
|
|
890
|
+
retry(pending, error) {
|
|
891
|
+
answer(pending, { error });
|
|
892
|
+
this.inFlight = false;
|
|
893
|
+
this.inFlightKeepaliveBytes = 0;
|
|
894
|
+
pending.attempts += 1;
|
|
895
|
+
if (pending.attempts >= MAX_ATTEMPTS) {
|
|
896
|
+
this.deps.logger.debug(`gave up on an event after ${String(pending.attempts)} tries`, error);
|
|
897
|
+
} else {
|
|
898
|
+
this.deps.logger.debug("sending failed, will retry", error);
|
|
899
|
+
this.queue.unshift(pending);
|
|
900
|
+
}
|
|
901
|
+
const wait = this.backoff;
|
|
902
|
+
this.backoff = Math.min(this.backoff * 2, MAX_BACKOFF);
|
|
903
|
+
this.pause(wait);
|
|
904
|
+
}
|
|
905
|
+
pause(ms) {
|
|
906
|
+
this.paused = true;
|
|
907
|
+
setTimeout(() => {
|
|
908
|
+
this.paused = false;
|
|
909
|
+
this.dispatch();
|
|
910
|
+
}, ms);
|
|
911
|
+
}
|
|
912
|
+
disable(status) {
|
|
913
|
+
this.disabled = true;
|
|
914
|
+
for (const pending of this.queue.splice(0)) answer(pending, { error: new Error(`dropped: Tlm rejected this DSN (HTTP ${String(status)})`) });
|
|
915
|
+
this.deps.onDisable?.();
|
|
916
|
+
const where = this.deps.origin ?? "unknown origin";
|
|
917
|
+
this.deps.logger.warnOnce(
|
|
918
|
+
status === 401 ? "Tlm rejected the key (HTTP 401): check the DSN on your project's setup page. Nothing more will be sent from this page." : `This site's domain (${where}) is blocked for this project in Tlm (HTTP 403). Events won't be sent from this page. A project admin can unblock it in the project's settings.`
|
|
919
|
+
);
|
|
920
|
+
}
|
|
921
|
+
notifyIfIdle() {
|
|
922
|
+
if (!this.isIdle()) return;
|
|
923
|
+
const waiters = this.idleWaiters;
|
|
924
|
+
this.idleWaiters = [];
|
|
925
|
+
for (const w of waiters) w();
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
function retryAfter(header) {
|
|
929
|
+
const seconds = Number.parseInt(header ?? "", 10);
|
|
930
|
+
return seconds >= 0 ? seconds : DEFAULT_PAUSE;
|
|
931
|
+
}
|
|
932
|
+
function encode(event) {
|
|
933
|
+
try {
|
|
934
|
+
return encodeWithin(event);
|
|
935
|
+
} catch {
|
|
936
|
+
return void 0;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
function encodeWithin(event) {
|
|
940
|
+
let body = JSON.stringify(event);
|
|
941
|
+
if (byteLength(body) <= MAX_BODY) return body;
|
|
942
|
+
const trimmed = { ...event };
|
|
943
|
+
delete trimmed.breadcrumbs;
|
|
944
|
+
body = JSON.stringify(trimmed);
|
|
945
|
+
if (byteLength(body) <= MAX_BODY) return body;
|
|
946
|
+
if (trimmed.exception?.frames) {
|
|
947
|
+
trimmed.exception = { ...trimmed.exception, frames: trimmed.exception.frames.slice(0, FRAMES_WHEN_TOO_BIG) };
|
|
948
|
+
body = JSON.stringify(trimmed);
|
|
949
|
+
if (byteLength(body) <= MAX_BODY) return body;
|
|
950
|
+
}
|
|
951
|
+
return void 0;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
// src/client.ts
|
|
955
|
+
var INSTRUMENTS = {
|
|
956
|
+
console: instrumentConsole,
|
|
957
|
+
dom: instrumentDom,
|
|
958
|
+
fetch: instrumentFetch,
|
|
959
|
+
xhr: instrumentXhr,
|
|
960
|
+
history: instrumentHistory
|
|
961
|
+
};
|
|
962
|
+
var DEFAULT_MAX_BREADCRUMBS = 50;
|
|
963
|
+
var OWN_URL = void 0;
|
|
964
|
+
var TEST_TIMEOUT_MS = 1e4;
|
|
965
|
+
function testFailure(result) {
|
|
966
|
+
if ("error" in result) {
|
|
967
|
+
const message = result.error instanceof Error ? result.error.message : String(result.error);
|
|
968
|
+
return `couldn't reach Tlm (${message}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;
|
|
969
|
+
}
|
|
970
|
+
const { status } = result;
|
|
971
|
+
if (status >= 200 && status < 300) return void 0;
|
|
972
|
+
if (status === 401) return "Tlm rejected the key (HTTP 401). Check the DSN on your project's setup page.";
|
|
973
|
+
if (status === 403) return "this site's domain is blocked for the project (HTTP 403). A project admin can unblock it in the project's settings.";
|
|
974
|
+
if (status === 429) return "Tlm asked to slow down (HTTP 429). Try again in a minute.";
|
|
975
|
+
if (status >= 500) return `Tlm had an error (HTTP ${String(status)}). The event will be retried.`;
|
|
976
|
+
return `Tlm rejected the event (HTTP ${String(status)}).`;
|
|
977
|
+
}
|
|
978
|
+
var active;
|
|
979
|
+
var installed = /* @__PURE__ */ new Map();
|
|
980
|
+
var sharedOptions = {
|
|
981
|
+
skipUrl: (url) => active?.isOwnUrl(url) ?? false,
|
|
982
|
+
get stripQuery() {
|
|
983
|
+
return active?.options.stripQuery !== false;
|
|
984
|
+
},
|
|
985
|
+
onRequestStart: () => active?.rum?.requestStart(),
|
|
986
|
+
onRequest: (timing, token) => {
|
|
987
|
+
active?.rum?.request(timing, token);
|
|
988
|
+
},
|
|
989
|
+
onNavigate: () => {
|
|
990
|
+
active?.rum?.navigate();
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
var RUM_KINDS = /* @__PURE__ */ new Set(["fetch", "xhr", "history"]);
|
|
994
|
+
var rejected = /* @__PURE__ */ new Set();
|
|
995
|
+
var recorderFor = (kind) => (crumb) => {
|
|
996
|
+
if (active && active.options.breadcrumbs?.[kind] !== false) active.addBreadcrumb(crumb);
|
|
997
|
+
};
|
|
998
|
+
function unwrapped(fn) {
|
|
999
|
+
return fn.__tlm_original__ ?? fn;
|
|
1000
|
+
}
|
|
1001
|
+
var Client = class {
|
|
1002
|
+
constructor(options, win, scope2 = new Scope()) {
|
|
1003
|
+
this.options = options;
|
|
1004
|
+
this.win = win;
|
|
1005
|
+
this.scope = scope2;
|
|
1006
|
+
this.cleanups = [];
|
|
1007
|
+
this.deduper = new Deduper();
|
|
1008
|
+
this.rateGuard = new RateGuard();
|
|
1009
|
+
this.closed = false;
|
|
1010
|
+
this.logger = createLogger(() => options.debug === true);
|
|
1011
|
+
this.ignore = [...DEFAULT_IGNORE, ...options.ignoreErrors ?? []];
|
|
1012
|
+
if (options.enabled === false) {
|
|
1013
|
+
this.logger.debug("disabled (enabled: false): nothing will be sent");
|
|
1014
|
+
this.inactive = "the SDK is off (enabled: false).";
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
if (typeof options.dsn !== "string" || options.dsn === "") {
|
|
1018
|
+
this.logger.debug("no DSN given: nothing will be sent");
|
|
1019
|
+
this.inactive = `no DSN given to init() or in <meta name="tlm-dsn">.`;
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
const endpoint = parseDsn(options.dsn);
|
|
1023
|
+
if (!endpoint) {
|
|
1024
|
+
this.logger.debug("invalid DSN: nothing will be sent", options.dsn);
|
|
1025
|
+
this.inactive = "invalid DSN. Copy it from your project's setup page.";
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
this.endpointBase = endpoint.base;
|
|
1029
|
+
const fetchFn = unwrapped(win.fetch).bind(win);
|
|
1030
|
+
const { url } = endpoint;
|
|
1031
|
+
this.transport = new Transport({ url, fetch: fetchFn, logger: this.logger, origin: win.location.origin, onDisable: () => rejected.add(url) });
|
|
1032
|
+
if (rejected.has(url)) {
|
|
1033
|
+
this.transport.disabled = true;
|
|
1034
|
+
this.logger.debug("Tlm already rejected this DSN on this page: nothing will be sent");
|
|
1035
|
+
} else if (options.heartbeat !== false) {
|
|
1036
|
+
this.cleanups.push(scheduleHeartbeat({ url: endpoint.heartbeatUrl, key: endpoint.key, fetch: fetchFn, options, logger: this.logger }));
|
|
1037
|
+
}
|
|
1038
|
+
const auto = options.autoCapture;
|
|
1039
|
+
if (auto !== false) {
|
|
1040
|
+
this.cleanups.push(
|
|
1041
|
+
installGlobalHandlers(
|
|
1042
|
+
win,
|
|
1043
|
+
(error, mechanism) => this.captureException(error, void 0, mechanism),
|
|
1044
|
+
{ onerror: auto?.onerror !== false, onunhandledrejection: auto?.onunhandledrejection !== false }
|
|
1045
|
+
)
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
if (options.rum && !this.transport.disabled) {
|
|
1049
|
+
try {
|
|
1050
|
+
this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.2.0" }, environment: environmentOf(options), release: releaseOf(options) });
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
this.logger.debug("RUM didn't start", error);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
active = this;
|
|
1056
|
+
for (const [kind, instrument] of Object.entries(INSTRUMENTS)) {
|
|
1057
|
+
const needed = options.breadcrumbs?.[kind] !== false || this.rum !== void 0 && RUM_KINDS.has(kind);
|
|
1058
|
+
if (!needed || installed.has(kind)) continue;
|
|
1059
|
+
try {
|
|
1060
|
+
installed.set(kind, instrument(win, recorderFor(kind), sharedOptions));
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
this.logger.debug(`couldn't record ${kind} breadcrumbs`, error);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
this.isDependency = importmapDependencies(win.document, win.location.href);
|
|
1066
|
+
this.followMeta();
|
|
1067
|
+
const onTurboLoad = () => {
|
|
1068
|
+
this.rum?.navigate();
|
|
1069
|
+
this.followMeta();
|
|
1070
|
+
};
|
|
1071
|
+
win.document.addEventListener("turbo:load", onTurboLoad);
|
|
1072
|
+
this.cleanups.push(() => {
|
|
1073
|
+
win.document.removeEventListener("turbo:load", onTurboLoad);
|
|
1074
|
+
});
|
|
1075
|
+
const onPageHide = () => {
|
|
1076
|
+
this.transport?.sendQueuedNow();
|
|
1077
|
+
};
|
|
1078
|
+
win.addEventListener("pagehide", onPageHide);
|
|
1079
|
+
this.cleanups.push(() => {
|
|
1080
|
+
win.removeEventListener("pagehide", onPageHide);
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
captureException(error, ctx, mechanism = "manual") {
|
|
1084
|
+
return this.capture(() => eventFromException(error, this.env(), ctx, mechanism));
|
|
1085
|
+
}
|
|
1086
|
+
captureMessage(message, ctx) {
|
|
1087
|
+
const context = typeof ctx === "string" ? { level: ctx } : ctx;
|
|
1088
|
+
return this.capture(() => eventFromMessage(message, this.env(), context));
|
|
1089
|
+
}
|
|
1090
|
+
/**
|
|
1091
|
+
* Sends one test error to check the setup end to end. Skips the filters
|
|
1092
|
+
* (ignoreErrors, duplicates, the rate cap); `beforeSend` edits apply, but
|
|
1093
|
+
* if it drops the event the original is sent anyway.
|
|
1094
|
+
*/
|
|
1095
|
+
async test() {
|
|
1096
|
+
const fail = (reason) => {
|
|
1097
|
+
this.logger.warn(`Test event not sent: ${reason}`);
|
|
1098
|
+
return { ok: false, reason };
|
|
1099
|
+
};
|
|
1100
|
+
const { transport } = this;
|
|
1101
|
+
if (this.closed) return Promise.resolve(fail("the SDK was closed."));
|
|
1102
|
+
if (!transport) return Promise.resolve(fail(this.inactive ?? "the SDK isn't sending."));
|
|
1103
|
+
if (transport.disabled) return Promise.resolve(fail("Tlm already rejected this DSN on this page (HTTP 401/403)."));
|
|
1104
|
+
let event;
|
|
1105
|
+
try {
|
|
1106
|
+
const error = new Error("Test event from Tlm.test(). If you can see it in Tlm, your setup works.");
|
|
1107
|
+
error.name = "TlmTest";
|
|
1108
|
+
throw error;
|
|
1109
|
+
} catch (error) {
|
|
1110
|
+
event = eventFromException(error, this.env(), { tags: { "tlm.test": "true" }, fingerprint: ["tlm.test"] });
|
|
1111
|
+
}
|
|
1112
|
+
const final = this.beforeSend(event) ?? event;
|
|
1113
|
+
return new Promise((resolve) => {
|
|
1114
|
+
let settled = false;
|
|
1115
|
+
const settle = (result) => {
|
|
1116
|
+
if (settled) return;
|
|
1117
|
+
settled = true;
|
|
1118
|
+
clearTimeout(timer);
|
|
1119
|
+
resolve(result);
|
|
1120
|
+
};
|
|
1121
|
+
const timer = setTimeout(() => {
|
|
1122
|
+
settle(fail(`no answer from Tlm within ${String(TEST_TIMEOUT_MS / 1e3)} s.`));
|
|
1123
|
+
}, TEST_TIMEOUT_MS);
|
|
1124
|
+
transport.send(final, (answer2) => {
|
|
1125
|
+
if (settled) return;
|
|
1126
|
+
const reason = testFailure(answer2);
|
|
1127
|
+
if (reason !== void 0) {
|
|
1128
|
+
settle(fail(reason));
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
this.logger.info(`Test event sent (${"status" in answer2 ? String(answer2.status) : "?"}). Look for "TlmTest" in your project: ${final.uuid}`);
|
|
1132
|
+
settle({ ok: true, id: final.uuid });
|
|
1133
|
+
});
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
addBreadcrumb(crumb) {
|
|
1137
|
+
this.scope.addBreadcrumb(crumb, this.options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS);
|
|
1138
|
+
}
|
|
1139
|
+
async flush(timeoutMs) {
|
|
1140
|
+
return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
|
|
1141
|
+
}
|
|
1142
|
+
/** Names the current RUM page view. Does nothing without RUM. */
|
|
1143
|
+
setRoute(name) {
|
|
1144
|
+
this.rum?.setRoute(name);
|
|
1145
|
+
}
|
|
1146
|
+
/** True for requests to Tlm itself. */
|
|
1147
|
+
isOwnUrl(url) {
|
|
1148
|
+
return this.endpointBase !== void 0 && url.startsWith(`${this.endpointBase}/`);
|
|
1149
|
+
}
|
|
1150
|
+
/** Removes every listener and wrapper it can. Events already queued still go out. */
|
|
1151
|
+
close() {
|
|
1152
|
+
this.closed = true;
|
|
1153
|
+
try {
|
|
1154
|
+
this.rum?.close();
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
this.logger.debug("RUM didn't close cleanly", error);
|
|
1157
|
+
}
|
|
1158
|
+
if (active === this) {
|
|
1159
|
+
active = void 0;
|
|
1160
|
+
for (const [kind, restore] of installed) {
|
|
1161
|
+
try {
|
|
1162
|
+
if (restore()) installed.delete(kind);
|
|
1163
|
+
} catch {
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
for (const cleanup of this.cleanups.splice(0).reverse()) {
|
|
1168
|
+
try {
|
|
1169
|
+
cleanup();
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
this.logger.debug("cleanup failed", error);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
/** The page's user and route from its meta tags. A user the app set itself is left alone. */
|
|
1176
|
+
followMeta() {
|
|
1177
|
+
const doc = this.win.document;
|
|
1178
|
+
const user = metaContent(doc, "user");
|
|
1179
|
+
const current = this.scope.user?.id;
|
|
1180
|
+
if (current === void 0 || current === this.metaUser) this.scope.setUser(user === void 0 ? null : { id: user });
|
|
1181
|
+
this.metaUser = user;
|
|
1182
|
+
const route = metaContent(doc, "route");
|
|
1183
|
+
if (route !== void 0) this.setRoute(route);
|
|
1184
|
+
}
|
|
1185
|
+
env() {
|
|
1186
|
+
const { win } = this;
|
|
1187
|
+
return {
|
|
1188
|
+
options: this.options,
|
|
1189
|
+
scope: this.scope,
|
|
1190
|
+
origin: win.location.origin,
|
|
1191
|
+
href: win.location.href,
|
|
1192
|
+
userAgent: win.navigator.userAgent,
|
|
1193
|
+
session: this.rum?.session,
|
|
1194
|
+
isDependency: this.isDependency,
|
|
1195
|
+
ownUrl: OWN_URL
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
capture(build) {
|
|
1199
|
+
const transport = this.transport;
|
|
1200
|
+
if (!transport || this.closed || transport.disabled) return void 0;
|
|
1201
|
+
const event = build();
|
|
1202
|
+
if (shouldIgnore(event, this.ignore)) {
|
|
1203
|
+
this.logger.debug("ignored", event.exception?.type ?? event.message);
|
|
1204
|
+
return void 0;
|
|
1205
|
+
}
|
|
1206
|
+
const now = Date.now();
|
|
1207
|
+
if (this.deduper.isDuplicate(event, now)) return void 0;
|
|
1208
|
+
const final = this.beforeSend(event);
|
|
1209
|
+
if (!final) return void 0;
|
|
1210
|
+
if (!this.rateGuard.take(now)) {
|
|
1211
|
+
this.logger.debug("too many events, dropped one");
|
|
1212
|
+
return void 0;
|
|
1213
|
+
}
|
|
1214
|
+
transport.send(final);
|
|
1215
|
+
return final.uuid;
|
|
1216
|
+
}
|
|
1217
|
+
beforeSend(event) {
|
|
1218
|
+
const hook = this.options.beforeSend;
|
|
1219
|
+
if (!hook) return event;
|
|
1220
|
+
let result;
|
|
1221
|
+
try {
|
|
1222
|
+
result = hook(event);
|
|
1223
|
+
} catch (error) {
|
|
1224
|
+
this.logger.debug("beforeSend threw; sending the event unchanged", error);
|
|
1225
|
+
return event;
|
|
1226
|
+
}
|
|
1227
|
+
if (result === null) return void 0;
|
|
1228
|
+
if ((typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
|
|
1229
|
+
this.logger.warnOnce("beforeSend returned a Promise, so the event was dropped. It must return the event (or null) right away, not async.");
|
|
1230
|
+
return void 0;
|
|
1231
|
+
}
|
|
1232
|
+
if (typeof result !== "object" || Array.isArray(result) || !("uuid" in result) || typeof result.uuid !== "string") {
|
|
1233
|
+
this.logger.debug("beforeSend returned neither an event nor null; dropped", result);
|
|
1234
|
+
return void 0;
|
|
1235
|
+
}
|
|
1236
|
+
return result;
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
|
|
1240
|
+
// src/index.ts
|
|
1241
|
+
var SDK_VERSION = "0.2.0";
|
|
1242
|
+
var client;
|
|
1243
|
+
var pendingRoute;
|
|
1244
|
+
var pendingScope = new Scope();
|
|
1245
|
+
function scope() {
|
|
1246
|
+
return client?.scope ?? pendingScope;
|
|
1247
|
+
}
|
|
1248
|
+
function safely(fn, fallback) {
|
|
1249
|
+
try {
|
|
1250
|
+
return fn();
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
client?.logger.debug("internal error", error);
|
|
1253
|
+
return fallback;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
function withMeta(options, doc) {
|
|
1257
|
+
return {
|
|
1258
|
+
...options,
|
|
1259
|
+
dsn: options.dsn ?? metaContent(doc, "dsn"),
|
|
1260
|
+
environment: options.environment ?? metaContent(doc, "environment"),
|
|
1261
|
+
release: options.release ?? metaContent(doc, "release")
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
function init(options = {}) {
|
|
1265
|
+
safely(() => {
|
|
1266
|
+
if (typeof window === "undefined") return;
|
|
1267
|
+
const kept = scope();
|
|
1268
|
+
client?.close();
|
|
1269
|
+
client = new Client(withMeta(options, window.document), window, kept);
|
|
1270
|
+
if (pendingRoute) client.setRoute(pendingRoute.name);
|
|
1271
|
+
pendingRoute = void 0;
|
|
1272
|
+
if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
|
|
1273
|
+
else Reflect.deleteProperty(window, CONSOLE_HANDLE);
|
|
1274
|
+
}, void 0);
|
|
1275
|
+
}
|
|
1276
|
+
var CONSOLE_HANDLE = "__tlm";
|
|
1277
|
+
async function test() {
|
|
1278
|
+
const notInitialized = () => {
|
|
1279
|
+
const reason = "init() hasn't run on this page (or this isn't a browser).";
|
|
1280
|
+
console.warn(`[tlm] Test event not sent: ${reason}`);
|
|
1281
|
+
return { ok: false, reason };
|
|
1282
|
+
};
|
|
1283
|
+
return safely(async () => client ? client.test() : Promise.resolve(notInitialized()), Promise.resolve({ ok: false, reason: "internal error." }));
|
|
1284
|
+
}
|
|
1285
|
+
function captureException(error, context) {
|
|
1286
|
+
return safely(() => client?.captureException(error, context), void 0);
|
|
1287
|
+
}
|
|
1288
|
+
function captureMessage(message, context) {
|
|
1289
|
+
return safely(() => client?.captureMessage(message, context), void 0);
|
|
1290
|
+
}
|
|
1291
|
+
function setUser(user) {
|
|
1292
|
+
safely(() => {
|
|
1293
|
+
scope().setUser(user);
|
|
1294
|
+
}, void 0);
|
|
1295
|
+
}
|
|
1296
|
+
function setTag(key, value) {
|
|
1297
|
+
safely(() => {
|
|
1298
|
+
scope().setTag(key, value);
|
|
1299
|
+
}, void 0);
|
|
1300
|
+
}
|
|
1301
|
+
function setTags(tags) {
|
|
1302
|
+
safely(() => {
|
|
1303
|
+
scope().setTags(tags);
|
|
1304
|
+
}, void 0);
|
|
1305
|
+
}
|
|
1306
|
+
function addBreadcrumb(crumb) {
|
|
1307
|
+
safely(() => {
|
|
1308
|
+
if (client) client.addBreadcrumb(crumb);
|
|
1309
|
+
else pendingScope.addBreadcrumb(crumb, 50);
|
|
1310
|
+
}, void 0);
|
|
1311
|
+
}
|
|
1312
|
+
async function flush(timeoutMs) {
|
|
1313
|
+
return safely(async () => client?.flush(timeoutMs) ?? Promise.resolve(true), Promise.resolve(false));
|
|
1314
|
+
}
|
|
1315
|
+
function setRoute(name) {
|
|
1316
|
+
safely(() => {
|
|
1317
|
+
if (client) client.setRoute(name);
|
|
1318
|
+
else pendingRoute = { name };
|
|
1319
|
+
}, void 0);
|
|
1320
|
+
}
|
|
1321
|
+
function close() {
|
|
1322
|
+
safely(() => {
|
|
1323
|
+
client?.close();
|
|
1324
|
+
client = void 0;
|
|
1325
|
+
pendingScope = new Scope();
|
|
1326
|
+
pendingRoute = void 0;
|
|
1327
|
+
if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
|
|
1328
|
+
}, void 0);
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
exports.SDK_VERSION = SDK_VERSION;
|
|
1332
|
+
exports.addBreadcrumb = addBreadcrumb;
|
|
1333
|
+
exports.captureException = captureException;
|
|
1334
|
+
exports.captureMessage = captureMessage;
|
|
1335
|
+
exports.close = close;
|
|
1336
|
+
exports.flush = flush;
|
|
1337
|
+
exports.init = init;
|
|
1338
|
+
exports.setRoute = setRoute;
|
|
1339
|
+
exports.setTag = setTag;
|
|
1340
|
+
exports.setTags = setTags;
|
|
1341
|
+
exports.setUser = setUser;
|
|
1342
|
+
exports.test = test;
|