@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 ADDED
@@ -0,0 +1,21 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-11-22)
4
+
5
+ - For apps without a bundler (Rails with importmap, plain
6
+ `<script type="module">`): `dist/tlm.esm.js` and `dist/rum.esm.js`, one
7
+ file each, without imports, minified, each starting with its license line.
8
+ - `Tlm.init()` takes `dsn`, `environment` and `release` from the page's
9
+ `<meta name="tlm-dsn">`, `tlm-environment` and `tlm-release` when they
10
+ aren't given, the user from `tlm-user` and the RUM route from `tlm-route`.
11
+ `rum()` without a `sampleRate` reads `tlm-rum-sample-rate`.
12
+ - Follows Turbo: each `turbo:load` reads `tlm-user` and `tlm-route` again
13
+ and counts as a navigation. A `tlm-user` that disappears clears the user.
14
+ - On pages with an importmap, libraries pinned in it aren't in-app frames.
15
+ `<meta name="tlm-in-app">` lists the app's own specifiers; without it,
16
+ scoped pins and pins whose file isn't named after them are libraries.
17
+ - `tlm.esm.js`'s own frames are never in-app.
18
+
19
+ ## 0.1.0 (2026-11-22)
20
+
21
+ First release.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hullop
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,366 @@
1
- # Temporary Holding Version
1
+ # @hullop/tlm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reports your browser app's errors to [Tlm](https://tlm.hullop.com),
4
+ which groups them into issues, emails you when one is new or comes back,
5
+ and shows you what broke and why.
6
+
7
+ Works with any framework (React, Vue, Svelte, Angular, plain pages), has
8
+ no dependencies and weighs under 10 KB gzipped.
9
+
10
+ ## Installation
11
+
12
+ ```sh
13
+ npm install @hullop/tlm
14
+ ```
15
+
16
+ Then, as early as possible in your app's entry point (`main.ts`,
17
+ `index.js`, …), before the app renders:
18
+
19
+ ```ts
20
+ import * as Tlm from "@hullop/tlm";
21
+
22
+ Tlm.init({
23
+ dsn: "https://tlm_…@tlm.hullop.com", // from your project's setup page
24
+ environment: "production",
25
+ release: "web@1.4.2",
26
+ });
27
+ ```
28
+
29
+ That's it. From now on, uncaught errors and unhandled promise rejections
30
+ are reported on their own, along with what happened right before them:
31
+ clicks, navigation, network requests and console messages.
32
+
33
+ The DSN is public: it can only send events, so it's fine in browser code.
34
+ Without a DSN nothing is captured or sent, so dev and tests stay quiet
35
+ when you leave it out:
36
+
37
+ ```ts
38
+ Tlm.init({ dsn: import.meta.env.VITE_TLM_DSN });
39
+ ```
40
+
41
+ `environment` and `release` are optional. Issues are counted per
42
+ environment, and `release` tells you which deploy an error came from.
43
+
44
+ ### New domains
45
+
46
+ The first time events arrive from a new domain, Tlm keeps them and
47
+ asks the project's admins whether that domain is yours. If an admin
48
+ blocks it, pages there stop sending, and you'll see this once in the
49
+ browser console:
50
+
51
+ > [tlm] This site's domain (https://…) is blocked for this project in Tlm (HTTP 403). Events won't be sent from this page.
52
+
53
+ ### Content Security Policy
54
+
55
+ If your site sends a Content Security Policy, add your DSN's origin (its
56
+ scheme, host and port) to `connect-src`, next to the ones you already
57
+ allow:
58
+
59
+ ```
60
+ Content-Security-Policy: connect-src 'self' https://tlm.hullop.com
61
+ ```
62
+
63
+ That's all it needs, with or without RUM:
64
+
65
+ - Events, heartbeats, page views and `Tlm.test()` go out with
66
+ `fetch` or `navigator.sendBeacon`, which `connect-src` covers.
67
+ - Nothing for `script-src`: the package is bundled with your code, and it
68
+ doesn't load scripts or use `eval` or `new Function`.
69
+ - RUM's performance measurements and its `sessionStorage` entry aren't
70
+ covered by CSP.
71
+
72
+ If `connect-src` is missing it, the browser blocks the requests and logs
73
+ its own CSP error in the console; nothing reaches Tlm.
74
+ `Tlm.test()` (see [Checking your setup](#checking-your-setup))
75
+ then answers "couldn't reach Tlm (…). Check the DSN's host, your
76
+ network, and your Content-Security-Policy's connect-src." CSP violation reports
77
+ (`report-uri`, `report-to`) go wherever your policy says, not to Tlm.
78
+
79
+ ### Framework notes
80
+
81
+ - **Next.js, Nuxt, SvelteKit and other SSR frameworks:** importing the
82
+ package on the server is safe, and `init` does nothing there. Call it
83
+ from client-only code (e.g. a `"use client"` component's effect, or
84
+ `instrumentation-client.ts` in Next.js).
85
+ - **React:** errors caught by an error boundary aren't uncaught, so
86
+ report them yourself from `componentDidCatch`, or from `onCaughtError`
87
+ in React 19's `createRoot`:
88
+
89
+ ```ts
90
+ createRoot(el, { onCaughtError: (error) => Tlm.captureException(error) });
91
+ ```
92
+
93
+ - **Vue:** add `app.config.errorHandler = (error) => Tlm.captureException(error);`
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
+
147
+ ## Checking your setup
148
+
149
+ Send one test error and see what Tlm answered:
150
+
151
+ ```ts
152
+ const result = await Tlm.test();
153
+ // { ok: true, id: "…" } or { ok: false, reason: "Tlm rejected the key (HTTP 401)…" }
154
+ ```
155
+
156
+ It also logs one line to the console, `[tlm] Test event sent (202)…`
157
+ or why it wasn't. The event is a `TlmTest` error tagged
158
+ `tlm.test: "true"`, and every test groups into one issue. It skips
159
+ `ignoreErrors`, duplicate detection and the rate cap; `beforeSend` edits
160
+ apply, but if `beforeSend` drops it, it's sent anyway.
161
+
162
+ With `debug: true`, it's also on `window.__tlm.test()`, so you can
163
+ run it from the browser's console without importing anything.
164
+
165
+ ## Reporting things yourself
166
+
167
+ ```ts
168
+ try {
169
+ await checkout(cart);
170
+ } catch (error) {
171
+ Tlm.captureException(error, { tags: { step: "payment" } });
172
+ showRetry();
173
+ }
174
+
175
+ Tlm.captureMessage("Payment gateway slow", "warning");
176
+ ```
177
+
178
+ Both return the event's id, or `undefined` when nothing was sent.
179
+
180
+ ## Users and tags
181
+
182
+ Say who hit the error, by id (an id, not personal data), and add tags to
183
+ filter by:
184
+
185
+ ```ts
186
+ Tlm.setUser({ id: currentUser.id });
187
+ Tlm.setTag("plan", "pro");
188
+ ```
189
+
190
+ `setUser(null)` clears the user on logout.
191
+
192
+ ## Privacy
193
+
194
+ - Query strings and `#hashes` are removed from every URL sent (the page
195
+ URL and the breadcrumbs). Hash-router routes (`#/orders/7`) are kept in
196
+ navigation breadcrumbs, without their query. Turn it off with
197
+ `stripQuery: false`.
198
+ - Click breadcrumbs describe the element (`form.checkout > button#buy`),
199
+ never its text or input values.
200
+ - Cookies and request headers are never sent, only the user agent.
201
+ Usernames and passwords in URLs are removed.
202
+ - Console breadcrumbs keep a short summary of what was logged: strings
203
+ as they are, errors as `Type: message`, and only the first level of an
204
+ object's keys (`{id: 4812, email: "…"}`). If your app logs personal
205
+ data, turn them off with `breadcrumbs: { console: false }`.
206
+ - Once a day per release and environment, a few seconds after `init()`,
207
+ the SDK sends a heartbeat so Tlm knows the app is running even
208
+ before its first error. It carries only the SDK's name and version, the
209
+ release and the environment: no user, URL, user agent or browser id. The
210
+ day it was sent is kept in `localStorage` (`tlm:heartbeat:…`).
211
+ Turn it off with `heartbeat: false`.
212
+ - `beforeSend` sees every event last, and can edit it or drop it:
213
+
214
+ ```ts
215
+ Tlm.init({
216
+ dsn: "…",
217
+ beforeSend(event) {
218
+ if (event.request) event.request.url = event.request.url.replace(/\/users\/\d+/, "/users/:id");
219
+ return event; // or null to drop it
220
+ },
221
+ });
222
+ ```
223
+
224
+ ## Options
225
+
226
+ | Option | Default | |
227
+ |---|---|---|
228
+ | `dsn` | `tlm-dsn` meta tag | Your project's DSN. Without it, nothing is sent |
229
+ | `environment` | `tlm-environment` meta tag | e.g. `"production"`, `"staging"` |
230
+ | `release` | `tlm-release` meta tag | Your app's version or git sha |
231
+ | `debug` | `false` | Logs what the SDK does, prefixed `[tlm]` |
232
+ | `enabled` | `true` | `false` turns everything off |
233
+ | `beforeSend` | none | `(event) => event \| null`, to edit or drop events |
234
+ | `ignoreErrors` | browser noise | Strings (matched anywhere in `"Type: message"`) or regexps. Added to the built-in list (`ResizeObserver loop…`, `Script error.`) |
235
+ | `inAppUrls` | same origin | Strings or regexps for script URLs that are your app's own code (see below) |
236
+ | `stripQuery` | `true` | Remove `?query` and `#hash` from URLs |
237
+ | `breadcrumbs` | all on | `{ console, dom, fetch, xhr, history }`, each `true`/`false` |
238
+ | `maxBreadcrumbs` | `50` | How many breadcrumbs to keep |
239
+ | `autoCapture` | both on | `{ onerror, onunhandledrejection }`, or `false` for neither |
240
+ | `heartbeat` | `true` | `false` stops the daily heartbeat (see [Privacy](#privacy)) |
241
+
242
+ Other functions: `setTags(tags)`, `addBreadcrumb({ message, category?, level? })`,
243
+ `flush(timeoutMs?)` (waits until queued events are sent) and `close()`
244
+ (removes everything the SDK installed).
245
+
246
+ ## Page speed (RUM)
247
+
248
+ Real User Monitoring shows how fast your pages are for the people using
249
+ them: Web Vitals per page, the slow requests pages make, and single
250
+ visits. It's off by default and ships as a separate import, so apps that
251
+ don't use it don't download it (under 5 KB gzipped):
252
+
253
+ ```ts
254
+ import * as Tlm from "@hullop/tlm";
255
+ import { rum } from "@hullop/tlm/rum";
256
+
257
+ Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
258
+ ```
259
+
260
+ - **Sampling:** `sampleRate` is the share of browser tabs measured,
261
+ decided once per tab. A measured tab sends all its page views. Without
262
+ it, `rum()` reads `<meta name="tlm-rum-sample-rate">` and stays off when
263
+ there's none.
264
+ - **What's measured:** for page loads, LCP, INP, CLS, TTFB and FCP; for
265
+ in-app navigations to a new path (pushState, LiveView; a new query
266
+ string alone, like a filter or a search box, stays the same page view),
267
+ INP, CLS and a navigation
268
+ time, from the click until the page's requests have finished and the DOM
269
+ has been quiet for half a second (at most 10 s). Plus the page's fetch
270
+ and XHR calls, and for slow pages the slowest resources it loaded.
271
+ - **When it sends:** in batches, when the tab is hidden or closed, and
272
+ every 10 page views or 5 minutes while it stays open. Batches over 1 KB
273
+ are gzipped. If Tlm is down or slow, page views are dropped
274
+ quietly; nothing is retried.
275
+ - **Privacy:** no cookies, no user id, no query strings or fragments. A
276
+ random id for the tab's visit, and the tab's sampling decision, are kept
277
+ in `sessionStorage` (key `tlm:rum`) and end with the tab. Errors
278
+ from a measured tab carry the visit's id, so an issue links to the visit.
279
+ Tlm derives the country and browser and doesn't store the IP or
280
+ user agent. Whether you need consent for analytics is your call.
281
+ - **Routes:** Tlm groups pages by guessing which path segments are
282
+ ids (`/orders/81` → `/orders/:id`). If your router knows the route, say
283
+ it after each navigation:
284
+
285
+ ```ts
286
+ Tlm.setRoute("/orders/:id");
287
+ ```
288
+
289
+ or pass `route: (location) => …` to `rum()`. Apps that route in the
290
+ `#hash` need this: fragments are never sent, so every page would
291
+ otherwise be `/`.
292
+ - **Editing or dropping page views:** `rum({ sampleRate, beforeSendPageview(pv) { … return pv; } })`;
293
+ return `null` to drop one.
294
+
295
+ ## How errors are grouped
296
+
297
+ Tlm groups events into issues by the error type and the functions
298
+ in your app's own code that it passed through. The SDK marks a stack
299
+ frame as your code when its script is on the page's own origin (or is a
300
+ webpack dev module, `webpack-internal:///./src/…`) and
301
+ isn't a dependency bundle (`node_modules`, `.vite/deps`, `vendor` chunks,
302
+ Next.js framework chunks). Content hashes in file names are ignored, so
303
+ a new deploy doesn't open new issues. The SDK's own `tlm.esm.js` is
304
+ never your code.
305
+
306
+ On pages with a `<script type="importmap">`, libraries pinned in it are
307
+ not your code either. With a `tlm-in-app` meta tag, that's every pin it
308
+ doesn't list. Without one, the SDK guesses: scoped pins
309
+ (`@hotwired/turbo-rails`) and pins whose file isn't named after them
310
+ (`turbo.min.js`) are libraries. A vendored `lodash` served as
311
+ `lodash-….js` looks like your own code until you add the tag.
312
+
313
+ If your scripts come from a CDN, say so:
314
+
315
+ ```ts
316
+ Tlm.init({ dsn: "…", inAppUrls: ["https://cdn.example.com/app/"] });
317
+ ```
318
+
319
+ ## Source maps
320
+
321
+ Upload your build's source maps and Tlm shows your original files,
322
+ lines and function names, and groups errors by them. Upload them with the
323
+ [`tlm` CLI](https://github.com/cirope/tlm-cli) before you
324
+ deploy, with `TLM_UPLOAD_TOKEN` (from your project's settings) and
325
+ `TLM_DSN` set in your CI:
326
+
327
+ ```sh
328
+ tlm upload ./dist --release "$GIT_SHA"
329
+ ```
330
+
331
+ Make the app report the same release: pass it to `init({ release })`, or
332
+ define the `__TLM_RELEASE__` constant at build time. With Vite, build
333
+ hidden source maps so the bundle doesn't point to them, and delete the maps
334
+ before you deploy (`tlm upload --delete` does it):
335
+
336
+ ```ts
337
+ // vite.config.ts
338
+ export default defineConfig({
339
+ build: { sourcemap: "hidden" },
340
+ define: { __TLM_RELEASE__: JSON.stringify(process.env.GIT_SHA) },
341
+ });
342
+ ```
343
+
344
+ With webpack: `new DefinePlugin({ __TLM_RELEASE__: JSON.stringify(sha) })`.
345
+
346
+ ## What it won't do (yet)
347
+
348
+ - **Minified stack traces without source maps.** Upload them (see
349
+ [Source maps](#source-maps)); without them, frames show the built code
350
+ and the same error can open a new issue after a deploy.
351
+ - **Browsers name functions differently.** The SDK normalizes names
352
+ (`Cart.checkout` in Chrome and `checkout` in Firefox both become
353
+ `checkout`), but Safari sometimes leaves frames out, so the same error
354
+ can occasionally group separately per browser.
355
+ - **Browsers only.** For servers, use a server SDK: Node
356
+ ([`@hullop/tlm-node`](https://www.npmjs.com/package/@hullop/tlm-node),
357
+ for Express and Next.js) or [Elixir](https://hex.pm/packages/tlm).
358
+
359
+ It never throws into your app, never blocks it, and keeps quiet in the
360
+ console unless something's misconfigured (or you set `debug: true`).
361
+ When an error repeats in a loop, it sends it once; and it sends at most
362
+ 30 events every 10 seconds per page.
363
+
364
+ ## License
365
+
366
+ MIT
@@ -0,0 +1,62 @@
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
+
7
+ // src/util.ts
8
+ function uuid4() {
9
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
10
+ const b = crypto.getRandomValues(new Uint8Array(16));
11
+ b[6] = (b[6] ?? 0) & 15 | 64;
12
+ b[8] = (b[8] ?? 0) & 63 | 128;
13
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
14
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
15
+ }
16
+ function truncate(s, max) {
17
+ if (s.length <= max) return s;
18
+ const last = s.charCodeAt(max - 1);
19
+ return s.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
20
+ }
21
+ function safeStringify(value, max = 8192) {
22
+ return truncate(stringify(value), max);
23
+ }
24
+ function stringify(value) {
25
+ if (typeof value === "string") return value;
26
+ if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
27
+ return String(value);
28
+ }
29
+ const seen = /* @__PURE__ */ new WeakSet();
30
+ try {
31
+ return JSON.stringify(value, (_key, v) => {
32
+ if (typeof v === "bigint") return v.toString();
33
+ if (typeof v === "object" && v !== null) {
34
+ if (seen.has(v)) return "[Circular]";
35
+ seen.add(v);
36
+ }
37
+ return v;
38
+ });
39
+ } catch {
40
+ try {
41
+ return String(value);
42
+ } catch {
43
+ return "[unserializable]";
44
+ }
45
+ }
46
+ }
47
+ function stripUrl(url) {
48
+ const i = url.search(/[?#]/);
49
+ return i === -1 ? url : url.slice(0, i);
50
+ }
51
+ var MAX_URL = 500;
52
+ function rumUrl(base, url) {
53
+ try {
54
+ const parsed = new URL(url, base);
55
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
56
+ return (parsed.origin + parsed.pathname).slice(0, MAX_URL);
57
+ } catch {
58
+ return void 0;
59
+ }
60
+ }
61
+
62
+ export { metaContent, rumUrl, safeStringify, stripUrl, truncate, uuid4 };