@grafana/faro-web-sdk 2.8.0 → 2.8.1

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.
Files changed (28) hide show
  1. package/dist/bundle/faro-web-sdk.iife.js +1 -1
  2. package/dist/bundle/types/instrumentations/console/instrumentation.d.ts +1 -1
  3. package/dist/bundle/types/instrumentations/csp/instrumentation.d.ts +1 -1
  4. package/dist/bundle/types/instrumentations/errors/instrumentation.d.ts +1 -1
  5. package/dist/bundle/types/instrumentations/navigation/instrumentation.d.ts +1 -1
  6. package/dist/bundle/types/instrumentations/performance/instrumentation.d.ts +1 -1
  7. package/dist/bundle/types/instrumentations/session/instrumentation.d.ts +1 -1
  8. package/dist/bundle/types/instrumentations/userActions/instrumentation.d.ts +1 -1
  9. package/dist/bundle/types/instrumentations/view/instrumentation.d.ts +1 -1
  10. package/dist/bundle/types/instrumentations/webVitals/instrumentation.d.ts +1 -1
  11. package/dist/bundle/types/transports/console/transport.d.ts +1 -1
  12. package/dist/bundle/types/transports/fetch/transport.d.ts +5 -1
  13. package/dist/cjs/transports/fetch/transport.js +77 -17
  14. package/dist/cjs/transports/fetch/transport.js.map +1 -1
  15. package/dist/esm/transports/fetch/transport.js +77 -17
  16. package/dist/esm/transports/fetch/transport.js.map +1 -1
  17. package/dist/types/instrumentations/console/instrumentation.d.ts +1 -1
  18. package/dist/types/instrumentations/csp/instrumentation.d.ts +1 -1
  19. package/dist/types/instrumentations/errors/instrumentation.d.ts +1 -1
  20. package/dist/types/instrumentations/navigation/instrumentation.d.ts +1 -1
  21. package/dist/types/instrumentations/performance/instrumentation.d.ts +1 -1
  22. package/dist/types/instrumentations/session/instrumentation.d.ts +1 -1
  23. package/dist/types/instrumentations/userActions/instrumentation.d.ts +1 -1
  24. package/dist/types/instrumentations/view/instrumentation.d.ts +1 -1
  25. package/dist/types/instrumentations/webVitals/instrumentation.d.ts +1 -1
  26. package/dist/types/transports/console/transport.d.ts +1 -1
  27. package/dist/types/transports/fetch/transport.d.ts +5 -1
  28. package/package.json +3 -3
