@hullop/tlm 0.1.0 → 0.3.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 +23 -0
- package/README.md +75 -8
- package/dist/{chunk-YN5N3X7X.js → chunk-ECMQ35KU.js} +7 -1
- package/dist/index.cjs +106 -12
- package/dist/index.d.cts +8 -5
- package/dist/index.d.ts +8 -5
- package/dist/index.js +101 -13
- package/dist/rum.cjs +10 -3
- package/dist/rum.d.cts +9 -3
- package/dist/rum.d.ts +9 -3
- package/dist/rum.esm.js +2 -0
- package/dist/rum.js +5 -4
- package/dist/tlm.esm.js +7 -0
- package/dist/{types-CmaNTQav.d.cts → types-DdYHLwav.d.cts} +11 -4
- package/dist/{types-CmaNTQav.d.ts → types-DdYHLwav.d.ts} +11 -4
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 (2026-11-26)
|
|
4
|
+
|
|
5
|
+
- Each error event carries the viewport's size when it was captured:
|
|
6
|
+
`viewport: { width, height }`, in CSS pixels and rounded to whole pixels,
|
|
7
|
+
so Tlm can tell whether an error happened on a phone layout. Left out
|
|
8
|
+
when the window has no size. `beforeSend` sees it like the rest of the event.
|
|
9
|
+
|
|
10
|
+
## 0.2.0 (2026-11-22)
|
|
11
|
+
|
|
12
|
+
- For apps without a bundler (Rails with importmap, plain
|
|
13
|
+
`<script type="module">`): `dist/tlm.esm.js` and `dist/rum.esm.js`, one
|
|
14
|
+
file each, without imports, minified, each starting with its license line.
|
|
15
|
+
- `Tlm.init()` takes `dsn`, `environment` and `release` from the page's
|
|
16
|
+
`<meta name="tlm-dsn">`, `tlm-environment` and `tlm-release` when they
|
|
17
|
+
aren't given, the user from `tlm-user` and the RUM route from `tlm-route`.
|
|
18
|
+
`rum()` without a `sampleRate` reads `tlm-rum-sample-rate`.
|
|
19
|
+
- Follows Turbo: each `turbo:load` reads `tlm-user` and `tlm-route` again
|
|
20
|
+
and counts as a navigation. A `tlm-user` that disappears clears the user.
|
|
21
|
+
- On pages with an importmap, libraries pinned in it aren't in-app frames.
|
|
22
|
+
`<meta name="tlm-in-app">` lists the app's own specifiers; without it,
|
|
23
|
+
scoped pins and pins whose file isn't named after them are libraries.
|
|
24
|
+
- `tlm.esm.js`'s own frames are never in-app.
|
|
25
|
+
|
|
3
26
|
## 0.1.0 (2026-11-22)
|
|
4
27
|
|
|
5
28
|
First release.
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ which groups them into issues, emails you when one is new or comes back,
|
|
|
5
5
|
and shows you what broke and why.
|
|
6
6
|
|
|
7
7
|
Works with any framework (React, Vue, Svelte, Angular, plain pages), has
|
|
8
|
-
no dependencies and weighs
|
|
8
|
+
no dependencies and weighs under 10 KB gzipped.
|
|
9
9
|
|
|
10
10
|
## Installation
|
|
11
11
|
|
|
@@ -92,6 +92,58 @@ network, and your Content-Security-Policy's connect-src." CSP violation reports
|
|
|
92
92
|
|
|
93
93
|
- **Vue:** add `app.config.errorHandler = (error) => Tlm.captureException(error);`
|
|
94
94
|
|
|
95
|
+
### Without a bundler (Rails, importmap)
|
|
96
|
+
|
|
97
|
+
The package ships two self-contained ES modules for pages that load
|
|
98
|
+
scripts as they are: `dist/tlm.esm.js` (the SDK) and `dist/rum.esm.js`
|
|
99
|
+
([RUM](#page-speed-rum)). Neither imports anything, and each starts with
|
|
100
|
+
its license line, so you can copy them into your app as they are. With
|
|
101
|
+
importmap-rails, put them in `vendor/javascript` and pin them under the
|
|
102
|
+
package's names:
|
|
103
|
+
|
|
104
|
+
```ruby
|
|
105
|
+
# config/importmap.rb
|
|
106
|
+
pin "@hullop/tlm", to: "tlm.esm.js"
|
|
107
|
+
pin "@hullop/tlm/rum", to: "rum.esm.js"
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Let the server render the settings into the layout's `<head>`, and call
|
|
111
|
+
`init()` with no DSN:
|
|
112
|
+
|
|
113
|
+
```html
|
|
114
|
+
<meta name="tlm-dsn" content="https://tlm_…@tlm.hullop.com">
|
|
115
|
+
<meta name="tlm-environment" content="production">
|
|
116
|
+
<meta name="tlm-release" content="4b6c3f8">
|
|
117
|
+
<meta name="tlm-user" content="42">
|
|
118
|
+
<meta name="tlm-route" content="/orders/:id(.:format)">
|
|
119
|
+
<meta name="tlm-rum-sample-rate" content="0.1">
|
|
120
|
+
<meta name="tlm-in-app" content="application controllers/">
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
```js
|
|
124
|
+
import * as Tlm from "@hullop/tlm";
|
|
125
|
+
import { rum } from "@hullop/tlm/rum";
|
|
126
|
+
|
|
127
|
+
Tlm.init({ rum: rum() });
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
- **What each tag sets:** `tlm-dsn`, `tlm-environment` and
|
|
131
|
+
`tlm-release` stand in for the `init()` options of the same names, and
|
|
132
|
+
options you pass win. `tlm-user` is the user's id (see
|
|
133
|
+
[Users and tags](#users-and-tags)). `tlm-route` names the page for RUM.
|
|
134
|
+
`rum()` without a `sampleRate` reads `tlm-rum-sample-rate`, and RUM
|
|
135
|
+
stays off without one. Missing or empty tags are left out.
|
|
136
|
+
- **Turbo:** on every `turbo:load`, the SDK reads `tlm-user` and
|
|
137
|
+
`tlm-route` again and counts the visit as a navigation. When
|
|
138
|
+
`tlm-user` is gone (the user signed out), the user is cleared. A user
|
|
139
|
+
you set with `setUser` is left alone.
|
|
140
|
+
- **Your code and your libraries:** everything an importmap app loads
|
|
141
|
+
comes from your own origin, so the SDK reads the page's
|
|
142
|
+
`<script type="importmap">` to tell them apart (see
|
|
143
|
+
[How errors are grouped](#how-errors-are-grouped)). `tlm-in-app` lists
|
|
144
|
+
the specifiers that are your own code, a trailing `/` covering a whole
|
|
145
|
+
directory. Every other pin is then a library.
|
|
146
|
+
|
|
95
147
|
## Checking your setup
|
|
96
148
|
|
|
97
149
|
Send one test error and see what Tlm answered:
|
|
@@ -147,6 +199,10 @@ Tlm.setTag("plan", "pro");
|
|
|
147
199
|
never its text or input values.
|
|
148
200
|
- Cookies and request headers are never sent, only the user agent.
|
|
149
201
|
Usernames and passwords in URLs are removed.
|
|
202
|
+
- Each error event carries the size of the viewport when it was captured
|
|
203
|
+
(`viewport: { width, height }`, in CSS pixels and rounded to whole
|
|
204
|
+
pixels), so Tlm can tell whether an error happened on a phone layout. `beforeSend` can change or remove
|
|
205
|
+
it. Heartbeats and page views never carry it.
|
|
150
206
|
- Console breadcrumbs keep a short summary of what was logged: strings
|
|
151
207
|
as they are, errors as `Type: message`, and only the first level of an
|
|
152
208
|
object's keys (`{id: 4812, email: "…"}`). If your app logs personal
|
|
@@ -173,9 +229,9 @@ Tlm.setTag("plan", "pro");
|
|
|
173
229
|
|
|
174
230
|
| Option | Default | |
|
|
175
231
|
|---|---|---|
|
|
176
|
-
| `dsn` |
|
|
177
|
-
| `environment` |
|
|
178
|
-
| `release` |
|
|
232
|
+
| `dsn` | `tlm-dsn` meta tag | Your project's DSN. Without it, nothing is sent |
|
|
233
|
+
| `environment` | `tlm-environment` meta tag | e.g. `"production"`, `"staging"` |
|
|
234
|
+
| `release` | `tlm-release` meta tag | Your app's version or git sha |
|
|
179
235
|
| `debug` | `false` | Logs what the SDK does, prefixed `[tlm]` |
|
|
180
236
|
| `enabled` | `true` | `false` turns everything off |
|
|
181
237
|
| `beforeSend` | none | `(event) => event \| null`, to edit or drop events |
|
|
@@ -196,7 +252,7 @@ Other functions: `setTags(tags)`, `addBreadcrumb({ message, category?, level? })
|
|
|
196
252
|
Real User Monitoring shows how fast your pages are for the people using
|
|
197
253
|
them: Web Vitals per page, the slow requests pages make, and single
|
|
198
254
|
visits. It's off by default and ships as a separate import, so apps that
|
|
199
|
-
don't use it don't download it (
|
|
255
|
+
don't use it don't download it (under 5 KB gzipped):
|
|
200
256
|
|
|
201
257
|
```ts
|
|
202
258
|
import * as Tlm from "@hullop/tlm";
|
|
@@ -206,7 +262,9 @@ Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
|
206
262
|
```
|
|
207
263
|
|
|
208
264
|
- **Sampling:** `sampleRate` is the share of browser tabs measured,
|
|
209
|
-
decided once per tab. A measured tab sends all its page views.
|
|
265
|
+
decided once per tab. A measured tab sends all its page views. Without
|
|
266
|
+
it, `rum()` reads `<meta name="tlm-rum-sample-rate">` and stays off when
|
|
267
|
+
there's none.
|
|
210
268
|
- **What's measured:** for page loads, LCP, INP, CLS, TTFB and FCP; for
|
|
211
269
|
in-app navigations to a new path (pushState, LiveView; a new query
|
|
212
270
|
string alone, like a filter or a search box, stays the same page view),
|
|
@@ -246,8 +304,17 @@ frame as your code when its script is on the page's own origin (or is a
|
|
|
246
304
|
webpack dev module, `webpack-internal:///./src/…`) and
|
|
247
305
|
isn't a dependency bundle (`node_modules`, `.vite/deps`, `vendor` chunks,
|
|
248
306
|
Next.js framework chunks). Content hashes in file names are ignored, so
|
|
249
|
-
a new deploy doesn't open new issues.
|
|
250
|
-
|
|
307
|
+
a new deploy doesn't open new issues. The SDK's own `tlm.esm.js` is
|
|
308
|
+
never your code.
|
|
309
|
+
|
|
310
|
+
On pages with a `<script type="importmap">`, libraries pinned in it are
|
|
311
|
+
not your code either. With a `tlm-in-app` meta tag, that's every pin it
|
|
312
|
+
doesn't list. Without one, the SDK guesses: scoped pins
|
|
313
|
+
(`@hotwired/turbo-rails`) and pins whose file isn't named after them
|
|
314
|
+
(`turbo.min.js`) are libraries. A vendored `lodash` served as
|
|
315
|
+
`lodash-….js` looks like your own code until you add the tag.
|
|
316
|
+
|
|
317
|
+
If your scripts come from a CDN, say so:
|
|
251
318
|
|
|
252
319
|
```ts
|
|
253
320
|
Tlm.init({ dsn: "…", inAppUrls: ["https://cdn.example.com/app/"] });
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
// src/meta.ts
|
|
2
|
+
function metaContent(doc, name) {
|
|
3
|
+
const content = doc.querySelector(`meta[name="tlm-${name}"]`)?.getAttribute("content")?.trim();
|
|
4
|
+
return content === "" ? void 0 : content;
|
|
5
|
+
}
|
|
6
|
+
|
|
1
7
|
// src/util.ts
|
|
2
8
|
function uuid4() {
|
|
3
9
|
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
@@ -53,4 +59,4 @@ function rumUrl(base, url) {
|
|
|
53
59
|
}
|
|
54
60
|
}
|
|
55
61
|
|
|
56
|
-
export { rumUrl, safeStringify, stripUrl, truncate, uuid4 };
|
|
62
|
+
export { metaContent, rumUrl, safeStringify, stripUrl, truncate, uuid4 };
|
package/dist/index.cjs
CHANGED
|
@@ -154,7 +154,7 @@ function toFrames(raw, opts) {
|
|
|
154
154
|
}
|
|
155
155
|
return frames;
|
|
156
156
|
}
|
|
157
|
-
function toFrame(raw, { origin, inAppUrls }) {
|
|
157
|
+
function toFrame(raw, { origin, inAppUrls, isDependency, ownUrl }) {
|
|
158
158
|
let url;
|
|
159
159
|
try {
|
|
160
160
|
url = new URL(raw.url, origin);
|
|
@@ -165,7 +165,10 @@ function toFrame(raw, { origin, inAppUrls }) {
|
|
|
165
165
|
const sameOrigin = url?.origin === origin || webpackInternal;
|
|
166
166
|
let file = stripUrl(raw.url);
|
|
167
167
|
if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
|
|
168
|
-
const
|
|
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);
|
|
169
172
|
const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
|
|
170
173
|
if (raw.line !== void 0) frame.line = raw.line;
|
|
171
174
|
if (raw.column !== void 0) frame.column = raw.column;
|
|
@@ -173,6 +176,14 @@ function toFrame(raw, { origin, inAppUrls }) {
|
|
|
173
176
|
}
|
|
174
177
|
|
|
175
178
|
// src/event.ts
|
|
179
|
+
function wholePixels(n) {
|
|
180
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n) : void 0;
|
|
181
|
+
}
|
|
182
|
+
function viewportOf(win) {
|
|
183
|
+
const width = wholePixels(win.innerWidth);
|
|
184
|
+
const height = wholePixels(win.innerHeight);
|
|
185
|
+
return width === void 0 || height === void 0 ? void 0 : { width, height };
|
|
186
|
+
}
|
|
176
187
|
var MAX_MESSAGE = 8192;
|
|
177
188
|
var LEVELS = /* @__PURE__ */ new Set(["fatal", "error", "warning", "info"]);
|
|
178
189
|
var LEVEL_ALIASES = { debug: "info", log: "info", warn: "warning", critical: "fatal" };
|
|
@@ -195,7 +206,7 @@ function errorType(error) {
|
|
|
195
206
|
function eventFromException(error, env, ctx, mechanism = "manual") {
|
|
196
207
|
const event = baseEvent(env, ctx);
|
|
197
208
|
if (isErrorLike(error)) {
|
|
198
|
-
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
|
|
209
|
+
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, isDependency: env.isDependency, ownUrl: env.ownUrl }) : [];
|
|
199
210
|
event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
|
|
200
211
|
if (frames.length > 0) event.exception.frames = frames;
|
|
201
212
|
} else {
|
|
@@ -221,7 +232,7 @@ function releaseOf(options) {
|
|
|
221
232
|
function environmentOf(options) {
|
|
222
233
|
return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
|
|
223
234
|
}
|
|
224
|
-
function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
|
|
235
|
+
function baseEvent({ options, scope: scope2, href, userAgent, session, viewport }, ctx = {}) {
|
|
225
236
|
const event = {
|
|
226
237
|
v: 1,
|
|
227
238
|
uuid: uuid4(),
|
|
@@ -229,13 +240,14 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
|
|
|
229
240
|
platform: "javascript",
|
|
230
241
|
level: toLevel(ctx.level),
|
|
231
242
|
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
232
|
-
sdk: { name: SDK_NAME, version: "0.
|
|
243
|
+
sdk: { name: SDK_NAME, version: "0.3.0" }
|
|
233
244
|
};
|
|
234
245
|
const environment = environmentOf(options);
|
|
235
246
|
if (environment !== void 0) event.environment = environment;
|
|
236
247
|
const release = releaseOf(options);
|
|
237
248
|
if (release !== void 0) event.release = release;
|
|
238
249
|
if (session !== void 0) event.session = session;
|
|
250
|
+
if (viewport !== void 0) event.viewport = viewport;
|
|
239
251
|
if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
|
|
240
252
|
const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
|
|
241
253
|
if (user) event.user = user;
|
|
@@ -359,7 +371,7 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
359
371
|
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
360
372
|
let status;
|
|
361
373
|
try {
|
|
362
|
-
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.
|
|
374
|
+
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.0" }, environment, release });
|
|
363
375
|
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
364
376
|
({ status } = response);
|
|
365
377
|
} catch (error) {
|
|
@@ -374,6 +386,56 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
374
386
|
}
|
|
375
387
|
}
|
|
376
388
|
|
|
389
|
+
// src/meta.ts
|
|
390
|
+
function metaContent(doc, name) {
|
|
391
|
+
const content = doc.querySelector(`meta[name="tlm-${name}"]`)?.getAttribute("content")?.trim();
|
|
392
|
+
return content === "" ? void 0 : content;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// src/importmap.ts
|
|
396
|
+
var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
|
|
397
|
+
function pinsOf(doc, base) {
|
|
398
|
+
const pins = [];
|
|
399
|
+
for (const script of doc.querySelectorAll('script[type="importmap"]')) {
|
|
400
|
+
let map;
|
|
401
|
+
try {
|
|
402
|
+
map = JSON.parse(script.textContent);
|
|
403
|
+
} catch {
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
|
|
407
|
+
if (typeof imports !== "object" || imports === null) continue;
|
|
408
|
+
for (const [specifier, target] of Object.entries(imports)) {
|
|
409
|
+
if (!isBare(specifier) || typeof target !== "string") continue;
|
|
410
|
+
try {
|
|
411
|
+
pins.push({ specifier, url: stripUrl(new URL(target, base).href) });
|
|
412
|
+
} catch {
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return pins;
|
|
417
|
+
}
|
|
418
|
+
function namedAfterPin({ specifier, url }) {
|
|
419
|
+
const name = specifier.replace(/\/$/, "");
|
|
420
|
+
const path = normalizeModule(new URL(url).pathname).replace(/\.m?js$/, "").replace(/\/$/, "");
|
|
421
|
+
return path.endsWith(`/${name}`) || path.endsWith(`/${name}/index`);
|
|
422
|
+
}
|
|
423
|
+
function listedIn(inApp, specifier) {
|
|
424
|
+
return inApp.some((entry) => entry.endsWith("/") ? specifier.startsWith(entry) || specifier === entry.slice(0, -1) : specifier === entry);
|
|
425
|
+
}
|
|
426
|
+
function importmapDependencies(doc, base) {
|
|
427
|
+
const inApp = metaContent(doc, "in-app")?.split(/\s+/);
|
|
428
|
+
const isDependency = (pin) => inApp ? !listedIn(inApp, pin.specifier) : pin.specifier.startsWith("@") || !namedAfterPin(pin);
|
|
429
|
+
const exact = /* @__PURE__ */ new Set();
|
|
430
|
+
const prefixes = [];
|
|
431
|
+
for (const pin of pinsOf(doc, base)) {
|
|
432
|
+
if (!isDependency(pin)) continue;
|
|
433
|
+
if (pin.specifier.endsWith("/")) prefixes.push(pin.url);
|
|
434
|
+
else exact.add(pin.url);
|
|
435
|
+
}
|
|
436
|
+
return (url) => exact.has(url) || prefixes.some((prefix) => url.startsWith(prefix));
|
|
437
|
+
}
|
|
438
|
+
|
|
377
439
|
// src/describe.ts
|
|
378
440
|
var MAX_KEYS = 10;
|
|
379
441
|
var MAX_STRING = 100;
|
|
@@ -907,6 +969,7 @@ var INSTRUMENTS = {
|
|
|
907
969
|
history: instrumentHistory
|
|
908
970
|
};
|
|
909
971
|
var DEFAULT_MAX_BREADCRUMBS = 50;
|
|
972
|
+
var OWN_URL = void 0;
|
|
910
973
|
var TEST_TIMEOUT_MS = 1e4;
|
|
911
974
|
function testFailure(result) {
|
|
912
975
|
if ("error" in result) {
|
|
@@ -962,7 +1025,7 @@ var Client = class {
|
|
|
962
1025
|
}
|
|
963
1026
|
if (typeof options.dsn !== "string" || options.dsn === "") {
|
|
964
1027
|
this.logger.debug("no DSN given: nothing will be sent");
|
|
965
|
-
this.inactive =
|
|
1028
|
+
this.inactive = `no DSN given to init() or in <meta name="tlm-dsn">.`;
|
|
966
1029
|
return;
|
|
967
1030
|
}
|
|
968
1031
|
const endpoint = parseDsn(options.dsn);
|
|
@@ -993,7 +1056,7 @@ var Client = class {
|
|
|
993
1056
|
}
|
|
994
1057
|
if (options.rum && !this.transport.disabled) {
|
|
995
1058
|
try {
|
|
996
|
-
this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.
|
|
1059
|
+
this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.3.0" }, environment: environmentOf(options), release: releaseOf(options) });
|
|
997
1060
|
} catch (error) {
|
|
998
1061
|
this.logger.debug("RUM didn't start", error);
|
|
999
1062
|
}
|
|
@@ -1008,6 +1071,16 @@ var Client = class {
|
|
|
1008
1071
|
this.logger.debug(`couldn't record ${kind} breadcrumbs`, error);
|
|
1009
1072
|
}
|
|
1010
1073
|
}
|
|
1074
|
+
this.isDependency = importmapDependencies(win.document, win.location.href);
|
|
1075
|
+
this.followMeta();
|
|
1076
|
+
const onTurboLoad = () => {
|
|
1077
|
+
this.rum?.navigate();
|
|
1078
|
+
this.followMeta();
|
|
1079
|
+
};
|
|
1080
|
+
win.document.addEventListener("turbo:load", onTurboLoad);
|
|
1081
|
+
this.cleanups.push(() => {
|
|
1082
|
+
win.document.removeEventListener("turbo:load", onTurboLoad);
|
|
1083
|
+
});
|
|
1011
1084
|
const onPageHide = () => {
|
|
1012
1085
|
this.transport?.sendQueuedNow();
|
|
1013
1086
|
};
|
|
@@ -1108,6 +1181,16 @@ var Client = class {
|
|
|
1108
1181
|
}
|
|
1109
1182
|
}
|
|
1110
1183
|
}
|
|
1184
|
+
/** The page's user and route from its meta tags. A user the app set itself is left alone. */
|
|
1185
|
+
followMeta() {
|
|
1186
|
+
const doc = this.win.document;
|
|
1187
|
+
const user = metaContent(doc, "user");
|
|
1188
|
+
const current = this.scope.user?.id;
|
|
1189
|
+
if (current === void 0 || current === this.metaUser) this.scope.setUser(user === void 0 ? null : { id: user });
|
|
1190
|
+
this.metaUser = user;
|
|
1191
|
+
const route = metaContent(doc, "route");
|
|
1192
|
+
if (route !== void 0) this.setRoute(route);
|
|
1193
|
+
}
|
|
1111
1194
|
env() {
|
|
1112
1195
|
const { win } = this;
|
|
1113
1196
|
return {
|
|
@@ -1116,7 +1199,10 @@ var Client = class {
|
|
|
1116
1199
|
origin: win.location.origin,
|
|
1117
1200
|
href: win.location.href,
|
|
1118
1201
|
userAgent: win.navigator.userAgent,
|
|
1119
|
-
session: this.rum?.session
|
|
1202
|
+
session: this.rum?.session,
|
|
1203
|
+
isDependency: this.isDependency,
|
|
1204
|
+
ownUrl: OWN_URL,
|
|
1205
|
+
viewport: viewportOf(win)
|
|
1120
1206
|
};
|
|
1121
1207
|
}
|
|
1122
1208
|
capture(build) {
|
|
@@ -1162,7 +1248,7 @@ var Client = class {
|
|
|
1162
1248
|
};
|
|
1163
1249
|
|
|
1164
1250
|
// src/index.ts
|
|
1165
|
-
var SDK_VERSION = "0.
|
|
1251
|
+
var SDK_VERSION = "0.3.0";
|
|
1166
1252
|
var client;
|
|
1167
1253
|
var pendingRoute;
|
|
1168
1254
|
var pendingScope = new Scope();
|
|
@@ -1177,12 +1263,20 @@ function safely(fn, fallback) {
|
|
|
1177
1263
|
return fallback;
|
|
1178
1264
|
}
|
|
1179
1265
|
}
|
|
1180
|
-
function
|
|
1266
|
+
function withMeta(options, doc) {
|
|
1267
|
+
return {
|
|
1268
|
+
...options,
|
|
1269
|
+
dsn: options.dsn ?? metaContent(doc, "dsn"),
|
|
1270
|
+
environment: options.environment ?? metaContent(doc, "environment"),
|
|
1271
|
+
release: options.release ?? metaContent(doc, "release")
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
function init(options = {}) {
|
|
1181
1275
|
safely(() => {
|
|
1182
1276
|
if (typeof window === "undefined") return;
|
|
1183
1277
|
const kept = scope();
|
|
1184
1278
|
client?.close();
|
|
1185
|
-
client = new Client(options, window, kept);
|
|
1279
|
+
client = new Client(withMeta(options, window.document), window, kept);
|
|
1186
1280
|
if (pendingRoute) client.setRoute(pendingRoute.name);
|
|
1187
1281
|
pendingRoute = void 0;
|
|
1188
1282
|
if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-
|
|
2
|
-
export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent } from './types-
|
|
1
|
+
import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-DdYHLwav.cjs';
|
|
2
|
+
export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent, V as Viewport } from './types-DdYHLwav.cjs';
|
|
3
3
|
|
|
4
4
|
/** The version of this SDK, as sent in every event's `sdk.version`. */
|
|
5
5
|
declare const SDK_VERSION: string;
|
|
@@ -13,10 +13,13 @@ declare const SDK_VERSION: string;
|
|
|
13
13
|
* Tlm.init({ dsn: "https://tlm_…@tlm.hullop.com" });
|
|
14
14
|
* ```
|
|
15
15
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
16
|
+
* Options not given are read from the page's meta tags (`tlm-dsn`,
|
|
17
|
+
* `tlm-environment`, `tlm-release`), so a server-rendered page can call a
|
|
18
|
+
* bare `Tlm.init()`. Without a DSN, nothing is captured or sent. Calling it
|
|
19
|
+
* again replaces the options. Safe to import during server-side rendering:
|
|
20
|
+
* it does nothing there.
|
|
18
21
|
*/
|
|
19
|
-
declare function init(options
|
|
22
|
+
declare function init(options?: TlmOptions): void;
|
|
20
23
|
/**
|
|
21
24
|
* Sends one test error, to check your setup end to end. Resolves to
|
|
22
25
|
* `{ ok: true, id }` once Tlm accepts it, or `{ ok: false, reason }`,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-
|
|
2
|
-
export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent } from './types-
|
|
1
|
+
import { B as Breadcrumb, C as CaptureContext, L as Level, T as TlmOptions, a as TestResult } from './types-DdYHLwav.js';
|
|
2
|
+
export { b as BreadcrumbKind, F as Frame, R as RequestTiming, c as RumContext, d as RumHandle, e as RumPlugin, f as TlmEvent, V as Viewport } from './types-DdYHLwav.js';
|
|
3
3
|
|
|
4
4
|
/** The version of this SDK, as sent in every event's `sdk.version`. */
|
|
5
5
|
declare const SDK_VERSION: string;
|
|
@@ -13,10 +13,13 @@ declare const SDK_VERSION: string;
|
|
|
13
13
|
* Tlm.init({ dsn: "https://tlm_…@tlm.hullop.com" });
|
|
14
14
|
* ```
|
|
15
15
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
16
|
+
* Options not given are read from the page's meta tags (`tlm-dsn`,
|
|
17
|
+
* `tlm-environment`, `tlm-release`), so a server-rendered page can call a
|
|
18
|
+
* bare `Tlm.init()`. Without a DSN, nothing is captured or sent. Calling it
|
|
19
|
+
* again replaces the options. Safe to import during server-side rendering:
|
|
20
|
+
* it does nothing there.
|
|
18
21
|
*/
|
|
19
|
-
declare function init(options
|
|
22
|
+
declare function init(options?: TlmOptions): void;
|
|
20
23
|
/**
|
|
21
24
|
* Sends one test error, to check your setup end to end. Resolves to
|
|
22
25
|
* `{ ok: true, id }` once Tlm accepts it, or `{ ok: false, reason }`,
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-
|
|
1
|
+
import { metaContent, truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-ECMQ35KU.js';
|
|
2
2
|
|
|
3
3
|
// src/dsn.ts
|
|
4
4
|
function parseDsn(dsn) {
|
|
@@ -99,7 +99,7 @@ function toFrames(raw, opts) {
|
|
|
99
99
|
}
|
|
100
100
|
return frames;
|
|
101
101
|
}
|
|
102
|
-
function toFrame(raw, { origin, inAppUrls }) {
|
|
102
|
+
function toFrame(raw, { origin, inAppUrls, isDependency, ownUrl }) {
|
|
103
103
|
let url;
|
|
104
104
|
try {
|
|
105
105
|
url = new URL(raw.url, origin);
|
|
@@ -110,7 +110,10 @@ function toFrame(raw, { origin, inAppUrls }) {
|
|
|
110
110
|
const sameOrigin = url?.origin === origin || webpackInternal;
|
|
111
111
|
let file = stripUrl(raw.url);
|
|
112
112
|
if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
|
|
113
|
-
const
|
|
113
|
+
const absolute = url ? stripUrl(url.href) : void 0;
|
|
114
|
+
const own = absolute !== void 0 && absolute === ownUrl;
|
|
115
|
+
const dependency = absolute !== void 0 && isDependency?.(absolute) === true;
|
|
116
|
+
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);
|
|
114
117
|
const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
|
|
115
118
|
if (raw.line !== void 0) frame.line = raw.line;
|
|
116
119
|
if (raw.column !== void 0) frame.column = raw.column;
|
|
@@ -118,6 +121,14 @@ function toFrame(raw, { origin, inAppUrls }) {
|
|
|
118
121
|
}
|
|
119
122
|
|
|
120
123
|
// src/event.ts
|
|
124
|
+
function wholePixels(n) {
|
|
125
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n) : void 0;
|
|
126
|
+
}
|
|
127
|
+
function viewportOf(win) {
|
|
128
|
+
const width = wholePixels(win.innerWidth);
|
|
129
|
+
const height = wholePixels(win.innerHeight);
|
|
130
|
+
return width === void 0 || height === void 0 ? void 0 : { width, height };
|
|
131
|
+
}
|
|
121
132
|
var MAX_MESSAGE = 8192;
|
|
122
133
|
var LEVELS = /* @__PURE__ */ new Set(["fatal", "error", "warning", "info"]);
|
|
123
134
|
var LEVEL_ALIASES = { debug: "info", log: "info", warn: "warning", critical: "fatal" };
|
|
@@ -140,7 +151,7 @@ function errorType(error) {
|
|
|
140
151
|
function eventFromException(error, env, ctx, mechanism = "manual") {
|
|
141
152
|
const event = baseEvent(env, ctx);
|
|
142
153
|
if (isErrorLike(error)) {
|
|
143
|
-
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
|
|
154
|
+
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, isDependency: env.isDependency, ownUrl: env.ownUrl }) : [];
|
|
144
155
|
event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
|
|
145
156
|
if (frames.length > 0) event.exception.frames = frames;
|
|
146
157
|
} else {
|
|
@@ -166,7 +177,7 @@ function releaseOf(options) {
|
|
|
166
177
|
function environmentOf(options) {
|
|
167
178
|
return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
|
|
168
179
|
}
|
|
169
|
-
function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
|
|
180
|
+
function baseEvent({ options, scope: scope2, href, userAgent, session, viewport }, ctx = {}) {
|
|
170
181
|
const event = {
|
|
171
182
|
v: 1,
|
|
172
183
|
uuid: uuid4(),
|
|
@@ -174,13 +185,14 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
|
|
|
174
185
|
platform: "javascript",
|
|
175
186
|
level: toLevel(ctx.level),
|
|
176
187
|
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
177
|
-
sdk: { name: SDK_NAME, version: "0.
|
|
188
|
+
sdk: { name: SDK_NAME, version: "0.3.0" }
|
|
178
189
|
};
|
|
179
190
|
const environment = environmentOf(options);
|
|
180
191
|
if (environment !== void 0) event.environment = environment;
|
|
181
192
|
const release = releaseOf(options);
|
|
182
193
|
if (release !== void 0) event.release = release;
|
|
183
194
|
if (session !== void 0) event.session = session;
|
|
195
|
+
if (viewport !== void 0) event.viewport = viewport;
|
|
184
196
|
if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
|
|
185
197
|
const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
|
|
186
198
|
if (user) event.user = user;
|
|
@@ -304,7 +316,7 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
304
316
|
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
305
317
|
let status;
|
|
306
318
|
try {
|
|
307
|
-
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.
|
|
319
|
+
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.0" }, environment, release });
|
|
308
320
|
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
309
321
|
({ status } = response);
|
|
310
322
|
} catch (error) {
|
|
@@ -319,6 +331,50 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
319
331
|
}
|
|
320
332
|
}
|
|
321
333
|
|
|
334
|
+
// src/importmap.ts
|
|
335
|
+
var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
|
|
336
|
+
function pinsOf(doc, base) {
|
|
337
|
+
const pins = [];
|
|
338
|
+
for (const script of doc.querySelectorAll('script[type="importmap"]')) {
|
|
339
|
+
let map;
|
|
340
|
+
try {
|
|
341
|
+
map = JSON.parse(script.textContent);
|
|
342
|
+
} catch {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
|
|
346
|
+
if (typeof imports !== "object" || imports === null) continue;
|
|
347
|
+
for (const [specifier, target] of Object.entries(imports)) {
|
|
348
|
+
if (!isBare(specifier) || typeof target !== "string") continue;
|
|
349
|
+
try {
|
|
350
|
+
pins.push({ specifier, url: stripUrl(new URL(target, base).href) });
|
|
351
|
+
} catch {
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return pins;
|
|
356
|
+
}
|
|
357
|
+
function namedAfterPin({ specifier, url }) {
|
|
358
|
+
const name = specifier.replace(/\/$/, "");
|
|
359
|
+
const path = normalizeModule(new URL(url).pathname).replace(/\.m?js$/, "").replace(/\/$/, "");
|
|
360
|
+
return path.endsWith(`/${name}`) || path.endsWith(`/${name}/index`);
|
|
361
|
+
}
|
|
362
|
+
function listedIn(inApp, specifier) {
|
|
363
|
+
return inApp.some((entry) => entry.endsWith("/") ? specifier.startsWith(entry) || specifier === entry.slice(0, -1) : specifier === entry);
|
|
364
|
+
}
|
|
365
|
+
function importmapDependencies(doc, base) {
|
|
366
|
+
const inApp = metaContent(doc, "in-app")?.split(/\s+/);
|
|
367
|
+
const isDependency = (pin) => inApp ? !listedIn(inApp, pin.specifier) : pin.specifier.startsWith("@") || !namedAfterPin(pin);
|
|
368
|
+
const exact = /* @__PURE__ */ new Set();
|
|
369
|
+
const prefixes = [];
|
|
370
|
+
for (const pin of pinsOf(doc, base)) {
|
|
371
|
+
if (!isDependency(pin)) continue;
|
|
372
|
+
if (pin.specifier.endsWith("/")) prefixes.push(pin.url);
|
|
373
|
+
else exact.add(pin.url);
|
|
374
|
+
}
|
|
375
|
+
return (url) => exact.has(url) || prefixes.some((prefix) => url.startsWith(prefix));
|
|
376
|
+
}
|
|
377
|
+
|
|
322
378
|
// src/describe.ts
|
|
323
379
|
var MAX_KEYS = 10;
|
|
324
380
|
var MAX_STRING = 100;
|
|
@@ -852,6 +908,7 @@ var INSTRUMENTS = {
|
|
|
852
908
|
history: instrumentHistory
|
|
853
909
|
};
|
|
854
910
|
var DEFAULT_MAX_BREADCRUMBS = 50;
|
|
911
|
+
var OWN_URL = void 0;
|
|
855
912
|
var TEST_TIMEOUT_MS = 1e4;
|
|
856
913
|
function testFailure(result) {
|
|
857
914
|
if ("error" in result) {
|
|
@@ -907,7 +964,7 @@ var Client = class {
|
|
|
907
964
|
}
|
|
908
965
|
if (typeof options.dsn !== "string" || options.dsn === "") {
|
|
909
966
|
this.logger.debug("no DSN given: nothing will be sent");
|
|
910
|
-
this.inactive =
|
|
967
|
+
this.inactive = `no DSN given to init() or in <meta name="tlm-dsn">.`;
|
|
911
968
|
return;
|
|
912
969
|
}
|
|
913
970
|
const endpoint = parseDsn(options.dsn);
|
|
@@ -938,7 +995,7 @@ var Client = class {
|
|
|
938
995
|
}
|
|
939
996
|
if (options.rum && !this.transport.disabled) {
|
|
940
997
|
try {
|
|
941
|
-
this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.
|
|
998
|
+
this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.3.0" }, environment: environmentOf(options), release: releaseOf(options) });
|
|
942
999
|
} catch (error) {
|
|
943
1000
|
this.logger.debug("RUM didn't start", error);
|
|
944
1001
|
}
|
|
@@ -953,6 +1010,16 @@ var Client = class {
|
|
|
953
1010
|
this.logger.debug(`couldn't record ${kind} breadcrumbs`, error);
|
|
954
1011
|
}
|
|
955
1012
|
}
|
|
1013
|
+
this.isDependency = importmapDependencies(win.document, win.location.href);
|
|
1014
|
+
this.followMeta();
|
|
1015
|
+
const onTurboLoad = () => {
|
|
1016
|
+
this.rum?.navigate();
|
|
1017
|
+
this.followMeta();
|
|
1018
|
+
};
|
|
1019
|
+
win.document.addEventListener("turbo:load", onTurboLoad);
|
|
1020
|
+
this.cleanups.push(() => {
|
|
1021
|
+
win.document.removeEventListener("turbo:load", onTurboLoad);
|
|
1022
|
+
});
|
|
956
1023
|
const onPageHide = () => {
|
|
957
1024
|
this.transport?.sendQueuedNow();
|
|
958
1025
|
};
|
|
@@ -1053,6 +1120,16 @@ var Client = class {
|
|
|
1053
1120
|
}
|
|
1054
1121
|
}
|
|
1055
1122
|
}
|
|
1123
|
+
/** The page's user and route from its meta tags. A user the app set itself is left alone. */
|
|
1124
|
+
followMeta() {
|
|
1125
|
+
const doc = this.win.document;
|
|
1126
|
+
const user = metaContent(doc, "user");
|
|
1127
|
+
const current = this.scope.user?.id;
|
|
1128
|
+
if (current === void 0 || current === this.metaUser) this.scope.setUser(user === void 0 ? null : { id: user });
|
|
1129
|
+
this.metaUser = user;
|
|
1130
|
+
const route = metaContent(doc, "route");
|
|
1131
|
+
if (route !== void 0) this.setRoute(route);
|
|
1132
|
+
}
|
|
1056
1133
|
env() {
|
|
1057
1134
|
const { win } = this;
|
|
1058
1135
|
return {
|
|
@@ -1061,7 +1138,10 @@ var Client = class {
|
|
|
1061
1138
|
origin: win.location.origin,
|
|
1062
1139
|
href: win.location.href,
|
|
1063
1140
|
userAgent: win.navigator.userAgent,
|
|
1064
|
-
session: this.rum?.session
|
|
1141
|
+
session: this.rum?.session,
|
|
1142
|
+
isDependency: this.isDependency,
|
|
1143
|
+
ownUrl: OWN_URL,
|
|
1144
|
+
viewport: viewportOf(win)
|
|
1065
1145
|
};
|
|
1066
1146
|
}
|
|
1067
1147
|
capture(build) {
|
|
@@ -1107,7 +1187,7 @@ var Client = class {
|
|
|
1107
1187
|
};
|
|
1108
1188
|
|
|
1109
1189
|
// src/index.ts
|
|
1110
|
-
var SDK_VERSION = "0.
|
|
1190
|
+
var SDK_VERSION = "0.3.0";
|
|
1111
1191
|
var client;
|
|
1112
1192
|
var pendingRoute;
|
|
1113
1193
|
var pendingScope = new Scope();
|
|
@@ -1122,12 +1202,20 @@ function safely(fn, fallback) {
|
|
|
1122
1202
|
return fallback;
|
|
1123
1203
|
}
|
|
1124
1204
|
}
|
|
1125
|
-
function
|
|
1205
|
+
function withMeta(options, doc) {
|
|
1206
|
+
return {
|
|
1207
|
+
...options,
|
|
1208
|
+
dsn: options.dsn ?? metaContent(doc, "dsn"),
|
|
1209
|
+
environment: options.environment ?? metaContent(doc, "environment"),
|
|
1210
|
+
release: options.release ?? metaContent(doc, "release")
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
function init(options = {}) {
|
|
1126
1214
|
safely(() => {
|
|
1127
1215
|
if (typeof window === "undefined") return;
|
|
1128
1216
|
const kept = scope();
|
|
1129
1217
|
client?.close();
|
|
1130
|
-
client = new Client(options, window, kept);
|
|
1218
|
+
client = new Client(withMeta(options, window.document), window, kept);
|
|
1131
1219
|
if (pendingRoute) client.setRoute(pendingRoute.name);
|
|
1132
1220
|
pendingRoute = void 0;
|
|
1133
1221
|
if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
|
package/dist/rum.cjs
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// src/meta.ts
|
|
4
|
+
function metaContent(doc, name) {
|
|
5
|
+
const content = doc.querySelector(`meta[name="tlm-${name}"]`)?.getAttribute("content")?.trim();
|
|
6
|
+
return content === "" ? void 0 : content;
|
|
7
|
+
}
|
|
8
|
+
|
|
3
9
|
// src/util.ts
|
|
4
10
|
function uuid4() {
|
|
5
11
|
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
@@ -517,11 +523,12 @@ function observeVitals() {
|
|
|
517
523
|
var SEND_EVERY = 10;
|
|
518
524
|
var SEND_INTERVAL_MS = 5 * 6e4;
|
|
519
525
|
var load;
|
|
520
|
-
function rum(options) {
|
|
526
|
+
function rum(options = {}) {
|
|
521
527
|
return { start: (ctx) => start(ctx, options) };
|
|
522
528
|
}
|
|
523
529
|
function start(ctx, options) {
|
|
524
|
-
const
|
|
530
|
+
const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ?? 0);
|
|
531
|
+
const { id, sampled } = sessionFor(sampleRate);
|
|
525
532
|
if (!sampled) {
|
|
526
533
|
ctx.logger.debug("RUM: this tab wasn't sampled");
|
|
527
534
|
const nothing = () => void 0;
|
|
@@ -538,7 +545,7 @@ function start(ctx, options) {
|
|
|
538
545
|
logger: ctx.logger,
|
|
539
546
|
sdk: ctx.sdk,
|
|
540
547
|
session: id,
|
|
541
|
-
sampleRate
|
|
548
|
+
sampleRate,
|
|
542
549
|
environment: ctx.environment,
|
|
543
550
|
release: ctx.release,
|
|
544
551
|
beforeSendPageview: options.beforeSendPageview
|
package/dist/rum.d.cts
CHANGED
|
@@ -34,8 +34,12 @@ interface PageView {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
interface RumOptions {
|
|
37
|
-
/**
|
|
38
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab.
|
|
39
|
+
* `0.1` is a good start. Default: the page's
|
|
40
|
+
* `<meta name="tlm-rum-sample-rate">`, or no RUM without one.
|
|
41
|
+
*/
|
|
42
|
+
sampleRate?: number;
|
|
39
43
|
/** Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it. */
|
|
40
44
|
route?: (location: Location) => string | undefined;
|
|
41
45
|
/** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
|
|
@@ -50,8 +54,10 @@ interface RumOptions {
|
|
|
50
54
|
*
|
|
51
55
|
* Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
52
56
|
* ```
|
|
57
|
+
*
|
|
58
|
+
* Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate">`.
|
|
53
59
|
*/
|
|
54
|
-
declare function rum(options
|
|
60
|
+
declare function rum(options?: RumOptions): RumPlugin;
|
|
55
61
|
|
|
56
62
|
export { rum };
|
|
57
63
|
export type { PageView, RumOptions };
|
package/dist/rum.d.ts
CHANGED
|
@@ -34,8 +34,12 @@ interface PageView {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
interface RumOptions {
|
|
37
|
-
/**
|
|
38
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab.
|
|
39
|
+
* `0.1` is a good start. Default: the page's
|
|
40
|
+
* `<meta name="tlm-rum-sample-rate">`, or no RUM without one.
|
|
41
|
+
*/
|
|
42
|
+
sampleRate?: number;
|
|
39
43
|
/** Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it. */
|
|
40
44
|
route?: (location: Location) => string | undefined;
|
|
41
45
|
/** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
|
|
@@ -50,8 +54,10 @@ interface RumOptions {
|
|
|
50
54
|
*
|
|
51
55
|
* Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
52
56
|
* ```
|
|
57
|
+
*
|
|
58
|
+
* Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate">`.
|
|
53
59
|
*/
|
|
54
|
-
declare function rum(options
|
|
60
|
+
declare function rum(options?: RumOptions): RumPlugin;
|
|
55
61
|
|
|
56
62
|
export { rum };
|
|
57
63
|
export type { PageView, RumOptions };
|
package/dist/rum.esm.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @hullop/tlm/rum 0.3.0 | MIT */
|
|
2
|
+
function N(i,e){let t=i.querySelector(`meta[name="tlm-${e}"]`)?.getAttribute("content")?.trim();return t===""?void 0:t}function R(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let i=crypto.getRandomValues(new Uint8Array(16));i[6]=(i[6]??0)&15|64,i[8]=(i[8]??0)&63|128;let e=Array.from(i,t=>t.toString(16).padStart(2,"0")).join("");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function O(i){let e=i.search(/[?#]/);return e===-1?i:i.slice(0,e)}var K=500;function B(i,e){try{let t=new URL(e,i);return t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(t.origin+t.pathname).slice(0,K)}catch{return}}var D=500,z=1e4,G=1e3,Q=50,Y=30,H=300,x={lcp:4e3,inp:500,nav:2500},_=()=>location.pathname,E=class{constructor(e){this.options=e;this.finished=[];this.lastKey=_();this.lastClick=-1/0;this.closed=false;this.resources=[];this.cleanups=[];e.first&&(this.current=this.begin("hard",0),e.hardId!==void 0&&(this.current.id=e.hardId));let t=()=>{this.lastClick=performance.now();},o=n=>{n.persisted&&this.next(performance.now());};document.addEventListener("click",t,true),window.addEventListener("pageshow",o),this.cleanups.push(()=>{document.removeEventListener("click",t,true),window.removeEventListener("pageshow",o);});try{if(typeof PerformanceObserver<"u"&&PerformanceObserver.supportedEntryTypes.includes("resource")){let n=new PerformanceObserver(r=>{for(let l of r.getEntries())this.resources.push({name:l.name,type:l.initiatorType,start:l.startTime,duration:l.duration,size:l.transferSize});this.resources.length>H&&this.resources.splice(0,this.resources.length-H);});n.observe({type:"resource",buffered:!0}),this.cleanups.push(()=>{n.disconnect();});}}catch{}}navigate(){if(this.closed||_()===this.lastKey)return;let e=performance.now(),t=this.lastClick>=(this.current?.start??-1/0)&&e-this.lastClick<=G?this.lastClick:e;this.lastClick=-1/0,this.next(t);}requestStart(){return this.current&&(this.current.pending+=1),this.current}request(e,t){let o=[this.current,...this.finished].filter(r=>r!==void 0),n=t===void 0?o.filter(r=>r.start<=e.start).sort((r,l)=>l.start-r.start)[0]:o.find(r=>r===t);n&&(n.pending=Math.max(0,n.pending-1),n.requests.length<Q&&n.requests.push(e),n===this.current&&this.settle?.());}setRoute(e){this.current&&(this.current.route=e===void 0?void 0:O(e));}currentId(){return this.current?.id}finishedCount(){return this.finished.length}takeFinished(){let e=this.finished.splice(0).map(t=>this.toPageView(t));return e.length>0&&this.current&&this.options.vitals()?.prune(this.current.start),e}snapshot(){return [...this.finished,...this.current?[this.current]:[]].map(t=>this.toPageView(t))}close(){this.closed=true,this.settle=void 0;for(let e of this.cleanups.splice(0))e();}next(e){this.closed||(this.current&&(this.current.end=e,this.finished.push(this.current)),this.current=this.begin("soft",e),this.watch(this.current));}begin(e,t){this.lastKey=_();let o;try{o=this.options.route?.(location);}catch{}return {id:R(),key:this.lastKey,path:location.pathname,navigation:e,start:t,route:o===void 0?void 0:O(o),requests:[],pending:0}}watch(e){this.settle?.();let t=e.start,o,n,r=s=>{clearTimeout(o),clearTimeout(h),n?.disconnect(),this.settle===a&&(this.settle=void 0),e.nav=Math.round(s);},l=()=>{e.pending===0&&r(t-e.start);},a=()=>{t=performance.now(),clearTimeout(o),o=setTimeout(l,D);},h=setTimeout(()=>{r(z);},z);try{n=new MutationObserver(a),n.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});}catch{}this.settle=()=>{if(e!==this.current||this.closed){clearTimeout(o),clearTimeout(h),n?.disconnect();return}a();},o=setTimeout(l,D);}toPageView(e){let t=this.options.vitals(),o=e.end??performance.now(),n={...e.navigation==="hard"?t?.hard():{},...t?.span(e.start,o),...e.nav===void 0?{}:{nav:e.nav}},r={id:e.id,at:new Date(performance.timeOrigin+e.start).toISOString(),path:e.path,navigation:e.navigation};if(e.route!==void 0&&e.route!==""&&(r.route=e.route),Object.keys(n).length>0&&(r.vitals=n),e.requests.length>0&&(r.requests=e.requests.map(a=>({method:a.method,url:a.url,status:a.status,start:Math.max(0,Math.round(a.start-e.start)),duration:Math.round(a.end-a.start)}))),(n.lcp??0)>x.lcp||(n.inp??0)>x.inp||(n.nav??0)>x.nav){let h=this.resources.flatMap(s=>{let p=B(location.href,s.name),g=s.start>=e.start&&(e.end===void 0||s.start<e.end);return p!==void 0&&g&&!this.options.own(s.name)?[{...s,name:p}]:[]}).sort((s,p)=>p.duration-s.duration).slice(0,Y);h.length>0&&(r.waterfall=h.map(s=>({name:s.name,type:s.type,start:Math.round(s.start-e.start),duration:Math.round(s.duration),...s.size>0?{size:s.size}:{}})));}return r}};var A="text/plain;charset=UTF-8",Z=new TextEncoder,ee=i=>Z.encode(i).length,V=class{constructor(e){this.options=e;this.stopped=false;this.pausedUntil=0;this.compressing=new Set;this.sent=new Map;}undispatched(){return [...this.compressing].flatMap(e=>e.pageviews)}async send(e,t){if(this.stopped||Date.now()<this.pausedUntil)return;let o=e.flatMap(r=>this.prepare(r)).filter(r=>this.sent.get(r.id)!==JSON.stringify(r)),n=this.batches(o);if(t!=="visible"&&(n=te(n,48e3,this.options.logger)),t==="pagehide"){for(let r of n)this.unload(r);return}if(t==="hidden"){await Promise.all(n.map(async r=>this.post(r,t)));return}for(let r of n)await this.post(r,t);}prepare(e){let t=this.options.beforeSendPageview;if(!t)return [e];let o;try{o=t(e);}catch(n){return this.options.logger.debug("beforeSendPageview threw; sending the page view unchanged",n),[e]}return o===null?[]:typeof o=="object"&&"then"in o?(this.options.logger.warnOnce("beforeSendPageview returned a Promise, so the page view was dropped. It must return the page view (or null) right away, not async."),[]):[o]}batches(e){let{sdk:t,environment:o,release:n,session:r,sampleRate:l}=this.options,a=p=>{let g=JSON.stringify({v:1,sdk:t,environment:o,release:n,session:r,sample_rate:l,pageviews:p});return {body:g,pageviews:p,bytes:ee(g)}},h=[],s=[];for(let p of e){if(a([...s,p]).bytes<=32e3){s.push(p);continue}s.length>0&&h.push(a(s)),s=[p],a(s).bytes>32e3&&(this.options.logger.debug("dropped a page view that is too big to send",p.id),s=[]);}return s.length>0&&h.push(a(s)),h}dispatched(e){for(let t of e.pageviews)this.sent.delete(t.id),this.sent.set(t.id,JSON.stringify(t));for(let t of [...this.sent.keys()].slice(0,Math.max(0,this.sent.size-200)))this.sent.delete(t);}unload(e){this.dispatched(e);let t=false;try{t=navigator.sendBeacon(this.options.url,new Blob([e.body],{type:A}));}catch{}if(!t)try{this.options.fetch(this.options.url,{method:"POST",body:e.body,headers:{"Content-Type":A},keepalive:!0,credentials:"omit"}).catch(()=>{});}catch{}}async post(e,t){let{url:o,fetch:n,logger:r}=this.options,l={"Content-Type":A},a=e.body;if(e.bytes>1024&&typeof CompressionStream=="function"){this.compressing.add(e);try{a=await ne(e.body),l["Content-Encoding"]="gzip";}catch{a=e.body;}finally{this.compressing.delete(e);}}this.dispatched(e);let h;try{h=await n(o,{method:"POST",body:a,headers:l,keepalive:!0,credentials:"omit"});}catch(p){t==="hidden"?this.unload(e):r.debug("page views not sent",p);return}let{status:s}=h;if(s===401||s===403||s===404)this.stopped=true,r.debug(`Tlm turned RUM down (HTTP ${String(s)}): no more page views from this page`);else if(s===429){let p=Number.parseInt(h.headers.get("Retry-After")??"",10);this.pausedUntil=Date.now()+(p>=0?p:60)*1e3;}else (s<200||s>=300)&&r.debug(`page views dropped (HTTP ${String(s)})`);}};function te(i,e,t){let o=[],n=0;for(let r of [...i].reverse()){if(n+r.bytes>e){t.debug("an unloading page can't send this much; dropped the oldest page views");break}n+=r.bytes,o.unshift(r);}return o}async function ne(i){let e=new Response(i).body;if(!e)throw new Error("no stream");return new Response(e.pipeThrough(new CompressionStream("gzip"))).arrayBuffer()}var F="tlm:rum",$;function ie(){let i;try{i=sessionStorage.getItem(F);}catch{return $}if(i!==null)try{let e=JSON.parse(i);if(typeof e=="object"&&e!==null&&"session"in e&&"rate"in e&&"sampled"in e){let{session:t,rate:o,sampled:n}=e;if(typeof t=="string"&&typeof o=="number"&&typeof n=="boolean")return {session:t,rate:o,sampled:n}}}catch{}}function W(i,e=Math.random){let t=ie();if(t?.rate===i)return {id:t.session,sampled:t.sampled};let o=i>0&&i<=1,n={session:R(),rate:i,sampled:o&&e()<i};$=n;try{sessionStorage.setItem(F,JSON.stringify(n));}catch{}return {id:n.session,sampled:n.sampled}}function k(i,e){let t=i===void 0?void 0:Reflect.get(i,e);return typeof t=="number"?t:void 0}var re=1e3,se=5e3;function X(){let i=performance.getEntriesByType("navigation")[0],e=k(i,"activationStart")??0,t=k(i,"responseStart"),o=t===void 0?void 0:Math.max(0,t-e),n=document.visibilityState==="hidden"&&Reflect.get(document,"prerendering")!==true?0:1/0,r=1/0,l,a,h=[],s=[],p=()=>{document.visibilityState==="hidden"&&(n=Math.min(n,performance.now()));};document.addEventListener("visibilitychange",p,true);let g=[],v=(d,u,f)=>{try{if(typeof PerformanceObserver>"u"||!PerformanceObserver.supportedEntryTypes.includes(d))return;let c=new PerformanceObserver(m=>{try{u(m.getEntries());}catch{}});c.observe({type:d,buffered:!0,...f}),g.push(c);}catch{}},w=d=>{for(let u of d){let f=k(u,"interactionId")??0;f>0&&s.length<5e3&&s.push({id:f,t:u.startTime,d:u.duration});}};v("first-input",d=>{for(let u of d)r=Math.min(r,u.startTime);w(d);}),v("paint",d=>{for(let u of d)u.name==="first-contentful-paint"&&u.startTime<n&&(a=u.startTime);}),v("largest-contentful-paint",d=>{for(let u of d)u.startTime<Math.min(n,r)&&(l=u.startTime);}),v("layout-shift",d=>{for(let u of d){let f=k(u,"value");f!==void 0&&Reflect.get(u,"hadRecentInput")!==!0&&h.length<5e3&&h.push({t:u.startTime,v:f});}}),v("event",w,{durationThreshold:16});let S=d=>d===void 0?void 0:Math.round(Math.max(0,d-e)),T=(d,u)=>f=>f.t>=d&&f.t<u;return {hard(){let d={},u=S(l),f=S(a);return u!==void 0&&(d.lcp=u),f!==void 0&&(d.fcp=f),o!==void 0&&(d.ttfb=Math.round(o)),d},span(d,u){let f={},c=0,m=0,M=-1/0,C=-1/0,U=false;for(let{t:b,v:P}of h.filter(T(d,u)).sort((j,J)=>j.t-J.t))U=true,(b-C>re||b-M>=se)&&(M=b,m=0),m+=P,C=b,c=Math.max(c,m);U&&(f.cls=c);let I=new Map;for(let{id:b,d:P}of s.filter(T(d,u)))I.set(b,Math.max(I.get(b)??0,P));let L=[...I.values()].sort((b,P)=>P-b),q=L[Math.min(L.length-1,Math.floor(L.length/50))];return q!==void 0&&(f.inp=Math.round(q)),f},prune(d){let u=f=>{let c=f.filter(m=>m.t>=d);f.splice(0,f.length,...c);};u(h),u(s);},stop(){for(let d of g)d.disconnect();document.removeEventListener("visibilitychange",p,true);}}}var oe=10,ae=5*6e4,y;function Te(i={}){return {start:e=>de(e,i)}}function de(i,e){let t=e.sampleRate??Number(N(i.win.document,"rum-sample-rate")??0),{id:o,sampled:n}=W(t);if(!n){i.logger.debug("RUM: this tab wasn't sampled");let c=()=>{};return {session:void 0,requestStart:c,request:c,navigate:c,setRoute:c,close:c}}let r=i.url.slice(0,i.url.indexOf("/api/pageviews")),l=X(),a=new E({vitals:()=>l,route:e.route,own:c=>c.startsWith(`${r}/`),first:y?.open??true,hardId:y?.id}),h=a.currentId();y??(y={id:h??"",open:h!==void 0});let s=new V({url:i.url,fetch:i.fetch,logger:i.logger,sdk:i.sdk,session:o,sampleRate:t,environment:i.environment,release:i.release,beforeSendPageview:e.beforeSendPageview}),p=false,g,v=()=>{p=true,clearTimeout(g),a.close(),l.stop(),document.removeEventListener("visibilitychange",d),window.removeEventListener("pagehide",u);},w=(c,m)=>{c.length!==0&&s.send(c,m).then(()=>{s.stopped&&!p&&v();},()=>{});},S=c=>{w([...a.takeFinished(),...a.snapshot()],c);},T=()=>{clearTimeout(g),g=void 0,w(a.takeFinished(),"visible");},d=()=>{document.visibilityState==="hidden"&&S("hidden");},u=()=>{let c=[...s.undispatched(),...a.takeFinished(),...a.snapshot()];w([...new Map(c.map(m=>[m.id,m])).values()],"pagehide");};document.addEventListener("visibilitychange",d),window.addEventListener("pagehide",u);let f=c=>(...m)=>{if(!p)try{c(...m);}catch(M){i.logger.debug("RUM error",M);}};return {session:o,requestStart:f(()=>{a.requestStart();}),request:f(c=>{a.request(c);}),navigate:f(()=>{a.navigate(),y&&a.currentId()!==y.id&&(y.open=!1);let c=a.finishedCount();c>=oe?T():c>0&&(g??(g=setTimeout(T,ae)));}),setRoute:f(c=>{a.setRoute(c);}),close:f(()=>{S("visible"),v();})}}export{Te as rum};
|
package/dist/rum.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { uuid4, stripUrl, rumUrl } from './chunk-
|
|
1
|
+
import { metaContent, uuid4, stripUrl, rumUrl } from './chunk-ECMQ35KU.js';
|
|
2
2
|
|
|
3
3
|
// src/rum/pageviews.ts
|
|
4
4
|
var QUIET_MS = 500;
|
|
@@ -493,11 +493,12 @@ function observeVitals() {
|
|
|
493
493
|
var SEND_EVERY = 10;
|
|
494
494
|
var SEND_INTERVAL_MS = 5 * 6e4;
|
|
495
495
|
var load;
|
|
496
|
-
function rum(options) {
|
|
496
|
+
function rum(options = {}) {
|
|
497
497
|
return { start: (ctx) => start(ctx, options) };
|
|
498
498
|
}
|
|
499
499
|
function start(ctx, options) {
|
|
500
|
-
const
|
|
500
|
+
const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ?? 0);
|
|
501
|
+
const { id, sampled } = sessionFor(sampleRate);
|
|
501
502
|
if (!sampled) {
|
|
502
503
|
ctx.logger.debug("RUM: this tab wasn't sampled");
|
|
503
504
|
const nothing = () => void 0;
|
|
@@ -514,7 +515,7 @@ function start(ctx, options) {
|
|
|
514
515
|
logger: ctx.logger,
|
|
515
516
|
sdk: ctx.sdk,
|
|
516
517
|
session: id,
|
|
517
|
-
sampleRate
|
|
518
|
+
sampleRate,
|
|
518
519
|
environment: ctx.environment,
|
|
519
520
|
release: ctx.release,
|
|
520
521
|
beforeSendPageview: options.beforeSendPageview
|
package/dist/tlm.esm.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/*! @hullop/tlm 0.3.0 | MIT */
|
|
2
|
+
function Z(t){let e;try{e=new URL(t);}catch{return null}if(e.protocol!=="https:"&&e.protocol!=="http:"||e.username==="")return null;let n=e.origin+e.pathname.replace(/\/+$/,""),r=e.username;return {url:`${n}/api/events?key=${r}`,heartbeatUrl:`${n}/api/heartbeats?key=${r}`,pageviewsUrl:`${n}/api/pageviews?key=${r}`,base:n,key:r}}function ee(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=crypto.getRandomValues(new Uint8Array(16));t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function w(t,e){if(t.length<=e)return t;let n=t.charCodeAt(e-1);return t.slice(0,n>=55296&&n<=56319?e-1:e)}function H(t,e=8192){return w(Oe(t),e)}function Oe(t){if(typeof t=="string")return t;if(t===void 0||typeof t=="function"||typeof t=="symbol"||typeof t=="bigint")return String(t);let e=new WeakSet;try{return JSON.stringify(t,(n,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="object"&&r!==null){if(e.has(r))return "[Circular]";e.add(r);}return r})}catch{try{return String(t)}catch{return "[unserializable]"}}}function h(t){let e=t.search(/[?#]/);return e===-1?t:t.slice(0,e)}var Le=500;function te(t,e){try{let n=new URL(e,t);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:(n.origin+n.pathname).slice(0,Le)}catch{return}}var Ae=250,Ue=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/,Ne=/^(.*?)@(.*):(\d+):(\d+)$/,$e=/\((\S+?):(\d+):(\d+)\)/,De=/^(.*?) line (\d+) > (?:eval|Function)/,Me=new Set(["global code","module code","eval code"]);function ne(t){let e=[];for(let n of t.split(`
|
|
3
|
+
`)){let r=Ie(n)??Pe(n);r&&e.push(r);}return e}function Ie(t){let e=Ue.exec(t);if(e?.[2]===void 0)return;let n=e[2],r=Number(e[3]),i=Number(e[4]);if(n.startsWith("eval at ")){let o=$e.exec(n);if(o?.[1]===void 0)return;n=o[1],r=Number(o[2]),i=Number(o[3]);}return {function:W(e[1]),url:n,line:r,column:i}}function Pe(t){let e=Ne.exec(t);if(e?.[2]===void 0||e[2]==="")return;let n=e[1],r=/^([^*]*)\*(.*)$/.exec(n??"");if(r){if(r[1]!=="async")return;n=r[2];}let i=De.exec(e[2]);return i?.[1]!==void 0&&i[1]!==""?{function:W(n),url:i[1],line:Number(i[2]),column:void 0}:{function:W(n),url:e[2],line:Number(e[3]),column:Number(e[4])}}function W(t){if(t===void 0||t===""||Me.has(t))return;let e=t.replace(/^async\*/,"").replace(/^(?:async|new) /,"").replace(/ \[as [^\]]*\]$/,"").replace(/[/<]+$/,""),n=e.slice(Math.max(e.lastIndexOf("."),e.lastIndexOf("/"))+1);return n!==""&&n!=="<anonymous>"?n:void 0}function K(t){return /^(?:chrome|moz|safari|safari-web)-extension:\/\//.test(t)}var Be=[/\/node_modules\//,/\/\.vite\/deps\//,/\/vendors?(?:\/|[-.~][^/]*$)/,/chunk-vendors/,/vendors~/,/\/@vite\//,/\/@react-refresh/,/\/_next\/static\/chunks\/(?:framework|main|webpack)[-.]/],Fe=/[-.~]([A-Za-z0-9_]{8,}|[A-Za-z0-9_-]{8})(?=\.)/g;function Ce(t){return /\d/.test(t)?true:t.length!==8?false:/[_-]/.test(t)||/[A-Z]/.test(t)&&/[a-z]/.test(t)&&!/[a-z]{3}/.test(t)}function V(t){let e=h(t),n=e.lastIndexOf("/")+1,r=e.slice(n).replace(Fe,(i,o)=>Ce(o)?"":i);return e.slice(0,n)+r}function re(t,e){let n=[];for(let r of t)if(r.function?.startsWith("__tlm")!==true){if(n.length===Ae)break;n.push(je(r,e));}return n}function je(t,{origin:e,inAppUrls:n,isDependency:r,ownUrl:i}){let o;try{o=new URL(t.url,e);}catch{o=void 0;}let s=t.url.startsWith("webpack-internal://"),u=o?.origin===e||s,c=h(t.url);o&&!s&&(c=u?o.pathname:h(o.href));let d=o?h(o.href):void 0,a=d!==void 0&&d===i,l=d!==void 0&&r?.(d)===true,p=!a&&(n?n.some(v=>typeof v=="string"?t.url.includes(v):v.test(t.url)):u&&!K(t.url)&&!Be.some(v=>v.test(c))&&!l),g={module:V(c),function:t.function??"?",file:c,in_app:p};return t.line!==void 0&&(g.line=t.line),t.column!==void 0&&(g.column=t.column),g}function ie(t){return Number.isFinite(t)&&t>0?Math.round(t):void 0}function oe(t){let e=ie(t.innerWidth),n=ie(t.innerHeight);return e===void 0||n===void 0?void 0:{width:e,height:n}}var X=8192,qe=new Set(["fatal","error","warning","info"]),He={debug:"info",log:"info",warn:"warning",critical:"fatal"};function We(t){return typeof t!="string"?"error":qe.has(t)?t:He[t]??"error"}var x="@hullop/tlm";function Ke(t){if(t instanceof Error)return true;if(typeof t!="object"||t===null)return false;let e=t;return typeof e.message=="string"&&(typeof e.name=="string"||typeof e.stack=="string")}function Ve(t){if(typeof t.name=="string"&&t.name!=="")return t.name;let e=t.constructor?.name;return typeof e=="string"&&e!==""&&e!=="Object"?e:"Error"}function G(t,e,n,r="manual"){let i=ae(e,n);if(Ke(t)){let o=typeof t.stack=="string"?re(ne(t.stack),{origin:e.origin,inAppUrls:e.options.inAppUrls,isDependency:e.isDependency,ownUrl:e.ownUrl}):[];i.exception={type:Ve(t),message:w(String(t.message),X)},o.length>0&&(i.exception.frames=o);}else i.exception={type:r==="onunhandledrejection"?"UnhandledRejection":"NonError",message:H(t,X)};return i}function se(t,e,n){let r=ae(e,n);return r.message=H(t,X),r}function Xe(){return typeof __TLM_RELEASE__=="string"?__TLM_RELEASE__:void 0}function _(t){let e=t.release??Xe();return e===""?void 0:e}function k(t){return typeof t.environment=="string"&&t.environment!==""?t.environment:void 0}function ae({options:t,scope:e,href:n,userAgent:r,session:i,viewport:o},s={}){let u={v:1,uuid:ee(),timestamp:new Date().toISOString(),platform:"javascript",level:We(s.level),request:{url:t.stripQuery===false?n:h(n),headers:{"user-agent":r}},sdk:{name:x,version:"0.3.0"}},c=k(t);c!==void 0&&(u.environment=c);let d=_(t);d!==void 0&&(u.release=d),i!==void 0&&(u.session=i),o!==void 0&&(u.viewport=o),s.fingerprint&&s.fingerprint.length>0&&(u.fingerprint=s.fingerprint.map(String));let a=s.user?{id:String(s.user.id)}:e.user;a&&(u.user=a);let l={...e.tags,...s.tags};Object.keys(l).length>0&&(u.tags=l);let p=e.getBreadcrumbs();return p.length>0&&(u.breadcrumbs=p),u}var ue=["ResizeObserver loop limit exceeded","ResizeObserver loop completed with undelivered notifications",/^(?:Error: )?Script error\.?$/];function de(t){let{exception:e}=t;return e?e.message!==void 0&&e.message!==""?`${e.type}: ${e.message}`:e.type:t.message??""}function ce(t,e){let n=t.exception?.frames;if(n!==void 0&&n.length>0&&n.every(i=>K(i.file)))return true;let r=de(t);return e.some(i=>typeof i=="string"?r.includes(i):i.test(r))}var U=class{constructor(e=1e3){this.windowMs=e;this.lastAt=0;}isDuplicate(e,n){let r=(e.exception?.frames??[]).slice(0,5).map(s=>`${s.file}:${String(s.line)}:${String(s.column)}`),i=`${de(e)}
|
|
4
|
+
${r.join(`
|
|
5
|
+
`)}`,o=i===this.last&&n-this.lastAt<=this.windowMs;return this.last=i,this.lastAt=n,o}},N=class{constructor(e=30,n=1e4){this.max=e;this.windowMs=n;this.times=[];}take(e){return this.times=this.times.filter(n=>e-n<this.windowMs),this.times.length>=this.max?false:(this.times.push(e),true)}};function le(t,e,n){let r=o=>{try{if(typeof o.target?.nodeType=="number")return;let s=o;e(s.error??ze(s),"onerror");}catch{}},i=o=>{try{e(o.reason,"onunhandledrejection");}catch{}};return n.onerror&&t.addEventListener("error",r),n.onunhandledrejection&&t.addEventListener("unhandledrejection",i),()=>{t.removeEventListener("error",r),t.removeEventListener("unhandledrejection",i);}}var Ge=/^(?:Uncaught |uncaught exception: )?(null|undefined)$/;function ze(t){let e=Ge.exec(t.message),n=new Error(e?.[1]??(t.message!==""?t.message:"Unknown error"));return e&&(n.name="NonError"),n.stack=typeof t.filename=="string"&&t.filename!==""?`${n.name}: ${n.message}
|
|
6
|
+
at ? (${t.filename}:${String(t.lineno)}:${String(t.colno)})`:"",n}var fe=5e3,Qe="tlm:heartbeat:",pe=new Set;function me(t){let e,n=()=>{Ye(t);},r=setTimeout(()=>{"requestIdleCallback"in globalThis?e=requestIdleCallback(n,{timeout:fe}):n();},fe);return ()=>{clearTimeout(r),e!==void 0&&cancelIdleCallback(e);}}function Je(t){try{return localStorage.getItem(t)}catch{return null}}async function Ye({url:t,key:e,fetch:n,options:r,logger:i}){let o=_(r),s=k(r),u=Qe+e,c=JSON.stringify([new Date().toISOString().slice(0,10),o??"",s??""]);if(Je(u)===c||pe.has(u+c))return;let d;try{let a=JSON.stringify({v:1,sdk:{name:x,version:"0.3.0"},environment:s,release:o});({status:d}=await n(t,{method:"POST",body:a,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:!0,credentials:"omit"}));}catch(a){i.debug("heartbeat not sent",a);return}if(!(d===429||d>=500))try{localStorage.setItem(u,c);}catch{pe.add(u+c);}}function T(t,e){let n=t.querySelector(`meta[name="tlm-${e}"]`)?.getAttribute("content")?.trim();return n===""?void 0:n}var Ze=t=>!/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(t);function et(t,e){let n=[];for(let r of t.querySelectorAll('script[type="importmap"]')){let i;try{i=JSON.parse(r.textContent);}catch{continue}let o=typeof i=="object"&&i!==null&&"imports"in i?i.imports:void 0;if(!(typeof o!="object"||o===null)){for(let[s,u]of Object.entries(o))if(!(!Ze(s)||typeof u!="string"))try{n.push({specifier:s,url:h(new URL(u,e).href)});}catch{}}}return n}function tt({specifier:t,url:e}){let n=t.replace(/\/$/,""),r=V(new URL(e).pathname).replace(/\.m?js$/,"").replace(/\/$/,"");return r.endsWith(`/${n}`)||r.endsWith(`/${n}/index`)}function nt(t,e){return t.some(n=>n.endsWith("/")?e.startsWith(n)||e===n.slice(0,-1):e===n)}function ge(t,e){let n=T(t,"in-app")?.split(/\s+/),r=s=>n?!nt(n,s.specifier):s.specifier.startsWith("@")||!tt(s),i=new Set,o=[];for(let s of et(t,e))r(s)&&(s.specifier.endsWith("/")?o.push(s.url):i.add(s.url));return s=>i.has(s)||o.some(u=>s.startsWith(u))}var $=10,rt=100;function D(t,e=false){if(typeof t=="string")return e?JSON.stringify(w(t,rt)):t;if(t===null||typeof t!="object")return typeof t=="function"?`[Function ${t.name!==""?t.name:"anonymous"}]`:String(t);let n=t;if(t instanceof Error||typeof n.message=="string"&&typeof n.name=="string")return `${String(n.name)}: ${String(n.message)}`;if(typeof n.nodeType=="number")return typeof n.tagName=="string"?`<${n.tagName.toLowerCase()}>`:"[Node]";if(e)return Array.isArray(t)?`[Array(${String(t.length)})]`:"{\u2026}";if(Array.isArray(t))return `[${t.slice(0,$).map(i=>D(i,true)).join(", ")}${t.length>$?", \u2026":""}]`;try{let r=Object.keys(t);return `{${r.slice(0,$).map(o=>`${o}: ${D(t[o],!0)}`).join(", ")}${r.length>$?", \u2026":""}}`}catch{return "{\u2026}"}}var he="__tlm_original__";function E(t,e,n){let r=t[e];if(typeof r!="function"||r[he]!==void 0)return ()=>true;let i=n(r);return Object.defineProperty(i,he,{value:r}),t[e]=i,()=>t[e]!==i?false:(t[e]=r,true)}function m(t){try{t();}catch{}}function R(t,e,n){let r=e;try{let i=new URL(e,t.location.href);i.username="",i.password="",r=i.origin===t.location.origin?i.pathname+i.search+i.hash:i.href;}catch{}return n?h(r):r}function M(t,e,n,r){let i=t.onRequest?te(e.location.href,r):void 0;if(i===void 0)return ()=>{};let o=performance.now(),s=t.onRequestStart?.();return u=>{t.onRequest?.({method:n.toUpperCase(),url:i,status:u??0,start:o,end:performance.now()},s);}}function I(t,e){try{return new URL(e,t.location.href).href}catch{return e}}function P(t){return t===void 0||t>=500?"error":t>=400?"warning":"info"}function B(t,e,n){return `${t.toUpperCase()} ${e} \u2192 ${n===void 0?"failed":String(n)}`}var ye={error:"error",warn:"warning",log:"info",info:"info"};function be(t,e,n){let r=t.console,i=Object.keys(ye).map(o=>E(r,o,s=>function(...c){m(()=>{e({category:"console",level:ye[o],message:w(c.map(d=>D(d)).join(" "),500)});}),s.apply(this,c);}));return ()=>i.map(o=>o()).every(Boolean)}var it=3;function ot(t){let e=[],n=t;for(;n&&e.length<it&&n.tagName!=="BODY"&&n.tagName!=="HTML";){let r=n.tagName.toLowerCase();n.id!==""&&(r+=`#${n.id}`);for(let i of Array.from(n.classList))r+=`.${i}`;e.unshift(r),n=n.parentElement;}return e.join(" > ")}function ve(t,e,n){let r=i=>{m(()=>{let o=i.target;if(o?.nodeType!==1)return;let s=ot(o);s!==""&&e({category:"ui.click",level:"info",message:s});});};return t.document.addEventListener("click",r,true),()=>(t.document.removeEventListener("click",r,true),true)}function st(t,e){let n=typeof Request<"u"&&t instanceof Request,r;return n?r=t.url:t instanceof URL?r=t.href:r=String(t),{method:e?.method??(n?t.method:"GET"),url:r}}function we(t,e,n){return E(t,"fetch",r=>async function(o,s){let u=r.apply(this,arguments),c=d=>{};return m(()=>{let{method:d,url:a}=st(o,s);if(n.skipUrl(I(t,a)))return;let l=R(t,a,n.stripQuery),p=M(n,t,d,a);c=g=>{m(()=>{p(g),e({category:"fetch",level:P(g),message:B(d,l,g)});});};}),u.then(d=>(c(d.status),d),d=>{throw c(void 0),d})})}function Te(t,e,n){let r=()=>{let a=R(t,t.location.href,n.stripQuery),{hash:l}=t.location;return !n.stripQuery||!/^#!?\//.test(l)?a:`${a}#${h(l.slice(1))}`},i=r(),o=()=>{m(()=>{let a=r();a!==i&&(e({category:"navigation",level:"info",message:`${i} \u2192 ${a}`}),i=a);});},s=a=>E(t.history,a,l=>function(...g){l.apply(this,g),o(),u();}),u=()=>{m(()=>{n.onNavigate?.();});},c=()=>{o(),u();},d=[s("pushState"),s("replaceState")];return t.addEventListener("popstate",c),t.addEventListener("hashchange",o),()=>d.map(a=>a()).every(Boolean)?(t.removeEventListener("popstate",c),t.removeEventListener("hashchange",o),true):false}function Ee(t,e,n){let r=t.XMLHttpRequest;if(!r)return ()=>true;let i=r.prototype,o=new WeakMap,s=E(i,"open",c=>function(...a){m(()=>{let[l,p]=a;o.set(this,{method:String(l),url:p instanceof URL?p.href:String(p)});}),c.apply(this,a);}),u=E(i,"send",c=>function(a){m(()=>{let l=o.get(this);if(!l||n.skipUrl(I(t,l.url)))return;let p=R(t,l.url,n.stripQuery),g=M(n,t,l.method,l.url);this.addEventListener("loadend",()=>{m(()=>{let v=this.status!==0?this.status:void 0;g(v),e({category:"xhr",level:P(v),message:B(l.method,p,v)});});},{once:!0});}),c.call(this,a);});return ()=>[s(),u()].every(Boolean)}function Se(t){let e=new Set,{debug:n,info:r,warn:i}=console;return {debug(...o){t()&&n.call(console,"[tlm]",...o);},warnOnce(o){e.has(o)||(e.add(o),i.call(console,`[tlm] ${o}`));},info(o){r.call(console,`[tlm] ${o}`);},warn(o){i.call(console,`[tlm] ${o}`);}}}var at=500,S=class{constructor(){this.tags={};this.breadcrumbs=[];}setUser(e){this.user=e?{id:String(e.id)}:void 0;}setTag(e,n){this.tags[e]=String(n);}setTags(e){for(let[n,r]of Object.entries(e))this.setTag(n,r);}addBreadcrumb(e,n){this.breadcrumbs.push({...e,timestamp:e.timestamp??new Date().toISOString(),message:w(String(e.message),at)}),this.breadcrumbs.length>n&&this.breadcrumbs.splice(0,this.breadcrumbs.length-n);}getBreadcrumbs(){return this.breadcrumbs.map(e=>({...e}))}clear(){this.user=void 0,this.tags={},this.breadcrumbs=[];}};function O(t,e){let{onAnswer:n}=t;t.onAnswer=void 0,n?.(e);}var z=1e3,ut=6e4,dt=8,ct=60,Re=6e4,Q=1e6,lt=50,ft=new TextEncoder,L=t=>ft.encode(t).length,F=class{constructor(e){this.deps=e;this.disabled=false;this.queue=[];this.inFlight=false;this.paused=false;this.backoff=z;this.inFlightKeepaliveBytes=0;this.idleWaiters=[];this.maxQueue=e.maxQueue??30;}send(e,n){if(!this.disabled){if(this.queue.length>=this.maxQueue){let r=this.queue.shift();r&&O(r,{error:new Error("dropped: too many events queued")}),this.deps.logger.debug("queue full, dropped the oldest event");}this.queue.push({event:e,attempts:0,...n?{onAnswer:n}:{}}),this.dispatch();}}async flush(e=2e3){return this.isIdle()?Promise.resolve(true):new Promise(n=>{let r=setTimeout(()=>{this.idleWaiters=this.idleWaiters.filter(o=>o!==i),n(false);},e),i=()=>{clearTimeout(r),n(true);};this.idleWaiters.push(i);})}sendQueuedNow(){if(this.disabled||this.paused)return;let e=Re-this.inFlightKeepaliveBytes;for(let{event:n}of this.queue.splice(0)){let r=xe(n);if(r===void 0)continue;let i=L(r),o=i<=e;o&&(e-=i);try{this.deps.fetch(this.deps.url,{method:"POST",body:r,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:o,credentials:"omit"}).catch(()=>{});}catch{}}this.notifyIfIdle();}isIdle(){return !this.inFlight&&(this.queue.length===0||this.disabled)}dispatch(){let e=this.inFlight||this.paused||this.disabled?void 0:this.queue.shift();if(!e){this.notifyIfIdle();return}let n=xe(e.event);if(n===void 0){this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable",e.event.uuid),O(e,{error:new Error("dropped: over 1 MB or not JSON-encodable")}),this.dispatch();return}this.inFlight=true;let r=L(n),i=r<=Re;this.inFlightKeepaliveBytes=i?r:0;let o;try{o=this.deps.fetch(this.deps.url,{method:"POST",body:n,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:i,credentials:"omit"});}catch(s){o=Promise.reject(s instanceof Error?s:new Error(String(s)));}o.then(s=>{this.handle(e,s);},s=>{this.retry(e,s);});}handle(e,n){this.inFlight=false,this.inFlightKeepaliveBytes=0;let{status:r}=n;if(O(e,{status:r}),r>=200&&r<300)this.backoff=z;else if(r===429)this.backoff=z,this.pause(pt(n.headers.get("Retry-After"))*1e3);else if(r===401||r===403)this.disable(r);else if(r>=500){this.retry(e,`HTTP ${String(r)}`);return}else {let{logger:i}=this.deps;n.text().then(o=>{i.debug(`Tlm rejected an event (HTTP ${String(r)})`,e.event.uuid,o);},()=>{i.debug(`Tlm rejected an event (HTTP ${String(r)})`,e.event.uuid);});}this.dispatch();}retry(e,n){O(e,{error:n}),this.inFlight=false,this.inFlightKeepaliveBytes=0,e.attempts+=1,e.attempts>=dt?this.deps.logger.debug(`gave up on an event after ${String(e.attempts)} tries`,n):(this.deps.logger.debug("sending failed, will retry",n),this.queue.unshift(e));let r=this.backoff;this.backoff=Math.min(this.backoff*2,ut),this.pause(r);}pause(e){this.paused=true,setTimeout(()=>{this.paused=false,this.dispatch();},e);}disable(e){this.disabled=true;for(let r of this.queue.splice(0))O(r,{error:new Error(`dropped: Tlm rejected this DSN (HTTP ${String(e)})`)});this.deps.onDisable?.();let n=this.deps.origin??"unknown origin";this.deps.logger.warnOnce(e===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 (${n}) 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.`);}notifyIfIdle(){if(!this.isIdle())return;let e=this.idleWaiters;this.idleWaiters=[];for(let n of e)n();}};function pt(t){let e=Number.parseInt(t??"",10);return e>=0?e:ct}function xe(t){try{return mt(t)}catch{return}}function mt(t){let e=JSON.stringify(t);if(L(e)<=Q)return e;let n={...t};if(delete n.breadcrumbs,e=JSON.stringify(n),L(e)<=Q||n.exception?.frames&&(n.exception={...n.exception,frames:n.exception.frames.slice(0,lt)},e=JSON.stringify(n),L(e)<=Q))return e}var gt={console:be,dom:ve,fetch:we,xhr:Ee,history:Te},ht=50,yt=import.meta.url,_e=1e4;function bt(t){if("error"in t)return `couldn't reach Tlm (${t.error instanceof Error?t.error.message:String(t.error)}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;let{status:e}=t;if(!(e>=200&&e<300))return e===401?"Tlm rejected the key (HTTP 401). Check the DSN on your project's setup page.":e===403?"this site's domain is blocked for the project (HTTP 403). A project admin can unblock it in the project's settings.":e===429?"Tlm asked to slow down (HTTP 429). Try again in a minute.":e>=500?`Tlm had an error (HTTP ${String(e)}). The event will be retried.`:`Tlm rejected the event (HTTP ${String(e)}).`}var y,C=new Map,vt={skipUrl:t=>y?.isOwnUrl(t)??false,get stripQuery(){return y?.options.stripQuery!==false},onRequestStart:()=>y?.rum?.requestStart(),onRequest:(t,e)=>{y?.rum?.request(t,e);},onNavigate:()=>{y?.rum?.navigate();}},wt=new Set(["fetch","xhr","history"]),ke=new Set,Tt=t=>e=>{y&&y.options.breadcrumbs?.[t]!==false&&y.addBreadcrumb(e);};function Et(t){return t.__tlm_original__??t}var j=class{constructor(e,n,r=new S){this.options=e;this.win=n;this.scope=r;this.cleanups=[];this.deduper=new U;this.rateGuard=new N;this.closed=false;if(this.logger=Se(()=>e.debug===true),this.ignore=[...ue,...e.ignoreErrors??[]],e.enabled===false){this.logger.debug("disabled (enabled: false): nothing will be sent"),this.inactive="the SDK is off (enabled: false).";return}if(typeof e.dsn!="string"||e.dsn===""){this.logger.debug("no DSN given: nothing will be sent"),this.inactive='no DSN given to init() or in <meta name="tlm-dsn">.';return}let i=Z(e.dsn);if(!i){this.logger.debug("invalid DSN: nothing will be sent",e.dsn),this.inactive="invalid DSN. Copy it from your project's setup page.";return}this.endpointBase=i.base;let o=Et(n.fetch).bind(n),{url:s}=i;this.transport=new F({url:s,fetch:o,logger:this.logger,origin:n.location.origin,onDisable:()=>ke.add(s)}),ke.has(s)?(this.transport.disabled=true,this.logger.debug("Tlm already rejected this DSN on this page: nothing will be sent")):e.heartbeat!==false&&this.cleanups.push(me({url:i.heartbeatUrl,key:i.key,fetch:o,options:e,logger:this.logger}));let u=e.autoCapture;if(u!==false&&this.cleanups.push(le(n,(a,l)=>this.captureException(a,void 0,l),{onerror:u?.onerror!==false,onunhandledrejection:u?.onunhandledrejection!==false})),e.rum&&!this.transport.disabled)try{this.rum=e.rum.start({win:n,url:i.pageviewsUrl,fetch:o,logger:this.logger,options:e,sdk:{name:x,version:"0.3.0"},environment:k(e),release:_(e)});}catch(a){this.logger.debug("RUM didn't start",a);}y=this;for(let[a,l]of Object.entries(gt))if(!(!(e.breadcrumbs?.[a]!==false||this.rum!==void 0&&wt.has(a))||C.has(a)))try{C.set(a,l(n,Tt(a),vt));}catch(g){this.logger.debug(`couldn't record ${a} breadcrumbs`,g);}this.isDependency=ge(n.document,n.location.href),this.followMeta();let c=()=>{this.rum?.navigate(),this.followMeta();};n.document.addEventListener("turbo:load",c),this.cleanups.push(()=>{n.document.removeEventListener("turbo:load",c);});let d=()=>{this.transport?.sendQueuedNow();};n.addEventListener("pagehide",d),this.cleanups.push(()=>{n.removeEventListener("pagehide",d);});}captureException(e,n,r="manual"){return this.capture(()=>G(e,this.env(),n,r))}captureMessage(e,n){let r=typeof n=="string"?{level:n}:n;return this.capture(()=>se(e,this.env(),r))}async test(){let e=o=>(this.logger.warn(`Test event not sent: ${o}`),{ok:false,reason:o}),{transport:n}=this;if(this.closed)return Promise.resolve(e("the SDK was closed."));if(!n)return Promise.resolve(e(this.inactive??"the SDK isn't sending."));if(n.disabled)return Promise.resolve(e("Tlm already rejected this DSN on this page (HTTP 401/403)."));let r;try{let o=new Error("Test event from Tlm.test(). If you can see it in Tlm, your setup works.");throw o.name="TlmTest",o}catch(o){r=G(o,this.env(),{tags:{"tlm.test":"true"},fingerprint:["tlm.test"]});}let i=this.beforeSend(r)??r;return new Promise(o=>{let s=false,u=d=>{s||(s=true,clearTimeout(c),o(d));},c=setTimeout(()=>{u(e(`no answer from Tlm within ${String(_e/1e3)} s.`));},_e);n.send(i,d=>{if(s)return;let a=bt(d);if(a!==void 0){u(e(a));return}this.logger.info(`Test event sent (${"status"in d?String(d.status):"?"}). Look for "TlmTest" in your project: ${i.uuid}`),u({ok:true,id:i.uuid});});})}addBreadcrumb(e){this.scope.addBreadcrumb(e,this.options.maxBreadcrumbs??ht);}async flush(e){return this.transport?this.transport.flush(e):Promise.resolve(true)}setRoute(e){this.rum?.setRoute(e);}isOwnUrl(e){return this.endpointBase!==void 0&&e.startsWith(`${this.endpointBase}/`)}close(){this.closed=true;try{this.rum?.close();}catch(e){this.logger.debug("RUM didn't close cleanly",e);}if(y===this){y=void 0;for(let[e,n]of C)try{n()&&C.delete(e);}catch{}}for(let e of this.cleanups.splice(0).reverse())try{e();}catch(n){this.logger.debug("cleanup failed",n);}}followMeta(){let e=this.win.document,n=T(e,"user"),r=this.scope.user?.id;(r===void 0||r===this.metaUser)&&this.scope.setUser(n===void 0?null:{id:n}),this.metaUser=n;let i=T(e,"route");i!==void 0&&this.setRoute(i);}env(){let{win:e}=this;return {options:this.options,scope:this.scope,origin:e.location.origin,href:e.location.href,userAgent:e.navigator.userAgent,session:this.rum?.session,isDependency:this.isDependency,ownUrl:yt,viewport:oe(e)}}capture(e){let n=this.transport;if(!n||this.closed||n.disabled)return;let r=e();if(ce(r,this.ignore)){this.logger.debug("ignored",r.exception?.type??r.message);return}let i=Date.now();if(this.deduper.isDuplicate(r,i))return;let o=this.beforeSend(r);if(o){if(!this.rateGuard.take(i)){this.logger.debug("too many events, dropped one");return}return n.send(o),o.uuid}}beforeSend(e){let n=this.options.beforeSend;if(!n)return e;let r;try{r=n(e);}catch(i){return this.logger.debug("beforeSend threw; sending the event unchanged",i),e}if(r!==null){if((typeof r=="object"||typeof r=="function")&&"then"in r&&typeof r.then=="function"){this.logger.warnOnce("beforeSend returned a Promise, so the event was dropped. It must return the event (or null) right away, not async.");return}if(typeof r!="object"||Array.isArray(r)||!("uuid"in r)||typeof r.uuid!="string"){this.logger.debug("beforeSend returned neither an event nor null; dropped",r);return}return r}}};var An="0.3.0",f,A,Y=new S;function q(){return f?.scope??Y}function b(t,e){try{return t()}catch(n){return f?.logger.debug("internal error",n),e}}function St(t,e){return {...t,dsn:t.dsn??T(e,"dsn"),environment:t.environment??T(e,"environment"),release:t.release??T(e,"release")}}function Un(t={}){b(()=>{if(typeof window>"u")return;let e=q();f?.close(),f=new j(St(t,window.document),window,e),A&&f.setRoute(A.name),A=void 0,t.debug===!0?Object.defineProperty(window,J,{value:{test:Rt},configurable:!0,writable:!0}):Reflect.deleteProperty(window,J);},void 0);}var J="__tlm";async function Rt(){let t=()=>{let e="init() hasn't run on this page (or this isn't a browser).";return console.warn(`[tlm] Test event not sent: ${e}`),{ok:false,reason:e}};return b(async()=>f?f.test():Promise.resolve(t()),Promise.resolve({ok:false,reason:"internal error."}))}function Nn(t,e){return b(()=>f?.captureException(t,e),void 0)}function $n(t,e){return b(()=>f?.captureMessage(t,e),void 0)}function Dn(t){b(()=>{q().setUser(t);},void 0);}function Mn(t,e){b(()=>{q().setTag(t,e);},void 0);}function In(t){b(()=>{q().setTags(t);},void 0);}function Pn(t){b(()=>{f?f.addBreadcrumb(t):Y.addBreadcrumb(t,50);},void 0);}async function Bn(t){return b(async()=>f?.flush(t)??Promise.resolve(true),Promise.resolve(false))}function Fn(t){b(()=>{f?f.setRoute(t):A={name:t};},void 0);}function Cn(){b(()=>{f?.close(),f=void 0,Y=new S,A=void 0,typeof window<"u"&&Reflect.deleteProperty(window,J);},void 0);}
|
|
7
|
+
export{An as SDK_VERSION,Pn as addBreadcrumb,Nn as captureException,$n as captureMessage,Cn as close,Bn as flush,Un as init,Fn as setRoute,Mn as setTag,In as setTags,Dn as setUser,Rt as test};
|
|
@@ -74,6 +74,11 @@ interface RumHandle {
|
|
|
74
74
|
interface RumPlugin {
|
|
75
75
|
start: (ctx: RumContext) => RumHandle;
|
|
76
76
|
}
|
|
77
|
+
/** The viewport's size in CSS pixels, so Tlm can tell a phone layout from a desktop's. */
|
|
78
|
+
interface Viewport {
|
|
79
|
+
width: number;
|
|
80
|
+
height: number;
|
|
81
|
+
}
|
|
77
82
|
/** An event as sent to Tlm (protocol v1). */
|
|
78
83
|
interface TlmEvent {
|
|
79
84
|
v: 1;
|
|
@@ -105,6 +110,8 @@ interface TlmEvent {
|
|
|
105
110
|
};
|
|
106
111
|
/** The tab's RUM session, so the error links to its visit. Only from tabs RUM sampled. */
|
|
107
112
|
session?: string;
|
|
113
|
+
/** The viewport's size in whole CSS pixels when the event was captured. Left out when the browser gives no positive size for both. */
|
|
114
|
+
viewport?: Viewport;
|
|
108
115
|
}
|
|
109
116
|
/** Extra details for one captured event. They merge over what `setUser`/`setTag` set. */
|
|
110
117
|
interface CaptureContext {
|
|
@@ -126,11 +133,11 @@ type TestResult = {
|
|
|
126
133
|
};
|
|
127
134
|
type BreadcrumbKind = "console" | "dom" | "fetch" | "xhr" | "history";
|
|
128
135
|
interface TlmOptions {
|
|
129
|
-
/** Your project's DSN, from its setup page in Tlm. Without
|
|
136
|
+
/** Your project's DSN, from its setup page in Tlm. Default: `<meta name="tlm-dsn">`. Without one, nothing is sent. */
|
|
130
137
|
dsn?: string;
|
|
131
|
-
/** e.g. `"production"`, `"staging"`. Issues are counted per environment. */
|
|
138
|
+
/** e.g. `"production"`, `"staging"`. Issues are counted per environment. Default: `<meta name="tlm-environment">`. */
|
|
132
139
|
environment?: string;
|
|
133
|
-
/** Your app's version or git sha, e.g. `"web@1.4.2"`. */
|
|
140
|
+
/** Your app's version or git sha, e.g. `"web@1.4.2"`. Default: `<meta name="tlm-release">`. */
|
|
134
141
|
release?: string;
|
|
135
142
|
/** Logs what the SDK does to the console, prefixed `[tlm]`. Default `false`. */
|
|
136
143
|
debug?: boolean;
|
|
@@ -176,4 +183,4 @@ interface TlmOptions {
|
|
|
176
183
|
};
|
|
177
184
|
}
|
|
178
185
|
|
|
179
|
-
export type { Breadcrumb as B, CaptureContext as C, Frame as F, Level as L, RequestTiming as R, TlmOptions as T, TestResult as a, BreadcrumbKind as b, RumContext as c, RumHandle as d, RumPlugin as e, TlmEvent as f };
|
|
186
|
+
export type { Breadcrumb as B, CaptureContext as C, Frame as F, Level as L, RequestTiming as R, TlmOptions as T, Viewport as V, TestResult as a, BreadcrumbKind as b, RumContext as c, RumHandle as d, RumPlugin as e, TlmEvent as f };
|
|
@@ -74,6 +74,11 @@ interface RumHandle {
|
|
|
74
74
|
interface RumPlugin {
|
|
75
75
|
start: (ctx: RumContext) => RumHandle;
|
|
76
76
|
}
|
|
77
|
+
/** The viewport's size in CSS pixels, so Tlm can tell a phone layout from a desktop's. */
|
|
78
|
+
interface Viewport {
|
|
79
|
+
width: number;
|
|
80
|
+
height: number;
|
|
81
|
+
}
|
|
77
82
|
/** An event as sent to Tlm (protocol v1). */
|
|
78
83
|
interface TlmEvent {
|
|
79
84
|
v: 1;
|
|
@@ -105,6 +110,8 @@ interface TlmEvent {
|
|
|
105
110
|
};
|
|
106
111
|
/** The tab's RUM session, so the error links to its visit. Only from tabs RUM sampled. */
|
|
107
112
|
session?: string;
|
|
113
|
+
/** The viewport's size in whole CSS pixels when the event was captured. Left out when the browser gives no positive size for both. */
|
|
114
|
+
viewport?: Viewport;
|
|
108
115
|
}
|
|
109
116
|
/** Extra details for one captured event. They merge over what `setUser`/`setTag` set. */
|
|
110
117
|
interface CaptureContext {
|
|
@@ -126,11 +133,11 @@ type TestResult = {
|
|
|
126
133
|
};
|
|
127
134
|
type BreadcrumbKind = "console" | "dom" | "fetch" | "xhr" | "history";
|
|
128
135
|
interface TlmOptions {
|
|
129
|
-
/** Your project's DSN, from its setup page in Tlm. Without
|
|
136
|
+
/** Your project's DSN, from its setup page in Tlm. Default: `<meta name="tlm-dsn">`. Without one, nothing is sent. */
|
|
130
137
|
dsn?: string;
|
|
131
|
-
/** e.g. `"production"`, `"staging"`. Issues are counted per environment. */
|
|
138
|
+
/** e.g. `"production"`, `"staging"`. Issues are counted per environment. Default: `<meta name="tlm-environment">`. */
|
|
132
139
|
environment?: string;
|
|
133
|
-
/** Your app's version or git sha, e.g. `"web@1.4.2"`. */
|
|
140
|
+
/** Your app's version or git sha, e.g. `"web@1.4.2"`. Default: `<meta name="tlm-release">`. */
|
|
134
141
|
release?: string;
|
|
135
142
|
/** Logs what the SDK does to the console, prefixed `[tlm]`. Default `false`. */
|
|
136
143
|
debug?: boolean;
|
|
@@ -176,4 +183,4 @@ interface TlmOptions {
|
|
|
176
183
|
};
|
|
177
184
|
}
|
|
178
185
|
|
|
179
|
-
export type { Breadcrumb as B, CaptureContext as C, Frame as F, Level as L, RequestTiming as R, TlmOptions as T, TestResult as a, BreadcrumbKind as b, RumContext as c, RumHandle as d, RumPlugin as e, TlmEvent as f };
|
|
186
|
+
export type { Breadcrumb as B, CaptureContext as C, Frame as F, Level as L, RequestTiming as R, TlmOptions as T, Viewport as V, TestResult as a, BreadcrumbKind as b, RumContext as c, RumHandle as d, RumPlugin as e, TlmEvent as f };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hullop/tlm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Reports your browser app's errors to Tlm.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"error-tracking",
|
|
@@ -52,12 +52,12 @@
|
|
|
52
52
|
"access": "public"
|
|
53
53
|
},
|
|
54
54
|
"scripts": {
|
|
55
|
-
"build": "tsup",
|
|
55
|
+
"build": "rm -rf dist && tsup",
|
|
56
56
|
"test": "vitest run --project unit",
|
|
57
57
|
"test:browser": "vitest run --project browser",
|
|
58
58
|
"typecheck": "tsc --noEmit",
|
|
59
59
|
"size": "size-limit",
|
|
60
|
-
"check": "npm run typecheck && npm test && npm run build && npm run size",
|
|
60
|
+
"check": "npm run typecheck && npm test && npm run build && node scripts/check-standalone.mjs && npm run size",
|
|
61
61
|
"prepublishOnly": "npm run check"
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|