@hullop/tlm 0.2.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 +7 -0
- package/README.md +4 -0
- package/dist/index.cjs +16 -6
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +16 -6
- package/dist/rum.esm.js +1 -1
- package/dist/tlm.esm.js +6 -6
- package/dist/{types-BluGo23D.d.cts → types-DdYHLwav.d.cts} +8 -1
- package/dist/{types-BluGo23D.d.ts → types-DdYHLwav.d.ts} +8 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
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
|
+
|
|
3
10
|
## 0.2.0 (2026-11-22)
|
|
4
11
|
|
|
5
12
|
- For apps without a bundler (Rails with importmap, plain
|
package/README.md
CHANGED
|
@@ -199,6 +199,10 @@ Tlm.setTag("plan", "pro");
|
|
|
199
199
|
never its text or input values.
|
|
200
200
|
- Cookies and request headers are never sent, only the user agent.
|
|
201
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.
|
|
202
206
|
- Console breadcrumbs keep a short summary of what was logged: strings
|
|
203
207
|
as they are, errors as `Type: message`, and only the first level of an
|
|
204
208
|
object's keys (`{id: 4812, email: "…"}`). If your app logs personal
|
package/dist/index.cjs
CHANGED
|
@@ -176,6 +176,14 @@ function toFrame(raw, { origin, inAppUrls, isDependency, ownUrl }) {
|
|
|
176
176
|
}
|
|
177
177
|
|
|
178
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
|
+
}
|
|
179
187
|
var MAX_MESSAGE = 8192;
|
|
180
188
|
var LEVELS = /* @__PURE__ */ new Set(["fatal", "error", "warning", "info"]);
|
|
181
189
|
var LEVEL_ALIASES = { debug: "info", log: "info", warn: "warning", critical: "fatal" };
|
|
@@ -224,7 +232,7 @@ function releaseOf(options) {
|
|
|
224
232
|
function environmentOf(options) {
|
|
225
233
|
return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
|
|
226
234
|
}
|
|
227
|
-
function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
|
|
235
|
+
function baseEvent({ options, scope: scope2, href, userAgent, session, viewport }, ctx = {}) {
|
|
228
236
|
const event = {
|
|
229
237
|
v: 1,
|
|
230
238
|
uuid: uuid4(),
|
|
@@ -232,13 +240,14 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
|
|
|
232
240
|
platform: "javascript",
|
|
233
241
|
level: toLevel(ctx.level),
|
|
234
242
|
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
235
|
-
sdk: { name: SDK_NAME, version: "0.
|
|
243
|
+
sdk: { name: SDK_NAME, version: "0.3.0" }
|
|
236
244
|
};
|
|
237
245
|
const environment = environmentOf(options);
|
|
238
246
|
if (environment !== void 0) event.environment = environment;
|
|
239
247
|
const release = releaseOf(options);
|
|
240
248
|
if (release !== void 0) event.release = release;
|
|
241
249
|
if (session !== void 0) event.session = session;
|
|
250
|
+
if (viewport !== void 0) event.viewport = viewport;
|
|
242
251
|
if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
|
|
243
252
|
const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
|
|
244
253
|
if (user) event.user = user;
|
|
@@ -362,7 +371,7 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
362
371
|
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
363
372
|
let status;
|
|
364
373
|
try {
|
|
365
|
-
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 });
|
|
366
375
|
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
367
376
|
({ status } = response);
|
|
368
377
|
} catch (error) {
|
|
@@ -1047,7 +1056,7 @@ var Client = class {
|
|
|
1047
1056
|
}
|
|
1048
1057
|
if (options.rum && !this.transport.disabled) {
|
|
1049
1058
|
try {
|
|
1050
|
-
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) });
|
|
1051
1060
|
} catch (error) {
|
|
1052
1061
|
this.logger.debug("RUM didn't start", error);
|
|
1053
1062
|
}
|
|
@@ -1192,7 +1201,8 @@ var Client = class {
|
|
|
1192
1201
|
userAgent: win.navigator.userAgent,
|
|
1193
1202
|
session: this.rum?.session,
|
|
1194
1203
|
isDependency: this.isDependency,
|
|
1195
|
-
ownUrl: OWN_URL
|
|
1204
|
+
ownUrl: OWN_URL,
|
|
1205
|
+
viewport: viewportOf(win)
|
|
1196
1206
|
};
|
|
1197
1207
|
}
|
|
1198
1208
|
capture(build) {
|
|
@@ -1238,7 +1248,7 @@ var Client = class {
|
|
|
1238
1248
|
};
|
|
1239
1249
|
|
|
1240
1250
|
// src/index.ts
|
|
1241
|
-
var SDK_VERSION = "0.
|
|
1251
|
+
var SDK_VERSION = "0.3.0";
|
|
1242
1252
|
var client;
|
|
1243
1253
|
var pendingRoute;
|
|
1244
1254
|
var pendingScope = new Scope();
|
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;
|
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;
|
package/dist/index.js
CHANGED
|
@@ -121,6 +121,14 @@ function toFrame(raw, { origin, inAppUrls, isDependency, ownUrl }) {
|
|
|
121
121
|
}
|
|
122
122
|
|
|
123
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
|
+
}
|
|
124
132
|
var MAX_MESSAGE = 8192;
|
|
125
133
|
var LEVELS = /* @__PURE__ */ new Set(["fatal", "error", "warning", "info"]);
|
|
126
134
|
var LEVEL_ALIASES = { debug: "info", log: "info", warn: "warning", critical: "fatal" };
|
|
@@ -169,7 +177,7 @@ function releaseOf(options) {
|
|
|
169
177
|
function environmentOf(options) {
|
|
170
178
|
return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
|
|
171
179
|
}
|
|
172
|
-
function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
|
|
180
|
+
function baseEvent({ options, scope: scope2, href, userAgent, session, viewport }, ctx = {}) {
|
|
173
181
|
const event = {
|
|
174
182
|
v: 1,
|
|
175
183
|
uuid: uuid4(),
|
|
@@ -177,13 +185,14 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
|
|
|
177
185
|
platform: "javascript",
|
|
178
186
|
level: toLevel(ctx.level),
|
|
179
187
|
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
180
|
-
sdk: { name: SDK_NAME, version: "0.
|
|
188
|
+
sdk: { name: SDK_NAME, version: "0.3.0" }
|
|
181
189
|
};
|
|
182
190
|
const environment = environmentOf(options);
|
|
183
191
|
if (environment !== void 0) event.environment = environment;
|
|
184
192
|
const release = releaseOf(options);
|
|
185
193
|
if (release !== void 0) event.release = release;
|
|
186
194
|
if (session !== void 0) event.session = session;
|
|
195
|
+
if (viewport !== void 0) event.viewport = viewport;
|
|
187
196
|
if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
|
|
188
197
|
const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
|
|
189
198
|
if (user) event.user = user;
|
|
@@ -307,7 +316,7 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
307
316
|
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
308
317
|
let status;
|
|
309
318
|
try {
|
|
310
|
-
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 });
|
|
311
320
|
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
312
321
|
({ status } = response);
|
|
313
322
|
} catch (error) {
|
|
@@ -986,7 +995,7 @@ var Client = class {
|
|
|
986
995
|
}
|
|
987
996
|
if (options.rum && !this.transport.disabled) {
|
|
988
997
|
try {
|
|
989
|
-
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) });
|
|
990
999
|
} catch (error) {
|
|
991
1000
|
this.logger.debug("RUM didn't start", error);
|
|
992
1001
|
}
|
|
@@ -1131,7 +1140,8 @@ var Client = class {
|
|
|
1131
1140
|
userAgent: win.navigator.userAgent,
|
|
1132
1141
|
session: this.rum?.session,
|
|
1133
1142
|
isDependency: this.isDependency,
|
|
1134
|
-
ownUrl: OWN_URL
|
|
1143
|
+
ownUrl: OWN_URL,
|
|
1144
|
+
viewport: viewportOf(win)
|
|
1135
1145
|
};
|
|
1136
1146
|
}
|
|
1137
1147
|
capture(build) {
|
|
@@ -1177,7 +1187,7 @@ var Client = class {
|
|
|
1177
1187
|
};
|
|
1178
1188
|
|
|
1179
1189
|
// src/index.ts
|
|
1180
|
-
var SDK_VERSION = "0.
|
|
1190
|
+
var SDK_VERSION = "0.3.0";
|
|
1181
1191
|
var client;
|
|
1182
1192
|
var pendingRoute;
|
|
1183
1193
|
var pendingScope = new Scope();
|
package/dist/rum.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @hullop/tlm/rum 0.
|
|
1
|
+
/*! @hullop/tlm/rum 0.3.0 | MIT */
|
|
2
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/tlm.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/*! @hullop/tlm 0.
|
|
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
|
|
3
|
-
`)){let r=
|
|
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
4
|
${r.join(`
|
|
5
|
-
`)}`,
|
|
6
|
-
at ? (${t.filename}:${String(t.lineno)}:${String(t.colno)})`:"",n}var ce=5e3,Ve="tlm:heartbeat:",le=new Set;function fe(t){let e,n=()=>{Qe(t);},r=setTimeout(()=>{"requestIdleCallback"in globalThis?e=requestIdleCallback(n,{timeout:ce}):n();},ce);return ()=>{clearTimeout(r),e!==void 0&&cancelIdleCallback(e);}}function ze(t){try{return localStorage.getItem(t)}catch{return null}}async function Qe({url:t,key:e,fetch:n,options:r,logger:i}){let s=_(r),o=k(r),d=Ve+e,c=JSON.stringify([new Date().toISOString().slice(0,10),s??"",o??""]);if(ze(d)===c||le.has(d+c))return;let u;try{let a=JSON.stringify({v:1,sdk:{name:x,version:"0.2.0"},environment:o,release:s});({status:u}=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(!(u===429||u>=500))try{localStorage.setItem(d,c);}catch{le.add(d+c);}}function w(t,e){let n=t.querySelector(`meta[name="tlm-${e}"]`)?.getAttribute("content")?.trim();return n===""?void 0:n}var Je=t=>!/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(t);function Ye(t,e){let n=[];for(let r of t.querySelectorAll('script[type="importmap"]')){let i;try{i=JSON.parse(r.textContent);}catch{continue}let s=typeof i=="object"&&i!==null&&"imports"in i?i.imports:void 0;if(!(typeof s!="object"||s===null)){for(let[o,d]of Object.entries(s))if(!(!Je(o)||typeof d!="string"))try{n.push({specifier:o,url:g(new URL(d,e).href)});}catch{}}}return n}function Ze({specifier:t,url:e}){let n=t.replace(/\/$/,""),r=X(new URL(e).pathname).replace(/\.m?js$/,"").replace(/\/$/,"");return r.endsWith(`/${n}`)||r.endsWith(`/${n}/index`)}function et(t,e){return t.some(n=>n.endsWith("/")?e.startsWith(n)||e===n.slice(0,-1):e===n)}function pe(t,e){let n=w(t,"in-app")?.split(/\s+/),r=o=>n?!et(n,o.specifier):o.specifier.startsWith("@")||!Ze(o),i=new Set,s=[];for(let o of Ye(t,e))r(o)&&(o.specifier.endsWith("/")?s.push(o.url):i.add(o.url));return o=>i.has(o)||s.some(d=>o.startsWith(d))}var $=10,tt=100;function D(t,e=false){if(typeof t=="string")return e?JSON.stringify(T(t,tt)):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(s=>`${s}: ${D(t[s],!0)}`).join(", ")}${r.length>$?", \u2026":""}}`}catch{return "{\u2026}"}}var me="__tlm_original__";function E(t,e,n){let r=t[e];if(typeof r!="function"||r[me]!==void 0)return ()=>true;let i=n(r);return Object.defineProperty(i,me,{value:r}),t[e]=i,()=>t[e]!==i?false:(t[e]=r,true)}function p(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?g(r):r}function I(t,e,n,r){let i=t.onRequest?te(e.location.href,r):void 0;if(i===void 0)return ()=>{};let s=performance.now(),o=t.onRequestStart?.();return d=>{t.onRequest?.({method:n.toUpperCase(),url:i,status:d??0,start:s,end:performance.now()},o);}}function M(t,e){try{return new URL(e,t.location.href).href}catch{return e}}function B(t){return t===void 0||t>=500?"error":t>=400?"warning":"info"}function P(t,e,n){return `${t.toUpperCase()} ${e} \u2192 ${n===void 0?"failed":String(n)}`}var ge={error:"error",warn:"warning",log:"info",info:"info"};function he(t,e,n){let r=t.console,i=Object.keys(ge).map(s=>E(r,s,o=>function(...c){p(()=>{e({category:"console",level:ge[s],message:T(c.map(u=>D(u)).join(" "),500)});}),o.apply(this,c);}));return ()=>i.map(s=>s()).every(Boolean)}var nt=3;function rt(t){let e=[],n=t;for(;n&&e.length<nt&&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 ye(t,e,n){let r=i=>{p(()=>{let s=i.target;if(s?.nodeType!==1)return;let o=rt(s);o!==""&&e({category:"ui.click",level:"info",message:o});});};return t.document.addEventListener("click",r,true),()=>(t.document.removeEventListener("click",r,true),true)}function it(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 be(t,e,n){return E(t,"fetch",r=>async function(s,o){let d=r.apply(this,arguments),c=u=>{};return p(()=>{let{method:u,url:a}=it(s,o);if(n.skipUrl(M(t,a)))return;let l=R(t,a,n.stripQuery),h=I(n,t,u,a);c=m=>{p(()=>{h(m),e({category:"fetch",level:B(m),message:P(u,l,m)});});};}),d.then(u=>(c(u.status),u),u=>{throw c(void 0),u})})}function ve(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}#${g(l.slice(1))}`},i=r(),s=()=>{p(()=>{let a=r();a!==i&&(e({category:"navigation",level:"info",message:`${i} \u2192 ${a}`}),i=a);});},o=a=>E(t.history,a,l=>function(...m){l.apply(this,m),s(),d();}),d=()=>{p(()=>{n.onNavigate?.();});},c=()=>{s(),d();},u=[o("pushState"),o("replaceState")];return t.addEventListener("popstate",c),t.addEventListener("hashchange",s),()=>u.map(a=>a()).every(Boolean)?(t.removeEventListener("popstate",c),t.removeEventListener("hashchange",s),true):false}function Te(t,e,n){let r=t.XMLHttpRequest;if(!r)return ()=>true;let i=r.prototype,s=new WeakMap,o=E(i,"open",c=>function(...a){p(()=>{let[l,h]=a;s.set(this,{method:String(l),url:h instanceof URL?h.href:String(h)});}),c.apply(this,a);}),d=E(i,"send",c=>function(a){p(()=>{let l=s.get(this);if(!l||n.skipUrl(M(t,l.url)))return;let h=R(t,l.url,n.stripQuery),m=I(n,t,l.method,l.url);this.addEventListener("loadend",()=>{p(()=>{let v=this.status!==0?this.status:void 0;m(v),e({category:"xhr",level:B(v),message:P(l.method,h,v)});});},{once:!0});}),c.call(this,a);});return ()=>[o(),d()].every(Boolean)}function we(t){let e=new Set,{debug:n,info:r,warn:i}=console;return {debug(...s){t()&&n.call(console,"[tlm]",...s);},warnOnce(s){e.has(s)||(e.add(s),i.call(console,`[tlm] ${s}`));},info(s){r.call(console,`[tlm] ${s}`);},warn(s){i.call(console,`[tlm] ${s}`);}}}var st=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:T(String(e.message),st)}),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,ot=6e4,at=8,ut=60,Ee=6e4,Q=1e6,dt=50,ct=new TextEncoder,L=t=>ct.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(s=>s!==i),n(false);},e),i=()=>{clearTimeout(r),n(true);};this.idleWaiters.push(i);})}sendQueuedNow(){if(this.disabled||this.paused)return;let e=Ee-this.inFlightKeepaliveBytes;for(let{event:n}of this.queue.splice(0)){let r=Se(n);if(r===void 0)continue;let i=L(r),s=i<=e;s&&(e-=i);try{this.deps.fetch(this.deps.url,{method:"POST",body:r,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:s,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=Se(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<=Ee;this.inFlightKeepaliveBytes=i?r:0;let s;try{s=this.deps.fetch(this.deps.url,{method:"POST",body:n,headers:{"Content-Type":"text/plain;charset=UTF-8"},keepalive:i,credentials:"omit"});}catch(o){s=Promise.reject(o instanceof Error?o:new Error(String(o)));}s.then(o=>{this.handle(e,o);},o=>{this.retry(e,o);});}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(lt(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(s=>{i.debug(`Tlm rejected an event (HTTP ${String(r)})`,e.event.uuid,s);},()=>{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>=at?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,ot),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 lt(t){let e=Number.parseInt(t??"",10);return e>=0?e:ut}function Se(t){try{return ft(t)}catch{return}}function ft(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,dt)},e=JSON.stringify(n),L(e)<=Q))return e}var pt={console:he,dom:ye,fetch:be,xhr:Te,history:ve},mt=50,gt=import.meta.url,Re=1e4;function ht(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,yt={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();}},bt=new Set(["fetch","xhr","history"]),xe=new Set,vt=t=>e=>{y&&y.options.breadcrumbs?.[t]!==false&&y.addBreadcrumb(e);};function Tt(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=we(()=>e.debug===true),this.ignore=[...oe,...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 s=Tt(n.fetch).bind(n),{url:o}=i;this.transport=new F({url:o,fetch:s,logger:this.logger,origin:n.location.origin,onDisable:()=>xe.add(o)}),xe.has(o)?(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(fe({url:i.heartbeatUrl,key:i.key,fetch:s,options:e,logger:this.logger}));let d=e.autoCapture;if(d!==false&&this.cleanups.push(de(n,(a,l)=>this.captureException(a,void 0,l),{onerror:d?.onerror!==false,onunhandledrejection:d?.onunhandledrejection!==false})),e.rum&&!this.transport.disabled)try{this.rum=e.rum.start({win:n,url:i.pageviewsUrl,fetch:s,logger:this.logger,options:e,sdk:{name:x,version:"0.2.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(pt))if(!(!(e.breadcrumbs?.[a]!==false||this.rum!==void 0&&bt.has(a))||C.has(a)))try{C.set(a,l(n,vt(a),yt));}catch(m){this.logger.debug(`couldn't record ${a} breadcrumbs`,m);}this.isDependency=pe(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 u=()=>{this.transport?.sendQueuedNow();};n.addEventListener("pagehide",u),this.cleanups.push(()=>{n.removeEventListener("pagehide",u);});}captureException(e,n,r="manual"){return this.capture(()=>V(e,this.env(),n,r))}captureMessage(e,n){let r=typeof n=="string"?{level:n}:n;return this.capture(()=>ie(e,this.env(),r))}async test(){let e=s=>(this.logger.warn(`Test event not sent: ${s}`),{ok:false,reason:s}),{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 s=new Error("Test event from Tlm.test(). If you can see it in Tlm, your setup works.");throw s.name="TlmTest",s}catch(s){r=V(s,this.env(),{tags:{"tlm.test":"true"},fingerprint:["tlm.test"]});}let i=this.beforeSend(r)??r;return new Promise(s=>{let o=false,d=u=>{o||(o=true,clearTimeout(c),s(u));},c=setTimeout(()=>{d(e(`no answer from Tlm within ${String(Re/1e3)} s.`));},Re);n.send(i,u=>{if(o)return;let a=ht(u);if(a!==void 0){d(e(a));return}this.logger.info(`Test event sent (${"status"in u?String(u.status):"?"}). Look for "TlmTest" in your project: ${i.uuid}`),d({ok:true,id:i.uuid});});})}addBreadcrumb(e){this.scope.addBreadcrumb(e,this.options.maxBreadcrumbs??mt);}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=w(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=w(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:gt}}capture(e){let n=this.transport;if(!n||this.closed||n.disabled)return;let r=e();if(ue(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 s=this.beforeSend(r);if(s){if(!this.rateGuard.take(i)){this.logger.debug("too many events, dropped one");return}return n.send(s),s.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 On="0.2.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 wt(t,e){return {...t,dsn:t.dsn??w(e,"dsn"),environment:t.environment??w(e,"environment"),release:t.release??w(e,"release")}}function Ln(t={}){b(()=>{if(typeof window>"u")return;let e=q();f?.close(),f=new j(wt(t,window.document),window,e),A&&f.setRoute(A.name),A=void 0,t.debug===!0?Object.defineProperty(window,J,{value:{test:Et},configurable:!0,writable:!0}):Reflect.deleteProperty(window,J);},void 0);}var J="__tlm";async function Et(){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 An(t,e){return b(()=>f?.captureException(t,e),void 0)}function Un(t,e){return b(()=>f?.captureMessage(t,e),void 0)}function Nn(t){b(()=>{q().setUser(t);},void 0);}function $n(t,e){b(()=>{q().setTag(t,e);},void 0);}function Dn(t){b(()=>{q().setTags(t);},void 0);}function In(t){b(()=>{f?f.addBreadcrumb(t):Y.addBreadcrumb(t,50);},void 0);}async function Mn(t){return b(async()=>f?.flush(t)??Promise.resolve(true),Promise.resolve(false))}function Bn(t){b(()=>{f?f.setRoute(t):A={name:t};},void 0);}function Pn(){b(()=>{f?.close(),f=void 0,Y=new S,A=void 0,typeof window<"u"&&Reflect.deleteProperty(window,J);},void 0);}
|
|
7
|
-
export{
|
|
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 {
|
|
@@ -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 {
|
|
@@ -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 };
|