@@ -1 +1 @@
1
- var GrafanaFaroWebSdk=function(e){"use strict";class t{constructor(e,t){var i,n;this.signalBuffer=[],this.itemLimit=null!==(i=null==t?void 0:t.itemLimit)&&void 0!==i?i:50,this.sendTimeout=null!==(n=null==t?void 0:t.sendTimeout)&&void 0!==n?n:250,this.paused=(null==t?void 0:t.paused)||!1,this.sendFn=e,this.paused||this.start(),"undefined"!=typeof document&&document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flush()})}addItem(e){this.paused||(this.signalBuffer.push(e),this.signalBuffer.length>=this.itemLimit&&this.flush())}start(){this.paused=!1,this.sendTimeout>0&&(this.flushInterval=setInterval(()=>this.flush(),this.sendTimeout))}pause(){this.paused=!0,clearInterval(this.flushInterval)}groupItems(e){const t=new Map;return e.forEach(e=>{const i=JSON.stringify(e.meta);let n=t.get(i);n=void 0===n?[e]:[...n,e],t.set(i,n)}),Array.from(t.values())}flush(){if(this.paused||0===this.signalBuffer.length)return;this.groupItems(this.signalBuffer).forEach(this.sendFn),this.signalBuffer=[]}}var i;e.TransportItemType=void 0,(i=e.TransportItemType||(e.TransportItemType={})).EXCEPTION="exception",i.LOG="log",i.MEASUREMENT="measurement",i.TRACE="trace",i.EVENT="event";const n={[e.TransportItemType.EXCEPTION]:"exceptions",[e.TransportItemType.LOG]:"logs",[e.TransportItemType.MEASUREMENT]:"measurements",[e.TransportItemType.TRACE]:"traces",[e.TransportItemType.EVENT]:"events"};function s(e,i,n,s){var o;i.debug("Initializing transports");const a=[];let l=n.paused,u=[];const c=e=>{let t=e;for(const e of u){const i=t.map(e).filter(Boolean);if(0===i.length)return[];t=r(i,n)}return t},d=e=>{const t=c(e);if(0!==t.length)for(const e of a)i.debug(`Transporting item using ${e.name}\n`,t),e.isBatched()&&e.send(t)};let p;(null===(o=n.batching)||void 0===o?void 0:o.enabled)&&(p=new t(d,{sendTimeout:n.batching.sendTimeout,itemLimit:n.batching.itemLimit,paused:l}));return{add:(...t)=>{i.debug("Adding transports"),t.forEach(t=>{i.debug(`Adding "${t.name}" transport`);a.some(e=>e===t)?i.warn(`Transport ${t.name} is already added`):(t.unpatchedConsole=e,t.internalLogger=i,t.config=n,t.metas=s,a.push(t))})},addBeforeSendHooks:(...e)=>{i.debug("Adding beforeSendHooks\n",u),e.forEach(e=>{e&&u.push(e)})},getBeforeSendHooks:()=>[...u],execute:e=>{var t;l||((null===(t=n.batching)||void 0===t?void 0:t.enabled)&&(null==p||p.addItem(e)),(e=>{var t,s;if((null===(t=n.batching)||void 0===t?void 0:t.enabled)&&a.every(e=>e.isBatched()))return;const[r]=c([e]);if(void 0!==r)for(const e of a)i.debug(`Transporting item using ${e.name}\n`,r),e.isBatched()?(null===(s=n.batching)||void 0===s?void 0:s.enabled)||e.send([r]):e.send(r)})(e))},isPaused:()=>l,pause:()=>{i.debug("Pausing transports"),null==p||p.pause(),l=!0},remove:(...e)=>{i.debug("Removing transports"),e.forEach(e=>{i.debug(`Removing "${e.name}" transport`);const t=a.indexOf(e);-1!==t?a.splice(t,1):i.warn(`Transport "${e.name}" is not added`)})},removeBeforeSendHooks:(...e)=>{u.filter(t=>!e.includes(t))},get transports(){return[...a]},unpause:()=>{i.debug("Unpausing transports"),null==p||p.start(),l=!1}}}function r(t,i){if(i.preserveOriginalError)for(const i of t)i.type===e.TransportItemType.EXCEPTION&&delete i.payload.originalError;return t}function o(e,t){return typeof e===t}function a(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function l(e,t){try{return e instanceof t}catch(e){return!1}}const u=e=>o(e,"null"),c=e=>o(e,"string"),d=e=>o(e,"number")&&!isNaN(e)||o(e,"bigint"),p=e=>o(e,"boolean"),g=e=>!u(e)&&o(e,"object"),h=e=>o(e,"function"),f=e=>a(e,"Array"),m=e=>!g(e)&&!h(e),v="undefined"!=typeof Event,b=e=>v&&l(e,Event),w="undefined"!=typeof Error,y=e=>w&&l(e,Error),S=e=>a(e,"ErrorEvent"),T=e=>a(e,"DOMError"),E=e=>a(e,"DOMException"),k="undefined"!=typeof Element,I="undefined"!=typeof Map;function x(e){return null==e||(f(e)||c(e)?0===e.length:!!g(e)&&0===Object.keys(e).length)}function O(e,t){if(e===t)return!0;if(o(e,"number")&&isNaN(e))return o(t,"number")&&isNaN(t);const i=f(e),n=f(t);if(i!==n)return!1;if(i&&n){const i=e.length;if(i!==t.length)return!1;for(let n=i;0!==n--;)if(!O(e[n],t[n]))return!1;return!0}const s=g(e),r=g(t);if(s!==r)return!1;if(e&&t&&s&&r){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let e of i)if(!n.includes(e))return!1;for(let n of i)if(!O(e[n],t[n]))return!1;return!0}return!1}function A(){return Date.now()}function L(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}function _(){return(new Date).toISOString()}function C(e){return new Date(e).toISOString()}var U;e.LogLevel=void 0,(U=e.LogLevel||(e.LogLevel={})).TRACE="trace",U.DEBUG="debug",U.INFO="info",U.LOG="log",U.WARN="warn",U.ERROR="error";const j=e.LogLevel.LOG,M=[e.LogLevel.TRACE,e.LogLevel.DEBUG,e.LogLevel.INFO,e.LogLevel.LOG,e.LogLevel.WARN,e.LogLevel.ERROR];function P(){}function N(e){const{size:t,concurrency:i}=e,n=[];let s=0;const r=()=>{if(s<i&&n.length){const{producer:e,resolve:t,reject:i}=n.shift();s++,e().then(e=>{s--,r(),t(e)},e=>{s--,r(),i(e)})}};return{add:e=>{if(n.length+s>=t)throw new Error("Task buffer full");return new Promise((t,i)=>{n.push({producer:e,resolve:t,reject:i}),r()})}}}const R="abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789";function D(e=10){const t=new Uint32Array(e),i="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(null==i?void 0:i.getRandomValues)i.getRandomValues(t);else for(let i=0;i<e;i++)t[i]=Math.floor(4294967296*Math.random());let n="";for(let i=0;i<e;i++)n+=R[t[i]%59];return n}const z="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:void 0;function q(e){const t=`__faroBundleId_${e}`,i=null==z?void 0:z[t];if("string"==typeof i&&""!==i)return i;const n="undefined"!=typeof window?window[t]:void 0;return"string"==typeof n&&""!==n?n:void 0}function B(e={}){return JSON.stringify(null!=e?e:{},function(){const e=new WeakSet;return function(t,i){if(g(i)&&null!==i){if(e.has(i))return null;e.add(i)}return i}}())}function F(e={}){const t={};for(const[i,n]of Object.entries(e))t[i]=g(n)&&null!==n?B(n):String(n);return t}class V{constructor(){this.subscribers=[]}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>this.unsubscribe(e)}}unsubscribe(e){this.subscribers=this.subscribers.filter(t=>t!==e)}notify(e){this.subscribers.forEach(t=>t(e))}first(){const e=new V,t=t=>{e.notify(t),i.unsubscribe()},i=this.subscribe(t),n=e.unsubscribe.bind(e);return this.withUnsubscribeOverride(e,n,t)}takeWhile(e){const t=new V,i=n=>{e(n)?t.notify(n):t.unsubscribe(i)};this.subscribe(i);const n=t.unsubscribe.bind(t);return this.withUnsubscribeOverride(t,n,i)}filter(e){const t=new V,i=i=>{e(i)&&t.notify(i)};this.subscribe(i);const n=t.unsubscribe.bind(t);return this.withUnsubscribeOverride(t,n,i)}merge(...e){const t=new V,i=[];e.forEach(e=>{const n=e.subscribe(e=>{t.notify(e)});i.push(n)});const n=t.unsubscribeAll.bind(t);return t.unsubscribe=()=>{i.forEach(e=>e.unsubscribe()),n()},t}withUnsubscribeOverride(e,t,i){return e.unsubscribe=e=>{t(e),this.unsubscribe(i)},e}unsubscribeAll(){this.subscribers=[]}}var $;e.InternalLoggerLevel=void 0,($=e.InternalLoggerLevel||(e.InternalLoggerLevel={}))[$.OFF=0]="OFF",$[$.ERROR=1]="ERROR",$[$.WARN=2]="WARN",$[$.INFO=3]="INFO",$[$.VERBOSE=4]="VERBOSE";const H={debug:P,error:P,info:P,prefix:"Faro",warn:P},G=e.InternalLoggerLevel.ERROR,W=Object.assign({},console);let K=W;function X(e){var t;return K=null!==(t=e.unpatchedConsole)&&void 0!==t?t:K,K}function J(t=W,i=G){const n=H;return i>e.InternalLoggerLevel.OFF&&(n.error=i>=e.InternalLoggerLevel.ERROR?function(...e){t.error(`${n.prefix}\n`,...e)}:P,n.warn=i>=e.InternalLoggerLevel.WARN?function(...e){t.warn(`${n.prefix}\n`,...e)}:P,n.info=i>=e.InternalLoggerLevel.INFO?function(...e){t.info(`${n.prefix}\n`,...e)}:P,n.debug=i>=e.InternalLoggerLevel.VERBOSE?function(...e){t.debug(`${n.prefix}\n`,...e)}:P),n}let Z=H;function Y(e,t){return Z=J(e,t.internalLoggerLevel),Z}class Q{constructor(){this.unpatchedConsole=W,this.internalLogger=H,this.config={},this.metas={}}logDebug(...e){this.internalLogger.debug(`${this.name}\n`,...e)}logInfo(...e){this.internalLogger.info(`${this.name}\n`,...e)}logWarn(...e){this.internalLogger.warn(`${this.name}\n`,...e)}logError(...e){this.internalLogger.error(`${this.name}\n`,...e)}}class ee extends Q{isBatched(){return!1}getIgnoreUrls(){return[]}}function te(e,t){var i,n;if(void 0===t)return e;if(void 0===e)return{resourceSpans:t};const s=null===(i=e.resourceSpans)||void 0===i?void 0:i[0];if(void 0===s)return e;const r=(null==s?void 0:s.scopeSpans)||[],o=(null===(n=null==t?void 0:t[0])||void 0===n?void 0:n.scopeSpans)||[];return Object.assign(Object.assign({},e),{resourceSpans:[Object.assign(Object.assign({},s),{scopeSpans:[...r,...o]})]})}function ie(t){let i={meta:{}};return void 0!==t[0]&&(i.meta=t[0].meta),t.forEach(t=>{switch(t.type){case e.TransportItemType.LOG:case e.TransportItemType.EVENT:case e.TransportItemType.EXCEPTION:case e.TransportItemType.MEASUREMENT:{const e=n[t.type],s=i[e];i=Object.assign(Object.assign({},i),{[e]:void 0===s?[t.payload]:[...s,t.payload]});break}case e.TransportItemType.TRACE:i=Object.assign(Object.assign({},i),{traces:te(i.traces,t.payload.resourceSpans)})}}),i}const ne="normal";var se;e.UserActionState=void 0,(se=e.UserActionState||(e.UserActionState={}))[se.Started=0]="Started",se[se.Halted=1]="Halted",se[se.Cancelled=2]="Cancelled",se[se.Ended=3]="Ended";class re{constructor(){this.buffer=[]}addItem(e){this.buffer.push(e)}flushBuffer(e){if(h(e))for(const t of this.buffer)e(t);this.buffer.length=0}size(){return this.buffer.length}}class oe extends V{constructor({name:t,parentId:i,trigger:n,transports:s,attributes:r,trackUserActionsExcludeItem:o,importance:a=ne,pushEvent:l}){super(),this.name=t,this.attributes=r,this.id=D(),this.trigger=n,this.parentId=null!=i?i:this.id,this.trackUserActionsExcludeItem=o,this.importance=a,this._pushEvent=l,this._itemBuffer=new re,this._transports=s,this._state=e.UserActionState.Started,this._start()}addItem(t){return this._state===e.UserActionState.Started&&(this._itemBuffer.addItem(t),!0)}_start(){this._state=e.UserActionState.Started,this._state===e.UserActionState.Started&&(this.startTime=A(),this._startTimeMono=L())}halt(){this._state===e.UserActionState.Started&&(this._state=e.UserActionState.Halted,this.notify(this._state))}cancel(){this._state===e.UserActionState.Started&&this._itemBuffer.flushBuffer(e=>{this._transports.execute(e)}),this._state=e.UserActionState.Cancelled,this.notify(this._state)}end(){if(this._state===e.UserActionState.Cancelled)return;const t=A(),i=L()-this._startTimeMono;this._state=e.UserActionState.Ended,this._itemBuffer.flushBuffer(t=>{if(function(t,i){return(null==i?void 0:i(t))||t.type===e.TransportItemType.MEASUREMENT&&"web-vitals"===t.payload.type}(t,this.trackUserActionsExcludeItem))return void this._transports.execute(t);const i=Object.assign(Object.assign({},t),{payload:Object.assign(Object.assign({},t.payload),{action:{parentId:this.id,name:this.name}})});this._transports.execute(i)}),this._state=e.UserActionState.Ended,this.notify(this._state),this._pushEvent("faro.user.action",Object.assign({userActionName:this.name,userActionStartTime:this.startTime.toString(),userActionEndTime:t.toString(),userActionDuration:i.toString(),userActionTrigger:this.trigger,userActionImportance:this.importance},F(this.attributes)),void 0,{timestampOverwriteMs:this.startTime,customPayloadTransformer:e=>(e.action={id:this.id,name:this.name},e)})}getState(){return this._state}}const ae=new V;function le(t,i){if(!t)return!1;return(null==t?void 0:t.getState())===e.UserActionState.Started&&(t.addItem(i),!0)}const ue="Error",ce=e=>e.map(e=>g(e)?B(e):String(e)).join(" ");let de;function pe({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){var a;t.debug("Initializing exceptions API");let l=null;de=null!==(a=i.parseStacktrace)&&void 0!==a?a:de;const d=e=>{t.debug("Changing stacktrace parser"),de=null!=e?e:de},{ignoreErrors:p=[],preserveOriginalError:h}=i;return d(i.parseStacktrace),{changeStacktraceParser:d,getStacktraceParser:()=>de,pushError:(a,{skipDedupe:d,stackFrames:m,type:v,context:b,spanContext:w,timestampOverwriteMs:S,originalError:T,fingerprint:E,fatal:k}={})=>{var I;if(!function(e,t){const{message:i,name:n,stack:s}=t;return r=e,o=i+" "+n+" "+s,r.some(e=>c(e)?o.includes(e):!!o.match(e));var r,o}(p,null!=T?T:a))try{const c=F(Object.assign(Object.assign({},function(e){let t=e.cause;y(t)?t=e.cause.toString():null!==t&&(g(e.cause)||f(e.cause))?t=B(e.cause):null!=t&&(t=e.cause.toString());return null==t?{}:{cause:t}}(null!=T?T:a)),null!=b?b:{})),p={meta:n.value,payload:Object.assign(Object.assign(Object.assign(Object.assign({type:v||a.name||ue,value:a.message,timestamp:S?C(S):_(),trace:w?{trace_id:w.traceId,span_id:w.spanId}:r.getTraceContext()},x(c)?{}:{context:c}),h?{originalError:T}:{}),E?{fingerprint:E}:{}),void 0!==k?{fatal:k}:{}),type:e.TransportItemType.EXCEPTION};(null==(m=null!=m?m:a.stack?null==de?void 0:de(a).frames:void 0)?void 0:m.length)&&(p.payload.stacktrace={frames:m});const A={type:p.payload.type,value:p.payload.value,stacktrace:p.payload.stacktrace,context:p.payload.context,fingerprint:p.payload.fingerprint,fatal:null!==(I=p.payload.fatal)&&void 0!==I&&I};if(!d&&i.dedupe&&!u(l)&&O(A,l))return void t.debug("Skipping error push because it is the same as the last one\n",p.payload);l=A,t.debug("Pushing exception\n",p),le(o.getActiveUserAction(),p)||s.execute(p)}catch(e){t.error("Error pushing event",e)}}}}const ge=e=>e.map(e=>{try{return String(e)}catch(e){return""}}).join(" ");function he(t,i,n,s,r){i.debug("Initializing API");let o=null;const a=function({transports:t,internalLogger:i,config:n,pushEvent:s}){var r;const o=null===(r=n.userActionsInstrumentation)||void 0===r?void 0:r.excludeItem;let a;const l=()=>a,u={startUserAction:(n,r,u)=>{if(void 0===l()){const i=new oe({name:n,transports:t,attributes:r,trigger:(null==u?void 0:u.triggerName)||"faroApiCall",importance:(null==u?void 0:u.importance)||ne,trackUserActionsExcludeItem:o,pushEvent:s});return i.filter(t=>[e.UserActionState.Ended,e.UserActionState.Cancelled].includes(t)).first().subscribe(()=>{a=void 0}),ae.notify({type:"user_action_start",userAction:i}),a=i,a}i.error("Attempted to create a new user action while one is already running. This is not possible.")},getActiveUserAction:l};return u}({transports:r,config:n,internalLogger:i,pushEvent:(e,t,n,s)=>{o?o(e,t,n,s):i.warn("pushEventImpl is not initialized. Event dropped:",{name:e,attributes:t,domain:n,options:s})}}),l=function(t,i,n,s,r){let o;return i.debug("Initializing traces API"),{getOTEL:()=>o,getTraceContext:()=>{const e=null==o?void 0:o.trace.getSpanContext(o.context.active());return e?{trace_id:e.traceId,span_id:e.spanId}:void 0},initOTEL:(e,t)=>{i.debug("Initializing OpenTelemetry"),o={trace:e,context:t}},isOTELInitialized:()=>!!o,pushTraces:t=>{try{const n={type:e.TransportItemType.TRACE,payload:t,meta:s.value};i.debug("Pushing trace\n",n),r.execute(n)}catch(e){i.error("Error pushing trace\n",e)}}}}(0,i,0,s,r),d={internalLogger:i,userActionsApi:a,config:n,metas:s,transports:r,tracesApi:l},p=function({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){let a=null;return{pushEvent:(l,c,d,{skipDedupe:p,spanContext:g,timestampOverwriteMs:h,customPayloadTransformer:f=e=>e}={})=>{try{const m=F(c),v={meta:n.value,payload:f({name:l,domain:null!=d?d:i.eventDomain,attributes:x(m)?void 0:m,timestamp:h?C(h):_(),trace:g?{trace_id:g.traceId,span_id:g.spanId}:r.getTraceContext()}),type:e.TransportItemType.EVENT},b={name:v.payload.name,attributes:v.payload.attributes,domain:v.payload.domain};if(!p&&i.dedupe&&!u(a)&&O(b,a))return void t.debug("Skipping event push because it is the same as the last one\n",v.payload);a=b,t.debug("Pushing event\n",v),le(o.getActiveUserAction(),v)||s.execute(v)}catch(e){t.error("Error pushing event",e)}}}}(d);return o=p.pushEvent,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l),pe(d)),function({internalLogger:e,metas:t}){let i,n,s,r;e.debug("Initializing meta API");const o=e=>{n&&t.remove(n),n={user:e},t.add(n)},a=(e,n)=>{var s;const r=null==n?void 0:n.overrides,o=r?{overrides:Object.assign(Object.assign({},null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.overrides),r)}:{};i&&t.remove(i),i={session:Object.assign(Object.assign({},x(e)?void 0:e),o)},t.add(i)},l=()=>t.value.session,u=()=>t.value.page;return{setUser:o,resetUser:o,setSession:a,resetSession:a,getSession:l,setView:(e,i)=>{var n;if((null==i?void 0:i.overrides)&&a(l(),{overrides:i.overrides}),(null===(n=null==s?void 0:s.view)||void 0===n?void 0:n.name)===(null==e?void 0:e.name))return;const r=s;s={view:e},t.add(s),r&&t.remove(r)},getView:()=>t.value.view,setPage:e=>{var i;const n=c(e)?Object.assign(Object.assign({},null!==(i=null==r?void 0:r.page)&&void 0!==i?i:u()),{id:e}):e;r&&t.remove(r),r={page:n},t.add(r)},getPage:u}}(d)),function({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){var a;t.debug("Initializing logs API");let l=null;const c=null!==(a=i.logArgsSerializer)&&void 0!==a?a:ge;return{pushLog:(a,{context:d,level:p,skipDedupe:g,spanContext:h,timestampOverwriteMs:f}={})=>{try{const m=F(d),v={type:e.TransportItemType.LOG,payload:{message:c(a),level:null!=p?p:j,context:x(m)?void 0:m,timestamp:f?C(f):_(),trace:h?{trace_id:h.traceId,span_id:h.spanId}:r.getTraceContext()},meta:n.value},b={message:v.payload.message,level:v.payload.level,context:v.payload.context};if(!g&&i.dedupe&&!u(l)&&O(b,l))return void t.debug("Skipping log push because it is the same as the last one\n",v.payload);l=b,t.debug("Pushing log\n",v),le(o.getActiveUserAction(),v)||s.execute(v)}catch(e){t.error("Error pushing log\n",e)}}}}(d)),function({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){t.debug("Initializing measurements API");let a=null;return{pushMeasurement:(l,{skipDedupe:c,context:d,spanContext:p,timestampOverwriteMs:g}={})=>{try{const h=F(d),f={type:e.TransportItemType.MEASUREMENT,payload:Object.assign(Object.assign({},l),{trace:p?{trace_id:p.traceId,span_id:p.spanId}:r.getTraceContext(),timestamp:g?C(g):_(),context:x(h)?void 0:h}),meta:n.value},m={type:f.payload.type,values:f.payload.values,context:f.payload.context};if(!c&&i.dedupe&&!u(a)&&O(m,a))return void t.debug("Skipping measurement push because it is the same as the last one\n",f.payload);a=m,t.debug("Pushing measurement\n",f),le(o.getActiveUserAction(),f)||s.execute(f)}catch(e){t.error("Error pushing measurement\n",e)}}}}(d)),p),a)}class fe extends Q{constructor(){super(...arguments),this.api={},this.transports={}}}const me="2.8.0";function ve(e){var t,i;const n=e.config.app.name,s=n?function(e){return null==z?void 0:z[`__faroGitHash_${e}`]}(n):void 0,r={sdk:{version:me,name:"faro"},app:Object.assign({bundleId:n&&q(n)},void 0!==s?{gitHash:s}:{})},o=null===(t=e.config.sessionTracking)||void 0===t?void 0:t.session;o&&e.api.setSession(o),e.config.app&&(r.app=Object.assign(Object.assign({},e.config.app),r.app)),e.config.user&&(r.user=e.config.user),e.config.view&&(r.view=e.config.view),e.metas.add(r,...null!==(i=e.config.metas)&&void 0!==i?i:[])}const be="_faroInternal";function we(e){e.config.isolate?e.internalLogger.debug("Skipping registering internal Faro instance on global object"):(e.internalLogger.debug("Registering internal Faro instance on global object"),Object.defineProperty(z,be,{configurable:!1,enumerable:!1,writable:!1,value:e}))}function ye(){return be in z}function Se(t,i,n,s,r,o,a){return i.debug("Initializing Faro"),e.faro={api:o,config:n,instrumentations:a,internalLogger:i,metas:s,pause:r.pause,transports:r,unpatchedConsole:t,unpause:r.unpause},we(e.faro),function(e){if(e.config.preventGlobalExposure)e.internalLogger.debug("Skipping registering public Faro instance in the global scope");else{if(e.internalLogger.debug(`Registering public faro reference in the global scope using "${e.config.globalObjectKey}" key`),e.config.globalObjectKey in z)return void e.internalLogger.warn(`Skipping global registration due to key "${e.config.globalObjectKey}" being used already. Please set "globalObjectKey" to something else or set "preventGlobalExposure" to "true"`);Object.defineProperty(z,e.config.globalObjectKey,{configurable:!1,writable:!1,value:e})}}(e.faro),e.faro}function Te(e){const t=X(e),i=Y(t,e);if(ye()&&!e.isolate)return void i.error('Faro is already registered. Either add instrumentations, transports etc. to the global faro instance or use the "isolate" property');i.debug("Initializing");const n=function(e,t){let i=[],n=[];const s=()=>i.reduce((e,t)=>Object.assign(e,h(t)?t():t),{}),r=()=>{if(n.length){const e=s();n.forEach(t=>t(e))}};return{add:(...e)=>{t.debug("Adding metas\n",e),i.push(...e),r()},remove:(...e)=>{t.debug("Removing metas\n",e),i=i.filter(t=>!e.includes(t)),r()},addListener:e=>{t.debug("Adding metas listener\n",e),n.push(e)},removeListener:e=>{t.debug("Removing metas listener\n",e),n=n.filter(t=>t!==e)},get value(){return s()}}}(0,i),r=s(t,i,e,n),o=he(0,i,e,n,r),a=function(e,t,i,n,s,r){t.debug("Initializing instrumentations");const o=[];return{add:(...a)=>{t.debug("Adding instrumentations"),a.forEach(a=>{t.debug(`Adding "${a.name}" instrumentation`),o.some(e=>e.name===a.name)?t.warn(`Instrumentation ${a.name} is already added`):(a.unpatchedConsole=e,a.internalLogger=t,a.config=i,a.metas=n,a.transports=s,a.api=r,o.push(a),a.initialize())})},get instrumentations(){return[...o]},remove:(...e)=>{t.debug("Removing instrumentations"),e.forEach(e=>{var i,n;t.debug(`Removing "${e.name}" instrumentation`);const s=o.reduce((t,i,n)=>null===t&&i.name===e.name?n:null,null);null!==s?(null===(n=(i=o[s]).destroy)||void 0===n||n.call(i),o.splice(s,1)):t.warn(`Instrumentation "${e.name}" is not added`)})}}}(t,i,e,n,r,o),l=Se(t,i,e,n,r,o,a);return ve(l),function(e){e.transports.add(...e.config.transports),e.transports.addBeforeSendHooks(e.config.beforeSend)}(l),function(e){e.instrumentations.add(...e.config.instrumentations)}(l),l}e.faro={api:{pushLog:()=>{},pushError:()=>{},changeStacktraceParser:()=>{},getStacktraceParser:()=>{},pushMeasurement:()=>{},pushTraces:()=>{},getOTEL:()=>{},getTraceContext:()=>{},initOTEL:()=>{},isOTELInitialized:()=>!1,setUser:()=>{},resetUser:()=>{},setSession:()=>{},resetSession:()=>{},getSession:()=>{},setView:()=>{},getView:()=>{},setPage:()=>{},getPage:()=>{},pushEvent:()=>{},startUserAction:()=>{},getActiveUserAction:()=>{}}};const Ee="faro",ke={enabled:!0,sendTimeout:250,itemLimit:50},Ie="view_changed",xe="session_start",Oe="session_resume",Ae="session_extend",Le="service_name_override",_e="unknown";var Ce,Ue={exports:{}},je=Ue.exports;var Me=(Ce||(Ce=1,function(e,t){!function(i,n){var s="function",r="undefined",o="object",a="string",l="major",u="model",c="name",d="type",p="vendor",g="version",h="architecture",f="console",m="mobile",v="tablet",b="smarttv",w="wearable",y="embedded",S="Amazon",T="Apple",E="ASUS",k="BlackBerry",I="Browser",x="Chrome",O="Firefox",A="Google",L="Honor",_="Huawei",C="LG",U="Microsoft",j="Motorola",M="Nvidia",P="OnePlus",N="Opera",R="OPPO",D="Samsung",z="Sharp",q="Sony",B="Xiaomi",F="Zebra",V="Facebook",$="Chromium OS",H="Mac OS",G=" Browser",W=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},K=function(e,t){return typeof e===a&&-1!==X(t).indexOf(X(e))},X=function(e){return e.toLowerCase()},J=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===r?e:e.substring(0,500)},Z=function(e,t){for(var i,r,a,l,u,c,d=0;d<t.length&&!u;){var p=t[d],g=t[d+1];for(i=r=0;i<p.length&&!u&&p[i];)if(u=p[i++].exec(e))for(a=0;a<g.length;a++)c=u[++r],typeof(l=g[a])===o&&l.length>0?2===l.length?typeof l[1]==s?this[l[0]]=l[1].call(this,c):this[l[0]]=l[1]:3===l.length?typeof l[1]!==s||l[1].exec&&l[1].test?this[l[0]]=c?c.replace(l[1],l[2]):n:this[l[0]]=c?l[1].call(this,c,l[2]):n:4===l.length&&(this[l[0]]=c?l[3].call(this,c.replace(l[1],l[2])):n):this[l]=c||n;d+=2}},Y=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var s=0;s<t[i].length;s++)if(K(t[i][s],e))return"?"===i?n:i}else if(K(t[i],e))return"?"===i?n:i;return t.hasOwnProperty("*")?t["*"]:e},Q={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},ee={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[g,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[g,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,g],[/opios[\/ ]+([\w\.]+)/i],[g,[c,N+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[g,[c,N+" GX"]],[/\bopr\/([\w\.]+)/i],[g,[c,N]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[g,[c,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[g,[c,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[c,g],[/quark(?:pc)?\/([-\w\.]+)/i],[g,[c,"Quark"]],[/\bddg\/([\w\.]+)/i],[g,[c,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[g,[c,"UC"+I]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[g,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[g,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[g,[c,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[g,[c,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[g,[c,"Smart Lenovo "+I]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+I],g],[/\bfocus\/([\w\.]+)/i],[g,[c,O+" Focus"]],[/\bopt\/([\w\.]+)/i],[g,[c,N+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[g,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[g,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[g,[c,N+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[g,[c,"MIUI"+G]],[/fxios\/([\w\.-]+)/i],[g,[c,O]],[/\bqihoobrowser\/?([\w\.]*)/i],[g,[c,"360"]],[/\b(qq)\/([\w\.]+)/i],[[c,/(.+)/,"$1Browser"],g],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1"+G],g],[/samsungbrowser\/([\w\.]+)/i],[g,[c,D+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[g,[c,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[c,"Sogou Mobile"],g],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[c,g],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[c],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[g,c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,V],g],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[c,g],[/\bgsa\/([\w\.]+) .*safari\//i],[g,[c,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[g,[c,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[g,[c,x+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,x+" WebView"],g],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[g,[c,"Android "+I]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,g],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[g,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[g,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[g,Y,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[c,g],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],g],[/(wolvic|librewolf)\/([\w\.]+)/i],[c,g],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[g,[c,O+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[c,[g,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[c,[g,/master.|lts./,""]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[h,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[h,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[h,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[h,/ower/,"",X]],[/ sun4\w[;\)]/i],[[h,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[h,X]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[u,[p,D],[d,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[p,D],[d,m]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[p,T],[d,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[p,T],[d,v]],[/(macintosh);/i],[u,[p,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[p,z],[d,m]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[u,[p,L],[d,v]],[/honor([-\w ]+)[;\)]/i],[u,[p,L],[d,m]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[u,[p,_],[d,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[p,_],[d,m]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[u,/_/g," "],[p,B],[d,v]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[u,/_/g," "],[p,B],[d,m]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[p,R],[d,m]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[u,[p,Y,{OnePlus:["304","403","203"],"*":R}],[d,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[p,"Vivo"],[d,m]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[p,"Realme"],[d,m]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[u,[p,j],[d,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[p,j],[d,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[p,C],[d,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[p,C],[d,m]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[u,[p,"Lenovo"],[d,v]],[/(nokia) (t[12][01])/i],[p,u,[d,v]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[u,/_/g," "],[d,m],[p,"Nokia"]],[/(pixel (c|tablet))\b/i],[u,[p,A],[d,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[p,A],[d,m]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[u,[p,q],[d,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[p,q],[d,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[p,P],[d,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[p,S],[d,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[p,S],[d,m]],[/(playbook);[-\w\),; ]+(rim)/i],[u,p,[d,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[p,k],[d,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[p,E],[d,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[p,E],[d,m]],[/(nexus 9)/i],[u,[p,"HTC"],[d,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[u,/_/g," "],[d,m]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[u,[p,"TCL"],[d,v]],[/(itel) ((\w+))/i],[[p,X],u,[d,Y,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[p,"Acer"],[d,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[p,"Meizu"],[d,m]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[p,"Ulefone"],[d,m]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[p,"Energizer"],[d,m]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[p,"Cat"],[d,m]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[p,"Smartfren"],[d,m]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[p,"Nothing"],[d,m]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[u,[p,"Archos"],[d,v]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[u,[p,"Archos"],[d,m]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[p,u,[d,v]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[p,u,[d,m]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,u,[d,v]],[/(surface duo)/i],[u,[p,U],[d,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[p,"Fairphone"],[d,m]],[/(u304aa)/i],[u,[p,"AT&T"],[d,m]],[/\bsie-(\w*)/i],[u,[p,"Siemens"],[d,m]],[/\b(rct\w+) b/i],[u,[p,"RCA"],[d,v]],[/\b(venue[\d ]{2,7}) b/i],[u,[p,"Dell"],[d,v]],[/\b(q(?:mv|ta)\w+) b/i],[u,[p,"Verizon"],[d,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[u,[p,"Barnes & Noble"],[d,v]],[/\b(tm\d{3}\w+) b/i],[u,[p,"NuVision"],[d,v]],[/\b(k88) b/i],[u,[p,"ZTE"],[d,v]],[/\b(nx\d{3}j) b/i],[u,[p,"ZTE"],[d,m]],[/\b(gen\d{3}) b.+49h/i],[u,[p,"Swiss"],[d,m]],[/\b(zur\d{3}) b/i],[u,[p,"Swiss"],[d,v]],[/\b((zeki)?tb.*\b) b/i],[u,[p,"Zeki"],[d,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],u,[d,v]],[/\b(ns-?\w{0,9}) b/i],[u,[p,"Insignia"],[d,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[u,[p,"NextBook"],[d,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],u,[d,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],u,[d,m]],[/\b(ph-1) /i],[u,[p,"Essential"],[d,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[u,[p,"Envizen"],[d,v]],[/\b(trio[-\w\. ]+) b/i],[u,[p,"MachSpeed"],[d,v]],[/\btu_(1491) b/i],[u,[p,"Rotor"],[d,v]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[u,[p,M],[d,v]],[/(sprint) (\w+)/i],[p,u,[d,m]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[p,U],[d,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[p,F],[d,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[p,F],[d,m]],[/smart-tv.+(samsung)/i],[p,[d,b]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[p,D],[d,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,C],[d,b]],[/(apple) ?tv/i],[p,[u,T+" TV"],[d,b]],[/crkey/i],[[u,x+"cast"],[p,A],[d,b]],[/droid.+aft(\w+)( bui|\))/i],[u,[p,S],[d,b]],[/(shield \w+ tv)/i],[u,[p,M],[d,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[p,z],[d,b]],[/(bravia[\w ]+)( bui|\))/i],[u,[p,q],[d,b]],[/(mi(tv|box)-?\w+) bui/i],[u,[p,B],[d,b]],[/Hbbtv.*(technisat) (.*);/i],[p,u,[d,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,J],[u,J],[d,b]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[u,[d,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,u,[d,f]],[/droid.+; (shield)( bui|\))/i],[u,[p,M],[d,f]],[/(playstation \w+)/i],[u,[p,q],[d,f]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[p,U],[d,f]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[u,[p,D],[d,w]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[p,u,[d,w]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[u,[p,R],[d,w]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[p,T],[d,w]],[/(opwwe\d{3})/i],[u,[p,P],[d,w]],[/(moto 360)/i],[u,[p,j],[d,w]],[/(smartwatch 3)/i],[u,[p,q],[d,w]],[/(g watch r)/i],[u,[p,C],[d,w]],[/droid.+; (wt63?0{2,3})\)/i],[u,[p,F],[d,w]],[/droid.+; (glass) \d/i],[u,[p,A],[d,w]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,u,[d,w]],[/; (quest( \d| pro)?)/i],[u,[p,V],[d,w]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[d,y]],[/(aeobc)\b/i],[u,[p,S],[d,y]],[/(homepod).+mac os/i],[u,[p,T],[d,y]],[/windows iot/i],[[d,y]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[d,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[d,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,m]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[u,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[g,[c,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[c,g],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[g,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[c,g],[/ladybird\//i],[[c,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[g,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,g],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[c,[g,Y,Q]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[g,Y,Q],[c,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[g,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,H],[g,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[g,c],[/(ubuntu) ([\w\.]+) like android/i],[[c,/(.+)/,"$1 Touch"],g],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[c,g],[/\(bb(10);/i],[g,[c,k]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[g,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[g,[c,O+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[g,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[g,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[g,[c,x+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,$],g],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,g],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],g],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[c,g]]},te=function(e,t){if(typeof e===o&&(t=e,e=n),!(this instanceof te))return new te(e,t).getResult();var f=typeof i!==r&&i.navigator?i.navigator:n,b=e||(f&&f.userAgent?f.userAgent:""),w=f&&f.userAgentData?f.userAgentData:n,y=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(ee,t):ee,S=f&&f.userAgent==b;return this.getBrowser=function(){var e,t={};return t[c]=n,t[g]=n,Z.call(t,b,y.browser),t[l]=typeof(e=t[g])===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n,S&&f&&f.brave&&typeof f.brave.isBrave==s&&(t[c]="Brave"),t},this.getCPU=function(){var e={};return e[h]=n,Z.call(e,b,y.cpu),e},this.getDevice=function(){var e={};return e[p]=n,e[u]=n,e[d]=n,Z.call(e,b,y.device),S&&!e[d]&&w&&w.mobile&&(e[d]=m),S&&"Macintosh"==e[u]&&f&&typeof f.standalone!==r&&f.maxTouchPoints&&f.maxTouchPoints>2&&(e[u]="iPad",e[d]=v),e},this.getEngine=function(){var e={};return e[c]=n,e[g]=n,Z.call(e,b,y.engine),e},this.getOS=function(){var e={};return e[c]=n,e[g]=n,Z.call(e,b,y.os),S&&!e[c]&&w&&w.platform&&"Unknown"!=w.platform&&(e[c]=w.platform.replace(/chrome os/i,$).replace(/macos/i,H)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===a&&e.length>500?J(e,500):e,this},this.setUA(b),this};te.VERSION="1.0.41",te.BROWSER=W([c,g,l]),te.CPU=W([h]),te.DEVICE=W([u,p,d,f,m,b,v,w,y]),te.ENGINE=te.OS=W([c,g]),e.exports&&(t=e.exports=te),t.UAParser=te;var ie=typeof i!==r&&(i.jQuery||i.Zepto);if(ie&&!ie.ua){var ne=new te;ie.ua=ne.getResult(),ie.ua.get=function(){return ne.getUA()},ie.ua.set=function(e){ne.setUA(e);var t=ne.getResult();for(var i in t)ie.ua[i]=t[i]}}}("object"==typeof window?window:je)}(Ue,Ue.exports)),Ue.exports);let Pe,Ne;function Re(){const e="undefined"!=typeof navigator?navigator.userAgent:"";return Pe===e&&Ne||(Ne=new Me.UAParser(e).getResult(),Pe=e),Ne}const De=()=>{const{browser:e,os:t,ua:i}=Re(),{name:n,version:s}=e,{name:r,version:o}=t,a=navigator.language,l=i.includes("Mobi"),u=function(){if(!n||!s)return;if("userAgentData"in navigator&&navigator.userAgentData)return navigator.userAgentData.brands;return}();return{browser:{name:null!=n?n:_e,version:null!=s?s:_e,os:`${null!=r?r:_e} ${null!=o?o:_e}`,userAgent:null!=i?i:_e,language:null!=a?a:_e,mobile:l,brands:null!=u?u:_e,viewportWidth:`${window.innerWidth}`,viewportHeight:`${window.innerHeight}`}}},ze=()=>{const{name:e,version:t}=Re().os;if(!e&&!t)return{};const i={};return e&&(i.name=e),t&&(i.version=t),{os:i}};function qe(t){var i,n,s,r;return{id:null!==(r=null===(s=null===(n=null===(i=e.faro.config)||void 0===i?void 0:i.sessionTracking)||void 0===n?void 0:n.generateSessionId)||void 0===s?void 0:s.call(n))&&void 0!==r?r:D(),attributes:t}}const Be=()=>({sdk:{name:"faro-web",version:me}}),Fe="sessionStorage",Ve="localStorage";function $e(t){var i;try{let e;e=window[t];const i="__faro_storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(n){return null===(i=e.faro.internalLogger)||void 0===i||i.info(`Web storage of type ${t} is not available. Reason: ${n}`),!1}}function He(e,t){return Je(t)?window[t].getItem(e):null}function Ge(e,t,i){if(Je(i))try{window[i].setItem(e,t)}catch(e){}}function We(e,t){Je(t)&&window[t].removeItem(e)}const Ke=$e(Ve),Xe=$e(Fe);function Je(e){return e===Ve?Ke:e===Fe&&Xe}function Ze(e,t){let i,n=!1;const s=()=>{null!=i?(e(...i),i=null,setTimeout(s,t)):n=!1};return(...r)=>{n?i=r:(e(...r),n=!0,setTimeout(s,t))}}function Ye(){return e.faro.transports.transports.flatMap(e=>e.getIgnoreUrls())}function Qe(e=""){return Ye().some(t=>e&&null!=e.match(t))}function et(e){return c(e)?e:e instanceof URL?e.href:!x(e)&&h(null==e?void 0:e.toString)?e.toString():void 0}const tt="com.grafana.faro.session",it=144e5,nt=9e5,st=nt,rt={enabled:!0,persistent:!1,maxSessionPersistenceTime:st};function ot(){var t,i,n;const s=e.faro.config.sessionTracking,r=null!==(n=null!==(i=null===(t=null==s?void 0:s.sampler)||void 0===t?void 0:t.call(s,{metas:e.faro.metas.value}))&&void 0!==i?i:null==s?void 0:s.samplingRate)&&void 0!==n?n:1,o="number"==typeof r?function(e){return Math.min(1,Math.max(0,e))}(r):0;return Math.random()<o}function at({sessionId:t,started:i,lastActivity:n,isSampled:s=!0}={}){var r,o;const a=A(),l=null===(o=null===(r=e.faro.config)||void 0===r?void 0:r.sessionTracking)||void 0===o?void 0:o.generateSessionId;return null==t&&(t="function"==typeof l?l():D()),{sessionId:t,lastActivity:null!=n?n:a,started:null!=i?i:a,isSampled:s}}function lt(e){if(null==e)return!1;const t=A();if(!(t-e.started<it))return!1;return t-e.lastActivity<nt}function ut({fetchUserSession:t,storeUserSession:i}){return function({forceSessionExtend:n}={forceSessionExtend:!1}){var s,r,o;if(!t||!i)return;const a=e.faro.config.sessionTracking,l=null==a?void 0:a.persistent;if(l&&!Ke||!l&&!Xe)return;const u=t();if(!1===n&&lt(u))i(Object.assign(Object.assign({},u),{lastActivity:A()}));else{let t=ct(at({isSampled:ot()}),u);i(t),null===(s=e.faro.api)||void 0===s||s.setSession(t.sessionMeta),null===(r=null==a?void 0:a.onSessionChange)||void 0===r||r.call(a,null!==(o=null==u?void 0:u.sessionMeta)&&void 0!==o?o:null,t.sessionMeta)}}}function ct(t,i){var n,s,r,o,a,l,u;const c=Object.assign(Object.assign({},t),{sessionMeta:{id:t.sessionId,attributes:pt(Object.assign(Object.assign(Object.assign({},null===(s=null===(n=e.faro.config.sessionTracking)||void 0===n?void 0:n.session)||void 0===s?void 0:s.attributes),null!==(o=null===(r=e.faro.metas.value.session)||void 0===r?void 0:r.attributes)&&void 0!==o?o:{}),{isSampled:t.isSampled.toString()}))}}),d=null!==(l=null===(a=e.faro.metas.value.session)||void 0===a?void 0:a.overrides)&&void 0!==l?l:null===(u=null==i?void 0:i.sessionMeta)||void 0===u?void 0:u.overrides;x(d)||(c.sessionMeta.overrides=d);const p=null==i?void 0:i.sessionId;return null!=p&&(c.sessionMeta.attributes.previousSession=p),c}function dt({fetchUserSession:t,storeUserSession:i}){let n=!1;return function(s){if(n)return;const r=s.session,o=t();let a=null==r?void 0:r.id;const l=null==r?void 0:r.attributes,u=null==r?void 0:r.overrides,c=null==o?void 0:o.sessionMeta,d=null==c?void 0:c.overrides,p=!!u&&!O(u,d),g=!!l&&!O(l,null==c?void 0:c.attributes);if(!!r&&a!==(null==o?void 0:o.sessionId)||g||p){const t=ct(at({sessionId:a,isSampled:ot()}),o);i(t),function(t,i={},n={}){var s,r,o;if(!t)return;const a=i.serviceName,l=null!==(o=null!==(s=n.serviceName)&&void 0!==s?s:null===(r=e.faro.metas.value.app)||void 0===r?void 0:r.name)&&void 0!==o?o:"";a&&a!==l&&e.faro.api.pushEvent(Le,{serviceName:a,previousServiceName:l})}(p,u,d),n=!0;try{e.faro.api.setSession(t.sessionMeta)}finally{n=!1}}}}function pt(e){const t={};for(const i of Object.keys(e)){const n=e[i];void 0!==n&&(t[i]=n)}return t}class gt{constructor(){this.updateSession=Ze(()=>this.updateUserSession(),1e3),this.updateUserSession=ut({fetchUserSession:gt.fetchUserSession,storeUserSession:gt.storeUserSession}),this.init()}static removeUserSession(){We(tt,gt.storageTypeLocal)}static storeUserSession(e){Ge(tt,B(e),gt.storageTypeLocal)}static fetchUserSession(){const e=He(tt,gt.storageTypeLocal);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.updateSession()}),e.faro.metas.addListener(dt({fetchUserSession:gt.fetchUserSession,storeUserSession:gt.storeUserSession}))}}gt.storageTypeLocal=Ve;class ht{constructor(){this.updateSession=Ze(()=>this.updateUserSession(),1e3),this.updateUserSession=ut({fetchUserSession:ht.fetchUserSession,storeUserSession:ht.storeUserSession}),this.init()}static removeUserSession(){We(tt,ht.storageTypeSession)}static storeUserSession(e){Ge(tt,B(e),ht.storageTypeSession)}static fetchUserSession(){const e=He(tt,ht.storageTypeSession);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.updateSession()}),e.faro.metas.addListener(dt({fetchUserSession:ht.fetchUserSession,storeUserSession:ht.storeUserSession}))}}function ft(e){return(null==e?void 0:e.persistent)?gt:ht}ht.storageTypeSession=Fe;class mt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-session",this.version=me}sendSessionStartEvent(e){var t,i;const n=e.session;if(n&&n.id!==(null===(t=this.notifiedSession)||void 0===t?void 0:t.id)){if(this.notifiedSession&&this.notifiedSession.id===(null===(i=n.attributes)||void 0===i?void 0:i.previousSession))return this.api.pushEvent(Ae,{},void 0,{skipDedupe:!0}),void(this.notifiedSession=n);this.notifiedSession=n,this.api.pushEvent(xe,{},void 0,{skipDedupe:!0})}}createInitialSession(e,t){var i,n,s,r,o,a;let l,u,c=e.fetchUserSession();if(t.persistent&&t.maxSessionPersistenceTime&&c){const e=A();c.lastActivity<e-t.maxSessionPersistenceTime&&(gt.removeUserSession(),c=null)}if(lt(c)){const e=null==c?void 0:c.sessionId;u=at({sessionId:e,isSampled:c.isSampled||!1,started:null==c?void 0:c.started});const s=null==c?void 0:c.sessionMeta,r=Object.assign(Object.assign({},null===(i=t.session)||void 0===i?void 0:i.overrides),null==s?void 0:s.overrides);u.sessionMeta=Object.assign(Object.assign({},t.session),{id:e,attributes:Object.assign(Object.assign(Object.assign({},null===(n=t.session)||void 0===n?void 0:n.attributes),null==s?void 0:s.attributes),{isSampled:u.isSampled.toString()}),overrides:r}),l=Oe}else{const e=null!==(r=null===(s=t.session)||void 0===s?void 0:s.id)&&void 0!==r?r:qe().id;u=at({sessionId:e,isSampled:ot()});const i=null===(o=t.session)||void 0===o?void 0:o.overrides;u.sessionMeta=Object.assign({id:e,attributes:Object.assign({isSampled:u.isSampled.toString()},null===(a=t.session)||void 0===a?void 0:a.attributes)},i?{overrides:i}:{}),l=xe}return{initialSession:u,lifecycleType:l}}registerBeforeSendHook(e){var t;const{updateSession:i}=new e;null===(t=this.transports)||void 0===t||t.addBeforeSendHooks(e=>{var t,n,s;i();const r=null===(t=e.meta.session)||void 0===t?void 0:t.attributes;if(r&&"true"===(null==r?void 0:r.isSampled)){let t=JSON.parse(JSON.stringify(e));const i=null===(n=t.meta.session)||void 0===n?void 0:n.attributes;return null==i||delete i.isSampled,0===Object.keys(null!=i?i:{}).length&&(null===(s=t.meta.session)||void 0===s||delete s.attributes),t}return null})}initialize(){this.logDebug("init session instrumentation");const e=this.config.sessionTracking;if(null==e?void 0:e.enabled){const t=ft(e);this.registerBeforeSendHook(t);const{initialSession:i,lifecycleType:n}=this.createInitialSession(t,e);t.storeUserSession(i);const s=i.sessionMeta;this.notifiedSession=s,this.api.setSession(s),n===xe&&this.api.pushEvent(xe,{},void 0,{skipDedupe:!0}),n===Oe&&this.api.pushEvent(Oe,{},void 0,{skipDedupe:!0})}this.metas.addListener(this.sendSessionStartEvent.bind(this))}}const vt="http-request-start",bt="http-request-end";let wt,yt=!1;const St=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;const Tt=/^\s*at (?:(?![a-z]+:\/\/)([^(]+?) ?\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Et=/\((\S*)(?::(\d+))(?::(\d+))\)/,kt="address at ",It=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|safari-extension|safari-web-extension|capacitor)?:\/.*?|\[native code]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,xt=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ot="safari-extension",At="safari-web-extension",Lt=/Minified React error #\d+;/i;function _t(e,t,i,n){const s={filename:e||document.location.href,function:t||"?"};return void 0!==i&&(s.lineno=i),void 0!==n&&(s.colno=n),s}function Ct(e,t){const i=null==e?void 0:e.includes(Ot),n=!i&&(null==e?void 0:e.includes(At));return i||n?[(null==e?void 0:e.includes("@"))?e.split("@")[0]:e,i?`${Ot}:${t}`:`${At}:${t}`]:[e,t]}function Ut(e){let t=[];e.stacktrace?t=e.stacktrace.split("\n").filter((e,t)=>t%2==0):e.stack&&(t=e.stack.split("\n"));const i=t.reduce((t,i,n)=>{if(i.length>1024)return t;let s,r,o,a,l;if(s=Tt.exec(i)){if(r=s[1],o=s[2],a=s[3],l=s[4],null==o?void 0:o.startsWith("eval")){const e=Et.exec(o);e&&(o=e[1],a=e[2],l=e[3])}o=(null==o?void 0:o.startsWith(kt))?o.substring(11):o,[r,o]=Ct(r,o)}else if(s=It.exec(i)){if(r=s[1],o=s[3],a=s[4],l=s[5],o&&o.includes(" > eval")){const e=xt.exec(o);e&&(r=r||"eval",o=e[1],a=e[2])}else 0===n&&!l&&d(e.columnNumber)&&(l=String(e.columnNumber+1));[r,o]=Ct(r,o)}return(o||r)&&t.push(_t(o,r,a?Number(a):void 0,l?Number(l):void 0)),t},[]);return Lt.test(e.message)?i.slice(1):i}function jt(e){return{frames:Ut(e)}}function Mt(e){let t,i,n,s,r=[];if(S(e)&&e.error)t=e.error.message,i=e.error.name,r=Ut(e.error);else if((n=T(e))||E(e)){const{name:s,message:r}=e;i=null!=s?s:n?"DOMError":"DOMException",t=r?`${i}: ${r}`:i}else y(e)?(i=e.name,t=e.message,r=Ut(e)):(g(e)||(s=b(e)))&&(i=s?e.constructor.name:void 0,t=`Non-Error exception captured with keys: ${Object.keys(e)}`);return[t,i,r]}function Pt(e){const[t,i,n,s,r]=e;let o,a,l=[];const u=c(t),d=_t(i,"?",n,s);return r||!u?([o,a,l]=Mt(null!=r?r:t),0===l.length&&(l=[d])):u&&([o,a]=function(e){var t,i;const n=e.match(St),s=null!==(t=null==n?void 0:n[1])&&void 0!==t?t:ue;return[null!==(i=null==n?void 0:n[2])&&void 0!==i?i:e,s]}(t),l=[d]),{value:o,type:a,stackFrames:l}}function Nt(e,t){return y(e[0])?Pt(e):{value:t(e)}}class Rt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-console",this.version=me,this.errorSerializer=ge}initialize(){var t,i;const n=this.config.consoleInstrumentation,s=(null==n?void 0:n.serializeErrors)||!!(null==n?void 0:n.errorSerializer);this.errorSerializer=s?null!==(t=null==n?void 0:n.errorSerializer)&&void 0!==t?t:ce:ge;const r=null!==(i=null==n?void 0:n.disabledLevels)&&void 0!==i?i:Rt.defaultDisabledLevels,o=function(e){if(wt||(wt=new V),!yt){const t=null!=e?e:W;M.forEach(e=>{console[e]=(...i)=>{var n;wt.notify({type:"console",level:e,args:i}),null===(n=t[e])||void 0===n||n.apply(console,i)}}),yt=!0}return wt}(this.unpatchedConsole);this.subscription=o.subscribe(({level:t,args:i})=>{if(!r.includes(t))try{if(t!==e.LogLevel.ERROR||(null==n?void 0:n.consoleErrorAsLog))if(t===e.LogLevel.ERROR&&(null==n?void 0:n.consoleErrorAsLog)){const{value:e,type:n,stackFrames:s}=Nt(i,this.errorSerializer);this.api.pushLog(e?[Rt.consoleErrorPrefix+e]:i,{level:t,context:{value:null!=e?e:"",type:null!=n?n:"",stackFrames:(null==s?void 0:s.length)?ce(s):""}})}else this.api.pushLog(i,{level:t});else{const{value:e,type:t,stackFrames:n}=Nt(i,this.errorSerializer);if(e&&!t&&!n)return void this.api.pushError(new Error(Rt.consoleErrorPrefix+e));this.api.pushError(new Error(Rt.consoleErrorPrefix+e),{type:t,stackFrames:n})}}catch(e){this.logError(e)}})}destroy(){var e;null===(e=this.subscription)||void 0===e||e.unsubscribe(),this.subscription=void 0}}Rt.defaultDisabledLevels=[e.LogLevel.DEBUG,e.LogLevel.TRACE,e.LogLevel.LOG],Rt.consoleErrorPrefix="console.error: ";class Dt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-errors",this.version=me}initialize(){var e;this.logDebug("Initializing"),function(e){const t=window.onerror;window.onerror=(...i)=>{try{const{value:t,type:n,stackFrames:s}=Pt(i),r=i[4];if(t){const i={type:n,stackFrames:s};null!=r&&(i.originalError=r),e.pushError(new Error(t),i)}}finally{null==t||t.apply(window,i)}}}(this.api),e=this.api,window.addEventListener("unhandledrejection",t=>{var i,n;let s,r,o=t;o.reason?o=t.reason:(null===(i=t.detail)||void 0===i?void 0:i.reason)&&(o=null===(n=t.detail)||void 0===n?void 0:n.reason);let a=[];m(o)?(s=`Non-Error promise rejection captured with value: ${String(o)}`,r="UnhandledRejection"):[s,r,a]=Mt(o),s&&e.pushError(new Error(s),{type:r,stackFrames:a})})}}class zt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-view",this.version=me}sendViewChangedEvent(e){var t,i,n,s;const r=e.view;r&&r.name!==(null===(t=this.notifiedView)||void 0===t?void 0:t.name)&&(this.api.pushEvent(Ie,{fromView:null!==(n=null===(i=this.notifiedView)||void 0===i?void 0:i.name)&&void 0!==n?n:_e,toView:null!==(s=r.name)&&void 0!==s?s:_e},void 0,{skipDedupe:!0}),this.notifiedView=r)}initialize(){this.metas.addListener(this.sendViewChangedEvent.bind(this))}}class qt{t;o=0;i=[];u(e){if(e.hadRecentInput)return;const t=this.i[0],i=this.i.at(-1);this.o&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.o+=e.value,this.i.push(e)):(this.o=e.value,this.i=[e]),this.t?.(e)}}const Bt=()=>{const e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},Ft=e=>{if("loading"===document.readyState)return"loading";const t=Bt();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},Vt=e=>{const t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},$t=e=>{let t="";try{for(;9!==e?.nodeType;){const i=e,n=i.id?"#"+i.id:[Vt(i),...Array.from(i.classList).sort()].join(".");if(t.length+n.length>99)return t||n;if(t=t?n+">"+t:n,i.id)break;e=i.parentNode}}catch{}return t},Ht=new WeakMap;function Gt(e,t){let i=Ht.get(t);return i||(i=new WeakMap,Ht.set(t,i)),i.get(e)||i.set(e,new t),i.get(e)}let Wt=-1;const Kt=()=>Wt,Xt=e=>{addEventListener("pageshow",t=>{t.persisted&&(Wt=t.timeStamp,e(t))},!0)},Jt=(e,t,i,n)=>{let s,r;return o=>{t.value>=0&&(o||n)&&(r=t.value-(s??0),(r||void 0===s)&&(s=t.value,t.delta=r,t.rating=((e,t)=>e>t[1]?"poor":e>t[0]?"needs-improvement":"good")(t.value,i),e(t)))}},Zt=e=>{requestAnimationFrame(()=>requestAnimationFrame(e))},Yt=()=>Bt()?.activationStart??0,Qt=(e,t=-1)=>{const i=Bt();let n="navigate";return Kt()>=0?n="back-forward-cache":i&&(document.prerendering||Yt()>0?n="prerender":document.wasDiscarded?n="restore":i.type&&(n=i.type.replace(/_/g,"-"))),{name:e,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},ei=(e,t,i={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){const n=new PerformanceObserver(e=>{queueMicrotask(()=>{t(e.getEntries())})});return n.observe({type:e,buffered:!0,...i}),n}}catch{}},ti=e=>{let t=!1;return()=>{t||(e(),t=!0)}};let ii=-1;const ni=new Set,si=()=>"hidden"!==document.visibilityState||document.prerendering?1/0:0,ri=e=>{if("hidden"===document.visibilityState){if("visibilitychange"===e.type)for(const e of ni)e();isFinite(ii)||(ii="visibilitychange"===e.type?e.timeStamp:0,removeEventListener("prerenderingchange",ri,!0))}},oi=()=>{if(ii<0){const e=Yt(),t=document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(t=>"hidden"===t.name&&t.startTime>=e)?.startTime;ii=t??si(),addEventListener("visibilitychange",ri,!0),addEventListener("prerenderingchange",ri,!0),Xt(()=>{setTimeout(()=>{ii=si()})})}return{get firstHiddenTime(){return ii},onHidden(e){ni.add(e)}}},ai=e=>{document.prerendering?addEventListener("prerenderingchange",e,!0):e()},li=[1800,3e3],ui=(e,t={})=>{ai(()=>{const i=oi();let n,s=Qt("FCP");const r=ei("paint",e=>{for(const t of e)"first-contentful-paint"===t.name&&(r.disconnect(),t.startTime<i.firstHiddenTime&&(s.value=Math.max(t.startTime-Yt(),0),s.entries.push(t),n(!0)))});r&&(n=Jt(e,s,li,t.reportAllChanges),Xt(i=>{s=Qt("FCP"),n=Jt(e,s,li,t.reportAllChanges),Zt(()=>{s.value=performance.now()-i.timeStamp,n(!0)})}))})},ci=[.1,.25],di=e=>e.find(e=>1===e.node?.nodeType)||e[0];let pi=0,gi=1/0,hi=0;const fi=e=>{for(const t of e)t.interactionId&&(gi=Math.min(gi,t.interactionId),hi=Math.max(hi,t.interactionId),pi=hi?(hi-gi)/7+1:0)};let mi;const vi=()=>mi?pi:performance.interactionCount??0;let bi=0;class wi{l=[];h=new Map;m;p;v(){bi=vi(),this.l.length=0,this.h.clear()}M(){const e=Math.min(this.l.length-1,Math.floor((vi()-bi)/50));return this.l[e]}u(e){if(this.m?.(e),!e.interactionId&&"first-input"!==e.entryType)return;const t=this.l.at(-1);let i=this.h.get(e.interactionId);if(i||this.l.length<10||e.duration>t.T){if(i?e.duration>i.T?(i.entries=[e],i.T=e.duration):e.duration===i.T&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],T:e.duration},this.h.set(i.id,i),this.l.push(i)),this.l.sort((e,t)=>t.T-e.T),this.l.length>10){const e=this.l.splice(10);for(const t of e)this.h.delete(t.id)}this.p?.(i)}}}const yi=e=>{const t=globalThis.requestIdleCallback||setTimeout,i=globalThis.cancelIdleCallback||clearTimeout;if("hidden"===document.visibilityState)e();else{const n=ti(e);let s=-1;const r=()=>{i(s),n()};addEventListener("visibilitychange",r,{once:!0,capture:!0}),s=t(()=>{removeEventListener("visibilitychange",r,{capture:!0}),n()})}},Si=[200,500],Ti=(e,t={})=>{const i=Gt(t=Object.assign({},t),wi);let n=[],s=[],r=0;const o=new WeakMap,a=new WeakMap;let l=!1;const u=()=>{l||(yi(c),l=!0)},c=()=>{const e=new Set(i.l.map(e=>o.get(e.entries[0]))),t=s.length-10;s=s.filter((i,n)=>n>=t||e.has(i));const a=new Set;for(const e of s){const t=d(e.startTime,e.processingEnd);for(const e of t)a.add(e)}n=n.filter(e=>e.startTime>r||a.has(e)),l=!1};i.m=e=>{const i=e.startTime+e.duration;let n;r=Math.max(r,e.processingEnd);for(let r=s.length-1;r>=0;r--){const o=s[r];if(Math.abs(i-o.renderTime)<=8){n=o,n.startTime=Math.min(e.startTime,n.startTime),n.processingStart=Math.min(e.processingStart,n.processingStart),n.processingEnd=Math.max(e.processingEnd,n.processingEnd),!1!==t.includeProcessedEventEntries&&n.entries.push(e);break}}n||(n={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:i,entries:!1!==t.includeProcessedEventEntries?[e]:[]},s.push(n)),(e.interactionId||"first-input"===e.entryType)&&o.set(e,n),u()},i.p=e=>{if(!a.get(e)){const i=e.entries.find(e=>e.target)?.target;if(i){const n=t.generateTarget?.(i)??$t(i);a.set(e,n)}else{const t=e.entries.find(e=>e.targetSelector)?.targetSelector;t&&a.set(e,t)}}};const d=(e,t)=>{const i=[];for(const s of n)if(!(s.startTime+s.duration<e)){if(s.startTime>t)break;i.push(s)}return i};ei("long-animation-frame",e=>{n=n.concat(e),u()}),((e,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const i=oi();ai(()=>{"interactionCount"in performance||mi||(mi=ei("event",fi,{durationThreshold:0}));let n,s=Qt("INP");const r=Gt(t,wi),o=e=>{yi(()=>{for(const t of e)r.u(t);const t=r.M();t&&t.T!==s.value&&(s.value=t.T,s.entries=t.entries,n())})},a=ei("event",o,{durationThreshold:t.durationThreshold??40});n=Jt(e,s,Si,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),i.onHidden(()=>{o(a.takeRecords()),n(!0)}),Xt(()=>{r.v(),s=Qt("INP"),n=Jt(e,s,Si,t.reportAllChanges)}))})})(t=>{e((e=>{const t=e.entries[0],n=o.get(t),s=t.processingStart,r=Math.max(t.startTime+t.duration,s),l=Math.min(n.processingEnd,r),u=n.entries.sort((e,t)=>e.processingStart-t.processingStart),c=d(t.startTime,l),p=i.h.get(t.interactionId),g={interactionTarget:a.get(p),interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:r,processedEventEntries:u,longAnimationFrameEntries:c,inputDelay:s-t.startTime,processingDuration:l-s,presentationDelay:r-l,loadState:Ft(t.startTime),longestScript:void 0,totalScriptDuration:void 0,totalStyleAndLayoutDuration:void 0,totalPaintDuration:void 0,totalUnattributedDuration:void 0};return(e=>{if(!e.longAnimationFrameEntries?.length)return;const t=e.interactionTime,i=e.inputDelay,n=e.processingDuration;let s,r,o=0,a=0,l=0,u=0;for(const l of e.longAnimationFrameEntries){a=a+l.startTime+l.duration-l.styleAndLayoutStart;for(const e of l.scripts){const l=e.startTime+e.duration;if(l<t)continue;const c=l-Math.max(t,e.startTime),d=e.duration?c/e.duration*e.forcedStyleAndLayoutDuration:0;o+=c-d,a+=d,c>u&&(r=e.startTime<t+i?"input-delay":e.startTime>=t+i+n?"presentation-delay":"processing-duration",s=e,u=c)}}const c=e.longAnimationFrameEntries.at(-1),d=c?c.startTime+c.duration:0;d>=t+i+n&&(l=e.nextPaintTime-d),s&&r&&(e.longestScript={entry:s,subpart:r,intersectingDuration:u}),e.totalScriptDuration=o,e.totalStyleAndLayoutDuration=a,e.totalPaintDuration=l,e.totalUnattributedDuration=e.nextPaintTime-t-o-a-l})(g),Object.assign(e,{attribution:g})})(t))},t)};class Ei{m;u(e){this.m?.(e)}}const ki=[2500,4e3],Ii=[800,1800],xi=e=>{document.prerendering?ai(()=>xi(e)):"complete"!==document.readyState?addEventListener("load",()=>xi(e),!0):setTimeout(e)},Oi="com.grafana.faro.lastNavigationId",Ai="load_state",Li="time_to_first_byte";class _i{constructor(e,t){this.corePushMeasurement=e,this.webVitalConfig=t}initialize(){this.measureCLS(),this.measureFCP(),this.measureINP(),this.measureLCP(),this.measureTTFB()}measureCLS(){var e;((e,t={})=>{const i=Gt(t=Object.assign({},t),qt),n=new WeakMap;i.t=e=>{if(e?.sources?.length){const i=di(e.sources),s=i?.node;if(s){const e=t.generateTarget?.(s)??$t(s);n.set(i,e)}}},((e,t={})=>{const i=oi();ui(ti(()=>{let n,s=Qt("CLS",0);const r=Gt(t,qt),o=e=>{for(const t of e)r.u(t);r.o>s.value&&(s.value=r.o,s.entries=r.i,n())},a=ei("layout-shift",o);a&&(n=Jt(e,s,ci,t.reportAllChanges),i.onHidden(()=>{o(a.takeRecords()),n(!0)}),Xt(()=>{r.o=0,s=Qt("CLS",0),n=Jt(e,s,ci,t.reportAllChanges),Zt(n)}),setTimeout(n))}))})(t=>{e((e=>{let t={};if(e.entries.length){const i=e.entries.reduce((e,t)=>e.value>t.value?e:t);if(i?.sources?.length){const e=di(i.sources);e&&(t={largestShiftTarget:n.get(e),largestShiftTime:i.startTime,largestShiftValue:i.value,largestShiftSource:e,largestShiftEntry:i,loadState:Ft(i.startTime)})}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{loadState:t,largestShiftValue:i,largestShiftTime:n,largestShiftTarget:s}=e.attribution,r=this.buildInitialValues(e);this.addIfPresent(r,"largest_shift_value",i),this.addIfPresent(r,"largest_shift_time",n);const o=this.buildInitialContext(e);this.addIfPresent(o,Ai,t),this.addIfPresent(o,"largest_shift_target",s),this.pushMeasurement(r,o)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureFCP(){var e;((e,t={})=>{ui(t=>{e((e=>{let t={timeToFirstByte:0,firstByteToFCP:e.value,loadState:Ft(Kt())};if(e.entries.length){const i=Bt(),n=e.entries.at(-1);if(i){const s=i.activationStart||0,r=Math.max(0,i.responseStart-s);t={timeToFirstByte:r,firstByteToFCP:e.value-r,loadState:Ft(e.entries[0].startTime),navigationEntry:i,fcpEntry:n}}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{firstByteToFCP:t,timeToFirstByte:i,loadState:n}=e.attribution,s=this.buildInitialValues(e);this.addIfPresent(s,"first_byte_to_fcp",t),this.addIfPresent(s,Li,i);const r=this.buildInitialContext(e);this.addIfPresent(r,Ai,n),this.pushMeasurement(s,r)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureINP(){var e;Ti(e=>{const{interactionTime:t,presentationDelay:i,inputDelay:n,processingDuration:s,nextPaintTime:r,loadState:o,interactionTarget:a,interactionType:l}=e.attribution,u=this.buildInitialValues(e);this.addIfPresent(u,"interaction_time",t),this.addIfPresent(u,"presentation_delay",i),this.addIfPresent(u,"input_delay",n),this.addIfPresent(u,"processing_duration",s),this.addIfPresent(u,"next_paint_time",r);const c=this.buildInitialContext(e);this.addIfPresent(c,Ai,o),this.addIfPresent(c,"interaction_target",a),this.addIfPresent(c,"interaction_type",l),this.pushMeasurement(u,c)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureLCP(){var e;((e,t={})=>{const i=Gt(t=Object.assign({},t),Ei),n=new WeakMap;i.m=e=>{const i=e.element;if(i){const s=t.generateTarget?.(i)??$t(i);n.set(e,s)}else e.id&&n.set(e,`#${e.id}`)},((e,t={})=>{ai(()=>{const i=oi();let n,s=Qt("LCP");const r=Gt(t,Ei),o=e=>{t.reportAllChanges||(e=e.slice(-1));for(const t of e)r.u(t),t.startTime<i.firstHiddenTime&&(s.value=Math.max(t.startTime-Yt(),0),s.entries=[t],n())},a=ei("largest-contentful-paint",o);if(a){n=Jt(e,s,ki,t.reportAllChanges);const i=ti(()=>{o(a.takeRecords()),a.disconnect(),n(!0)}),r=e=>{e.isTrusted&&(yi(i),removeEventListener(e.type,r,{capture:!0}))};for(const e of["keydown","click","visibilitychange"])addEventListener(e,r,{capture:!0});Xt(i=>{s=Qt("LCP"),n=Jt(e,s,ki,t.reportAllChanges),Zt(()=>{s.value=performance.now()-i.timeStamp,n(!0)})})}})})(t=>{e((e=>{let t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){const i=e.entries.at(-1),s=i.url&&performance.getEntriesByType("resource").find(e=>e.name===i.url);t.target=n.get(i),t.lcpEntry=i,i.url&&(t.url=i.url),s&&(t.lcpResourceEntry=s);const r=Bt();if(r){const i=r.activationStart||0,n=Math.max(0,r.responseStart-i),o=Math.max(n,s?(s.requestStart||s.startTime)-i:0),a=Math.min(e.value,Math.max(o,s?s.responseEnd-i:0));t={...t,timeToFirstByte:n,resourceLoadDelay:o-n,resourceLoadDuration:a-o,elementRenderDelay:e.value-a,navigationEntry:r}}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{elementRenderDelay:t,resourceLoadDelay:i,resourceLoadDuration:n,timeToFirstByte:s,target:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"element_render_delay",t),this.addIfPresent(o,"resource_load_delay",i),this.addIfPresent(o,"resource_load_duration",n),this.addIfPresent(o,Li,s);const a=this.buildInitialContext(e);this.addIfPresent(a,"element",r),this.pushMeasurement(o,a)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureTTFB(){var e;((e,t={})=>{((e,t={})=>{let i=Qt("TTFB"),n=Jt(e,i,Ii,t.reportAllChanges);xi(()=>{const s=Bt();s&&(i.value=Math.max(s.responseStart-Yt(),0),i.entries=[s],n(!0),Xt(()=>{i=Qt("TTFB",0),n=Jt(e,i,Ii,t.reportAllChanges),n(!0)}))})})(t=>{e((e=>{let t={waitingDuration:0,cacheDuration:0,dnsDuration:0,connectionDuration:0,requestDuration:0};if(e.entries.length){const i=e.entries[0],n=i.activationStart||0,s=Math.max((i.workerStart||i.fetchStart)-n,0),r=Math.max(i.domainLookupStart-n,0),o=Math.max(i.connectStart-n,0),a=Math.max(i.connectEnd-n,0);t={waitingDuration:s,cacheDuration:r-s,dnsDuration:o-r,connectionDuration:a-o,requestDuration:e.value-a,navigationEntry:i}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{dnsDuration:t,connectionDuration:i,requestDuration:n,waitingDuration:s,cacheDuration:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"dns_duration",t),this.addIfPresent(o,"connection_duration",i),this.addIfPresent(o,"request_duration",n),this.addIfPresent(o,"waiting_duration",s),this.addIfPresent(o,"cache_duration",r);const a=this.buildInitialContext(e);this.pushMeasurement(o,a)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}buildInitialValues(e){const t=e.name.toLowerCase();return{[t]:e.value,delta:e.delta}}buildInitialContext(e){var t;const i=null!==(t=He(Oi,Fe))&&void 0!==t?t:_e;return{id:e.id,rating:e.rating,navigation_type:e.navigationType,navigation_entry_id:i}}pushMeasurement(e,t){this.corePushMeasurement({type:"web-vitals",values:e},{context:t})}addIfPresent(e,t,i){i&&(e[t]=i)}}class Ci extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-web-vitals",this.version=me}initialize(){this.logDebug("Initializing");new _i(this.api.pushMeasurement,this.config.webVitalsInstrumentation).initialize()}}function Ui(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}function ji(e,t,i,n){return new(i||(i=Promise))(function(s,r){function o(e){try{l(n.next(e))}catch(e){r(e)}}function a(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const Mi="resource",Pi=/^00-[a-f0-9]{32}-[a-f0-9]{16}-[0-9]{1,2}$/;function Ni(e=[]){for(const t of e)if("traceparent"===t.name){if(!Pi.test(t.description))continue;const[,e,i]=t.description.split("-");if(null!=e&&null!=i)return{traceId:e,spanId:i};break}}function Ri(e,t={}){for(const[i,n]of Object.entries(t)){const t=e[i];return null!=t&&(f(n)?n.includes(t):t===n)}return!0}function Di(e){const{connectEnd:t,connectStart:i,decodedBodySize:n,domainLookupEnd:s,domainLookupStart:r,duration:o,encodedBodySize:a,fetchStart:l,initiatorType:u,name:c,nextHopProtocol:d,redirectEnd:p,redirectStart:g,renderBlockingStatus:h,requestStart:f,responseEnd:m,responseStart:v,responseStatus:b,secureConnectionStart:w,transferSize:y,workerStart:S}=e;return{name:c,httpHost:qi(c),duration:Bi(o),tcpHandshakeTime:Bi(t-i),dnsLookupTime:Bi(s-r),tlsNegotiationTime:Bi(t-w),responseStatus:Bi(b),redirectTime:Bi(p-g),requestTime:Bi(v-f),responseTime:Bi(m-v),fetchTime:Bi(m-l),serviceWorkerTime:Bi(S>0?l-S:0),decodedBodySize:Bi(n),encodedBodySize:Bi(a),cacheHitStatus:function(){let e="fullLoad";0===y?n>0&&(e="cache"):null!=b?304===b&&(e="conditionalFetch"):a>0&&y<a&&(e="conditionalFetch");return e}(),renderBlockingStatus:Bi(h),protocol:d,initiatorType:u,visibilityState:document.visibilityState,ttfb:Bi(v-f),transferSize:Bi(y)}}function zi(e){const{activationStart:t,domComplete:i,domContentLoadedEventEnd:n,domContentLoadedEventStart:s,domInteractive:r,fetchStart:o,loadEventEnd:a,loadEventStart:l,responseStart:u,type:c}=e,d=function(){var e;if(null!=(null===(e=performance.timing)||void 0===e?void 0:e.domLoading))return performance.timing.domLoading-performance.timeOrigin;return null}();return Object.assign(Object.assign({},Di(e)),{pageLoadTime:Bi(i-o),documentParsingTime:Bi(d?r-d:null),domProcessingTime:Bi(i-r),domContentLoadHandlerTime:Bi(n-s),onLoadTime:Bi(a-l),ttfb:Bi(Math.max(u-(null!=t?t:0),0)),type:c})}function qi(e){try{return new URL(e).host||_e}catch(e){return _e}}function Bi(e){return null==e?_e:"number"==typeof e?Math.round(e>0?e:0).toString():e.toString()}const Fi={initiatorType:["xmlhttprequest","fetch"]};const Vi=new V;class $i extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-performance",this.version=me}initialize(){"PerformanceObserver"in window?function(e){if("complete"===document.readyState)e();else{const t=()=>{"complete"===document.readyState&&(e(),document.removeEventListener("readystatechange",t))};document.addEventListener("readystatechange",t)}}(()=>ji(this,void 0,void 0,function*(){const t=this.api.pushEvent,{faroNavigationId:i}=yield function(e){let t;const i=new Promise(e=>{t=e});return new PerformanceObserver(i=>{var n;const[s]=i.getEntries();if(null==s||Qe(s.name))return;const r=s.toJSON();let o=Ni(null==r?void 0:r.serverTiming);const a=null!==(n=He(Oi,Fe))&&void 0!==n?n:_e,l=Object.assign(Object.assign({},zi(r)),{faroNavigationId:D(),faroPreviousNavigationId:a});Ge(Oi,l.faroNavigationId,Fe),e("faro.performance.navigation",l,void 0,{spanContext:o,timestampOverwriteMs:performance.timeOrigin+r.startTime}),t(l)}).observe({type:"navigation",buffered:!0}),i}(t);null!=i&&function(t,i,n){const s=e.faro.config.trackResources;new PerformanceObserver(e=>{const r=e.getEntries();for(const e of r){if(Qe(e.name))continue;null==n||n.notify({type:Mi});const r=e.toJSON();let o=Ni(null==r?void 0:r.serverTiming);if(null==s&&Ri(r,Fi)||s){const e=Object.assign(Object.assign({},Di(r)),{faroNavigationId:t,faroResourceId:D()});i("faro.performance.resource",e,void 0,{spanContext:o,timestampOverwriteMs:performance.timeOrigin+r.startTime})}}}).observe({type:Mi,buffered:!0})}(i,t,Vi)})):this.logDebug("performance observer not supported. Disable performance instrumentation.")}}const Hi="data-faro-user-action-name";let Gi,Wi;function Ki(){return Gi||(Gi=new V),Wi||(Wi=new MutationObserver((e,t)=>{Gi.notify({type:"dom-mutation"})}),Wi.observe(document,{attributes:!0,childList:!0,subtree:!0,characterData:!0})),Gi}const Xi="fetch",Ji="xhr";let Zi,Yi,Qi,en,tn=!1;function nn(){if(Zi)return Zi;function e(e){Zi.notify({type:vt,request:e})}function t(e){Zi.notify({type:bt,request:e})}return Zi=new V,tn||(!function({onRequestEnd:e,onRequestStart:t}){Qi||(Qi=window.fetch);window.fetch=function(){var i,n;const s=null!==(i=et(arguments[0]))&&void 0!==i?i:"",r=Qe(s),o=(null!==(n=arguments[1])&&void 0!==n?n:{}).method,a=D();return r||t({url:s,method:o,requestId:a,apiType:Xi}),Qi.apply(this,arguments).then(t=>(r||e({url:s,method:o,requestId:a,apiType:Xi}),t)).catch(t=>{throw r||e({url:s,method:o,requestId:a,apiType:Xi}),t})}}({onRequestStart:e,onRequestEnd:t}),function({onRequestStart:e,onRequestEnd:t}){Yi||(Yi=XMLHttpRequest.prototype.open);XMLHttpRequest.prototype.open=function(){const i=arguments[1],n=Qe(i),s=arguments[0],r=D();this.addEventListener("loadstart",function(){n||e({url:i,method:s,requestId:r,apiType:Ji})}),this.addEventListener("load",function(){n||t({url:i,method:s,requestId:r,apiType:Ji})}),this.addEventListener("error",function(){n||t({url:i,method:s,requestId:r,apiType:Ji})}),this.addEventListener("abort",function(){n||t({url:i,method:s,requestId:r,apiType:Ji})}),Yi.apply(this,arguments)}}({onRequestStart:e,onRequestEnd:t}),tn=!0),Zi}let sn=!1;function rn(e){return e.type===bt}class on{constructor(e){this.userAction=e,this.http=nn(),this.dom=Ki(),this.perf=(en||(en=new V),sn||(Vi.subscribe(e=>{e.type===Mi&&en.notify({type:"resource-entry"})}),sn=!0),en),this.isValid=!1,this.runningRequests=new Map}attach(){this.allMonitorsSub=(new V).merge(this.http,this.dom,this.perf).takeWhile(()=>[e.UserActionState.Started,e.UserActionState.Halted].includes(this.userAction.getState())).filter(t=>!!(this.userAction.getState()!==e.UserActionState.Halted||rn(t)&&this.runningRequests.has(t.request.requestId))).subscribe(t=>{(function(e){return e.type===vt})(t)&&this.runningRequests.set(t.request.requestId,t.request),rn(t)&&this.runningRequests.delete(t.request.requestId),rn(t)?this.userAction.getState()===e.UserActionState.Halted&&0===this.runningRequests.size&&this.endAction():(this.isValid||(this.isValid=!0),this.scheduleFollowUp())}),this.stateSub=this.userAction.filter(t=>[e.UserActionState.Ended,e.UserActionState.Cancelled].includes(t)).first().subscribe(()=>this.cleanup()),this.scheduleFollowUp()}scheduleFollowUp(){this.clearTimer(this.followUpTid),this.followUpTid=setTimeout(()=>{this.userAction.getState()===e.UserActionState.Started&&this.runningRequests.size>0?this.haltAction():this.isValid?this.endAction():this.cancelAction()},100)}haltAction(){this.userAction.getState()===e.UserActionState.Started&&(this.userAction.halt(),this.startHaltTimeout())}startHaltTimeout(){var t,i,n;this.clearTimer(this.haltTid),this.haltTid=(t=this.haltTid,i=()=>{this.userAction.getState()===e.UserActionState.Halted&&this.endAction()},n=1e4,t&&clearTimeout(t),setTimeout(()=>{i()},n))}endAction(){this.userAction.end(),this.cleanup()}cancelAction(){this.userAction.cancel(),this.cleanup()}cleanup(){var e,t;this.clearTimer(this.followUpTid),this.clearTimer(this.haltTid),null===(e=this.allMonitorsSub)||void 0===e||e.unsubscribe(),null===(t=this.stateSub)||void 0===t||t.unsubscribe(),this.allMonitorsSub=void 0,this.stateSub=void 0,this.runningRequests.clear()}clearTimer(e){e&&clearTimeout(e)}}function an(e){const{api:t,config:i}=e;function n(e){new on(e).attach()}return{processUserEvent:function(e){var s,r;const o=function(e,t){const i=function(e){const t=e.split("data-")[1],i=null==t?void 0:t.replace(/-(.)/g,(e,t)=>t.toUpperCase());return null==i?void 0:i.replace(/-/g,"")}(t),n=e.dataset;for(const e in n)if(e===i)return n[e];return}(e.target,null!==(r=null===(s=i.userActionsInstrumentation)||void 0===s?void 0:s.dataAttributeName)&&void 0!==r?r:"faroUserActionName");if(!o)return;const a=t.startUserAction(o,{},{triggerName:e.type});a&&n(a)},processUserActionStarted:n}}class ln extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-user-action",this.version=me}initialize(){const{processUserEvent:t,processUserActionStarted:i}=an(e.faro);window.addEventListener("pointerdown",t),window.addEventListener("keydown",e=>{[" ","Enter"].includes(e.key)&&t(e)}),this._userActionSub=ae.subscribe(({type:e,userAction:t})=>{"user_action_start"===e&&i(t)})}destroy(){var e;null===(e=this._userActionSub)||void 0===e||e.unsubscribe()}}class un extends fe{constructor(){super(),this.name="@grafana/faro-web-sdk:instrumentation-csp",this.version=me}initialize(){document.addEventListener("securitypolicyviolation",this.securitypolicyviolationHandler.bind(this))}destroy(){document.removeEventListener("securitypolicyviolation",this.securitypolicyviolationHandler)}securitypolicyviolationHandler(e){const t={blockedURI:e.blockedURI,columnNumber:e.columnNumber,disposition:e.disposition,documentURI:e.documentURI,effectiveDirective:e.effectiveDirective,lineNumber:e.lineNumber,originalPolicy:e.originalPolicy,referrer:e.referrer,sample:e.sample,sourceFile:e.sourceFile,statusCode:e.statusCode,violatedDirective:e.violatedDirective};this.api.pushEvent("securitypolicyviolation",F(t))}}class cn extends V{constructor(e,t){var i,n,s,r;super(),this._tracking=!1,this.eventsObservable=e,this._options={inactivityMs:null!==(i=null==t?void 0:t.inactivityMs)&&void 0!==i?i:100,drainTimeoutMs:null!==(n=null==t?void 0:t.drainTimeoutMs)&&void 0!==n?n:1e4,isOperationStart:null!==(s=null==t?void 0:t.isOperationStart)&&void 0!==s?s:()=>{},isOperationEnd:null!==(r=null==t?void 0:t.isOperationEnd)&&void 0!==r?r:()=>{}},this._initialize()}_initialize(){this.eventsObservable.filter(()=>this._tracking).subscribe(e=>{var t,i,n;this._lastEventTime=L(),null===(t=this._currentEvents)||void 0===t||t.push(e);const s=this._options.isOperationStart(e);s&&(null===(i=this._activeOperations)||void 0===i||i.set(s,!0));const r=this._options.isOperationEnd(e);r&&(null===(n=this._activeOperations)||void 0===n||n.delete(r)),this._scheduleInactivityCheck()})}startTracking(){this._tracking||(this._tracking=!0,this._startTime=L(),this._lastEventTime=this._startTime,this.notify({message:"tracking-started"}),this._currentEvents=[],this._activeOperations=new Map,this._scheduleInactivityCheck())}stopTracking(){let e;this._tracking=!1,this._clearTimer(this._inactivityTid),this._clearTimer(this._drainTid),e=this.hasActiveOperations()?L()-this._startTime:this._lastEventTime?this._lastEventTime-this._startTime:0,this.notify({message:"tracking-ended",events:this._currentEvents,duration:e})}_scheduleInactivityCheck(){this._inactivityTid=dn(this._inactivityTid,()=>{this.hasActiveOperations()?this._startDrainTimeout():this.stopTracking()},this._options.inactivityMs)}_startDrainTimeout(){this._drainTid=dn(this._drainTid,()=>{this.stopTracking()},this._options.drainTimeoutMs)}hasActiveOperations(){return!!this._activeOperations&&this._activeOperations.size>0}_clearTimer(e){e&&clearTimeout(e)}}function dn(e,t,i){return e&&clearTimeout(e),e=setTimeout(()=>{t()},i)}let pn;const gn=new Set,hn=new Map;let fn,mn,vn,bn,wn,yn,Sn,Tn,En=!1;class kn extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-navigation",this.version=me}initialize(){const t=nn(),i=Ki(),n=function(){function e(e,t){const i=null!=t?t:location.href;i!==mn&&(fn.notify({type:"url-change",from:mn,to:i,trigger:e}),mn=i)}if(fn||(fn=new V,mn=location.href),!En)if("navigation"in window&&"NavigateEvent"in window){Sn=t=>{try{const i=null==t?void 0:t.destination;(null==i?void 0:i.sameDocument)&&"string"==typeof i.url&&e("navigate",i.url)}catch(e){}},window.navigation.addEventListener("navigate",Sn);const t=window.NavigateEvent;t&&t.prototype&&"function"==typeof t.prototype.intercept&&(Tn||(Tn=t.prototype.intercept),t.prototype.intercept=function(t){try{const t=!!(null==this?void 0:this.canIntercept),i=null==this?void 0:this.destination;t&&i&&!1===i.sameDocument&&"string"==typeof i.url&&e("navigate-intercept",i.url)}catch(e){}return Tn.call(this,t)}),En=!0}else vn||(vn=window.history.pushState),window.history.pushState=function(...t){const i=vn.apply(window.history,t);return e("pushState"),i},bn||(bn=window.history.replaceState),window.history.replaceState=function(...t){const i=bn.apply(window.history,t);return e("replaceState"),i},wn=()=>e("popstate"),yn=()=>e("hashchange"),window.addEventListener("popstate",wn),window.addEventListener("hashchange",yn),En=!0;return fn}(),s=(r=["pointerdown","keydown"],pn||(pn=new V),r.forEach(e=>{if(!gn.has(e)){const t=()=>{pn.notify({type:"interaction",name:e})};window.addEventListener(e,t),gn.add(e),hn.set(e,t)}}),pn);var r;const o=new cn((new V).merge(t,i,n),{inactivityMs:100,drainTimeoutMs:1e4,isOperationStart:e=>function(e){return e.type===vt}(e)?e.request.requestId:void 0,isOperationEnd:e=>function(e){return e.type===bt}(e)?e.request.requestId:void 0});o.filter(e=>"tracking-ended"===e.message).subscribe(t=>{var i,n,s;if((null===(i=t.events)||void 0===i?void 0:i.some(e=>"url-change"===e.type))&&(null===(n=t.events)||void 0===n?void 0:n.some(e=>"dom-mutation"===e.type))){const i=null===(s=t.events)||void 0===s?void 0:s.find(e=>"url-change"===e.type);e.faro.api.pushEvent("faro.navigation",{fromUrl:null==i?void 0:i.from,toUrl:null==i?void 0:i.to,sameDocument:String(!0),duration:t.duration})}}),s.subscribe(()=>{o.startTracking()})}}function In(e={}){const t=[new ln,new Dt,new Ci,new mt,new zt,new kn];return!1!==e.enablePerformanceInstrumentation&&t.unshift(new $i),!1!==e.enableContentSecurityPolicyInstrumentation&&t.push(new un),!1!==e.captureConsole&&t.push(new Rt),t}const xn="browser",On=()=>{const e=window.k6;return{k6:Object.assign({isK6Browser:!0},(null==e?void 0:e.testRunId)&&{testRunId:null==e?void 0:e.testRunId})}};let An,Ln;function _n({generatePageId:e,initialPageMeta:t}={}){return()=>{const i=location.href;return h(e)&&An!==i&&(An=i,Ln=e(location)),{page:Object.assign(Object.assign({url:i},Ln?{id:Ln}:{}),t)}}}class Cn extends ee{constructor(e){var t,i,n,s,r;super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-fetch",this.version=me,this.disabledUntil=new Date(0),this.rateLimitBackoffMs=null!==(t=e.defaultRateLimitBackoffMs)&&void 0!==t?t:5e3,this.getNow=null!==(i=e.getNow)&&void 0!==i?i:()=>Date.now();const o=null!==(n=e.requestCompression)&&void 0!==n&&n;o&&"undefined"==typeof CompressionStream?(this.compressionEnabled=!1,this.logWarn("requestCompression is enabled but CompressionStream is not available. Falling back to uncompressed.")):this.compressionEnabled=o,this.promiseBuffer=N({size:null!==(s=e.bufferSize)&&void 0!==s?s:30,concurrency:null!==(r=e.concurrency)&&void 0!==r?r:5})}send(e){return ji(this,void 0,void 0,function*(){try{if(this.disabledUntil>new Date(this.getNow()))return this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`),Promise.resolve();yield this.promiseBuffer.add(()=>ji(this,void 0,void 0,function*(){const t=JSON.stringify(ie(e)),{url:i,requestOptions:n,apiKey:s}=this.options,r=null!=n?n:{},{headers:o={}}=r,a=Ui(r,["headers"]);let l;const u=this.metas.value.session;null!=u&&(l=u.id);const c={};for(const[e,t]of Object.entries(o))c[e]="function"==typeof t?yield Promise.resolve(t()):t;let d=t,p=t.length;const g={};return this.compressionEnabled&&(d=yield this.compress(t),p=d.size,g["Content-Encoding"]="gzip"),fetch(i,Object.assign({method:"POST",headers:Object.assign(Object.assign(Object.assign(Object.assign({"Content-Type":"application/json"},g),c),s?{"x-api-key":s}:{}),l?{"x-faro-session-id":l}:{}),body:d,keepalive:p<=6e4},null!=a?a:{})).then(e=>ji(this,void 0,void 0,function*(){if(202===e.status){"invalid"===e.headers.get("X-Faro-Session-Status")&&this.extendFaroSession(this.config,this.logDebug)}return 429===e.status&&(this.disabledUntil=this.getRetryAfterDate(e),this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`)),e.text().catch(P),e})).catch(e=>{this.logError("Failed sending payload to the receiver\n",JSON.parse(t),e)})}))}catch(e){this.logError(e)}})}getIgnoreUrls(){var e;return[this.options.url].concat(null!==(e=this.config.ignoreUrls)&&void 0!==e?e:[])}isBatched(){return!0}getRetryAfterDate(e){const t=this.getNow(),i=e.headers.get("Retry-After");if(i){const e=Number(i);if(!isNaN(e))return new Date(1e3*e+t);const n=Date.parse(i);if(!isNaN(n))return new Date(n)}return new Date(t+this.rateLimitBackoffMs)}compress(e){return ji(this,void 0,void 0,function*(){const t=new ReadableStream({start(t){t.enqueue((new TextEncoder).encode(e)),t.close()}}).pipeThrough(new CompressionStream("gzip")).getReader(),i=[];for(;;){const{done:e,value:n}=yield t.read();if(e)break;i.push(n)}return new Blob(i)})}extendFaroSession(e,t){const i="Session expired",n=e.sessionTracking;if(null==n?void 0:n.enabled){const{fetchUserSession:e,storeUserSession:s}=ft(n);ut({fetchUserSession:e,storeUserSession:s})({forceSessionExtend:!0}),t(`${i} created new session.`)}else t(`${i}.`)}}function Un(e){var t,i,n,s,r;const o=[],a=J(e.unpatchedConsole,e.internalLoggerLevel);e.transports?((e.url||e.apiKey)&&a.error('if "transports" is defined, "url" and "apiKey" should not be defined'),o.push(...e.transports)):e.url?o.push(new Cn({url:e.url,apiKey:e.apiKey,requestCompression:e.requestCompression})):a.error('either "url" or "transports" must be defined');const{dedupe:l=!0,eventDomain:u=xn,globalObjectKey:c=Ee,instrumentations:d=In(),internalLoggerLevel:p=G,isolate:g=!1,logArgsSerializer:h=ge,metas:f=Mn(e),paused:m=!1,preventGlobalExposure:v=!1,unpatchedConsole:b=W,url:w,experimental:y}=e,S=Ui(e,["dedupe","eventDomain","globalObjectKey","instrumentations","internalLoggerLevel","isolate","logArgsSerializer","metas","paused","preventGlobalExposure","unpatchedConsole","url","experimental"]),T=null!==(t=null==y?void 0:y.trackNavigation)&&void 0!==t&&t,E={dataAttributeName:null!==(n=null===(i=e.userActionsInstrumentation)||void 0===i?void 0:i.dataAttributeName)&&void 0!==n?n:Hi,excludeItem:null===(s=e.userActionsInstrumentation)||void 0===s?void 0:s.excludeItem};return Object.assign(Object.assign({},S),{batching:Object.assign(Object.assign({},ke),e.batching),dedupe:l,globalObjectKey:c,instrumentations:jn(d,e),internalLoggerLevel:p,isolate:g,logArgsSerializer:h,metas:f,parseStacktrace:jt,paused:m,preventGlobalExposure:v,transports:o,unpatchedConsole:b,eventDomain:u,ignoreUrls:[...null!==(r=e.ignoreUrls)&&void 0!==r?r:[],...w?[w]:[],/\/collect(?:\/[\w]*)?$/],sessionTracking:Object.assign(Object.assign(Object.assign({},rt),e.sessionTracking),Pn({trackGeolocation:e.trackGeolocation,sessionTracking:e.sessionTracking})),userActionsInstrumentation:E,experimental:{trackNavigation:T}})}function jn(e,{experimental:t}){var i;const n=null!==(i=null==t?void 0:t.trackNavigation)&&void 0!==i&&i;return e.filter(e=>!("@grafana/faro-web-sdk:instrumentation-navigation"===e.name&&!n))}function Mn(e){var t,i;const{page:n,generatePageId:s}=null!==(t=null==e?void 0:e.pageTracking)&&void 0!==t?t:{},r=[De,ze,_n({generatePageId:s,initialPageMeta:n}),...null!==(i=e.metas)&&void 0!==i?i:[],Be];return g(null===window||void 0===window?void 0:window.k6)?[...r,On]:r}function Pn({trackGeolocation:e,sessionTracking:t}){var i;const n={};return p(e)&&(n.geoLocationTrackingEnabled=e),x(n)?{}:{session:Object.assign(Object.assign({},null!==(i=null==t?void 0:t.session)&&void 0!==i?i:{}),{overrides:n})}}return e.BaseExtension=Q,e.BaseInstrumentation=fe,e.BaseTransport=ee,e.CSPInstrumentation=un,e.ConsoleInstrumentation=Rt,e.ConsoleTransport=class extends ee{constructor(e={}){super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-console",this.version=me}send(t){var i;return this.unpatchedConsole[null!==(i=this.options.level)&&void 0!==i?i:e.LogLevel.DEBUG]("New event",ie([t]))}},e.EVENT_CLICK="click",e.EVENT_NAVIGATION="navigation",e.EVENT_ROUTE_CHANGE="route_change",e.EVENT_SESSION_EXTEND=Ae,e.EVENT_SESSION_RESUME=Oe,e.EVENT_SESSION_START=xe,e.EVENT_VIEW_CHANGED=Ie,e.ErrorsInstrumentation=Dt,e.FetchTransport=Cn,e.MAX_SESSION_PERSISTENCE_TIME=st,e.NavigationInstrumentation=kn,e.Observable=V,e.PerformanceInstrumentation=$i,e.PersistentSessionsManager=gt,e.SESSION_EXPIRATION_TIME=it,e.SESSION_INACTIVITY_TIME=nt,e.STORAGE_KEY=tt,e.SessionInstrumentation=mt,e.UserActionInstrumentation=ln,e.VERSION=me,e.ViewInstrumentation=zt,e.VolatileSessionsManager=ht,e.WebVitalsInstrumentation=Ci,e.allLogLevels=M,e.browserMeta=De,e.buildStackFrame=_t,e.createInternalLogger=J,e.createPromiseBuffer=N,e.createSession=qe,e.deepEqual=O,e.defaultEventDomain=xn,e.defaultExceptionType=ue,e.defaultGlobalObjectKey=Ee,e.defaultInternalLoggerLevel=G,e.defaultLogLevel=j,e.genShortID=D,e.getCurrentTimestamp=_,e.getDataFromSafariExtensions=Ct,e.getIgnoreUrls=Ye,e.getInternalFaroFromGlobalObject=function(){return z[be]},e.getStackFramesFromError=Ut,e.getTransportBody=ie,e.getUrlFromResource=et,e.getWebInstrumentations=In,e.globalObject=z,e.initializeFaro=function(e){const t=Un(e);if(t)return Te(t)},e.internalGlobalObjectKey=be,e.isArray=f,e.isBoolean=p,e.isDomError=T,e.isDomException=E,e.isElement=e=>k&&l(e,Element),e.isElementDefined=k,e.isEmpty=x,e.isError=y,e.isErrorDefined=w,e.isErrorEvent=S,e.isEvent=b,e.isEventDefined=v,e.isFunction=h,e.isInstanceOf=l,e.isInt=e=>d(e)&&Number.isInteger(e),e.isInternalFaroOnGlobalObject=ye,e.isMap=e=>I&&l(e,Map),e.isMapDefined=I,e.isNull=u,e.isNumber=d,e.isObject=g,e.isPrimitive=m,e.isRegExp=e=>a(e,"RegExp"),e.isString=c,e.isSymbol=e=>o(e,"symbol"),e.isSyntheticEvent=e=>g(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e,e.isThenable=e=>h(null==e?void 0:e.then),e.isToString=a,e.isTypeof=o,e.isUndefined=e=>o(e,"undefined"),e.makeCoreConfig=Un,e.noop=P,e.osMeta=ze,e.parseStacktrace=jt,e.sdkMeta=Be,e.setInternalFaroOnGlobalObject=we,e.transportItemTypeToBodyKey=n,e.unknownString=_e,e.userActionDataAttribute=Hi,e}({});
1
+ var GrafanaFaroWebSdk=function(e){"use strict";class t{constructor(e,t){var i,n;this.signalBuffer=[],this.itemLimit=null!==(i=null==t?void 0:t.itemLimit)&&void 0!==i?i:50,this.sendTimeout=null!==(n=null==t?void 0:t.sendTimeout)&&void 0!==n?n:250,this.paused=(null==t?void 0:t.paused)||!1,this.sendFn=e,this.paused||this.start(),"undefined"!=typeof document&&document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.flush()})}addItem(e){this.paused||(this.signalBuffer.push(e),this.signalBuffer.length>=this.itemLimit&&this.flush())}start(){this.paused=!1,this.sendTimeout>0&&(this.flushInterval=setInterval(()=>this.flush(),this.sendTimeout))}pause(){this.paused=!0,clearInterval(this.flushInterval)}groupItems(e){const t=new Map;return e.forEach(e=>{const i=JSON.stringify(e.meta);let n=t.get(i);n=void 0===n?[e]:[...n,e],t.set(i,n)}),Array.from(t.values())}flush(){if(this.paused||0===this.signalBuffer.length)return;this.groupItems(this.signalBuffer).forEach(this.sendFn),this.signalBuffer=[]}}var i;e.TransportItemType=void 0,(i=e.TransportItemType||(e.TransportItemType={})).EXCEPTION="exception",i.LOG="log",i.MEASUREMENT="measurement",i.TRACE="trace",i.EVENT="event";const n={[e.TransportItemType.EXCEPTION]:"exceptions",[e.TransportItemType.LOG]:"logs",[e.TransportItemType.MEASUREMENT]:"measurements",[e.TransportItemType.TRACE]:"traces",[e.TransportItemType.EVENT]:"events"};function s(e,i,n,s){var o;i.debug("Initializing transports");const a=[];let l=n.paused,u=[];const c=e=>{let t=e;for(const e of u){const i=t.map(e).filter(Boolean);if(0===i.length)return[];t=r(i,n)}return t},d=e=>{const t=c(e);if(0!==t.length)for(const e of a)i.debug(`Transporting item using ${e.name}\n`,t),e.isBatched()&&e.send(t)};let p;(null===(o=n.batching)||void 0===o?void 0:o.enabled)&&(p=new t(d,{sendTimeout:n.batching.sendTimeout,itemLimit:n.batching.itemLimit,paused:l}));return{add:(...t)=>{i.debug("Adding transports"),t.forEach(t=>{i.debug(`Adding "${t.name}" transport`);a.some(e=>e===t)?i.warn(`Transport ${t.name} is already added`):(t.unpatchedConsole=e,t.internalLogger=i,t.config=n,t.metas=s,a.push(t))})},addBeforeSendHooks:(...e)=>{i.debug("Adding beforeSendHooks\n",u),e.forEach(e=>{e&&u.push(e)})},getBeforeSendHooks:()=>[...u],execute:e=>{var t;l||((null===(t=n.batching)||void 0===t?void 0:t.enabled)&&(null==p||p.addItem(e)),(e=>{var t,s;if((null===(t=n.batching)||void 0===t?void 0:t.enabled)&&a.every(e=>e.isBatched()))return;const[r]=c([e]);if(void 0!==r)for(const e of a)i.debug(`Transporting item using ${e.name}\n`,r),e.isBatched()?(null===(s=n.batching)||void 0===s?void 0:s.enabled)||e.send([r]):e.send(r)})(e))},isPaused:()=>l,pause:()=>{i.debug("Pausing transports"),null==p||p.pause(),l=!0},remove:(...e)=>{i.debug("Removing transports"),e.forEach(e=>{i.debug(`Removing "${e.name}" transport`);const t=a.indexOf(e);-1!==t?a.splice(t,1):i.warn(`Transport "${e.name}" is not added`)})},removeBeforeSendHooks:(...e)=>{u.filter(t=>!e.includes(t))},get transports(){return[...a]},unpause:()=>{i.debug("Unpausing transports"),null==p||p.start(),l=!1}}}function r(t,i){if(i.preserveOriginalError)for(const i of t)i.type===e.TransportItemType.EXCEPTION&&delete i.payload.originalError;return t}function o(e,t){return typeof e===t}function a(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function l(e,t){try{return e instanceof t}catch(e){return!1}}const u=e=>o(e,"null"),c=e=>o(e,"string"),d=e=>o(e,"number")&&!isNaN(e)||o(e,"bigint"),p=e=>o(e,"boolean"),g=e=>!u(e)&&o(e,"object"),h=e=>o(e,"function"),f=e=>a(e,"Array"),m=e=>!g(e)&&!h(e),v="undefined"!=typeof Event,b=e=>v&&l(e,Event),w="undefined"!=typeof Error,y=e=>w&&l(e,Error),S=e=>a(e,"ErrorEvent"),T=e=>a(e,"DOMError"),E=e=>a(e,"DOMException"),k="undefined"!=typeof Element,I="undefined"!=typeof Map;function x(e){return null==e||(f(e)||c(e)?0===e.length:!!g(e)&&0===Object.keys(e).length)}function O(e,t){if(e===t)return!0;if(o(e,"number")&&isNaN(e))return o(t,"number")&&isNaN(t);const i=f(e),n=f(t);if(i!==n)return!1;if(i&&n){const i=e.length;if(i!==t.length)return!1;for(let n=i;0!==n--;)if(!O(e[n],t[n]))return!1;return!0}const s=g(e),r=g(t);if(s!==r)return!1;if(e&&t&&s&&r){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let e of i)if(!n.includes(e))return!1;for(let n of i)if(!O(e[n],t[n]))return!1;return!0}return!1}function A(){return Date.now()}function L(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}function _(){return(new Date).toISOString()}function C(e){return new Date(e).toISOString()}var U;e.LogLevel=void 0,(U=e.LogLevel||(e.LogLevel={})).TRACE="trace",U.DEBUG="debug",U.INFO="info",U.LOG="log",U.WARN="warn",U.ERROR="error";const j=e.LogLevel.LOG,M=[e.LogLevel.TRACE,e.LogLevel.DEBUG,e.LogLevel.INFO,e.LogLevel.LOG,e.LogLevel.WARN,e.LogLevel.ERROR];function P(){}function N(e){const{size:t,concurrency:i}=e,n=[];let s=0;const r=()=>{if(s<i&&n.length){const{producer:e,resolve:t,reject:i}=n.shift();s++,e().then(e=>{s--,r(),t(e)},e=>{s--,r(),i(e)})}};return{add:e=>{if(n.length+s>=t)throw new Error("Task buffer full");return new Promise((t,i)=>{n.push({producer:e,resolve:t,reject:i}),r()})}}}const R="abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789";function D(e=10){const t=new Uint32Array(e),i="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(null==i?void 0:i.getRandomValues)i.getRandomValues(t);else for(let i=0;i<e;i++)t[i]=Math.floor(4294967296*Math.random());let n="";for(let i=0;i<e;i++)n+=R[t[i]%59];return n}const q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:void 0;function z(e){const t=`__faroBundleId_${e}`,i=null==q?void 0:q[t];if("string"==typeof i&&""!==i)return i;const n="undefined"!=typeof window?window[t]:void 0;return"string"==typeof n&&""!==n?n:void 0}function B(e={}){return JSON.stringify(null!=e?e:{},function(){const e=new WeakSet;return function(t,i){if(g(i)&&null!==i){if(e.has(i))return null;e.add(i)}return i}}())}function F(e={}){const t={};for(const[i,n]of Object.entries(e))t[i]=g(n)&&null!==n?B(n):String(n);return t}class V{constructor(){this.subscribers=[]}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>this.unsubscribe(e)}}unsubscribe(e){this.subscribers=this.subscribers.filter(t=>t!==e)}notify(e){this.subscribers.forEach(t=>t(e))}first(){const e=new V,t=t=>{e.notify(t),i.unsubscribe()},i=this.subscribe(t),n=e.unsubscribe.bind(e);return this.withUnsubscribeOverride(e,n,t)}takeWhile(e){const t=new V,i=n=>{e(n)?t.notify(n):t.unsubscribe(i)};this.subscribe(i);const n=t.unsubscribe.bind(t);return this.withUnsubscribeOverride(t,n,i)}filter(e){const t=new V,i=i=>{e(i)&&t.notify(i)};this.subscribe(i);const n=t.unsubscribe.bind(t);return this.withUnsubscribeOverride(t,n,i)}merge(...e){const t=new V,i=[];e.forEach(e=>{const n=e.subscribe(e=>{t.notify(e)});i.push(n)});const n=t.unsubscribeAll.bind(t);return t.unsubscribe=()=>{i.forEach(e=>e.unsubscribe()),n()},t}withUnsubscribeOverride(e,t,i){return e.unsubscribe=e=>{t(e),this.unsubscribe(i)},e}unsubscribeAll(){this.subscribers=[]}}var $;e.InternalLoggerLevel=void 0,($=e.InternalLoggerLevel||(e.InternalLoggerLevel={}))[$.OFF=0]="OFF",$[$.ERROR=1]="ERROR",$[$.WARN=2]="WARN",$[$.INFO=3]="INFO",$[$.VERBOSE=4]="VERBOSE";const H={debug:P,error:P,info:P,prefix:"Faro",warn:P},G=e.InternalLoggerLevel.ERROR,W=Object.assign({},console);let K=W;function X(e){var t;return K=null!==(t=e.unpatchedConsole)&&void 0!==t?t:K,K}function J(t=W,i=G){const n=H;return i>e.InternalLoggerLevel.OFF&&(n.error=i>=e.InternalLoggerLevel.ERROR?function(...e){t.error(`${n.prefix}\n`,...e)}:P,n.warn=i>=e.InternalLoggerLevel.WARN?function(...e){t.warn(`${n.prefix}\n`,...e)}:P,n.info=i>=e.InternalLoggerLevel.INFO?function(...e){t.info(`${n.prefix}\n`,...e)}:P,n.debug=i>=e.InternalLoggerLevel.VERBOSE?function(...e){t.debug(`${n.prefix}\n`,...e)}:P),n}let Z=H;function Y(e,t){return Z=J(e,t.internalLoggerLevel),Z}class Q{constructor(){this.unpatchedConsole=W,this.internalLogger=H,this.config={},this.metas={}}logDebug(...e){this.internalLogger.debug(`${this.name}\n`,...e)}logInfo(...e){this.internalLogger.info(`${this.name}\n`,...e)}logWarn(...e){this.internalLogger.warn(`${this.name}\n`,...e)}logError(...e){this.internalLogger.error(`${this.name}\n`,...e)}}class ee extends Q{isBatched(){return!1}getIgnoreUrls(){return[]}}function te(e,t){var i,n;if(void 0===t)return e;if(void 0===e)return{resourceSpans:t};const s=null===(i=e.resourceSpans)||void 0===i?void 0:i[0];if(void 0===s)return e;const r=(null==s?void 0:s.scopeSpans)||[],o=(null===(n=null==t?void 0:t[0])||void 0===n?void 0:n.scopeSpans)||[];return Object.assign(Object.assign({},e),{resourceSpans:[Object.assign(Object.assign({},s),{scopeSpans:[...r,...o]})]})}function ie(t){let i={meta:{}};return void 0!==t[0]&&(i.meta=t[0].meta),t.forEach(t=>{switch(t.type){case e.TransportItemType.LOG:case e.TransportItemType.EVENT:case e.TransportItemType.EXCEPTION:case e.TransportItemType.MEASUREMENT:{const e=n[t.type],s=i[e];i=Object.assign(Object.assign({},i),{[e]:void 0===s?[t.payload]:[...s,t.payload]});break}case e.TransportItemType.TRACE:i=Object.assign(Object.assign({},i),{traces:te(i.traces,t.payload.resourceSpans)})}}),i}const ne="normal";var se;e.UserActionState=void 0,(se=e.UserActionState||(e.UserActionState={}))[se.Started=0]="Started",se[se.Halted=1]="Halted",se[se.Cancelled=2]="Cancelled",se[se.Ended=3]="Ended";class re{constructor(){this.buffer=[]}addItem(e){this.buffer.push(e)}flushBuffer(e){if(h(e))for(const t of this.buffer)e(t);this.buffer.length=0}size(){return this.buffer.length}}class oe extends V{constructor({name:t,parentId:i,trigger:n,transports:s,attributes:r,trackUserActionsExcludeItem:o,importance:a=ne,pushEvent:l}){super(),this.name=t,this.attributes=r,this.id=D(),this.trigger=n,this.parentId=null!=i?i:this.id,this.trackUserActionsExcludeItem=o,this.importance=a,this._pushEvent=l,this._itemBuffer=new re,this._transports=s,this._state=e.UserActionState.Started,this._start()}addItem(t){return this._state===e.UserActionState.Started&&(this._itemBuffer.addItem(t),!0)}_start(){this._state=e.UserActionState.Started,this._state===e.UserActionState.Started&&(this.startTime=A(),this._startTimeMono=L())}halt(){this._state===e.UserActionState.Started&&(this._state=e.UserActionState.Halted,this.notify(this._state))}cancel(){this._state===e.UserActionState.Started&&this._itemBuffer.flushBuffer(e=>{this._transports.execute(e)}),this._state=e.UserActionState.Cancelled,this.notify(this._state)}end(){if(this._state===e.UserActionState.Cancelled)return;const t=A(),i=L()-this._startTimeMono;this._state=e.UserActionState.Ended,this._itemBuffer.flushBuffer(t=>{if(function(t,i){return(null==i?void 0:i(t))||t.type===e.TransportItemType.MEASUREMENT&&"web-vitals"===t.payload.type}(t,this.trackUserActionsExcludeItem))return void this._transports.execute(t);const i=Object.assign(Object.assign({},t),{payload:Object.assign(Object.assign({},t.payload),{action:{parentId:this.id,name:this.name}})});this._transports.execute(i)}),this._state=e.UserActionState.Ended,this.notify(this._state),this._pushEvent("faro.user.action",Object.assign({userActionName:this.name,userActionStartTime:this.startTime.toString(),userActionEndTime:t.toString(),userActionDuration:i.toString(),userActionTrigger:this.trigger,userActionImportance:this.importance},F(this.attributes)),void 0,{timestampOverwriteMs:this.startTime,customPayloadTransformer:e=>(e.action={id:this.id,name:this.name},e)})}getState(){return this._state}}const ae=new V;function le(t,i){if(!t)return!1;return(null==t?void 0:t.getState())===e.UserActionState.Started&&(t.addItem(i),!0)}const ue="Error",ce=e=>e.map(e=>g(e)?B(e):String(e)).join(" ");let de;function pe({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){var a;t.debug("Initializing exceptions API");let l=null;de=null!==(a=i.parseStacktrace)&&void 0!==a?a:de;const d=e=>{t.debug("Changing stacktrace parser"),de=null!=e?e:de},{ignoreErrors:p=[],preserveOriginalError:h}=i;return d(i.parseStacktrace),{changeStacktraceParser:d,getStacktraceParser:()=>de,pushError:(a,{skipDedupe:d,stackFrames:m,type:v,context:b,spanContext:w,timestampOverwriteMs:S,originalError:T,fingerprint:E,fatal:k}={})=>{var I;if(!function(e,t){const{message:i,name:n,stack:s}=t;return r=e,o=i+" "+n+" "+s,r.some(e=>c(e)?o.includes(e):!!o.match(e));var r,o}(p,null!=T?T:a))try{const c=F(Object.assign(Object.assign({},function(e){let t=e.cause;y(t)?t=e.cause.toString():null!==t&&(g(e.cause)||f(e.cause))?t=B(e.cause):null!=t&&(t=e.cause.toString());return null==t?{}:{cause:t}}(null!=T?T:a)),null!=b?b:{})),p={meta:n.value,payload:Object.assign(Object.assign(Object.assign(Object.assign({type:v||a.name||ue,value:a.message,timestamp:S?C(S):_(),trace:w?{trace_id:w.traceId,span_id:w.spanId}:r.getTraceContext()},x(c)?{}:{context:c}),h?{originalError:T}:{}),E?{fingerprint:E}:{}),void 0!==k?{fatal:k}:{}),type:e.TransportItemType.EXCEPTION};(null==(m=null!=m?m:a.stack?null==de?void 0:de(a).frames:void 0)?void 0:m.length)&&(p.payload.stacktrace={frames:m});const A={type:p.payload.type,value:p.payload.value,stacktrace:p.payload.stacktrace,context:p.payload.context,fingerprint:p.payload.fingerprint,fatal:null!==(I=p.payload.fatal)&&void 0!==I&&I};if(!d&&i.dedupe&&!u(l)&&O(A,l))return void t.debug("Skipping error push because it is the same as the last one\n",p.payload);l=A,t.debug("Pushing exception\n",p),le(o.getActiveUserAction(),p)||s.execute(p)}catch(e){t.error("Error pushing event",e)}}}}const ge=e=>e.map(e=>{try{return String(e)}catch(e){return""}}).join(" ");function he(t,i,n,s,r){i.debug("Initializing API");let o=null;const a=function({transports:t,internalLogger:i,config:n,pushEvent:s}){var r;const o=null===(r=n.userActionsInstrumentation)||void 0===r?void 0:r.excludeItem;let a;const l=()=>a,u={startUserAction:(n,r,u)=>{if(void 0===l()){const i=new oe({name:n,transports:t,attributes:r,trigger:(null==u?void 0:u.triggerName)||"faroApiCall",importance:(null==u?void 0:u.importance)||ne,trackUserActionsExcludeItem:o,pushEvent:s});return i.filter(t=>[e.UserActionState.Ended,e.UserActionState.Cancelled].includes(t)).first().subscribe(()=>{a=void 0}),ae.notify({type:"user_action_start",userAction:i}),a=i,a}i.error("Attempted to create a new user action while one is already running. This is not possible.")},getActiveUserAction:l};return u}({transports:r,config:n,internalLogger:i,pushEvent:(e,t,n,s)=>{o?o(e,t,n,s):i.warn("pushEventImpl is not initialized. Event dropped:",{name:e,attributes:t,domain:n,options:s})}}),l=function(t,i,n,s,r){let o;return i.debug("Initializing traces API"),{getOTEL:()=>o,getTraceContext:()=>{const e=null==o?void 0:o.trace.getSpanContext(o.context.active());return e?{trace_id:e.traceId,span_id:e.spanId}:void 0},initOTEL:(e,t)=>{i.debug("Initializing OpenTelemetry"),o={trace:e,context:t}},isOTELInitialized:()=>!!o,pushTraces:t=>{try{const n={type:e.TransportItemType.TRACE,payload:t,meta:s.value};i.debug("Pushing trace\n",n),r.execute(n)}catch(e){i.error("Error pushing trace\n",e)}}}}(0,i,0,s,r),d={internalLogger:i,userActionsApi:a,config:n,metas:s,transports:r,tracesApi:l},p=function({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){let a=null;return{pushEvent:(l,c,d,{skipDedupe:p,spanContext:g,timestampOverwriteMs:h,customPayloadTransformer:f=e=>e}={})=>{try{const m=F(c),v={meta:n.value,payload:f({name:l,domain:null!=d?d:i.eventDomain,attributes:x(m)?void 0:m,timestamp:h?C(h):_(),trace:g?{trace_id:g.traceId,span_id:g.spanId}:r.getTraceContext()}),type:e.TransportItemType.EVENT},b={name:v.payload.name,attributes:v.payload.attributes,domain:v.payload.domain};if(!p&&i.dedupe&&!u(a)&&O(b,a))return void t.debug("Skipping event push because it is the same as the last one\n",v.payload);a=b,t.debug("Pushing event\n",v),le(o.getActiveUserAction(),v)||s.execute(v)}catch(e){t.error("Error pushing event",e)}}}}(d);return o=p.pushEvent,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l),pe(d)),function({internalLogger:e,metas:t}){let i,n,s,r;e.debug("Initializing meta API");const o=e=>{n&&t.remove(n),n={user:e},t.add(n)},a=(e,n)=>{var s;const r=null==n?void 0:n.overrides,o=r?{overrides:Object.assign(Object.assign({},null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.overrides),r)}:{};i&&t.remove(i),i={session:Object.assign(Object.assign({},x(e)?void 0:e),o)},t.add(i)},l=()=>t.value.session,u=()=>t.value.page;return{setUser:o,resetUser:o,setSession:a,resetSession:a,getSession:l,setView:(e,i)=>{var n;if((null==i?void 0:i.overrides)&&a(l(),{overrides:i.overrides}),(null===(n=null==s?void 0:s.view)||void 0===n?void 0:n.name)===(null==e?void 0:e.name))return;const r=s;s={view:e},t.add(s),r&&t.remove(r)},getView:()=>t.value.view,setPage:e=>{var i;const n=c(e)?Object.assign(Object.assign({},null!==(i=null==r?void 0:r.page)&&void 0!==i?i:u()),{id:e}):e;r&&t.remove(r),r={page:n},t.add(r)},getPage:u}}(d)),function({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){var a;t.debug("Initializing logs API");let l=null;const c=null!==(a=i.logArgsSerializer)&&void 0!==a?a:ge;return{pushLog:(a,{context:d,level:p,skipDedupe:g,spanContext:h,timestampOverwriteMs:f}={})=>{try{const m=F(d),v={type:e.TransportItemType.LOG,payload:{message:c(a),level:null!=p?p:j,context:x(m)?void 0:m,timestamp:f?C(f):_(),trace:h?{trace_id:h.traceId,span_id:h.spanId}:r.getTraceContext()},meta:n.value},b={message:v.payload.message,level:v.payload.level,context:v.payload.context};if(!g&&i.dedupe&&!u(l)&&O(b,l))return void t.debug("Skipping log push because it is the same as the last one\n",v.payload);l=b,t.debug("Pushing log\n",v),le(o.getActiveUserAction(),v)||s.execute(v)}catch(e){t.error("Error pushing log\n",e)}}}}(d)),function({internalLogger:t,config:i,metas:n,transports:s,tracesApi:r,userActionsApi:o}){t.debug("Initializing measurements API");let a=null;return{pushMeasurement:(l,{skipDedupe:c,context:d,spanContext:p,timestampOverwriteMs:g}={})=>{try{const h=F(d),f={type:e.TransportItemType.MEASUREMENT,payload:Object.assign(Object.assign({},l),{trace:p?{trace_id:p.traceId,span_id:p.spanId}:r.getTraceContext(),timestamp:g?C(g):_(),context:x(h)?void 0:h}),meta:n.value},m={type:f.payload.type,values:f.payload.values,context:f.payload.context};if(!c&&i.dedupe&&!u(a)&&O(m,a))return void t.debug("Skipping measurement push because it is the same as the last one\n",f.payload);a=m,t.debug("Pushing measurement\n",f),le(o.getActiveUserAction(),f)||s.execute(f)}catch(e){t.error("Error pushing measurement\n",e)}}}}(d)),p),a)}class fe extends Q{constructor(){super(...arguments),this.api={},this.transports={}}}const me="2.8.1";function ve(e){var t,i;const n=e.config.app.name,s=n?function(e){return null==q?void 0:q[`__faroGitHash_${e}`]}(n):void 0,r={sdk:{version:me,name:"faro"},app:Object.assign({bundleId:n&&z(n)},void 0!==s?{gitHash:s}:{})},o=null===(t=e.config.sessionTracking)||void 0===t?void 0:t.session;o&&e.api.setSession(o),e.config.app&&(r.app=Object.assign(Object.assign({},e.config.app),r.app)),e.config.user&&(r.user=e.config.user),e.config.view&&(r.view=e.config.view),e.metas.add(r,...null!==(i=e.config.metas)&&void 0!==i?i:[])}const be="_faroInternal";function we(e){e.config.isolate?e.internalLogger.debug("Skipping registering internal Faro instance on global object"):(e.internalLogger.debug("Registering internal Faro instance on global object"),Object.defineProperty(q,be,{configurable:!1,enumerable:!1,writable:!1,value:e}))}function ye(){return be in q}function Se(t,i,n,s,r,o,a){return i.debug("Initializing Faro"),e.faro={api:o,config:n,instrumentations:a,internalLogger:i,metas:s,pause:r.pause,transports:r,unpatchedConsole:t,unpause:r.unpause},we(e.faro),function(e){if(e.config.preventGlobalExposure)e.internalLogger.debug("Skipping registering public Faro instance in the global scope");else{if(e.internalLogger.debug(`Registering public faro reference in the global scope using "${e.config.globalObjectKey}" key`),e.config.globalObjectKey in q)return void e.internalLogger.warn(`Skipping global registration due to key "${e.config.globalObjectKey}" being used already. Please set "globalObjectKey" to something else or set "preventGlobalExposure" to "true"`);Object.defineProperty(q,e.config.globalObjectKey,{configurable:!1,writable:!1,value:e})}}(e.faro),e.faro}function Te(e){const t=X(e),i=Y(t,e);if(ye()&&!e.isolate)return void i.error('Faro is already registered. Either add instrumentations, transports etc. to the global faro instance or use the "isolate" property');i.debug("Initializing");const n=function(e,t){let i=[],n=[];const s=()=>i.reduce((e,t)=>Object.assign(e,h(t)?t():t),{}),r=()=>{if(n.length){const e=s();n.forEach(t=>t(e))}};return{add:(...e)=>{t.debug("Adding metas\n",e),i.push(...e),r()},remove:(...e)=>{t.debug("Removing metas\n",e),i=i.filter(t=>!e.includes(t)),r()},addListener:e=>{t.debug("Adding metas listener\n",e),n.push(e)},removeListener:e=>{t.debug("Removing metas listener\n",e),n=n.filter(t=>t!==e)},get value(){return s()}}}(0,i),r=s(t,i,e,n),o=he(0,i,e,n,r),a=function(e,t,i,n,s,r){t.debug("Initializing instrumentations");const o=[];return{add:(...a)=>{t.debug("Adding instrumentations"),a.forEach(a=>{t.debug(`Adding "${a.name}" instrumentation`),o.some(e=>e.name===a.name)?t.warn(`Instrumentation ${a.name} is already added`):(a.unpatchedConsole=e,a.internalLogger=t,a.config=i,a.metas=n,a.transports=s,a.api=r,o.push(a),a.initialize())})},get instrumentations(){return[...o]},remove:(...e)=>{t.debug("Removing instrumentations"),e.forEach(e=>{var i,n;t.debug(`Removing "${e.name}" instrumentation`);const s=o.reduce((t,i,n)=>null===t&&i.name===e.name?n:null,null);null!==s?(null===(n=(i=o[s]).destroy)||void 0===n||n.call(i),o.splice(s,1)):t.warn(`Instrumentation "${e.name}" is not added`)})}}}(t,i,e,n,r,o),l=Se(t,i,e,n,r,o,a);return ve(l),function(e){e.transports.add(...e.config.transports),e.transports.addBeforeSendHooks(e.config.beforeSend)}(l),function(e){e.instrumentations.add(...e.config.instrumentations)}(l),l}e.faro={api:{pushLog:()=>{},pushError:()=>{},changeStacktraceParser:()=>{},getStacktraceParser:()=>{},pushMeasurement:()=>{},pushTraces:()=>{},getOTEL:()=>{},getTraceContext:()=>{},initOTEL:()=>{},isOTELInitialized:()=>!1,setUser:()=>{},resetUser:()=>{},setSession:()=>{},resetSession:()=>{},getSession:()=>{},setView:()=>{},getView:()=>{},setPage:()=>{},getPage:()=>{},pushEvent:()=>{},startUserAction:()=>{},getActiveUserAction:()=>{}}};const Ee="faro",ke={enabled:!0,sendTimeout:250,itemLimit:50},Ie="view_changed",xe="session_start",Oe="session_resume",Ae="session_extend",Le="service_name_override",_e="unknown";var Ce,Ue={exports:{}},je=Ue.exports;var Me=(Ce||(Ce=1,function(e,t){!function(i,n){var s="function",r="undefined",o="object",a="string",l="major",u="model",c="name",d="type",p="vendor",g="version",h="architecture",f="console",m="mobile",v="tablet",b="smarttv",w="wearable",y="embedded",S="Amazon",T="Apple",E="ASUS",k="BlackBerry",I="Browser",x="Chrome",O="Firefox",A="Google",L="Honor",_="Huawei",C="LG",U="Microsoft",j="Motorola",M="Nvidia",P="OnePlus",N="Opera",R="OPPO",D="Samsung",q="Sharp",z="Sony",B="Xiaomi",F="Zebra",V="Facebook",$="Chromium OS",H="Mac OS",G=" Browser",W=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},K=function(e,t){return typeof e===a&&-1!==X(t).indexOf(X(e))},X=function(e){return e.toLowerCase()},J=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===r?e:e.substring(0,500)},Z=function(e,t){for(var i,r,a,l,u,c,d=0;d<t.length&&!u;){var p=t[d],g=t[d+1];for(i=r=0;i<p.length&&!u&&p[i];)if(u=p[i++].exec(e))for(a=0;a<g.length;a++)c=u[++r],typeof(l=g[a])===o&&l.length>0?2===l.length?typeof l[1]==s?this[l[0]]=l[1].call(this,c):this[l[0]]=l[1]:3===l.length?typeof l[1]!==s||l[1].exec&&l[1].test?this[l[0]]=c?c.replace(l[1],l[2]):n:this[l[0]]=c?l[1].call(this,c,l[2]):n:4===l.length&&(this[l[0]]=c?l[3].call(this,c.replace(l[1],l[2])):n):this[l]=c||n;d+=2}},Y=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var s=0;s<t[i].length;s++)if(K(t[i][s],e))return"?"===i?n:i}else if(K(t[i],e))return"?"===i?n:i;return t.hasOwnProperty("*")?t["*"]:e},Q={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},ee={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[g,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[g,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,g],[/opios[\/ ]+([\w\.]+)/i],[g,[c,N+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[g,[c,N+" GX"]],[/\bopr\/([\w\.]+)/i],[g,[c,N]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[g,[c,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[g,[c,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[c,g],[/quark(?:pc)?\/([-\w\.]+)/i],[g,[c,"Quark"]],[/\bddg\/([\w\.]+)/i],[g,[c,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[g,[c,"UC"+I]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[g,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[g,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[g,[c,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[g,[c,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[g,[c,"Smart Lenovo "+I]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+I],g],[/\bfocus\/([\w\.]+)/i],[g,[c,O+" Focus"]],[/\bopt\/([\w\.]+)/i],[g,[c,N+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[g,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[g,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[g,[c,N+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[g,[c,"MIUI"+G]],[/fxios\/([\w\.-]+)/i],[g,[c,O]],[/\bqihoobrowser\/?([\w\.]*)/i],[g,[c,"360"]],[/\b(qq)\/([\w\.]+)/i],[[c,/(.+)/,"$1Browser"],g],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1"+G],g],[/samsungbrowser\/([\w\.]+)/i],[g,[c,D+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[g,[c,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[c,"Sogou Mobile"],g],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[c,g],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[c],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[g,c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,V],g],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[c,g],[/\bgsa\/([\w\.]+) .*safari\//i],[g,[c,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[g,[c,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[g,[c,x+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,x+" WebView"],g],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[g,[c,"Android "+I]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,g],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[g,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[g,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[g,Y,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[c,g],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],g],[/(wolvic|librewolf)\/([\w\.]+)/i],[c,g],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[g,[c,O+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[c,[g,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[c,[g,/master.|lts./,""]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[h,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[h,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[h,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[h,/ower/,"",X]],[/ sun4\w[;\)]/i],[[h,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[h,X]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[u,[p,D],[d,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[p,D],[d,m]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[p,T],[d,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[p,T],[d,v]],[/(macintosh);/i],[u,[p,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[p,q],[d,m]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[u,[p,L],[d,v]],[/honor([-\w ]+)[;\)]/i],[u,[p,L],[d,m]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[u,[p,_],[d,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[p,_],[d,m]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[u,/_/g," "],[p,B],[d,v]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[u,/_/g," "],[p,B],[d,m]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[p,R],[d,m]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[u,[p,Y,{OnePlus:["304","403","203"],"*":R}],[d,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[p,"Vivo"],[d,m]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[p,"Realme"],[d,m]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[u,[p,j],[d,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[p,j],[d,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[p,C],[d,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[p,C],[d,m]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[u,[p,"Lenovo"],[d,v]],[/(nokia) (t[12][01])/i],[p,u,[d,v]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[u,/_/g," "],[d,m],[p,"Nokia"]],[/(pixel (c|tablet))\b/i],[u,[p,A],[d,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[p,A],[d,m]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[u,[p,z],[d,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[p,z],[d,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[p,P],[d,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[p,S],[d,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[p,S],[d,m]],[/(playbook);[-\w\),; ]+(rim)/i],[u,p,[d,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[p,k],[d,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[p,E],[d,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[p,E],[d,m]],[/(nexus 9)/i],[u,[p,"HTC"],[d,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[u,/_/g," "],[d,m]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[u,[p,"TCL"],[d,v]],[/(itel) ((\w+))/i],[[p,X],u,[d,Y,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[p,"Acer"],[d,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[p,"Meizu"],[d,m]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[p,"Ulefone"],[d,m]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[p,"Energizer"],[d,m]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[p,"Cat"],[d,m]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[p,"Smartfren"],[d,m]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[p,"Nothing"],[d,m]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[u,[p,"Archos"],[d,v]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[u,[p,"Archos"],[d,m]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[p,u,[d,v]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[p,u,[d,m]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,u,[d,v]],[/(surface duo)/i],[u,[p,U],[d,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[p,"Fairphone"],[d,m]],[/(u304aa)/i],[u,[p,"AT&T"],[d,m]],[/\bsie-(\w*)/i],[u,[p,"Siemens"],[d,m]],[/\b(rct\w+) b/i],[u,[p,"RCA"],[d,v]],[/\b(venue[\d ]{2,7}) b/i],[u,[p,"Dell"],[d,v]],[/\b(q(?:mv|ta)\w+) b/i],[u,[p,"Verizon"],[d,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[u,[p,"Barnes & Noble"],[d,v]],[/\b(tm\d{3}\w+) b/i],[u,[p,"NuVision"],[d,v]],[/\b(k88) b/i],[u,[p,"ZTE"],[d,v]],[/\b(nx\d{3}j) b/i],[u,[p,"ZTE"],[d,m]],[/\b(gen\d{3}) b.+49h/i],[u,[p,"Swiss"],[d,m]],[/\b(zur\d{3}) b/i],[u,[p,"Swiss"],[d,v]],[/\b((zeki)?tb.*\b) b/i],[u,[p,"Zeki"],[d,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],u,[d,v]],[/\b(ns-?\w{0,9}) b/i],[u,[p,"Insignia"],[d,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[u,[p,"NextBook"],[d,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],u,[d,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],u,[d,m]],[/\b(ph-1) /i],[u,[p,"Essential"],[d,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[u,[p,"Envizen"],[d,v]],[/\b(trio[-\w\. ]+) b/i],[u,[p,"MachSpeed"],[d,v]],[/\btu_(1491) b/i],[u,[p,"Rotor"],[d,v]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[u,[p,M],[d,v]],[/(sprint) (\w+)/i],[p,u,[d,m]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[p,U],[d,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[p,F],[d,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[p,F],[d,m]],[/smart-tv.+(samsung)/i],[p,[d,b]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[p,D],[d,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,C],[d,b]],[/(apple) ?tv/i],[p,[u,T+" TV"],[d,b]],[/crkey/i],[[u,x+"cast"],[p,A],[d,b]],[/droid.+aft(\w+)( bui|\))/i],[u,[p,S],[d,b]],[/(shield \w+ tv)/i],[u,[p,M],[d,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[p,q],[d,b]],[/(bravia[\w ]+)( bui|\))/i],[u,[p,z],[d,b]],[/(mi(tv|box)-?\w+) bui/i],[u,[p,B],[d,b]],[/Hbbtv.*(technisat) (.*);/i],[p,u,[d,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,J],[u,J],[d,b]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[u,[d,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,u,[d,f]],[/droid.+; (shield)( bui|\))/i],[u,[p,M],[d,f]],[/(playstation \w+)/i],[u,[p,z],[d,f]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[p,U],[d,f]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[u,[p,D],[d,w]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[p,u,[d,w]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[u,[p,R],[d,w]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[p,T],[d,w]],[/(opwwe\d{3})/i],[u,[p,P],[d,w]],[/(moto 360)/i],[u,[p,j],[d,w]],[/(smartwatch 3)/i],[u,[p,z],[d,w]],[/(g watch r)/i],[u,[p,C],[d,w]],[/droid.+; (wt63?0{2,3})\)/i],[u,[p,F],[d,w]],[/droid.+; (glass) \d/i],[u,[p,A],[d,w]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,u,[d,w]],[/; (quest( \d| pro)?)/i],[u,[p,V],[d,w]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[d,y]],[/(aeobc)\b/i],[u,[p,S],[d,y]],[/(homepod).+mac os/i],[u,[p,T],[d,y]],[/windows iot/i],[[d,y]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[d,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[d,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,m]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[u,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[g,[c,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[c,g],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[g,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[c,g],[/ladybird\//i],[[c,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[g,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,g],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[c,[g,Y,Q]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[g,Y,Q],[c,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[g,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,H],[g,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[g,c],[/(ubuntu) ([\w\.]+) like android/i],[[c,/(.+)/,"$1 Touch"],g],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[c,g],[/\(bb(10);/i],[g,[c,k]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[g,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[g,[c,O+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[g,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[g,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[g,[c,x+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,$],g],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,g],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],g],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[c,g]]},te=function(e,t){if(typeof e===o&&(t=e,e=n),!(this instanceof te))return new te(e,t).getResult();var f=typeof i!==r&&i.navigator?i.navigator:n,b=e||(f&&f.userAgent?f.userAgent:""),w=f&&f.userAgentData?f.userAgentData:n,y=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(ee,t):ee,S=f&&f.userAgent==b;return this.getBrowser=function(){var e,t={};return t[c]=n,t[g]=n,Z.call(t,b,y.browser),t[l]=typeof(e=t[g])===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n,S&&f&&f.brave&&typeof f.brave.isBrave==s&&(t[c]="Brave"),t},this.getCPU=function(){var e={};return e[h]=n,Z.call(e,b,y.cpu),e},this.getDevice=function(){var e={};return e[p]=n,e[u]=n,e[d]=n,Z.call(e,b,y.device),S&&!e[d]&&w&&w.mobile&&(e[d]=m),S&&"Macintosh"==e[u]&&f&&typeof f.standalone!==r&&f.maxTouchPoints&&f.maxTouchPoints>2&&(e[u]="iPad",e[d]=v),e},this.getEngine=function(){var e={};return e[c]=n,e[g]=n,Z.call(e,b,y.engine),e},this.getOS=function(){var e={};return e[c]=n,e[g]=n,Z.call(e,b,y.os),S&&!e[c]&&w&&w.platform&&"Unknown"!=w.platform&&(e[c]=w.platform.replace(/chrome os/i,$).replace(/macos/i,H)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===a&&e.length>500?J(e,500):e,this},this.setUA(b),this};te.VERSION="1.0.41",te.BROWSER=W([c,g,l]),te.CPU=W([h]),te.DEVICE=W([u,p,d,f,m,b,v,w,y]),te.ENGINE=te.OS=W([c,g]),e.exports&&(t=e.exports=te),t.UAParser=te;var ie=typeof i!==r&&(i.jQuery||i.Zepto);if(ie&&!ie.ua){var ne=new te;ie.ua=ne.getResult(),ie.ua.get=function(){return ne.getUA()},ie.ua.set=function(e){ne.setUA(e);var t=ne.getResult();for(var i in t)ie.ua[i]=t[i]}}}("object"==typeof window?window:je)}(Ue,Ue.exports)),Ue.exports);let Pe,Ne;function Re(){const e="undefined"!=typeof navigator?navigator.userAgent:"";return Pe===e&&Ne||(Ne=new Me.UAParser(e).getResult(),Pe=e),Ne}const De=()=>{const{browser:e,os:t,ua:i}=Re(),{name:n,version:s}=e,{name:r,version:o}=t,a=navigator.language,l=i.includes("Mobi"),u=function(){if(!n||!s)return;if("userAgentData"in navigator&&navigator.userAgentData)return navigator.userAgentData.brands;return}();return{browser:{name:null!=n?n:_e,version:null!=s?s:_e,os:`${null!=r?r:_e} ${null!=o?o:_e}`,userAgent:null!=i?i:_e,language:null!=a?a:_e,mobile:l,brands:null!=u?u:_e,viewportWidth:`${window.innerWidth}`,viewportHeight:`${window.innerHeight}`}}},qe=()=>{const{name:e,version:t}=Re().os;if(!e&&!t)return{};const i={};return e&&(i.name=e),t&&(i.version=t),{os:i}};function ze(t){var i,n,s,r;return{id:null!==(r=null===(s=null===(n=null===(i=e.faro.config)||void 0===i?void 0:i.sessionTracking)||void 0===n?void 0:n.generateSessionId)||void 0===s?void 0:s.call(n))&&void 0!==r?r:D(),attributes:t}}const Be=()=>({sdk:{name:"faro-web",version:me}}),Fe="sessionStorage",Ve="localStorage";function $e(t){var i;try{let e;e=window[t];const i="__faro_storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(n){return null===(i=e.faro.internalLogger)||void 0===i||i.info(`Web storage of type ${t} is not available. Reason: ${n}`),!1}}function He(e,t){return Je(t)?window[t].getItem(e):null}function Ge(e,t,i){if(Je(i))try{window[i].setItem(e,t)}catch(e){}}function We(e,t){Je(t)&&window[t].removeItem(e)}const Ke=$e(Ve),Xe=$e(Fe);function Je(e){return e===Ve?Ke:e===Fe&&Xe}function Ze(e,t){let i,n=!1;const s=()=>{null!=i?(e(...i),i=null,setTimeout(s,t)):n=!1};return(...r)=>{n?i=r:(e(...r),n=!0,setTimeout(s,t))}}function Ye(){return e.faro.transports.transports.flatMap(e=>e.getIgnoreUrls())}function Qe(e=""){return Ye().some(t=>e&&null!=e.match(t))}function et(e){return c(e)?e:e instanceof URL?e.href:!x(e)&&h(null==e?void 0:e.toString)?e.toString():void 0}const tt="com.grafana.faro.session",it=144e5,nt=9e5,st=nt,rt={enabled:!0,persistent:!1,maxSessionPersistenceTime:st};function ot(){var t,i,n;const s=e.faro.config.sessionTracking,r=null!==(n=null!==(i=null===(t=null==s?void 0:s.sampler)||void 0===t?void 0:t.call(s,{metas:e.faro.metas.value}))&&void 0!==i?i:null==s?void 0:s.samplingRate)&&void 0!==n?n:1,o="number"==typeof r?function(e){return Math.min(1,Math.max(0,e))}(r):0;return Math.random()<o}function at({sessionId:t,started:i,lastActivity:n,isSampled:s=!0}={}){var r,o;const a=A(),l=null===(o=null===(r=e.faro.config)||void 0===r?void 0:r.sessionTracking)||void 0===o?void 0:o.generateSessionId;return null==t&&(t="function"==typeof l?l():D()),{sessionId:t,lastActivity:null!=n?n:a,started:null!=i?i:a,isSampled:s}}function lt(e){if(null==e)return!1;const t=A();if(!(t-e.started<it))return!1;return t-e.lastActivity<nt}function ut({fetchUserSession:t,storeUserSession:i}){return function({forceSessionExtend:n}={forceSessionExtend:!1}){var s,r,o;if(!t||!i)return;const a=e.faro.config.sessionTracking,l=null==a?void 0:a.persistent;if(l&&!Ke||!l&&!Xe)return;const u=t();if(!1===n&&lt(u))i(Object.assign(Object.assign({},u),{lastActivity:A()}));else{let t=ct(at({isSampled:ot()}),u);i(t),null===(s=e.faro.api)||void 0===s||s.setSession(t.sessionMeta),null===(r=null==a?void 0:a.onSessionChange)||void 0===r||r.call(a,null!==(o=null==u?void 0:u.sessionMeta)&&void 0!==o?o:null,t.sessionMeta)}}}function ct(t,i){var n,s,r,o,a,l,u;const c=Object.assign(Object.assign({},t),{sessionMeta:{id:t.sessionId,attributes:pt(Object.assign(Object.assign(Object.assign({},null===(s=null===(n=e.faro.config.sessionTracking)||void 0===n?void 0:n.session)||void 0===s?void 0:s.attributes),null!==(o=null===(r=e.faro.metas.value.session)||void 0===r?void 0:r.attributes)&&void 0!==o?o:{}),{isSampled:t.isSampled.toString()}))}}),d=null!==(l=null===(a=e.faro.metas.value.session)||void 0===a?void 0:a.overrides)&&void 0!==l?l:null===(u=null==i?void 0:i.sessionMeta)||void 0===u?void 0:u.overrides;x(d)||(c.sessionMeta.overrides=d);const p=null==i?void 0:i.sessionId;return null!=p&&(c.sessionMeta.attributes.previousSession=p),c}function dt({fetchUserSession:t,storeUserSession:i}){let n=!1;return function(s){if(n)return;const r=s.session,o=t();let a=null==r?void 0:r.id;const l=null==r?void 0:r.attributes,u=null==r?void 0:r.overrides,c=null==o?void 0:o.sessionMeta,d=null==c?void 0:c.overrides,p=!!u&&!O(u,d),g=!!l&&!O(l,null==c?void 0:c.attributes);if(!!r&&a!==(null==o?void 0:o.sessionId)||g||p){const t=ct(at({sessionId:a,isSampled:ot()}),o);i(t),function(t,i={},n={}){var s,r,o;if(!t)return;const a=i.serviceName,l=null!==(o=null!==(s=n.serviceName)&&void 0!==s?s:null===(r=e.faro.metas.value.app)||void 0===r?void 0:r.name)&&void 0!==o?o:"";a&&a!==l&&e.faro.api.pushEvent(Le,{serviceName:a,previousServiceName:l})}(p,u,d),n=!0;try{e.faro.api.setSession(t.sessionMeta)}finally{n=!1}}}}function pt(e){const t={};for(const i of Object.keys(e)){const n=e[i];void 0!==n&&(t[i]=n)}return t}class gt{constructor(){this.updateSession=Ze(()=>this.updateUserSession(),1e3),this.updateUserSession=ut({fetchUserSession:gt.fetchUserSession,storeUserSession:gt.storeUserSession}),this.init()}static removeUserSession(){We(tt,gt.storageTypeLocal)}static storeUserSession(e){Ge(tt,B(e),gt.storageTypeLocal)}static fetchUserSession(){const e=He(tt,gt.storageTypeLocal);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.updateSession()}),e.faro.metas.addListener(dt({fetchUserSession:gt.fetchUserSession,storeUserSession:gt.storeUserSession}))}}gt.storageTypeLocal=Ve;class ht{constructor(){this.updateSession=Ze(()=>this.updateUserSession(),1e3),this.updateUserSession=ut({fetchUserSession:ht.fetchUserSession,storeUserSession:ht.storeUserSession}),this.init()}static removeUserSession(){We(tt,ht.storageTypeSession)}static storeUserSession(e){Ge(tt,B(e),ht.storageTypeSession)}static fetchUserSession(){const e=He(tt,ht.storageTypeSession);return e?JSON.parse(e):null}init(){document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.updateSession()}),e.faro.metas.addListener(dt({fetchUserSession:ht.fetchUserSession,storeUserSession:ht.storeUserSession}))}}function ft(e){return(null==e?void 0:e.persistent)?gt:ht}ht.storageTypeSession=Fe;class mt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-session",this.version=me}sendSessionStartEvent(e){var t,i;const n=e.session;if(n&&n.id!==(null===(t=this.notifiedSession)||void 0===t?void 0:t.id)){if(this.notifiedSession&&this.notifiedSession.id===(null===(i=n.attributes)||void 0===i?void 0:i.previousSession))return this.api.pushEvent(Ae,{},void 0,{skipDedupe:!0}),void(this.notifiedSession=n);this.notifiedSession=n,this.api.pushEvent(xe,{},void 0,{skipDedupe:!0})}}createInitialSession(e,t){var i,n,s,r,o,a;let l,u,c=e.fetchUserSession();if(t.persistent&&t.maxSessionPersistenceTime&&c){const e=A();c.lastActivity<e-t.maxSessionPersistenceTime&&(gt.removeUserSession(),c=null)}if(lt(c)){const e=null==c?void 0:c.sessionId;u=at({sessionId:e,isSampled:c.isSampled||!1,started:null==c?void 0:c.started});const s=null==c?void 0:c.sessionMeta,r=Object.assign(Object.assign({},null===(i=t.session)||void 0===i?void 0:i.overrides),null==s?void 0:s.overrides);u.sessionMeta=Object.assign(Object.assign({},t.session),{id:e,attributes:Object.assign(Object.assign(Object.assign({},null===(n=t.session)||void 0===n?void 0:n.attributes),null==s?void 0:s.attributes),{isSampled:u.isSampled.toString()}),overrides:r}),l=Oe}else{const e=null!==(r=null===(s=t.session)||void 0===s?void 0:s.id)&&void 0!==r?r:ze().id;u=at({sessionId:e,isSampled:ot()});const i=null===(o=t.session)||void 0===o?void 0:o.overrides;u.sessionMeta=Object.assign({id:e,attributes:Object.assign({isSampled:u.isSampled.toString()},null===(a=t.session)||void 0===a?void 0:a.attributes)},i?{overrides:i}:{}),l=xe}return{initialSession:u,lifecycleType:l}}registerBeforeSendHook(e){var t;const{updateSession:i}=new e;null===(t=this.transports)||void 0===t||t.addBeforeSendHooks(e=>{var t,n,s;i();const r=null===(t=e.meta.session)||void 0===t?void 0:t.attributes;if(r&&"true"===(null==r?void 0:r.isSampled)){let t=JSON.parse(JSON.stringify(e));const i=null===(n=t.meta.session)||void 0===n?void 0:n.attributes;return null==i||delete i.isSampled,0===Object.keys(null!=i?i:{}).length&&(null===(s=t.meta.session)||void 0===s||delete s.attributes),t}return null})}initialize(){this.logDebug("init session instrumentation");const e=this.config.sessionTracking;if(null==e?void 0:e.enabled){const t=ft(e);this.registerBeforeSendHook(t);const{initialSession:i,lifecycleType:n}=this.createInitialSession(t,e);t.storeUserSession(i);const s=i.sessionMeta;this.notifiedSession=s,this.api.setSession(s),n===xe&&this.api.pushEvent(xe,{},void 0,{skipDedupe:!0}),n===Oe&&this.api.pushEvent(Oe,{},void 0,{skipDedupe:!0})}this.metas.addListener(this.sendSessionStartEvent.bind(this))}}const vt="http-request-start",bt="http-request-end";let wt,yt=!1;const St=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;const Tt=/^\s*at (?:(?![a-z]+:\/\/)([^(]+?) ?\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Et=/\((\S*)(?::(\d+))(?::(\d+))\)/,kt="address at ",It=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|safari-extension|safari-web-extension|capacitor)?:\/.*?|\[native code]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,xt=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ot="safari-extension",At="safari-web-extension",Lt=/Minified React error #\d+;/i;function _t(e,t,i,n){const s={filename:e||document.location.href,function:t||"?"};return void 0!==i&&(s.lineno=i),void 0!==n&&(s.colno=n),s}function Ct(e,t){const i=null==e?void 0:e.includes(Ot),n=!i&&(null==e?void 0:e.includes(At));return i||n?[(null==e?void 0:e.includes("@"))?e.split("@")[0]:e,i?`${Ot}:${t}`:`${At}:${t}`]:[e,t]}function Ut(e){let t=[];e.stacktrace?t=e.stacktrace.split("\n").filter((e,t)=>t%2==0):e.stack&&(t=e.stack.split("\n"));const i=t.reduce((t,i,n)=>{if(i.length>1024)return t;let s,r,o,a,l;if(s=Tt.exec(i)){if(r=s[1],o=s[2],a=s[3],l=s[4],null==o?void 0:o.startsWith("eval")){const e=Et.exec(o);e&&(o=e[1],a=e[2],l=e[3])}o=(null==o?void 0:o.startsWith(kt))?o.substring(11):o,[r,o]=Ct(r,o)}else if(s=It.exec(i)){if(r=s[1],o=s[3],a=s[4],l=s[5],o&&o.includes(" > eval")){const e=xt.exec(o);e&&(r=r||"eval",o=e[1],a=e[2])}else 0===n&&!l&&d(e.columnNumber)&&(l=String(e.columnNumber+1));[r,o]=Ct(r,o)}return(o||r)&&t.push(_t(o,r,a?Number(a):void 0,l?Number(l):void 0)),t},[]);return Lt.test(e.message)?i.slice(1):i}function jt(e){return{frames:Ut(e)}}function Mt(e){let t,i,n,s,r=[];if(S(e)&&e.error)t=e.error.message,i=e.error.name,r=Ut(e.error);else if((n=T(e))||E(e)){const{name:s,message:r}=e;i=null!=s?s:n?"DOMError":"DOMException",t=r?`${i}: ${r}`:i}else y(e)?(i=e.name,t=e.message,r=Ut(e)):(g(e)||(s=b(e)))&&(i=s?e.constructor.name:void 0,t=`Non-Error exception captured with keys: ${Object.keys(e)}`);return[t,i,r]}function Pt(e){const[t,i,n,s,r]=e;let o,a,l=[];const u=c(t),d=_t(i,"?",n,s);return r||!u?([o,a,l]=Mt(null!=r?r:t),0===l.length&&(l=[d])):u&&([o,a]=function(e){var t,i;const n=e.match(St),s=null!==(t=null==n?void 0:n[1])&&void 0!==t?t:ue;return[null!==(i=null==n?void 0:n[2])&&void 0!==i?i:e,s]}(t),l=[d]),{value:o,type:a,stackFrames:l}}function Nt(e,t){return y(e[0])?Pt(e):{value:t(e)}}class Rt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-console",this.version=me,this.errorSerializer=ge}initialize(){var t,i;const n=this.config.consoleInstrumentation,s=(null==n?void 0:n.serializeErrors)||!!(null==n?void 0:n.errorSerializer);this.errorSerializer=s?null!==(t=null==n?void 0:n.errorSerializer)&&void 0!==t?t:ce:ge;const r=null!==(i=null==n?void 0:n.disabledLevels)&&void 0!==i?i:Rt.defaultDisabledLevels,o=function(e){if(wt||(wt=new V),!yt){const t=null!=e?e:W;M.forEach(e=>{console[e]=(...i)=>{var n;wt.notify({type:"console",level:e,args:i}),null===(n=t[e])||void 0===n||n.apply(console,i)}}),yt=!0}return wt}(this.unpatchedConsole);this.subscription=o.subscribe(({level:t,args:i})=>{if(!r.includes(t))try{if(t!==e.LogLevel.ERROR||(null==n?void 0:n.consoleErrorAsLog))if(t===e.LogLevel.ERROR&&(null==n?void 0:n.consoleErrorAsLog)){const{value:e,type:n,stackFrames:s}=Nt(i,this.errorSerializer);this.api.pushLog(e?[Rt.consoleErrorPrefix+e]:i,{level:t,context:{value:null!=e?e:"",type:null!=n?n:"",stackFrames:(null==s?void 0:s.length)?ce(s):""}})}else this.api.pushLog(i,{level:t});else{const{value:e,type:t,stackFrames:n}=Nt(i,this.errorSerializer);if(e&&!t&&!n)return void this.api.pushError(new Error(Rt.consoleErrorPrefix+e));this.api.pushError(new Error(Rt.consoleErrorPrefix+e),{type:t,stackFrames:n})}}catch(e){this.logError(e)}})}destroy(){var e;null===(e=this.subscription)||void 0===e||e.unsubscribe(),this.subscription=void 0}}Rt.defaultDisabledLevels=[e.LogLevel.DEBUG,e.LogLevel.TRACE,e.LogLevel.LOG],Rt.consoleErrorPrefix="console.error: ";class Dt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-errors",this.version=me}initialize(){var e;this.logDebug("Initializing"),function(e){const t=window.onerror;window.onerror=(...i)=>{try{const{value:t,type:n,stackFrames:s}=Pt(i),r=i[4];if(t){const i={type:n,stackFrames:s};null!=r&&(i.originalError=r),e.pushError(new Error(t),i)}}finally{null==t||t.apply(window,i)}}}(this.api),e=this.api,window.addEventListener("unhandledrejection",t=>{var i,n;let s,r,o=t;o.reason?o=t.reason:(null===(i=t.detail)||void 0===i?void 0:i.reason)&&(o=null===(n=t.detail)||void 0===n?void 0:n.reason);let a=[];m(o)?(s=`Non-Error promise rejection captured with value: ${String(o)}`,r="UnhandledRejection"):[s,r,a]=Mt(o),s&&e.pushError(new Error(s),{type:r,stackFrames:a})})}}class qt extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-view",this.version=me}sendViewChangedEvent(e){var t,i,n,s;const r=e.view;r&&r.name!==(null===(t=this.notifiedView)||void 0===t?void 0:t.name)&&(this.api.pushEvent(Ie,{fromView:null!==(n=null===(i=this.notifiedView)||void 0===i?void 0:i.name)&&void 0!==n?n:_e,toView:null!==(s=r.name)&&void 0!==s?s:_e},void 0,{skipDedupe:!0}),this.notifiedView=r)}initialize(){this.metas.addListener(this.sendViewChangedEvent.bind(this))}}class zt{t;o=0;i=[];u(e){if(e.hadRecentInput)return;const t=this.i[0],i=this.i.at(-1);this.o&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.o+=e.value,this.i.push(e)):(this.o=e.value,this.i=[e]),this.t?.(e)}}const Bt=()=>{const e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},Ft=e=>{if("loading"===document.readyState)return"loading";const t=Bt();if(t){if(e<t.domInteractive)return"loading";if(0===t.domContentLoadedEventStart||e<t.domContentLoadedEventStart)return"dom-interactive";if(0===t.domComplete||e<t.domComplete)return"dom-content-loaded"}return"complete"},Vt=e=>{const t=e.nodeName;return 1===e.nodeType?t.toLowerCase():t.toUpperCase().replace(/^#/,"")},$t=e=>{let t="";try{for(;9!==e?.nodeType;){const i=e,n=i.id?"#"+i.id:[Vt(i),...Array.from(i.classList).sort()].join(".");if(t.length+n.length>99)return t||n;if(t=t?n+">"+t:n,i.id)break;e=i.parentNode}}catch{}return t},Ht=new WeakMap;function Gt(e,t){let i=Ht.get(t);return i||(i=new WeakMap,Ht.set(t,i)),i.get(e)||i.set(e,new t),i.get(e)}let Wt=-1;const Kt=()=>Wt,Xt=e=>{addEventListener("pageshow",t=>{t.persisted&&(Wt=t.timeStamp,e(t))},!0)},Jt=(e,t,i,n)=>{let s,r;return o=>{t.value>=0&&(o||n)&&(r=t.value-(s??0),(r||void 0===s)&&(s=t.value,t.delta=r,t.rating=((e,t)=>e>t[1]?"poor":e>t[0]?"needs-improvement":"good")(t.value,i),e(t)))}},Zt=e=>{requestAnimationFrame(()=>requestAnimationFrame(e))},Yt=()=>Bt()?.activationStart??0,Qt=(e,t=-1)=>{const i=Bt();let n="navigate";return Kt()>=0?n="back-forward-cache":i&&(document.prerendering||Yt()>0?n="prerender":document.wasDiscarded?n="restore":i.type&&(n=i.type.replace(/_/g,"-"))),{name:e,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},ei=(e,t,i={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){const n=new PerformanceObserver(e=>{queueMicrotask(()=>{t(e.getEntries())})});return n.observe({type:e,buffered:!0,...i}),n}}catch{}},ti=e=>{let t=!1;return()=>{t||(e(),t=!0)}};let ii=-1;const ni=new Set,si=()=>"hidden"!==document.visibilityState||document.prerendering?1/0:0,ri=e=>{if("hidden"===document.visibilityState){if("visibilitychange"===e.type)for(const e of ni)e();isFinite(ii)||(ii="visibilitychange"===e.type?e.timeStamp:0,removeEventListener("prerenderingchange",ri,!0))}},oi=()=>{if(ii<0){const e=Yt(),t=document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(t=>"hidden"===t.name&&t.startTime>=e)?.startTime;ii=t??si(),addEventListener("visibilitychange",ri,!0),addEventListener("prerenderingchange",ri,!0),Xt(()=>{setTimeout(()=>{ii=si()})})}return{get firstHiddenTime(){return ii},onHidden(e){ni.add(e)}}},ai=e=>{document.prerendering?addEventListener("prerenderingchange",e,!0):e()},li=[1800,3e3],ui=(e,t={})=>{ai(()=>{const i=oi();let n,s=Qt("FCP");const r=ei("paint",e=>{for(const t of e)"first-contentful-paint"===t.name&&(r.disconnect(),t.startTime<i.firstHiddenTime&&(s.value=Math.max(t.startTime-Yt(),0),s.entries.push(t),n(!0)))});r&&(n=Jt(e,s,li,t.reportAllChanges),Xt(i=>{s=Qt("FCP"),n=Jt(e,s,li,t.reportAllChanges),Zt(()=>{s.value=performance.now()-i.timeStamp,n(!0)})}))})},ci=[.1,.25],di=e=>e.find(e=>1===e.node?.nodeType)||e[0];let pi=0,gi=1/0,hi=0;const fi=e=>{for(const t of e)t.interactionId&&(gi=Math.min(gi,t.interactionId),hi=Math.max(hi,t.interactionId),pi=hi?(hi-gi)/7+1:0)};let mi;const vi=()=>mi?pi:performance.interactionCount??0;let bi=0;class wi{l=[];h=new Map;m;p;v(){bi=vi(),this.l.length=0,this.h.clear()}M(){const e=Math.min(this.l.length-1,Math.floor((vi()-bi)/50));return this.l[e]}u(e){if(this.m?.(e),!e.interactionId&&"first-input"!==e.entryType)return;const t=this.l.at(-1);let i=this.h.get(e.interactionId);if(i||this.l.length<10||e.duration>t.T){if(i?e.duration>i.T?(i.entries=[e],i.T=e.duration):e.duration===i.T&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],T:e.duration},this.h.set(i.id,i),this.l.push(i)),this.l.sort((e,t)=>t.T-e.T),this.l.length>10){const e=this.l.splice(10);for(const t of e)this.h.delete(t.id)}this.p?.(i)}}}const yi=e=>{const t=globalThis.requestIdleCallback||setTimeout,i=globalThis.cancelIdleCallback||clearTimeout;if("hidden"===document.visibilityState)e();else{const n=ti(e);let s=-1;const r=()=>{i(s),n()};addEventListener("visibilitychange",r,{once:!0,capture:!0}),s=t(()=>{removeEventListener("visibilitychange",r,{capture:!0}),n()})}},Si=[200,500],Ti=(e,t={})=>{const i=Gt(t=Object.assign({},t),wi);let n=[],s=[],r=0;const o=new WeakMap,a=new WeakMap;let l=!1;const u=()=>{l||(yi(c),l=!0)},c=()=>{const e=new Set(i.l.map(e=>o.get(e.entries[0]))),t=s.length-10;s=s.filter((i,n)=>n>=t||e.has(i));const a=new Set;for(const e of s){const t=d(e.startTime,e.processingEnd);for(const e of t)a.add(e)}n=n.filter(e=>e.startTime>r||a.has(e)),l=!1};i.m=e=>{const i=e.startTime+e.duration;let n;r=Math.max(r,e.processingEnd);for(let r=s.length-1;r>=0;r--){const o=s[r];if(Math.abs(i-o.renderTime)<=8){n=o,n.startTime=Math.min(e.startTime,n.startTime),n.processingStart=Math.min(e.processingStart,n.processingStart),n.processingEnd=Math.max(e.processingEnd,n.processingEnd),!1!==t.includeProcessedEventEntries&&n.entries.push(e);break}}n||(n={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:i,entries:!1!==t.includeProcessedEventEntries?[e]:[]},s.push(n)),(e.interactionId||"first-input"===e.entryType)&&o.set(e,n),u()},i.p=e=>{if(!a.get(e)){const i=e.entries.find(e=>e.target)?.target;if(i){const n=t.generateTarget?.(i)??$t(i);a.set(e,n)}else{const t=e.entries.find(e=>e.targetSelector)?.targetSelector;t&&a.set(e,t)}}};const d=(e,t)=>{const i=[];for(const s of n)if(!(s.startTime+s.duration<e)){if(s.startTime>t)break;i.push(s)}return i};ei("long-animation-frame",e=>{n=n.concat(e),u()}),((e,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const i=oi();ai(()=>{"interactionCount"in performance||mi||(mi=ei("event",fi,{durationThreshold:0}));let n,s=Qt("INP");const r=Gt(t,wi),o=e=>{yi(()=>{for(const t of e)r.u(t);const t=r.M();t&&t.T!==s.value&&(s.value=t.T,s.entries=t.entries,n())})},a=ei("event",o,{durationThreshold:t.durationThreshold??40});n=Jt(e,s,Si,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),i.onHidden(()=>{o(a.takeRecords()),n(!0)}),Xt(()=>{r.v(),s=Qt("INP"),n=Jt(e,s,Si,t.reportAllChanges)}))})})(t=>{e((e=>{const t=e.entries[0],n=o.get(t),s=t.processingStart,r=Math.max(t.startTime+t.duration,s),l=Math.min(n.processingEnd,r),u=n.entries.sort((e,t)=>e.processingStart-t.processingStart),c=d(t.startTime,l),p=i.h.get(t.interactionId),g={interactionTarget:a.get(p),interactionType:t.name.startsWith("key")?"keyboard":"pointer",interactionTime:t.startTime,nextPaintTime:r,processedEventEntries:u,longAnimationFrameEntries:c,inputDelay:s-t.startTime,processingDuration:l-s,presentationDelay:r-l,loadState:Ft(t.startTime),longestScript:void 0,totalScriptDuration:void 0,totalStyleAndLayoutDuration:void 0,totalPaintDuration:void 0,totalUnattributedDuration:void 0};return(e=>{if(!e.longAnimationFrameEntries?.length)return;const t=e.interactionTime,i=e.inputDelay,n=e.processingDuration;let s,r,o=0,a=0,l=0,u=0;for(const l of e.longAnimationFrameEntries){a=a+l.startTime+l.duration-l.styleAndLayoutStart;for(const e of l.scripts){const l=e.startTime+e.duration;if(l<t)continue;const c=l-Math.max(t,e.startTime),d=e.duration?c/e.duration*e.forcedStyleAndLayoutDuration:0;o+=c-d,a+=d,c>u&&(r=e.startTime<t+i?"input-delay":e.startTime>=t+i+n?"presentation-delay":"processing-duration",s=e,u=c)}}const c=e.longAnimationFrameEntries.at(-1),d=c?c.startTime+c.duration:0;d>=t+i+n&&(l=e.nextPaintTime-d),s&&r&&(e.longestScript={entry:s,subpart:r,intersectingDuration:u}),e.totalScriptDuration=o,e.totalStyleAndLayoutDuration=a,e.totalPaintDuration=l,e.totalUnattributedDuration=e.nextPaintTime-t-o-a-l})(g),Object.assign(e,{attribution:g})})(t))},t)};class Ei{m;u(e){this.m?.(e)}}const ki=[2500,4e3],Ii=[800,1800],xi=e=>{document.prerendering?ai(()=>xi(e)):"complete"!==document.readyState?addEventListener("load",()=>xi(e),!0):setTimeout(e)},Oi="com.grafana.faro.lastNavigationId",Ai="load_state",Li="time_to_first_byte";class _i{constructor(e,t){this.corePushMeasurement=e,this.webVitalConfig=t}initialize(){this.measureCLS(),this.measureFCP(),this.measureINP(),this.measureLCP(),this.measureTTFB()}measureCLS(){var e;((e,t={})=>{const i=Gt(t=Object.assign({},t),zt),n=new WeakMap;i.t=e=>{if(e?.sources?.length){const i=di(e.sources),s=i?.node;if(s){const e=t.generateTarget?.(s)??$t(s);n.set(i,e)}}},((e,t={})=>{const i=oi();ui(ti(()=>{let n,s=Qt("CLS",0);const r=Gt(t,zt),o=e=>{for(const t of e)r.u(t);r.o>s.value&&(s.value=r.o,s.entries=r.i,n())},a=ei("layout-shift",o);a&&(n=Jt(e,s,ci,t.reportAllChanges),i.onHidden(()=>{o(a.takeRecords()),n(!0)}),Xt(()=>{r.o=0,s=Qt("CLS",0),n=Jt(e,s,ci,t.reportAllChanges),Zt(n)}),setTimeout(n))}))})(t=>{e((e=>{let t={};if(e.entries.length){const i=e.entries.reduce((e,t)=>e.value>t.value?e:t);if(i?.sources?.length){const e=di(i.sources);e&&(t={largestShiftTarget:n.get(e),largestShiftTime:i.startTime,largestShiftValue:i.value,largestShiftSource:e,largestShiftEntry:i,loadState:Ft(i.startTime)})}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{loadState:t,largestShiftValue:i,largestShiftTime:n,largestShiftTarget:s}=e.attribution,r=this.buildInitialValues(e);this.addIfPresent(r,"largest_shift_value",i),this.addIfPresent(r,"largest_shift_time",n);const o=this.buildInitialContext(e);this.addIfPresent(o,Ai,t),this.addIfPresent(o,"largest_shift_target",s),this.pushMeasurement(r,o)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureFCP(){var e;((e,t={})=>{ui(t=>{e((e=>{let t={timeToFirstByte:0,firstByteToFCP:e.value,loadState:Ft(Kt())};if(e.entries.length){const i=Bt(),n=e.entries.at(-1);if(i){const s=i.activationStart||0,r=Math.max(0,i.responseStart-s);t={timeToFirstByte:r,firstByteToFCP:e.value-r,loadState:Ft(e.entries[0].startTime),navigationEntry:i,fcpEntry:n}}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{firstByteToFCP:t,timeToFirstByte:i,loadState:n}=e.attribution,s=this.buildInitialValues(e);this.addIfPresent(s,"first_byte_to_fcp",t),this.addIfPresent(s,Li,i);const r=this.buildInitialContext(e);this.addIfPresent(r,Ai,n),this.pushMeasurement(s,r)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureINP(){var e;Ti(e=>{const{interactionTime:t,presentationDelay:i,inputDelay:n,processingDuration:s,nextPaintTime:r,loadState:o,interactionTarget:a,interactionType:l}=e.attribution,u=this.buildInitialValues(e);this.addIfPresent(u,"interaction_time",t),this.addIfPresent(u,"presentation_delay",i),this.addIfPresent(u,"input_delay",n),this.addIfPresent(u,"processing_duration",s),this.addIfPresent(u,"next_paint_time",r);const c=this.buildInitialContext(e);this.addIfPresent(c,Ai,o),this.addIfPresent(c,"interaction_target",a),this.addIfPresent(c,"interaction_type",l),this.pushMeasurement(u,c)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureLCP(){var e;((e,t={})=>{const i=Gt(t=Object.assign({},t),Ei),n=new WeakMap;i.m=e=>{const i=e.element;if(i){const s=t.generateTarget?.(i)??$t(i);n.set(e,s)}else e.id&&n.set(e,`#${e.id}`)},((e,t={})=>{ai(()=>{const i=oi();let n,s=Qt("LCP");const r=Gt(t,Ei),o=e=>{t.reportAllChanges||(e=e.slice(-1));for(const t of e)r.u(t),t.startTime<i.firstHiddenTime&&(s.value=Math.max(t.startTime-Yt(),0),s.entries=[t],n())},a=ei("largest-contentful-paint",o);if(a){n=Jt(e,s,ki,t.reportAllChanges);const i=ti(()=>{o(a.takeRecords()),a.disconnect(),n(!0)}),r=e=>{e.isTrusted&&(yi(i),removeEventListener(e.type,r,{capture:!0}))};for(const e of["keydown","click","visibilitychange"])addEventListener(e,r,{capture:!0});Xt(i=>{s=Qt("LCP"),n=Jt(e,s,ki,t.reportAllChanges),Zt(()=>{s.value=performance.now()-i.timeStamp,n(!0)})})}})})(t=>{e((e=>{let t={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){const i=e.entries.at(-1),s=i.url&&performance.getEntriesByType("resource").find(e=>e.name===i.url);t.target=n.get(i),t.lcpEntry=i,i.url&&(t.url=i.url),s&&(t.lcpResourceEntry=s);const r=Bt();if(r){const i=r.activationStart||0,n=Math.max(0,r.responseStart-i),o=Math.max(n,s?(s.requestStart||s.startTime)-i:0),a=Math.min(e.value,Math.max(o,s?s.responseEnd-i:0));t={...t,timeToFirstByte:n,resourceLoadDelay:o-n,resourceLoadDuration:a-o,elementRenderDelay:e.value-a,navigationEntry:r}}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{elementRenderDelay:t,resourceLoadDelay:i,resourceLoadDuration:n,timeToFirstByte:s,target:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"element_render_delay",t),this.addIfPresent(o,"resource_load_delay",i),this.addIfPresent(o,"resource_load_duration",n),this.addIfPresent(o,Li,s);const a=this.buildInitialContext(e);this.addIfPresent(a,"element",r),this.pushMeasurement(o,a)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}measureTTFB(){var e;((e,t={})=>{((e,t={})=>{let i=Qt("TTFB"),n=Jt(e,i,Ii,t.reportAllChanges);xi(()=>{const s=Bt();s&&(i.value=Math.max(s.responseStart-Yt(),0),i.entries=[s],n(!0),Xt(()=>{i=Qt("TTFB",0),n=Jt(e,i,Ii,t.reportAllChanges),n(!0)}))})})(t=>{e((e=>{let t={waitingDuration:0,cacheDuration:0,dnsDuration:0,connectionDuration:0,requestDuration:0};if(e.entries.length){const i=e.entries[0],n=i.activationStart||0,s=Math.max((i.workerStart||i.fetchStart)-n,0),r=Math.max(i.domainLookupStart-n,0),o=Math.max(i.connectStart-n,0),a=Math.max(i.connectEnd-n,0);t={waitingDuration:s,cacheDuration:r-s,dnsDuration:o-r,connectionDuration:a-o,requestDuration:e.value-a,navigationEntry:i}}return Object.assign(e,{attribution:t})})(t))},t)})(e=>{const{dnsDuration:t,connectionDuration:i,requestDuration:n,waitingDuration:s,cacheDuration:r}=e.attribution,o=this.buildInitialValues(e);this.addIfPresent(o,"dns_duration",t),this.addIfPresent(o,"connection_duration",i),this.addIfPresent(o,"request_duration",n),this.addIfPresent(o,"waiting_duration",s),this.addIfPresent(o,"cache_duration",r);const a=this.buildInitialContext(e);this.pushMeasurement(o,a)},{reportAllChanges:null===(e=this.webVitalConfig)||void 0===e?void 0:e.reportAllChanges})}buildInitialValues(e){const t=e.name.toLowerCase();return{[t]:e.value,delta:e.delta}}buildInitialContext(e){var t;const i=null!==(t=He(Oi,Fe))&&void 0!==t?t:_e;return{id:e.id,rating:e.rating,navigation_type:e.navigationType,navigation_entry_id:i}}pushMeasurement(e,t){this.corePushMeasurement({type:"web-vitals",values:e},{context:t})}addIfPresent(e,t,i){i&&(e[t]=i)}}class Ci extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-web-vitals",this.version=me}initialize(){this.logDebug("Initializing");new _i(this.api.pushMeasurement,this.config.webVitalsInstrumentation).initialize()}}function Ui(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}function ji(e,t,i,n){return new(i||(i=Promise))(function(s,r){function o(e){try{l(n.next(e))}catch(e){r(e)}}function a(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const Mi="resource",Pi=/^00-[a-f0-9]{32}-[a-f0-9]{16}-[0-9]{1,2}$/;function Ni(e=[]){for(const t of e)if("traceparent"===t.name){if(!Pi.test(t.description))continue;const[,e,i]=t.description.split("-");if(null!=e&&null!=i)return{traceId:e,spanId:i};break}}function Ri(e,t={}){for(const[i,n]of Object.entries(t)){const t=e[i];return null!=t&&(f(n)?n.includes(t):t===n)}return!0}function Di(e){const{connectEnd:t,connectStart:i,decodedBodySize:n,domainLookupEnd:s,domainLookupStart:r,duration:o,encodedBodySize:a,fetchStart:l,initiatorType:u,name:c,nextHopProtocol:d,redirectEnd:p,redirectStart:g,renderBlockingStatus:h,requestStart:f,responseEnd:m,responseStart:v,responseStatus:b,secureConnectionStart:w,transferSize:y,workerStart:S}=e;return{name:c,httpHost:zi(c),duration:Bi(o),tcpHandshakeTime:Bi(t-i),dnsLookupTime:Bi(s-r),tlsNegotiationTime:Bi(t-w),responseStatus:Bi(b),redirectTime:Bi(p-g),requestTime:Bi(v-f),responseTime:Bi(m-v),fetchTime:Bi(m-l),serviceWorkerTime:Bi(S>0?l-S:0),decodedBodySize:Bi(n),encodedBodySize:Bi(a),cacheHitStatus:function(){let e="fullLoad";0===y?n>0&&(e="cache"):null!=b?304===b&&(e="conditionalFetch"):a>0&&y<a&&(e="conditionalFetch");return e}(),renderBlockingStatus:Bi(h),protocol:d,initiatorType:u,visibilityState:document.visibilityState,ttfb:Bi(v-f),transferSize:Bi(y)}}function qi(e){const{activationStart:t,domComplete:i,domContentLoadedEventEnd:n,domContentLoadedEventStart:s,domInteractive:r,fetchStart:o,loadEventEnd:a,loadEventStart:l,responseStart:u,type:c}=e,d=function(){var e;if(null!=(null===(e=performance.timing)||void 0===e?void 0:e.domLoading))return performance.timing.domLoading-performance.timeOrigin;return null}();return Object.assign(Object.assign({},Di(e)),{pageLoadTime:Bi(i-o),documentParsingTime:Bi(d?r-d:null),domProcessingTime:Bi(i-r),domContentLoadHandlerTime:Bi(n-s),onLoadTime:Bi(a-l),ttfb:Bi(Math.max(u-(null!=t?t:0),0)),type:c})}function zi(e){try{return new URL(e).host||_e}catch(e){return _e}}function Bi(e){return null==e?_e:"number"==typeof e?Math.round(e>0?e:0).toString():e.toString()}const Fi={initiatorType:["xmlhttprequest","fetch"]};const Vi=new V;class $i extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-performance",this.version=me}initialize(){"PerformanceObserver"in window?function(e){if("complete"===document.readyState)e();else{const t=()=>{"complete"===document.readyState&&(e(),document.removeEventListener("readystatechange",t))};document.addEventListener("readystatechange",t)}}(()=>ji(this,void 0,void 0,function*(){const t=this.api.pushEvent,{faroNavigationId:i}=yield function(e){let t;const i=new Promise(e=>{t=e});return new PerformanceObserver(i=>{var n;const[s]=i.getEntries();if(null==s||Qe(s.name))return;const r=s.toJSON();let o=Ni(null==r?void 0:r.serverTiming);const a=null!==(n=He(Oi,Fe))&&void 0!==n?n:_e,l=Object.assign(Object.assign({},qi(r)),{faroNavigationId:D(),faroPreviousNavigationId:a});Ge(Oi,l.faroNavigationId,Fe),e("faro.performance.navigation",l,void 0,{spanContext:o,timestampOverwriteMs:performance.timeOrigin+r.startTime}),t(l)}).observe({type:"navigation",buffered:!0}),i}(t);null!=i&&function(t,i,n){const s=e.faro.config.trackResources;new PerformanceObserver(e=>{const r=e.getEntries();for(const e of r){if(Qe(e.name))continue;null==n||n.notify({type:Mi});const r=e.toJSON();let o=Ni(null==r?void 0:r.serverTiming);if(null==s&&Ri(r,Fi)||s){const e=Object.assign(Object.assign({},Di(r)),{faroNavigationId:t,faroResourceId:D()});i("faro.performance.resource",e,void 0,{spanContext:o,timestampOverwriteMs:performance.timeOrigin+r.startTime})}}}).observe({type:Mi,buffered:!0})}(i,t,Vi)})):this.logDebug("performance observer not supported. Disable performance instrumentation.")}}const Hi="data-faro-user-action-name";let Gi,Wi;function Ki(){return Gi||(Gi=new V),Wi||(Wi=new MutationObserver((e,t)=>{Gi.notify({type:"dom-mutation"})}),Wi.observe(document,{attributes:!0,childList:!0,subtree:!0,characterData:!0})),Gi}const Xi="fetch",Ji="xhr";let Zi,Yi,Qi,en,tn=!1;function nn(){if(Zi)return Zi;function e(e){Zi.notify({type:vt,request:e})}function t(e){Zi.notify({type:bt,request:e})}return Zi=new V,tn||(!function({onRequestEnd:e,onRequestStart:t}){Qi||(Qi=window.fetch);window.fetch=function(){var i,n;const s=null!==(i=et(arguments[0]))&&void 0!==i?i:"",r=Qe(s),o=(null!==(n=arguments[1])&&void 0!==n?n:{}).method,a=D();return r||t({url:s,method:o,requestId:a,apiType:Xi}),Qi.apply(this,arguments).then(t=>(r||e({url:s,method:o,requestId:a,apiType:Xi}),t)).catch(t=>{throw r||e({url:s,method:o,requestId:a,apiType:Xi}),t})}}({onRequestStart:e,onRequestEnd:t}),function({onRequestStart:e,onRequestEnd:t}){Yi||(Yi=XMLHttpRequest.prototype.open);XMLHttpRequest.prototype.open=function(){const i=arguments[1],n=Qe(i),s=arguments[0],r=D();this.addEventListener("loadstart",function(){n||e({url:i,method:s,requestId:r,apiType:Ji})}),this.addEventListener("load",function(){n||t({url:i,method:s,requestId:r,apiType:Ji})}),this.addEventListener("error",function(){n||t({url:i,method:s,requestId:r,apiType:Ji})}),this.addEventListener("abort",function(){n||t({url:i,method:s,requestId:r,apiType:Ji})}),Yi.apply(this,arguments)}}({onRequestStart:e,onRequestEnd:t}),tn=!0),Zi}let sn=!1;function rn(e){return e.type===bt}class on{constructor(e){this.userAction=e,this.http=nn(),this.dom=Ki(),this.perf=(en||(en=new V),sn||(Vi.subscribe(e=>{e.type===Mi&&en.notify({type:"resource-entry"})}),sn=!0),en),this.isValid=!1,this.runningRequests=new Map}attach(){this.allMonitorsSub=(new V).merge(this.http,this.dom,this.perf).takeWhile(()=>[e.UserActionState.Started,e.UserActionState.Halted].includes(this.userAction.getState())).filter(t=>!!(this.userAction.getState()!==e.UserActionState.Halted||rn(t)&&this.runningRequests.has(t.request.requestId))).subscribe(t=>{(function(e){return e.type===vt})(t)&&this.runningRequests.set(t.request.requestId,t.request),rn(t)&&this.runningRequests.delete(t.request.requestId),rn(t)?this.userAction.getState()===e.UserActionState.Halted&&0===this.runningRequests.size&&this.endAction():(this.isValid||(this.isValid=!0),this.scheduleFollowUp())}),this.stateSub=this.userAction.filter(t=>[e.UserActionState.Ended,e.UserActionState.Cancelled].includes(t)).first().subscribe(()=>this.cleanup()),this.scheduleFollowUp()}scheduleFollowUp(){this.clearTimer(this.followUpTid),this.followUpTid=setTimeout(()=>{this.userAction.getState()===e.UserActionState.Started&&this.runningRequests.size>0?this.haltAction():this.isValid?this.endAction():this.cancelAction()},100)}haltAction(){this.userAction.getState()===e.UserActionState.Started&&(this.userAction.halt(),this.startHaltTimeout())}startHaltTimeout(){var t,i,n;this.clearTimer(this.haltTid),this.haltTid=(t=this.haltTid,i=()=>{this.userAction.getState()===e.UserActionState.Halted&&this.endAction()},n=1e4,t&&clearTimeout(t),setTimeout(()=>{i()},n))}endAction(){this.userAction.end(),this.cleanup()}cancelAction(){this.userAction.cancel(),this.cleanup()}cleanup(){var e,t;this.clearTimer(this.followUpTid),this.clearTimer(this.haltTid),null===(e=this.allMonitorsSub)||void 0===e||e.unsubscribe(),null===(t=this.stateSub)||void 0===t||t.unsubscribe(),this.allMonitorsSub=void 0,this.stateSub=void 0,this.runningRequests.clear()}clearTimer(e){e&&clearTimeout(e)}}function an(e){const{api:t,config:i}=e;function n(e){new on(e).attach()}return{processUserEvent:function(e){var s,r;const o=function(e,t){const i=function(e){const t=e.split("data-")[1],i=null==t?void 0:t.replace(/-(.)/g,(e,t)=>t.toUpperCase());return null==i?void 0:i.replace(/-/g,"")}(t),n=e.dataset;for(const e in n)if(e===i)return n[e];return}(e.target,null!==(r=null===(s=i.userActionsInstrumentation)||void 0===s?void 0:s.dataAttributeName)&&void 0!==r?r:"faroUserActionName");if(!o)return;const a=t.startUserAction(o,{},{triggerName:e.type});a&&n(a)},processUserActionStarted:n}}class ln extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-user-action",this.version=me}initialize(){const{processUserEvent:t,processUserActionStarted:i}=an(e.faro);window.addEventListener("pointerdown",t),window.addEventListener("keydown",e=>{[" ","Enter"].includes(e.key)&&t(e)}),this._userActionSub=ae.subscribe(({type:e,userAction:t})=>{"user_action_start"===e&&i(t)})}destroy(){var e;null===(e=this._userActionSub)||void 0===e||e.unsubscribe()}}class un extends fe{constructor(){super(),this.name="@grafana/faro-web-sdk:instrumentation-csp",this.version=me}initialize(){document.addEventListener("securitypolicyviolation",this.securitypolicyviolationHandler.bind(this))}destroy(){document.removeEventListener("securitypolicyviolation",this.securitypolicyviolationHandler)}securitypolicyviolationHandler(e){const t={blockedURI:e.blockedURI,columnNumber:e.columnNumber,disposition:e.disposition,documentURI:e.documentURI,effectiveDirective:e.effectiveDirective,lineNumber:e.lineNumber,originalPolicy:e.originalPolicy,referrer:e.referrer,sample:e.sample,sourceFile:e.sourceFile,statusCode:e.statusCode,violatedDirective:e.violatedDirective};this.api.pushEvent("securitypolicyviolation",F(t))}}class cn extends V{constructor(e,t){var i,n,s,r;super(),this._tracking=!1,this.eventsObservable=e,this._options={inactivityMs:null!==(i=null==t?void 0:t.inactivityMs)&&void 0!==i?i:100,drainTimeoutMs:null!==(n=null==t?void 0:t.drainTimeoutMs)&&void 0!==n?n:1e4,isOperationStart:null!==(s=null==t?void 0:t.isOperationStart)&&void 0!==s?s:()=>{},isOperationEnd:null!==(r=null==t?void 0:t.isOperationEnd)&&void 0!==r?r:()=>{}},this._initialize()}_initialize(){this.eventsObservable.filter(()=>this._tracking).subscribe(e=>{var t,i,n;this._lastEventTime=L(),null===(t=this._currentEvents)||void 0===t||t.push(e);const s=this._options.isOperationStart(e);s&&(null===(i=this._activeOperations)||void 0===i||i.set(s,!0));const r=this._options.isOperationEnd(e);r&&(null===(n=this._activeOperations)||void 0===n||n.delete(r)),this._scheduleInactivityCheck()})}startTracking(){this._tracking||(this._tracking=!0,this._startTime=L(),this._lastEventTime=this._startTime,this.notify({message:"tracking-started"}),this._currentEvents=[],this._activeOperations=new Map,this._scheduleInactivityCheck())}stopTracking(){let e;this._tracking=!1,this._clearTimer(this._inactivityTid),this._clearTimer(this._drainTid),e=this.hasActiveOperations()?L()-this._startTime:this._lastEventTime?this._lastEventTime-this._startTime:0,this.notify({message:"tracking-ended",events:this._currentEvents,duration:e})}_scheduleInactivityCheck(){this._inactivityTid=dn(this._inactivityTid,()=>{this.hasActiveOperations()?this._startDrainTimeout():this.stopTracking()},this._options.inactivityMs)}_startDrainTimeout(){this._drainTid=dn(this._drainTid,()=>{this.stopTracking()},this._options.drainTimeoutMs)}hasActiveOperations(){return!!this._activeOperations&&this._activeOperations.size>0}_clearTimer(e){e&&clearTimeout(e)}}function dn(e,t,i){return e&&clearTimeout(e),e=setTimeout(()=>{t()},i)}let pn;const gn=new Set,hn=new Map;let fn,mn,vn,bn,wn,yn,Sn,Tn,En=!1;class kn extends fe{constructor(){super(...arguments),this.name="@grafana/faro-web-sdk:instrumentation-navigation",this.version=me}initialize(){const t=nn(),i=Ki(),n=function(){function e(e,t){const i=null!=t?t:location.href;i!==mn&&(fn.notify({type:"url-change",from:mn,to:i,trigger:e}),mn=i)}if(fn||(fn=new V,mn=location.href),!En)if("navigation"in window&&"NavigateEvent"in window){Sn=t=>{try{const i=null==t?void 0:t.destination;(null==i?void 0:i.sameDocument)&&"string"==typeof i.url&&e("navigate",i.url)}catch(e){}},window.navigation.addEventListener("navigate",Sn);const t=window.NavigateEvent;t&&t.prototype&&"function"==typeof t.prototype.intercept&&(Tn||(Tn=t.prototype.intercept),t.prototype.intercept=function(t){try{const t=!!(null==this?void 0:this.canIntercept),i=null==this?void 0:this.destination;t&&i&&!1===i.sameDocument&&"string"==typeof i.url&&e("navigate-intercept",i.url)}catch(e){}return Tn.call(this,t)}),En=!0}else vn||(vn=window.history.pushState),window.history.pushState=function(...t){const i=vn.apply(window.history,t);return e("pushState"),i},bn||(bn=window.history.replaceState),window.history.replaceState=function(...t){const i=bn.apply(window.history,t);return e("replaceState"),i},wn=()=>e("popstate"),yn=()=>e("hashchange"),window.addEventListener("popstate",wn),window.addEventListener("hashchange",yn),En=!0;return fn}(),s=(r=["pointerdown","keydown"],pn||(pn=new V),r.forEach(e=>{if(!gn.has(e)){const t=()=>{pn.notify({type:"interaction",name:e})};window.addEventListener(e,t),gn.add(e),hn.set(e,t)}}),pn);var r;const o=new cn((new V).merge(t,i,n),{inactivityMs:100,drainTimeoutMs:1e4,isOperationStart:e=>function(e){return e.type===vt}(e)?e.request.requestId:void 0,isOperationEnd:e=>function(e){return e.type===bt}(e)?e.request.requestId:void 0});o.filter(e=>"tracking-ended"===e.message).subscribe(t=>{var i,n,s;if((null===(i=t.events)||void 0===i?void 0:i.some(e=>"url-change"===e.type))&&(null===(n=t.events)||void 0===n?void 0:n.some(e=>"dom-mutation"===e.type))){const i=null===(s=t.events)||void 0===s?void 0:s.find(e=>"url-change"===e.type);e.faro.api.pushEvent("faro.navigation",{fromUrl:null==i?void 0:i.from,toUrl:null==i?void 0:i.to,sameDocument:String(!0),duration:t.duration})}}),s.subscribe(()=>{o.startTracking()})}}function In(e={}){const t=[new ln,new Dt,new Ci,new mt,new qt,new kn];return!1!==e.enablePerformanceInstrumentation&&t.unshift(new $i),!1!==e.enableContentSecurityPolicyInstrumentation&&t.push(new un),!1!==e.captureConsole&&t.push(new Rt),t}const xn="browser",On=()=>{const e=window.k6;return{k6:Object.assign({isK6Browser:!0},(null==e?void 0:e.testRunId)&&{testRunId:null==e?void 0:e.testRunId})}};let An,Ln;function _n({generatePageId:e,initialPageMeta:t}={}){return()=>{const i=location.href;return h(e)&&An!==i&&(An=i,Ln=e(location)),{page:Object.assign(Object.assign({url:i},Ln?{id:Ln}:{}),t)}}}let Cn=0,Un=0;class jn extends ee{constructor(e){var t,i,n,s,r;super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-fetch",this.version=me,this.disabledUntil=new Date(0),this.rateLimitBackoffMs=null!==(t=e.defaultRateLimitBackoffMs)&&void 0!==t?t:5e3,this.getNow=null!==(i=e.getNow)&&void 0!==i?i:()=>Date.now();const o=null!==(n=e.requestCompression)&&void 0!==n&&n;o&&"undefined"==typeof CompressionStream?(this.compressionEnabled=!1,this.logWarn("requestCompression is enabled but CompressionStream is not available. Falling back to uncompressed.")):this.compressionEnabled=o,this.promiseBuffer=N({size:null!==(s=e.bufferSize)&&void 0!==s?s:30,concurrency:null!==(r=e.concurrency)&&void 0!==r?r:5})}send(e){return ji(this,void 0,void 0,function*(){try{if(this.disabledUntil>new Date(this.getNow()))return this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`),Promise.resolve();yield this.promiseBuffer.add(()=>ji(this,void 0,void 0,function*(){const t=JSON.stringify(ie(e)),{url:i,requestOptions:n,apiKey:s}=this.options,r=null!=n?n:{},{headers:o={}}=r,a=Ui(r,["headers"]),{keepalive:l}=a,u=Ui(a,["keepalive"]);let c;const d=this.metas.value.session;null!=d&&(c=d.id);const p={};for(const[e,t]of Object.entries(o))p[e]="function"==typeof t?yield Promise.resolve(t()):t;let g=t,h=t.length;const f={};this.compressionEnabled&&(g=yield this.compress(t),h=g.size,f["Content-Encoding"]="gzip");const m=Object.assign({method:"POST",headers:Object.assign(Object.assign(Object.assign(Object.assign({"Content-Type":"application/json"},f),p),s?{"x-api-key":s}:{}),c?{"x-faro-session-id":c}:{}),body:g},null!=u?u:{});return this.fetchWithKeepaliveRetry(i,m,h,l).catch(e=>{this.logError("Failed sending payload to the receiver\n",JSON.parse(t),e)})}))}catch(e){this.logError(e)}})}getIgnoreUrls(){var e;return[this.options.url].concat(null!==(e=this.config.ignoreUrls)&&void 0!==e?e:[])}isBatched(){return!0}getRetryAfterDate(e){const t=this.getNow(),i=e.headers.get("Retry-After");if(i){const e=Number(i);if(!isNaN(e))return new Date(1e3*e+t);const n=Date.parse(i);if(!isNaN(n))return new Date(n)}return new Date(t+this.rateLimitBackoffMs)}reserveKeepalive(e,t){if(!1===t)return{keepalive:!1,release:P};if(e>6e4||Cn+e>6e4||Un>=9)return this.logDebug("Disabling keepalive because the pending keepalive request budget would be exceeded."),{keepalive:!1,release:P};Cn+=e,Un++;let i=!1;return{keepalive:!0,release:()=>{i||(i=!0,Cn=Math.max(0,Cn-e),Un=Math.max(0,Un-1))}}}fetchWithKeepaliveRetry(e,t,i,n){return ji(this,void 0,void 0,function*(){const s=this.reserveKeepalive(i,n);try{const i=yield fetch(e,Object.assign(Object.assign({},t),{keepalive:s.keepalive}));return this.handleResponse(i)}catch(i){if(s.keepalive&&this.isFetchNetworkError(i)){this.logDebug("Retrying failed keepalive request with keepalive disabled.");const i=yield fetch(e,Object.assign(Object.assign({},t),{keepalive:!1}));return this.handleResponse(i)}throw i}finally{s.release()}})}handleResponse(e){return ji(this,void 0,void 0,function*(){if(202===e.status){"invalid"===e.headers.get("X-Faro-Session-Status")&&this.extendFaroSession(this.config,this.logDebug)}return 429===e.status&&(this.disabledUntil=this.getRetryAfterDate(e),this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`)),e.text().catch(P),e})}isFetchNetworkError(e){return e instanceof TypeError}compress(e){return ji(this,void 0,void 0,function*(){const t=new ReadableStream({start(t){t.enqueue((new TextEncoder).encode(e)),t.close()}}).pipeThrough(new CompressionStream("gzip")).getReader(),i=[];for(;;){const{done:e,value:n}=yield t.read();if(e)break;i.push(n)}return new Blob(i)})}extendFaroSession(e,t){const i="Session expired",n=e.sessionTracking;if(null==n?void 0:n.enabled){const{fetchUserSession:e,storeUserSession:s}=ft(n);ut({fetchUserSession:e,storeUserSession:s})({forceSessionExtend:!0}),t(`${i} created new session.`)}else t(`${i}.`)}}function Mn(e){var t,i,n,s,r;const o=[],a=J(e.unpatchedConsole,e.internalLoggerLevel);e.transports?((e.url||e.apiKey)&&a.error('if "transports" is defined, "url" and "apiKey" should not be defined'),o.push(...e.transports)):e.url?o.push(new jn({url:e.url,apiKey:e.apiKey,requestCompression:e.requestCompression})):a.error('either "url" or "transports" must be defined');const{dedupe:l=!0,eventDomain:u=xn,globalObjectKey:c=Ee,instrumentations:d=In(),internalLoggerLevel:p=G,isolate:g=!1,logArgsSerializer:h=ge,metas:f=Nn(e),paused:m=!1,preventGlobalExposure:v=!1,unpatchedConsole:b=W,url:w,experimental:y}=e,S=Ui(e,["dedupe","eventDomain","globalObjectKey","instrumentations","internalLoggerLevel","isolate","logArgsSerializer","metas","paused","preventGlobalExposure","unpatchedConsole","url","experimental"]),T=null!==(t=null==y?void 0:y.trackNavigation)&&void 0!==t&&t,E={dataAttributeName:null!==(n=null===(i=e.userActionsInstrumentation)||void 0===i?void 0:i.dataAttributeName)&&void 0!==n?n:Hi,excludeItem:null===(s=e.userActionsInstrumentation)||void 0===s?void 0:s.excludeItem};return Object.assign(Object.assign({},S),{batching:Object.assign(Object.assign({},ke),e.batching),dedupe:l,globalObjectKey:c,instrumentations:Pn(d,e),internalLoggerLevel:p,isolate:g,logArgsSerializer:h,metas:f,parseStacktrace:jt,paused:m,preventGlobalExposure:v,transports:o,unpatchedConsole:b,eventDomain:u,ignoreUrls:[...null!==(r=e.ignoreUrls)&&void 0!==r?r:[],...w?[w]:[],/\/collect(?:\/[\w]*)?$/],sessionTracking:Object.assign(Object.assign(Object.assign({},rt),e.sessionTracking),Rn({trackGeolocation:e.trackGeolocation,sessionTracking:e.sessionTracking})),userActionsInstrumentation:E,experimental:{trackNavigation:T}})}function Pn(e,{experimental:t}){var i;const n=null!==(i=null==t?void 0:t.trackNavigation)&&void 0!==i&&i;return e.filter(e=>!("@grafana/faro-web-sdk:instrumentation-navigation"===e.name&&!n))}function Nn(e){var t,i;const{page:n,generatePageId:s}=null!==(t=null==e?void 0:e.pageTracking)&&void 0!==t?t:{},r=[De,qe,_n({generatePageId:s,initialPageMeta:n}),...null!==(i=e.metas)&&void 0!==i?i:[],Be];return g(null===window||void 0===window?void 0:window.k6)?[...r,On]:r}function Rn({trackGeolocation:e,sessionTracking:t}){var i;const n={};return p(e)&&(n.geoLocationTrackingEnabled=e),x(n)?{}:{session:Object.assign(Object.assign({},null!==(i=null==t?void 0:t.session)&&void 0!==i?i:{}),{overrides:n})}}return e.BaseExtension=Q,e.BaseInstrumentation=fe,e.BaseTransport=ee,e.CSPInstrumentation=un,e.ConsoleInstrumentation=Rt,e.ConsoleTransport=class extends ee{constructor(e={}){super(),this.options=e,this.name="@grafana/faro-web-sdk:transport-console",this.version=me}send(t){var i;return this.unpatchedConsole[null!==(i=this.options.level)&&void 0!==i?i:e.LogLevel.DEBUG]("New event",ie([t]))}},e.EVENT_CLICK="click",e.EVENT_NAVIGATION="navigation",e.EVENT_ROUTE_CHANGE="route_change",e.EVENT_SESSION_EXTEND=Ae,e.EVENT_SESSION_RESUME=Oe,e.EVENT_SESSION_START=xe,e.EVENT_VIEW_CHANGED=Ie,e.ErrorsInstrumentation=Dt,e.FetchTransport=jn,e.MAX_SESSION_PERSISTENCE_TIME=st,e.NavigationInstrumentation=kn,e.Observable=V,e.PerformanceInstrumentation=$i,e.PersistentSessionsManager=gt,e.SESSION_EXPIRATION_TIME=it,e.SESSION_INACTIVITY_TIME=nt,e.STORAGE_KEY=tt,e.SessionInstrumentation=mt,e.UserActionInstrumentation=ln,e.VERSION=me,e.ViewInstrumentation=qt,e.VolatileSessionsManager=ht,e.WebVitalsInstrumentation=Ci,e.allLogLevels=M,e.browserMeta=De,e.buildStackFrame=_t,e.createInternalLogger=J,e.createPromiseBuffer=N,e.createSession=ze,e.deepEqual=O,e.defaultEventDomain=xn,e.defaultExceptionType=ue,e.defaultGlobalObjectKey=Ee,e.defaultInternalLoggerLevel=G,e.defaultLogLevel=j,e.genShortID=D,e.getCurrentTimestamp=_,e.getDataFromSafariExtensions=Ct,e.getIgnoreUrls=Ye,e.getInternalFaroFromGlobalObject=function(){return q[be]},e.getStackFramesFromError=Ut,e.getTransportBody=ie,e.getUrlFromResource=et,e.getWebInstrumentations=In,e.globalObject=q,e.initializeFaro=function(e){const t=Mn(e);if(t)return Te(t)},e.internalGlobalObjectKey=be,e.isArray=f,e.isBoolean=p,e.isDomError=T,e.isDomException=E,e.isElement=e=>k&&l(e,Element),e.isElementDefined=k,e.isEmpty=x,e.isError=y,e.isErrorDefined=w,e.isErrorEvent=S,e.isEvent=b,e.isEventDefined=v,e.isFunction=h,e.isInstanceOf=l,e.isInt=e=>d(e)&&Number.isInteger(e),e.isInternalFaroOnGlobalObject=ye,e.isMap=e=>I&&l(e,Map),e.isMapDefined=I,e.isNull=u,e.isNumber=d,e.isObject=g,e.isPrimitive=m,e.isRegExp=e=>a(e,"RegExp"),e.isString=c,e.isSymbol=e=>o(e,"symbol"),e.isSyntheticEvent=e=>g(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e,e.isThenable=e=>h(null==e?void 0:e.then),e.isToString=a,e.isTypeof=o,e.isUndefined=e=>o(e,"undefined"),e.makeCoreConfig=Mn,e.noop=P,e.osMeta=qe,e.parseStacktrace=jt,e.sdkMeta=Be,e.setInternalFaroOnGlobalObject=we,e.transportItemTypeToBodyKey=n,e.unknownString=_e,e.userActionDataAttribute=Hi,e}({});
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation, LogLevel } from '@grafana/faro-core';
2
2
  export declare class ConsoleInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-console";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  static defaultDisabledLevels: LogLevel[];
6
6
  static consoleErrorPrefix: string;
7
7
  private errorSerializer;
@@ -2,7 +2,7 @@ import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  import type { Instrumentation } from '@grafana/faro-core';
3
3
  export declare class CSPInstrumentation extends BaseInstrumentation implements Instrumentation {
4
4
  readonly name = "@grafana/faro-web-sdk:instrumentation-csp";
5
- readonly version = "2.8.0";
5
+ readonly version = "2.8.1";
6
6
  constructor();
7
7
  initialize(): void;
8
8
  destroy(): void;
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ErrorsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-errors";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class NavigationInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-navigation";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -3,6 +3,6 @@ import type { ResourceEntryMessage } from './types';
3
3
  export declare const performanceEntriesSubscription: Observable<ResourceEntryMessage>;
4
4
  export declare class PerformanceInstrumentation extends BaseInstrumentation {
5
5
  readonly name = "@grafana/faro-web-sdk:instrumentation-performance";
6
- readonly version = "2.8.0";
6
+ readonly version = "2.8.1";
7
7
  initialize(): void;
8
8
  }
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class SessionInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-session";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  private notifiedSession;
6
6
  private sendSessionStartEvent;
7
7
  private createInitialSession;
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class UserActionInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-user-action";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  private _userActionSub?;
6
6
  initialize(): void;
7
7
  destroy(): void;
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ViewInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-view";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  private notifiedView;
6
6
  private sendViewChangedEvent;
7
7
  initialize(): void;
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class WebVitalsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-web-vitals";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -4,7 +4,7 @@ import type { ConsoleTransportOptions } from './types';
4
4
  export declare class ConsoleTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-console";
7
- readonly version = "2.8.0";
7
+ readonly version = "2.8.1";
8
8
  constructor(options?: ConsoleTransportOptions);
9
9
  send(item: TransportItem): void;
10
10
  }
@@ -4,7 +4,7 @@ import type { FetchTransportOptions } from './types';
4
4
  export declare class FetchTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-fetch";
7
- readonly version = "2.8.0";
7
+ readonly version = "2.8.1";
8
8
  promiseBuffer: PromiseBuffer<Response | void>;
9
9
  private readonly rateLimitBackoffMs;
10
10
  private readonly getNow;
@@ -15,6 +15,10 @@ export declare class FetchTransport extends BaseTransport {
15
15
  getIgnoreUrls(): Patterns;
16
16
  isBatched(): boolean;
17
17
  private getRetryAfterDate;
18
+ private reserveKeepalive;
19
+ private fetchWithKeepaliveRetry;
20
+ private handleResponse;
21
+ private isFetchNetworkError;
18
22
  private compress;
19
23
  private extendFaroSession;
20
24
  }
@@ -28,8 +28,11 @@ const DEFAULT_BUFFER_SIZE = 30;
28
28
  const DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17
29
29
  const DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;
30
30
  const BEACON_BODY_SIZE_LIMIT = 60000;
31
+ const MAX_KEEPALIVE_REQUESTS = 9;
31
32
  const TOO_MANY_REQUESTS = 429;
32
33
  const ACCEPTED = 202;
34
+ let pendingKeepaliveBodySize = 0;
35
+ let pendingKeepaliveRequests = 0;
33
36
  class FetchTransport extends faro_core_1.BaseTransport {
34
37
  constructor(options) {
35
38
  var _a, _b, _c, _d, _e;
@@ -64,6 +67,7 @@ class FetchTransport extends faro_core_1.BaseTransport {
64
67
  const jsonBody = JSON.stringify((0, faro_core_1.getTransportBody)(items));
65
68
  const { url, requestOptions, apiKey } = this.options;
66
69
  const _a = requestOptions !== null && requestOptions !== void 0 ? requestOptions : {}, { headers = {} } = _a, restOfRequestOptions = __rest(_a, ["headers"]);
70
+ const { keepalive: configuredKeepalive } = restOfRequestOptions, requestOptionsWithoutKeepalive = __rest(restOfRequestOptions, ["keepalive"]);
67
71
  let sessionId;
68
72
  const sessionMeta = this.metas.value.session;
69
73
  if (sessionMeta != null) {
@@ -81,23 +85,8 @@ class FetchTransport extends faro_core_1.BaseTransport {
81
85
  bodySize = body.size;
82
86
  compressionHeaders['Content-Encoding'] = 'gzip';
83
87
  }
84
- return fetch(url, Object.assign({ method: 'POST', headers: Object.assign(Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, compressionHeaders), resolvedHeaders), (apiKey ? { 'x-api-key': apiKey } : {})), (sessionId ? { 'x-faro-session-id': sessionId } : {})), body, keepalive: bodySize <= BEACON_BODY_SIZE_LIMIT }, (restOfRequestOptions !== null && restOfRequestOptions !== void 0 ? restOfRequestOptions : {})))
85
- .then((response) => __awaiter(this, void 0, void 0, function* () {
86
- if (response.status === ACCEPTED) {
87
- const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';
88
- if (sessionExpired) {
89
- this.extendFaroSession(this.config, this.logDebug);
90
- }
91
- }
92
- if (response.status === TOO_MANY_REQUESTS) {
93
- this.disabledUntil = this.getRetryAfterDate(response);
94
- this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);
95
- }
96
- // read the body so the connection can be closed
97
- response.text().catch(faro_core_1.noop);
98
- return response;
99
- }))
100
- .catch((err) => {
88
+ const requestInit = Object.assign({ method: 'POST', headers: Object.assign(Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, compressionHeaders), resolvedHeaders), (apiKey ? { 'x-api-key': apiKey } : {})), (sessionId ? { 'x-faro-session-id': sessionId } : {})), body }, (requestOptionsWithoutKeepalive !== null && requestOptionsWithoutKeepalive !== void 0 ? requestOptionsWithoutKeepalive : {}));
89
+ return this.fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive).catch((err) => {
101
90
  this.logError('Failed sending payload to the receiver\n', JSON.parse(jsonBody), err);
102
91
  });
103
92
  }));
@@ -129,6 +118,77 @@ class FetchTransport extends faro_core_1.BaseTransport {
129
118
  }
130
119
  return new Date(now + this.rateLimitBackoffMs);
131
120
  }
121
+ reserveKeepalive(bodySize, configuredKeepalive) {
122
+ if (configuredKeepalive === false) {
123
+ return {
124
+ keepalive: false,
125
+ release: faro_core_1.noop,
126
+ };
127
+ }
128
+ if (bodySize > BEACON_BODY_SIZE_LIMIT ||
129
+ pendingKeepaliveBodySize + bodySize > BEACON_BODY_SIZE_LIMIT ||
130
+ pendingKeepaliveRequests >= MAX_KEEPALIVE_REQUESTS) {
131
+ this.logDebug('Disabling keepalive because the pending keepalive request budget would be exceeded.');
132
+ return {
133
+ keepalive: false,
134
+ release: faro_core_1.noop,
135
+ };
136
+ }
137
+ pendingKeepaliveBodySize += bodySize;
138
+ pendingKeepaliveRequests++;
139
+ let released = false;
140
+ return {
141
+ keepalive: true,
142
+ release: () => {
143
+ if (released) {
144
+ return;
145
+ }
146
+ released = true;
147
+ pendingKeepaliveBodySize = Math.max(0, pendingKeepaliveBodySize - bodySize);
148
+ pendingKeepaliveRequests = Math.max(0, pendingKeepaliveRequests - 1);
149
+ },
150
+ };
151
+ }
152
+ fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive) {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ const keepaliveReservation = this.reserveKeepalive(bodySize, configuredKeepalive);
155
+ try {
156
+ const response = yield fetch(url, Object.assign(Object.assign({}, requestInit), { keepalive: keepaliveReservation.keepalive }));
157
+ return this.handleResponse(response);
158
+ }
159
+ catch (err) {
160
+ if (keepaliveReservation.keepalive && this.isFetchNetworkError(err)) {
161
+ this.logDebug('Retrying failed keepalive request with keepalive disabled.');
162
+ const response = yield fetch(url, Object.assign(Object.assign({}, requestInit), { keepalive: false }));
163
+ return this.handleResponse(response);
164
+ }
165
+ throw err;
166
+ }
167
+ finally {
168
+ keepaliveReservation.release();
169
+ }
170
+ });
171
+ }
172
+ handleResponse(response) {
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ if (response.status === ACCEPTED) {
175
+ const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';
176
+ if (sessionExpired) {
177
+ this.extendFaroSession(this.config, this.logDebug);
178
+ }
179
+ }
180
+ if (response.status === TOO_MANY_REQUESTS) {
181
+ this.disabledUntil = this.getRetryAfterDate(response);
182
+ this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);
183
+ }
184
+ // read the body so the connection can be closed
185
+ response.text().catch(faro_core_1.noop);
186
+ return response;
187
+ });
188
+ }
189
+ isFetchNetworkError(err) {
190
+ return err instanceof TypeError;
191
+ }
132
192
  compress(body) {
133
193
  return __awaiter(this, void 0, void 0, function* () {
134
194
  const stream = new ReadableStream({
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,kDAAwH;AAGxH,kFAA0F;AAC1F,2GAA0G;AAI1G,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,QAAQ,GAAG,GAAG,CAAC;AAErB,MAAa,cAAe,SAAQ,yBAAa;IAW/C,YAAoB,OAA8B;;QAChD,KAAK,EAAE,CAAC;QADU,YAAO,GAAP,OAAO,CAAuB;QAVzC,SAAI,GAAG,uCAAuC,CAAC;QAC/C,YAAO,GAAG,mBAAO,CAAC;QAOnB,kBAAa,GAAS,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;QAKxC,IAAI,CAAC,kBAAkB,GAAG,MAAA,OAAO,CAAC,yBAAyB,mCAAI,6BAA6B,CAAC;QAC7F,IAAI,CAAC,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QAEnD,MAAM,kBAAkB,GAAG,MAAA,OAAO,CAAC,kBAAkB,mCAAI,KAAK,CAAC;QAE/D,IAAI,kBAAkB,IAAI,OAAO,iBAAiB,KAAK,WAAW,E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,MAAM,CAAC,CAAC;QAC1B,CAAC;KAAA;IAEO,iBAAiB,CAAC,MAAc,EAAE,QAAmC;QAC3E,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;QAE/C,MAAM,qBAAqB,GAAG,MAAM,CAAC,eAAe,CAAC;QAErD,IAAI,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,OAAO,EAAE,CAAC;YACnC,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,GAAG,IAAA,0CAAyB,EAAC,qBAAqB,CAAC,CAAC;YAEhG,IAAA,2CAAqB,EAAC,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;YAE5F,QAAQ,CAAC,GAAG,oBAAoB,uBAAuB,CAAC,CAAC;QAC3D,CAAC;aAAM,CAAC;YACN,QAAQ,CAAC,GAAG,oBAAoB,GAAG,CAAC,CAAC;QACvC,CAAC;IACH,CAAC;CACF;AA9KD,wCA8KC","sourcesContent":["import { BaseExtension, BaseTransport, createPromiseBuffer, getTransportBody, noop, VERSION } from '@grafana/faro-core';\nimport type { Config, Patterns, PromiseBuffer, TransportItem } from '@grafana/faro-core';\n\nimport { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager';\nimport { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private readonly compressionEnabled: boolean;\n private disabledUntil: Date = new Date(0);\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n const requestCompression = options.requestCompression ?? false;\n\n if (requestCompression && typeof CompressionStream === 'undefined') {\n this.compressionEnabled = false;\n this.logWarn(\n 'requestCompression is enabled but CompressionStream is not available. Falling back to uncompressed.'\n );\n } else {\n this.compressionEnabled = requestCompression;\n }\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(async () => {\n const jsonBody = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers = {}, ...restOfRequestOptions } = requestOptions ?? {};\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n const resolvedHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n resolvedHeaders[key] = typeof value === 'function' ? await Promise.resolve(value()) : value;\n }\n\n let body: string | Blob = jsonBody;\n let bodySize = jsonBody.length;\n const compressionHeaders: Record<string, string> = {};\n\n if (this.compressionEnabled) {\n body = await this.compress(jsonBody);\n bodySize = body.size;\n compressionHeaders['Content-Encoding'] = 'gzip';\n }\n\n return fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...compressionHeaders,\n ...resolvedHeaders,\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n keepalive: bodySize <= BEACON_BODY_SIZE_LIMIT,\n ...(restOfRequestOptions ?? {}),\n })\n .then(async (response) => {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n })\n .catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(jsonBody), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private async compress(body: string): Promise<Blob> {\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(new TextEncoder().encode(body));\n controller.close();\n },\n }).pipeThrough(new CompressionStream('gzip'));\n\n const reader = stream.getReader();\n const chunks: BlobPart[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n }\n return new Blob(chunks);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,kDAAwH;AAGxH,kFAA0F;AAC1F,2GAA0G;AAI1G,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,QAAQ,GAAG,GAAG,CAAC;AAErB,IAAI,wBAAwB,GAAG,CAAC,CAAC;AACjC,IAAI,wBAAwB,GAAG,CAAC,CAAC;AAOjC,MAAa,cAAe,SAAQ,yBAAa;IAW/C,YAAoB,OAA8B;;QAChD,KAAK,EAAE,CAAC;QADU,YAAO,GAAP,OAAO,CAAuB;QAVzC,SAAI,GAAG,uCAAuC,CAAC;QAC/C,YAAO,GAAG,mBAAO,CAAC;QAOnB,kBAAa,GAAS,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;QAKxC,IAAI,CAAC,kBAAkB,GAAG,MAAA,OAAO,CAAC,yBAAyB,mCAAI,6BAA6B,CAAC;QAC7F,IAAI,CAAC,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QAEnD,MAAM,kBAAkB,GAAG,MAAA,OAAO,CAAC,kBAAkB,mCAAI,KAAK,CAAC;QAE/D,IAAI,kBAAkB,IAAI,OAAO,iBAAiB,KAAK,WAAW,EAAE,CAAC;YACnE,IAAI,CAAC,kBAAkB,GAAG,KAAK,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H,CAAC;CACF;AA7PD,wCA6PC","sourcesContent":["import { BaseExtension, BaseTransport, createPromiseBuffer, getTransportBody, noop, VERSION } from '@grafana/faro-core';\nimport type { Config, Patterns, PromiseBuffer, TransportItem } from '@grafana/faro-core';\n\nimport { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager';\nimport { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst MAX_KEEPALIVE_REQUESTS = 9;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nlet pendingKeepaliveBodySize = 0;\nlet pendingKeepaliveRequests = 0;\n\ninterface KeepaliveReservation {\n keepalive: boolean;\n release: () => void;\n}\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private readonly compressionEnabled: boolean;\n private disabledUntil: Date = new Date(0);\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n const requestCompression = options.requestCompression ?? false;\n\n if (requestCompression && typeof CompressionStream === 'undefined') {\n this.compressionEnabled = false;\n this.logWarn(\n 'requestCompression is enabled but CompressionStream is not available. Falling back to uncompressed.'\n );\n } else {\n this.compressionEnabled = requestCompression;\n }\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(async () => {\n const jsonBody = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers = {}, ...restOfRequestOptions } = requestOptions ?? {};\n const { keepalive: configuredKeepalive, ...requestOptionsWithoutKeepalive } = restOfRequestOptions;\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n const resolvedHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n resolvedHeaders[key] = typeof value === 'function' ? await Promise.resolve(value()) : value;\n }\n\n let body: string | Blob = jsonBody;\n let bodySize = jsonBody.length;\n const compressionHeaders: Record<string, string> = {};\n\n if (this.compressionEnabled) {\n body = await this.compress(jsonBody);\n bodySize = body.size;\n compressionHeaders['Content-Encoding'] = 'gzip';\n }\n\n const requestInit: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...compressionHeaders,\n ...resolvedHeaders,\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n ...(requestOptionsWithoutKeepalive ?? {}),\n };\n\n return this.fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive).catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(jsonBody), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private reserveKeepalive(bodySize: number, configuredKeepalive?: boolean): KeepaliveReservation {\n if (configuredKeepalive === false) {\n return {\n keepalive: false,\n release: noop,\n };\n }\n\n if (\n bodySize > BEACON_BODY_SIZE_LIMIT ||\n pendingKeepaliveBodySize + bodySize > BEACON_BODY_SIZE_LIMIT ||\n pendingKeepaliveRequests >= MAX_KEEPALIVE_REQUESTS\n ) {\n this.logDebug('Disabling keepalive because the pending keepalive request budget would be exceeded.');\n\n return {\n keepalive: false,\n release: noop,\n };\n }\n\n pendingKeepaliveBodySize += bodySize;\n pendingKeepaliveRequests++;\n\n let released = false;\n\n return {\n keepalive: true,\n release: () => {\n if (released) {\n return;\n }\n\n released = true;\n pendingKeepaliveBodySize = Math.max(0, pendingKeepaliveBodySize - bodySize);\n pendingKeepaliveRequests = Math.max(0, pendingKeepaliveRequests - 1);\n },\n };\n }\n\n private async fetchWithKeepaliveRetry(\n url: string,\n requestInit: RequestInit,\n bodySize: number,\n configuredKeepalive?: boolean\n ): Promise<Response> {\n const keepaliveReservation = this.reserveKeepalive(bodySize, configuredKeepalive);\n\n try {\n const response = await fetch(url, {\n ...requestInit,\n keepalive: keepaliveReservation.keepalive,\n });\n\n return this.handleResponse(response);\n } catch (err) {\n if (keepaliveReservation.keepalive && this.isFetchNetworkError(err)) {\n this.logDebug('Retrying failed keepalive request with keepalive disabled.');\n\n const response = await fetch(url, {\n ...requestInit,\n keepalive: false,\n });\n\n return this.handleResponse(response);\n }\n\n throw err;\n } finally {\n keepaliveReservation.release();\n }\n }\n\n private async handleResponse(response: Response): Promise<Response> {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n }\n\n private isFetchNetworkError(err: unknown): boolean {\n return err instanceof TypeError;\n }\n\n private async compress(body: string): Promise<Blob> {\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(new TextEncoder().encode(body));\n controller.close();\n },\n }).pipeThrough(new CompressionStream('gzip'));\n\n const reader = stream.getReader();\n const chunks: BlobPart[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n }\n return new Blob(chunks);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
@@ -25,8 +25,11 @@ const DEFAULT_BUFFER_SIZE = 30;
25
25
  const DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17
26
26
  const DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;
27
27
  const BEACON_BODY_SIZE_LIMIT = 60000;
28
+ const MAX_KEEPALIVE_REQUESTS = 9;
28
29
  const TOO_MANY_REQUESTS = 429;
29
30
  const ACCEPTED = 202;
31
+ let pendingKeepaliveBodySize = 0;
32
+ let pendingKeepaliveRequests = 0;
30
33
  export class FetchTransport extends BaseTransport {
31
34
  constructor(options) {
32
35
  var _a, _b, _c, _d, _e;
@@ -61,6 +64,7 @@ export class FetchTransport extends BaseTransport {
61
64
  const jsonBody = JSON.stringify(getTransportBody(items));
62
65
  const { url, requestOptions, apiKey } = this.options;
63
66
  const _a = requestOptions !== null && requestOptions !== void 0 ? requestOptions : {}, { headers = {} } = _a, restOfRequestOptions = __rest(_a, ["headers"]);
67
+ const { keepalive: configuredKeepalive } = restOfRequestOptions, requestOptionsWithoutKeepalive = __rest(restOfRequestOptions, ["keepalive"]);
64
68
  let sessionId;
65
69
  const sessionMeta = this.metas.value.session;
66
70
  if (sessionMeta != null) {
@@ -78,23 +82,8 @@ export class FetchTransport extends BaseTransport {
78
82
  bodySize = body.size;
79
83
  compressionHeaders['Content-Encoding'] = 'gzip';
80
84
  }
81
- return fetch(url, Object.assign({ method: 'POST', headers: Object.assign(Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, compressionHeaders), resolvedHeaders), (apiKey ? { 'x-api-key': apiKey } : {})), (sessionId ? { 'x-faro-session-id': sessionId } : {})), body, keepalive: bodySize <= BEACON_BODY_SIZE_LIMIT }, (restOfRequestOptions !== null && restOfRequestOptions !== void 0 ? restOfRequestOptions : {})))
82
- .then((response) => __awaiter(this, void 0, void 0, function* () {
83
- if (response.status === ACCEPTED) {
84
- const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';
85
- if (sessionExpired) {
86
- this.extendFaroSession(this.config, this.logDebug);
87
- }
88
- }
89
- if (response.status === TOO_MANY_REQUESTS) {
90
- this.disabledUntil = this.getRetryAfterDate(response);
91
- this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);
92
- }
93
- // read the body so the connection can be closed
94
- response.text().catch(noop);
95
- return response;
96
- }))
97
- .catch((err) => {
85
+ const requestInit = Object.assign({ method: 'POST', headers: Object.assign(Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, compressionHeaders), resolvedHeaders), (apiKey ? { 'x-api-key': apiKey } : {})), (sessionId ? { 'x-faro-session-id': sessionId } : {})), body }, (requestOptionsWithoutKeepalive !== null && requestOptionsWithoutKeepalive !== void 0 ? requestOptionsWithoutKeepalive : {}));
86
+ return this.fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive).catch((err) => {
98
87
  this.logError('Failed sending payload to the receiver\n', JSON.parse(jsonBody), err);
99
88
  });
100
89
  }));
@@ -126,6 +115,77 @@ export class FetchTransport extends BaseTransport {
126
115
  }
127
116
  return new Date(now + this.rateLimitBackoffMs);
128
117
  }
118
+ reserveKeepalive(bodySize, configuredKeepalive) {
119
+ if (configuredKeepalive === false) {
120
+ return {
121
+ keepalive: false,
122
+ release: noop,
123
+ };
124
+ }
125
+ if (bodySize > BEACON_BODY_SIZE_LIMIT ||
126
+ pendingKeepaliveBodySize + bodySize > BEACON_BODY_SIZE_LIMIT ||
127
+ pendingKeepaliveRequests >= MAX_KEEPALIVE_REQUESTS) {
128
+ this.logDebug('Disabling keepalive because the pending keepalive request budget would be exceeded.');
129
+ return {
130
+ keepalive: false,
131
+ release: noop,
132
+ };
133
+ }
134
+ pendingKeepaliveBodySize += bodySize;
135
+ pendingKeepaliveRequests++;
136
+ let released = false;
137
+ return {
138
+ keepalive: true,
139
+ release: () => {
140
+ if (released) {
141
+ return;
142
+ }
143
+ released = true;
144
+ pendingKeepaliveBodySize = Math.max(0, pendingKeepaliveBodySize - bodySize);
145
+ pendingKeepaliveRequests = Math.max(0, pendingKeepaliveRequests - 1);
146
+ },
147
+ };
148
+ }
149
+ fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive) {
150
+ return __awaiter(this, void 0, void 0, function* () {
151
+ const keepaliveReservation = this.reserveKeepalive(bodySize, configuredKeepalive);
152
+ try {
153
+ const response = yield fetch(url, Object.assign(Object.assign({}, requestInit), { keepalive: keepaliveReservation.keepalive }));
154
+ return this.handleResponse(response);
155
+ }
156
+ catch (err) {
157
+ if (keepaliveReservation.keepalive && this.isFetchNetworkError(err)) {
158
+ this.logDebug('Retrying failed keepalive request with keepalive disabled.');
159
+ const response = yield fetch(url, Object.assign(Object.assign({}, requestInit), { keepalive: false }));
160
+ return this.handleResponse(response);
161
+ }
162
+ throw err;
163
+ }
164
+ finally {
165
+ keepaliveReservation.release();
166
+ }
167
+ });
168
+ }
169
+ handleResponse(response) {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ if (response.status === ACCEPTED) {
172
+ const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';
173
+ if (sessionExpired) {
174
+ this.extendFaroSession(this.config, this.logDebug);
175
+ }
176
+ }
177
+ if (response.status === TOO_MANY_REQUESTS) {
178
+ this.disabledUntil = this.getRetryAfterDate(response);
179
+ this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);
180
+ }
181
+ // read the body so the connection can be closed
182
+ response.text().catch(noop);
183
+ return response;
184
+ });
185
+ }
186
+ isFetchNetworkError(err) {
187
+ return err instanceof TypeError;
188
+ }
129
189
  compress(body) {
130
190
  return __awaiter(this, void 0, void 0, function* () {
131
191
  const stream = new ReadableStream({
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAGxH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAC1F,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAI1G,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,QAAQ,GAAG,GAAG,CAAC;AAErB,MAAM,OAAO,cAAe,SAAQ,aAAa;IAW/C,YAAoB,OAA8B;;QAChD,KAAK,EAAE,CAAC;QADU,YAAO,GAAP,OAAO,CAAuB;QAVzC,SAAI,GAAG,uCAAuC,CAAC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,CAAC,CAAC,WAAW,CAAC,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC;YAE9C,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;YAClC,MAAM,MAAM,GAAe,EAAE,CAAC;YAC9B,SAAS,CAAC;gBACR,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;gBAC5C,IAAI,IAAI,EAAE,CAAC;oBACT,MAAM;gBACR,CAAC;gBACD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACrB,CAAC;YACD,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC;QAC1B,CAAC;KAAA;IAEO,iBAAiB,CAAC,MAAc,EAAE,QAAmC;QAC3E,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;QAE/C,MAAM,qBAAqB,GAAG,MAAM,CAAC,eAAe,CAAC;QAErD,IAAI,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,OAAO,EAAE,CAAC;YACnC,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,GAAG,yBAAyB,CAAC,qBAAqB,CAAC,CAAC;YAEhG,qBAAqB,CAAC,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;YAE5F,QAAQ,CAAC,GAAG,oBAAoB,uBAAuB,CAAC,CAAC;QAC3D,CAAC;aAAM,CAAC;YACN,QAAQ,CAAC,GAAG,oBAAoB,GAAG,CAAC,CAAC;QACvC,CAAC;IACH,CAAC;CACF","sourcesContent":["import { BaseExtension, BaseTransport, createPromiseBuffer, getTransportBody, noop, VERSION } from '@grafana/faro-core';\nimport type { Config, Patterns, PromiseBuffer, TransportItem } from '@grafana/faro-core';\n\nimport { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager';\nimport { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private readonly compressionEnabled: boolean;\n private disabledUntil: Date = new Date(0);\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n const requestCompression = options.requestCompression ?? false;\n\n if (requestCompression && typeof CompressionStream === 'undefined') {\n this.compressionEnabled = false;\n this.logWarn(\n 'requestCompression is enabled but CompressionStream is not available. Falling back to uncompressed.'\n );\n } else {\n this.compressionEnabled = requestCompression;\n }\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(async () => {\n const jsonBody = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers = {}, ...restOfRequestOptions } = requestOptions ?? {};\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n const resolvedHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n resolvedHeaders[key] = typeof value === 'function' ? await Promise.resolve(value()) : value;\n }\n\n let body: string | Blob = jsonBody;\n let bodySize = jsonBody.length;\n const compressionHeaders: Record<string, string> = {};\n\n if (this.compressionEnabled) {\n body = await this.compress(jsonBody);\n bodySize = body.size;\n compressionHeaders['Content-Encoding'] = 'gzip';\n }\n\n return fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...compressionHeaders,\n ...resolvedHeaders,\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n keepalive: bodySize <= BEACON_BODY_SIZE_LIMIT,\n ...(restOfRequestOptions ?? {}),\n })\n .then(async (response) => {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n })\n .catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(jsonBody), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private async compress(body: string): Promise<Blob> {\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(new TextEncoder().encode(body));\n controller.close();\n },\n }).pipeThrough(new CompressionStream('gzip'));\n\n const reader = stream.getReader();\n const chunks: BlobPart[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n }\n return new Blob(chunks);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transports/fetch/transport.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAGxH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAC1F,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAI1G,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,mBAAmB,GAAG,CAAC,CAAC,CAAC,uCAAuC;AACtE,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAE3C,MAAM,sBAAsB,GAAG,KAAK,CAAC;AACrC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,QAAQ,GAAG,GAAG,CAAC;AAErB,IAAI,wBAAwB,GAAG,CAAC,CAAC;AACjC,IAAI,wBAAwB,GAAG,CAAC,CAAC;AAOjC,MAAM,OAAO,cAAe,SAAQ,aAAa;IAW/C,YAAoB,OAA8B;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Ac,EAAE,QAAmC;QAC3E,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;QAE/C,MAAM,qBAAqB,GAAG,MAAM,CAAC,eAAe,CAAC;QAErD,IAAI,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAE,OAAO,EAAE,CAAC;YACnC,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,GAAG,yBAAyB,CAAC,qBAAqB,CAAC,CAAC;YAEhG,qBAAqB,CAAC,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;YAE5F,QAAQ,CAAC,GAAG,oBAAoB,uBAAuB,CAAC,CAAC;QAC3D,CAAC;aAAM,CAAC;YACN,QAAQ,CAAC,GAAG,oBAAoB,GAAG,CAAC,CAAC;QACvC,CAAC;IACH,CAAC;CACF","sourcesContent":["import { BaseExtension, BaseTransport, createPromiseBuffer, getTransportBody, noop, VERSION } from '@grafana/faro-core';\nimport type { Config, Patterns, PromiseBuffer, TransportItem } from '@grafana/faro-core';\n\nimport { getSessionManagerByConfig } from '../../instrumentations/session/sessionManager';\nimport { getUserSessionUpdater } from '../../instrumentations/session/sessionManager/sessionManagerUtils';\n\nimport type { FetchTransportOptions } from './types';\n\nconst DEFAULT_BUFFER_SIZE = 30;\nconst DEFAULT_CONCURRENCY = 5; // chrome supports 10 total, firefox 17\nconst DEFAULT_RATE_LIMIT_BACKOFF_MS = 5000;\n\nconst BEACON_BODY_SIZE_LIMIT = 60000;\nconst MAX_KEEPALIVE_REQUESTS = 9;\nconst TOO_MANY_REQUESTS = 429;\nconst ACCEPTED = 202;\n\nlet pendingKeepaliveBodySize = 0;\nlet pendingKeepaliveRequests = 0;\n\ninterface KeepaliveReservation {\n keepalive: boolean;\n release: () => void;\n}\n\nexport class FetchTransport extends BaseTransport {\n readonly name = '@grafana/faro-web-sdk:transport-fetch';\n readonly version = VERSION;\n\n promiseBuffer: PromiseBuffer<Response | void>;\n\n private readonly rateLimitBackoffMs: number;\n private readonly getNow: () => number;\n private readonly compressionEnabled: boolean;\n private disabledUntil: Date = new Date(0);\n\n constructor(private options: FetchTransportOptions) {\n super();\n\n this.rateLimitBackoffMs = options.defaultRateLimitBackoffMs ?? DEFAULT_RATE_LIMIT_BACKOFF_MS;\n this.getNow = options.getNow ?? (() => Date.now());\n\n const requestCompression = options.requestCompression ?? false;\n\n if (requestCompression && typeof CompressionStream === 'undefined') {\n this.compressionEnabled = false;\n this.logWarn(\n 'requestCompression is enabled but CompressionStream is not available. Falling back to uncompressed.'\n );\n } else {\n this.compressionEnabled = requestCompression;\n }\n\n this.promiseBuffer = createPromiseBuffer({\n size: options.bufferSize ?? DEFAULT_BUFFER_SIZE,\n concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,\n });\n }\n\n async send(items: TransportItem[]): Promise<void> {\n try {\n if (this.disabledUntil > new Date(this.getNow())) {\n this.logWarn(`Dropping transport item due to too many requests. Backoff until ${this.disabledUntil}`);\n\n return Promise.resolve();\n }\n\n await this.promiseBuffer.add(async () => {\n const jsonBody = JSON.stringify(getTransportBody(items));\n\n const { url, requestOptions, apiKey } = this.options;\n\n const { headers = {}, ...restOfRequestOptions } = requestOptions ?? {};\n const { keepalive: configuredKeepalive, ...requestOptionsWithoutKeepalive } = restOfRequestOptions;\n\n let sessionId;\n const sessionMeta = this.metas.value.session;\n if (sessionMeta != null) {\n sessionId = sessionMeta.id;\n }\n\n const resolvedHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n resolvedHeaders[key] = typeof value === 'function' ? await Promise.resolve(value()) : value;\n }\n\n let body: string | Blob = jsonBody;\n let bodySize = jsonBody.length;\n const compressionHeaders: Record<string, string> = {};\n\n if (this.compressionEnabled) {\n body = await this.compress(jsonBody);\n bodySize = body.size;\n compressionHeaders['Content-Encoding'] = 'gzip';\n }\n\n const requestInit: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...compressionHeaders,\n ...resolvedHeaders,\n ...(apiKey ? { 'x-api-key': apiKey } : {}),\n ...(sessionId ? { 'x-faro-session-id': sessionId } : {}),\n },\n body,\n ...(requestOptionsWithoutKeepalive ?? {}),\n };\n\n return this.fetchWithKeepaliveRetry(url, requestInit, bodySize, configuredKeepalive).catch((err) => {\n this.logError('Failed sending payload to the receiver\\n', JSON.parse(jsonBody), err);\n });\n });\n } catch (err) {\n this.logError(err);\n }\n }\n\n override getIgnoreUrls(): Patterns {\n return ([this.options.url] as Patterns).concat(this.config.ignoreUrls ?? []);\n }\n\n override isBatched(): boolean {\n return true;\n }\n\n private getRetryAfterDate(response: Response): Date {\n const now = this.getNow();\n const retryAfterHeader = response.headers.get('Retry-After');\n\n if (retryAfterHeader) {\n const delay = Number(retryAfterHeader);\n\n if (!isNaN(delay)) {\n return new Date(delay * 1000 + now);\n }\n\n const date = Date.parse(retryAfterHeader);\n\n if (!isNaN(date)) {\n return new Date(date);\n }\n }\n\n return new Date(now + this.rateLimitBackoffMs);\n }\n\n private reserveKeepalive(bodySize: number, configuredKeepalive?: boolean): KeepaliveReservation {\n if (configuredKeepalive === false) {\n return {\n keepalive: false,\n release: noop,\n };\n }\n\n if (\n bodySize > BEACON_BODY_SIZE_LIMIT ||\n pendingKeepaliveBodySize + bodySize > BEACON_BODY_SIZE_LIMIT ||\n pendingKeepaliveRequests >= MAX_KEEPALIVE_REQUESTS\n ) {\n this.logDebug('Disabling keepalive because the pending keepalive request budget would be exceeded.');\n\n return {\n keepalive: false,\n release: noop,\n };\n }\n\n pendingKeepaliveBodySize += bodySize;\n pendingKeepaliveRequests++;\n\n let released = false;\n\n return {\n keepalive: true,\n release: () => {\n if (released) {\n return;\n }\n\n released = true;\n pendingKeepaliveBodySize = Math.max(0, pendingKeepaliveBodySize - bodySize);\n pendingKeepaliveRequests = Math.max(0, pendingKeepaliveRequests - 1);\n },\n };\n }\n\n private async fetchWithKeepaliveRetry(\n url: string,\n requestInit: RequestInit,\n bodySize: number,\n configuredKeepalive?: boolean\n ): Promise<Response> {\n const keepaliveReservation = this.reserveKeepalive(bodySize, configuredKeepalive);\n\n try {\n const response = await fetch(url, {\n ...requestInit,\n keepalive: keepaliveReservation.keepalive,\n });\n\n return this.handleResponse(response);\n } catch (err) {\n if (keepaliveReservation.keepalive && this.isFetchNetworkError(err)) {\n this.logDebug('Retrying failed keepalive request with keepalive disabled.');\n\n const response = await fetch(url, {\n ...requestInit,\n keepalive: false,\n });\n\n return this.handleResponse(response);\n }\n\n throw err;\n } finally {\n keepaliveReservation.release();\n }\n }\n\n private async handleResponse(response: Response): Promise<Response> {\n if (response.status === ACCEPTED) {\n const sessionExpired = response.headers.get('X-Faro-Session-Status') === 'invalid';\n\n if (sessionExpired) {\n this.extendFaroSession(this.config, this.logDebug);\n }\n }\n\n if (response.status === TOO_MANY_REQUESTS) {\n this.disabledUntil = this.getRetryAfterDate(response);\n this.logWarn(`Too many requests, backing off until ${this.disabledUntil}`);\n }\n\n // read the body so the connection can be closed\n response.text().catch(noop);\n return response;\n }\n\n private isFetchNetworkError(err: unknown): boolean {\n return err instanceof TypeError;\n }\n\n private async compress(body: string): Promise<Blob> {\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(new TextEncoder().encode(body));\n controller.close();\n },\n }).pipeThrough(new CompressionStream('gzip'));\n\n const reader = stream.getReader();\n const chunks: BlobPart[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n }\n return new Blob(chunks);\n }\n\n private extendFaroSession(config: Config, logDebug: BaseExtension['logDebug']) {\n const SessionExpiredString = `Session expired`;\n\n const sessionTrackingConfig = config.sessionTracking;\n\n if (sessionTrackingConfig?.enabled) {\n const { fetchUserSession, storeUserSession } = getSessionManagerByConfig(sessionTrackingConfig);\n\n getUserSessionUpdater({ fetchUserSession, storeUserSession })({ forceSessionExtend: true });\n\n logDebug(`${SessionExpiredString} created new session.`);\n } else {\n logDebug(`${SessionExpiredString}.`);\n }\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation, LogLevel } from '@grafana/faro-core';
2
2
  export declare class ConsoleInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-console";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  static defaultDisabledLevels: LogLevel[];
6
6
  static consoleErrorPrefix: string;
7
7
  private errorSerializer;
@@ -2,7 +2,7 @@ import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  import type { Instrumentation } from '@grafana/faro-core';
3
3
  export declare class CSPInstrumentation extends BaseInstrumentation implements Instrumentation {
4
4
  readonly name = "@grafana/faro-web-sdk:instrumentation-csp";
5
- readonly version = "2.8.0";
5
+ readonly version = "2.8.1";
6
6
  constructor();
7
7
  initialize(): void;
8
8
  destroy(): void;
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ErrorsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-errors";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class NavigationInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-navigation";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -3,6 +3,6 @@ import type { ResourceEntryMessage } from './types';
3
3
  export declare const performanceEntriesSubscription: Observable<ResourceEntryMessage>;
4
4
  export declare class PerformanceInstrumentation extends BaseInstrumentation {
5
5
  readonly name = "@grafana/faro-web-sdk:instrumentation-performance";
6
- readonly version = "2.8.0";
6
+ readonly version = "2.8.1";
7
7
  initialize(): void;
8
8
  }
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class SessionInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-session";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  private notifiedSession;
6
6
  private sendSessionStartEvent;
7
7
  private createInitialSession;
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class UserActionInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-user-action";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  private _userActionSub?;
6
6
  initialize(): void;
7
7
  destroy(): void;
@@ -1,7 +1,7 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class ViewInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-view";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  private notifiedView;
6
6
  private sendViewChangedEvent;
7
7
  initialize(): void;
@@ -1,6 +1,6 @@
1
1
  import { BaseInstrumentation } from '@grafana/faro-core';
2
2
  export declare class WebVitalsInstrumentation extends BaseInstrumentation {
3
3
  readonly name = "@grafana/faro-web-sdk:instrumentation-web-vitals";
4
- readonly version = "2.8.0";
4
+ readonly version = "2.8.1";
5
5
  initialize(): void;
6
6
  }
@@ -4,7 +4,7 @@ import type { ConsoleTransportOptions } from './types';
4
4
  export declare class ConsoleTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-console";
7
- readonly version = "2.8.0";
7
+ readonly version = "2.8.1";
8
8
  constructor(options?: ConsoleTransportOptions);
9
9
  send(item: TransportItem): void;
10
10
  }
@@ -4,7 +4,7 @@ import type { FetchTransportOptions } from './types';
4
4
  export declare class FetchTransport extends BaseTransport {
5
5
  private options;
6
6
  readonly name = "@grafana/faro-web-sdk:transport-fetch";
7
- readonly version = "2.8.0";
7
+ readonly version = "2.8.1";
8
8
  promiseBuffer: PromiseBuffer<Response | void>;
9
9
  private readonly rateLimitBackoffMs;
10
10
  private readonly getNow;
@@ -15,6 +15,10 @@ export declare class FetchTransport extends BaseTransport {
15
15
  getIgnoreUrls(): Patterns;
16
16
  isBatched(): boolean;
17
17
  private getRetryAfterDate;
18
+ private reserveKeepalive;
19
+ private fetchWithKeepaliveRetry;
20
+ private handleResponse;
21
+ private isFetchNetworkError;
18
22
  private compress;
19
23
  private extendFaroSession;
20
24
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@grafana/faro-web-sdk",
3
3
  "packageManager": "yarn@4.17.0",
4
- "version": "2.8.0",
4
+ "version": "2.8.1",
5
5
  "description": "Faro instrumentations, metas, transports for web.",
6
6
  "keywords": [
7
7
  "observability",
@@ -57,7 +57,7 @@
57
57
  "quality:circular-deps": "madge --circular ."
58
58
  },
59
59
  "dependencies": {
60
- "@grafana/faro-core": "^2.8.0",
60
+ "@grafana/faro-core": "^2.8.1",
61
61
  "ua-parser-js": "1.0.41",
62
62
  "web-vitals": "^5.1.0"
63
63
  },
@@ -69,5 +69,5 @@
69
69
  "publishConfig": {
70
70
  "access": "public"
71
71
  },
72
- "gitHead": "1da0e9c69eaafcf7a64f2f857fb44fa7b799cf9a"
72
+ "gitHead": "8efae53b855f9924cc730a7e198796f886875ca0"
73
73
  }