@hullop/tlm 0.3.0 → 0.4.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 -4
- package/dist/index.cjs +4 -4
- package/dist/index.js +4 -4
- package/dist/rum.cjs +2 -1
- package/dist/rum.d.cts +4 -3
- package/dist/rum.d.ts +4 -3
- package/dist/rum.esm.js +2 -2
- package/dist/rum.js +2 -1
- package/dist/tlm.esm.js +3 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0 (2026-11-26)
|
|
4
|
+
|
|
5
|
+
- A `rum()` with no `sampleRate` measures every tab when the page has no
|
|
6
|
+
`<meta name="tlm-rum-sample-rate">` either. Before, RUM stayed off
|
|
7
|
+
without a rate, so `Tlm.init({ rum: rum() })` silently sent nothing.
|
|
8
|
+
An explicit rate always wins, `sampleRate: 0` included.
|
|
9
|
+
|
|
3
10
|
## 0.3.0 (2026-11-26)
|
|
4
11
|
|
|
5
12
|
- Each error event carries the viewport's size when it was captured:
|
package/README.md
CHANGED
|
@@ -131,8 +131,8 @@ Tlm.init({ rum: rum() });
|
|
|
131
131
|
`tlm-release` stand in for the `init()` options of the same names, and
|
|
132
132
|
options you pass win. `tlm-user` is the user's id (see
|
|
133
133
|
[Users and tags](#users-and-tags)). `tlm-route` names the page for RUM.
|
|
134
|
-
`rum()` without a `sampleRate` reads `tlm-rum-sample-rate`,
|
|
135
|
-
|
|
134
|
+
`rum()` without a `sampleRate` reads `tlm-rum-sample-rate`, or measures
|
|
135
|
+
every tab without one. Missing or empty tags are left out.
|
|
136
136
|
- **Turbo:** on every `turbo:load`, the SDK reads `tlm-user` and
|
|
137
137
|
`tlm-route` again and counts the visit as a navigation. When
|
|
138
138
|
`tlm-user` is gone (the user signed out), the user is cleared. A user
|
|
@@ -263,8 +263,8 @@ Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
|
263
263
|
|
|
264
264
|
- **Sampling:** `sampleRate` is the share of browser tabs measured,
|
|
265
265
|
decided once per tab. A measured tab sends all its page views. Without
|
|
266
|
-
it,
|
|
267
|
-
|
|
266
|
+
it, it's read from `<meta name="tlm-rum-sample-rate">`, or every tab is
|
|
267
|
+
measured. `sampleRate: 0` turns it off.
|
|
268
268
|
- **What's measured:** for page loads, LCP, INP, CLS, TTFB and FCP; for
|
|
269
269
|
in-app navigations to a new path (pushState, LiveView; a new query
|
|
270
270
|
string alone, like a filter or a search box, stays the same page view),
|
package/dist/index.cjs
CHANGED
|
@@ -240,7 +240,7 @@ function baseEvent({ options, scope: scope2, href, userAgent, session, viewport
|
|
|
240
240
|
platform: "javascript",
|
|
241
241
|
level: toLevel(ctx.level),
|
|
242
242
|
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
243
|
-
sdk: { name: SDK_NAME, version: "0.
|
|
243
|
+
sdk: { name: SDK_NAME, version: "0.4.0" }
|
|
244
244
|
};
|
|
245
245
|
const environment = environmentOf(options);
|
|
246
246
|
if (environment !== void 0) event.environment = environment;
|
|
@@ -371,7 +371,7 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
371
371
|
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
372
372
|
let status;
|
|
373
373
|
try {
|
|
374
|
-
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.4.0" }, environment, release });
|
|
375
375
|
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
376
376
|
({ status } = response);
|
|
377
377
|
} catch (error) {
|
|
@@ -1056,7 +1056,7 @@ var Client = class {
|
|
|
1056
1056
|
}
|
|
1057
1057
|
if (options.rum && !this.transport.disabled) {
|
|
1058
1058
|
try {
|
|
1059
|
-
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.4.0" }, environment: environmentOf(options), release: releaseOf(options) });
|
|
1060
1060
|
} catch (error) {
|
|
1061
1061
|
this.logger.debug("RUM didn't start", error);
|
|
1062
1062
|
}
|
|
@@ -1248,7 +1248,7 @@ var Client = class {
|
|
|
1248
1248
|
};
|
|
1249
1249
|
|
|
1250
1250
|
// src/index.ts
|
|
1251
|
-
var SDK_VERSION = "0.
|
|
1251
|
+
var SDK_VERSION = "0.4.0";
|
|
1252
1252
|
var client;
|
|
1253
1253
|
var pendingRoute;
|
|
1254
1254
|
var pendingScope = new Scope();
|
package/dist/index.js
CHANGED
|
@@ -185,7 +185,7 @@ function baseEvent({ options, scope: scope2, href, userAgent, session, viewport
|
|
|
185
185
|
platform: "javascript",
|
|
186
186
|
level: toLevel(ctx.level),
|
|
187
187
|
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
188
|
-
sdk: { name: SDK_NAME, version: "0.
|
|
188
|
+
sdk: { name: SDK_NAME, version: "0.4.0" }
|
|
189
189
|
};
|
|
190
190
|
const environment = environmentOf(options);
|
|
191
191
|
if (environment !== void 0) event.environment = environment;
|
|
@@ -316,7 +316,7 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
316
316
|
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
317
317
|
let status;
|
|
318
318
|
try {
|
|
319
|
-
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.4.0" }, environment, release });
|
|
320
320
|
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
321
321
|
({ status } = response);
|
|
322
322
|
} catch (error) {
|
|
@@ -995,7 +995,7 @@ var Client = class {
|
|
|
995
995
|
}
|
|
996
996
|
if (options.rum && !this.transport.disabled) {
|
|
997
997
|
try {
|
|
998
|
-
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.4.0" }, environment: environmentOf(options), release: releaseOf(options) });
|
|
999
999
|
} catch (error) {
|
|
1000
1000
|
this.logger.debug("RUM didn't start", error);
|
|
1001
1001
|
}
|
|
@@ -1187,7 +1187,7 @@ var Client = class {
|
|
|
1187
1187
|
};
|
|
1188
1188
|
|
|
1189
1189
|
// src/index.ts
|
|
1190
|
-
var SDK_VERSION = "0.
|
|
1190
|
+
var SDK_VERSION = "0.4.0";
|
|
1191
1191
|
var client;
|
|
1192
1192
|
var pendingRoute;
|
|
1193
1193
|
var pendingScope = new Scope();
|
package/dist/rum.cjs
CHANGED
|
@@ -522,12 +522,13 @@ function observeVitals() {
|
|
|
522
522
|
// src/rum/index.ts
|
|
523
523
|
var SEND_EVERY = 10;
|
|
524
524
|
var SEND_INTERVAL_MS = 5 * 6e4;
|
|
525
|
+
var EVERY_TAB = 1;
|
|
525
526
|
var load;
|
|
526
527
|
function rum(options = {}) {
|
|
527
528
|
return { start: (ctx) => start(ctx, options) };
|
|
528
529
|
}
|
|
529
530
|
function start(ctx, options) {
|
|
530
|
-
const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ??
|
|
531
|
+
const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ?? EVERY_TAB);
|
|
531
532
|
const { id, sampled } = sessionFor(sampleRate);
|
|
532
533
|
if (!sampled) {
|
|
533
534
|
ctx.logger.debug("RUM: this tab wasn't sampled");
|
package/dist/rum.d.cts
CHANGED
|
@@ -36,8 +36,8 @@ interface PageView {
|
|
|
36
36
|
interface RumOptions {
|
|
37
37
|
/**
|
|
38
38
|
* Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab.
|
|
39
|
-
* `0.1` is a good start.
|
|
40
|
-
* `<meta name="tlm-rum-sample-rate">`,
|
|
39
|
+
* `0.1` is a good start. An explicit rate always wins, `0` included.
|
|
40
|
+
* Default: the page's `<meta name="tlm-rum-sample-rate">`, else every tab.
|
|
41
41
|
*/
|
|
42
42
|
sampleRate?: number;
|
|
43
43
|
/** Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it. */
|
|
@@ -55,7 +55,8 @@ interface RumOptions {
|
|
|
55
55
|
* Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
56
56
|
* ```
|
|
57
57
|
*
|
|
58
|
-
* Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate"
|
|
58
|
+
* Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate">`,
|
|
59
|
+
* or every tab is measured.
|
|
59
60
|
*/
|
|
60
61
|
declare function rum(options?: RumOptions): RumPlugin;
|
|
61
62
|
|
package/dist/rum.d.ts
CHANGED
|
@@ -36,8 +36,8 @@ interface PageView {
|
|
|
36
36
|
interface RumOptions {
|
|
37
37
|
/**
|
|
38
38
|
* Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab.
|
|
39
|
-
* `0.1` is a good start.
|
|
40
|
-
* `<meta name="tlm-rum-sample-rate">`,
|
|
39
|
+
* `0.1` is a good start. An explicit rate always wins, `0` included.
|
|
40
|
+
* Default: the page's `<meta name="tlm-rum-sample-rate">`, else every tab.
|
|
41
41
|
*/
|
|
42
42
|
sampleRate?: number;
|
|
43
43
|
/** Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it. */
|
|
@@ -55,7 +55,8 @@ interface RumOptions {
|
|
|
55
55
|
* Tlm.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
56
56
|
* ```
|
|
57
57
|
*
|
|
58
|
-
* Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate"
|
|
58
|
+
* Without a `sampleRate`, it's read from `<meta name="tlm-rum-sample-rate">`,
|
|
59
|
+
* or every tab is measured.
|
|
59
60
|
*/
|
|
60
61
|
declare function rum(options?: RumOptions): RumPlugin;
|
|
61
62
|
|
package/dist/rum.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @hullop/tlm/rum 0.
|
|
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};
|
|
1
|
+
/*! @hullop/tlm/rum 0.4.0 | MIT */
|
|
2
|
+
function B(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 N(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,Y=50,Q=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<Y&&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=N(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,Q);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,de=1,y;function Pe(i={}){return {start:e=>ue(e,i)}}function ue(i,e){let t=e.sampleRate??Number(B(i.win.document,"rum-sample-rate")??de),{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{Pe as rum};
|
package/dist/rum.js
CHANGED
|
@@ -492,12 +492,13 @@ function observeVitals() {
|
|
|
492
492
|
// src/rum/index.ts
|
|
493
493
|
var SEND_EVERY = 10;
|
|
494
494
|
var SEND_INTERVAL_MS = 5 * 6e4;
|
|
495
|
+
var EVERY_TAB = 1;
|
|
495
496
|
var load;
|
|
496
497
|
function rum(options = {}) {
|
|
497
498
|
return { start: (ctx) => start(ctx, options) };
|
|
498
499
|
}
|
|
499
500
|
function start(ctx, options) {
|
|
500
|
-
const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ??
|
|
501
|
+
const sampleRate = options.sampleRate ?? Number(metaContent(ctx.win.document, "rum-sample-rate") ?? EVERY_TAB);
|
|
501
502
|
const { id, sampled } = sessionFor(sampleRate);
|
|
502
503
|
if (!sampled) {
|
|
503
504
|
ctx.logger.debug("RUM: this tab wasn't sampled");
|
package/dist/tlm.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/*! @hullop/tlm 0.
|
|
1
|
+
/*! @hullop/tlm 0.4.0 | MIT */
|
|
2
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
|
+
`)){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.4.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
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);}
|
|
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.4.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.4.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.4.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
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};
|