@chrom-ar/collector 0.3.1 → 0.5.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 +39 -0
- package/README.md +140 -22
- package/dist/chunk-42XODVHT.js +63 -0
- package/dist/collector.esm.js +7 -0
- package/dist/index.cjs +203 -42
- package/dist/index.d.cts +18 -121
- package/dist/index.d.ts +18 -121
- package/dist/index.js +187 -87
- package/dist/rum.cjs +645 -0
- package/dist/rum.d.cts +63 -0
- package/dist/rum.d.ts +63 -0
- package/dist/rum.esm.js +2 -0
- package/dist/rum.js +614 -0
- package/dist/types-ml-o_-mr.d.cts +183 -0
- package/dist/types-ml-o_-mr.d.ts +183 -0
- package/package.json +19 -5
package/dist/rum.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { RumPlugin } from './index.js';
|
|
2
|
+
|
|
3
|
+
/** A page view as sent to Collector (protocol v1, "Page views"). */
|
|
4
|
+
interface PageView {
|
|
5
|
+
id: string;
|
|
6
|
+
/** ISO 8601, when it started. */
|
|
7
|
+
at: string;
|
|
8
|
+
/** The path only: no query or fragment. */
|
|
9
|
+
path: string;
|
|
10
|
+
route?: string;
|
|
11
|
+
navigation: "hard" | "soft";
|
|
12
|
+
vitals?: {
|
|
13
|
+
lcp?: number;
|
|
14
|
+
inp?: number;
|
|
15
|
+
cls?: number;
|
|
16
|
+
ttfb?: number;
|
|
17
|
+
fcp?: number;
|
|
18
|
+
nav?: number;
|
|
19
|
+
};
|
|
20
|
+
requests?: {
|
|
21
|
+
method: string;
|
|
22
|
+
url: string;
|
|
23
|
+
status: number;
|
|
24
|
+
start: number;
|
|
25
|
+
duration: number;
|
|
26
|
+
}[];
|
|
27
|
+
waterfall?: {
|
|
28
|
+
name: string;
|
|
29
|
+
type: string;
|
|
30
|
+
start: number;
|
|
31
|
+
duration: number;
|
|
32
|
+
size?: number;
|
|
33
|
+
}[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface RumOptions {
|
|
37
|
+
/**
|
|
38
|
+
* Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab. `0.1` is a good start.
|
|
39
|
+
* Default: the page's `<meta name="collector-rum-sample-rate">`; without either, nothing is measured.
|
|
40
|
+
*/
|
|
41
|
+
sampleRate?: number;
|
|
42
|
+
/**
|
|
43
|
+
* Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it, and it wins
|
|
44
|
+
* over the page's `<meta name="collector-route">`.
|
|
45
|
+
*/
|
|
46
|
+
route?: (location: Location) => string | undefined;
|
|
47
|
+
/** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
|
|
48
|
+
beforeSendPageview?: (pageview: PageView) => PageView | null;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Real User Monitoring: how fast your pages are for the people using them.
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* import * as Collector from "@chrom-ar/collector";
|
|
55
|
+
* import { rum } from "@chrom-ar/collector/rum";
|
|
56
|
+
*
|
|
57
|
+
* Collector.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
declare function rum(options?: RumOptions): RumPlugin;
|
|
61
|
+
|
|
62
|
+
export { rum };
|
|
63
|
+
export type { PageView, RumOptions };
|
package/dist/rum.esm.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @chrom-ar/collector v0.5.0 | MIT */
|
|
2
|
+
function _(r){if(typeof document>"u")return;let e=document.querySelector(`meta[name="${r}"]`)?.content.trim();return e===void 0||e===""?void 0:e}function L(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let r=crypto.getRandomValues(new Uint8Array(16));r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=Array.from(r,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 A(r){let e=r.search(/[?#]/);return e===-1?r:r.slice(0,e)}var K=500;function B(r,e){try{let t=new URL(e,r);return t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(t.origin+t.pathname).slice(0,K)}catch{return}}var D=500,F=1e4,G=1e3,Q=50,Y=30,H=300,C={lcp:4e3,inp:500,nav:2500},U=()=>location.pathname,V=class{constructor(e){this.options=e;this.finished=[];this.lastKey=U();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(i=>{for(let l of i.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||U()===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(i=>i!==void 0),n=t===void 0?o.filter(i=>i.start<=e.start).sort((i,l)=>l.start-i.start)[0]:o.find(i=>i===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:A(e),this.current.named=true);}pageLoaded(){this.closed||(this.navigate(),this.current&&this.current.named!==true&&(this.current.route=this.routeFor(true)));}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){return this.lastKey=U(),{id:L(),key:this.lastKey,path:location.pathname,navigation:e,start:t,route:this.routeFor(e==="hard"),requests:[],pending:0}}routeFor(e){let t;try{t=this.options.route?.(location);}catch{}return t===void 0&&e&&(t=this.options.pageRoute?.()),t===void 0?void 0:A(t)}watch(e){this.settle?.();let t=e.start,o,n,i=s=>{clearTimeout(o),clearTimeout(h),n?.disconnect(),this.settle===a&&(this.settle=void 0),e.nav=Math.round(s);},l=()=>{e.pending===0&&i(t-e.start);},a=()=>{t=performance.now(),clearTimeout(o),o=setTimeout(l,D);},h=setTimeout(()=>{i(F);},F);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}},i={id:e.id,at:new Date(performance.timeOrigin+e.start).toISOString(),path:e.path,navigation:e.navigation};if(e.route!==void 0&&e.route!==""&&(i.route=e.route),Object.keys(n).length>0&&(i.vitals=n),e.requests.length>0&&(i.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)>C.lcp||(n.inp??0)>C.inp||(n.nav??0)>C.nav){let h=this.resources.flatMap(s=>{let f=B(location.href,s.name),g=s.start>=e.start&&(e.end===void 0||s.start<e.end);return f!==void 0&&g&&!this.options.own(s.name)?[{...s,name:f}]:[]}).sort((s,f)=>f.duration-s.duration).slice(0,Y);h.length>0&&(i.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 i}};var q="text/plain;charset=UTF-8",Z=new TextEncoder,ee=r=>Z.encode(r).length,k=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(i=>this.prepare(i)).filter(i=>this.sent.get(i.id)!==JSON.stringify(i)),n=this.batches(o);if(t!=="visible"&&(n=te(n,48e3,this.options.logger)),t==="pagehide"){for(let i of n)this.unload(i);return}if(t==="hidden"){await Promise.all(n.map(async i=>this.post(i,t)));return}for(let i of n)await this.post(i,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:i,sampleRate:l}=this.options,a=f=>{let g=JSON.stringify({v:1,sdk:t,environment:o,release:n,session:i,sample_rate:l,pageviews:f});return {body:g,pageviews:f,bytes:ee(g)}},h=[],s=[];for(let f of e){if(a([...s,f]).bytes<=32e3){s.push(f);continue}s.length>0&&h.push(a(s)),s=[f],a(s).bytes>32e3&&(this.options.logger.debug("dropped a page view that is too big to send",f.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:q}));}catch{}if(!t)try{this.options.fetch(this.options.url,{method:"POST",body:e.body,headers:{"Content-Type":q},keepalive:!0,credentials:"omit"}).catch(()=>{});}catch{}}async post(e,t){let{url:o,fetch:n,logger:i}=this.options,l={"Content-Type":q},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(f){t==="hidden"?this.unload(e):i.debug("page views not sent",f);return}let{status:s}=h;if(s===401||s===403||s===404)this.stopped=true,i.debug(`Collector turned RUM down (HTTP ${String(s)}): no more page views from this page`);else if(s===429){let f=Number.parseInt(h.headers.get("Retry-After")??"",10);this.pausedUntil=Date.now()+(f>=0?f:60)*1e3;}else (s<200||s>=300)&&i.debug(`page views dropped (HTTP ${String(s)})`);}};function te(r,e,t){let o=[],n=0;for(let i of [...r].reverse()){if(n+i.bytes>e){t.debug("an unloading page can't send this much; dropped the oldest page views");break}n+=i.bytes,o.unshift(i);}return o}async function ne(r){let e=new Response(r).body;if(!e)throw new Error("no stream");return new Response(e.pipeThrough(new CompressionStream("gzip"))).arrayBuffer()}var z="collector:rum",$;function re(){let r;try{r=sessionStorage.getItem(z);}catch{return $}if(r!==null)try{let e=JSON.parse(r);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(r,e=Math.random){let t=re();if(t?.rate===r)return {id:t.session,sampled:t.sampled};let o=r>0&&r<=1,n={session:L(),rate:r,sampled:o&&e()<r};$=n;try{sessionStorage.setItem(z,JSON.stringify(n));}catch{}return {id:n.session,sampled:n.sampled}}function I(r,e){let t=r===void 0?void 0:Reflect.get(r,e);return typeof t=="number"?t:void 0}var ie=1e3,se=5e3;function X(){let r=performance.getEntriesByType("navigation")[0],e=I(r,"activationStart")??0,t=I(r,"responseStart"),o=t===void 0?void 0:Math.max(0,t-e),n=document.visibilityState==="hidden"&&Reflect.get(document,"prerendering")!==true?0:1/0,i=1/0,l,a,h=[],s=[],f=()=>{document.visibilityState==="hidden"&&(n=Math.min(n,performance.now()));};document.addEventListener("visibilitychange",f,true);let g=[],w=(d,u,p)=>{try{if(typeof PerformanceObserver>"u"||!PerformanceObserver.supportedEntryTypes.includes(d))return;let m=new PerformanceObserver(b=>{try{u(b.getEntries());}catch{}});m.observe({type:d,buffered:!0,...p}),g.push(m);}catch{}},T=d=>{for(let u of d){let p=I(u,"interactionId")??0;p>0&&s.length<5e3&&s.push({id:p,t:u.startTime,d:u.duration});}};w("first-input",d=>{for(let u of d)i=Math.min(i,u.startTime);T(d);}),w("paint",d=>{for(let u of d)u.name==="first-contentful-paint"&&u.startTime<n&&(a=u.startTime);}),w("largest-contentful-paint",d=>{for(let u of d)u.startTime<Math.min(n,i)&&(l=u.startTime);}),w("layout-shift",d=>{for(let u of d){let p=I(u,"value");p!==void 0&&Reflect.get(u,"hadRecentInput")!==!0&&h.length<5e3&&h.push({t:u.startTime,v:p});}}),w("event",T,{durationThreshold:16});let M=d=>d===void 0?void 0:Math.round(Math.max(0,d-e)),P=(d,u)=>p=>p.t>=d&&p.t<u;return {hard(){let d={},u=M(l),p=M(a);return u!==void 0&&(d.lcp=u),p!==void 0&&(d.fcp=p),o!==void 0&&(d.ttfb=Math.round(o)),d},span(d,u){let p={},m=0,b=0,c=-1/0,v=-1/0,E=false;for(let{t:y,v:R}of h.filter(P(d,u)).sort((j,J)=>j.t-J.t))E=true,(y-v>ie||y-c>=se)&&(c=y,b=0),b+=R,v=y,m=Math.max(m,b);E&&(p.cls=m);let O=new Map;for(let{id:y,d:R}of s.filter(P(d,u)))O.set(y,Math.max(O.get(y)??0,R));let x=[...O.values()].sort((y,R)=>R-y),N=x[Math.min(x.length-1,Math.floor(x.length/50))];return N!==void 0&&(p.inp=Math.round(N)),p},prune(d){let u=p=>{let m=p.filter(b=>b.t>=d);p.splice(0,p.length,...m);};u(h),u(s);},stop(){for(let d of g)d.disconnect();document.removeEventListener("visibilitychange",f,true);}}}var oe=10,ae=5*6e4,S;function Te(r={}){return {start:e=>de(e,r)}}function de(r,e){let t=e.sampleRate??Number(_("collector-rum-sample-rate")),{id:o,sampled:n}=W(t);if(!n){r.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 i=r.url.slice(0,r.url.indexOf("/api/pageviews")),l=X(),a=new V({vitals:()=>l,route:e.route,pageRoute:()=>_("collector-route"),own:c=>c.startsWith(`${i}/`),first:S?.open??true,hardId:S?.id}),h=a.currentId();S??(S={id:h??"",open:h!==void 0});let s=new k({url:r.url,fetch:r.fetch,logger:r.logger,sdk:r.sdk,session:o,sampleRate:t,environment:r.environment,release:r.release,beforeSendPageview:e.beforeSendPageview}),f=false,g,w=()=>{f=true,clearTimeout(g),a.close(),l.stop(),document.removeEventListener("visibilitychange",d),document.removeEventListener("turbo:load",b),window.removeEventListener("pagehide",u);},T=(c,v)=>{c.length!==0&&s.send(c,v).then(()=>{s.stopped&&!f&&w();},()=>{});},M=c=>{T([...a.takeFinished(),...a.snapshot()],c);},P=()=>{clearTimeout(g),g=void 0,T(a.takeFinished(),"visible");},d=()=>{document.visibilityState==="hidden"&&M("hidden");},u=()=>{let c=[...s.undispatched(),...a.takeFinished(),...a.snapshot()];T([...new Map(c.map(v=>[v.id,v])).values()],"pagehide");};document.addEventListener("visibilitychange",d),window.addEventListener("pagehide",u);let p=()=>{S&&a.currentId()!==S.id&&(S.open=false);let c=a.finishedCount();c>=oe?P():c>0&&(g??(g=setTimeout(P,ae)));},m=c=>(...v)=>{if(!f)try{c(...v);}catch(E){r.logger.debug("RUM error",E);}},b=m(()=>{a.pageLoaded(),p();});return document.addEventListener("turbo:load",b),{session:o,requestStart:m(()=>{a.requestStart();}),request:m(c=>{a.request(c);}),navigate:m(()=>{a.navigate(),p();}),setRoute:m(c=>{a.setRoute(c);}),close:m(()=>{M("visible"),w();})}}export{Te as rum};
|